1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-12-28 20:52:30 +01:00
ntfy/web/src/app/Poller.js

63 lines
1.7 KiB
JavaScript
Raw Normal View History

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