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/. */
5 // Get the best-available objects for indexedDB and requestAnimationFrame.
6 window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7 window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
10 var gAppInitDone = false;
11 var gUIHideCountdown = 0;
13 var gTrackUpdateInterval;
14 var gAction, gActionLabel;
15 var gBackendURL = "https://backend.lantea.kairo.at";
16 var gAuthClientID = "lantea";
18 window.onload = function() {
19 if (/\/login\.html/.test(window.location)) {
20 // If we are in the login window, call a function to complete the process and don't do anything else here.
21 completeLoginWindow();
24 gAction = document.getElementById("action");
25 gActionLabel = document.getElementById("actionlabel");
27 var mSel = document.getElementById("mapSelector");
28 for (var mapStyle in gMapStyles) {
29 var opt = document.createElement("option");
31 opt.text = gMapStyles[mapStyle].name;
35 var areas = document.getElementsByClassName("overlayArea");
36 for (var i = 0; i <= areas.length - 1; i++) {
37 areas[i].addEventListener("mouseup", uiEvHandler, false);
38 areas[i].addEventListener("mousemove", uiEvHandler, false);
39 areas[i].addEventListener("mousedown", uiEvHandler, false);
40 areas[i].addEventListener("mouseout", uiEvHandler, false);
42 areas[i].addEventListener("touchstart", uiEvHandler, false);
43 areas[i].addEventListener("touchmove", uiEvHandler, false);
44 areas[i].addEventListener("touchend", uiEvHandler, false);
45 areas[i].addEventListener("touchcancel", uiEvHandler, false);
46 areas[i].addEventListener("touchleave", uiEvHandler, false);
49 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
51 if (navigator.platform.length == "") {
52 // For Firefox OS, don't display the "save" button.
53 // Do this by setting the debugHide class for testing in debug mode.
54 document.getElementById("saveTrackButton").classList.add("debugHide");
57 // Set backend URL in a way that it works for testing on localhost as well as
58 // both the lantea.kairo.at and lantea-dev.kairo.at deployments.
59 if (window.location.host == "localhost") {
60 gBackendURL = window.location.protocol + '//' + window.location.host + "/lantea-backend/";
63 gBackendURL = window.location.protocol + '//' + "backend." + window.location.host + "/";
65 // Make sure to use a different login client ID for the -dev setup.
66 if (/\-dev\./.test(window.location.host)) {
67 gAuthClientID += "-dev";
70 // Set up the login area.
71 document.getElementById("loginbtn").onclick = startLogin;
72 document.getElementById("logoutbtn").onclick = doLogout;
73 prepareLoginButton(function() {
74 // Anything that needs the backend should only be triggered from in here.
75 // That makes sure that the first call the the backend is oauth_state and no other is running in parallel.
76 // If we call multiple backend methods at once and no session is open, we create multiple sessions, which calls for confusion later on.
78 // Call any UI preparation that needs the backend.
81 gAction.addEventListener("dbinit-done", initMap, false);
82 gAction.addEventListener("mapinit-done", postInit, false);
83 console.log("starting DB init...");
87 function postInit(aEvent) {
88 gAction.removeEventListener(aEvent.type, postInit, false);
89 console.log("init done, draw map.");
90 gMapPrefsLoaded = true;
92 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
93 window.setTimeout(gMap.resizeAndDraw, 100);
94 gActionLabel.textContent = "";
95 gAction.style.display = "none";
96 setTracking(document.getElementById("trackCheckbox"));
97 gPrefs.get("devicename", function(aValue) {
99 document.getElementById("uploadDevName").value = aValue;
104 window.onresize = function() {
105 gMap.resizeAndDraw();
108 function startLogin() {
109 var authURL = authData["url"] + "authorize?response_type=code&client_id=" + gAuthClientID + "&scope=email" +
110 "&state=" + authData["state"] + "&redirect_uri=" + encodeURIComponent(getRedirectURI());
111 if (window.open(authURL, "KaiRoAuth", 'height=450,width=600')) {
112 console.log("Sign In window open.");
115 console.log("Opening Sign In window failed.");
119 function getRedirectURI() {
120 return window.location.protocol + '//' + window.location.host + window.location.pathname.replace("index.html", "") + "login.html";
123 function doLogout() {
124 fetchBackend("logout", "GET", null,
125 function(aResult, aStatus) {
127 prepareLoginButton();
130 console.log("Backend issue trying to log out.");
137 function prepareLoginButton(aCallback) {
138 fetchBackend("oauth_state", "GET", null,
139 function(aResult, aStatus) {
140 if (aStatus == 200) {
141 if (aResult["logged_in"]) {
143 "email": aResult["email"],
144 "permissions": aResult["permissions"],
150 authData = {"state": aResult["state"], "url": aResult["url"]};
156 console.log("Backend error " + aStatus + " fetching OAuth state: " + aResult["message"]);
158 if (aCallback) { aCallback(); }
164 function completeLoginWindow() {
166 window.opener.finishLogin(getParameterByName("code"), getParameterByName("state"));
170 document.getElementById("logininfo").textContent = "You have called this document outside of the login flow, which is not supported.";
174 function finishLogin(aCode, aState) {
175 if (aState == authData["state"]) {
176 fetchBackend("login?code=" + aCode + "&state=" + aState + "&redirect_uri=" + encodeURIComponent(getRedirectURI()), "GET", null,
177 function(aResult, aStatus) {
178 if (aStatus == 200) {
180 "email": aResult["email"],
181 "permissions": aResult["permissions"],
186 console.log("Login error " + aStatus + ": " + aResult["message"]);
187 prepareLoginButton();
194 console.log("Login state did not match, not continuing with login.");
198 function displayLogin() {
199 document.getElementById("loginbtn").classList.add("hidden");
200 document.getElementById("logindesc").classList.add("hidden");
201 document.getElementById("username").classList.remove("hidden");
202 document.getElementById("username").textContent = userData.email;
203 document.getElementById("uploadTrackButton").disabled = false;
204 document.getElementById("logoutbtn").classList.remove("hidden");
207 function displayLogout() {
208 document.getElementById("logoutbtn").classList.add("hidden");
209 document.getElementById("username").classList.add("hidden");
210 document.getElementById("username").textContent = "";
211 document.getElementById("uploadTrackButton").disabled = true;
212 document.getElementById("loginbtn").classList.remove("hidden");
213 document.getElementById("logindesc").classList.remove("hidden");
216 function initDB(aEvent) {
219 gAction.removeEventListener(aEvent.type, initDB, false);
220 var request = window.indexedDB.open("MainDB-lantea", 2);
221 request.onerror = function(event) {
222 // Errors can be handled here. Error codes explain in:
223 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
225 console.log("error opening mainDB: " + event.target.errorCode);
227 request.onsuccess = function(event) {
228 mainDB = request.result;
229 var throwEv = new CustomEvent("dbinit-done");
230 gAction.dispatchEvent(throwEv);
232 request.onupgradeneeded = function(event) {
233 mainDB = request.result;
234 var ver = mainDB.version || 0; // version is empty string for a new DB
236 console.log("mainDB has version " + ver + ", upgrade needed.");
237 if (!mainDB.objectStoreNames.contains("prefs")) {
238 // Create a "prefs" objectStore.
239 var prefsStore = mainDB.createObjectStore("prefs");
241 if (!mainDB.objectStoreNames.contains("track")) {
242 // Create a "track" objectStore.
243 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
245 if (!mainDB.objectStoreNames.contains("tilecache")) {
246 // Create a "tilecache" objectStore.
247 var tilecacheStore = mainDB.createObjectStore("tilecache");
249 mainDB.onversionchange = function(event) {
258 if (gUIHideCountdown <= 0) {
259 var areas = document.getElementsByClassName('overlayArea');
260 for (var i = 0; i <= areas.length - 1; i++) {
261 areas[i].classList.remove("hidden");
263 setTimeout(maybeHideUI, 1000);
265 gUIHideCountdown = 5;
268 function maybeHideUI() {
270 if (gUIHideCountdown <= 0) {
271 var areas = document.getElementsByClassName('overlayArea');
272 for (var i = 0; i <= areas.length - 1; i++) {
273 areas[i].classList.add("hidden");
277 setTimeout(maybeHideUI, 1000);
281 function updateTrackInfo() {
282 document.getElementById("trackLengthNum").textContent = calcTrackLength().toFixed(1);
283 var duration = calcTrackDuration();
284 var durationM = Math.round(duration/60);
285 var durationH = Math.floor(durationM/60); durationM = durationM - durationH * 60;
286 document.getElementById("trackDurationH").style.display = durationH ? "inline" : "none";
287 document.getElementById("trackDurationHNum").textContent = durationH;
288 document.getElementById("trackDurationMNum").textContent = durationM;
291 function toggleTrackArea() {
292 var fs = document.getElementById("trackArea");
293 if (fs.classList.contains("hidden")) {
294 fs.classList.remove("hidden");
296 gTrackUpdateInterval = setInterval(updateTrackInfo, 1000);
299 clearInterval(gTrackUpdateInterval);
300 fs.classList.add("hidden");
304 function toggleSettings() {
305 var fs = document.getElementById("settingsArea");
306 if (fs.classList.contains("hidden")) {
307 fs.classList.remove("hidden");
311 fs.classList.add("hidden");
315 function toggleFullscreen() {
316 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
317 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
318 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
319 if (document.cancelFullScreen) {
320 document.cancelFullScreen();
321 } else if (document.mozCancelFullScreen) {
322 document.mozCancelFullScreen();
323 } else if (document.webkitCancelFullScreen) {
324 document.webkitCancelFullScreen();
328 var elem = document.getElementById("body");
329 if (elem.requestFullScreen) {
330 elem.requestFullScreen();
331 } else if (elem.mozRequestFullScreen) {
332 elem.mozRequestFullScreen();
333 } else if (elem.webkitRequestFullScreen) {
334 elem.webkitRequestFullScreen();
339 function showUploadDialog() {
340 var dia = document.getElementById("trackDialogArea");
341 var areas = dia.children;
342 for (var i = 0; i <= areas.length - 1; i++) {
343 areas[i].style.display = "none";
345 document.getElementById("uploadDialog").style.display = "block";
346 document.getElementById("uploadTrackButton").disabled = true;
347 dia.classList.remove("hidden");
350 function showGLWarningDialog() {
351 var dia = document.getElementById("dialogArea");
352 var areas = dia.children;
353 for (var i = 0; i <= areas.length - 1; i++) {
354 areas[i].style.display = "none";
356 document.getElementById("noGLwarning").style.display = "block";
357 dia.classList.remove("hidden");
360 function cancelTrackDialog() {
361 document.getElementById("trackDialogArea").classList.add("hidden");
362 document.getElementById("uploadTrackButton").disabled = false;
366 handleEvent: function(aEvent) {
367 var touchEvent = aEvent.type.indexOf('touch') != -1;
369 switch (aEvent.type) {
383 function setUploadField(aField) {
385 case "uploadDevName":
386 gPrefs.set("devicename", aField.value);
391 function makeISOString(aTimestamp) {
392 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
393 var tsDate = new Date(aTimestamp);
394 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
395 return tsDate.getUTCFullYear() + "-" +
396 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
397 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
398 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
399 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
400 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
403 function convertTrack(aTargetFormat) {
405 switch (aTargetFormat) {
407 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
408 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
410 out += ' <trk>' + "\n";
411 out += ' <trkseg>' + "\n";
412 for (var i = 0; i < gTrack.length; i++) {
413 if (gTrack[i].beginSegment && i > 0) {
414 out += ' </trkseg>' + "\n";
415 out += ' <trkseg>' + "\n";
417 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
418 gTrack[i].coords.longitude + '">' + "\n";
419 if (gTrack[i].coords.altitude) {
420 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
422 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
423 out += ' </trkpt>' + "\n";
425 out += ' </trkseg>' + "\n";
426 out += ' </trk>' + "\n";
428 out += '</gpx>' + "\n";
431 out = JSON.stringify(gTrack);
439 function saveTrack() {
441 var outDataURI = "data:application/gpx+xml," +
442 encodeURIComponent(convertTrack("gpx"));
443 window.open(outDataURI, 'GPX Track');
447 function saveTrackDump() {
449 var outDataURI = "data:application/json," +
450 encodeURIComponent(convertTrack("json"));
451 window.open(outDataURI, 'JSON dump');
455 function uploadTrack() {
456 // Hide all areas in the dialog.
457 var dia = document.getElementById("trackDialogArea");
458 var areas = dia.children;
459 for (var i = 0; i <= areas.length - 1; i++) {
460 areas[i].style.display = "none";
462 // Reset all the fields in the status area.
463 document.getElementById("uploadStatusCloseButton").disabled = true;
464 document.getElementById("uploadInProgress").style.display = "block";
465 document.getElementById("uploadSuccess").style.display = "none";
466 document.getElementById("uploadFailed").style.display = "none";
467 document.getElementById("uploadError").style.display = "none";
468 document.getElementById("uploadErrorMsg").textContent = "";
469 // Now show the status area.
470 document.getElementById("uploadStatus").style.display = "block";
472 // Assemble field to post to the backend.
473 var formData = new FormData();
474 formData.append("jsondata", convertTrack("json"));
475 var desc = document.getElementById("uploadDesc").value;
476 formData.append("comment",
477 desc.length ? desc : "Track recorded via Lantea Maps");
478 formData.append("devicename",
479 document.getElementById("uploadDevName").value);
480 formData.append("public",
481 document.getElementById("uploadPublic").value);
483 fetchBackend("save_track", "POST", formData,
484 function(aResult, aStatusCode) {
485 if (aStatusCode >= 400) {
486 reportUploadStatus(false, aResult);
489 reportUploadStatus(true);
495 function reportUploadStatus(aSuccess, aMessage) {
496 document.getElementById("uploadStatusCloseButton").disabled = false;
497 document.getElementById("uploadInProgress").style.display = "none";
499 document.getElementById("uploadSuccess").style.display = "block";
502 document.getElementById("uploadErrorMsg").textContent = aMessage;
503 document.getElementById("uploadError").style.display = "block";
506 document.getElementById("uploadFailed").style.display = "block";
513 get: function(aKey, aCallback) {
516 var transaction = mainDB.transaction([this.objStore]);
517 var request = transaction.objectStore(this.objStore).get(aKey);
518 request.onsuccess = function(event) {
519 aCallback(request.result, event);
521 request.onerror = function(event) {
522 // Errors can be handled here.
523 aCallback(undefined, event);
527 set: function(aKey, aValue, aCallback) {
531 var transaction = mainDB.transaction([this.objStore], "readwrite");
532 var objStore = transaction.objectStore(this.objStore);
533 var request = objStore.put(aValue, aKey);
534 request.onsuccess = function(event) {
537 aCallback(success, event);
539 request.onerror = function(event) {
540 // Errors can be handled here.
542 aCallback(success, event);
546 unset: function(aKey, aCallback) {
550 var transaction = mainDB.transaction([this.objStore], "readwrite");
551 var request = transaction.objectStore(this.objStore).delete(aKey);
552 request.onsuccess = function(event) {
555 aCallback(success, event);
557 request.onerror = function(event) {
558 // Errors can be handled here.
560 aCallback(success, event);
568 getList: function(aCallback) {
571 var transaction = mainDB.transaction([this.objStore]);
572 var objStore = transaction.objectStore(this.objStore);
573 if (objStore.getAll) { // currently Mozilla-specific
574 objStore.getAll().onsuccess = function(event) {
575 aCallback(event.target.result);
578 else { // Use cursor (standard method).
580 objStore.openCursor().onsuccess = function(event) {
581 var cursor = event.target.result;
583 tPoints.push(cursor.value);
593 getListStepped: function(aCallback) {
596 var transaction = mainDB.transaction([this.objStore]);
597 var objStore = transaction.objectStore(this.objStore);
598 // Use cursor in reverse direction (so we get the most recent position first)
599 objStore.openCursor(null, "prev").onsuccess = function(event) {
600 var cursor = event.target.result;
602 aCallback(cursor.value);
611 push: function(aValue, aCallback) {
614 var transaction = mainDB.transaction([this.objStore], "readwrite");
615 var objStore = transaction.objectStore(this.objStore);
616 var request = objStore.add(aValue);
617 request.onsuccess = function(event) {
619 aCallback(request.result, event);
621 request.onerror = function(event) {
622 // Errors can be handled here.
624 aCallback(false, event);
628 clear: function(aCallback) {
632 var transaction = mainDB.transaction([this.objStore], "readwrite");
633 var request = transaction.objectStore(this.objStore).clear();
634 request.onsuccess = function(event) {
637 aCallback(success, event);
639 request.onerror = function(event) {
640 // Errors can be handled here.
642 aCallback(success, event);
647 function fetchBackend(aEndpoint, aMethod, aSendData, aCallback, aCallbackForwards) {
648 var XHR = new XMLHttpRequest();
649 XHR.onreadystatechange = function() {
650 if (XHR.readyState == 4) {
651 // State says we are fully loaded.
653 if (XHR.getResponseHeader("Content-Type") == "application/json") {
654 // Got a JSON object, see if we have success.
656 result = JSON.parse(XHR.responseText);
660 result = {"error": e,
661 "message": XHR.responseText};
665 result = XHR.responseText;
667 aCallback(result, XHR.status, aCallbackForwards);
670 XHR.open(aMethod, gBackendURL + aEndpoint, true);
671 XHR.withCredentials = "true";
672 //XHR.setRequestHeader("Accept", "application/json");
674 XHR.send(aSendData); // Send actual form data.
677 aCallback(e, 500, aCallbackForwards);
681 function getParameterByName(aName) {
682 // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
683 name = aName.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
684 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
685 results = regex.exec(location.search);
686 return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));