sw.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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. await Promise.all([
  42. (async () => {
  43. await db.notifications.add({
  44. ...message,
  45. subscriptionId,
  46. // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  47. new: 1,
  48. });
  49. const badgeCount = await db.notifications.where({ new: 1 }).count();
  50. console.log("[ServiceWorker] Setting new app badge count", { badgeCount });
  51. self.navigator.setAppBadge?.(badgeCount);
  52. })(),
  53. db.subscriptions.update(subscriptionId, {
  54. last: message.id,
  55. }),
  56. // Please update the desktop notification in Notifier.js to match any changes
  57. self.registration.showNotification(formatTitleWithDefault(message, message.topic), {
  58. tag: subscriptionId,
  59. body: formatMessage(message),
  60. icon: image ?? "/static/images/ntfy.png",
  61. image,
  62. data,
  63. timestamp: message.time * 1_000,
  64. }),
  65. ]);
  66. } else {
  67. // We can't ignore the push, since permission can be revoked by the browser
  68. await self.registration.showNotification("Unknown notification received from server", {
  69. body: "You may need to update ntfy by opening the web app",
  70. icon: "/static/images/ntfy.png",
  71. data,
  72. });
  73. }
  74. })()
  75. );
  76. });
  77. self.addEventListener("notificationclick", (event) => {
  78. console.log("[ServiceWorker] NotificationClick");
  79. event.notification.close();
  80. event.waitUntil(
  81. (async () => {
  82. const clients = await self.clients.matchAll({ type: "window" });
  83. const rootUrl = new URL(self.location.origin);
  84. const rootClient = clients.find((client) => client.url === rootUrl.toString());
  85. if (event.notification.data.event !== "message") {
  86. if (rootClient) {
  87. rootClient.focus();
  88. } else {
  89. self.clients.openWindow(rootUrl);
  90. }
  91. } else {
  92. const { message } = event.notification.data;
  93. if (message.click) {
  94. self.clients.openWindow(message.click);
  95. return;
  96. }
  97. const topicUrl = new URL(message.topic, self.location.origin);
  98. const topicClient = clients.find((client) => client.url === topicUrl.toString());
  99. if (topicClient) {
  100. topicClient.focus();
  101. } else if (rootClient) {
  102. rootClient.focus();
  103. } else {
  104. self.clients.openWindow(topicUrl);
  105. }
  106. }
  107. })()
  108. );
  109. });
  110. // self.__WB_MANIFEST is default injection point
  111. // eslint-disable-next-line no-underscore-dangle
  112. precacheAndRoute(self.__WB_MANIFEST);
  113. // clean old assets
  114. cleanupOutdatedCaches();
  115. // to allow work offline
  116. if (import.meta.env.MODE !== "development") {
  117. registerRoute(new NavigationRoute(createHandlerBoundToURL("/")));
  118. registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
  119. }