"use strict";
const NEEDS_YOU = { en: "{0} needs you", "zh-cn": "{0} 需要你处理" };
const A_TASK = { en: "A task needs you", "zh-cn": "有任务需要你处理" };
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
self.addEventListener("push", (e) => e.waitUntil(show()));
async function pending() {
const stop = new AbortController();
const timer = setTimeout(() => stop.abort(), 5000);
try {
const sub = await self.registration.pushManager.getSubscription();
const res = await fetch("/api/push/pending", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ endpoint: sub ? sub.endpoint : "" }),
signal: stop.signal,
});
return res.ok ? await res.json() : null;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
async function show() {
const answer = await pending();
if (!answer) {
await self.registration.showNotification(A_TASK.en, { icon: "/icon.png", tag: "kanzo", data: { where: "" } });
return;
}
const words = NEEDS_YOU[answer.lang] || NEEDS_YOU.en;
for (const t of answer.tasks) {
await self.registration.showNotification(words.replace("{0}", `${t.project}#${t.id}`), {
body: t.title,
icon: "/icon.png",
tag: `kanzo-${t.shared ? "@" : ""}${t.id}`,
data: { where: `${t.shared ? "@" : ""}${t.project}/${t.id}` },
});
}
}
self.addEventListener("notificationclick", (e) => {
e.notification.close();
e.waitUntil(open(e.notification.data?.where ?? ""));
});
async function open(where) {
const pages = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
const page = pages.find((p) => new URL(p.url).searchParams.has("app")) || pages[0];
if (page) {
await page.focus();
page.postMessage({ open: where });
} else {
await self.clients.openWindow("/" + (where ? "#" + where : ""));
}
}
self.addEventListener("pushsubscriptionchange", (e) => e.waitUntil(renew(e.oldSubscription)));
async function renew(old) {
const send = (method, body) =>
fetch("/api/push", { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const { key } = await (await fetch("/api/push")).json();
const applicationServerKey = Uint8Array.from(atob(key.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
const sub = await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });
await send("POST", { endpoint: sub.endpoint, lang: "" });
if (old) await send("DELETE", { endpoint: old.endpoint });
}