aboutsummaryrefslogtreecommitdiff
path: root/src/service-worker.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/service-worker.ts')
-rw-r--r--src/service-worker.ts40
1 files changed, 31 insertions, 9 deletions
diff --git a/src/service-worker.ts b/src/service-worker.ts
index 7d2310f6..082a25de 100644
--- a/src/service-worker.ts
+++ b/src/service-worker.ts
@@ -4,6 +4,8 @@
/// <reference lib="webworker" />
import { build, files, version } from '$service-worker';
+import { database } from './lib/Database/user';
+import { type Notification, notifications } from './lib/Data/AniList/notifications';
const sw = /** @type {ServiceWorkerGlobalScope} */ /** @type {unknown} */ self;
@@ -90,19 +92,39 @@ self.addEventListener('fetch', (event) => {
event.respondWith(respond());
});
-self.addEventListener('push', (e: Event) => {
- if (!(self.Notification && self.Notification.permission === 'granted')) {
+self.addEventListener('push', async () => {
+ if (self.Notification && self.Notification.permission !== 'granted') {
return;
}
- const event = e as PushEvent;
+ try {
+ const user = (await database.users.toArray()).at(0);
+
+ if (!user) return;
+
+ const recentNotifications = await notifications(user.user.accessToken);
+
+ if (
+ recentNotifications &&
+ recentNotifications.length > 0 &&
+ (recentNotifications[0].id > (user.lastNotificationID as number) ||
+ new Date(recentNotifications[0].createdAt * 1000).getTime() + 30000 > new Date().getTime())
+ ) {
+ await database.users.update(user.id, { lastNotificationID: recentNotifications[0].id });
- if (event.data) {
- event.waitUntil(
(self as unknown as ServiceWorkerGlobalScope).registration.showNotification('due.moe', {
- body: event.data.json().url,
- icon: '/favicon-196x196.png'
- })
- );
+ body: `${recentNotifications[0].user.name}${recentNotifications[0].context}`,
+ icon: recentNotifications[0].user.avatar.large || '/favicon-196x196.png'
+ });
+ }
+ } catch (error) {
+ console.error(error);
}
});
+
+self.addEventListener('notificationclick', (e: Event) => {
+ const event = e as NotificationEvent;
+
+ event.notification.close();
+ event.waitUntil(clients.openWindow('https://anilist.co/notifications'));
+});