ntfy/web/src/components/hooks.js

142 lines
5.9 KiB
JavaScript
Raw Normal View History

import {useNavigate, useParams} from "react-router-dom";
2023-01-24 21:31:39 +01:00
import {useEffect, useState} from "react";
import subscriptionManager from "../app/SubscriptionManager";
import {disallowedTopic, expandSecureUrl, topicUrl} from "../app/utils";
import notifier from "../app/Notifier";
import routes from "./routes";
import connectionManager from "../app/ConnectionManager";
import poller from "../app/Poller";
import pruner from "../app/Pruner";
2022-12-09 02:50:48 +01:00
import session from "../app/Session";
2023-01-24 21:31:39 +01:00
import accountApi, {UnauthorizedError} from "../app/AccountApi";
/**
* 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).
*/
2023-01-24 21:31:39 +01:00
export const useConnectionListeners = (account, subscriptions, users) => {
const navigate = useNavigate();
2023-01-24 21:31:39 +01:00
// Register listeners for incoming messages, and connection state changes
useEffect(() => {
2023-01-12 03:38:10 +01:00
const handleMessage = async (subscriptionId, message) => {
const subscription = await subscriptionManager.get(subscriptionId);
if (subscription.internal) {
await handleInternalMessage(message);
} else {
await handleNotification(subscriptionId, message);
}
};
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") {
2023-01-18 21:50:06 +01:00
console.log(`[ConnectionListener] Triggering account sync`);
await accountApi.sync();
2023-01-12 03:38:10 +01:00
} else {
console.log(`[ConnectionListener] Unknown message type. Doing nothing.`);
}
} catch (e) {
console.log(`[ConnectionListener] Error parsing sync topic message`, e);
}
};
const handleNotification = async (subscriptionId, notification) => {
const added = await subscriptionManager.addNotification(subscriptionId, notification);
if (added) {
const defaultClickAction = (subscription) => navigate(routes.forSubscription(subscription));
await notifier.notify(subscriptionId, notification, defaultClickAction)
}
};
connectionManager.registerStateListener(subscriptionManager.updateState);
2023-01-12 03:38:10 +01:00
connectionManager.registerMessageListener(handleMessage);
return () => {
connectionManager.resetStateListener();
2023-01-12 03:38:10 +01:00
connectionManager.resetMessageListener();
}
},
// We have to disable dep checking for "navigate". This is fine, it never changes.
// eslint-disable-next-line
[]
);
2023-01-24 21:31:39 +01:00
// Sync topic listener: For accounts with sync_topic, subscribe to an internal topic
useEffect(() => {
if (!account || !account.sync_topic) {
return;
}
subscriptionManager.add(config.base_url, account.sync_topic, true); // Dangle!
}, [account]);
// When subscriptions or users change, refresh the connections
useEffect(() => {
connectionManager.refresh(subscriptions, users); // Dangle
}, [subscriptions, 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 04:47:12 +01:00
const baseUrl = (params.baseUrl) ? expandSecureUrl(params.baseUrl) : config.base_url;
console.log(`[App] Auto-subscribing to ${topicUrl(baseUrl, params.topic)}`);
(async () => {
const subscription = await subscriptionManager.add(baseUrl, params.topic);
2022-12-09 02:50:48 +01:00
if (session.exists()) {
try {
2022-12-25 17:59:44 +01:00
const remoteSubscription = await accountApi.addSubscription({
base_url: baseUrl,
topic: params.topic
});
await subscriptionManager.setRemoteId(subscription.id, remoteSubscription.id);
} catch (e) {
console.log(`[App] Auto-subscribing failed`, e);
if ((e instanceof UnauthorizedError)) {
session.resetAndRedirect(routes.login);
}
}
2022-12-09 02:50:48 +01:00
}
poller.pollInBackground(subscription); // Dangle!
})();
}
}, [params, subscriptions, selected, hasRun]);
};
2022-03-11 21:17:12 +01: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-11 21:17:12 +01:00
*/
export const useBackgroundProcesses = () => {
useEffect(() => {
poller.startWorker();
pruner.startWorker();
2022-12-25 19:42:44 +01:00
accountApi.startWorker();
}, []);
}
2023-01-03 04:21:11 +01:00
export const useAccountListener = (setAccount) => {
useEffect(() => {
accountApi.registerListener(setAccount);
2023-01-12 03:38:10 +01:00
accountApi.sync(); // Dangle
2023-01-03 04:21:11 +01:00
return () => {
2023-01-12 03:38:10 +01:00
accountApi.resetListener();
2023-01-03 04:21:11 +01:00
}
}, []);
}