Debian Codegraph @

web/src/components/hooks.js

raw
1 import { useParams } from "react-router-dom";
2 import { useEffect, useMemo, useState } from "react";
3 import { useLiveQuery } from "dexie-react-hooks";
4 import subscriptionManager from "../app/SubscriptionManager";
5 import { disallowedTopic, expandSecureUrl, topicUrl } from "../app/utils";
6 import routes from "./routes";
7 import connectionManager from "../app/ConnectionManager";
8 import poller from "../app/Poller";
9 import pruner from "../app/Pruner";
10 import session from "../app/Session";
11 import accountApi from "../app/AccountApi";
12 import versionChecker from "../app/VersionChecker";
13 import { UnauthorizedError } from "../app/errors";
14 import notifier from "../app/Notifier";
15 import prefs from "../app/Prefs";
16 import { EVENT_MESSAGE_DELETE, EVENT_MESSAGE_CLEAR, SW_PERIODIC_SYNC_EXTEND_TOKEN_TAG } from "../app/events";
17
18 /**
19 * Wire connectionManager and subscriptionManager so that subscriptions are updated when the connection
20 * state changes. Conversely, when the subscription changes, the connection is refreshed (which may lead
21 * to the connection being re-established).
22 *
23 * When Web Push is enabled, we do not need to connect to our home server via WebSocket, since notifications
24 * will be delivered via Web Push. However, we still need to connect to other servers via WebSocket, or for internal
25 * topics, such as sync topics (st_...).
26 */
27 export const useConnectionListeners = (account, subscriptions, users, webPushTopics) => {
28 const wsSubscriptions = useMemo(
29 () => (subscriptions && webPushTopics ? subscriptions.filter((s) => !webPushTopics.includes(s.topic)) : []),
30 // wsSubscriptions should stay stable unless the list of subscription IDs changes. Without the memo, the connection
31 // listener calls a refresh for no reason. This isn't a problem due to the makeConnectionId, but it triggers an
32 // unnecessary recomputation for every received message.
33 [JSON.stringify({ subscriptions: subscriptions?.map(({ id }) => id), webPushTopics })],
34 );
35
36 // Register listeners for incoming messages, and connection state changes
37 useEffect(
38 () => {
39 const handleInternalMessage = async (message) => {
40 console.log(`[ConnectionListener] Received message on sync topic`, message.message);
41 try {
42 const data = JSON.parse(message.message);
43 if (data.event === "sync") {
44 console.log(`[ConnectionListener] Triggering account sync`);
45 await accountApi.sync();
46 } else {
47 console.log(`[ConnectionListener] Unknown message type. Doing nothing.`);
48 }
49 } catch (e) {
50 console.log(`[ConnectionListener] Error parsing sync topic message`, e);
51 }
52 };
53
54 const handleNotification = async (subscription, notification) => {
55 // This logic is (partially) duplicated in
56 // - Android: SubscriberService::onNotificationReceived()
57 // - Android: FirebaseService::onMessageReceived()
58 // - Web app: hooks.js:handleNotification()
59 // - Web app: sw.js:handleMessage(), sw.js:handleMessageClear(), ...
60
61 if (notification.event === EVENT_MESSAGE_DELETE && notification.sequence_id) {
62 await subscriptionManager.deleteNotificationBySequenceId(subscription.id, notification.sequence_id);
63 await notifier.cancel(subscription, notification);
64 } else if (notification.event === EVENT_MESSAGE_CLEAR && notification.sequence_id) {
65 await subscriptionManager.markNotificationReadBySequenceId(subscription.id, notification.sequence_id);
66 await notifier.cancel(subscription, notification);
67 } else {
68 // Regular message: delete existing and add new
69 const sequenceId = notification.sequence_id || notification.id;
70 if (sequenceId) {
71 await subscriptionManager.deleteNotificationBySequenceId(subscription.id, sequenceId);
72 }
73 const added = await subscriptionManager.addNotification(subscription.id, notification);
74 if (added) {
75 await subscriptionManager.notify(subscription.id, notification);
76 }
77 }
78 };
79
80 const handleMessage = async (subscriptionId, message) => {
81 const subscription = await subscriptionManager.get(subscriptionId);
82
83 // Race condition: sometimes the subscription is already unsubscribed from account
84 // sync before the message is handled
85 if (!subscription) {
86 return;
87 }
88
89 if (subscription.internal) {
90 await handleInternalMessage(message);
91 } else {
92 await handleNotification(subscription, message);
93 }
94 };
95
96 connectionManager.registerStateListener((id, state) => subscriptionManager.updateState(id, state));
97 connectionManager.registerMessageListener(handleMessage);
98
99 return () => {
100 connectionManager.resetStateListener();
101 connectionManager.resetMessageListener();
102 };
103 },
104 // We have to disable dep checking for "navigate". This is fine, it never changes.
105
106 [],
107 );
108
109 // Sync topic listener: For accounts with sync_topic, subscribe to an internal topic
110 useEffect(() => {
111 if (!account || !account.sync_topic) {
112 return;
113 }
114 subscriptionManager.upsert(config.base_url, account.sync_topic, { internal: true }); // Dangle!
115 }, [account]);
116
117 // When subscriptions or users change, refresh the connections
118 useEffect(() => {
119 connectionManager.refresh(wsSubscriptions, users); // Dangle
120 }, [wsSubscriptions, users]);
121 };
122
123 /**
124 * Automatically adds a subscription if we navigate to a page that has not been subscribed to.
125 * This will only be run once after the initial page load.
126 */
127 export const useAutoSubscribe = (subscriptions, selected) => {
128 const [hasRun, setHasRun] = useState(false);
129 const params = useParams();
130
131 useEffect(() => {
132 const loaded = subscriptions !== null && subscriptions !== undefined;
133 if (!loaded || hasRun) {
134 return;
135 }
136 setHasRun(true);
137 const eligible = params.topic && !selected && !disallowedTopic(params.topic);
138 if (eligible) {
139 const baseUrl = params.baseUrl ? expandSecureUrl(params.baseUrl) : config.base_url;
140 console.log(`[Hooks] Auto-subscribing to ${topicUrl(baseUrl, params.topic)}`);
141 (async () => {
142 const subscription = await subscriptionManager.upsert(baseUrl, params.topic);
143 if (session.exists()) {
144 try {
145 await accountApi.addSubscription(baseUrl, params.topic);
146 } catch (e) {
147 console.log(`[Hooks] Auto-subscribing failed`, e);
148 if (e instanceof UnauthorizedError) {
149 await session.resetAndRedirect(routes.login);
150 }
151 }
152 }
153 poller.pollInBackground(subscription); // Dangle!
154 })();
155 }
156 }, [params, subscriptions, selected, hasRun]);
157 };
158
159 const webPushBroadcastChannel = new BroadcastChannel("web-push-broadcast");
160
161 /**
162 * Hook to return a value that's refreshed when the notification permission changes
163 */
164 export const useNotificationPermissionListener = (query) => {
165 const [result, setResult] = useState(query());
166
167 useEffect(() => {
168 const handler = () => {
169 setResult(query());
170 };
171
172 if ("permissions" in navigator) {
173 navigator.permissions.query({ name: "notifications" }).then((permission) => {
174 permission.addEventListener("change", handler);
175
176 return () => {
177 permission.removeEventListener("change", handler);
178 };
179 });
180 }
181 }, []);
182
183 return result;
184 };
185
186 /**
187 * Updates the Web Push subscriptions when the list of topics changes,
188 * as well as plays a sound when a new broadcast message is received from
189 * the service worker, since the service worker cannot play sounds.
190 */
191 const useWebPushListener = (topics) => {
192 const [prevUpdate, setPrevUpdate] = useState();
193 const pushPossible = useNotificationPermissionListener(() => notifier.pushPossible());
194
195 useEffect(() => {
196 const nextUpdate = JSON.stringify({ topics, pushPossible });
197 if (topics === undefined || nextUpdate === prevUpdate) {
198 return;
199 }
200
201 (async () => {
202 try {
203 console.log("[useWebPushListener] Refreshing web push subscriptions", topics);
204 await subscriptionManager.updateWebPushSubscriptions(topics);
205 setPrevUpdate(nextUpdate);
206 } catch (e) {
207 console.error("[useWebPushListener] Error refreshing web push subscriptions", e);
208 }
209 })();
210 }, [topics, pushPossible, prevUpdate]);
211
212 useEffect(() => {
213 const onMessage = () => {
214 notifier.playSound(); // Service Worker cannot play sound, so we do it here!
215 };
216
217 webPushBroadcastChannel.addEventListener("message", onMessage);
218
219 return () => {
220 webPushBroadcastChannel.removeEventListener("message", onMessage);
221 };
222 });
223 };
224
225 /**
226 * Hook to return a list of Web Push enabled topics using a live query. This hook will return an empty list if
227 * permissions are not granted, or if the browser does not support Web Push. Notification permissions are acted upon
228 * automatically.
229 */
230 export const useWebPushTopics = () => {
231 const pushPossible = useNotificationPermissionListener(() => notifier.pushPossible());
232
233 const topics = useLiveQuery(
234 async () => subscriptionManager.webPushTopics(pushPossible),
235 // invalidate (reload) query when these values change
236 [pushPossible],
237 );
238
239 useWebPushListener(topics);
240
241 return topics;
242 };
243
244 const matchMedia = window.matchMedia("(display-mode: standalone)");
245 const isIOSStandalone = window.navigator.standalone === true;
246
247 /*
248 * Watches the "display-mode" to detect if the app is running as a standalone app (PWA).
249 */
250 export const useIsLaunchedPWA = () => {
251 const [isStandalone, setIsStandalone] = useState(matchMedia.matches);
252
253 useEffect(() => {
254 if (isIOSStandalone) {
255 return () => {
256 // No need to listen for events on iOS
257 };
258 }
259 const handler = (evt) => {
260 console.log(`[useIsLaunchedPWA] App is now running ${evt.matches ? "standalone" : "in the browser"}`);
261 setIsStandalone(evt.matches);
262 };
263 matchMedia.addEventListener("change", handler);
264 return () => {
265 matchMedia.removeEventListener("change", handler);
266 };
267 }, []);
268
269 return isIOSStandalone || isStandalone;
270 };
271
272 /**
273 * Watches the result of `useIsLaunchedPWA` and enables "Web Push" if it is.
274 */
275 export const useStandaloneWebPushAutoSubscribe = () => {
276 const isLaunchedPWA = useIsLaunchedPWA();
277
278 useEffect(() => {
279 if (isLaunchedPWA) {
280 console.log(`[useStandaloneWebPushAutoSubscribe] Turning on web push automatically`);
281 prefs.setWebPushEnabled(true); // Dangle!
282 }
283 }, [isLaunchedPWA]);
284 };
285
286 /**
287 * Registers a periodicsync listener for `extend_token` (see sw.js).
288 * This extends the token regardless of whether the browser is open.
289 *
290 * CAVEATS:
291 * - Chromium-only
292 * - Only when the PWA is _installed_ (not just running in a browser tab)
293 * - Only when notifications are granted
294 *
295 * This is an experimental feature:
296 * https://developer.mozilla.org/en-US/docs/Web/API/Web_Periodic_Background_Synchronization_API
297 */
298 const usePeriodicTokenExtend = () => {
299 const isLaunchedPWA = useIsLaunchedPWA();
300 const pushPossible = useNotificationPermissionListener(() => notifier.pushPossible());
301
302 useEffect(() => {
303 (async () => {
304 if (!isLaunchedPWA) {
305 console.debug("[usePeriodicTokenExtend] Skipping: Not running as PWA");
306 return;
307 }
308
309 if (!pushPossible) {
310 console.debug("[usePeriodicTokenExtend] Skipping: Web push not possible or granted");
311 return;
312 }
313
314 try {
315 const registration = await navigator.serviceWorker.ready;
316 if (!registration.periodicSync) {
317 console.debug("[usePeriodicTokenExtend] Skipping: Periodic Sync not supported");
318 return;
319 }
320
321 console.log(`[usePeriodicTokenExtend] Turning on periodicsync "${SW_PERIODIC_SYNC_EXTEND_TOKEN_TAG}"`);
322 await registration.periodicSync.register(SW_PERIODIC_SYNC_EXTEND_TOKEN_TAG, {
323 minInterval: 12 * 60 * 60 * 1000, // 12 hours
324 });
325 } catch (error) {
326 console.log("[usePeriodicTokenExtend] Periodic Sync could not be registered", error);
327 }
328 })();
329 }, [isLaunchedPWA, pushPossible]);
330 };
331
332 /**
333 * Start the poller and the pruner. This is done in a side effect as opposed to just in Pruner.js
334 * and Poller.js, because side effect imports are not a thing in JS, and "Optimize imports" cleans
335 * up "unused" imports. See https://github.com/binwiederhier/ntfy/issues/186.
336 */
337
338 const startWorkers = () => {
339 poller.startWorker();
340 pruner.startWorker();
341 accountApi.startWorker();
342 versionChecker.startWorker();
343 };
344
345 const stopWorkers = () => {
346 poller.stopWorker();
347 pruner.stopWorker();
348 accountApi.stopWorker();
349 versionChecker.stopWorker();
350 };
351
352 export const useBackgroundProcesses = () => {
353 useStandaloneWebPushAutoSubscribe();
354 usePeriodicTokenExtend();
355
356 useEffect(() => {
357 console.log("[useBackgroundProcesses] mounting");
358 startWorkers();
359
360 return () => {
361 console.log("[useBackgroundProcesses] unloading");
362 stopWorkers();
363 };
364 }, []);
365 };
366
367 export const useAccountListener = (setAccount) => {
368 useEffect(() => {
369 accountApi.registerListener(setAccount);
370 accountApi.sync(); // Dangle
371 return () => {
372 accountApi.resetListener();
373 };
374 }, []);
375 };
376
377 /**
378 * Hook to detect version/config changes and call the provided callback when a change is detected.
379 */
380 export const useVersionChangeListener = (onVersionChange) => {
381 useEffect(() => {
382 versionChecker.registerListener(onVersionChange);
383 return () => {
384 versionChecker.resetListener();
385 };
386 }, [onVersionChange]);
387 };