1 from flask import Flask, render_template, send_file, request, session, redirect, url_for, make_response
2 from flask_cors import CORS
5 import matplotlib.pyplot as plt
6 from matplotlib.ticker import MaxNLocator
12 from datetime import date, timedelta, datetime, timezone
14 from json import loads
15 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, max_interval="years"):
29 """Convert date/time in ISO format to relative, human readable string.
31 Example return values: 'an hour ago', 'Yesterday', '3 months ago',
34 When optional max_interval is set to "days", the return value will
35 report at most the number of days ago, not week, months or years.
37 if jinja2.is_undefined(time):
39 if max_interval not in ["years", "days"]:
42 diff = datetime.now(timezone.utc) - time
43 second_diff = diff.seconds
47 return 'in the future'
53 return str(int(second_diff)) + " seconds ago"
56 if second_diff < 3600:
57 return str(int(second_diff / 60)) + " minutes ago"
58 if second_diff < 7200:
60 if second_diff < 86400:
61 return str(int(second_diff / 3600)) + " hours ago"
64 if day_diff < 7 or max_interval == "days":
65 return str(day_diff) + " days ago"
67 return str(int(day_diff / 7)) + " weeks ago"
69 return str(int(day_diff / 30)) + " months ago"
70 return str(int(day_diff / 365)) + " years ago"
73 app.jinja_env.filters['humanize'] = humanize_ts
80 return render_template('hello.html', name=db.get_name(uid))
81 return render_template('hello.html')
84 @app.route('/login', methods=["POST"])
85 @app.route('/login/<iid>')
87 if request.method == "POST":
88 iid = request.data.decode("utf-8")
95 db.add_user_identifier(iid, iid, "Default")
100 return redirect(url_for('user'))
103 @app.route('/logout')
105 session.pop('uid', None)
106 session.pop('iid', None)
107 return redirect(url_for('user'))
114 counts = db.drink_count(uid, 0)
115 return render_template('user.html',
116 name=db.get_name(uid),
117 flavors=[_name for (_name, _ord) in db.flavors()],
119 identifiers=db.list_user_identifiers(uid),
122 last_events=db.last_events()
124 # TODO: Replace stamp parameter with proper cache control HTTP
125 # headers in response
126 return render_template('user.html', stamp=time.time(),
127 last_events=db.last_events(),
131 @app.route('/user/rename')
133 name = request.args.get("name")
134 if name and "uid" in session:
136 db.name_user(uid, name)
137 return redirect(url_for('user'))
140 @app.route('/user/identifier/add', methods=["POST"])
141 def user_add_identifier():
142 if request.method == "POST":
144 if "uid" in session and "id" in json:
145 db.add_user_identifier(session["uid"], json["id"], 'None')
146 return redirect(url_for('user'))
149 @app.route('/user/identifier/rename', methods=["POST"])
150 def user_rename_identifier():
151 if request.method == "POST":
153 if "uid" in session and all(key in json for key in ["id", "name"]):
154 db.rename_user_identifier(session["uid"], json["id"], json["name"])
155 return redirect(url_for('user'))
158 @app.route('/user/identifier/disable', methods=["POST"])
159 def user_disable_identifier():
160 if request.method == "POST":
162 if "uid" in session and "id" in json:
163 db.disable_user_identifier(session["uid"], json["id"])
164 return logout() # force logout
167 @app.route("/coffee/graph_flavors")
168 def coffee_graph_flavors():
169 days = request.args.get('days', default=0, type=int)
170 start = request.args.get('start', default=0, type=int)
175 flavors, counts = zip(*db.coffee_flavors(uid, days, start))
177 flavors, counts = zip(*db.coffee_flavors(None, days, start))
178 fig = plt.figure(figsize=(3, 3))
179 ax = fig.add_subplot(111)
181 if "normalize" in matplotlib.pyplot.pie.__code__.co_varnames:
182 # Matplotlib >= 3.3.0
183 ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '',
187 ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '')
189 ax.legend(flavors, bbox_to_anchor=(1.0, 1.0))
192 ax.set_title("Your taste")
194 ax.set_title("This week taste")
196 fig.savefig(b, format="svg", bbox_inches="tight")
198 return send_file(b, mimetype="image/svg+xml")
201 @app.route("/coffee/graph_history")
202 def coffee_graph_history():
206 hist = db.coffee_history(uid)
208 hist = db.coffee_history()
214 unix_days, counts, flavors = zip(*hist)
215 fig = plt.figure(figsize=(4, 3))
216 ax = fig.add_subplot(111)
218 list_flavor = [_name for (_name, _ord) in sorted(db.flavors(), key=lambda x: x[1])]
219 l = [{} for i in range(len(list_flavor))]
224 for(d, c, f) in zip(unix_days, counts, flavors):
228 for i in range(len(list_flavor)):
229 if f == list_flavor[i]:
234 z = list(0 for i in range(len(l[0])))
235 for flavor in range(len(list_flavor)):
236 sortedlist = [(k, l[flavor][k]) for k in sorted(l[flavor])]
237 x = [i[0] for i in sortedlist]
238 y = [i[1] for i in sortedlist]
239 ax.bar(range(len(x)), y, bottom=z)
240 z = [sum(i) for i in zip(y, z)]
242 unix_days = set(unix_days)
243 xdays = [i.strftime("%a") for i in [
244 date.today() - timedelta(j - 1) for j in
245 range(len(unix_days), 0, -1)]]
248 ax.set_xticks(range(len(unix_days)))
249 ax.set_xticklabels(xdays)
252 ax.set_title("Your week")
254 ax.set_title("This week total")
256 ax.yaxis.set_major_locator(MaxNLocator(integer=True))
257 fig.savefig(b, format="svg", bbox_inches="tight")
260 return send_file(b, mimetype="image/svg+xml")
263 @app.route("/coffee/add", methods=["POST"])
265 if request.method == "POST":
268 if "iid" in session and all(key in json for key in ["flavor", "time"]):
269 print("User/id '%s' had '%s' at %s" % (session["iid"], json["flavor"], json["time"]))
270 db.add_coffee(session["iid"], json["flavor"], json["time"])
271 return redirect(url_for('user'))
274 @app.route("/event", methods=["POST"])
277 print("User '%(uid)s' registered event %(event_name)s at %(time)s" % json)
278 db.add_event(json["uid"], json["event_name"], json["time"])
279 return redirect(url_for('user'))
282 # TODO: Remove me - unused
283 @app.route("/coffee/count")
285 start = request.args.get("start")
286 stop = request.args.get("stop")
287 return str(dict(db.drink_count(session.get("uid"), start, stop)).get("coffee", 0))
292 response = make_response(render_template('main.js'))
293 response.headers['Content-Type'] = "text/javascript"
297 @app.route("/log", methods=["POST"])
299 if request.method == "POST":
300 data = request.data.decode("utf-8")
306 @app.route("/tellCoffeebot", methods=["POST"])
307 def tell_coffeebot():
308 err = "Don't worry now! There is a NEW HOPE Tonda is buying NEW PACK!"
309 if request.method == "POST":
310 what = loads(request.data.decode("utf-8"))
312 with open(".coffee.conf", "r") as f:
313 conf = loads(f.read())
315 return "Config read error: '%s'! Please find in git history how the .coffee.conf file should look." \
318 res = post(conf["coffeebot"]["url"], json=what)
319 print("res is {}".format(res))
321 err = "No connection! No covfefe! We all die here!"
323 err = "Slack doesn't like our request! It's discrimination!"