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";
17 var gOSMAPIURL = "https://api.openstreetmap.org/";
19 oauth_consumer_key: "6jjWwlbhGqyYeCdlFE1lTGG6IRGOv1yKpFxkcq2z",
20 oauth_secret: "A21gUeDM6mdoQgbA9uF7zJ13sbUQrNG7QQ4oSrKA",
21 url: "https://www.openstreetmap.org",
22 landing: "auth-done.html",
25 window.onload = function() {
26 if (/\/login\.html/.test(window.location)) {
27 // If we are in the login window, call a function to complete the process and don't do anything else here.
28 completeLoginWindow();
31 gAction = document.getElementById("action");
32 gActionLabel = document.getElementById("actionlabel");
34 var mSel = document.getElementById("mapSelector");
35 for (var mapStyle in gMapStyles) {
36 var opt = document.createElement("option");
38 opt.text = gMapStyles[mapStyle].name;
42 var areas = document.getElementsByClassName("overlayArea");
43 for (var i = 0; i <= areas.length - 1; i++) {
44 areas[i].addEventListener("mouseup", uiEvHandler, false);
45 areas[i].addEventListener("mousemove", uiEvHandler, false);
46 areas[i].addEventListener("mousedown", uiEvHandler, false);
47 areas[i].addEventListener("mouseout", uiEvHandler, false);
49 areas[i].addEventListener("touchstart", uiEvHandler, false);
50 areas[i].addEventListener("touchmove", uiEvHandler, false);
51 areas[i].addEventListener("touchend", uiEvHandler, false);
52 areas[i].addEventListener("touchcancel", uiEvHandler, false);
53 areas[i].addEventListener("touchleave", uiEvHandler, false);
56 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
58 if (navigator.platform.length == "") {
59 // For Firefox OS, don't display the "save" button.
60 // Do this by setting the debugHide class for testing in debug mode.
61 document.getElementById("saveTrackButton").classList.add("debugHide");
64 // Set backend URL in a way that it works for testing on localhost as well as
65 // both the lantea.kairo.at and lantea-dev.kairo.at deployments.
66 if (window.location.host == "localhost") {
67 gBackendURL = window.location.protocol + '//' + window.location.host + "/lantea-backend/";
70 gBackendURL = window.location.protocol + '//' + "backend." + window.location.host + "/";
72 // Make sure to use a different login client ID for the -dev setup.
73 if (/\-dev\./.test(window.location.host)) {
74 gAuthClientID += "-dev";
77 // Set up the login area.
78 document.getElementById("loginbtn").onclick = startLogin;
79 document.getElementById("logoutbtn").onclick = doLogout;
80 prepareLoginButton(function() {
81 // Anything that needs the backend should only be triggered from in here.
82 // That makes sure that the first call the the backend is oauth_state and no other is running in parallel.
83 // If we call multiple backend methods at once and no session is open, we create multiple sessions, which calls for confusion later on.
85 // Call any UI preparation that needs the backend.
89 // Note that GPX upload returns an error 500 on the dev API right now.
90 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
93 gAction.addEventListener("dbinit-done", initMap, false);
94 gAction.addEventListener("mapinit-done", postInit, false);
95 console.log("starting DB init...");
99 function postInit(aEvent) {
100 gAction.removeEventListener(aEvent.type, postInit, false);
101 console.log("init done, draw map.");
102 gMapPrefsLoaded = true;
104 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
105 window.setTimeout(gMap.resizeAndDraw, 100);
106 gActionLabel.textContent = "";
107 gAction.style.display = "none";
108 setTracking(document.getElementById("trackCheckbox"));
109 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
111 document.getElementById("uploadUser").value = aValue;
112 document.getElementById("uploadTrackButton").disabled = false;
115 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
116 var upwd = document.getElementById("uploadPwd");
118 document.getElementById("uploadPwd").value = aValue;
122 window.onresize = function() {
123 gMap.resizeAndDraw();
126 function startLogin() {
127 var authURL = authData["url"] + "authorize?response_type=code&client_id=" + gAuthClientID + "&scope=email" +
128 "&state=" + authData["state"] + "&redirect_uri=" + encodeURIComponent(getRedirectURI());
129 if (window.open(authURL, "KaiRoAuth", 'height=450,width=600')) {
130 console.log("Sign In window open.");
133 console.log("Opening Sign In window failed.");
137 function getRedirectURI() {
138 return window.location.protocol + '//' + window.location.host + window.location.pathname + "login.html";
141 function doLogout() {
142 fetchBackend("logout", "GET", null,
143 function(aResult, aStatus) {
145 prepareLoginButton();
148 console.log("Backend issue trying to log out.");
155 function prepareLoginButton(aCallback) {
156 fetchBackend("oauth_state", "GET", null,
157 function(aResult, aStatus) {
158 if (aStatus == 200) {
159 if (aResult["logged_in"]) {
161 "email": aResult["email"],
162 "permissions": aResult["permissions"],
168 authData = {"state": aResult["state"], "url": aResult["url"]};
174 console.log("Backend issue fetching OAuth state.");
176 if (aCallback) { aCallback(); }
182 function completeLoginWindow() {
184 window.opener.finishLogin(getParameterByName("code"), getParameterByName("state"));
188 document.getElementById("logininfo").textContent = "You have called this document outside of the login flow, which is not supported.";
192 function finishLogin(aCode, aState) {
193 if (aState == authData["state"]) {
194 fetchBackend("login?code=" + aCode + "&state=" + aState + "&redirect_uri=" + encodeURIComponent(getRedirectURI()), "GET", null,
195 function(aResult, aStatus) {
196 if (aStatus == 200) {
198 "email": aResult["email"],
199 "permissions": aResult["permissions"],
204 console.log("Login error " + aStatus + ": " + aResult["message"]);
205 prepareLoginButton();
212 console.log("Login state did not match, not continuing with login.");
216 function displayLogin() {
217 document.getElementById("loginbtn").classList.add("hidden");
218 document.getElementById("logindesc").classList.add("hidden");
219 document.getElementById("username").classList.remove("hidden");
220 document.getElementById("username").textContent = userData.email;
221 document.getElementById("uploadTrackButton").disabled = false;
222 document.getElementById("logoutbtn").classList.remove("hidden");
225 function displayLogout() {
226 document.getElementById("logoutbtn").classList.add("hidden");
227 document.getElementById("username").classList.add("hidden");
228 document.getElementById("username").textContent = "";
229 document.getElementById("uploadTrackButton").disabled = true;
230 document.getElementById("loginbtn").classList.remove("hidden");
231 document.getElementById("logindesc").classList.remove("hidden");
234 function initDB(aEvent) {
237 gAction.removeEventListener(aEvent.type, initDB, false);
238 var request = window.indexedDB.open("MainDB-lantea", 2);
239 request.onerror = function(event) {
240 // Errors can be handled here. Error codes explain in:
241 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
243 console.log("error opening mainDB: " + event.target.errorCode);
245 request.onsuccess = function(event) {
246 mainDB = request.result;
247 var throwEv = new CustomEvent("dbinit-done");
248 gAction.dispatchEvent(throwEv);
250 request.onupgradeneeded = function(event) {
251 mainDB = request.result;
252 var ver = mainDB.version || 0; // version is empty string for a new DB
254 console.log("mainDB has version " + ver + ", upgrade needed.");
255 if (!mainDB.objectStoreNames.contains("prefs")) {
256 // Create a "prefs" objectStore.
257 var prefsStore = mainDB.createObjectStore("prefs");
259 if (!mainDB.objectStoreNames.contains("track")) {
260 // Create a "track" objectStore.
261 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
263 if (!mainDB.objectStoreNames.contains("tilecache")) {
264 // Create a "tilecache" objectStore.
265 var tilecacheStore = mainDB.createObjectStore("tilecache");
267 mainDB.onversionchange = function(event) {
276 if (gUIHideCountdown <= 0) {
277 var areas = document.getElementsByClassName('overlayArea');
278 for (var i = 0; i <= areas.length - 1; i++) {
279 areas[i].classList.remove("hidden");
281 setTimeout(maybeHideUI, 1000);
283 gUIHideCountdown = 5;
286 function maybeHideUI() {
288 if (gUIHideCountdown <= 0) {
289 var areas = document.getElementsByClassName('overlayArea');
290 for (var i = 0; i <= areas.length - 1; i++) {
291 areas[i].classList.add("hidden");
295 setTimeout(maybeHideUI, 1000);
299 function updateTrackInfo() {
300 document.getElementById("trackLengthNum").textContent = calcTrackLength().toFixed(1);
301 var duration = calcTrackDuration();
302 var durationM = Math.round(duration/60);
303 var durationH = Math.floor(durationM/60); durationM = durationM - durationH * 60;
304 document.getElementById("trackDurationH").style.display = durationH ? "inline" : "none";
305 document.getElementById("trackDurationHNum").textContent = durationH;
306 document.getElementById("trackDurationMNum").textContent = durationM;
309 function toggleTrackArea() {
310 var fs = document.getElementById("trackArea");
311 if (fs.classList.contains("hidden")) {
312 fs.classList.remove("hidden");
314 gTrackUpdateInterval = setInterval(updateTrackInfo, 1000);
317 clearInterval(gTrackUpdateInterval);
318 fs.classList.add("hidden");
322 function toggleSettings() {
323 var fs = document.getElementById("settingsArea");
324 if (fs.classList.contains("hidden")) {
325 fs.classList.remove("hidden");
329 fs.classList.add("hidden");
333 function toggleFullscreen() {
334 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
335 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
336 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
337 if (document.cancelFullScreen) {
338 document.cancelFullScreen();
339 } else if (document.mozCancelFullScreen) {
340 document.mozCancelFullScreen();
341 } else if (document.webkitCancelFullScreen) {
342 document.webkitCancelFullScreen();
346 var elem = document.getElementById("body");
347 if (elem.requestFullScreen) {
348 elem.requestFullScreen();
349 } else if (elem.mozRequestFullScreen) {
350 elem.mozRequestFullScreen();
351 } else if (elem.webkitRequestFullScreen) {
352 elem.webkitRequestFullScreen();
357 function showUploadDialog() {
358 var dia = document.getElementById("dialogArea");
359 var areas = dia.children;
360 for (var i = 0; i <= areas.length - 1; i++) {
361 areas[i].style.display = "none";
363 document.getElementById("uploadDialog").style.display = "block";
364 document.getElementById("uploadTrackButton").disabled = true;
365 dia.classList.remove("hidden");
368 function showGLWarningDialog() {
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("noGLwarning").style.display = "block";
375 dia.classList.remove("hidden");
378 function cancelDialog() {
379 document.getElementById("dialogArea").classList.add("hidden");
380 document.getElementById("uploadTrackButton").disabled = false;
384 handleEvent: function(aEvent) {
385 var touchEvent = aEvent.type.indexOf('touch') != -1;
387 switch (aEvent.type) {
401 function setUploadField(aField) {
404 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
405 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
408 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
413 function makeISOString(aTimestamp) {
414 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
415 var tsDate = new Date(aTimestamp);
416 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
417 return tsDate.getUTCFullYear() + "-" +
418 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
419 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
420 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
421 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
422 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
425 function convertTrack(aTargetFormat) {
427 switch (aTargetFormat) {
429 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
430 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
432 out += ' <trk>' + "\n";
433 out += ' <trkseg>' + "\n";
434 for (var i = 0; i < gTrack.length; i++) {
435 if (gTrack[i].beginSegment && i > 0) {
436 out += ' </trkseg>' + "\n";
437 out += ' <trkseg>' + "\n";
439 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
440 gTrack[i].coords.longitude + '">' + "\n";
441 if (gTrack[i].coords.altitude) {
442 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
444 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
445 out += ' </trkpt>' + "\n";
447 out += ' </trkseg>' + "\n";
448 out += ' </trk>' + "\n";
450 out += '</gpx>' + "\n";
453 out = JSON.stringify(gTrack);
461 function saveTrack() {
463 var outDataURI = "data:application/gpx+xml," +
464 encodeURIComponent(convertTrack("gpx"));
465 window.open(outDataURI, 'GPX Track');
469 function saveTrackDump() {
471 var outDataURI = "data:application/json," +
472 encodeURIComponent(convertTrack("json"));
473 window.open(outDataURI, 'JSON dump');
477 function uploadTrack() {
478 // Hide all areas in the dialog.
479 var dia = document.getElementById("dialogArea");
480 var areas = dia.children;
481 for (var i = 0; i <= areas.length - 1; i++) {
482 areas[i].style.display = "none";
484 // Reset all the fields in the status area.
485 document.getElementById("uploadStatusCloseButton").disabled = true;
486 document.getElementById("uploadInProgress").style.display = "block";
487 document.getElementById("uploadSuccess").style.display = "none";
488 document.getElementById("uploadFailed").style.display = "none";
489 document.getElementById("uploadError").style.display = "none";
490 document.getElementById("uploadErrorMsg").textContent = "";
491 // Now show the status area.
492 document.getElementById("uploadStatus").style.display = "block";
494 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
495 var trackBlob = new Blob([convertTrack("gpx")],
496 { "type" : "application/gpx+xml" });
497 var formData = new FormData();
498 formData.append("file", trackBlob);
499 var desc = document.getElementById("uploadDesc").value;
500 formData.append("description",
501 desc.length ? desc : "Track recorded via Lantea Maps");
502 //formData.append("tags", "");
503 formData.append("visibility",
504 document.getElementById("uploadVisibility").value);
506 /* GPS trace upload API still only supports HTTP Basic Auth. This below would be OAuth code to try.
507 // Init OSM Auth, see https://github.com/osmlab/osm-auth
509 oauth_consumer_key: gOSMOAuthData.oauth_consumer_key,
510 oauth_secret: gOSMOAuthData.oauth_secret,
511 url: gOSMOAuthData.url,
512 landing: gOSMOAuthData.landing,
513 auto: true // show a login form if the user is not authenticated and
514 // you try to do a call
517 // Do an authenticate request first, so that we actuall do the login.
518 if (!auth.authenticated) {
519 auth.authenticate(function(err, xhrresponse) {
521 reportUploadStatus(false);
524 reportUploadStatus(true);
528 if (!auth.authenticated) {
529 reportUploadStatus(false);
532 // Only now do the actual upload.
535 path: "/api/0.6/gpx/create",
537 options: {"header": {"Content-Type": "multipart/form-data"}},
539 function(err, xhrresponse) {
541 reportUploadStatus(false);
544 reportUploadStatus(true);
550 // Do an empty POST request first, so that we don't send everything,
551 // then ask for credentials, and then send again.
552 var hXHR = new XMLHttpRequest();
553 hXHR.onreadystatechange = function() {
554 if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
555 // 400 is Bad Request, but that's expected as this was empty.
556 // So far so good, init actual upload.
557 var XHR = new XMLHttpRequest();
558 XHR.onreadystatechange = function() {
559 if (XHR.readyState == 4 && XHR.status == 200) {
560 // Everthing looks fine.
561 reportUploadStatus(true);
562 } else if (XHR.readyState == 4 && XHR.status != 200) {
563 // Fetched the wrong page or network error...
564 reportUploadStatus(false);
567 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
568 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
569 // So, we'll ask the user for entering credentials with rather ugly UI.
570 XHR.withCredentials = true;
572 XHR.send(formData); // Send actual form data.
575 reportUploadStatus(false, e);
577 } else if (hXHR.readyState == 4 && hXHR.status != 200) {
578 // Fetched the wrong page or network error...
579 reportUploadStatus(false);
582 hXHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
583 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
584 // So, we'll ask the user for entering credentials with rather ugly UI.
585 hXHR.withCredentials = true;
587 hXHR.send(); // Empty request, see above.
590 reportUploadStatus(false, e);
594 function reportUploadStatus(aSuccess, aMessage) {
595 document.getElementById("uploadStatusCloseButton").disabled = false;
596 document.getElementById("uploadInProgress").style.display = "none";
598 document.getElementById("uploadSuccess").style.display = "block";
601 document.getElementById("uploadErrorMsg").textContent = aMessage;
602 document.getElementById("uploadError").style.display = "block";
605 document.getElementById("uploadFailed").style.display = "block";
612 get: function(aKey, aCallback) {
615 var transaction = mainDB.transaction([this.objStore]);
616 var request = transaction.objectStore(this.objStore).get(aKey);
617 request.onsuccess = function(event) {
618 aCallback(request.result, event);
620 request.onerror = function(event) {
621 // Errors can be handled here.
622 aCallback(undefined, event);
626 set: function(aKey, aValue, aCallback) {
630 var transaction = mainDB.transaction([this.objStore], "readwrite");
631 var objStore = transaction.objectStore(this.objStore);
632 var request = objStore.put(aValue, aKey);
633 request.onsuccess = function(event) {
636 aCallback(success, event);
638 request.onerror = function(event) {
639 // Errors can be handled here.
641 aCallback(success, event);
645 unset: function(aKey, aCallback) {
649 var transaction = mainDB.transaction([this.objStore], "readwrite");
650 var request = transaction.objectStore(this.objStore).delete(aKey);
651 request.onsuccess = function(event) {
654 aCallback(success, event);
656 request.onerror = function(event) {
657 // Errors can be handled here.
659 aCallback(success, event);
667 getList: function(aCallback) {
670 var transaction = mainDB.transaction([this.objStore]);
671 var objStore = transaction.objectStore(this.objStore);
672 if (objStore.getAll) { // currently Mozilla-specific
673 objStore.getAll().onsuccess = function(event) {
674 aCallback(event.target.result);
677 else { // Use cursor (standard method).
679 objStore.openCursor().onsuccess = function(event) {
680 var cursor = event.target.result;
682 tPoints.push(cursor.value);
692 getListStepped: function(aCallback) {
695 var transaction = mainDB.transaction([this.objStore]);
696 var objStore = transaction.objectStore(this.objStore);
697 // Use cursor in reverse direction (so we get the most recent position first)
698 objStore.openCursor(null, "prev").onsuccess = function(event) {
699 var cursor = event.target.result;
701 aCallback(cursor.value);
710 push: function(aValue, aCallback) {
713 var transaction = mainDB.transaction([this.objStore], "readwrite");
714 var objStore = transaction.objectStore(this.objStore);
715 var request = objStore.add(aValue);
716 request.onsuccess = function(event) {
718 aCallback(request.result, event);
720 request.onerror = function(event) {
721 // Errors can be handled here.
723 aCallback(false, event);
727 clear: function(aCallback) {
731 var transaction = mainDB.transaction([this.objStore], "readwrite");
732 var request = transaction.objectStore(this.objStore).clear();
733 request.onsuccess = function(event) {
736 aCallback(success, event);
738 request.onerror = function(event) {
739 // Errors can be handled here.
741 aCallback(success, event);
746 function fetchBackend(aEndpoint, aMethod, aSendData, aCallback, aCallbackForwards) {
747 var XHR = new XMLHttpRequest();
748 XHR.onreadystatechange = function() {
749 if (XHR.readyState == 4) {
750 // State says we are fully loaded.
752 if (XHR.getResponseHeader("Content-Type") == "application/json") {
753 // Got a JSON object, see if we have success.
754 result = JSON.parse(XHR.responseText);
757 result = XHR.responseText;
759 aCallback(result, XHR.status, aCallbackForwards);
762 XHR.open(aMethod, gBackendURL + aEndpoint, true);
763 //XHR.setRequestHeader("Accept", "application/json");
765 XHR.send(aSendData); // Send actual form data.
768 aCallback(e, 500, aCallbackForwards);
772 function getParameterByName(aName) {
773 // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
774 name = aName.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
775 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
776 results = regex.exec(location.search);
777 return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));