sw.js 12 KB

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