sw.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 { ACTION_COPY, ACTION_HTTP, ACTION_VIEW } from "../src/app/actions";
  8. import { badge, icon, messageWithSequenceId, notificationTag, toNotificationParams } from "../src/app/notificationUtils";
  9. import initI18n from "../src/app/i18n";
  10. import {
  11. EVENT_MESSAGE,
  12. EVENT_MESSAGE_CLEAR,
  13. EVENT_MESSAGE_DELETE,
  14. WEBPUSH_EVENT_MESSAGE,
  15. WEBPUSH_EVENT_SUBSCRIPTION_EXPIRING,
  16. } from "../src/app/events";
  17. /**
  18. * General docs for service workers and PWAs:
  19. * https://vite-pwa-org.netlify.app/guide/
  20. * https://developer.chrome.com/docs/workbox/
  21. *
  22. * This file uses the (event) => event.waitUntil(<promise>) pattern.
  23. * This is because the event handler itself cannot be async, but
  24. * the service worker needs to stay active while the promise completes.
  25. */
  26. const broadcastChannel = new BroadcastChannel("web-push-broadcast");
  27. /**
  28. * Handle a received web push message and show notification.
  29. *
  30. * Since the service worker cannot play a sound, we send a broadcast to the web app, which (if it is running)
  31. * receives the broadcast and plays a sound (see web/src/app/WebPush.js).
  32. */
  33. const handlePushMessage = async (data) => {
  34. const { subscription_id: subscriptionId, message } = data;
  35. const db = await dbAsync();
  36. console.log("[ServiceWorker] Message received", data);
  37. // Look up subscription for baseUrl and topic
  38. const subscription = await db.subscriptions.get(subscriptionId);
  39. if (!subscription) {
  40. console.log("[ServiceWorker] Subscription not found", subscriptionId);
  41. return;
  42. }
  43. // Delete existing notification with same sequence ID (if any)
  44. const sequenceId = message.sequence_id || message.id;
  45. if (sequenceId) {
  46. await db.notifications.where({ subscriptionId, sequenceId }).delete();
  47. }
  48. // Add notification to database
  49. await db.notifications.add({
  50. ...messageWithSequenceId(message),
  51. subscriptionId,
  52. new: 1, // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  53. });
  54. // Update subscription last message id (for ?since=... queries)
  55. await db.subscriptions.update(subscriptionId, {
  56. last: message.id,
  57. });
  58. // Update badge in PWA
  59. const badgeCount = await db.notifications.where({ new: 1 }).count();
  60. self.navigator.setAppBadge?.(badgeCount);
  61. // Broadcast the message to potentially play a sound
  62. broadcastChannel.postMessage(message);
  63. await self.registration.showNotification(
  64. ...toNotificationParams({
  65. message,
  66. defaultTitle: message.topic,
  67. topicRoute: new URL(message.topic, self.location.origin).toString(),
  68. baseUrl: subscription.baseUrl,
  69. topic: subscription.topic,
  70. })
  71. );
  72. };
  73. /**
  74. * Handle a message_delete event: delete the notification from the database.
  75. */
  76. const handlePushMessageDelete = async (data) => {
  77. const { subscription_id: subscriptionId, message } = data;
  78. const db = await dbAsync();
  79. console.log("[ServiceWorker] Deleting notification sequence", data);
  80. // Look up subscription for baseUrl and topic
  81. const subscription = await db.subscriptions.get(subscriptionId);
  82. if (!subscription) {
  83. console.log("[ServiceWorker] Subscription not found", subscriptionId);
  84. return;
  85. }
  86. // Delete notification with the same sequence_id
  87. const sequenceId = message.sequence_id;
  88. if (sequenceId) {
  89. await db.notifications.where({ subscriptionId, sequenceId }).delete();
  90. }
  91. // Close browser notification with matching tag (scoped by topic)
  92. const tag = notificationTag(subscription.baseUrl, subscription.topic, message.sequence_id || message.id);
  93. const notifications = await self.registration.getNotifications({ tag });
  94. notifications.forEach((notification) => notification.close());
  95. // Update subscription last message id (for ?since=... queries)
  96. await db.subscriptions.update(subscriptionId, {
  97. last: message.id,
  98. });
  99. };
  100. /**
  101. * Handle a message_clear event: clear/dismiss the notification.
  102. */
  103. const handlePushMessageClear = async (data) => {
  104. const { subscription_id: subscriptionId, message } = data;
  105. const db = await dbAsync();
  106. console.log("[ServiceWorker] Marking notification as read", data);
  107. // Look up subscription for baseUrl and topic
  108. const subscription = await db.subscriptions.get(subscriptionId);
  109. if (!subscription) {
  110. console.log("[ServiceWorker] Subscription not found", subscriptionId);
  111. return;
  112. }
  113. // Mark notification as read (set new = 0)
  114. const sequenceId = message.sequence_id;
  115. if (sequenceId) {
  116. await db.notifications.where({ subscriptionId, sequenceId }).modify({ new: 0 });
  117. }
  118. // Close browser notification with matching tag (scoped by topic)
  119. const tag = notificationTag(subscription.baseUrl, subscription.topic, message.sequence_id || message.id);
  120. const notifications = await self.registration.getNotifications({ tag });
  121. notifications.forEach((notification) => notification.close());
  122. // Update subscription last message id (for ?since=... queries)
  123. await db.subscriptions.update(subscriptionId, {
  124. last: message.id,
  125. });
  126. // Update badge count
  127. const badgeCount = await db.notifications.where({ new: 1 }).count();
  128. self.navigator.setAppBadge?.(badgeCount);
  129. };
  130. /**
  131. * Handle a received web push subscription expiring.
  132. */
  133. const handlePushSubscriptionExpiring = async (data) => {
  134. const t = await initI18n();
  135. console.log("[ServiceWorker] Handling incoming subscription expiring event", data);
  136. await self.registration.showNotification(t("web_push_subscription_expiring_title"), {
  137. body: t("web_push_subscription_expiring_body"),
  138. icon,
  139. data,
  140. badge,
  141. });
  142. };
  143. /**
  144. * Handle unknown push message. We can't ignore the push, since
  145. * permission can be revoked by the browser.
  146. */
  147. const handlePushUnknown = async (data) => {
  148. const t = await initI18n();
  149. console.log("[ServiceWorker] Unknown event received", data);
  150. await self.registration.showNotification(t("web_push_unknown_notification_title"), {
  151. body: t("web_push_unknown_notification_body"),
  152. icon,
  153. data,
  154. badge,
  155. });
  156. };
  157. /**
  158. * Handle a received web push notification
  159. * @param {object} data see server/types.go, type webPushPayload
  160. */
  161. const handlePush = async (data) => {
  162. // This logic is (partially) duplicated in
  163. // - Android: SubscriberService::onNotificationReceived()
  164. // - Android: FirebaseService::onMessageReceived()
  165. // - Web app: hooks.js:handleNotification()
  166. // - Web app: sw.js:handleMessage(), sw.js:handleMessageClear(), ...
  167. if (data.event === WEBPUSH_EVENT_MESSAGE) {
  168. const { message } = data;
  169. if (message.event === EVENT_MESSAGE) {
  170. return await handlePushMessage(data);
  171. } else if (message.event === EVENT_MESSAGE_DELETE) {
  172. return await handlePushMessageDelete(data);
  173. } else if (message.event === EVENT_MESSAGE_CLEAR) {
  174. return await handlePushMessageClear(data);
  175. }
  176. } else if (data.event === WEBPUSH_EVENT_SUBSCRIPTION_EXPIRING) {
  177. return await handlePushSubscriptionExpiring(data);
  178. }
  179. return await handlePushUnknown(data);
  180. };
  181. /**
  182. * Handle a user clicking on the displayed notification from `showNotification`.
  183. * This is also called when the user clicks on an action button.
  184. */
  185. const handleClick = async (event) => {
  186. const t = await initI18n();
  187. const clients = await self.clients.matchAll({ type: "window" });
  188. const rootUrl = new URL(self.location.origin);
  189. const rootClient = clients.find((client) => client.url === rootUrl.toString());
  190. const fallbackClient = clients[0];
  191. if (!event.notification.data?.message) {
  192. // e.g. something other than a message, e.g. a subscription_expiring event
  193. // simply open the web app on the root route (/)
  194. if (rootClient) {
  195. rootClient.focus();
  196. } else if (fallbackClient) {
  197. fallbackClient.focus();
  198. fallbackClient.navigate(rootUrl.toString());
  199. } else {
  200. self.clients.openWindow(rootUrl);
  201. }
  202. event.notification.close();
  203. } else {
  204. const { message, topicRoute } = event.notification.data;
  205. if (event.action) {
  206. const action = event.notification.data.message.actions.find(({ label }) => event.action === label);
  207. // Helper to clear notification and mark as read
  208. const clearNotification = async () => {
  209. event.notification.close();
  210. const { subscriptionId, message: msg } = event.notification.data;
  211. const seqId = msg.sequence_id || msg.id;
  212. if (subscriptionId && seqId) {
  213. const db = await dbAsync();
  214. await db.notifications.where({ subscriptionId, sequenceId: seqId }).modify({ new: 0 });
  215. const badgeCount = await db.notifications.where({ new: 1 }).count();
  216. self.navigator.setAppBadge?.(badgeCount);
  217. }
  218. };
  219. if (action.action === ACTION_VIEW) {
  220. self.clients.openWindow(action.url);
  221. if (action.clear) {
  222. await clearNotification();
  223. }
  224. } else if (action.action === ACTION_COPY) {
  225. try {
  226. // Service worker can't access the clipboard API directly, so we try to
  227. // open a focused client and use it, or fall back to opening a window
  228. const allClients = await self.clients.matchAll({ type: "window" });
  229. const focusedClient = allClients.find((c) => c.focused) || allClients[0];
  230. if (focusedClient) {
  231. focusedClient.postMessage({ type: "copy", value: action.value });
  232. }
  233. if (action.clear) {
  234. await clearNotification();
  235. }
  236. } catch (e) {
  237. console.error("[ServiceWorker] Error performing copy action", e);
  238. self.registration.showNotification(`${t("notifications_actions_failed_notification")}: ${action.label} (${action.action})`, {
  239. body: e.message,
  240. icon,
  241. badge,
  242. });
  243. }
  244. } else if (action.action === ACTION_HTTP) {
  245. try {
  246. const response = await fetch(action.url, {
  247. method: action.method ?? "POST",
  248. headers: action.headers ?? {},
  249. body: action.body,
  250. });
  251. if (!response.ok) {
  252. throw new Error(`HTTP ${response.status} ${response.statusText}`);
  253. }
  254. // Only clear on success
  255. if (action.clear) {
  256. await clearNotification();
  257. }
  258. } catch (e) {
  259. console.error("[ServiceWorker] Error performing http action", e);
  260. self.registration.showNotification(`${t("notifications_actions_failed_notification")}: ${action.label} (${action.action})`, {
  261. body: e.message,
  262. icon,
  263. badge,
  264. });
  265. }
  266. }
  267. } else if (message.click) {
  268. self.clients.openWindow(message.click);
  269. event.notification.close();
  270. } else {
  271. // If no action was clicked, and the message doesn't have a click url:
  272. // - first try focus an open tab on the `/:topic` route
  273. // - if not, use an open tab on the root route (`/`) and navigate to the topic
  274. // - if not, use whichever tab we have open and navigate to the topic
  275. // - finally, open a new tab focused on the topic
  276. const topicClient = clients.find((client) => client.url === topicRoute);
  277. if (topicClient) {
  278. topicClient.focus();
  279. } else if (rootClient) {
  280. rootClient.focus();
  281. rootClient.navigate(topicRoute);
  282. } else if (fallbackClient) {
  283. fallbackClient.focus();
  284. fallbackClient.navigate(topicRoute);
  285. } else {
  286. self.clients.openWindow(topicRoute);
  287. }
  288. event.notification.close();
  289. }
  290. }
  291. };
  292. self.addEventListener("install", () => {
  293. console.log("[ServiceWorker] Installed");
  294. self.skipWaiting();
  295. });
  296. self.addEventListener("activate", () => {
  297. console.log("[ServiceWorker] Activated");
  298. self.skipWaiting();
  299. });
  300. // There's no good way to test this, and Chrome doesn't seem to implement this,
  301. // so leaving it for now
  302. self.addEventListener("pushsubscriptionchange", (event) => {
  303. console.log("[ServiceWorker] PushSubscriptionChange");
  304. console.log(event);
  305. });
  306. self.addEventListener("push", (event) => {
  307. const data = event.data.json();
  308. console.log("[ServiceWorker] Received Web Push Event", { event, data });
  309. event.waitUntil(handlePush(data));
  310. });
  311. self.addEventListener("notificationclick", (event) => {
  312. console.log("[ServiceWorker] NotificationClick");
  313. event.waitUntil(handleClick(event));
  314. });
  315. // See https://vite-pwa-org.netlify.app/guide/inject-manifest.html#service-worker-code
  316. // self.__WB_MANIFEST is the workbox injection point that injects the manifest of the
  317. // vite dist files and their revision ids, for example:
  318. // [{"revision":"aaabbbcccdddeeefff12345","url":"/index.html"},...]
  319. precacheAndRoute(
  320. // eslint-disable-next-line no-underscore-dangle
  321. self.__WB_MANIFEST
  322. );
  323. // Claim all open windows
  324. clientsClaim();
  325. // Delete any cached old dist files from previous service worker versions
  326. cleanupOutdatedCaches();
  327. if (!import.meta.env.DEV) {
  328. // we need the app_root setting, so we import the config.js file from the go server
  329. // this does NOT include the same base_url as the web app running in a window,
  330. // since we don't have access to `window` like in `src/app/config.js`
  331. self.importScripts("/config.js");
  332. // this is the fallback single-page-app route, matching vite.config.js PWA config,
  333. // and is served by the go web server. It is needed for the single-page-app to work.
  334. // https://developer.chrome.com/docs/workbox/modules/workbox-routing/#how-to-register-a-navigation-route
  335. registerRoute(
  336. new NavigationRoute(createHandlerBoundToURL("/app.html"), {
  337. allowlist: [
  338. // the app root itself, could be /, or not
  339. new RegExp(`^${config.app_root}$`),
  340. ],
  341. })
  342. );
  343. // the manifest excludes config.js (see vite.config.js) since the dist-file differs from the
  344. // actual config served by the go server. this adds it back with `NetworkFirst`, so that the
  345. // most recent config from the go server is cached, but the app still works if the network
  346. // is unavailable. this is important since there's no "refresh" button in the installed pwa
  347. // to force a reload.
  348. registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
  349. }