db63d3f44b
2. Support both HTTP and HTTPS connections based on URL 3. Merged add and update options 4. Print exception info Signed-off-by: Arun Prakash Jana <engineerarun@gmail.com>
320 lines
9.5 KiB
Python
Executable File
320 lines
9.5 KiB
Python
Executable File
#!/usr/bin/python3
|
|
#
|
|
# Bookmark management utility
|
|
#
|
|
# Copyright (C) 2015 Arun Prakash Jana <engineerarun@gmail.com>
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU General Public License
|
|
# along with markit. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
import sys
|
|
import os
|
|
import sqlite3
|
|
from getopt import getopt, GetoptError
|
|
import readline
|
|
import webbrowser
|
|
import html.parser as HTMLParser
|
|
from http.client import HTTPConnection
|
|
from http.client import HTTPSConnection
|
|
|
|
# Globals
|
|
addurl = False
|
|
online = False
|
|
deletedb = False
|
|
showdb = False
|
|
search = False
|
|
entry = None
|
|
updatedb = False
|
|
|
|
def usage():
|
|
print("Usage: markit [OPTIONS] KEYWORDS...")
|
|
print("Bookmark manager. Your private Google.\n")
|
|
print("Options")
|
|
print(" -a URL tag entry1, tag entry2, ... add a bookmark")
|
|
print(" -d N delete entry at index N")
|
|
print(" -D delete ALL bookmarks")
|
|
print(" -o fetch title info from web")
|
|
print(" -p print all bookmarks")
|
|
print(" -s string(s) search all bookmarks for a (partial) tag or keyword")
|
|
print(" -u N update entry at index N (from output of -p)")
|
|
print(" you can either add or update or delete in one instance")
|
|
print(" any other input shows help and exits markit\n")
|
|
print("Version 0.1")
|
|
print("Copyright (C) 2015 Arun Prakash Jana <engineerarun@gmail.com>")
|
|
print("Webpage: https://github.com/jarun/markit")
|
|
sys.exit(1)
|
|
|
|
def initdb():
|
|
# Create a connection
|
|
conn = sqlite3.connect('bookmarks.db')
|
|
cur = conn.cursor()
|
|
|
|
# Create table if it doesn't exist
|
|
cur.execute('''CREATE TABLE if not exists bookmarks
|
|
(id integer PRIMARY KEY AUTOINCREMENT, URL text NOT NULL UNIQUE, tags text, metadata text)''')
|
|
conn.commit()
|
|
return (conn, cur)
|
|
|
|
def AddUpdateEntry(conn, cur, keywords, entry):
|
|
global online
|
|
|
|
tags = ','
|
|
url = keywords[0]
|
|
for tag in keywords[1:]:
|
|
if tags[-1] == ",":
|
|
tags += tag
|
|
else:
|
|
tags += " " + tag
|
|
|
|
if tags[-1] != ",":
|
|
tags += ","
|
|
|
|
meta = ''
|
|
|
|
if online == True:
|
|
secure = True
|
|
if url.find("https://") >= 0:
|
|
server = url[8:]
|
|
elif url.find("http://") >= 0:
|
|
secure = False
|
|
server = url[7:]
|
|
else:
|
|
online = False
|
|
|
|
if online == True:
|
|
marker = server.find("/")
|
|
if marker > 0:
|
|
server = server[:marker]
|
|
|
|
try:
|
|
print("server: [%s]" % server)
|
|
if secure == True:
|
|
urlconn = HTTPSConnection(server, timeout=30)
|
|
else:
|
|
urlconn = HTTPConnection(server, timeout=30)
|
|
print("URL: [%s]" % url)
|
|
urlconn.request("GET", url)
|
|
resp = urlconn.getresponse()
|
|
if resp.status != 200:
|
|
print("ERROR:", str(resp.status), ": ", resp.reason)
|
|
meta = ''
|
|
else:
|
|
parser = BMHTMLParser()
|
|
parser.feed(resp.read().decode('utf-8'))
|
|
if parser.data != None and parser.data.find("Error") < 0:
|
|
meta = parser.data
|
|
except Exception as e:
|
|
print("Exception: %s" % e)
|
|
meta = ''
|
|
finally:
|
|
urlconn.close()
|
|
|
|
print("meta: [%s]" % meta)
|
|
|
|
if entry == None: # Add a new entry
|
|
try:
|
|
cur.execute('INSERT INTO bookmarks(URL, tags, metadata) VALUES (?, ?, ?)', (url, tags, meta,))
|
|
conn.commit()
|
|
except sqlite3.IntegrityError:
|
|
print("URL already exists")
|
|
else: # Update an existing entry
|
|
try:
|
|
cur.execute("UPDATE bookmarks SET URL = ?, tags = ?, metadata = ? WHERE id = ?", (url, tags, meta, int(entry),))
|
|
conn.commit()
|
|
if cur.rowcount == 1:
|
|
print("Updated")
|
|
else:
|
|
print("No matching index")
|
|
except sqlite3.IntegrityError:
|
|
print("URL already exists")
|
|
|
|
def searchdb(cur, keywords):
|
|
searchtag = ''
|
|
searchkey = keywords[0]
|
|
for token in keywords:
|
|
searchtag += token + " "
|
|
|
|
searchtag = ',' + searchtag[0:-1] + ','
|
|
|
|
count = 0
|
|
results = []
|
|
for row in cur.execute("SELECT url, metadata FROM bookmarks WHERE tags LIKE ('%' || ? || '%') \
|
|
OR tags LIKE ('%' || ? || '%') \
|
|
OR URL LIKE ('%' || ? || '%') \
|
|
OR metadata LIKE ('%' || ? || '%')", (searchtag, searchkey, searchkey, searchkey,)):
|
|
results.append(row[0])
|
|
count += 1
|
|
print("\x1B[1m\x1B[93m%d. \x1B[0m\x1B[92m%s\x1B[0m\n\t%s" % (count, row[0], row[1]))
|
|
|
|
if count == 0:
|
|
return
|
|
|
|
while True:
|
|
nav = input("Index number to open: ")
|
|
if is_int(nav):
|
|
index = int(nav) - 1
|
|
if index < 0:
|
|
print("Index out of bound.")
|
|
continue
|
|
|
|
try:
|
|
_stderr = os.dup(2)
|
|
os.close(2)
|
|
_stdout = os.dup(1)
|
|
os.close(1)
|
|
fd = os.open(os.devnull, os.O_RDWR)
|
|
os.dup2(fd, 2)
|
|
os.dup2(fd, 1)
|
|
try:
|
|
webbrowser.open(results[int(nav) - 1])
|
|
finally:
|
|
os.close(fd)
|
|
os.dup2(_stderr, 2)
|
|
os.dup2(_stdout, 1)
|
|
except IndexError:
|
|
print("Index out of bound.")
|
|
else:
|
|
break
|
|
|
|
def cleardb(conn, cur, entry):
|
|
if entry == None: # Remove the table
|
|
cur.execute('DROP TABLE if exists bookmarks')
|
|
conn.commit()
|
|
else: # Remove a single entry
|
|
try:
|
|
cur.execute("DELETE FROM bookmarks WHERE id = ?", (int(entry),))
|
|
conn.commit()
|
|
if cur.rowcount == 1:
|
|
print("Removed")
|
|
else:
|
|
print("No matching index")
|
|
except IndexError:
|
|
print("Index out of bound.")
|
|
|
|
def printtable(cur):
|
|
for row in cur.execute('SELECT * FROM bookmarks'):
|
|
print("\x1B[1m\x1B[93m%s. \x1B[0m\x1B[92m%s\x1B[0m\n\t[TAGS] %s\n\t[META] %s" % (row[0], row[1], row[2][1:-1], row[3]))
|
|
|
|
def is_int(string):
|
|
try:
|
|
int(string)
|
|
return True
|
|
except:
|
|
return False
|
|
|
|
class BMHTMLParser(HTMLParser.HTMLParser):
|
|
def __init__(self):
|
|
HTMLParser.HTMLParser.__init__(self)
|
|
self.inTitle = False
|
|
self.data = ""
|
|
self.lasttag = None
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
self.inTitle = False
|
|
if tag == "title":
|
|
self.inTitle = True
|
|
self.lasttag = tag
|
|
|
|
def handle_endtag(self, tag):
|
|
if tag == "title":
|
|
self.inTitle = False
|
|
|
|
def handle_data(self, data):
|
|
if self.lasttag == "title" and self.inTitle == True:
|
|
self.data += data
|
|
|
|
|
|
# Main starts here
|
|
# ----------------
|
|
optlist = None
|
|
keywords = None
|
|
|
|
if len(sys.argv) < 2:
|
|
usage()
|
|
|
|
try:
|
|
optlist, keywords = getopt(sys.argv[1:], "d:u:aDops")
|
|
if len(optlist) < 1:
|
|
usage()
|
|
|
|
for opt in optlist:
|
|
if opt[0] == "-a":
|
|
if updatedb == True or deletedb == True:
|
|
print("You can either add or update or delete in one instance\n")
|
|
usage()
|
|
|
|
addurl = True
|
|
elif opt[0] == "-d":
|
|
if addurl == True or updatedb == True:
|
|
print("You can either add or update or delete in one instance\n")
|
|
usage()
|
|
|
|
if not opt[1].isdigit():
|
|
usage()
|
|
|
|
entry = opt[1]
|
|
if int(entry) <= 0:
|
|
usage()
|
|
|
|
deletedb = True
|
|
elif opt[0] == "-D":
|
|
if addurl == True or updatedb == True:
|
|
print("You can either add or update or delete in one instance\n")
|
|
usage()
|
|
|
|
deletedb = True
|
|
elif opt[0] == "-o":
|
|
online = True
|
|
elif opt[0] == "-p":
|
|
showdb = True
|
|
elif opt[0] == "-s":
|
|
search = True
|
|
elif opt[0] == "-u":
|
|
if addurl == True or deletedb == True:
|
|
print("You can either add or update or delete in one instance\n")
|
|
usage()
|
|
|
|
if not opt[1].isdigit():
|
|
usage()
|
|
|
|
entry = opt[1]
|
|
if int(entry) <= 0:
|
|
usage()
|
|
|
|
updatedb = True
|
|
except GetoptError as e:
|
|
print("markit:", e)
|
|
sys.exit(1)
|
|
|
|
conn, cur = initdb()
|
|
|
|
if addurl == True or updatedb == True:
|
|
if len(keywords) < 1:
|
|
usage()
|
|
|
|
AddUpdateEntry(conn, cur, keywords, entry)
|
|
|
|
if search == True:
|
|
if len(keywords) < 1:
|
|
usage()
|
|
|
|
searchdb(cur, keywords)
|
|
|
|
if showdb == True:
|
|
printtable(cur)
|
|
|
|
if deletedb == True:
|
|
cleardb(conn, cur, entry)
|
|
|
|
conn.close()
|