|
| 1 | +import { useEffect } from "react"; |
| 2 | +import { API_BASE } from "@/utils/constants"; |
| 3 | +import { baseHeaders } from "@/utils/request"; |
| 4 | + |
| 5 | +const PUSH_PUBKEY_URL = `${API_BASE}/web-push/pubkey`; |
| 6 | +const PUSH_USER_SUBSCRIBE_URL = `${API_BASE}/web-push/subscribe`; |
| 7 | + |
| 8 | +// If you update the service worker, increment this version or else |
| 9 | +// the service worker will not be updated with new changes - |
| 10 | +// Its version ID is independent of the app version to prevent reloading |
| 11 | +// or cache busting when not needed. |
| 12 | +const SW_VERSION = "1.0.0"; |
| 13 | + |
| 14 | +function log(message, ...args) { |
| 15 | + if (typeof message === "object") message = JSON.stringify(message, null, 2); |
| 16 | + console.log(`[useWebPushNotifications] ${message}`, ...args); |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Subscribes to push notifications for the current client - can be called multiple times without re-subscribing |
| 21 | + * or generating infinite tokens. |
| 22 | + * @returns {void} |
| 23 | + */ |
| 24 | +export async function subscribeToPushNotifications() { |
| 25 | + try { |
| 26 | + if (!("serviceWorker" in navigator) || !("PushManager" in window)) { |
| 27 | + log("Push notifications not supported"); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + // Check current permission status |
| 32 | + const permission = await Notification.requestPermission(); |
| 33 | + if (permission !== "granted") { |
| 34 | + log("Notification permission not granted"); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + const publicKey = await fetch(PUSH_PUBKEY_URL, { headers: baseHeaders() }) |
| 39 | + .then((res) => res.json()) |
| 40 | + .then(({ publicKey }) => { |
| 41 | + if (!publicKey) throw new Error("No public key found or generated"); |
| 42 | + return publicKey; |
| 43 | + }) |
| 44 | + .catch(() => null); |
| 45 | + |
| 46 | + if (!publicKey) return log("No public key found or generated"); |
| 47 | + |
| 48 | + const swReg = await navigator.serviceWorker.register( |
| 49 | + `/service-workers/push-notifications.js?v=${SW_VERSION}` |
| 50 | + ); |
| 51 | + |
| 52 | + // Check for updates |
| 53 | + swReg.addEventListener("updatefound", () => { |
| 54 | + const newWorker = swReg.installing; |
| 55 | + log("Service worker update found"); |
| 56 | + |
| 57 | + newWorker.addEventListener("statechange", () => { |
| 58 | + if ( |
| 59 | + newWorker.state === "installed" && |
| 60 | + navigator.serviceWorker.controller |
| 61 | + ) { |
| 62 | + // New service worker is installed and ready |
| 63 | + log("New service worker installed, ready to activate"); |
| 64 | + |
| 65 | + // Optionally show a notification to the user |
| 66 | + if (confirm("A new version is available. Reload to update?")) { |
| 67 | + window.location.reload(); |
| 68 | + } |
| 69 | + } |
| 70 | + }); |
| 71 | + }); |
| 72 | + |
| 73 | + // Handle service worker updates |
| 74 | + navigator.serviceWorker.addEventListener("controllerchange", () => { |
| 75 | + log("Service worker controller changed"); |
| 76 | + }); |
| 77 | + |
| 78 | + if (swReg.installing) { |
| 79 | + await new Promise((resolve) => { |
| 80 | + swReg.installing.addEventListener("statechange", () => { |
| 81 | + if (swReg.installing?.state === "activated") resolve(); |
| 82 | + }); |
| 83 | + }); |
| 84 | + } else if (swReg.waiting) { |
| 85 | + await new Promise((resolve) => { |
| 86 | + swReg.waiting.addEventListener("statechange", () => { |
| 87 | + if (swReg.waiting?.state === "activated") resolve(); |
| 88 | + }); |
| 89 | + }); |
| 90 | + } |
| 91 | + |
| 92 | + const subscription = await swReg.pushManager.subscribe({ |
| 93 | + userVisibleOnly: true, |
| 94 | + applicationServerKey: urlBase64ToUint8Array(publicKey), |
| 95 | + }); |
| 96 | + await fetch(PUSH_USER_SUBSCRIBE_URL, { |
| 97 | + method: "POST", |
| 98 | + body: JSON.stringify(subscription), |
| 99 | + headers: baseHeaders(), |
| 100 | + }); |
| 101 | + } catch (error) { |
| 102 | + log("Error subscribing to push notifications", error); |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +/** |
| 107 | + * Hook that registers a service worker for push notifications. |
| 108 | + * @returns {void} |
| 109 | + */ |
| 110 | +export default function useWebPushNotifications() { |
| 111 | + useEffect(() => { |
| 112 | + subscribeToPushNotifications(); |
| 113 | + }, []); |
| 114 | +} |
| 115 | + |
| 116 | +function urlBase64ToUint8Array(base64String) { |
| 117 | + const padding = "=".repeat((4 - (base64String.length % 4)) % 4); |
| 118 | + const base64 = (base64String + padding) |
| 119 | + .replace(/\-/g, "+") |
| 120 | + .replace(/_/g, "/"); |
| 121 | + const rawData = atob(base64); |
| 122 | + return new Uint8Array([...rawData].map((char) => char.charCodeAt(0))); |
| 123 | +} |
0 commit comments