From 9328519c2952f137ba5be007e4a866a1f78abba6 Mon Sep 17 00:00:00 2001 From: Kegan Dougal Date: Thu, 2 Apr 2020 18:06:27 +0100 Subject: [PATCH] Fix auto-register and constantly logging you out mess --- src/vector/app.js | 87 +++++++++++++++++++++++++++++---------- src/vector/dendrite-sw.js | 22 ++++++++-- src/vector/index.js | 2 +- webpack.config.js | 2 +- 4 files changed, 86 insertions(+), 27 deletions(-) diff --git a/src/vector/app.js b/src/vector/app.js index 16db0f2f..cb3ce2a2 100644 --- a/src/vector/app.js +++ b/src/vector/app.js @@ -125,6 +125,16 @@ function onNewScreen(screen) { const hash = '#/' + screen; lastLocationHashSet = hash; window.location.hash = hash; + if (!window.matrixChat) { + return; + } + if (screen === "register" || screen === "login" || screen === "welcome") { + autoRegister().then((creds) => { + window.matrixChat.onUserCompletedLoginFlow(creds, "-") + }, (err) => { + console.error("Failed to auto-register:", err) + }) + } } // We use this to work out what URL the SDK should @@ -174,6 +184,41 @@ function onTokenLoginCompleted() { window.location.href = formatted; } +async function autoRegister() { + console.log("dendrite: Auto-registration in progress"); + const cli = Matrix.createClient({ + baseUrl: "https://p2p.riot.im", + }); + const password = "this should be really really secure"; + + // make sure the server is up (active service worker) + await navigator.serviceWorker.ready; + + let response = null; + try { + response = await cli.register("p2p", password, "", { type: "m.login.dummy" }); + console.log("dendrite: Auto-registration done ", response); + } catch (err) { + console.error("dendrite: failed to register, trying to login:", err) + response = await cli.login("m.login.password", { + identifier: { + type: "m.id.user", + user: "p2p", + }, + password: password, + initial_device_display_name: "p2p-dendrite", + }) + } + + return { + userId: response.user_id, + deviceId: response.device_id, + homeserverUrl: cli.getHomeserverUrl(), + accessToken: response.access_token, + guest: cli.isGuest(), + }; +} + export async function loadApp() { // XXX: the way we pass the path to the worker script from webpack via html in body's dataset is a hack // but alternatives seem to require changing the interface to passing Workers to js-sdk @@ -185,7 +230,7 @@ export async function loadApp() { // make sure the indexeddb script is present, so fail hard. throw new Error("Missing indexeddb worker script!"); } - MatrixClientPeg.setIndexedDbWorkerScript(vectorIndexeddbWorkerScript); + // MatrixClientPeg.setIndexedDbWorkerScript(vectorIndexeddbWorkerScript); CallHandler.setConferenceHandler(VectorConferenceHandler); @@ -282,35 +327,32 @@ export async function loadApp() { if (vectorDendriteWorkerScript && 'serviceWorker' in navigator) { console.log("dendrite code exec... ", document.readyState); const loadDendriteSw = ()=>{ - console.log("Registering dendrite sw..."); + console.log("Registering dendrite sw...", vectorDendriteWorkerScript); + console.log("swjs: invoke navigator.serviceWorker.register") navigator.serviceWorker.register(vectorDendriteWorkerScript, { scope: "/" }).then(function(registration) { + console.log("swjs: navigator.serviceWorker.register resolved", registration) // Registration was successful console.log('ServiceWorker sw.js registration successful with scope: ', registration.scope); - /* const currWorker = registration.active; - currWorker.addEventListener('statechange', () => { - console.log("Current sw.js state: ", currWorker.state) - }); */ - - registration.addEventListener('updatefound', () => { - console.log("New dendrite sw.js found!") - const newWorker = registration.installing; - if (!newWorker) { - return; - } - newWorker.addEventListener('statechange', () => { - console.log("New sw.js state: ", newWorker.state) - }); - }) - - console.log("sw.js listening for new updates..."); // periodically check for updates setInterval(function() { + console.log("swjs invoke registration.update") registration.update(); }, 1000 * 60 * 30) // once every 30 minutes }, (err)=>{ // registration failed :( - console.log('ServiceWorker registration failed: ', err) - }) + console.log('dendrite: ServiceWorker registration failed: ', err); + }); + // First, do a one-off check if there's currently a + // service worker in control. + if (navigator.serviceWorker.controller) { + console.log('dendrite: This page is currently controlled by:', navigator.serviceWorker.controller); + } + + // Then, register a handler to detect when a new or + // updated service worker takes control. + navigator.serviceWorker.oncontrollerchange = function() { + console.log('dendrite: This page is now controlled by:', navigator.serviceWorker.controller); + }; } if (document.readyState === "loading") { window.addEventListener('DOMContentLoaded', loadDendriteSw); @@ -318,6 +360,7 @@ export async function loadApp() { loadDendriteSw(); } + /* // check if we are logged in and if not, register. const autoRegister = async () => { console.log("dendrite: Auto-registration in progress"); @@ -358,7 +401,7 @@ export async function loadApp() { }); }, 10) }) - }); + }); */ } const validBrowser = checkBrowserFeatures(); diff --git a/src/vector/dendrite-sw.js b/src/vector/dendrite-sw.js index 0568d049..282f5104 100644 --- a/src/vector/dendrite-sw.js +++ b/src/vector/dendrite-sw.js @@ -14,8 +14,20 @@ // limitations under the License. const bundle_path = self.location.href.replace("/dendrite_sw.js", "") - -const version = "0.0.3" +const id = Math.random(); +console.log("swjs: ", id," dendrite-sw.js file running...") +const version = "0.0.4" +self.registration.addEventListener('updatefound', () => { + console.log("swjs: ", id," updatefound registration event fired") + const newWorker = self.registration.installing; + if (!newWorker) { + console.log("swjs: ", id," updatefound registration event fired, no installing worker") + return; + } + newWorker.addEventListener('statechange', () => { + console.log("swjs: ", id," worker statechange: ", newWorker.state) + }); +}) self.importScripts(`${bundle_path}/wasm_exec.js`, `${bundle_path}/go_http_bridge.js`, @@ -48,6 +60,7 @@ function initDendrite() { // make fetch calls go through this sw - notably if a page registers a sw, it does NOT go through any sw by default // unless you refresh or call this function. console.log(`dendrite-sw.js: v${version} claiming open browser tabs`) + console.log("swjs: ", id," invoke self.clients.claim()") self.clients.claim() }).then(async function() { function sleep(ms) { @@ -55,6 +68,7 @@ function initDendrite() { } for (let i = 0; i < 30; i++) { // 3s if (global._go_js_server) { + console.log("swjs: ", id," init dendrite promise resolving") return; } await sleep(100); @@ -65,13 +79,16 @@ function initDendrite() { const initDendritePromise = initDendrite(); self.addEventListener('install', function(event) { + console.log("swjs: ", id," install event fired:", event) console.log(`dendrite-sw.js: v${version} SW install`) // Tell the browser to kill old sw's running in other tabs and replace them with this one // This may cause spontaneous logouts. + console.log("swjs: ", id," invoke self.skipWaiting") self.skipWaiting(); }) self.addEventListener('activate', function(event) { + console.log("swjs: ", id," activate event fired") console.log(`dendrite-sw.js: v${version} SW activate`) event.waitUntil(initDendritePromise) }) @@ -148,7 +165,6 @@ async function sendRequestToGo(event) { }) } - self.addEventListener('fetch', function(event) { event.respondWith((async () => { /* diff --git a/src/vector/index.js b/src/vector/index.js index 3f34f2c1..11fa6001 100644 --- a/src/vector/index.js +++ b/src/vector/index.js @@ -31,7 +31,7 @@ import './modernizr'; // load service worker if available on this platform if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('sw.js'); + // navigator.serviceWorker.register('sw.js'); } // Ensure the skin is the very first thing to load for the react-sdk. We don't even want to reference diff --git a/webpack.config.js b/webpack.config.js index 999a7ede..5dbaf20b 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -32,7 +32,7 @@ module.exports = (env, argv) => { entry: { "bundle": "./src/vector/index.js", - "indexeddb_worker": "./src/vector/indexeddb-worker.js", + // "indexeddb_worker": "./src/vector/indexeddb-worker.js", "dendrite_sw": "./src/vector/dendrite-sw.js", "mobileguide": "./src/vector/mobile_guide/index.js", "sqlitejs": "./src/vector/sqlitejs.js",