aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndy Carlson <thecarlsondaddy@gmail.com>2016-10-04 15:25:54 -0400
committerAndy Carlson <thecarlsondaddy@gmail.com>2016-10-04 15:25:54 -0400
commitac89fa01b56be2bf51ab1007659aaedd595f58de (patch)
tree296d86e8e96b5cd4d6915497801fd67cf54d6085
parent14a5587613a72efc1d5ad9e56cf2d66210370019 (diff)
Added URLs and templates
-rw-r--r--README.md13
-rw-r--r--ezdb.py229
-rw-r--r--junos-quicklinks.py95
-rw-r--r--templates/fqdn.html11
-rw-r--r--templates/root.html18
5 files changed, 365 insertions, 1 deletions
diff --git a/README.md b/README.md
index d836d51..001fb56 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,12 @@
-# junos-quicklink \ No newline at end of file
+# gist-client-android
+Requires [QPython](http://qpython.com/)
+###Installation
+1. Clone Repository
+2. Using the FTP server built into QPython, upload the repo folder to the "projects" folder on your Android device
+
+###Create Shortcut
+1. Open QPython
+2. Navigate to Programs->Projects
+3. Long-press on the project
+4. Click "OK" to confirm
+5. There will be a shortcut on your home screen
diff --git a/ezdb.py b/ezdb.py
new file mode 100644
index 0000000..985b5e1
--- /dev/null
+++ b/ezdb.py
@@ -0,0 +1,229 @@
+##########################################################
+#
+# ezdb.py - SQLite database functions
+#
+# NOTE: This only works with data of type text and varchar
+#
+# Import libraries
+# from ezdb import TableDef, DatabaseDef
+#
+# Create a table object with fields:
+# newtable = TableDef("people")
+# newtable.AddFields("name","text")
+# newtable.AddFields("age","text")
+#
+# Create database object
+# newdb = DatabaseDef("db/test.db")
+#
+# Add table to database
+# newdb.AddTable(newtable)
+#
+# Initialize database schema (write table schema to database)
+# newdb.Initialize()
+#
+# Alter Table (Add column only):
+# SQL: ALTER TABLE people ADD COLUMN address text;
+# EZBD: newdb.Alter("address","text")
+#
+# Insert into table
+# SQL: INSERT INTO people(name, age) VALUES("Bob","24");
+# EZDB: newdb.Insert("people",["Bob","24"])
+#
+# Return True on success, False on failure
+#
+# Update table entry
+# SQL: UPDATE people SET name='Robert', age='26' WHERE name='Bob' AND age='24';
+# EZDB: newdb.Update("people",["name","age"],["Robert","26"],["name","age"],["Bob","24"])
+#
+# returns True on success, False on failure
+#
+# Select Row(s) from table
+# SQL: SELECT * FROM people WHERE name='Robert';
+# EZDB: newdb.Select("people",["name"],["Robert"])
+#
+# SQL: SELECT * FROM people WHERE name='Robert' AND age='26';
+# EZDB: newdb.Select("people",["name","age"],["Robert","26"])
+#
+# returns [{"name": "Robert", "age":"26"}]
+# (additional rows will be pushed onto the array as additional dictonaries)
+#
+# Select all items from table
+# SQL: SELECT * FROM people;
+# EZDB: newdb.Select("people")
+#
+# returns [{"name": "Robert", "age":"26"}]
+# (additional rows will be pushed onto the array as additional dictonaries)
+#
+# Delete specific item from table
+# SQL: DELETE FROM people WHERE name='Robert';
+# EZDB: newdb.Delete("people",["name"],["Robert"])
+#
+# Delete all items from table:
+# SQL: DELETE FROM people WHERE 1
+# EZDB: newdb.Delete("people")
+#
+##########################################################
+
+import sqlite3
+import os
+import re
+
+class TableDef:
+ def __init__(self,name):
+ self.NAME = name
+ self.FIELDS = []
+
+ def AddField(self, name, fieldtype):
+ self.FIELDS.append({ "name" : name, "type" : fieldtype })
+
+ def Create(self):
+ createlist = [a["name"] + " " + a["type"] for a in self.FIELDS]
+ if len(createlist) >= 1:
+ return str("CREATE TABLE " + self.NAME + "(" + ",".join(createlist) + ");")
+ else:
+ return False
+
+ def Alter(self, columnname, columntype):
+ if columnname and columntype:
+ return str("ALTER TABLE " + self.NAME + " ADD COLUMN " + columnname + " " + columntype + ";")
+ else:
+ return False
+
+ def Insert(self, valuelist):
+ if len(valuelist) == len([a["name"] for a in self.FIELDS]):
+ return str("INSERT INTO " + self.NAME + "(" + ",".join([a["name"] for a in self.FIELDS]) + ") VALUES('" + "','".join(valuelist) + "');")
+ else:
+ return False
+
+ def Update(self, valuefieldlist, valuevaluelist, wherefieldlist, wherevaluelist):
+ if len(valuefieldlist) == len(valuevaluelist) and len(wherefieldlist) == len(wherevaluelist):
+ return str("UPDATE " + self.NAME + " SET " + ", ".join([valuefieldlist[idx] + "='" + valuevaluelist[idx] + "'" for idx in range(len(valuefieldlist))]) + " WHERE " + " AND ".join([wherefieldlist[idx] + "='" + wherevaluelist[idx] + "'" for idx in range(len(wherevaluelist))]) + ";")
+ else:
+ return False
+
+ def Select(self, fieldlist, valuelist):
+ if len([f for f in fieldlist if f in [a["name"] for a in self.FIELDS]]) > 0 and len(fieldlist) == len(valuelist):
+ return str("SELECT * FROM " + self.NAME + " WHERE " + " AND ".join([fieldlist[idx] + "='" + valuelist[idx] + "'" for idx in range(len(fieldlist))]) + ";")
+ else:
+ return False
+
+ def SelectAll(self):
+ return str("SELECT * FROM " + self.NAME + ";")
+
+ def Delete(self, fieldlist, valuelist):
+ if len([f for f in fieldlist if f in [a["name"] for a in self.FIELDS]]) > 0 and len(fieldlist) == len(valuelist):
+ return str("DELETE FROM " + self.NAME + " WHERE " + " AND ".join([fieldlist[idx] + "='" + valuelist[idx] + "'" for idx in range(len(fieldlist))]) + ";")
+ else:
+ return False
+
+ def DeleteAll(self):
+ return str("DELETE FROM " + self.NAME + " WHERE 1;")
+
+class DatabaseDef:
+ def __init__(self, filename):
+ self.DATABASE = filename
+ self.TABLES = []
+
+ def AddTable(self, tabledef):
+ self.TABLES.append({"name" : tabledef.NAME, "obj" : tabledef })
+
+ def ExistDB(self):
+ return os.path.exists(self.DATABASE)
+
+ def GetDB(self):
+ return sqlite3.connect(self.DATABASE)
+
+ def Initialize(self):
+ try:
+ if not self.ExistDB():
+ db = self.GetDB()
+ for table in self.TABLES:
+ result = db.cursor().execute(table["obj"].Create())
+ db.commit()
+ db.close()
+ else:
+ for table in self.TABLES:
+ db = self.GetDB()
+ result = db.cursor().execute("SELECT name, sql FROM sqlite_master WHERE type='table' AND name='" + table["name"] + "';")
+ tableinfo = [a for a in result if a[0] == table["name"]]
+ if len(tableinfo) == 0:
+ db.cursor().execute(table["obj"].Create())
+ else:
+ if not tableinfo[0][1] + ";" == table["obj"].Create():
+ oldcolumns = re.sub("^.*\(","", re.sub("\)$","",tableinfo[0][1])).split(",")
+ newcolumns = re.sub("^.*\(","", re.sub("\);$","",table["obj"].Create())).split(",")
+ if len(newcolumns) > len(oldcolumns):
+ newcolumns = [a for a in newcolumns if a not in set(oldcolumns)]
+ for thiscolumn in newcolumns:
+ self.Alter(table["name"], thiscolumn.split(" ")[0], thiscolumn.split(" ")[1])
+ else:
+ raise NameError("Cannot remove columns or change column type")
+ return True
+ except:
+ return False
+
+ def Alter(self, tablename, columnname, columntype):
+ try:
+ db = self.GetDB()
+ db.cursor().execute([a for a in self.TABLES if a["name"] == tablename][0]["obj"].Alter(columnname, columntype))
+ db.commit()
+ db.close()
+ except:
+ return False
+
+ def Insert(self, tablename, valuelist):
+ try:
+ db = self.GetDB()
+ db.cursor().execute([a for a in self.TABLES if a["name"] == tablename][0]["obj"].Insert(valuelist))
+ db.commit()
+ db.close()
+ return True
+ except:
+ return False
+
+ def Update(self, tablename, valuefieldlist, valuevaluelist, wherefieldlist, wherevaluelist):
+ try:
+ db = self.GetDB()
+ db.cursor().execute([a for a in self.TABLES if a["name"] == tablename][0]["obj"].Update(valuefieldlist,valuevaluelist,wherefieldlist,wherevaluelist))
+ db.commit()
+ db.close()
+ return True
+ except:
+ return False
+
+ def Delete(self, tablename, fieldlist = None, valuelist = None):
+ try:
+ db = self.GetDB()
+ returnval = None
+ if fieldlist and valuelist:
+ db.cursor.execute([a for a in self.TABLES if a["name"] == tablename][0]["obj"].Delete(fieldlist,valuelist))
+ else:
+ db.cursor.execute([a for a in self.TABLES if a["name"] == tablename][0]["obj"].DeleteAll())
+ except:
+ return False
+
+ def Select(self, tablename, fieldlist= None, valuelist = None):
+ try:
+ db = self.GetDB()
+ returnval = None
+ if fieldlist and valuelist:
+ returnval = []
+ result = db.cursor().execute([a for a in self.TABLES if a["name"] == tablename][0]["obj"].Select(fieldlist,valuelist)).fetchall()
+ for thisresult in result:
+ returnval.append(None)
+ returnval[len(returnval)-1] = {}
+ for i in range(0,len([a for a in self.TABLES if a["name"] == tablename][0]["obj"].FIELDS)):
+ returnval[len(returnval)-1][[a for a in self.TABLES if a["name"] == tablename][0]["obj"].FIELDS[i]["name"]] = str(thisresult[i])
+ else:
+ returnval = []
+ result = db.cursor().execute([a for a in self.TABLES if a["name"] == tablename][0]["obj"].SelectAll()).fetchall()
+ for thisresult in result:
+ returnval.append(None)
+ returnval[len(returnval)-1] = {}
+ for i in range(0,len([a for a in self.TABLES if a["name"] == tablename][0]["obj"].FIELDS)):
+ returnval[len(returnval)-1][[a for a in self.TABLES if a["name"] == tablename][0]["obj"].FIELDS[i]["name"]] = str(thisresult[i])
+
+ db.close()
+ return returnval
+ except:
+ return False
diff --git a/junos-quicklinks.py b/junos-quicklinks.py
new file mode 100644
index 0000000..a7d3c66
--- /dev/null
+++ b/junos-quicklinks.py
@@ -0,0 +1,95 @@
+#qpy:webapp:GistClientAndroid
+#qpy://127.0.0.1:8080/
+
+from flask import Flask, render_template, redirect, url_for, request
+import sqlite3
+from ezdb import DatabaseDef, TableDef
+import os
+import sys
+
+def GetQuickLinks(db):
+ return [a for a in db.Select("quicklinks")]
+
+def GetJunosFQDN(db):
+ return [a for a in db.Select("settings",["propname"],["fqdn"])][0]['propval']
+
+def ExistsJunosFQDN(db):
+ return [a["propval"] for a in db.Select("settings") if a["propname"] == "fqdn"]
+
+def ExistQuickLink(db,linkurl):
+ return [a["url"] for a in db.Select("quicklinks") if a["url"] == linkurl]
+
+# Database Def
+linktab = TableDef("quicklinks")
+linktab.AddField("url","text")
+settab = TableDef("settings")
+settab.AddField("propname","text")
+settab.AddField("propval","text")
+linkdb = DatabaseDef("./quicklinks.db")
+linkdb.AddTable(linktab)
+linkdb.AddTable(settab)
+
+if not linkdb.Initialize():
+ print "Error Initializing Database"
+ sys.exit()
+
+app = Flask(__name__)
+
+@app.route("/")
+def GetRoot():
+ response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
+ response.headers['Pragma'] = 'no-cache'
+
+ if not ExistJunosFQDN(linkdb):
+ return render_template("fqdn.html")
+ else:
+ linklist = GetQuickLinks(linkdb)
+ domainname = GetJunosFQDN(linkdb)
+
+ return render_template("root.html", domainname = domainname, linklist = linklist)
+
+@app.route("/moddomain/", methods = ["POST"])
+def ModFqdn():
+ domainname = str(request.form["fqdn"])
+
+ if len(domainname) < 1:
+ return redirect("/?error=invalid-fqdn")
+ else:
+ linkdb.Update("settings",["propval"],[domainname],["propname"],["fqdn"])
+ return redirect("/")
+@app.route("/resetdomain/", methods = ["POST"])
+def ResetDomain():
+ fqdn = str(request.form["domainname"])
+ if len(fqdn) > 0:
+ linkdb.Delete("settings",["propname"],["fqdn"])
+ return redirect("/")
+ else:
+ return redirect("/?error=reset-fqdn-fail")
+
+@app.route("/addlink/", methods = ["POST"])
+def AddLink():
+ linkurl = str(request.form["linkurl"])
+
+ if len(linkurl) < 1:
+ return redirect("/?error=invalid-url")
+ else:
+ if not ExistQuickLink(linkdb,linkurl):
+ linkdb.Insert("quicklinks",[linkurl])
+ return redirect("/")
+ else:
+ return redirect("/?error=link-exists")
+
+@app.route("/dellink/", methods = ["POST"])
+def DelLink():
+ linkurl = str(request.form["linkurl"])
+
+ if len(linkurl) > 0:
+ if ExistQuickLink(linkdb,linkurl):
+ linkdb.Delete("quicklinks",["url"],[linkurl])
+ return redirect("/")
+ else:
+ return redirect("/?error=delete-link-fail")
+ else:
+ return redirect("/?error=invalid-url")
+
+app.run("0.0.0.0",8080)
diff --git a/templates/fqdn.html b/templates/fqdn.html
new file mode 100644
index 0000000..2a87ab8
--- /dev/null
+++ b/templates/fqdn.html
@@ -0,0 +1,11 @@
+<html>
+<head>
+<title>Junos Quick Links</title>
+</head>
+<body>
+<form method="POST" action="/moddomain/">
+FQDN: <input type="text" name="fqdn" /><br/>
+<input type="submit" value="Update" /><br/><br/>
+</form>
+</body>
+</html>
diff --git a/templates/root.html b/templates/root.html
new file mode 100644
index 0000000..19e930f
--- /dev/null
+++ b/templates/root.html
@@ -0,0 +1,18 @@
+<html>
+<head>
+<title>Junos Quick Links</title>
+</head>
+<body>
+<form method="POST" action="/addlink/">
+URL: <input type="text" name="linkurl" /><br/>
+<input type="submit" value="Add Link"/><br/><br/>
+</form>
+<form method="POST" action="/resetdomain/">
+<input type="hidden" name="fqdn" value="{{domainname}}" /><input type="submit" value="Reset FQDN" /><br/><br/>
+</form>
+<b>Saved Links:</b><br/>
+{% for thislink in linklist %}
+<a href="https://{{domainname}}/dana/home/launch.cgi?url={{thislink['url']}}" target="_blank">{{thislink['url']}}</a><form method="POST" action="/dellink/"><input type="hidden" name="linkurl" value="{{thislink}}" /><input type="submit" value="Delete" /></form><br/>
+{% endfor %}
+</body>
+</html>