X-Git-Url: https://git-public.kairo.at/?p=lantea.git;a=blobdiff_plain;f=js%2Fui.js;h=d8953ad0df4b9a7815bd3a5db4bb64056f113db9;hp=650b9cee6a36ae904bc358d2265ed0cbd60e82a5;hb=070d28b52b712a9067c29e6a358d39d2c3816048;hpb=ac6286bd2c43fe4e522c5a1ab732902aa8935cbc diff --git a/js/ui.js b/js/ui.js index 650b9ce..d8953ad 100644 --- a/js/ui.js +++ b/js/ui.js @@ -2,16 +2,32 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -// Get the best-available indexedDB object. +// Get the best-available objects for indexedDB and requestAnimationFrame. window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; -var mainDB; +window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; +var mainDB; +var gAppInitDone = false; var gUIHideCountdown = 0; var gWaitCounter = 0; +var gTrackUpdateInterval; var gAction, gActionLabel; -var gOSMAPIURL = "http://api.openstreetmap.org/"; +var gBackendURL = "https://backend.lantea.kairo.at"; +var gAuthClientID = "lantea"; +var gOSMAPIURL = "https://api.openstreetmap.org/"; +var gOSMOAuthData = { + oauth_consumer_key: "6jjWwlbhGqyYeCdlFE1lTGG6IRGOv1yKpFxkcq2z", + oauth_secret: "A21gUeDM6mdoQgbA9uF7zJ13sbUQrNG7QQ4oSrKA", + url: "https://www.openstreetmap.org", + landing: "auth-done.html", +} window.onload = function() { + if (/\/login\.html/.test(window.location)) { + // If we are in the login window, call a function to complete the process and don't do anything else here. + completeLoginWindow(); + return; + } gAction = document.getElementById("action"); gActionLabel = document.getElementById("actionlabel"); @@ -45,10 +61,29 @@ window.onload = function() { document.getElementById("saveTrackButton").classList.add("debugHide"); } - // Without OAuth, the login data is useless - //document.getElementById("uploadSettingsArea").classList.remove("debugHide"); - // As login data is useless for now, always enable upload button - document.getElementById("uploadTrackButton").disabled = false; + // Set backend URL in a way that it works for testing on localhost as well as + // both the lantea.kairo.at and lantea-dev.kairo.at deployments. + if (window.location.host == "localhost") { + gBackendURL = window.location.protocol + '//' + window.location.host + "/lantea-backend/"; + } + else { + gBackendURL = window.location.protocol + '//' + "backend." + window.location.host + "/"; + } + // Make sure to use a different login client ID for the -dev setup. + if (/\-dev\./.test(window.location.host)) { + gAuthClientID += "-dev"; + } + + // Set up the login area. + document.getElementById("loginbtn").onclick = startLogin; + document.getElementById("logoutbtn").onclick = doLogout; + prepareLoginButton(function() { + // Anything that needs the backend should only be triggered from in here. + // That makes sure that the first call the the backend is oauth_state and no other is running in parallel. + // If we call multiple backend methods at once and no session is open, we create multiple sessions, which calls for confusion later on. + + // Call any UI preparation that needs the backend. + }); if (gDebug) { // Note that GPX upload returns an error 500 on the dev API right now. @@ -65,7 +100,9 @@ function postInit(aEvent) { gAction.removeEventListener(aEvent.type, postInit, false); console.log("init done, draw map."); gMapPrefsLoaded = true; - gMap.resizeAndDraw(); + gAppInitDone = true; + //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay. + window.setTimeout(gMap.resizeAndDraw, 100); gActionLabel.textContent = ""; gAction.style.display = "none"; setTracking(document.getElementById("trackCheckbox")); @@ -86,6 +123,114 @@ window.onresize = function() { gMap.resizeAndDraw(); } +function startLogin() { + var authURL = authData["url"] + "authorize?response_type=code&client_id=" + gAuthClientID + "&scope=email" + + "&state=" + authData["state"] + "&redirect_uri=" + encodeURIComponent(getRedirectURI()); + if (window.open(authURL, "KaiRoAuth", 'height=450,width=600')) { + console.log("Sign In window open."); + } + else { + console.log("Opening Sign In window failed."); + } +} + +function getRedirectURI() { + return window.location.protocol + '//' + window.location.host + window.location.pathname + "login.html"; +} + +function doLogout() { + fetchBackend("logout", "GET", null, + function(aResult, aStatus) { + if (aStatus < 400) { + prepareLoginButton(); + } + else { + console.log("Backend issue trying to log out."); + } + }, + {} + ); +} + +function prepareLoginButton(aCallback) { + fetchBackend("oauth_state", "GET", null, + function(aResult, aStatus) { + if (aStatus == 200) { + if (aResult["logged_in"]) { + userData = { + "email": aResult["email"], + "permissions": aResult["permissions"], + }; + authData = null; + displayLogin(); + } + else { + authData = {"state": aResult["state"], "url": aResult["url"]}; + userData = null; + displayLogout(); + } + } + else { + console.log("Backend error " + aStatus + " fetching OAuth state: " + aResult["message"]); + } + if (aCallback) { aCallback(); } + }, + {} + ); +} + +function completeLoginWindow() { + if (window.opener) { + window.opener.finishLogin(getParameterByName("code"), getParameterByName("state")); + window.close(); + } + else { + document.getElementById("logininfo").textContent = "You have called this document outside of the login flow, which is not supported."; + } +} + +function finishLogin(aCode, aState) { + if (aState == authData["state"]) { + fetchBackend("login?code=" + aCode + "&state=" + aState + "&redirect_uri=" + encodeURIComponent(getRedirectURI()), "GET", null, + function(aResult, aStatus) { + if (aStatus == 200) { + userData = { + "email": aResult["email"], + "permissions": aResult["permissions"], + }; + displayLogin(); + } + else { + console.log("Login error " + aStatus + ": " + aResult["message"]); + prepareLoginButton(); + } + }, + {} + ); + } + else { + console.log("Login state did not match, not continuing with login."); + } +} + +function displayLogin() { + document.getElementById("loginbtn").classList.add("hidden"); + document.getElementById("logindesc").classList.add("hidden"); + document.getElementById("username").classList.remove("hidden"); + document.getElementById("username").textContent = userData.email; + document.getElementById("uploadTrackButton").disabled = false; + document.getElementById("logoutbtn").classList.remove("hidden"); +} + +function displayLogout() { + document.getElementById("logoutbtn").classList.add("hidden"); + document.getElementById("username").classList.add("hidden"); + document.getElementById("username").textContent = ""; + document.getElementById("uploadTrackButton").disabled = true; + document.getElementById("loginbtn").classList.remove("hidden"); + document.getElementById("logindesc").classList.remove("hidden"); +} + function initDB(aEvent) { // Open DB. if (aEvent) @@ -151,25 +296,37 @@ function maybeHideUI() { } } +function updateTrackInfo() { + document.getElementById("trackLengthNum").textContent = calcTrackLength().toFixed(1); + var duration = calcTrackDuration(); + var durationM = Math.round(duration/60); + var durationH = Math.floor(durationM/60); durationM = durationM - durationH * 60; + document.getElementById("trackDurationH").style.display = durationH ? "inline" : "none"; + document.getElementById("trackDurationHNum").textContent = durationH; + document.getElementById("trackDurationMNum").textContent = durationM; +} + function toggleTrackArea() { var fs = document.getElementById("trackArea"); - if (fs.style.display != "block") { - fs.style.display = "block"; + if (fs.classList.contains("hidden")) { + fs.classList.remove("hidden"); showUI(); + gTrackUpdateInterval = setInterval(updateTrackInfo, 1000); } else { - fs.style.display = "none"; + clearInterval(gTrackUpdateInterval); + fs.classList.add("hidden"); } } function toggleSettings() { var fs = document.getElementById("settingsArea"); - if (fs.style.display != "block") { - fs.style.display = "block"; + if (fs.classList.contains("hidden")) { + fs.classList.remove("hidden"); showUI(); } else { - fs.style.display = "none"; + fs.classList.add("hidden"); } } @@ -345,6 +502,51 @@ function uploadTrack() { //formData.append("tags", ""); formData.append("visibility", document.getElementById("uploadVisibility").value); + +/* GPS trace upload API still only supports HTTP Basic Auth. This below would be OAuth code to try. + // Init OSM Auth, see https://github.com/osmlab/osm-auth + var auth = osmAuth({ + oauth_consumer_key: gOSMOAuthData.oauth_consumer_key, + oauth_secret: gOSMOAuthData.oauth_secret, + url: gOSMOAuthData.url, + landing: gOSMOAuthData.landing, + auto: true // show a login form if the user is not authenticated and + // you try to do a call + }); + + // Do an authenticate request first, so that we actuall do the login. + if (!auth.authenticated) { + auth.authenticate(function(err, xhrresponse) { + if (err) { + reportUploadStatus(false); + } + else { + reportUploadStatus(true); + } + }); + } + if (!auth.authenticated) { + reportUploadStatus(false); + return; + } + // Only now do the actual upload. + auth.xhr({ + method: "POST", + path: "/api/0.6/gpx/create", + content: formData, + options: {"header": {"Content-Type": "multipart/form-data"}}, + }, + function(err, xhrresponse) { + if (err) { + reportUploadStatus(false); + } + else { + reportUploadStatus(true); + } + } + ); +*/ + // Do an empty POST request first, so that we don't send everything, // then ask for credentials, and then send again. var hXHR = new XMLHttpRequest(); @@ -540,3 +742,38 @@ var gTrackStore = { } } }; + +function fetchBackend(aEndpoint, aMethod, aSendData, aCallback, aCallbackForwards) { + var XHR = new XMLHttpRequest(); + XHR.onreadystatechange = function() { + if (XHR.readyState == 4) { + // State says we are fully loaded. + var result = {}; + if (XHR.getResponseHeader("Content-Type") == "application/json") { + // Got a JSON object, see if we have success. + result = JSON.parse(XHR.responseText); + } + else { + result = XHR.responseText; + } + aCallback(result, XHR.status, aCallbackForwards); + } + }; + XHR.open(aMethod, gBackendURL + aEndpoint, true); + XHR.withCredentials = "true"; + //XHR.setRequestHeader("Accept", "application/json"); + try { + XHR.send(aSendData); // Send actual form data. + } + catch (e) { + aCallback(e, 500, aCallbackForwards); + } +} + +function getParameterByName(aName) { + // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript + name = aName.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); + var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), + results = regex.exec(location.search); + return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); +}