More work on service worker.

Ylian Saint-Hilaire committed Feb 8, 2021 at 23:35 UTC 9bdeafb2526b29d7716e8bf3147b6c3604e95a7e
2 files changed +104 -10
public/serviceworker.js new
+65
@@ -0,0 +1,65 @@
1 +
2 +// "BMWzSl5zZPWw_lAKVvQb8NZBQwCs83jQJc68cj04yQTYt_kAIvuCMte0wU7BXjODXuGn8ut5qwU0pR_44dZuAmQ"
3 +
4 +self.addEventListener('install', event => {
5 + console.log('Service Worker install', event);
6 +});
7 +
8 +
9 +// This will be called only once when the service worker is activated.
10 +self.addEventListener('activate', async() => {
11 +try {
12 + const applicationServerKey = urlB64ToUint8Array('BMWzSl5zZPWw_lAKVvQb8NZBQwCs83jQJc68cj04yQTYt_kAIvuCMte0wU7BXjODXuGn8ut5qwU0pR_44dZuAmQ')
13 + const options = { applicationServerKey, userVisibleOnly: true }
14 + const subscription = await self.registration.pushManager.subscribe(options)
15 + console.log(JSON.stringify(subscription))
16 + } catch (err) {
17 + console.log('Error', err)
18 + }
19 +})
20 +
21 +self.addEventListener('push', function (event) {
22 + console.log('Service Worker push', event);
23 + if (event.data) {
24 + console.log("Push event!! ", event.data.text());
25 + showLocalNotification("Yolo", event.data.text(), self.registration);
26 + } else {
27 + console.log("Push event but no data");
28 + }
29 +});
30 +
31 +
32 +self.addEventListener('message', function(event) {
33 + console.log('Service Worker message', event);
34 + if (isObject(event.data)) {
35 + if (event.data.type === 'sync') {
36 + // in this way, you can decide your tag
37 + //const id = event.data.id || uuid()
38 + // pass the port into the memory stor
39 + //syncStore[id] = Object.assign({ port: event.ports[0] }, event.data)
40 + //self.registration.sync.register(id)
41 + }
42 + }
43 +})
44 +
45 +self.addEventListener('sync', function(event) {
46 + console.log('Service Worker sync', event);
47 +})
48 +
49 +const showLocalNotification = function(title, body, swRegistration) {
50 + const options = {
51 + body
52 + // here you can add more properties like icon, image, vibrate, etc.
53 + };
54 + swRegistration.showNotification(title, options);
55 +};
56 +
57 +// Used to convert Base64 public VAPID key to bytearray.
58 +function urlBase64ToUint8Array(base64String) {
59 + const padding = '='.repeat((4 - base64String.length % 4) % 4);
60 + const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
61 + const rawData = window.atob(base64);
62 + const outputArray = new Uint8Array(rawData.length);
63 + for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); }
64 + return outputArray;
65 +}
\ No newline at end of file
views/default.handlebars
+39 -10
@@ -354,6 +354,7 @@
354 <p class="mL">
355 <span id="managePhoneNumber2" style="display:none"><a href=# onclick="return account_managePhone()">Manage phone number</a><br /></span>
356 <span id="verifyEmailId" style="display:none"><a href=# onclick="return account_showVerifyEmail()">Verify email</a><br /></span>
357 + <span id="accountEnablePushNotificationsSpan" style="display:none"><a href=# onclick="return account_enablePushNotifications()">Enable push notifications</a><br /></span>
358 <span id="accountEnableNotificationsSpan" style="display:none"><a href=# onclick="return account_enableNotifications()">Enable web notifications</a><br /></span>
359 <a href=# onclick="return account_showLocalizationSettings()">Localization Settings</a><br />
360 <a href=# onclick="return account_showAccountNotifySettings()">Notification Settings</a><br />
@@ -1359,6 +1360,37 @@
1360 // Fix links if a loginKey is used
1361 if (urlargs.key) { Q('termsLinkFooter').href += '?key=' + urlargs.key; }
1362
1363 + /*
1364 + // Register the service worker
1365 + if ('serviceWorker' in navigator) {
1366 + navigator.serviceWorker.addEventListener('message', function(event) {
1367 + console.log("Client message from service worker: " + event);
1368 + });
1369 +
1370 + navigator.serviceWorker.register('serviceworker.js')
1371 + .then(function(reg) {
1372 + // Registration worked
1373 + console.log('Registration succeeded. Scope is ' + reg.scope);
1374 +
1375 + reg.pushManager.getSubscription().then(function(sub) {
1376 + if (sub === null) {
1377 + // Update UI to ask user to register for Push
1378 + console.log('Not subscribed to push service.');
1379 + } else {
1380 + // We have a subscription, update the database
1381 + console.log('Subscription object: ', sub);
1382 +
1383 + navigator.serviceWorker.controller.postMessage({type: 'sync', text: 'Hello!'})
1384 + }
1385 + });
1386 +
1387 + }).catch((error) => {
1388 + // Registration failed
1389 + console.log('Registration failed with ' + error);
1390 + });
1391 + }
1392 + */
1393 +
1394 // Check if we are in debug mode
1395 args = parseUriArgs();
1396 if (args.key && (isAlphaNumeric(args.key) == false)) { delete args.key; }
@@ -2066,6 +2098,7 @@
2098 serverinfo = message.serverinfo;
2099 if (serverinfo.timeout) { setInterval(checkIdleSessionTimeout, 10000); checkIdleSessionTimeout(); }
2100 if (debugmode == 1) { console.log('Server time: ', printDateTime(new Date(serverinfo.serverTime))); }
2101 + //console.log(serverinfo);
2102 break;
2103 }
2104 case 'userinfo': {
@@ -9659,6 +9692,11 @@
9692 }
9693 }
9694
9695 + function account_enablePushNotifications() {
9696 + if ((serverinfo == null) || (serverinfo.vapidpublickey == null)) return;
9697 + return false;
9698 + }
9699 +
9700 function account_enableNotifications() {
9701 if (Notification) { Notification.requestPermission().then(function (permission) { QV('accountEnableNotificationsSpan', permission != 'granted'); }); }
9702 return false;
@@ -14043,6 +14081,7 @@
14081
14082 // Setup web notifications
14083 if ((x == 2) && Notification) { QV('accountEnableNotificationsSpan', Notification.permission != 'granted'); }
14084 + //QV('accountEnablePushNotificationsSpan', true);
14085
14086 // Fetch the server timeline stats if needed
14087 if ((x == 40) && (serverTimelineStats == null)) { refreshServerTimelineStats(); }
@@ -14449,16 +14488,6 @@
14488 function round(value, precision) { var multiplier = Math.pow(10, precision || 0); return Math.round(value * multiplier) / multiplier; }
14489 function safeNewWindow(url, target) { var newWindow = window.open(url, target, 'noopener,noreferrer'); if (newWindow) { newWindow.opener = null; } }
14490
14452 - // Used to convert Base64 public VAPID key to bytearray.
14453 - function urlBase64ToUint8Array(base64String) {
14454 - const padding = '='.repeat((4 - base64String.length % 4) % 4);
14455 - const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
14456 - const rawData = window.atob(base64);
14457 - const outputArray = new Uint8Array(rawData.length);
14458 - for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); }
14459 - return outputArray;
14460 - }
14461 -
14491 // Webkit seems to have a problem with "download" tag causing "network error", but openning the download in a hidden frame fixes it.
14492 // So we do that for all browsers except FireFox
14493 function downloadFile(link, name, closeDialog) {