sw.js 7.5 KB

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