sw.js 4.4 KB

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