sw.js 13 KB

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