sw.js 7.6 KB

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