Skip to content

Commit

Permalink
streamline control flow
Browse files Browse the repository at this point in the history
  • Loading branch information
schlawg authored Oct 24, 2024
1 parent d73ff19 commit a696070
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions ui/site/src/serviceWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit a696070

Please sign in to comment.