summaryrefslogtreecommitdiff
path: root/utab/__main__.py
diff options
context:
space:
mode:
authorFrederick Yin <fkfd@macaw.me>2020-07-04 14:23:36 +0800
committerFrederick Yin <fkfd@macaw.me>2020-07-04 14:23:36 +0800
commit0be69d4b5db18b1e0794fd3dc3297da0a16b1ccf (patch)
tree00c8f50f381d4531a3a45eeed0f9cdd1bf18f3b1 /utab/__main__.py
Minimal viable product
Diffstat (limited to 'utab/__main__.py')
-rw-r--r--utab/__main__.py77
1 files changed, 77 insertions, 0 deletions
diff --git a/utab/__main__.py b/utab/__main__.py
new file mode 100644
index 0000000..5e619ed
--- /dev/null
+++ b/utab/__main__.py
@@ -0,0 +1,77 @@
+from flask import Flask, Response, request, redirect, abort
+from appdirs import user_data_dir
+from pathlib import Path
+import urllib
+import sys
+import yaml
+import csv
+from .rendering import *
+
+app = Flask(__name__)
+
+# locate page template at e.g. $XDG_CONFIG_HOME/utab/index.html
+# and sites json file at utab/sites.json
+data_dir = user_data_dir(appname="utab")
+template_fp = Path(data_dir) / "index.html"
+css_dir = Path(data_dir) / "css"
+try:
+ template = Path.open(template_fp).read()
+except FileNotFoundError:
+ print("Template file not found.")
+ sys.exit(1)
+
+sites_fp = Path(data_dir) / "sites.csv"
+config_fp = Path(data_dir) / "config.yml"
+with open(config_fp) as f:
+ config = yaml.load(f.read())
+ f.close()
+
+
+def read_sites():
+ with open(sites_fp) as f:
+ sites = list(csv.reader(f))
+ f.close()
+ return sites
+
+
+@app.route("/")
+def index():
+ return render_page(
+ template,
+ sites=render_sites(
+ read_sites(), columns=config["columns"], rows=config["rows"]
+ ),
+ )
+
+
+@app.route("/go/<path:url>")
+def visit_site(url):
+ print(url)
+ url_unesc = urllib.parse.unquote(url) # unescaped url
+ print(url_unesc)
+ sites = read_sites()
+ for i, s in enumerate(sites):
+ if s[0] == url_unesc:
+ sites[i][VISITS] = str(int(sites[i][VISITS]) + 1)
+ with open(sites_fp, "w") as f:
+ # update visits
+ csv.writer(f).writerows(sites)
+ f.close()
+ return redirect(url_unesc, 302)
+
+
+@app.route("/css/<string:filename>")
+def serve_css(filename):
+ try:
+ with open(css_dir / filename) as f:
+ resp = Response(f.read(), 200, {"Content-Type": "text/css"})
+ f.close()
+ return resp
+ except FileNotFoundError:
+ return abort(404)
+ except:
+ return abort(500)
+
+
+# run on localhost only
+app.run("127.0.0.1", 64366)