Signed-off-by: moshyfawn email@moshyfawn.dev
+13
-4
entrypoints/background.ts
+13
-4
entrypoints/background.ts
···
1
1
import {
2
+
DEFAULT_POLL_INTERVAL,
2
3
fetchNotificationCount,
3
4
getNotificationsUrl,
4
5
getNotificationsUrlPattern,
···
6
7
import { renderCount, renderError } from "@/utils/badge";
7
8
import { notificationCount } from "@/utils/storage";
8
9
9
-
const POLL_INTERVAL_MINUTES = 1;
10
+
const scheduleNextPoll = (intervalSeconds: number): void => {
11
+
browser.alarms.clear("poll");
12
+
browser.alarms.create("poll", {
13
+
delayInMinutes: Math.max(intervalSeconds / 60, 1),
14
+
});
15
+
};
10
16
11
17
const updateCount = async (): Promise<void> => {
12
18
try {
13
-
const count = await fetchNotificationCount();
19
+
const { count, pollInterval } = await fetchNotificationCount();
14
20
await notificationCount.setValue(count);
15
21
renderCount(count);
22
+
scheduleNextPoll(pollInterval);
16
23
} catch {
17
24
renderError();
25
+
scheduleNextPoll(DEFAULT_POLL_INTERVAL);
18
26
}
19
27
};
20
28
21
29
export default defineBackground(() => {
22
30
const action = browser.action ?? browser.browserAction;
23
31
24
-
browser.alarms.create("poll", { periodInMinutes: POLL_INTERVAL_MINUTES });
25
-
browser.alarms.onAlarm.addListener(() => updateCount());
32
+
browser.alarms.onAlarm.addListener((alarm) => {
33
+
if (alarm.name === "poll") updateCount();
34
+
});
26
35
27
36
action.onClicked.addListener(async () => {
28
37
const tabs = await browser.tabs.query({
+14
-2
utils/api.ts
+14
-2
utils/api.ts
···
1
1
const BASE_URL = "https://tangled.org";
2
2
3
+
export const DEFAULT_POLL_INTERVAL = 60;
4
+
3
5
export const getNotificationsUrl = (): string => `${BASE_URL}/notifications`;
4
6
5
7
export const getNotificationsUrlPattern = (): string =>
6
8
`${BASE_URL}/notifications*`;
7
9
8
-
export const fetchNotificationCount = async (): Promise<number> => {
10
+
export interface NotificationResult {
11
+
count: number;
12
+
pollInterval: number;
13
+
}
14
+
15
+
export const fetchNotificationCount = async (): Promise<NotificationResult> => {
9
16
const response = await fetch(`${BASE_URL}/notifications/count`, {
10
17
credentials: "include",
11
18
});
···
13
20
if (!response.ok) throw new Error(`HTTP ${response.status}`);
14
21
const html = await response.text();
15
22
const match = html.match(/(\d+)/);
16
-
return match ? parseInt(match[1], 10) : 0;
23
+
const pollInterval =
24
+
Number(response.headers.get("X-Poll-Interval")) || DEFAULT_POLL_INTERVAL;
25
+
return {
26
+
count: match ? parseInt(match[1], 10) : 0,
27
+
pollInterval,
28
+
};
17
29
};
History
1 round
0 comments
moshyfawn.dev
submitted
#0
1 commit
expand
collapse
feat: use notifications polling interval header
Signed-off-by: moshyfawn <email@moshyfawn.dev>
merge conflicts detected
expand
collapse
expand
collapse
- utils/api.ts:13