// Exists so browsers treat the app as installable. It deliberately caches // nothing and never calls respondWith(): every request goes to the network // exactly as if there were no service worker. A caching worker would keep // serving an old JS bundle after a rebuild, and this app is a live view of // authenticated data with no useful offline mode anyway. self.addEventListener("install", () => self.skipWaiting()); self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim())); self.addEventListener("fetch", () => {}); // Push notifications (Settings > Notifications). The message arrives encrypted for this browser only and is read here; a tap opens the app // at the page it names, reusing a window that is already open. self.addEventListener("push", (event) => { let data = {}; try { data = event.data ? event.data.json() : {}; } catch { data = { body: event.data ? event.data.text() : "" }; } event.waitUntil( self.registration.showNotification(data.title || "Homelab Manager", { body: data.body || "", icon: "/icon-192.png", badge: "/favicon-32.png", tag: data.tag || undefined, // Buttons (Acknowledge, Silence): a press sends its own address, which is for this alert only, and says how it went. actions: Array.isArray(data.actions) ? data.actions.filter((a) => a && typeof a.action === "string" && typeof a.title === "string").slice(0, 3).map((a) => ({ action: a.action, title: a.title })) : [], data: { url: typeof data.url === "string" && data.url.startsWith("/") ? data.url : "/alerts", actions: Array.isArray(data.actions) ? data.actions : [] }, }), ); }); self.addEventListener("notificationclick", (event) => { event.notification.close(); const pressed = event.action && ((event.notification.data && event.notification.data.actions) || []).find((a) => a.action === event.action); if (pressed && typeof pressed.path === "string" && pressed.path.startsWith("/api/alert-actions/")) { event.waitUntil( fetch(pressed.path, { method: "POST", headers: { Accept: "application/json" }, credentials: "omit" }) .then((r) => r.json().catch(() => ({})).then((body) => ({ ok: r.ok, message: (body && body.message) || (r.ok ? "Done." : "That didn't work.") }))) .catch(() => ({ ok: false, message: "Couldn't reach Homelab Manager." })) .then((result) => self.registration.showNotification(result.ok ? pressed.title + ": done" : "Not done", { body: result.message, icon: "/icon-192.png", badge: "/favicon-32.png", tag: "alert-action-result" })), ); return; } const target = new URL((event.notification.data && event.notification.data.url) || "/alerts", self.location.origin).href; event.waitUntil( self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((windows) => { for (const w of windows) { if (new URL(w.url).origin === self.location.origin && "focus" in w) { return w.focus().then(() => ("navigate" in w ? w.navigate(target) : undefined)); } } return self.clients.openWindow(target); }), ); });