sw.js 9.2 KB

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