]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/blobdiff - app.py
Fix duplicate recording of coffees
[coffee/coffee-flask.git] / app.py
diff --git a/app.py b/app.py
index 54816242b4640af21592d5c153f659a4ccadd3f1..63ee2b5311b37e8827cecacb72459ea97b5983ca 100644 (file)
--- a/app.py
+++ b/app.py
@@ -10,8 +10,12 @@ from io import BytesIO
 
 import coffee_db as db
 import time
+import sys
 from datetime import date, timedelta
 
+from json import loads
+from requests import post
+
 db.init_db()
 app = Flask(__name__)
 CORS(app, supports_credentials=True)
@@ -53,7 +57,9 @@ def user():
                                count=db.coffee_count(uid, 0),
                                stamp=time.time()
                                )
-    return render_template('user.html')
+    # TODO: Replace stamp parameter with proper cache control HTTP
+    # headers in response
+    return render_template('user.html', stamp=time.time())
 
 
 @app.route('/user/rename')
@@ -67,18 +73,26 @@ def user_rename():
 
 @app.route("/coffee/graph_flavors")
 def coffee_graph_flavors():
+    days = request.args.get('days', default = 0, type = int)
+    start = request.args.get('start', default = 0, type = int)
+
     b = BytesIO()
     if "uid" in session:
         uid = session["uid"]
-        flavors, counts = zip(*db.coffee_flavors(uid))
+        flavors, counts = zip(*db.coffee_flavors(uid, days, start))
     else:
-        flavors, counts = zip(*db.coffee_flavors())
+        flavors, counts = zip(*db.coffee_flavors(None, days, start))
     fig = plt.figure(figsize=(3, 3))
     ax = fig.add_subplot(111)
     ax.set_aspect(1)
     ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '')
     ax.legend(flavors, bbox_to_anchor=(1.0, 1.0))
-    ax.set_title("Your taste")
+
+    if "uid" in session:
+        ax.set_title("Your taste")
+    else:
+        ax.set_title("This week taste")
+
     fig.savefig(b, format="svg", bbox_inches="tight")
     b.seek(0)
     return send_file(b, mimetype="image/svg+xml")
@@ -93,21 +107,21 @@ def coffee_graph_history():
     else:
         hist = db.coffee_history()
     if hist == []:
-        days = tuple()
+        unix_days = tuple()
         counts = tuple()
         flavors = tuple()
     else:
-        days, counts, flavors = zip(*hist)
+        unix_days, counts, flavors = zip(*hist)
     fig = plt.figure(figsize=(4, 3))
     ax = fig.add_subplot(111)
 
     list_flavor = sorted(db.flavors())
     l = [{} for i in range(len(list_flavor))]
     for ll in l:
-        for d in days:
+        for d in unix_days:
             ll[d] = 0
 
-    for(d, c, f) in zip(days, counts, flavors):
+    for(d, c, f) in zip(unix_days, counts, flavors):
         if f is None:
             continue
         what_f = 0
@@ -125,15 +139,20 @@ def coffee_graph_history():
         ax.bar(range(len(x)), y, bottom=z)
         z = [sum(i) for i in zip(y, z)]
 
-    days = set(days)
+    unix_days = set(unix_days)
     xdays = [i.strftime("%a") for i in [
         date.today() - timedelta(j - 1) for j in
-        range(len(days), 0, -1)]]
+        range(len(unix_days), 0, -1)]]
     xdays[-1] = "TDY"
     xdays[-2] = "YDA"
-    ax.set_xticks(range(len(days)))
+    ax.set_xticks(range(len(unix_days)))
     ax.set_xticklabels(xdays)
-    ax.set_title("Your week")
+
+    if "uid" in session:
+        ax.set_title("Your week")
+    else:
+        ax.set_title("This week total")
+
     ax.yaxis.set_major_locator(MaxNLocator(integer=True))
     fig.savefig(b, format="svg", bbox_inches="tight")
     b.seek(0)
@@ -171,3 +190,23 @@ def log():
         print("Log:", data)
         return data
     return "nope"
+
+@app.route("/tellCoffeebot", methods=["POST"])
+def tell_coffeebot():
+    err = "Don't worry now! There is a NEW HOPE Tonda is buying NEW PACK!"
+    if request.method == "POST":
+        what = loads(request.data.decode("utf-8"))
+    try:
+        with open(".config", "r") as f:
+            conf = loads(f.read())
+    except:
+        return "Config read error: '%s'! Please find in git history how the .config should look." \
+            % sys.exc_info()[1]
+    try:
+        res = post(conf["coffeebot"]["url"], json=what)
+        print("res is {}".format(res))
+    except:
+        err = "No connection! No covfefe! We all die here!"
+    if not res.ok:
+        err = "Slack doesn't like our request! It's discrimination!"
+    return err