forked from ionic-team/ionic-conference-app
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main-sw.js
82 lines (69 loc) · 2.58 KB
/
main-sw.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
importScripts('ngsw-worker.js');
importScripts('firebase-messaging-sw.js');
importScripts('idb-keyval-iife.min.js');
let sessionIdsOfSentNotifications = [];
async function getStoredNotifications() {
sessionIdsOfSentNotifications = await idbKeyval.get('sessionIdsOfSentNotifications') || [];
}
const showNotification = (session) => {
return self.registration.showNotification(
'Your favorite session will start soon',
{
body: `${session.location} will host "${session.name}".`,
icon: 'https://itnext-summit-2018.firebaseapp.com/assets/icons/icon-192x192.png',
vibrate: [100, 100, 200, 300],
tag: 'session',
data: session,
}).then(() => {
sessionIdsOfSentNotifications.push(session.id);
idbKeyval.set('sessionIdsOfSentNotifications', sessionIdsOfSentNotifications);
});
};
const isSessionAboutToStart = (session) => {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const [sessionHours, sessionMinutes] = session.timeStart.split(':');
const getNotificationTime = () => {
const minutesReference = parseInt(sessionMinutes, 10) - 5;
if (minutesReference < 0) {
return `${parseInt(sessionHours, 10) - 1}:${60 + minutesReference}`;
} else {
return `${sessionHours}:${minutesReference}`;
}
};
const notificationTime = getNotificationTime();
return Date.parse(`01/01/2018 ${hours}:${minutes}`) >= Date.parse(`01/01/2018 ${notificationTime}`) &&
Date.parse(`01/01/2018 ${hours}:${minutes}`) <= Date.parse(`01/01/2018 ${session.timeStart}`);
};
const isNotificationNotSentForSession = (session) => {
return !sessionIdsOfSentNotifications.includes(session.id);
};
const sendNotificationForSessionsAboutToStart = (sessions) => {
sessions
.filter(isSessionAboutToStart)
.filter(isNotificationNotSentForSession)
.forEach((session) => {
showNotification(session);
});
};
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil(clients.matchAll({
type: 'window'
}).then((clientList) => {
if (event.notification.tag && event.notification.tag === 'session' && clients.openWindow) {
return clients.openWindow(`/app/tabs/(schedule:session/${event.notification.data.id})`);
} else {
for (let i = 0; i < clientList.length; i++) {
const client = clientList[i];
return client.focus();
}
}
}));
});
setInterval(async () => {
const favorites = await idbKeyval.get('favorites') || [];
await getStoredNotifications();
sendNotificationForSessionsAboutToStart(favorites);
}, 1000 * 5);