]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/blob - templates/main.js
Add missing quotes in JS handler for disabling identifier
[coffee/coffee-flask.git] / templates / main.js
1 var flask = "{{ url_for('hello', _external=True) }}"
2
3 // State variables
4
5 var updateRemote = undefined;           // defined iff remote server accessible
6 var timeToLogout = undefined;           // defined during logout countdown
7 var logoutTimer;
8 var reloadTimer = undefined;
9 var id_user;                            // ID of the user who is to be accounted for the next coffee
10 var identifier_registration = false;    // true if identifier is supposed to be registered for user
11
12 console.log("hello from flask");
13 //sendJSON("{\"type\":\"empty\"}");
14
15 function update(id, msg) {
16     document.getElementById(id).innerHTML = msg;
17 }
18
19 function replayOfflineQueue() {
20     if (localStorage) {
21         let queue = JSON.parse(localStorage.getItem("offlineQueue")) || [];
22         if (Array.isArray(queue)) {
23             queue.forEach(function (entry) {
24                 updateRemote(entry.data, new Date(entry.time));
25             });
26             localStorage.removeItem("offlineQueue");
27         }
28     }
29 }
30
31 var flavorChosen;
32
33 // Central function to update UI elements. To ensure that the UI is
34 // consistent, other code should only change state variables and then
35 // call this function. This function updates the UI to match the state.
36 function updateUI()
37 {
38     try {
39         let offline = updateRemote === undefined;
40
41         document.getElementById("local").style.display = !offline ? "none" : "block";
42         document.getElementById("remote").style.display = offline ? "none" : "block";
43
44         if (offline) {
45             showOfflineQueue();
46             return;
47         }
48
49         if (id_user !== undefined) {
50             document.getElementById("nextStep").innerHTML = "Now select a beverage on the coffee machineā€¦";
51         } else {
52             document.getElementById("nextStep").innerHTML = "Enjoy your " + flavorChosen + "!";
53         }
54
55         if (timeToLogout !== undefined)
56             document.getElementById("logout_button").innerHTML = '<br>logout<br>(' + timeToLogout + ' s)';
57     }
58     catch (err) {
59         console.log("Error: ", err);
60     }
61 }
62
63 function hiddenUpdateRemote(json, time = new Date()) {
64     var msg = JSON.parse(json);
65
66     switch(msg.type) {
67         case "empty":
68             break;
69         case "rfid":
70             if (identifier_registration) {
71                 ajax("POST", "user/identifier/add", JSON.stringify({ id: msg.uid }), "user");
72
73                 addIdentifier_finish();
74             } else {
75                 login(msg.uid);
76             }
77             break;
78         case "keys":
79             if (!identifier_registration) {
80                 var flavor = getFlavor(msg.key);
81                 if (flavor !== "") {
82                     addCoffee(flavor, time);
83                 }
84             }
85             break;
86         case "ajax_failure":
87             ajax(msg.method, msg.route, msg.data, msg.id);
88             break;
89     }
90
91     sendLog(json);
92 }
93
94 function loadRemote(string) {
95     var xhr = new XMLHttpRequest();
96     xhr.onreadystatechange = function() {
97         if (this.readyState == 4) {
98             if (this.status == 200) {
99                 update("remote", this.responseText);
100                 updateRemote = hiddenUpdateRemote;
101                 replayOfflineQueue();
102                 updateUI();
103                 clearTimeout(reloadTimer);
104             } else {
105                 // Cancel current timer for the case when loadRemote()
106                 // was called multiple times (e.g. multiple ajax()
107                 // calls failed simultaneously).
108                 clearTimeout(reloadTimer);
109                 reloadTimer = setTimeout(loadRemote, 1000);
110             }
111         }
112     };
113     xhr.open("GET", flask, true);
114     xhr.send();
115 }
116
117 loadRemote();
118
119 function ajax(method, route, data, id) {
120     var xhr = new XMLHttpRequest();
121     xhr.onreadystatechange = function() {
122         if (this.readyState == 4) {
123             if (this.status == 200) {
124                 update(id, this.responseText);
125                 updateUI();
126             } else {
127                 updateRemote = undefined;
128                 updateUI();
129                 loadRemote(); // Try to contact the server periodically
130
131                 if (localStorage) {
132                     var ajax_failure = JSON.stringify({
133                         type: "ajax_failure",
134                         method: method,
135                         route: route,
136                         data: data,
137                         id: id
138                     });
139                     let queue = JSON.parse(localStorage.getItem("offlineQueue")) || [];
140                     queue.push({ time: Date.now(), data: ajax_failure });
141                     try {
142                         localStorage.setItem("offlineQueue", JSON.stringify(queue));
143                     }
144                     catch (err) {
145                         console.log(err);
146                     }
147                 }
148             }
149         }
150     };
151     xhr.open(method, flask + route, true);
152     xhr.withCredentials = true;
153     xhr.setRequestHeader("Content-type", "application/json");
154     if (method === "POST") {
155         xhr.send(data);
156     } else {
157         xhr.send();
158     }
159 }
160
161
162 function login(id) {
163     ajax("POST", "login", id, "user");
164     id_user = id;
165     countingTimeLogout(120);
166 }
167
168 function logout() {
169     sendReset();
170     ajax("GET", "logout", "", "user");
171     id_user = undefined;
172     timeToLogout = undefined;
173     identifier_registration = false;
174 }
175
176 function countingTimeLogout(count_time)
177 {
178     clearTimeout(logoutTimer);
179     timeToLogout = count_time;
180     updateUI();
181     if (count_time == 0) {
182         logout();
183     } else {
184         logoutTimer = setTimeout(function() { countingTimeLogout(count_time - 1); }, 1000);
185     }
186 }
187
188 function renameUser() {
189     ajax("GET", "user/rename?name=" +  document.getElementById("username").value, "", "user");
190 }
191
192 function getFlavor(letter) {
193     switch (letter) {
194         case "E": return "espresso";
195         case "C": return "cappuccino";
196         case "B": return "latte macchiato";
197         case "D": return "espresso lungo";
198         default: return "";
199     }
200 }
201
202 function addCoffee(flavor, time = new Date()) {
203     var data = JSON.stringify({
204         time: time.toISOString(),
205         flavor: flavor
206     });
207     if (id_user) {
208         ajax("POST", "coffee/add", data, "user");
209         flavorChosen = flavor;
210         id_user = undefined;
211         countingTimeLogout(10); //mean 10 seconds
212     }
213 }
214
215 function addIdentifier_start() {
216     identifier_registration = true;
217     document.getElementById("addIdentifier").disabled = true;
218     document.getElementById("labelIdentifier").style.visibility = "visible";
219     document.getElementById("abortIdentifier").disabled = false;
220 }
221
222 function addIdentifier_finish() {
223     identifier_registration = false;
224     document.getElementById("addIdentifier").disabled = false;
225     document.getElementById("labelIdentifier").style.visibility = "hidden";
226     document.getElementById("abortIdentifier").disabled = true;
227 }
228
229 function disableIdentifier(id) {
230     ajax("POST", "user/identifier/disable", JSON.stringify({ id: id }), "user");
231 }
232
233 function renameIdentifier(i) {
234     var data = JSON.stringify({
235         id: document.getElementById("identifier_" + i).innerText,
236         name: document.getElementById("identifier_name_" + i).value
237     });
238
239     ajax("POST", "user/identifier/rename", data, "user");
240 }
241
242 function sendLog(json) {
243     ajax("POST", "log", json, "log");
244 }
245
246 function tellCoffeebot(what)
247 {
248     ajax("POST", "tellCoffeebot", JSON.stringify({text: what}), "log");
249 }