ntfy/web/src/app/Poller.js

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

66 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-03-03 10:16:30 +13:00
import api from "./Api";
import subscriptionManager from "./SubscriptionManager";
2022-03-03 10:16:30 +13:00
2023-02-12 14:45:04 +13:00
const delayMillis = 2000; // 2 seconds
2022-03-03 10:16:30 +13:00
const intervalMillis = 300000; // 5 minutes
class Poller {
constructor() {
this.timer = null;
}
startWorker() {
if (this.timer !== null) {
return;
}
2022-03-09 05:33:17 +13:00
console.log(`[Poller] Starting worker`);
2022-03-03 10:16:30 +13:00
this.timer = setInterval(() => this.pollAll(), intervalMillis);
setTimeout(() => this.pollAll(), delayMillis);
2023-05-24 07:13:01 +12:00
}
2022-03-03 10:16:30 +13:00
stopWorker() {
clearTimeout(this.timer);
}
2022-03-03 10:16:30 +13:00
async pollAll() {
console.log(`[Poller] Polling all subscriptions`);
const subscriptions = await subscriptionManager.all();
await Promise.all(
subscriptions.map(async (s) => {
try {
await this.poll(s);
} catch (e) {
console.log(`[Poller] Error polling ${s.id}`, e);
}
})
);
2023-05-24 07:13:01 +12:00
}
2022-03-03 10:16:30 +13:00
async poll(subscription) {
console.log(`[Poller] Polling ${subscription.id}`);
const since = subscription.last;
const notifications = await api.poll(subscription.baseUrl, subscription.topic, since);
if (!notifications || notifications.length === 0) {
console.log(`[Poller] No new notifications found for ${subscription.id}`);
return;
}
console.log(`[Poller] Adding ${notifications.length} notification(s) for ${subscription.id}`);
await subscriptionManager.addNotifications(subscription.id, notifications);
2023-05-24 07:13:01 +12:00
}
pollInBackground(subscription) {
(async () => {
2023-05-24 07:13:01 +12:00
try {
2022-03-03 10:16:30 +13:00
await this.poll(subscription);
2023-05-24 07:13:01 +12:00
} catch (e) {
console.error(`[App] Error polling subscription ${subscription.id}`, e);
2023-05-24 07:13:01 +12:00
}
})();
2023-05-24 07:13:01 +12:00
}
2022-03-03 10:16:30 +13:00
}
const poller = new Poller();
export default poller;