|
| 1 | +import { getLocalStorage } from '@/lib/localStorage'; |
| 2 | + |
| 3 | +const NOTIFY_COMP_ORIGIN = import.meta.env.VITE_NOTIFY_COMP_ORIGIN ?? ''; |
| 4 | +const NOTIFY_COMP_TOKEN_URL = '/.netlify/functions/notify-comp-token'; |
| 5 | + |
| 6 | +interface PushSubscriptionJson { |
| 7 | + endpoint?: string; |
| 8 | + keys?: { |
| 9 | + p256dh?: string; |
| 10 | + auth?: string; |
| 11 | + }; |
| 12 | +} |
| 13 | + |
| 14 | +export interface AssignmentNotificationWatch { |
| 15 | + competitionId: string; |
| 16 | + wcaUserId: number; |
| 17 | +} |
| 18 | + |
| 19 | +export type AssignmentNotificationStatus = NotificationPermission | 'not-signed-in' | 'unsupported'; |
| 20 | + |
| 21 | +const notifyCompUrl = (path: string) => `${NOTIFY_COMP_ORIGIN}${path}`; |
| 22 | + |
| 23 | +const getAccessToken = () => { |
| 24 | + const expiresAt = Number(getLocalStorage('expirationTime') ?? 0); |
| 25 | + const accessToken = getLocalStorage('accessToken'); |
| 26 | + |
| 27 | + if (!accessToken || !expiresAt || expiresAt <= Date.now()) { |
| 28 | + return null; |
| 29 | + } |
| 30 | + |
| 31 | + return accessToken; |
| 32 | +}; |
| 33 | + |
| 34 | +const toUint8Array = (base64: string) => { |
| 35 | + const padding = '='.repeat((4 - (base64.length % 4)) % 4); |
| 36 | + const normalized = `${base64}${padding}`.replace(/-/g, '+').replace(/_/g, '/'); |
| 37 | + const raw = window.atob(normalized); |
| 38 | + const output = new Uint8Array(raw.length); |
| 39 | + |
| 40 | + for (let index = 0; index < raw.length; index += 1) { |
| 41 | + output[index] = raw.charCodeAt(index); |
| 42 | + } |
| 43 | + |
| 44 | + return output; |
| 45 | +}; |
| 46 | + |
| 47 | +export const getAssignmentNotificationStatus = (): AssignmentNotificationStatus => { |
| 48 | + if ( |
| 49 | + !('Notification' in window) || |
| 50 | + !('serviceWorker' in navigator) || |
| 51 | + !('PushManager' in window) |
| 52 | + ) { |
| 53 | + return 'unsupported'; |
| 54 | + } |
| 55 | + |
| 56 | + if (!getAccessToken()) { |
| 57 | + return 'not-signed-in'; |
| 58 | + } |
| 59 | + |
| 60 | + return Notification.permission; |
| 61 | +}; |
| 62 | + |
| 63 | +export const requestAssignmentNotificationPermission = async () => { |
| 64 | + if (!('Notification' in window)) { |
| 65 | + return 'unsupported' as const; |
| 66 | + } |
| 67 | + |
| 68 | + if (Notification.permission === 'granted') { |
| 69 | + return 'granted' as const; |
| 70 | + } |
| 71 | + |
| 72 | + return await Notification.requestPermission(); |
| 73 | +}; |
| 74 | + |
| 75 | +const fetchNotifyCompToken = async () => { |
| 76 | + const accessToken = getAccessToken(); |
| 77 | + if (!accessToken) { |
| 78 | + throw new Error('Sign in with WCA to enable assignment notifications.'); |
| 79 | + } |
| 80 | + |
| 81 | + const response = await fetch(NOTIFY_COMP_TOKEN_URL, { |
| 82 | + method: 'POST', |
| 83 | + headers: { |
| 84 | + 'Content-Type': 'application/json', |
| 85 | + }, |
| 86 | + body: JSON.stringify({ accessToken }), |
| 87 | + }); |
| 88 | + |
| 89 | + if (!response.ok) { |
| 90 | + throw new Error(await response.text()); |
| 91 | + } |
| 92 | + |
| 93 | + const payload = (await response.json()) as { token?: string }; |
| 94 | + if (!payload.token) { |
| 95 | + throw new Error('Notification token response was missing a token.'); |
| 96 | + } |
| 97 | + |
| 98 | + return payload.token; |
| 99 | +}; |
| 100 | + |
| 101 | +const fetchVapidPublicKey = async () => { |
| 102 | + const response = await fetch(notifyCompUrl('/v0/external/push/vapid-public-key')); |
| 103 | + |
| 104 | + if (!response.ok) { |
| 105 | + throw new Error(await response.text()); |
| 106 | + } |
| 107 | + |
| 108 | + const payload = (await response.json()) as { publicKey?: string }; |
| 109 | + if (!payload.publicKey) { |
| 110 | + throw new Error('NotifyComp did not return a VAPID public key.'); |
| 111 | + } |
| 112 | + |
| 113 | + return payload.publicKey; |
| 114 | +}; |
| 115 | + |
| 116 | +const getPushSubscription = async () => { |
| 117 | + const registration = await navigator.serviceWorker.ready; |
| 118 | + const existing = await registration.pushManager.getSubscription(); |
| 119 | + |
| 120 | + if (existing) { |
| 121 | + return existing; |
| 122 | + } |
| 123 | + |
| 124 | + return await registration.pushManager.subscribe({ |
| 125 | + userVisibleOnly: true, |
| 126 | + applicationServerKey: toUint8Array(await fetchVapidPublicKey()), |
| 127 | + }); |
| 128 | +}; |
| 129 | + |
| 130 | +export const enableAssignmentNotifications = async (watches: AssignmentNotificationWatch[]) => { |
| 131 | + const permission = await requestAssignmentNotificationPermission(); |
| 132 | + if (permission !== 'granted') { |
| 133 | + return permission; |
| 134 | + } |
| 135 | + |
| 136 | + const [token, subscription] = await Promise.all([fetchNotifyCompToken(), getPushSubscription()]); |
| 137 | + const payload = subscription.toJSON() as PushSubscriptionJson; |
| 138 | + |
| 139 | + if (!payload.endpoint || !payload.keys?.p256dh || !payload.keys.auth) { |
| 140 | + throw new Error('Browser push subscription is missing required keys.'); |
| 141 | + } |
| 142 | + |
| 143 | + const response = await fetch(notifyCompUrl('/v0/external/push/subscriptions'), { |
| 144 | + method: 'POST', |
| 145 | + headers: { |
| 146 | + Authorization: `Bearer ${token}`, |
| 147 | + 'Content-Type': 'application/json', |
| 148 | + }, |
| 149 | + body: JSON.stringify({ |
| 150 | + endpoint: payload.endpoint, |
| 151 | + p256dh: payload.keys.p256dh, |
| 152 | + auth: payload.keys.auth, |
| 153 | + watches, |
| 154 | + }), |
| 155 | + }); |
| 156 | + |
| 157 | + if (!response.ok) { |
| 158 | + throw new Error(await response.text()); |
| 159 | + } |
| 160 | + |
| 161 | + return permission; |
| 162 | +}; |
| 163 | + |
| 164 | +export const disableAssignmentNotifications = async () => { |
| 165 | + const registration = await navigator.serviceWorker.ready; |
| 166 | + const subscription = await registration.pushManager.getSubscription(); |
| 167 | + |
| 168 | + if (!subscription) { |
| 169 | + return; |
| 170 | + } |
| 171 | + |
| 172 | + const token = await fetchNotifyCompToken(); |
| 173 | + const payload = subscription.toJSON() as PushSubscriptionJson; |
| 174 | + |
| 175 | + if (payload.endpoint) { |
| 176 | + await fetch(notifyCompUrl('/v0/external/push/subscriptions'), { |
| 177 | + method: 'DELETE', |
| 178 | + headers: { |
| 179 | + Authorization: `Bearer ${token}`, |
| 180 | + 'Content-Type': 'application/json', |
| 181 | + }, |
| 182 | + body: JSON.stringify({ endpoint: payload.endpoint }), |
| 183 | + }); |
| 184 | + } |
| 185 | + |
| 186 | + await subscription.unsubscribe(); |
| 187 | +}; |
0 commit comments