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
16 from json import loads
17 from requests import post
21 CORS(app, supports_credentials=True)
22 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
29 return render_template('hello.html', name=db.get_name(uid))
30 return render_template('hello.html')
33 @app.route('/login', methods=["POST"])
34 @app.route('/login/<uid>')
36 if request.method == "POST":
37 uid = request.data.decode("utf-8")
41 return redirect(url_for('user'))
46 session.pop('uid', None)
47 return redirect(url_for('user'))
54 return render_template('user.html',
55 name=db.get_name(uid),
57 count=db.coffee_count(uid, 0),
60 # TODO: Replace stamp parameter with proper cache control HTTP
62 return render_template('user.html', stamp=time.time())
65 @app.route('/user/rename')
67 name = request.args.get("name")
68 if name and "uid" in session:
70 db.name_user(uid, name)
71 return redirect(url_for('user'))
74 @app.route("/coffee/graph_flavors")
75 def coffee_graph_flavors():
76 days = request.args.get('days', default = 0, type = int)
77 start = request.args.get('start', default = 0, type = int)
82 flavors, counts = zip(*db.coffee_flavors(uid, days, start))
84 flavors, counts = zip(*db.coffee_flavors(None, days, start))
85 fig = plt.figure(figsize=(3, 3))
86 ax = fig.add_subplot(111)
88 ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '')
89 ax.legend(flavors, bbox_to_anchor=(1.0, 1.0))
92 ax.set_title("Your taste")
94 ax.set_title("This week taste")
96 fig.savefig(b, format="svg", bbox_inches="tight")
98 return send_file(b, mimetype="image/svg+xml")
101 @app.route("/coffee/graph_history")
102 def coffee_graph_history():
106 hist = db.coffee_history(uid)
108 hist = db.coffee_history()
114 unix_days, counts, flavors = zip(*hist)
115 fig = plt.figure(figsize=(4, 3))
116 ax = fig.add_subplot(111)
118 list_flavor = sorted(db.flavors())
119 l = [{} for i in range(len(list_flavor))]
124 for(d, c, f) in zip(unix_days, counts, flavors):
128 for i in range(len(list_flavor)):
129 if f == list_flavor[i]:
134 z = list(0 for i in range(len(l[0])))
135 for flavor in range(len(list_flavor)):
136 sortedlist = [(k, l[flavor][k]) for k in sorted(l[flavor])]
137 x = [i[0] for i in sortedlist]
138 y = [i[1] for i in sortedlist]
139 ax.bar(range(len(x)), y, bottom=z)
140 z = [sum(i) for i in zip(y, z)]
142 unix_days = set(unix_days)
143 xdays = [i.strftime("%a") for i in [
144 date.today() - timedelta(j - 1) for j in
145 range(len(unix_days), 0, -1)]]
148 ax.set_xticks(range(len(unix_days)))
149 ax.set_xticklabels(xdays)
152 ax.set_title("Your week")
154 ax.set_title("This week total")
156 ax.yaxis.set_major_locator(MaxNLocator(integer=True))
157 fig.savefig(b, format="svg", bbox_inches="tight")
160 return send_file(b, mimetype="image/svg+xml")
163 @app.route("/coffee/add", methods=["POST"])
165 if request.method == "POST":
167 print("User '%(uid)s' had '%(flavor)s' at %(time)s" % json)
168 db.add_coffee(json["uid"], json["flavor"], json["time"])
169 return redirect(url_for('user'))
172 @app.route("/coffee/count")
174 start = request.args.get("start")
175 stop = request.args.get("stop")
176 return str(db.coffee_count(session.get("uid"), start, stop))
181 response = make_response(render_template('main.js'))
182 response.headers['Content-Type'] = "text/javascript"
186 @app.route("/log", methods=["POST"])
188 if request.method == "POST":
189 data = request.data.decode("utf-8")
194 @app.route("/tellCoffeebot", methods=["POST"])
195 def tell_coffeebot():
196 err = "Don't worry now! There is a NEW HOPE Tonda is buying NEW PACK!"
197 if request.method == "POST":
198 what = loads(request.data.decode("utf-8"))
200 with open(".config", "r") as f:
201 conf = loads(f.read())
203 return "Config read error: '%s'! Please find in git history how the .config should look." \
206 res = post(conf["coffeebot"]["url"], json=what)
207 print("res is {}".format(res))
209 err = "No connection! No covfefe! We all die here!"
211 err = "Slack doesn't like our request! It's discrimination!"