feat: push notifications

This commit is contained in:
2023-12-18 12:20:14 +00:00
parent a3d4b81e23
commit fec6f48bce
5 changed files with 165 additions and 1 deletions

View File

@ -3,6 +3,7 @@ declare const self: ServiceWorkerGlobalScope & {
__WB_MANIFEST: (string | PrecacheEntry)[];
};
import { hexToBech32 } from "@snort/shared";
import { clientsClaim } from "workbox-core";
import { PrecacheEntry, precacheAndRoute } from "workbox-precaching";
@ -29,3 +30,52 @@ self.addEventListener("install", event => {
// always skip waiting
self.skipWaiting();
});
const enum NotificationType {
StreamStarted = 1,
}
interface PushNotification {
type: NotificationType;
pubkey: string;
name?: string;
avatar?: string;
}
self.addEventListener("notificationclick", event => {
const ev = JSON.parse(event.notification.data) as PushNotification;
event.notification.close();
event.waitUntil(
(async () => {
const windows = await self.clients.matchAll({ type: "window" });
const url = () => {
return `/${hexToBech32("npub", ev.pubkey)}`;
};
for (const client of windows) {
if (client.url === url() && "focus" in client) return client.focus();
}
if (self.clients.openWindow) return self.clients.openWindow(url());
})()
);
});
self.addEventListener("push", async e => {
console.debug(e);
const data = e.data?.json() as PushNotification | undefined;
if (!data) return;
const icon = data.avatar ?? `${location.protocol}//${location.hostname}/logo_256.png`;
if (data?.type == NotificationType.StreamStarted) {
const ret = {
icon,
timestamp: new Date().getTime(),
data: JSON.stringify(data),
};
console.debug(ret);
await self.registration.showNotification(
`${data.name ?? hexToBech32("npub", data.pubkey).slice(0, 12)} went live`,
ret
);
}
});