]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/blobdiff - templates/main.js
Do not allow multiple reconnect timers running simultaneously
[coffee/coffee-flask.git] / templates / main.js
index f945b292cd14f4b767c725c9ae5bd4632f46ce93..02c956c33a0dd30b5badb90efdcb2c82f7454bf6 100644 (file)
@@ -3,9 +3,10 @@ var flask = "{{ url_for('hello', _external=True) }}"
 // State variables
 
 var updateRemote = undefined;   // defined iff remote server accessible
-var loggedIn = false;           // true after swiping the cards
 var timeToLogout = undefined;   // defined during logout countdown
 var logoutTimer;
+var reloadTimer = undefined;
+var id_user;                    // ID of the user who is to be accounted for the next coffee
 
 console.log("hello from flask");
 //sendJSON("{\"type\":\"empty\"}");
@@ -14,18 +15,14 @@ function update(id, msg) {
     document.getElementById(id).innerHTML = msg;
 }
 
-function loadLocalStorage() {
+function replayOfflineQueue() {
     if (localStorage) {
-        if (localStorage.length) {
-            for (var i = 0; i < localStorage.length; i++) {
-                var value = localStorage.getItem(localStorage.key(i));
-                try {
-                    updateRemote(value);
-                } catch (err) {
-                    console.log("no json: " + value)
-                }
-            }
-            localStorage.clear();
+        let queue = JSON.parse(localStorage.getItem("offlineQueue")) || [];
+        if (Array.isArray(queue)) {
+            queue.forEach(function (entry) {
+                updateRemote(entry.data, new Date(entry.time));
+            });
+            localStorage.removeItem("offlineQueue");
         }
     }
 }
@@ -37,49 +34,45 @@ var flavorChosen;
 // call this function. This function updates the UI to match the state.
 function updateUI()
 {
-    if (updateRemote === undefined) {
-        update("remote", "<center>Server offline...</center>");
-        document.getElementById("local").style.display = "block";
-    } else {
-        document.getElementById("local").style.display = "none";
+    try {
+        let offline = updateRemote === undefined;
+
+        document.getElementById("local").style.display = !offline ? "none" : "block";
+        document.getElementById("remote").style.display = offline ? "none" : "block";
 
-        if (loggedIn) {
+        if (offline)
+            return;
+
+        if (id_user !== undefined) {
             document.getElementById("nextStep").innerHTML = "Now select a beverage on the coffee machineā€¦";
         } else {
             document.getElementById("nextStep").innerHTML = "Enjoy your " + flavorChosen + "!";
         }
 
         if (timeToLogout !== undefined)
-            document.getElementById("logout_button").value = '\nlogout\n(' + timeToLogout + ' s)';
+            document.getElementById("logout_button").innerHTML = '<br>logout<br>(' + timeToLogout + ' s)';
+    }
+    catch (err) {
+        console.log("Error: ", err);
     }
 }
 
-function hiddenUpdateRemote(json) {
+function hiddenUpdateRemote(json, time = new Date()) {
     var msg = JSON.parse(json);
 
-    //update("json", "json: " + JSON.stringify(msg))
-
     switch(msg.type) {
         case "empty":
-            //update("json","");
             break;
         case "rfid":
-            /*update("json",
-                "uid: " + msg.uid + "<br>" +
-                "card type: " + msg.card_type + "<br>" +
-                "uid size: " + msg.size + " bytes<br>" +
-                "sak: " + msg.sak
-            );*/
             login(msg.uid);
             break;
         case "keys":
-            //update("json", "key: " + msg.key);
             var flavor = getFlavor(msg.key);
             if (flavor !== "") {
-                addCoffee(flavor);
+                addCoffee(flavor, time);
             }
             break;
-        case "fuck":
+        case "ajax_failure":
             ajax(msg.method, msg.route, msg.data, msg.id);
             break;
     }
@@ -89,11 +82,20 @@ function hiddenUpdateRemote(json) {
 function loadRemote(string) {
     var xhr = new XMLHttpRequest();
     xhr.onreadystatechange = function() {
-        if (this.readyState == 4 && this.status == 200) {
-            update("remote", this.responseText);
-            updateRemote = hiddenUpdateRemote;
-            loadLocalStorage();
-            updateUI();
+        if (this.readyState == 4) {
+            if (this.status == 200) {
+                update("remote", this.responseText);
+                updateRemote = hiddenUpdateRemote;
+                replayOfflineQueue();
+                updateUI();
+                clearTimeout(reloadTimer);
+            } else {
+                // Cancel current timer for the case when loadRemote()
+                // was called multiple times (e.g. multiple ajax()
+                // calls failed simultaneously).
+                clearTimeout(reloadTimer);
+                reloadTimer = setTimeout(loadRemote, 1000);
+            }
         }
     };
     xhr.open("GET", flask, true);
@@ -112,18 +114,24 @@ function ajax(method, route, data, id) {
             } else {
                 updateRemote = undefined;
                 updateUI();
+                loadRemote(); // Try to contact the server periodically
 
                 if (localStorage) {
-                    var now = Date.now();
-                    var fuck = JSON.stringify({
-                        type: "fuck",
+                    var ajax_failure = JSON.stringify({
+                        type: "ajax_failure",
                         method: method,
                         route: route,
                         data: data,
                         id: id
                     });
-                    localStorage.setItem(now, fuck);
-                    console.log(now + ": " + fuck);
+                    let queue = JSON.parse(localStorage.getItem("offlineQueue")) || [];
+                    queue.push({ time: Date.now(), data: ajax_failure });
+                    try {
+                        localStorage.setItem("offlineQueue", JSON.stringify(queue));
+                    }
+                    catch (err) {
+                        console.log(err);
+                    }
                 }
             }
         }
@@ -141,20 +149,20 @@ function ajax(method, route, data, id) {
 
 function login(id) {
     ajax("POST", "login", id, "user");
-    loggedIn = true;
-    clearTimeout(logoutTimer);
-    timeToLogout = undefined;
+    id_user = id;
+    countingTimeLogout(120);
 }
 
 function logout() {
     sendReset();
     ajax("GET", "logout", "", "user");
-    loggedIn = false;
+    id_user = undefined;
     timeToLogout = undefined;
 }
 
 function countingTimeLogout(count_time)
 {
+    clearTimeout(logoutTimer);
     timeToLogout = count_time;
     updateUI();
     if (count_time == 0) {
@@ -178,15 +186,16 @@ function getFlavor(letter) {
     }
 }
 
-function addCoffee(flavor) {
+function addCoffee(flavor, time = new Date()) {
     var data = JSON.stringify({
-        time: new Date().toISOString(),
-        flavor: flavor
+        time: time.toISOString(),
+        flavor: flavor,
+        uid: id_user
     });
-    if (loggedIn) {
+    if (id_user) {
         ajax("POST", "coffee/add", data, "user");
         flavorChosen = flavor;
-        loggedIn = false;
+        id_user = undefined;
         countingTimeLogout(10); //mean 10 seconds
     }
 }