sw.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 { getDbAsync } from "../src/app/getDb";
  6. import { formatMessage, formatTitleWithDefault } from "../src/app/notificationUtils";
  7. // See WebPushWorker, this is to play a sound on supported browsers,
  8. // if the app is in the foreground
  9. const broadcastChannel = new BroadcastChannel("web-push-broadcast");
  10. self.addEventListener("install", () => {
  11. console.log("[ServiceWorker] Installed");
  12. self.skipWaiting();
  13. });
  14. self.addEventListener("activate", () => {
  15. console.log("[ServiceWorker] Activated");
  16. self.skipWaiting();
  17. });
  18. // There's no good way to test this, and Chrome doesn't seem to implement this,
  19. // so leaving it for now
  20. self.addEventListener("pushsubscriptionchange", (event) => {
  21. console.log("[ServiceWorker] PushSubscriptionChange");
  22. console.log(event);
  23. });
  24. self.addEventListener("push", (event) => {
  25. // server/types.go webPushPayload
  26. const data = event.data.json();
  27. console.log("[ServiceWorker] Received Web Push Event", { event, data });
  28. event.waitUntil(
  29. (async () => {
  30. if (data.event === "subscription_expiring") {
  31. await self.registration.showNotification("Notifications will be paused", {
  32. body: "Open ntfy to continue receiving notifications",
  33. icon: "/static/images/ntfy.png",
  34. data,
  35. });
  36. } else if (data.event === "message") {
  37. const { subscription_id: subscriptionId, message } = data;
  38. broadcastChannel.postMessage(message);
  39. const db = await getDbAsync();
  40. const image = message.attachment?.name.match(/\.(png|jpe?g|gif|webp)$/i) ? message.attachment.url : undefined;
  41. const actions = message.actions
  42. ?.filter(({ action }) => action === "view" || action === "http")
  43. .map(({ label }) => ({
  44. action: label,
  45. title: label,
  46. }));
  47. await Promise.all([
  48. (async () => {
  49. await db.notifications.add({
  50. ...message,
  51. subscriptionId,
  52. // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  53. new: 1,
  54. });
  55. const badgeCount = await db.notifications.where({ new: 1 }).count();
  56. console.log("[ServiceWorker] Setting new app badge count", { badgeCount });
  57. self.navigator.setAppBadge?.(badgeCount);
  58. })(),
  59. db.subscriptions.update(subscriptionId, {
  60. last: message.id,
  61. }),
  62. // Please update the desktop notification in Notifier.js to match any changes
  63. self.registration.showNotification(formatTitleWithDefault(message, message.topic), {
  64. tag: subscriptionId,
  65. body: formatMessage(message),
  66. icon: image ?? "/static/images/ntfy.png",
  67. image,
  68. data,
  69. timestamp: message.time * 1_000,
  70. actions,
  71. }),
  72. ]);
  73. } else {
  74. // We can't ignore the push, since permission can be revoked by the browser
  75. await self.registration.showNotification("Unknown notification received from server", {
  76. body: "You may need to update ntfy by opening the web app",
  77. icon: "/static/images/ntfy.png",
  78. data,
  79. });
  80. }
  81. })()
  82. );
  83. });
  84. self.addEventListener("notificationclick", (event) => {
  85. console.log("[ServiceWorker] NotificationClick");
  86. event.waitUntil(
  87. (async () => {
  88. const clients = await self.clients.matchAll({ type: "window" });
  89. const rootUrl = new URL(self.location.origin);
  90. const rootClient = clients.find((client) => client.url === rootUrl.toString());
  91. if (event.notification.data?.event !== "message") {
  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. if (action.clear) {
  105. event.notification.close();
  106. }
  107. } else if (action.action === "http") {
  108. try {
  109. const response = await fetch(action.url, {
  110. method: action.method ?? "POST",
  111. headers: action.headers ?? {},
  112. body: action.body,
  113. });
  114. if (!response.ok) {
  115. throw new Error(`HTTP ${response.status} ${response.statusText}`);
  116. }
  117. if (action.clear) {
  118. event.notification.close();
  119. }
  120. } catch (e) {
  121. console.error("[ServiceWorker] Error performing http action", e);
  122. self.registration.showNotification(`Unsuccessful action ${action.label} (${action.action})`, {
  123. body: e.message,
  124. });
  125. }
  126. }
  127. } else if (message.click) {
  128. self.clients.openWindow(message.click);
  129. event.notification.close();
  130. } else {
  131. const topicUrl = new URL(message.topic, self.location.origin);
  132. const topicClient = clients.find((client) => client.url === topicUrl.toString());
  133. if (topicClient) {
  134. topicClient.focus();
  135. } else if (rootClient) {
  136. rootClient.focus();
  137. } else {
  138. self.clients.openWindow(topicUrl);
  139. }
  140. event.notification.close();
  141. }
  142. }
  143. })()
  144. );
  145. });
  146. // self.__WB_MANIFEST is default injection point
  147. // eslint-disable-next-line no-underscore-dangle
  148. precacheAndRoute(self.__WB_MANIFEST);
  149. // clean old assets
  150. cleanupOutdatedCaches();
  151. // to allow work offline
  152. if (import.meta.env.MODE !== "development") {
  153. registerRoute(new NavigationRoute(createHandlerBoundToURL("/")));
  154. registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
  155. }