add an indicator when login fails
[lantea.git] / js / ui.js
index a3b7f35c3f98f65be7502890d3a22eb12f8d8e64..92dd488e051e1c185707ccca347a9c8a621ea7bd 100644 (file)
--- a/js/ui.js
+++ b/js/ui.js
@@ -8,19 +8,16 @@ window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequest
 
 var mainDB;
 var gAppInitDone = false;
+var firstRun = false;
 var gUIHideCountdown = 0;
 var gWaitCounter = 0;
 var gTrackUpdateInterval;
 var gAction, gActionLabel;
-var gBackendURL = "https://backend.lantea.kairo.at";
+var authData = null, userData = null;
+var gBackendURL = "https://backend.lantea.kairo.at/";
 var gAuthClientID = "lantea";
 
 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");
 
@@ -32,7 +29,7 @@ window.onload = function() {
     mSel.add(opt, null);
   }
 
-  var areas = document.getElementsByClassName("overlayArea");
+  var areas = document.getElementsByClassName("autoFade");
   for (var i = 0; i <= areas.length - 1; i++) {
     areas[i].addEventListener("mouseup", uiEvHandler, false);
     areas[i].addEventListener("mousemove", uiEvHandler, false);
@@ -72,13 +69,9 @@ window.onload = function() {
   // 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.
-  });
+  // Put in a logged-out state by default.
+  // Opening the track drawer will update this correctly.
+  displayLogout();
 
   gAction.addEventListener("dbinit-done", initMap, false);
   gAction.addEventListener("mapinit-done", postInit, false);
@@ -101,6 +94,17 @@ function postInit(aEvent) {
       document.getElementById("uploadDevName").value = aValue;
     }
   });
+  if (firstRun) {
+    showFirstRunDialog();
+  }
+  else {
+    gPrefs.get("lastInfoShown", function(aValue) {
+      if (!aValue || !parseInt(aValue) || parseInt(aValue) < 1) {
+        showInfoDialog();
+      }
+    });
+  }
+  gPrefs.set("lastInfoShown", 1);
 }
 
 window.onresize = function() {
@@ -108,6 +112,24 @@ window.onresize = function() {
 }
 
 function startLogin() {
+  var logerr = document.getElementById("loginerror");
+  logerr.classList.add("hidden");
+  logerr.title = "";
+  if (!authData || !authData["state"]) {
+    // We have no oAuth state, try to fetch it and call ourselves again if it worked.
+    prepareLoginButton(function() {
+      if (authData && authData["state"]) {
+        startLogin();
+      }
+      else if (!userData) {
+        // Only warn if we didn't actually end up being logged in.
+        console.log("No OAuth state and fetching fails, client or server may be offline.");
+        logerr.classList.remove("hidden");
+        logerr.title = "Client or server may be offline.";
+      }
+    });
+    return;
+  }
   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')) {
@@ -115,6 +137,8 @@ function startLogin() {
   }
   else {
     console.log("Opening Sign In window failed.");
+    logerr.classList.remove("hidden");
+    logerr.title = "Opening Sign-In window failed.";
   }
 }
 
@@ -163,16 +187,6 @@ function prepareLoginButton(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,
@@ -241,6 +255,7 @@ function initDB(aEvent) {
     if (!mainDB.objectStoreNames.contains("prefs")) {
       // Create a "prefs" objectStore.
       var prefsStore = mainDB.createObjectStore("prefs");
+      firstRun = true;
     }
     if (!mainDB.objectStoreNames.contains("track")) {
       // Create a "track" objectStore.
@@ -260,7 +275,7 @@ function initDB(aEvent) {
 
 function showUI() {
   if (gUIHideCountdown <= 0) {
-    var areas = document.getElementsByClassName('overlayArea');
+    var areas = document.getElementsByClassName('autoFade');
     for (var i = 0; i <= areas.length - 1; i++) {
       areas[i].classList.remove("hidden");
     }
@@ -272,7 +287,7 @@ function showUI() {
 function maybeHideUI() {
   gUIHideCountdown--;
   if (gUIHideCountdown <= 0) {
-    var areas = document.getElementsByClassName('overlayArea');
+    var areas = document.getElementsByClassName('autoFade');
     for (var i = 0; i <= areas.length - 1; i++) {
       areas[i].classList.add("hidden");
     }
@@ -295,6 +310,7 @@ function updateTrackInfo() {
 function toggleTrackArea() {
   var fs = document.getElementById("trackArea");
   if (fs.classList.contains("hidden")) {
+    prepareLoginButton();
     fs.classList.remove("hidden");
     showUI();
     gTrackUpdateInterval = setInterval(updateTrackInfo, 1000);
@@ -351,6 +367,11 @@ function showUploadDialog() {
   dia.classList.remove("hidden");
 }
 
+function cancelTrackDialog() {
+  document.getElementById("trackDialogArea").classList.add("hidden");
+  document.getElementById("uploadTrackButton").disabled = false;
+}
+
 function showGLWarningDialog() {
   var dia = document.getElementById("dialogArea");
   var areas = dia.children;
@@ -361,9 +382,28 @@ function showGLWarningDialog() {
   dia.classList.remove("hidden");
 }
 
-function cancelTrackDialog() {
-  document.getElementById("trackDialogArea").classList.add("hidden");
-  document.getElementById("uploadTrackButton").disabled = false;
+function showFirstRunDialog() {
+  var dia = document.getElementById("dialogArea");
+  var areas = dia.children;
+  for (var i = 0; i <= areas.length - 1; i++) {
+    areas[i].style.display = "none";
+  }
+  document.getElementById("firstRunIntro").style.display = "block";
+  dia.classList.remove("hidden");
+}
+
+function closeDialog() {
+  document.getElementById("dialogArea").classList.add("hidden");
+}
+
+function showInfoDialog() {
+  var dia = document.getElementById("dialogArea");
+  var areas = dia.children;
+  for (var i = 0; i <= areas.length - 1; i++) {
+    areas[i].style.display = "none";
+  }
+  document.getElementById("infoDialog").style.display = "block";
+  dia.classList.remove("hidden");
 }
 
 var uiEvHandler = {
@@ -489,21 +529,31 @@ function uploadTrack() {
       if (aStatusCode >= 400) {
         reportUploadStatus(false, aResult);
       }
-      else {
+      else if (aResult["id"]) {
         reportUploadStatus(true);
       }
+      else { // If no ID is returned, we assume a general error.
+        reportUploadStatus(false);
+      }
     }
   );
 }
 
-function reportUploadStatus(aSuccess, aMessage) {
+function reportUploadStatus(aSuccess, aResponse) {
   document.getElementById("uploadStatusCloseButton").disabled = false;
   document.getElementById("uploadInProgress").style.display = "none";
   if (aSuccess) {
     document.getElementById("uploadSuccess").style.display = "block";
   }
-  else if (aMessage) {
-    document.getElementById("uploadErrorMsg").textContent = aMessage;
+  else if (aResponse && aResponse["message"]) {
+    document.getElementById("uploadErrorMsg").textContent = aResponse["message"];
+    if (aResponse["errortype"]) {
+      document.getElementById("uploadErrorMsg").textContent += " (" + aResponse["errortype"] + ")";
+    }
+    document.getElementById("uploadError").style.display = "block";
+  }
+  else if (aResponse) {
+    document.getElementById("uploadErrorMsg").textContent = aResponse;
     document.getElementById("uploadError").style.display = "block";
   }
   else {
@@ -681,11 +731,3 @@ function fetchBackend(aEndpoint, aMethod, aSendData, aCallback, aCallbackForward
     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, " "));
-}