sw.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 { toNotificationParams, icon, badge } from "../src/app/notificationUtils";
  8. import initI18n from "../src/app/i18n";
  9. import { messageWithSID } from "../src/app/utils";
  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. const addNotification = async ({ subscriptionId, message }) => {
  21. const db = await dbAsync();
  22. // Note: SubscriptionManager duplicates this logic, so if you change it here, change it there too
  23. // Add notification to database
  24. await db.notifications.add({
  25. ...messageWithSID(message),
  26. subscriptionId,
  27. new: 1, // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  28. });
  29. // Update subscription last message id (for ?since=... queries)
  30. await db.subscriptions.update(subscriptionId, {
  31. last: message.id,
  32. });
  33. const badgeCount = await db.notifications.where({ new: 1 }).count();
  34. console.log("[ServiceWorker] Setting new app badge count", { badgeCount });
  35. self.navigator.setAppBadge?.(badgeCount);
  36. };
  37. /**
  38. * Handle a received web push message and show notification.
  39. *
  40. * Since the service worker cannot play a sound, we send a broadcast to the web app, which (if it is running)
  41. * receives the broadcast and plays a sound (see web/src/app/WebPush.js).
  42. */
  43. const handlePushMessage = async (data) => {
  44. const { subscription_id: subscriptionId, message } = data;
  45. // Add notification to database
  46. await addNotification({ subscriptionId, message });
  47. // Don't show a notification for deleted messages
  48. if (message.deleted) {
  49. return;
  50. }
  51. // Broadcast the message to potentially play a sound
  52. broadcastChannel.postMessage(message);
  53. await self.registration.showNotification(
  54. ...toNotificationParams({
  55. subscriptionId,
  56. message,
  57. defaultTitle: message.topic,
  58. topicRoute: new URL(message.topic, self.location.origin).toString(),
  59. })
  60. );
  61. };
  62. /**
  63. * Handle a received web push subscription expiring.
  64. */
  65. const handlePushSubscriptionExpiring = async (data) => {
  66. const t = await initI18n();
  67. await self.registration.showNotification(t("web_push_subscription_expiring_title"), {
  68. body: t("web_push_subscription_expiring_body"),
  69. icon,
  70. data,
  71. badge,
  72. });
  73. };
  74. /**
  75. * Handle unknown push message. We can't ignore the push, since
  76. * permission can be revoked by the browser.
  77. */
  78. const handlePushUnknown = async (data) => {
  79. const t = await initI18n();
  80. await self.registration.showNotification(t("web_push_unknown_notification_title"), {
  81. body: t("web_push_unknown_notification_body"),
  82. icon,
  83. data,
  84. badge,
  85. });
  86. };
  87. /**
  88. * Handle a received web push notification
  89. * @param {object} data see server/types.go, type webPushPayload
  90. */
  91. const handlePush = async (data) => {
  92. if (data.event === "message") {
  93. await handlePushMessage(data);
  94. } else if (data.event === "subscription_expiring") {
  95. await handlePushSubscriptionExpiring(data);
  96. } else {
  97. await handlePushUnknown(data);
  98. }
  99. };
  100. /**
  101. * Handle a user clicking on the displayed notification from `showNotification`.
  102. * This is also called when the user clicks on an action button.
  103. */
  104. const handleClick = async (event) => {
  105. const t = await initI18n();
  106. const clients = await self.clients.matchAll({ type: "window" });
  107. const rootUrl = new URL(self.location.origin);
  108. const rootClient = clients.find((client) => client.url === rootUrl.toString());
  109. // perhaps open on another topic
  110. const fallbackClient = clients[0];
  111. if (!event.notification.data?.message) {
  112. // e.g. something other than a message, e.g. a subscription_expiring event
  113. // simply open the web app on the root route (/)
  114. if (rootClient) {
  115. rootClient.focus();
  116. } else if (fallbackClient) {
  117. fallbackClient.focus();
  118. fallbackClient.navigate(rootUrl.toString());
  119. } else {
  120. self.clients.openWindow(rootUrl);
  121. }
  122. event.notification.close();
  123. } else {
  124. const { message, topicRoute } = event.notification.data;
  125. if (event.action) {
  126. const action = event.notification.data.message.actions.find(({ label }) => event.action === label);
  127. if (action.action === "view") {
  128. self.clients.openWindow(action.url);
  129. } else if (action.action === "http") {
  130. try {
  131. const response = await fetch(action.url, {
  132. method: action.method ?? "POST",
  133. headers: action.headers ?? {},
  134. body: action.body,
  135. });
  136. if (!response.ok) {
  137. throw new Error(`HTTP ${response.status} ${response.statusText}`);
  138. }
  139. } catch (e) {
  140. console.error("[ServiceWorker] Error performing http action", e);
  141. self.registration.showNotification(`${t("notifications_actions_failed_notification")}: ${action.label} (${action.action})`, {
  142. body: e.message,
  143. icon,
  144. badge,
  145. });
  146. }
  147. }
  148. if (action.clear) {
  149. event.notification.close();
  150. }
  151. } else if (message.click) {
  152. self.clients.openWindow(message.click);
  153. event.notification.close();
  154. } else {
  155. // If no action was clicked, and the message doesn't have a click url:
  156. // - first try focus an open tab on the `/:topic` route
  157. // - if not, use an open tab on the root route (`/`) and navigate to the topic
  158. // - if not, use whichever tab we have open and navigate to the topic
  159. // - finally, open a new tab focused on the topic
  160. const topicClient = clients.find((client) => client.url === topicRoute);
  161. if (topicClient) {
  162. topicClient.focus();
  163. } else if (rootClient) {
  164. rootClient.focus();
  165. rootClient.navigate(topicRoute);
  166. } else if (fallbackClient) {
  167. fallbackClient.focus();
  168. fallbackClient.navigate(topicRoute);
  169. } else {
  170. self.clients.openWindow(topicRoute);
  171. }
  172. event.notification.close();
  173. }
  174. }
  175. };
  176. self.addEventListener("install", () => {
  177. console.log("[ServiceWorker] Installed");
  178. self.skipWaiting();
  179. });
  180. self.addEventListener("activate", () => {
  181. console.log("[ServiceWorker] Activated");
  182. self.skipWaiting();
  183. });
  184. // There's no good way to test this, and Chrome doesn't seem to implement this,
  185. // so leaving it for now
  186. self.addEventListener("pushsubscriptionchange", (event) => {
  187. console.log("[ServiceWorker] PushSubscriptionChange");
  188. console.log(event);
  189. });
  190. self.addEventListener("push", (event) => {
  191. const data = event.data.json();
  192. console.log("[ServiceWorker] Received Web Push Event", { event, data });
  193. event.waitUntil(handlePush(data));
  194. });
  195. self.addEventListener("notificationclick", (event) => {
  196. console.log("[ServiceWorker] NotificationClick");
  197. event.waitUntil(handleClick(event));
  198. });
  199. // See https://vite-pwa-org.netlify.app/guide/inject-manifest.html#service-worker-code
  200. // self.__WB_MANIFEST is the workbox injection point that injects the manifest of the
  201. // vite dist files and their revision ids, for example:
  202. // [{"revision":"aaabbbcccdddeeefff12345","url":"/index.html"},...]
  203. precacheAndRoute(
  204. // eslint-disable-next-line no-underscore-dangle
  205. self.__WB_MANIFEST
  206. );
  207. // Claim all open windows
  208. clientsClaim();
  209. // Delete any cached old dist files from previous service worker versions
  210. cleanupOutdatedCaches();
  211. if (!import.meta.env.DEV) {
  212. // we need the app_root setting, so we import the config.js file from the go server
  213. // this does NOT include the same base_url as the web app running in a window,
  214. // since we don't have access to `window` like in `src/app/config.js`
  215. self.importScripts("/config.js");
  216. // this is the fallback single-page-app route, matching vite.config.js PWA config,
  217. // and is served by the go web server. It is needed for the single-page-app to work.
  218. // https://developer.chrome.com/docs/workbox/modules/workbox-routing/#how-to-register-a-navigation-route
  219. registerRoute(
  220. new NavigationRoute(createHandlerBoundToURL("/app.html"), {
  221. allowlist: [
  222. // the app root itself, could be /, or not
  223. new RegExp(`^${config.app_root}$`),
  224. ],
  225. })
  226. );
  227. // the manifest excludes config.js (see vite.config.js) since the dist-file differs from the
  228. // actual config served by the go server. this adds it back with `NetworkFirst`, so that the
  229. // most recent config from the go server is cached, but the app still works if the network
  230. // is unavailable. this is important since there's no "refresh" button in the installed pwa
  231. // to force a reload.
  232. registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
  233. }