sw.js 11 KB

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