add admin UI for loading tracks
[lantea.git] / js / ui.js
CommitLineData
a7393a71
RK
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
23cd2dcc 4
41e2dba2 5// Get the best-available objects for indexedDB and requestAnimationFrame.
3d99a6fd 6window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
41e2dba2 7window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
993fd081 8
41e2dba2 9var mainDB;
16e4f664 10var gAppInitDone = false;
e1c3d337 11var firstRun = false;
7a549148 12var gUIHideCountdown = 0;
4b1d0915 13var gWaitCounter = 0;
026c4f46 14var gTrackUpdateInterval;
68afcd96 15var gAction, gActionLabel;
fd6126e2 16var authData = null, userData = null;
662078d1 17var gBackendURL = "https://backend.lantea.kairo.at/";
8f9306c5 18var gAuthClientID = "lantea";
7a549148 19
b47b4a65 20window.onload = function() {
68afcd96
RK
21 gAction = document.getElementById("action");
22 gActionLabel = document.getElementById("actionlabel");
23
b47b4a65
RK
24 var mSel = document.getElementById("mapSelector");
25 for (var mapStyle in gMapStyles) {
26 var opt = document.createElement("option");
27 opt.value = mapStyle;
28 opt.text = gMapStyles[mapStyle].name;
29 mSel.add(opt, null);
30 }
23cd2dcc 31
4018d25a 32 var areas = document.getElementsByClassName("autoFade");
7a549148
RK
33 for (var i = 0; i <= areas.length - 1; i++) {
34 areas[i].addEventListener("mouseup", uiEvHandler, false);
35 areas[i].addEventListener("mousemove", uiEvHandler, false);
36 areas[i].addEventListener("mousedown", uiEvHandler, false);
37 areas[i].addEventListener("mouseout", uiEvHandler, false);
38
39 areas[i].addEventListener("touchstart", uiEvHandler, false);
40 areas[i].addEventListener("touchmove", uiEvHandler, false);
41 areas[i].addEventListener("touchend", uiEvHandler, false);
42 areas[i].addEventListener("touchcancel", uiEvHandler, false);
43 areas[i].addEventListener("touchleave", uiEvHandler, false);
44 }
45
1222624d
RK
46 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
47
8e901dce 48 if (navigator.platform.length == "") {
b91b74a7
RK
49 // For Firefox OS, don't display the "save" button.
50 // Do this by setting the debugHide class for testing in debug mode.
51 document.getElementById("saveTrackButton").classList.add("debugHide");
c4d0569c
RK
52 }
53
8f9306c5
RK
54 // Set backend URL in a way that it works for testing on localhost as well as
55 // both the lantea.kairo.at and lantea-dev.kairo.at deployments.
56 if (window.location.host == "localhost") {
57 gBackendURL = window.location.protocol + '//' + window.location.host + "/lantea-backend/";
58 }
59 else {
60 gBackendURL = window.location.protocol + '//' + "backend." + window.location.host + "/";
61 }
62 // Make sure to use a different login client ID for the -dev setup.
63 if (/\-dev\./.test(window.location.host)) {
64 gAuthClientID += "-dev";
65 }
66
867ee0af
RK
67 document.getElementById("libCloseButton").onclick = hideLibrary;
68
8f9306c5
RK
69 // Set up the login area.
70 document.getElementById("loginbtn").onclick = startLogin;
71 document.getElementById("logoutbtn").onclick = doLogout;
fd6126e2
RK
72 // Put in a logged-out state by default.
73 // Opening the track drawer will update this correctly.
74 displayLogout();
43255174 75
582d50fc
RK
76 gAction.addEventListener("dbinit-done", initMap, false);
77 gAction.addEventListener("mapinit-done", postInit, false);
78 console.log("starting DB init...");
993fd081 79 initDB();
582d50fc 80}
4b1d0915 81
582d50fc
RK
82function postInit(aEvent) {
83 gAction.removeEventListener(aEvent.type, postInit, false);
84 console.log("init done, draw map.");
85 gMapPrefsLoaded = true;
16e4f664 86 gAppInitDone = true;
14acbcf7
RK
87 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
88 window.setTimeout(gMap.resizeAndDraw, 100);
582d50fc
RK
89 gActionLabel.textContent = "";
90 gAction.style.display = "none";
91 setTracking(document.getElementById("trackCheckbox"));
65946832 92 gPrefs.get("devicename", function(aValue) {
582d50fc 93 if (aValue) {
65946832 94 document.getElementById("uploadDevName").value = aValue;
4b1d0915 95 }
582d50fc 96 });
e1c3d337
RK
97 if (firstRun) {
98 showFirstRunDialog();
99 }
100 else {
101 gPrefs.get("lastInfoShown", function(aValue) {
102 if (!aValue || !parseInt(aValue) || parseInt(aValue) < 1) {
103 showInfoDialog();
104 }
105 });
106 }
107 gPrefs.set("lastInfoShown", 1);
b47b4a65
RK
108}
109
110window.onresize = function() {
ac6286bd 111 gMap.resizeAndDraw();
b47b4a65
RK
112}
113
8f9306c5 114function startLogin() {
662078d1
RK
115 var logerr = document.getElementById("loginerror");
116 logerr.classList.add("hidden");
117 logerr.title = "";
fd6126e2
RK
118 if (!authData || !authData["state"]) {
119 // We have no oAuth state, try to fetch it and call ourselves again if it worked.
120 prepareLoginButton(function() {
121 if (authData && authData["state"]) {
122 startLogin();
123 }
124 else if (!userData) {
125 // Only warn if we didn't actually end up being logged in.
126 console.log("No OAuth state and fetching fails, client or server may be offline.");
662078d1
RK
127 logerr.classList.remove("hidden");
128 logerr.title = "Client or server may be offline.";
fd6126e2
RK
129 }
130 });
131 return;
132 }
8f9306c5
RK
133 var authURL = authData["url"] + "authorize?response_type=code&client_id=" + gAuthClientID + "&scope=email" +
134 "&state=" + authData["state"] + "&redirect_uri=" + encodeURIComponent(getRedirectURI());
135 if (window.open(authURL, "KaiRoAuth", 'height=450,width=600')) {
136 console.log("Sign In window open.");
137 }
138 else {
139 console.log("Opening Sign In window failed.");
662078d1
RK
140 logerr.classList.remove("hidden");
141 logerr.title = "Opening Sign-In window failed.";
8f9306c5
RK
142 }
143}
144
145function getRedirectURI() {
67aadbe8 146 return window.location.protocol + '//' + window.location.host + window.location.pathname.replace("index.html", "") + "login.html";
8f9306c5
RK
147}
148
149function doLogout() {
150 fetchBackend("logout", "GET", null,
151 function(aResult, aStatus) {
152 if (aStatus < 400) {
153 prepareLoginButton();
154 }
155 else {
156 console.log("Backend issue trying to log out.");
157 }
158 },
159 {}
160 );
161}
162
163function prepareLoginButton(aCallback) {
164 fetchBackend("oauth_state", "GET", null,
165 function(aResult, aStatus) {
166 if (aStatus == 200) {
167 if (aResult["logged_in"]) {
168 userData = {
169 "email": aResult["email"],
170 "permissions": aResult["permissions"],
171 };
172 authData = null;
173 displayLogin();
174 }
175 else {
176 authData = {"state": aResult["state"], "url": aResult["url"]};
177 userData = null;
178 displayLogout();
179 }
180 }
181 else {
3c30699f 182 console.log("Backend error " + aStatus + " fetching OAuth state: " + aResult["message"]);
8f9306c5
RK
183 }
184 if (aCallback) { aCallback(); }
185 },
186 {}
187 );
188}
189
8f9306c5
RK
190function finishLogin(aCode, aState) {
191 if (aState == authData["state"]) {
192 fetchBackend("login?code=" + aCode + "&state=" + aState + "&redirect_uri=" + encodeURIComponent(getRedirectURI()), "GET", null,
193 function(aResult, aStatus) {
194 if (aStatus == 200) {
195 userData = {
196 "email": aResult["email"],
197 "permissions": aResult["permissions"],
198 };
199 displayLogin();
200 }
201 else {
202 console.log("Login error " + aStatus + ": " + aResult["message"]);
203 prepareLoginButton();
204 }
205 },
206 {}
207 );
208 }
209 else {
210 console.log("Login state did not match, not continuing with login.");
211 }
212}
213
214function displayLogin() {
215 document.getElementById("loginbtn").classList.add("hidden");
216 document.getElementById("logindesc").classList.add("hidden");
217 document.getElementById("username").classList.remove("hidden");
218 document.getElementById("username").textContent = userData.email;
219 document.getElementById("uploadTrackButton").disabled = false;
867ee0af 220 document.getElementById("libraryShowLine").classList.remove("hidden");
8f9306c5
RK
221 document.getElementById("logoutbtn").classList.remove("hidden");
222}
223
224function displayLogout() {
225 document.getElementById("logoutbtn").classList.add("hidden");
226 document.getElementById("username").classList.add("hidden");
227 document.getElementById("username").textContent = "";
228 document.getElementById("uploadTrackButton").disabled = true;
867ee0af 229 document.getElementById("libraryShowLine").classList.add("hidden");
8f9306c5
RK
230 document.getElementById("loginbtn").classList.remove("hidden");
231 document.getElementById("logindesc").classList.remove("hidden");
232}
233
582d50fc 234function initDB(aEvent) {
993fd081 235 // Open DB.
582d50fc
RK
236 if (aEvent)
237 gAction.removeEventListener(aEvent.type, initDB, false);
1222624d 238 var request = window.indexedDB.open("MainDB-lantea", 2);
993fd081
RK
239 request.onerror = function(event) {
240 // Errors can be handled here. Error codes explain in:
241 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
0713fd6a
RK
242 console.log("error opening mainDB: " + event.target.error);
243 showDBErrorDialog();
244 if (gDebug) {
245 console.log("error code: " + event.target.error.code +
246 " - name: " + event.target.error.name);
247 }
993fd081
RK
248 };
249 request.onsuccess = function(event) {
0713fd6a 250 mainDB = event.target.result;
582d50fc
RK
251 var throwEv = new CustomEvent("dbinit-done");
252 gAction.dispatchEvent(throwEv);
993fd081
RK
253 };
254 request.onupgradeneeded = function(event) {
255 mainDB = request.result;
a8634d37 256 var ver = mainDB.version || 0; // version is empty string for a new DB
915d4271
RK
257 if (gDebug)
258 console.log("mainDB has version " + ver + ", upgrade needed.");
259 if (!mainDB.objectStoreNames.contains("prefs")) {
a8634d37
RK
260 // Create a "prefs" objectStore.
261 var prefsStore = mainDB.createObjectStore("prefs");
e1c3d337 262 firstRun = true;
915d4271
RK
263 }
264 if (!mainDB.objectStoreNames.contains("track")) {
a8634d37
RK
265 // Create a "track" objectStore.
266 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
267 }
915d4271 268 if (!mainDB.objectStoreNames.contains("tilecache")) {
a8634d37
RK
269 // Create a "tilecache" objectStore.
270 var tilecacheStore = mainDB.createObjectStore("tilecache");
271 }
993fd081
RK
272 mainDB.onversionchange = function(event) {
273 mainDB.close();
274 mainDB = undefined;
275 initDB();
276 };
277 };
278}
279
7a549148
RK
280function showUI() {
281 if (gUIHideCountdown <= 0) {
4018d25a 282 var areas = document.getElementsByClassName('autoFade');
7a549148
RK
283 for (var i = 0; i <= areas.length - 1; i++) {
284 areas[i].classList.remove("hidden");
285 }
286 setTimeout(maybeHideUI, 1000);
287 }
288 gUIHideCountdown = 5;
289}
290
291function maybeHideUI() {
292 gUIHideCountdown--;
293 if (gUIHideCountdown <= 0) {
4018d25a 294 var areas = document.getElementsByClassName('autoFade');
7a549148
RK
295 for (var i = 0; i <= areas.length - 1; i++) {
296 areas[i].classList.add("hidden");
297 }
298 }
299 else {
300 setTimeout(maybeHideUI, 1000);
301 }
302}
303
026c4f46
RK
304function updateTrackInfo() {
305 document.getElementById("trackLengthNum").textContent = calcTrackLength().toFixed(1);
306 var duration = calcTrackDuration();
307 var durationM = Math.round(duration/60);
308 var durationH = Math.floor(durationM/60); durationM = durationM - durationH * 60;
309 document.getElementById("trackDurationH").style.display = durationH ? "inline" : "none";
310 document.getElementById("trackDurationHNum").textContent = durationH;
311 document.getElementById("trackDurationMNum").textContent = durationM;
312}
313
993fd081
RK
314function toggleTrackArea() {
315 var fs = document.getElementById("trackArea");
123b3142 316 if (fs.classList.contains("hidden")) {
4018d25a 317 prepareLoginButton();
123b3142 318 fs.classList.remove("hidden");
7a549148 319 showUI();
026c4f46 320 gTrackUpdateInterval = setInterval(updateTrackInfo, 1000);
993fd081
RK
321 }
322 else {
026c4f46 323 clearInterval(gTrackUpdateInterval);
123b3142 324 fs.classList.add("hidden");
993fd081
RK
325 }
326}
327
b47b4a65 328function toggleSettings() {
993fd081 329 var fs = document.getElementById("settingsArea");
123b3142
RK
330 if (fs.classList.contains("hidden")) {
331 fs.classList.remove("hidden");
7a549148 332 showUI();
b47b4a65
RK
333 }
334 else {
123b3142 335 fs.classList.add("hidden");
b47b4a65
RK
336 }
337}
99631a75 338
c5378747
RK
339function toggleFullscreen() {
340 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
341 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
342 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
343 if (document.cancelFullScreen) {
344 document.cancelFullScreen();
345 } else if (document.mozCancelFullScreen) {
346 document.mozCancelFullScreen();
347 } else if (document.webkitCancelFullScreen) {
348 document.webkitCancelFullScreen();
349 }
350 }
351 else {
352 var elem = document.getElementById("body");
353 if (elem.requestFullScreen) {
354 elem.requestFullScreen();
355 } else if (elem.mozRequestFullScreen) {
356 elem.mozRequestFullScreen();
357 } else if (elem.webkitRequestFullScreen) {
358 elem.webkitRequestFullScreen();
359 }
360 }
361}
362
43255174 363function showUploadDialog() {
6201b112 364 var dia = document.getElementById("trackDialogArea");
43255174
RK
365 var areas = dia.children;
366 for (var i = 0; i <= areas.length - 1; i++) {
367 areas[i].style.display = "none";
368 }
369 document.getElementById("uploadDialog").style.display = "block";
370 document.getElementById("uploadTrackButton").disabled = true;
371 dia.classList.remove("hidden");
372}
373
e1c3d337
RK
374function cancelTrackDialog() {
375 document.getElementById("trackDialogArea").classList.add("hidden");
376 document.getElementById("uploadTrackButton").disabled = false;
377}
378
ecde0af2
RK
379function showGLWarningDialog() {
380 var dia = document.getElementById("dialogArea");
381 var areas = dia.children;
382 for (var i = 0; i <= areas.length - 1; i++) {
383 areas[i].style.display = "none";
384 }
385 document.getElementById("noGLwarning").style.display = "block";
386 dia.classList.remove("hidden");
387}
388
0713fd6a
RK
389function showDBErrorDialog() {
390 var dia = document.getElementById("dialogArea");
391 var areas = dia.children;
392 for (var i = 0; i <= areas.length - 1; i++) {
393 areas[i].style.display = "none";
394 }
395 document.getElementById("DBError").style.display = "block";
396 dia.classList.remove("hidden");
397}
398
e1c3d337
RK
399function showFirstRunDialog() {
400 var dia = document.getElementById("dialogArea");
401 var areas = dia.children;
402 for (var i = 0; i <= areas.length - 1; i++) {
403 areas[i].style.display = "none";
404 }
405 document.getElementById("firstRunIntro").style.display = "block";
406 dia.classList.remove("hidden");
407}
408
409function closeDialog() {
410 document.getElementById("dialogArea").classList.add("hidden");
411}
412
413function showInfoDialog() {
414 var dia = document.getElementById("dialogArea");
415 var areas = dia.children;
416 for (var i = 0; i <= areas.length - 1; i++) {
417 areas[i].style.display = "none";
418 }
419 document.getElementById("infoDialog").style.display = "block";
420 dia.classList.remove("hidden");
43255174
RK
421}
422
7a549148
RK
423var uiEvHandler = {
424 handleEvent: function(aEvent) {
425 var touchEvent = aEvent.type.indexOf('touch') != -1;
426
427 switch (aEvent.type) {
428 case "mousedown":
429 case "touchstart":
430 case "mousemove":
431 case "touchmove":
432 case "mouseup":
433 case "touchend":
1222624d 434 case "keydown":
7a549148
RK
435 showUI();
436 break;
437 }
438 }
439};
440
8389557a
RK
441function setUploadField(aField) {
442 switch (aField.id) {
65946832
RK
443 case "uploadDevName":
444 gPrefs.set("devicename", aField.value);
8389557a
RK
445 break;
446 }
447}
448
99631a75
RK
449function makeISOString(aTimestamp) {
450 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
451 var tsDate = new Date(aTimestamp);
362a6833 452 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
99631a75 453 return tsDate.getUTCFullYear() + "-" +
362a6833 454 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
99631a75
RK
455 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
456 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
457 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
458 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
459}
460
8389557a
RK
461function convertTrack(aTargetFormat) {
462 var out = "";
463 switch (aTargetFormat) {
464 case "gpx":
465 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
466 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
467 if (gTrack.length) {
468 out += ' <trk>' + "\n";
993fd081 469 out += ' <trkseg>' + "\n";
8389557a
RK
470 for (var i = 0; i < gTrack.length; i++) {
471 if (gTrack[i].beginSegment && i > 0) {
472 out += ' </trkseg>' + "\n";
473 out += ' <trkseg>' + "\n";
474 }
475 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
476 gTrack[i].coords.longitude + '">' + "\n";
477 if (gTrack[i].coords.altitude) {
478 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
479 }
480 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
481 out += ' </trkpt>' + "\n";
482 }
483 out += ' </trkseg>' + "\n";
484 out += ' </trk>' + "\n";
993fd081 485 }
8389557a
RK
486 out += '</gpx>' + "\n";
487 break;
488 case "json":
489 out = JSON.stringify(gTrack);
490 break;
491 default:
492 break;
493 }
494 return out;
495}
496
497function saveTrack() {
498 if (gTrack.length) {
499 var outDataURI = "data:application/gpx+xml," +
500 encodeURIComponent(convertTrack("gpx"));
99631a75
RK
501 window.open(outDataURI, 'GPX Track');
502 }
503}
993fd081 504
4b12da3a
RK
505function saveTrackDump() {
506 if (gTrack.length) {
8389557a
RK
507 var outDataURI = "data:application/json," +
508 encodeURIComponent(convertTrack("json"));
4b12da3a
RK
509 window.open(outDataURI, 'JSON dump');
510 }
511}
512
8389557a 513function uploadTrack() {
6ddefbf9 514 // Hide all areas in the dialog.
6201b112 515 var dia = document.getElementById("trackDialogArea");
43255174
RK
516 var areas = dia.children;
517 for (var i = 0; i <= areas.length - 1; i++) {
518 areas[i].style.display = "none";
519 }
6ddefbf9
RK
520 // Reset all the fields in the status area.
521 document.getElementById("uploadStatusCloseButton").disabled = true;
522 document.getElementById("uploadInProgress").style.display = "block";
523 document.getElementById("uploadSuccess").style.display = "none";
d0c62ee0 524 document.getElementById("uploadFailed").style.display = "none";
6ddefbf9 525 document.getElementById("uploadError").style.display = "none";
d0c62ee0 526 document.getElementById("uploadErrorMsg").textContent = "";
6ddefbf9 527 // Now show the status area.
43255174
RK
528 document.getElementById("uploadStatus").style.display = "block";
529
6201b112 530 // Assemble field to post to the backend.
8389557a 531 var formData = new FormData();
6201b112 532 formData.append("jsondata", convertTrack("json"));
43255174 533 var desc = document.getElementById("uploadDesc").value;
6201b112 534 formData.append("comment",
43255174 535 desc.length ? desc : "Track recorded via Lantea Maps");
65946832
RK
536 formData.append("devicename",
537 document.getElementById("uploadDevName").value);
6201b112
RK
538 formData.append("public",
539 document.getElementById("uploadPublic").value);
540
541 fetchBackend("save_track", "POST", formData,
542 function(aResult, aStatusCode) {
543 if (aStatusCode >= 400) {
544 reportUploadStatus(false, aResult);
da6dad24 545 }
5e9f4a24 546 else if (aResult["id"]) {
da6dad24
RK
547 reportUploadStatus(true);
548 }
5e9f4a24
RK
549 else { // If no ID is returned, we assume a general error.
550 reportUploadStatus(false);
551 }
da6dad24
RK
552 }
553 );
8389557a
RK
554}
555
5e9f4a24 556function reportUploadStatus(aSuccess, aResponse) {
43255174
RK
557 document.getElementById("uploadStatusCloseButton").disabled = false;
558 document.getElementById("uploadInProgress").style.display = "none";
559 if (aSuccess) {
560 document.getElementById("uploadSuccess").style.display = "block";
561 }
b5291db1 562 else if (aResponse && aResponse["message"]) {
5e9f4a24
RK
563 document.getElementById("uploadErrorMsg").textContent = aResponse["message"];
564 if (aResponse["errortype"]) {
565 document.getElementById("uploadErrorMsg").textContent += " (" + aResponse["errortype"] + ")";
566 }
567 document.getElementById("uploadError").style.display = "block";
568 }
569 else if (aResponse) {
570 document.getElementById("uploadErrorMsg").textContent = aResponse;
43255174
RK
571 document.getElementById("uploadError").style.display = "block";
572 }
573 else {
574 document.getElementById("uploadFailed").style.display = "block";
575 }
8389557a
RK
576}
577
993fd081
RK
578var gPrefs = {
579 objStore: "prefs",
580
581 get: function(aKey, aCallback) {
582 if (!mainDB)
583 return;
584 var transaction = mainDB.transaction([this.objStore]);
585 var request = transaction.objectStore(this.objStore).get(aKey);
586 request.onsuccess = function(event) {
587 aCallback(request.result, event);
588 };
589 request.onerror = function(event) {
590 // Errors can be handled here.
591 aCallback(undefined, event);
592 };
593 },
594
595 set: function(aKey, aValue, aCallback) {
596 if (!mainDB)
597 return;
598 var success = false;
d4ccddb8 599 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081 600 var objStore = transaction.objectStore(this.objStore);
3610c22d 601 var request = objStore.put(aValue, aKey);
993fd081
RK
602 request.onsuccess = function(event) {
603 success = true;
604 if (aCallback)
605 aCallback(success, event);
606 };
607 request.onerror = function(event) {
608 // Errors can be handled here.
609 if (aCallback)
610 aCallback(success, event);
611 };
612 },
613
614 unset: function(aKey, aCallback) {
615 if (!mainDB)
616 return;
617 var success = false;
d4ccddb8 618 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
619 var request = transaction.objectStore(this.objStore).delete(aKey);
620 request.onsuccess = function(event) {
621 success = true;
622 if (aCallback)
623 aCallback(success, event);
624 };
625 request.onerror = function(event) {
626 // Errors can be handled here.
627 if (aCallback)
628 aCallback(success, event);
629 }
630 }
631};
632
633var gTrackStore = {
634 objStore: "track",
635
636 getList: function(aCallback) {
637 if (!mainDB)
638 return;
639 var transaction = mainDB.transaction([this.objStore]);
640 var objStore = transaction.objectStore(this.objStore);
641 if (objStore.getAll) { // currently Mozilla-specific
642 objStore.getAll().onsuccess = function(event) {
643 aCallback(event.target.result);
644 };
645 }
646 else { // Use cursor (standard method).
647 var tPoints = [];
648 objStore.openCursor().onsuccess = function(event) {
649 var cursor = event.target.result;
650 if (cursor) {
651 tPoints.push(cursor.value);
652 cursor.continue();
653 }
654 else {
655 aCallback(tPoints);
656 }
657 };
658 }
659 },
660
6ddefbf9
RK
661 getListStepped: function(aCallback) {
662 if (!mainDB)
663 return;
664 var transaction = mainDB.transaction([this.objStore]);
665 var objStore = transaction.objectStore(this.objStore);
666 // Use cursor in reverse direction (so we get the most recent position first)
667 objStore.openCursor(null, "prev").onsuccess = function(event) {
668 var cursor = event.target.result;
669 if (cursor) {
670 aCallback(cursor.value);
671 cursor.continue();
672 }
673 else {
674 aCallback(null);
675 }
676 };
677 },
678
993fd081
RK
679 push: function(aValue, aCallback) {
680 if (!mainDB)
681 return;
d4ccddb8 682 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
683 var objStore = transaction.objectStore(this.objStore);
684 var request = objStore.add(aValue);
685 request.onsuccess = function(event) {
686 if (aCallback)
687 aCallback(request.result, event);
688 };
689 request.onerror = function(event) {
690 // Errors can be handled here.
691 if (aCallback)
692 aCallback(false, event);
693 };
694 },
695
696 clear: function(aCallback) {
697 if (!mainDB)
698 return;
699 var success = false;
d4ccddb8 700 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
701 var request = transaction.objectStore(this.objStore).clear();
702 request.onsuccess = function(event) {
703 success = true;
704 if (aCallback)
705 aCallback(success, event);
706 };
707 request.onerror = function(event) {
708 // Errors can be handled here.
709 if (aCallback)
710 aCallback(success, event);
711 }
712 }
713};
8f9306c5
RK
714
715function fetchBackend(aEndpoint, aMethod, aSendData, aCallback, aCallbackForwards) {
716 var XHR = new XMLHttpRequest();
717 XHR.onreadystatechange = function() {
718 if (XHR.readyState == 4) {
719 // State says we are fully loaded.
720 var result = {};
721 if (XHR.getResponseHeader("Content-Type") == "application/json") {
722 // Got a JSON object, see if we have success.
65946832
RK
723 try {
724 result = JSON.parse(XHR.responseText);
725 }
726 catch (e) {
727 console.log(e);
728 result = {"error": e,
729 "message": XHR.responseText};
730 }
8f9306c5
RK
731 }
732 else {
733 result = XHR.responseText;
734 }
735 aCallback(result, XHR.status, aCallbackForwards);
736 }
737 };
738 XHR.open(aMethod, gBackendURL + aEndpoint, true);
87be1057 739 XHR.withCredentials = "true";
8f9306c5
RK
740 //XHR.setRequestHeader("Accept", "application/json");
741 try {
742 XHR.send(aSendData); // Send actual form data.
743 }
744 catch (e) {
745 aCallback(e, 500, aCallbackForwards);
746 }
747}