1 from flask import Flask, render_template, send_file, request, session, redirect, url_for, make_response
2 from flask_cors import CORS
7 import matplotlib.pyplot as plt
8 from matplotlib.ticker import MaxNLocator
11 import coffee_db as db
14 from datetime import date, timedelta, datetime, timezone
16 from json import loads
17 from requests import post
22 CORS(app, supports_credentials=True)
23 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
26 # Inspired by https://shubhamjain.co/til/how-to-render-human-readable-time-in-jinja/,
27 # updated to our needs
28 def humanize_ts(time):
30 Convert date in ISO format to relative, human readable string
31 like 'an hour ago', 'Yesterday', '3 months ago',
34 if jinja2.is_undefined(time):
36 now = datetime.now(timezone.utc)
37 if time[-1] == 'Z': # Convert Zulu time zone to datetime compatible format
38 time = time[0:-1] + '+00:00'
39 diff = now - datetime.fromisoformat(time)
40 second_diff = diff.seconds
50 return str(int(second_diff)) + " seconds ago"
53 if second_diff < 3600:
54 return str(int(second_diff / 60)) + " minutes ago"
55 if second_diff < 7200:
57 if second_diff < 86400:
58 return str(int(second_diff / 3600)) + " hours ago"
62 return str(day_diff) + " days ago"
64 return str(int(day_diff / 7)) + " weeks ago"
66 return str(int(day_diff / 30)) + " months ago"
67 return str(int(day_diff / 365)) + " years ago"
70 app.jinja_env.filters['humanize'] = humanize_ts
77 return render_template('hello.html', name=db.get_name(uid))
78 return render_template('hello.html')
81 @app.route('/login', methods=["POST"])
82 @app.route('/login/<iid>')
84 if request.method == "POST":
85 iid = request.data.decode("utf-8")
92 db.add_user_identifier(iid, iid, "Default")
97 return redirect(url_for('user'))
100 @app.route('/logout')
102 session.pop('uid', None)
103 session.pop('iid', None)
104 return redirect(url_for('user'))
111 counts = db.drink_count(uid, 0)
112 return render_template('user.html',
113 name=db.get_name(uid),
114 flavors=[_name for (_name, _ord) in db.flavors()],
116 identifiers=db.list_user_identifiers(uid),
119 last_events=db.last_events()
121 # TODO: Replace stamp parameter with proper cache control HTTP
122 # headers in response
123 return render_template('user.html', stamp=time.time(),
124 last_events=db.last_events(),
128 @app.route('/user/rename')
130 name = request.args.get("name")
131 if name and "uid" in session:
133 db.name_user(uid, name)
134 return redirect(url_for('user'))
137 @app.route('/user/identifier/add', methods=["POST"])
138 def user_add_identifier():
139 if request.method == "POST":
141 if "uid" in session and "id" in json:
142 db.add_user_identifier(session["uid"], json["id"], 'None')
143 return redirect(url_for('user'))
146 @app.route('/user/identifier/rename', methods=["POST"])
147 def user_rename_identifier():
148 if request.method == "POST":
150 if "uid" in session and all(key in json for key in ["id", "name"]):
151 db.rename_user_identifier(session["uid"], json["id"], json["name"])
152 return redirect(url_for('user'))
155 @app.route('/user/identifier/disable', methods=["POST"])
156 def user_disable_identifier():
157 if request.method == "POST":
159 if "uid" in session and "id" in json:
160 db.disable_user_identifier(session["uid"], json["id"])
161 return logout() # force logout
164 @app.route("/coffee/graph_flavors")
165 def coffee_graph_flavors():
166 days = request.args.get('days', default = 0, type = int)
167 start = request.args.get('start', default = 0, type = int)
172 flavors, counts = zip(*db.coffee_flavors(uid, days, start))
174 flavors, counts = zip(*db.coffee_flavors(None, days, start))
175 fig = plt.figure(figsize=(3, 3))
176 ax = fig.add_subplot(111)
178 if "normalize" in matplotlib.pyplot.pie.__code__.co_varnames:
179 # Matplotlib >= 3.3.0
180 ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '',
184 ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '')
186 ax.legend(flavors, bbox_to_anchor=(1.0, 1.0))
189 ax.set_title("Your taste")
191 ax.set_title("This week taste")
193 fig.savefig(b, format="svg", bbox_inches="tight")
195 return send_file(b, mimetype="image/svg+xml")
198 @app.route("/coffee/graph_history")
199 def coffee_graph_history():
203 hist = db.coffee_history(uid)
205 hist = db.coffee_history()
211 unix_days, counts, flavors = zip(*hist)
212 fig = plt.figure(figsize=(4, 3))
213 ax = fig.add_subplot(111)
215 list_flavor = [_name for (_name, _ord) in sorted(db.flavors(), key=lambda x: x[1])]
216 l = [{} for i in range(len(list_flavor))]
221 for(d, c, f) in zip(unix_days, counts, flavors):
225 for i in range(len(list_flavor)):
226 if f == list_flavor[i]:
231 z = list(0 for i in range(len(l[0])))
232 for flavor in range(len(list_flavor)):
233 sortedlist = [(k, l[flavor][k]) for k in sorted(l[flavor])]
234 x = [i[0] for i in sortedlist]
235 y = [i[1] for i in sortedlist]
236 ax.bar(range(len(x)), y, bottom=z)
237 z = [sum(i) for i in zip(y, z)]
239 unix_days = set(unix_days)
240 xdays = [i.strftime("%a") for i in [
241 date.today() - timedelta(j - 1) for j in
242 range(len(unix_days), 0, -1)]]
245 ax.set_xticks(range(len(unix_days)))
246 ax.set_xticklabels(xdays)
249 ax.set_title("Your week")
251 ax.set_title("This week total")
253 ax.yaxis.set_major_locator(MaxNLocator(integer=True))
254 fig.savefig(b, format="svg", bbox_inches="tight")
257 return send_file(b, mimetype="image/svg+xml")
260 @app.route("/coffee/add", methods=["POST"])
262 if request.method == "POST":
265 if "iid" in session and all(key in json for key in ["flavor", "time"]):
266 print("User/id '%s' had '%s' at %s" % (session["iid"], json["flavor"], json["time"]))
267 db.add_coffee(session["iid"], json["flavor"], json["time"])
268 return redirect(url_for('user'))
271 @app.route("/event", methods=["POST"])
274 print("User '%(uid)s' registered event %(event_name)s at %(time)s" % json)
275 db.add_event(json["uid"], json["event_name"], json["time"])
276 return redirect(url_for('user'))
279 # TODO: Remove me - unused
280 @app.route("/coffee/count")
282 start = request.args.get("start")
283 stop = request.args.get("stop")
284 return str(dict(db.drink_count(session.get("uid"), start, stop)).get("coffee", 0))
289 response = make_response(render_template('main.js'))
290 response.headers['Content-Type'] = "text/javascript"
294 @app.route("/log", methods=["POST"])
296 if request.method == "POST":
297 data = request.data.decode("utf-8")
302 @app.route("/tellCoffeebot", methods=["POST"])
303 def tell_coffeebot():
304 err = "Don't worry now! There is a NEW HOPE Tonda is buying NEW PACK!"
305 if request.method == "POST":
306 what = loads(request.data.decode("utf-8"))
308 with open(".coffee.conf", "r") as f:
309 conf = loads(f.read())
311 return "Config read error: '%s'! Please find in git history how the .coffee.conf file should look." \
314 res = post(conf["coffeebot"]["url"], json=what)
315 print("res is {}".format(res))
317 err = "No connection! No covfefe! We all die here!"
319 err = "Slack doesn't like our request! It's discrimination!"