sw.js 11 KB

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