ntfy/web/src/components/hooks.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

179 lines
6.4 KiB
JavaScript
Raw Normal View History

import { useParams } from "react-router-dom";
import { useEffect, useMemo, useState } from "react";
import subscriptionManager from "../app/SubscriptionManager";
import { disallowedTopic, expandSecureUrl, topicUrl } from "../app/utils";
import routes from "./routes";
import connectionManager from "../app/ConnectionManager";
import poller from "../app/Poller";
import pruner from "../app/Pruner";
2022-12-09 14:50:48 +13:00
import session from "../app/Session";
2023-02-03 09:19:37 +13:00
import accountApi from "../app/AccountApi";
import { UnauthorizedError } from "../app/errors";
2023-06-11 12:42:02 +12:00
import { webPush, useWebPushTopicListener } from "../app/WebPush";
/**
* Wire connectionManager and subscriptionManager so that subscriptions are updated when the connection
* state changes. Conversely, when the subscription changes, the connection is refreshed (which may lead
* to the connection being re-established).
*
* When Web Push is enabled, we do not need to connect to our home server via WebSocket, since notifications
* will be delivered via Web Push. However, we still need to connect to other servers via WebSocket, or for internal
* topics, such as sync topics (st_...).
*/
export const useConnectionListeners = (account, subscriptions, users, webPushTopics) => {
const wsSubscriptions = useMemo(
() => (subscriptions && webPushTopics ? subscriptions.filter((s) => !webPushTopics.includes(s.topic)) : []),
// wsSubscriptions should stay stable unless the list of subscription IDs changes. Without the memo, the connection
// listener calls a refresh for no reason. This isn't a problem due to the makeConnectionId, but it triggers an
// unnecessary recomputation for every received message.
[JSON.stringify({ subscriptions: subscriptions?.map(({ id }) => id), webPushTopics })]
);
2023-01-25 09:31:39 +13:00
// Register listeners for incoming messages, and connection state changes
useEffect(
() => {
const handleInternalMessage = async (message) => {
console.log(`[ConnectionListener] Received message on sync topic`, message.message);
try {
const data = JSON.parse(message.message);
if (data.event === "sync") {
console.log(`[ConnectionListener] Triggering account sync`);
2023-01-12 15:38:10 +13:00
await accountApi.sync();
} else {
console.log(`[ConnectionListener] Unknown message type. Doing nothing.`);
2023-05-24 07:13:01 +12:00
}
} catch (e) {
2023-01-12 15:38:10 +13:00
console.log(`[ConnectionListener] Error parsing sync topic message`, e);
2023-05-24 07:13:01 +12:00
}
};
2023-01-25 09:31:39 +13:00
const handleNotification = async (subscriptionId, notification) => {
const added = await subscriptionManager.addNotification(subscriptionId, notification);
if (added) {
await subscriptionManager.notify(subscriptionId, notification);
2023-01-25 09:31:39 +13:00
}
2023-05-24 07:13:01 +12:00
};
const handleMessage = async (subscriptionId, message) => {
const subscription = await subscriptionManager.get(subscriptionId);
2023-06-01 04:55:17 +12:00
// Race condition: sometimes the subscription is already unsubscribed from account
// sync before the message is handled
if (!subscription) {
return;
}
if (subscription.internal) {
await handleInternalMessage(message);
} else {
await handleNotification(subscriptionId, message);
}
};
connectionManager.registerStateListener((id, state) => subscriptionManager.updateState(id, state));
2023-01-12 15:38:10 +13:00
connectionManager.registerMessageListener(handleMessage);
2023-01-03 16:21:11 +13:00
return () => {
connectionManager.resetStateListener();
connectionManager.resetMessageListener();
2023-05-24 07:13:01 +12:00
};
},
// We have to disable dep checking for "navigate". This is fine, it never changes.
2023-05-24 19:03:28 +12:00
2023-05-24 07:13:01 +12:00
[]
);
2023-01-25 09:31:39 +13:00
// Sync topic listener: For accounts with sync_topic, subscribe to an internal topic
useEffect(() => {
2023-01-25 09:31:39 +13:00
if (!account || !account.sync_topic) {
2023-05-24 07:13:01 +12:00
return;
}
subscriptionManager.add(config.base_url, account.sync_topic, { internal: true }); // Dangle!
2023-01-25 09:31:39 +13:00
}, [account]);
// When subscriptions or users change, refresh the connections
useEffect(() => {
connectionManager.refresh(wsSubscriptions, users); // Dangle
}, [wsSubscriptions, users]);
};
/**
* Automatically adds a subscription if we navigate to a page that has not been subscribed to.
* This will only be run once after the initial page load.
*/
export const useAutoSubscribe = (subscriptions, selected) => {
const [hasRun, setHasRun] = useState(false);
const params = useParams();
useEffect(() => {
const loaded = subscriptions !== null && subscriptions !== undefined;
if (!loaded || hasRun) {
return;
}
setHasRun(true);
const eligible = params.topic && !selected && !disallowedTopic(params.topic);
if (eligible) {
2023-01-05 16:47:12 +13:00
const baseUrl = params.baseUrl ? expandSecureUrl(params.baseUrl) : config.base_url;
2023-02-03 09:19:37 +13:00
console.log(`[Hooks] Auto-subscribing to ${topicUrl(baseUrl, params.topic)}`);
(async () => {
const subscription = await subscriptionManager.add(baseUrl, params.topic);
2022-12-09 14:50:48 +13:00
if (session.exists()) {
try {
2023-02-13 08:09:44 +13:00
await accountApi.addSubscription(baseUrl, params.topic);
} catch (e) {
2023-02-03 09:19:37 +13:00
console.log(`[Hooks] Auto-subscribing failed`, e);
if (e instanceof UnauthorizedError) {
await session.resetAndRedirect(routes.login);
2022-12-09 14:50:48 +13:00
}
}
}
poller.pollInBackground(subscription); // Dangle!
2023-05-24 07:13:01 +12:00
})();
}
}, [params, subscriptions, selected, hasRun]);
};
2022-03-12 09:17:12 +13:00
/**
* Start the poller and the pruner. This is done in a side effect as opposed to just in Pruner.js
* and Poller.js, because side effect imports are not a thing in JS, and "Optimize imports" cleans
* up "unused" imports. See https://github.com/binwiederhier/ntfy/issues/186.
2022-03-12 09:17:12 +13:00
*/
const startWorkers = () => {
poller.startWorker();
pruner.startWorker();
accountApi.startWorker();
2023-06-11 12:42:02 +12:00
webPush.startWorker();
};
2023-06-18 08:32:24 +12:00
const stopWorkers = () => {
poller.stopWorker();
pruner.stopWorker();
accountApi.stopWorker();
webPush.stopWorker();
};
export const useBackgroundProcesses = () => {
2023-06-11 12:42:02 +12:00
useWebPushTopicListener();
useEffect(() => {
console.log("[useBackgroundProcesses] mounting");
startWorkers();
return () => {
console.log("[useBackgroundProcesses] unloading");
stopWorkers();
};
}, []);
};
2023-01-03 16:21:11 +13:00
export const useAccountListener = (setAccount) => {
useEffect(() => {
accountApi.registerListener(setAccount);
2023-01-12 15:38:10 +13:00
accountApi.sync(); // Dangle
2023-01-03 16:21:11 +13:00
return () => {
2023-01-12 15:38:10 +13:00
accountApi.resetListener();
2023-01-03 16:21:11 +13:00
};
}, []);
};