From a696070bbe9f092bf8e2138dfadddf71198f09f4 Mon Sep 17 00:00:00 2001 From: Jonathan Gamble <101470903+schlawg@users.noreply.github.com> Date: Thu, 24 Oct 2024 14:29:04 -0500 Subject: [PATCH] streamline control flow --- ui/site/src/serviceWorker.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ui/site/src/serviceWorker.ts b/ui/site/src/serviceWorker.ts index 4070a9c28ce7..cec777be6109 100644 --- a/ui/site/src/serviceWorker.ts +++ b/ui/site/src/serviceWorker.ts @@ -14,29 +14,29 @@ export default async function () { (await navigator.serviceWorker.register(workerUrl.href, { scope: '/', updateViaCache: 'all' })); const store = storage.make('push-subscribed'); + const resub = parseInt(store.get() || '0', 10) + 43200000 < Date.now(); // 12 hours const vapid = document.body.getAttribute('data-vapid'); + const sub = await reg.pushManager.getSubscription(); + if (!vapid || Notification.permission !== 'granted') { store.remove(); - reg.pushManager.getSubscription().then(sub => sub?.unsubscribe()); + sub?.unsubscribe(); return; - } - const sub = await reg.pushManager.getSubscription(); - const resub = parseInt(store.get() || '0', 10) + 43200000 < Date.now(); // 12 hours - const applicationServerKey = Uint8Array.from(atob(vapid), c => c.charCodeAt(0)); + } else if (sub && !resub) return; - if (sub && !resub) return; + const applicationServerKey = Uint8Array.from(atob(vapid), c => c.charCodeAt(0)); let newSub: PushSubscription | undefined = undefined; try { - newSub = await reg.pushManager.subscribe({ - userVisibleOnly: true, - applicationServerKey: applicationServerKey, - }); - if (!newSub) throw new Error(!!reg && JSON.stringify(await reg.pushManager.permissionState())); + newSub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }); + + if (!newSub) throw new Error(JSON.stringify(await reg.pushManager.permissionState())); + const res = await fetch('/push/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newSub), }); + if (res.ok && !res.redirected) store.set('' + Date.now()); else throw new Error(res.statusText); } catch (err: any) {