sw.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 { dbAsync } from "../src/app/db";
  6. import { formatMessage, formatTitleWithDefault } from "../src/app/notificationUtils";
  7. /**
  8. * General docs for service workers and PWAs:
  9. * https://vite-pwa-org.netlify.app/guide/
  10. * https://developer.chrome.com/docs/workbox/
  11. *
  12. * This file uses the (event) => event.waitUntil(<promise>) pattern.
  13. * This is because the event handler itself cannot be async, but
  14. * the service worker needs to stay active while the promise completes.
  15. */
  16. const broadcastChannel = new BroadcastChannel("web-push-broadcast");
  17. const isImage = (filenameOrUrl) => filenameOrUrl?.match(/\.(png|jpe?g|gif|webp)$/i) ?? false;
  18. const addNotification = async (data) => {
  19. const db = await dbAsync();
  20. const { subscription_id: subscriptionId, message } = data;
  21. await db.notifications.add({
  22. ...message,
  23. subscriptionId,
  24. // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  25. new: 1,
  26. });
  27. await db.subscriptions.update(subscriptionId, {
  28. last: message.id,
  29. });
  30. const badgeCount = await db.notifications.where({ new: 1 }).count();
  31. console.log("[ServiceWorker] Setting new app badge count", { badgeCount });
  32. self.navigator.setAppBadge?.(badgeCount);
  33. };
  34. const showNotification = (data) => {
  35. const { subscription_id: subscriptionId, message } = data;
  36. // Please update the desktop notification in Notifier.js to match any changes here
  37. const image = isImage(message.attachment?.name) ? message.attachment.url : undefined;
  38. self.registration.showNotification(formatTitleWithDefault(message, message.topic), {
  39. tag: subscriptionId,
  40. body: formatMessage(message),
  41. icon: image ?? "/static/images/ntfy.png",
  42. image,
  43. data,
  44. timestamp: message.time * 1_000,
  45. actions: message.actions
  46. ?.filter(({ action }) => action === "view" || action === "http")
  47. .map(({ label }) => ({
  48. action: label,
  49. title: label,
  50. })),
  51. });
  52. };
  53. /**
  54. * Handle a received web push notification
  55. * @param {object} data see server/types.go, type webPushPayload
  56. */
  57. const handlePush = async (data) => {
  58. if (data.event === "subscription_expiring") {
  59. await self.registration.showNotification("Notifications will be paused", {
  60. body: "Open ntfy to continue receiving notifications",
  61. icon: "/static/images/ntfy.png",
  62. data,
  63. });
  64. } else if (data.event === "message") {
  65. // see: web/src/app/WebPush.js
  66. // the service worker cannot play a sound, so if the web app
  67. // is running, it receives the broadcast and plays it.
  68. broadcastChannel.postMessage(data.message);
  69. await addNotification(data);
  70. await showNotification(data);
  71. } else {
  72. // We can't ignore the push, since permission can be revoked by the browser
  73. await self.registration.showNotification("Unknown notification received from server", {
  74. body: "You may need to update ntfy by opening the web app",
  75. icon: "/static/images/ntfy.png",
  76. data,
  77. });
  78. }
  79. };
  80. /**
  81. * Handle a user clicking on the displayed notification from `showNotification`
  82. * This is also called when the user clicks on an action button
  83. */
  84. const handleClick = async (event) => {
  85. const clients = await self.clients.matchAll({ type: "window" });
  86. const rootUrl = new URL(self.location.origin);
  87. const rootClient = clients.find((client) => client.url === rootUrl.toString());
  88. if (event.notification.data?.event !== "message") {
  89. // e.g. subscription_expiring event, simply open the web app on the root route (/)
  90. if (rootClient) {
  91. rootClient.focus();
  92. } else {
  93. self.clients.openWindow(rootUrl);
  94. }
  95. event.notification.close();
  96. } else {
  97. const { message } = event.notification.data;
  98. if (event.action) {
  99. const action = event.notification.data.message.actions.find(({ label }) => event.action === label);
  100. if (action.action === "view") {
  101. self.clients.openWindow(action.url);
  102. } else if (action.action === "http") {
  103. try {
  104. const response = await fetch(action.url, {
  105. method: action.method ?? "POST",
  106. headers: action.headers ?? {},
  107. body: action.body,
  108. });
  109. if (!response.ok) {
  110. throw new Error(`HTTP ${response.status} ${response.statusText}`);
  111. }
  112. } catch (e) {
  113. console.error("[ServiceWorker] Error performing http action", e);
  114. self.registration.showNotification(`Unsuccessful action ${action.label} (${action.action})`, {
  115. body: e.message,
  116. });
  117. }
  118. }
  119. if (action.clear) {
  120. event.notification.close();
  121. }
  122. } else if (message.click) {
  123. self.clients.openWindow(message.click);
  124. event.notification.close();
  125. } else {
  126. // If no action was clicked, and the message doesn't have a click url:
  127. // - first try focus an open tab on the `/:topic` route
  128. // - if not, an open tab on the root route (`/`)
  129. // - if no ntfy window is open, open a new tab on the `/:topic` route
  130. const topicUrl = new URL(message.topic, self.location.origin);
  131. const topicClient = clients.find((client) => client.url === topicUrl.toString());
  132. if (topicClient) {
  133. topicClient.focus();
  134. } else if (rootClient) {
  135. rootClient.focus();
  136. } else {
  137. self.clients.openWindow(topicUrl);
  138. }
  139. event.notification.close();
  140. }
  141. }
  142. };
  143. self.addEventListener("install", () => {
  144. console.log("[ServiceWorker] Installed");
  145. self.skipWaiting();
  146. });
  147. self.addEventListener("activate", () => {
  148. console.log("[ServiceWorker] Activated");
  149. self.skipWaiting();
  150. });
  151. // There's no good way to test this, and Chrome doesn't seem to implement this,
  152. // so leaving it for now
  153. self.addEventListener("pushsubscriptionchange", (event) => {
  154. console.log("[ServiceWorker] PushSubscriptionChange");
  155. console.log(event);
  156. });
  157. self.addEventListener("push", (event) => {
  158. const data = event.data.json();
  159. console.log("[ServiceWorker] Received Web Push Event", { event, data });
  160. event.waitUntil(handlePush(data));
  161. });
  162. self.addEventListener("notificationclick", (event) => {
  163. console.log("[ServiceWorker] NotificationClick");
  164. event.waitUntil(handleClick(event));
  165. });
  166. // see https://vite-pwa-org.netlify.app/guide/inject-manifest.html#service-worker-code
  167. // self.__WB_MANIFEST is the workbox injection point that injects the manifest of the
  168. // vite dist files and their revision ids, for example:
  169. // [{"revision":"aaabbbcccdddeeefff12345","url":"/index.html"},...]
  170. precacheAndRoute(
  171. // eslint-disable-next-line no-underscore-dangle
  172. self.__WB_MANIFEST
  173. );
  174. // delete any cached old dist files from previous service worker versions
  175. cleanupOutdatedCaches();
  176. if (import.meta.env.MODE !== "development") {
  177. // since the manifest only includes `/index.html`, this manually adds the root route `/`
  178. registerRoute(new NavigationRoute(createHandlerBoundToURL("/")));
  179. // the manifest excludes config.js (see vite.config.js) since the dist-file differs from the
  180. // actual config served by the go server. this adds it back with `NetworkFirst`, so that the
  181. // most recent config from the go server is cached, but the app still works if the network
  182. // is unavailable. this is important since there's no "refresh" button in the installed pwa
  183. // to force a reload.
  184. registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
  185. }