Debian Codegraph @

web/public/sw.js

raw
1 /* eslint-disable import/no-extraneous-dependencies */
2 import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from "workbox-precaching";
3 import { NavigationRoute, registerRoute } from "workbox-routing";
4 import { NetworkFirst } from "workbox-strategies";
5 import { clientsClaim } from "workbox-core";
6 import { dbAsync } from "../src/app/db";
7 import session from "../src/app/Session";
8 import { ACTION_HTTP, ACTION_VIEW } from "../src/app/actions";
9 import { badge, icon, messageWithSequenceId, notificationTag, toNotificationParams } from "../src/app/notificationUtils";
10 import initI18n from "../src/app/i18n";
11 import {
12 EVENT_MESSAGE,
13 EVENT_MESSAGE_CLEAR,
14 EVENT_MESSAGE_DELETE,
15 SW_PERIODIC_SYNC_EXTEND_TOKEN_TAG,
16 SW_WEBPUSH_EVENT_MESSAGE,
17 SW_WEBPUSH_EVENT_SUBSCRIPTION_EXPIRING,
18 } from "../src/app/events";
19
20 /**
21 * General docs for service workers and PWAs:
22 * https://vite-pwa-org.netlify.app/guide/
23 * https://developer.chrome.com/docs/workbox/
24 *
25 * This file uses the (event) => event.waitUntil(<promise>) pattern.
26 * This is because the event handler itself cannot be async, but
27 * the service worker needs to stay active while the promise completes.
28 */
29
30 const broadcastChannel = new BroadcastChannel("web-push-broadcast");
31
32 /**
33 * Handle a received web push message and show notification.
34 *
35 * Since the service worker cannot play a sound, we send a broadcast to the web app, which (if it is running)
36 * receives the broadcast and plays a sound (see web/src/app/WebPush.js).
37 */
38 const handlePushMessage = async (data) => {
39 const { subscription_id: subscriptionId, message } = data;
40
41 const db = await dbAsync();
42
43 console.log("[ServiceWorker] Message received", data);
44
45 // Look up subscription for baseUrl and topic
46 const subscription = await db.subscriptions.get(subscriptionId);
47 if (!subscription) {
48 console.log("[ServiceWorker] Subscription not found", subscriptionId);
49 handlePushUnknown(data);
50 return;
51 }
52
53 // NOTE: As soon as possible, to avoid this Safari error:
54 // > Push event handling completed without showing any notification via
55 // > ServiceWorkerRegistration.showNotification(). This may trigger removal of
56 // > the push subscription.
57 await self.registration.showNotification(
58 ...toNotificationParams({
59 message,
60 defaultTitle: message.topic,
61 topicRoute: new URL(message.topic, self.location.origin).toString(),
62 baseUrl: subscription.baseUrl,
63 topic: subscription.topic,
64 }),
65 );
66
67 // Delete existing notification with same sequence ID (if any)
68 const sequenceId = message.sequence_id || message.id;
69 if (sequenceId) {
70 await db.notifications.where({ subscriptionId, sequenceId }).delete();
71 }
72
73 // Add notification to database
74 await db.notifications.add({
75 ...messageWithSequenceId(message),
76 subscriptionId,
77 new: 1, // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
78 });
79
80 // Update subscription last message id (for ?since=... queries)
81 await db.subscriptions.update(subscriptionId, {
82 last: message.id,
83 });
84
85 // Update badge in PWA
86 const badgeCount = await db.notifications.where({ new: 1 }).count();
87 self.navigator.setAppBadge?.(badgeCount);
88
89 // Broadcast the message to potentially play a sound
90 broadcastChannel.postMessage(message);
91
92 await maybeExtendToken();
93 };
94
95 const refreshTokenThreshold = 1000 * 60 * 60; // 1 hour
96 const maybeExtendToken = async () => {
97 if (import.meta.env.DEV) {
98 console.warn("[ServiceWorker] Skipping token extension in development since no config.base_url exists");
99 return;
100 }
101
102 const token = await session.tokenAsync();
103 if (!token) {
104 console.debug("[ServiceWorker] No session token, skipping token extension");
105 return;
106 }
107
108 const lastExtendedAt = await session.lastExtendedAtAsync();
109 const now = Date.now();
110
111 if (lastExtendedAt && now - lastExtendedAt < refreshTokenThreshold) {
112 console.debug(`[ServiceWorker] Token extended ${Math.floor((now - lastExtendedAt) / 1000 / 60)} minutes ago, skipping`);
113 return;
114 }
115
116 console.log("[ServiceWorker] Extending user access token");
117
118 // duplicated from utils.js#accountTokenUrl since we can't import that here
119 // as long as there's mp3 and other incompatible imports there
120 const tokenUrl = `${config.base_url}/v1/account/token`;
121
122 try {
123 const response = await fetch(tokenUrl, {
124 method: "PATCH",
125 headers: {
126 Authorization: `Bearer ${token}`,
127 },
128 });
129
130 if (response.ok) {
131 await session.setLastExtendedAtAsync();
132 console.log(`[ServiceWorker] Token extended successfully`);
133 } else {
134 console.error(`[ServiceWorker] Failed to extend token: ${response.status} ${response.statusText}`);
135 }
136 } catch (e) {
137 console.error("[ServiceWorker] Failed to extend token", e);
138 }
139 };
140
141 /**
142 * Registers a periodic-sync listener for `extend_token` (see hooks.js).
143 * This extends the token regardless of whether the browser is open.
144 *
145 * CAVEATS:
146 * - Chromium-only
147 * - Only when the PWA is _installed_ (not just running in a browser tab)
148 * - Only when notifications are granted
149 */
150 self.addEventListener("periodicsync", (event) => {
151 if (event.tag === SW_PERIODIC_SYNC_EXTEND_TOKEN_TAG) {
152 console.log(`[ServiceWorker] Received periodicsync event "${SW_PERIODIC_SYNC_EXTEND_TOKEN_TAG}"`);
153 event.waitUntil(maybeExtendToken());
154 }
155 });
156
157 /**
158 * Handle a message_delete event: delete the notification from the database.
159 */
160 const handlePushMessageDelete = async (data) => {
161 const { subscription_id: subscriptionId, message } = data;
162 const db = await dbAsync();
163 console.log("[ServiceWorker] Deleting notification sequence", data);
164
165 // Look up subscription for baseUrl and topic
166 const subscription = await db.subscriptions.get(subscriptionId);
167 if (!subscription) {
168 console.log("[ServiceWorker] Subscription not found", subscriptionId);
169 return;
170 }
171
172 // Delete notification with the same sequence_id
173 const sequenceId = message.sequence_id;
174 if (sequenceId) {
175 await db.notifications.where({ subscriptionId, sequenceId }).delete();
176 }
177
178 // Close browser notification with matching tag (scoped by topic)
179 const tag = notificationTag(subscription.baseUrl, subscription.topic, message.sequence_id || message.id);
180 const notifications = await self.registration.getNotifications({ tag });
181 notifications.forEach((notification) => notification.close());
182
183 // Update subscription last message id (for ?since=... queries)
184 await db.subscriptions.update(subscriptionId, {
185 last: message.id,
186 });
187 };
188
189 /**
190 * Handle a message_clear event: clear/dismiss the notification.
191 */
192 const handlePushMessageClear = async (data) => {
193 const { subscription_id: subscriptionId, message } = data;
194 const db = await dbAsync();
195 console.log("[ServiceWorker] Marking notification as read", data);
196
197 // Look up subscription for baseUrl and topic
198 const subscription = await db.subscriptions.get(subscriptionId);
199 if (!subscription) {
200 console.log("[ServiceWorker] Subscription not found", subscriptionId);
201 return;
202 }
203
204 // Mark notification as read (set new = 0)
205 const sequenceId = message.sequence_id;
206 if (sequenceId) {
207 await db.notifications.where({ subscriptionId, sequenceId }).modify({ new: 0 });
208 }
209
210 // Close browser notification with matching tag (scoped by topic)
211 const tag = notificationTag(subscription.baseUrl, subscription.topic, message.sequence_id || message.id);
212 const notifications = await self.registration.getNotifications({ tag });
213 notifications.forEach((notification) => notification.close());
214
215 // Update subscription last message id (for ?since=... queries)
216 await db.subscriptions.update(subscriptionId, {
217 last: message.id,
218 });
219
220 // Update badge count
221 const badgeCount = await db.notifications.where({ new: 1 }).count();
222 self.navigator.setAppBadge?.(badgeCount);
223 };
224
225 /**
226 * Handle a received web push subscription expiring.
227 */
228 const handlePushSubscriptionExpiring = async (data) => {
229 const t = await initI18n();
230 console.log("[ServiceWorker] Handling incoming subscription expiring event", data);
231
232 await self.registration.showNotification(t("web_push_subscription_expiring_title"), {
233 body: t("web_push_subscription_expiring_body"),
234 icon,
235 data,
236 badge,
237 });
238 };
239
240 /**
241 * Handle unknown push message. We can't ignore the push, since
242 * permission can be revoked by the browser.
243 */
244 const handlePushUnknown = async (data) => {
245 const t = await initI18n();
246 console.log("[ServiceWorker] Unknown event received", data);
247
248 await self.registration.showNotification(t("web_push_unknown_notification_title"), {
249 body: t("web_push_unknown_notification_body"),
250 icon,
251 data,
252 badge,
253 });
254 };
255
256 /**
257 * Handle a received web push notification
258 * @param {object} data see server/types.go, type webPushPayload
259 */
260 const handlePush = async (data) => {
261 // This logic is (partially) duplicated in
262 // - Android: SubscriberService::onNotificationReceived()
263 // - Android: FirebaseService::onMessageReceived()
264 // - Web app: hooks.js:handleNotification()
265 // - Web app: sw.js:handleMessage(), sw.js:handleMessageClear(), ...
266
267 if (data.event === SW_WEBPUSH_EVENT_MESSAGE) {
268 const { message } = data;
269 if (message.event === EVENT_MESSAGE) {
270 return await handlePushMessage(data);
271 } else if (message.event === EVENT_MESSAGE_DELETE) {
272 return await handlePushMessageDelete(data);
273 } else if (message.event === EVENT_MESSAGE_CLEAR) {
274 return await handlePushMessageClear(data);
275 }
276 } else if (data.event === SW_WEBPUSH_EVENT_SUBSCRIPTION_EXPIRING) {
277 return await handlePushSubscriptionExpiring(data);
278 }
279
280 return await handlePushUnknown(data);
281 };
282
283 /**
284 * Handle a user clicking on the displayed notification from `showNotification`.
285 * This is also called when the user clicks on an action button.
286 */
287 const handleClick = async (event) => {
288 const t = await initI18n();
289
290 const clients = await self.clients.matchAll({ type: "window" });
291 const rootUrl = new URL(self.location.origin);
292 const rootClient = clients.find((client) => client.url === rootUrl.toString());
293 const fallbackClient = clients[0];
294
295 if (!event.notification.data?.message) {
296 // e.g. something other than a message, e.g. a subscription_expiring event
297 // simply open the web app on the root route (/)
298 if (rootClient) {
299 rootClient.focus();
300 } else if (fallbackClient) {
301 fallbackClient.focus();
302 fallbackClient.navigate(rootUrl.toString());
303 } else {
304 self.clients.openWindow(rootUrl);
305 }
306 event.notification.close();
307 } else {
308 const { message, topicRoute } = event.notification.data;
309
310 if (event.action) {
311 const action = event.notification.data.message.actions.find(({ label }) => event.action === label);
312
313 // Helper to clear notification and mark as read
314 const clearNotification = async () => {
315 event.notification.close();
316 const { subscriptionId, message: msg } = event.notification.data;
317 const seqId = msg.sequence_id || msg.id;
318 if (subscriptionId && seqId) {
319 const db = await dbAsync();
320 await db.notifications.where({ subscriptionId, sequenceId: seqId }).modify({ new: 0 });
321 const badgeCount = await db.notifications.where({ new: 1 }).count();
322 self.navigator.setAppBadge?.(badgeCount);
323 }
324 };
325
326 if (action.action === ACTION_VIEW) {
327 self.clients.openWindow(action.url);
328 if (action.clear) {
329 await clearNotification();
330 }
331 } else if (action.action === ACTION_HTTP) {
332 try {
333 const response = await fetch(action.url, {
334 method: action.method ?? "POST",
335 headers: action.headers ?? {},
336 body: action.body,
337 });
338
339 if (!response.ok) {
340 throw new Error(`HTTP ${response.status} ${response.statusText}`);
341 }
342
343 // Only clear on success
344 if (action.clear) {
345 await clearNotification();
346 }
347 } catch (e) {
348 console.error("[ServiceWorker] Error performing http action", e);
349 self.registration.showNotification(`${t("notifications_actions_failed_notification")}: ${action.label} (${action.action})`, {
350 body: e.message,
351 icon,
352 badge,
353 });
354 }
355 }
356 } else if (message.click) {
357 self.clients.openWindow(message.click);
358
359 event.notification.close();
360 } else {
361 // If no action was clicked, and the message doesn't have a click url:
362 // - first try focus an open tab on the `/:topic` route
363 // - if not, use an open tab on the root route (`/`) and navigate to the topic
364 // - if not, use whichever tab we have open and navigate to the topic
365 // - finally, open a new tab focused on the topic
366
367 const topicClient = clients.find((client) => client.url === topicRoute);
368
369 if (topicClient) {
370 topicClient.focus();
371 } else if (rootClient) {
372 rootClient.focus();
373 rootClient.navigate(topicRoute);
374 } else if (fallbackClient) {
375 fallbackClient.focus();
376 fallbackClient.navigate(topicRoute);
377 } else {
378 self.clients.openWindow(topicRoute);
379 }
380
381 event.notification.close();
382 }
383 }
384 };
385
386 self.addEventListener("install", () => {
387 console.log("[ServiceWorker] Installed");
388 self.skipWaiting();
389 });
390
391 self.addEventListener("activate", () => {
392 console.log("[ServiceWorker] Activated");
393 self.skipWaiting();
394 });
395
396 // There's no good way to test this, and Chrome doesn't seem to implement this,
397 // so leaving it for now
398 self.addEventListener("pushsubscriptionchange", (event) => {
399 console.log("[ServiceWorker] PushSubscriptionChange");
400 console.log(event);
401 });
402
403 self.addEventListener("push", (event) => {
404 const data = event.data.json();
405 console.log("[ServiceWorker] Received Web Push Event", { event, data });
406 event.waitUntil(handlePush(data));
407 });
408
409 self.addEventListener("notificationclick", (event) => {
410 console.log("[ServiceWorker] NotificationClick");
411 event.waitUntil(handleClick(event));
412 });
413
414 // See https://vite-pwa-org.netlify.app/guide/inject-manifest.html#service-worker-code
415 // self.__WB_MANIFEST is the workbox injection point that injects the manifest of the
416 // vite dist files and their revision ids, for example:
417 // [{"revision":"aaabbbcccdddeeefff12345","url":"/index.html"},...]
418 precacheAndRoute(
419 // eslint-disable-next-line no-underscore-dangle
420 self.__WB_MANIFEST,
421 );
422
423 // Claim all open windows
424 clientsClaim();
425
426 // Delete any cached old dist files from previous service worker versions
427 cleanupOutdatedCaches();
428
429 if (!import.meta.env.DEV) {
430 // we need the app_root setting, so we import the config.js file from the go server
431 // this does NOT include the same base_url as the web app running in a window,
432 // since we don't have access to `window` like in `src/app/config.js`
433 self.importScripts("/config.js");
434
435 // this is the fallback single-page-app route, matching vite.config.js PWA config,
436 // and is served by the go web server. It is needed for the single-page-app to work.
437 // https://developer.chrome.com/docs/workbox/modules/workbox-routing/#how-to-register-a-navigation-route
438 registerRoute(
439 new NavigationRoute(createHandlerBoundToURL("/app.html"), {
440 allowlist: [
441 // the app root itself, could be /, or not
442 new RegExp(`^${config.app_root}$`),
443 ],
444 }),
445 );
446
447 // the manifest excludes config.js (see vite.config.js) since the dist-file differs from the
448 // actual config served by the go server. this adds it back with `NetworkFirst`, so that the
449 // most recent config from the go server is cached, but the app still works if the network
450 // is unavailable. this is important since there's no "refresh" button in the installed pwa
451 // to force a reload.
452 registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
453 }