forked from memberapp/memberapp.github.io
-
Notifications
You must be signed in to change notification settings - Fork 6
/
sw.js
344 lines (289 loc) · 9.25 KB
/
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// sw.js
// A list of local resources we always want to be cached.
const PRECACHE_URLS = [
'pwa/manifest.webmanifest',
'css/feels.css',
'css/base.css',
'locale/en.json'
];
//If updating version here, also update version in login.js
const version = '6.0.4';
const RUNTIME = 'runtime-' + version;
const INSTALL = 'install-' + version;
const pushNotificationsPublicKey = 'BFG-5VUdKBFXFOOLxD5Jqmjbzw0lJaThIyVlx6QzsE70T_9_v0vgIn2IxYbKcgrXGLaiPmapddgAYFtdKe00q5A';
const SERVER_URL = '/v2/pn/sub';
var swpubkey = "";
self.addEventListener('install', (event) => {
self.skipWaiting()
console.log('[ServiceWorker] Skipped Waiting:');
event.waitUntil(
caches.open(INSTALL).then((cache) => {
return cache.addAll(PRECACHE_URLS);
})
);
});
self.addEventListener("activate", async function (event) {
console.log('[ServiceWorker] Activated. v' + version);
const currentCaches = [INSTALL, RUNTIME];
self.clients.matchAll({
includeUncontrolled: true
}).then(function (clientList) {
var urls = clientList.map(function (client) {
return client.url;
});
console.log('[ServiceWorker] Matching clients:', urls.join(', '));
});
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.map(function (cacheName) {
if (cacheName !== !currentCaches.includes(cacheName)) {
console.log('[ServiceWorker] Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
}).then(function () {
console.log('[ServiceWorker] Claiming clients for version', version);
return self.clients.claim();
})
);
//self.onpushsubscriptionchange();
});
self.addEventListener('fetch', function (event) {
if (event.request.url.includes('/versionmember')) {
event.respondWith(new Response(version, {
headers: {
'content-type': 'text/plain'
}
}));
}
else if (event.request.url.includes('/invalidatecache')) {
caches.delete(event.request);
event.respondWith(new Response("sw.js invalidated cache "+event.request), {
headers: {
'content-type': 'text/plain'
}
});
}
else if (event.request.url.startsWith(self.location.origin) && !event.request.url.includes('/v2/') ) {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
return caches.open(RUNTIME).then(cache => {
return fetch(event.request).then(response => {
// Put a copy of the response in the runtime cache.
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
});
})
);
}
});
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('message', function (event) {
//Message received from client
console.log(event.data);
if (event.data == 'subscribe') {
self.onpushsubscriptionchange();
} else {
swpubkey = event.data;
}
//Send response to client using the port that was sent with the message
//event.ports[0].postMessage("world");
});
//Push Notification Stuff
// urlB64ToUint8Array is a magic function that will encode the base64 public key
// to Array buffer which is needed by the subscription option
const urlB64ToUint8Array = base64String => {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
const rawData = atob(base64)
const outputArray = new Uint8Array(rawData.length)
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray
}
//self.onpushsubscriptionchange = subscribeForNotifications();
self.onpushsubscriptionchange = async function () {
// Push Notifications Stuff
// This will be called only once when the service worker is activated.
try {
const applicationServerKey = urlB64ToUint8Array(pushNotificationsPublicKey);
const options = { applicationServerKey, userVisibleOnly: true };
const subscription = await self.registration.pushManager.subscribe(options);
const response = await saveSubscription(subscription);
console.log(JSON.stringify(response))
} catch (err) {
console.log('Error', err)
}
}
// saveSubscription saves the subscription to the backend
const saveSubscription = async subscription => {
console.log(subscription);
console.log(SERVER_URL + swpubkey);
const response = await fetch(SERVER_URL + '?' + new URLSearchParams({ subscription: JSON.stringify(subscription), address: swpubkey }), { method: 'get', headers: { 'Content-Type': 'application/json' } });
console.log(response);
return response;
}
self.addEventListener("push", function (event) {
//console.log("Push event!! ", "test");
//showLocalNotification("Yolo", "test", self.registration);
if (event.data) {
console.log("Push event!! ", event.data.json());
showLocalNotification(event.data.json(), self.registration);
} else {
console.log("Push event but no data");
showLocalNotification("Error", self.registration);
}
});
const showLocalNotification = (payload, swRegistration) => {
//swRegistration.showNotification(title, {});
//showLocalNotification("Push Event", "Error", swRegistration);
var txid;
var name;
var picurl;
var pagingid;
var icon;
try {
body = payload.type;
txid = payload.txid;
name = payload.name;
picurl = payload.picurl;
pagingid = payload.pagingid;
} catch (err) {
//Probably the old type where the action is the whole body
}
var title = "Error";
var renotify = false;
var text = "";
switch (body) {
case "rating":
title = "Rated";
text = "Rating from @"+pagingid;
icon = "/img/notificationicons/rating.svg";
renotify = true;
break;
case "message":
title = "Message";
text = "Message from @"+pagingid;
icon = "/img/notificationicons/message.svg";
renotify = true;
break;
case "follow":
title = "Followed";
text = "Followed by @"+pagingid;
icon = "/img/notificationicons/follow.svg";
renotify = true;
break;
case "page":
title = "Paged";
text = "Paged by @"+pagingid;
icon = "/img/notificationicons/page.svg";
renotify = true;
break;
case "repost":
title = "Remembered";
text = "Remembered by @"+pagingid;
icon = "/img/notificationicons/repost.svg";
renotify = true;
break;
case "tip":
title = "Tipped";
text = "Tipped by @"+pagingid;
icon = "/img/notificationicons/tip.svg";
renotify = true;
break;
case "reply":
title = "Reply";
text = "Reply from @"+pagingid;
icon = "/img/notificationicons/reply.svg";
renotify = true;
break;
case "like":
title = "Liked";
text = "Liked by @"+pagingid;
icon = "/img/notificationicons/like.svg";
break;
case "thread":
title = "Reply";
text = "Thread reply by @"+pagingid;
icon = "/img/notificationicons/thread.svg";
break;
case "topic":
title = "Tag";
text = "Subscribed Tag Post by @"+pagingid;
icon = "/img/notificationicons/topic.svg";
break;
default:
}
const options = {
body: text,
tag: title,
renotify: true,
icon: icon,
data: {
time: new Date(Date.now()).toString(),
txid: txid
}
};
swRegistration.showNotification(title, options);
};
self.addEventListener('notificationclick', function (event) {
const clickedNotification = event.notification;
const page = '/index.html#notifications?txid=' + event.notification.data.txid;
//const promiseChain = clients.openWindow(page);
//event.waitUntil(promiseChain);
//find open window to show notification
const promiseChain = clients.matchAll({
type: 'window',
includeUncontrolled: true
}).then((windowClients) => {
let matchingClient = null;
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.url.startsWith("https://member.cash") && windowClient.url.includes('#notifications')) {
matchingClient = windowClient;
break;
}
}
if (matchingClient) {
//matchingClient.url = "https://member.cash" + page;
matchingClient.postMessage({
notificationpage: "https://member.cash" + page
});
return matchingClient.focus();
} else {
return clients.openWindow(page).then(windowClient => windowClient ? windowClient.focus() : null);
}
});
clickedNotification.close();
event.waitUntil(promiseChain);
// Do something as the result of the notification click
//const promiseChain = doSomething();
//event.waitUntil(promiseChain);
});
//https://developers.google.com/web/fundamentals/push-notifications/common-notification-patterns
function isClientFocused() {
return clients.matchAll({
type: 'window',
includeUncontrolled: true
}).then((windowClients) => {
let clientIsFocused = false;
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.focused) {
clientIsFocused = true;
break;
}
}
return clientIsFocused;
});
}