1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
import { env } from "$env/dynamic/public";
import {
isNotificationQueued,
notifications,
updateLastNotificationID,
} from "$lib/Data/AniList/notifications";
import { database } from "$lib/Database/IDB/user";
import { getFingerprint } from "./fingerprint";
import root from "./root";
export const requestNotifications = async () => {
if ("Notification" in window && navigator.serviceWorker) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
try {
const pushSubscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: env.PUBLIC_VAPID_PUBLIC_KEY,
});
await fetch(
root(`/api/notifications/subscribe?p=${getFingerprint()}`),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(pushSubscription),
},
);
} catch {
await fetch(`/api/notifications/unsubscribe?p=${getFingerprint()}`, {
method: "POST",
});
await updateLocalNotifications();
setInterval(async () => await updateLocalNotifications(), 1000 * 60);
}
}
}
};
const updateLocalNotifications = async () => {
const user = (await database.users.toArray()).at(0);
if (!user) return;
const recentNotifications = await notifications(user.user.accessToken);
if ((await window.Notification.requestPermission()) === "granted")
if (
recentNotifications &&
isNotificationQueued(recentNotifications, user.lastNotificationID)
) {
await updateLastNotificationID(user.id, recentNotifications);
new Notification("due.moe", {
body: `${recentNotifications[0].user.name}${recentNotifications[0].context}`,
icon:
recentNotifications[0].user.avatar.large || "/favicon-196x196.png",
tag: "notification-1",
});
}
};
|