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
76 def days_filter(time):
77 """Return the number of days elapsed since time."""
78 if jinja2.is_undefined(time):
80 diff = datetime.now(timezone.utc) - time
84 app.jinja_env.filters['days'] = days_filter
89 return render_template('hello.html')
94 # TODO: Replace stamp parameter with proper cache control HTTP
96 return render_template('home.html',
98 last_events=db.last_events())
101 @app.route('/login', methods=["POST"])
102 @app.route('/login/<iid>')
104 if request.method == "POST":
105 iid = request.data.decode("utf-8")
107 uid = db.get_uid(iid)
112 db.add_user_identifier(iid, iid, "Default")
117 return redirect(url_for('user'))
120 @app.route('/logout')
122 session.pop('uid', None)
123 session.pop('iid', None)
124 return redirect(url_for('home'))
131 counts = db.drink_count(uid, 0)
132 return render_template('user.html',
133 name=db.get_name(uid),
134 flavors=[_name for (_name, _ord) in db.flavors()],
136 identifiers=db.list_user_identifiers(uid),
139 last_events=db.last_events()
141 return redirect(url_for('home'))
144 @app.route('/user/rename')
146 name = request.args.get("name")
147 if name and "uid" in session:
149 db.name_user(uid, name)
150 return redirect(url_for('user'))
153 @app.route('/user/identifier/add', methods=["POST"])
154 def user_add_identifier():
155 if request.method == "POST":
157 if "uid" in session and "id" in json:
158 db.add_user_identifier(session["uid"], json["id"], 'None')
159 return redirect(url_for('user'))
162 @app.route('/user/identifier/rename', methods=["POST"])
163 def user_rename_identifier():
164 if request.method == "POST":
166 if "uid" in session and all(key in json for key in ["id", "name"]):
167 db.rename_user_identifier(session["uid"], json["id"], json["name"])
168 return redirect(url_for('user'))
171 @app.route('/user/identifier/disable', methods=["POST"])
172 def user_disable_identifier():
173 if request.method == "POST":
175 if "uid" in session and "id" in json:
176 db.disable_user_identifier(session["uid"], json["id"])
177 return logout() # force logout
180 @app.route("/coffee/graph_flavors")
181 def coffee_graph_flavors():
182 days = request.args.get('days', default=0, type=int)
183 start = request.args.get('start', default=0, type=int)
188 flavors, counts = zip(*db.coffee_flavors(uid, days, start))
190 flavors, counts = zip(*db.coffee_flavors(None, days, start))
191 fig = plt.figure(figsize=(3, 3))
192 ax = fig.add_subplot(111)
194 if "normalize" in matplotlib.pyplot.pie.__code__.co_varnames:
195 # Matplotlib >= 3.3.0
196 ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '',
200 ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '')
202 ax.legend(flavors, bbox_to_anchor=(1.0, 1.0))
205 ax.set_title("Your taste")
207 ax.set_title("This week taste")
209 fig.savefig(b, format="svg", bbox_inches="tight")
211 return send_file(b, mimetype="image/svg+xml")
214 @app.route("/coffee/graph_history")
215 def coffee_graph_history():
219 hist = db.coffee_history(uid)
221 hist = db.coffee_history()
227 unix_days, counts, flavors = zip(*hist)
228 fig = plt.figure(figsize=(4, 3))
229 ax = fig.add_subplot(111)
231 list_flavor = [_name for (_name, _ord) in sorted(db.flavors(), key=lambda x: x[1])]
232 l = [{} for i in range(len(list_flavor))]
237 for(d, c, f) in zip(unix_days, counts, flavors):
241 for i in range(len(list_flavor)):
242 if f == list_flavor[i]:
247 z = list(0 for i in range(len(l[0])))
248 for flavor in range(len(list_flavor)):
249 sortedlist = [(k, l[flavor][k]) for k in sorted(l[flavor])]
250 x = [i[0] for i in sortedlist]
251 y = [i[1] for i in sortedlist]
252 ax.bar(range(len(x)), y, bottom=z)
253 z = [sum(i) for i in zip(y, z)]
255 unix_days = set(unix_days)
256 xdays = [i.strftime("%a") for i in [
257 date.today() - timedelta(j - 1) for j in
258 range(len(unix_days), 0, -1)]]
261 ax.set_xticks(range(len(unix_days)))
262 ax.set_xticklabels(xdays)
265 ax.set_title("Your week")
267 ax.set_title("This week total")
269 ax.yaxis.set_major_locator(MaxNLocator(integer=True))
270 fig.savefig(b, format="svg", bbox_inches="tight")
273 return send_file(b, mimetype="image/svg+xml")
276 @app.route("/coffee/add", methods=["POST"])
278 if request.method == "POST":
281 if "iid" in session and all(key in json for key in ["flavor", "time"]):
282 print("User/id '%s' had '%s' at %s" % (session["iid"], json["flavor"], json["time"]))
283 db.add_coffee(session["iid"], json["flavor"], json["time"])
284 return redirect(url_for('user'))
287 @app.route("/event", methods=["POST"])
290 print("User '%(uid)s' registered event %(event_name)s at %(time)s" % json)
291 db.add_event(json["uid"], json["event_name"], json["time"])
292 return redirect(url_for('user'))
297 response = make_response(render_template('main.js'))
298 response.headers['Content-Type'] = "text/javascript"
302 @app.route("/log", methods=["POST"])
304 if request.method == "POST":
305 data = request.data.decode("utf-8")
311 @app.route("/tellCoffeebot", methods=["POST"])
312 def tell_coffeebot():
313 err = "Don't worry now! There is a NEW HOPE Tonda is buying NEW PACK!"
314 if request.method == "POST":
315 what = loads(request.data.decode("utf-8"))
317 with open(".coffee.conf", "r") as f:
318 conf = loads(f.read())
320 return "Config read error: '%s'! Please find in git history how the .coffee.conf file should look." \
323 res = post(conf["coffeebot"]["url"], json=what)
324 print("res is {}".format(res))
326 err = "No connection! No covfefe! We all die here!"
328 err = "Slack doesn't like our request! It's discrimination!"