+function getRedirectURI() {
+ return window.location.protocol + '//' + window.location.host + window.location.pathname.replace("index.html", "") + "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 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("libraryShowLine").classList.remove("hidden");
+ 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("libraryShowLine").classList.add("hidden");
+ document.getElementById("loginbtn").classList.remove("hidden");
+ document.getElementById("logindesc").classList.remove("hidden");
+}
+
+function initDB(aEvent) {