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;
12 var gUIHideCountdown = 0;
14 var gTrackUpdateInterval;
15 var gAction, gActionLabel;
16 var gBackendURL = "https://backend.lantea.kairo.at";
17 var gAuthClientID = "lantea";
19 window.onload = function() {
20 gAction = document.getElementById("action");
21 gActionLabel = document.getElementById("actionlabel");
23 var mSel = document.getElementById("mapSelector");
24 for (var mapStyle in gMapStyles) {
25 var opt = document.createElement("option");
27 opt.text = gMapStyles[mapStyle].name;
31 var areas = document.getElementsByClassName("autoFade");
32 for (var i = 0; i <= areas.length - 1; i++) {
33 areas[i].addEventListener("mouseup", uiEvHandler, false);
34 areas[i].addEventListener("mousemove", uiEvHandler, false);
35 areas[i].addEventListener("mousedown", uiEvHandler, false);
36 areas[i].addEventListener("mouseout", uiEvHandler, false);
38 areas[i].addEventListener("touchstart", uiEvHandler, false);
39 areas[i].addEventListener("touchmove", uiEvHandler, false);
40 areas[i].addEventListener("touchend", uiEvHandler, false);
41 areas[i].addEventListener("touchcancel", uiEvHandler, false);
42 areas[i].addEventListener("touchleave", uiEvHandler, false);
45 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
47 if (navigator.platform.length == "") {
48 // For Firefox OS, don't display the "save" button.
49 // Do this by setting the debugHide class for testing in debug mode.
50 document.getElementById("saveTrackButton").classList.add("debugHide");
53 // Set backend URL in a way that it works for testing on localhost as well as
54 // both the lantea.kairo.at and lantea-dev.kairo.at deployments.
55 if (window.location.host == "localhost") {
56 gBackendURL = window.location.protocol + '//' + window.location.host + "/lantea-backend/";
59 gBackendURL = window.location.protocol + '//' + "backend." + window.location.host + "/";
61 // Make sure to use a different login client ID for the -dev setup.
62 if (/\-dev\./.test(window.location.host)) {
63 gAuthClientID += "-dev";
66 document.getElementById("libCloseButton").onclick = hideLibrary;
68 // Set up the login area.
69 document.getElementById("loginbtn").onclick = startLogin;
70 document.getElementById("logoutbtn").onclick = doLogout;
71 prepareLoginButton(function() {
72 // Anything that needs the backend should only be triggered from in here.
73 // That makes sure that the first call the the backend is oauth_state and no other is running in parallel.
74 // If we call multiple backend methods at once and no session is open, we create multiple sessions, which calls for confusion later on.
76 // Call any UI preparation that needs the backend.
79 gAction.addEventListener("dbinit-done", initMap, false);
80 gAction.addEventListener("mapinit-done", postInit, false);
81 console.log("starting DB init...");
85 function postInit(aEvent) {
86 gAction.removeEventListener(aEvent.type, postInit, false);
87 console.log("init done, draw map.");
88 gMapPrefsLoaded = true;
90 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
91 window.setTimeout(gMap.resizeAndDraw, 100);
92 gActionLabel.textContent = "";
93 gAction.style.display = "none";
94 setTracking(document.getElementById("trackCheckbox"));
95 gPrefs.get("devicename", function(aValue) {
97 document.getElementById("uploadDevName").value = aValue;
101 showFirstRunDialog();
104 gPrefs.get("lastInfoShown", function(aValue) {
105 if (!aValue || !parseInt(aValue) || parseInt(aValue) < 1) {
110 gPrefs.set("lastInfoShown", 1);
113 window.onresize = function() {
114 gMap.resizeAndDraw();
117 function startLogin() {
118 var authURL = authData["url"] + "authorize?response_type=code&client_id=" + gAuthClientID + "&scope=email" +
119 "&state=" + authData["state"] + "&redirect_uri=" + encodeURIComponent(getRedirectURI());
120 if (window.open(authURL, "KaiRoAuth", 'height=450,width=600')) {
121 console.log("Sign In window open.");
124 console.log("Opening Sign In window failed.");
128 function getRedirectURI() {
129 return window.location.protocol + '//' + window.location.host + window.location.pathname.replace("index.html", "") + "login.html";
132 function doLogout() {
133 fetchBackend("logout", "GET", null,
134 function(aResult, aStatus) {
136 prepareLoginButton();
139 console.log("Backend issue trying to log out.");
146 function prepareLoginButton(aCallback) {
147 fetchBackend("oauth_state", "GET", null,
148 function(aResult, aStatus) {
149 if (aStatus == 200) {
150 if (aResult["logged_in"]) {
152 "email": aResult["email"],
153 "permissions": aResult["permissions"],
159 authData = {"state": aResult["state"], "url": aResult["url"]};
165 console.log("Backend error " + aStatus + " fetching OAuth state: " + aResult["message"]);
167 if (aCallback) { aCallback(); }
173 function finishLogin(aCode, aState) {
174 if (aState == authData["state"]) {
175 fetchBackend("login?code=" + aCode + "&state=" + aState + "&redirect_uri=" + encodeURIComponent(getRedirectURI()), "GET", null,
176 function(aResult, aStatus) {
177 if (aStatus == 200) {
179 "email": aResult["email"],
180 "permissions": aResult["permissions"],
185 console.log("Login error " + aStatus + ": " + aResult["message"]);
186 prepareLoginButton();
193 console.log("Login state did not match, not continuing with login.");
197 function displayLogin() {
198 document.getElementById("loginbtn").classList.add("hidden");
199 document.getElementById("logindesc").classList.add("hidden");
200 document.getElementById("username").classList.remove("hidden");
201 document.getElementById("username").textContent = userData.email;
202 document.getElementById("uploadTrackButton").disabled = false;
203 document.getElementById("libraryShowLine").classList.remove("hidden");
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("libraryShowLine").classList.add("hidden");
213 document.getElementById("loginbtn").classList.remove("hidden");
214 document.getElementById("logindesc").classList.remove("hidden");
217 function initDB(aEvent) {
220 gAction.removeEventListener(aEvent.type, initDB, false);
221 var request = window.indexedDB.open("MainDB-lantea", 2);
222 request.onerror = function(event) {
223 // Errors can be handled here. Error codes explain in:
224 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
226 console.log("error opening mainDB: " + event.target.errorCode);
228 request.onsuccess = function(event) {
229 mainDB = request.result;
230 var throwEv = new CustomEvent("dbinit-done");
231 gAction.dispatchEvent(throwEv);
233 request.onupgradeneeded = function(event) {
234 mainDB = request.result;
235 var ver = mainDB.version || 0; // version is empty string for a new DB
237 console.log("mainDB has version " + ver + ", upgrade needed.");
238 if (!mainDB.objectStoreNames.contains("prefs")) {
239 // Create a "prefs" objectStore.
240 var prefsStore = mainDB.createObjectStore("prefs");
243 if (!mainDB.objectStoreNames.contains("track")) {
244 // Create a "track" objectStore.
245 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
247 if (!mainDB.objectStoreNames.contains("tilecache")) {
248 // Create a "tilecache" objectStore.
249 var tilecacheStore = mainDB.createObjectStore("tilecache");
251 mainDB.onversionchange = function(event) {
260 if (gUIHideCountdown <= 0) {
261 var areas = document.getElementsByClassName('autoFade');
262 for (var i = 0; i <= areas.length - 1; i++) {
263 areas[i].classList.remove("hidden");
265 setTimeout(maybeHideUI, 1000);
267 gUIHideCountdown = 5;
270 function maybeHideUI() {
272 if (gUIHideCountdown <= 0) {
273 var areas = document.getElementsByClassName('autoFade');
274 for (var i = 0; i <= areas.length - 1; i++) {
275 areas[i].classList.add("hidden");
279 setTimeout(maybeHideUI, 1000);
283 function updateTrackInfo() {
284 document.getElementById("trackLengthNum").textContent = calcTrackLength().toFixed(1);
285 var duration = calcTrackDuration();
286 var durationM = Math.round(duration/60);
287 var durationH = Math.floor(durationM/60); durationM = durationM - durationH * 60;
288 document.getElementById("trackDurationH").style.display = durationH ? "inline" : "none";
289 document.getElementById("trackDurationHNum").textContent = durationH;
290 document.getElementById("trackDurationMNum").textContent = durationM;
293 function toggleTrackArea() {
294 var fs = document.getElementById("trackArea");
295 if (fs.classList.contains("hidden")) {
296 prepareLoginButton();
297 fs.classList.remove("hidden");
299 gTrackUpdateInterval = setInterval(updateTrackInfo, 1000);
302 clearInterval(gTrackUpdateInterval);
303 fs.classList.add("hidden");
307 function toggleSettings() {
308 var fs = document.getElementById("settingsArea");
309 if (fs.classList.contains("hidden")) {
310 fs.classList.remove("hidden");
314 fs.classList.add("hidden");
318 function toggleFullscreen() {
319 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
320 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
321 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
322 if (document.cancelFullScreen) {
323 document.cancelFullScreen();
324 } else if (document.mozCancelFullScreen) {
325 document.mozCancelFullScreen();
326 } else if (document.webkitCancelFullScreen) {
327 document.webkitCancelFullScreen();
331 var elem = document.getElementById("body");
332 if (elem.requestFullScreen) {
333 elem.requestFullScreen();
334 } else if (elem.mozRequestFullScreen) {
335 elem.mozRequestFullScreen();
336 } else if (elem.webkitRequestFullScreen) {
337 elem.webkitRequestFullScreen();
342 function showUploadDialog() {
343 var dia = document.getElementById("trackDialogArea");
344 var areas = dia.children;
345 for (var i = 0; i <= areas.length - 1; i++) {
346 areas[i].style.display = "none";
348 document.getElementById("uploadDialog").style.display = "block";
349 document.getElementById("uploadTrackButton").disabled = true;
350 dia.classList.remove("hidden");
353 function cancelTrackDialog() {
354 document.getElementById("trackDialogArea").classList.add("hidden");
355 document.getElementById("uploadTrackButton").disabled = false;
358 function showGLWarningDialog() {
359 var dia = document.getElementById("dialogArea");
360 var areas = dia.children;
361 for (var i = 0; i <= areas.length - 1; i++) {
362 areas[i].style.display = "none";
364 document.getElementById("noGLwarning").style.display = "block";
365 dia.classList.remove("hidden");
368 function showFirstRunDialog() {
369 var dia = document.getElementById("dialogArea");
370 var areas = dia.children;
371 for (var i = 0; i <= areas.length - 1; i++) {
372 areas[i].style.display = "none";
374 document.getElementById("firstRunIntro").style.display = "block";
375 dia.classList.remove("hidden");
378 function closeDialog() {
379 document.getElementById("dialogArea").classList.add("hidden");
382 function showInfoDialog() {
383 var dia = document.getElementById("dialogArea");
384 var areas = dia.children;
385 for (var i = 0; i <= areas.length - 1; i++) {
386 areas[i].style.display = "none";
388 document.getElementById("infoDialog").style.display = "block";
389 dia.classList.remove("hidden");
393 handleEvent: function(aEvent) {
394 var touchEvent = aEvent.type.indexOf('touch') != -1;
396 switch (aEvent.type) {
410 function setUploadField(aField) {
412 case "uploadDevName":
413 gPrefs.set("devicename", aField.value);
418 function makeISOString(aTimestamp) {
419 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
420 var tsDate = new Date(aTimestamp);
421 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
422 return tsDate.getUTCFullYear() + "-" +
423 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
424 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
425 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
426 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
427 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
430 function convertTrack(aTargetFormat) {
432 switch (aTargetFormat) {
434 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
435 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
437 out += ' <trk>' + "\n";
438 out += ' <trkseg>' + "\n";
439 for (var i = 0; i < gTrack.length; i++) {
440 if (gTrack[i].beginSegment && i > 0) {
441 out += ' </trkseg>' + "\n";
442 out += ' <trkseg>' + "\n";
444 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
445 gTrack[i].coords.longitude + '">' + "\n";
446 if (gTrack[i].coords.altitude) {
447 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
449 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
450 out += ' </trkpt>' + "\n";
452 out += ' </trkseg>' + "\n";
453 out += ' </trk>' + "\n";
455 out += '</gpx>' + "\n";
458 out = JSON.stringify(gTrack);
466 function saveTrack() {
468 var outDataURI = "data:application/gpx+xml," +
469 encodeURIComponent(convertTrack("gpx"));
470 window.open(outDataURI, 'GPX Track');
474 function saveTrackDump() {
476 var outDataURI = "data:application/json," +
477 encodeURIComponent(convertTrack("json"));
478 window.open(outDataURI, 'JSON dump');
482 function uploadTrack() {
483 // Hide all areas in the dialog.
484 var dia = document.getElementById("trackDialogArea");
485 var areas = dia.children;
486 for (var i = 0; i <= areas.length - 1; i++) {
487 areas[i].style.display = "none";
489 // Reset all the fields in the status area.
490 document.getElementById("uploadStatusCloseButton").disabled = true;
491 document.getElementById("uploadInProgress").style.display = "block";
492 document.getElementById("uploadSuccess").style.display = "none";
493 document.getElementById("uploadFailed").style.display = "none";
494 document.getElementById("uploadError").style.display = "none";
495 document.getElementById("uploadErrorMsg").textContent = "";
496 // Now show the status area.
497 document.getElementById("uploadStatus").style.display = "block";
499 // Assemble field to post to the backend.
500 var formData = new FormData();
501 formData.append("jsondata", convertTrack("json"));
502 var desc = document.getElementById("uploadDesc").value;
503 formData.append("comment",
504 desc.length ? desc : "Track recorded via Lantea Maps");
505 formData.append("devicename",
506 document.getElementById("uploadDevName").value);
507 formData.append("public",
508 document.getElementById("uploadPublic").value);
510 fetchBackend("save_track", "POST", formData,
511 function(aResult, aStatusCode) {
512 if (aStatusCode >= 400) {
513 reportUploadStatus(false, aResult);
515 else if (aResult["id"]) {
516 reportUploadStatus(true);
518 else { // If no ID is returned, we assume a general error.
519 reportUploadStatus(false);
525 function reportUploadStatus(aSuccess, aResponse) {
526 document.getElementById("uploadStatusCloseButton").disabled = false;
527 document.getElementById("uploadInProgress").style.display = "none";
529 document.getElementById("uploadSuccess").style.display = "block";
531 else if (aResponse && aResponse["message"]) {
532 document.getElementById("uploadErrorMsg").textContent = aResponse["message"];
533 if (aResponse["errortype"]) {
534 document.getElementById("uploadErrorMsg").textContent += " (" + aResponse["errortype"] + ")";
536 document.getElementById("uploadError").style.display = "block";
538 else if (aResponse) {
539 document.getElementById("uploadErrorMsg").textContent = aResponse;
540 document.getElementById("uploadError").style.display = "block";
543 document.getElementById("uploadFailed").style.display = "block";
550 get: function(aKey, aCallback) {
553 var transaction = mainDB.transaction([this.objStore]);
554 var request = transaction.objectStore(this.objStore).get(aKey);
555 request.onsuccess = function(event) {
556 aCallback(request.result, event);
558 request.onerror = function(event) {
559 // Errors can be handled here.
560 aCallback(undefined, event);
564 set: function(aKey, aValue, aCallback) {
568 var transaction = mainDB.transaction([this.objStore], "readwrite");
569 var objStore = transaction.objectStore(this.objStore);
570 var request = objStore.put(aValue, aKey);
571 request.onsuccess = function(event) {
574 aCallback(success, event);
576 request.onerror = function(event) {
577 // Errors can be handled here.
579 aCallback(success, event);
583 unset: function(aKey, aCallback) {
587 var transaction = mainDB.transaction([this.objStore], "readwrite");
588 var request = transaction.objectStore(this.objStore).delete(aKey);
589 request.onsuccess = function(event) {
592 aCallback(success, event);
594 request.onerror = function(event) {
595 // Errors can be handled here.
597 aCallback(success, event);
605 getList: function(aCallback) {
608 var transaction = mainDB.transaction([this.objStore]);
609 var objStore = transaction.objectStore(this.objStore);
610 if (objStore.getAll) { // currently Mozilla-specific
611 objStore.getAll().onsuccess = function(event) {
612 aCallback(event.target.result);
615 else { // Use cursor (standard method).
617 objStore.openCursor().onsuccess = function(event) {
618 var cursor = event.target.result;
620 tPoints.push(cursor.value);
630 getListStepped: function(aCallback) {
633 var transaction = mainDB.transaction([this.objStore]);
634 var objStore = transaction.objectStore(this.objStore);
635 // Use cursor in reverse direction (so we get the most recent position first)
636 objStore.openCursor(null, "prev").onsuccess = function(event) {
637 var cursor = event.target.result;
639 aCallback(cursor.value);
648 push: function(aValue, aCallback) {
651 var transaction = mainDB.transaction([this.objStore], "readwrite");
652 var objStore = transaction.objectStore(this.objStore);
653 var request = objStore.add(aValue);
654 request.onsuccess = function(event) {
656 aCallback(request.result, event);
658 request.onerror = function(event) {
659 // Errors can be handled here.
661 aCallback(false, event);
665 clear: function(aCallback) {
669 var transaction = mainDB.transaction([this.objStore], "readwrite");
670 var request = transaction.objectStore(this.objStore).clear();
671 request.onsuccess = function(event) {
674 aCallback(success, event);
676 request.onerror = function(event) {
677 // Errors can be handled here.
679 aCallback(success, event);
684 function fetchBackend(aEndpoint, aMethod, aSendData, aCallback, aCallbackForwards) {
685 var XHR = new XMLHttpRequest();
686 XHR.onreadystatechange = function() {
687 if (XHR.readyState == 4) {
688 // State says we are fully loaded.
690 if (XHR.getResponseHeader("Content-Type") == "application/json") {
691 // Got a JSON object, see if we have success.
693 result = JSON.parse(XHR.responseText);
697 result = {"error": e,
698 "message": XHR.responseText};
702 result = XHR.responseText;
704 aCallback(result, XHR.status, aCallbackForwards);
707 XHR.open(aMethod, gBackendURL + aEndpoint, true);
708 XHR.withCredentials = "true";
709 //XHR.setRequestHeader("Accept", "application/json");
711 XHR.send(aSendData); // Send actual form data.
714 aCallback(e, 500, aCallbackForwards);