sw.js 8.8 KB

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