-
Notifications
You must be signed in to change notification settings - Fork 115
/
ServiceWorker.ts
executable file
·1178 lines (1065 loc) · 47.9 KB
/
ServiceWorker.ts
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import bowser from "bowser";
import Environment from "../Environment";
import { WorkerMessenger, WorkerMessengerCommand, WorkerMessengerMessage } from "../libraries/WorkerMessenger";
import SdkEnvironment from "../managers/SdkEnvironment";
import ContextSW from "../models/ContextSW";
import OneSignalApiBase from "../OneSignalApiBase";
import OneSignalApiSW from "../OneSignalApiSW";
import Database from "../services/Database";
import { UnsubscriptionStrategy } from "../models/UnsubscriptionStrategy";
import { RawPushSubscription } from "../models/RawPushSubscription";
import { SubscriptionStateKind } from "../models/SubscriptionStateKind";
import { SubscriptionStrategyKind } from "../models/SubscriptionStrategyKind";
import { PushDeviceRecord } from "../models/PushDeviceRecord";
import {
UpsertSessionPayload, DeactivateSessionPayload,
PageVisibilityRequest, PageVisibilityResponse, SessionStatus
} from "../models/Session";
import Log from "../libraries/sw/Log";
import { ConfigHelper } from "../helpers/ConfigHelper";
import { OneSignalUtils } from "../utils/OneSignalUtils";
import { Utils } from "../context/shared/utils/Utils";
import {
OSWindowClient, OSServiceWorkerFields
} from "./types";
import ServiceWorkerHelper from "../helpers/ServiceWorkerHelper";
import { NotificationReceived, NotificationClicked } from "../models/Notification";
import { cancelableTimeout } from "../helpers/sw/CancelableTimeout";
import { DeviceRecord } from '../models/DeviceRecord';
declare var self: ServiceWorkerGlobalScope & OSServiceWorkerFields;
declare var Notification: Notification;
/**
* The main service worker script fetching and displaying notifications to users in the background even when the client
* site is not running. The worker is registered via the navigator.serviceWorker.register() call after the user first
* allows notification permissions, and is a pre-requisite to subscribing for push notifications.
*
* For HTTPS sites, the service worker is registered site-wide at the top-level scope. For HTTP sites, the service
* worker is registered to the iFrame pointing to subdomain.onesignal.com.
*/
export class ServiceWorker {
static UNSUBSCRIBED_FROM_NOTIFICATIONS: boolean | undefined;
/**
* An incrementing integer defined in package.json. Value doesn't matter as long as it's different from the
* previous version.
*/
static get VERSION() {
return Environment.version();
}
/**
* Describes what context the JavaScript code is running in and whether we're running in local development mode.
*/
static get environment() {
return Environment;
}
static get log() {
return Log;
}
/**
* An interface to the browser's IndexedDB.
*/
static get database() {
return Database;
}
/**
* Describes the current browser name and version.
*/
static get browser() {
return bowser;
}
/**
* Allows message passing between this service worker and its controlled clients, or webpages. Controlled
* clients include any HTTPS site page, or the nested iFrame pointing to OneSignal on any HTTP site. This allows
* events like notification dismissed, clicked, and displayed to be fired on the clients. It also allows the
* clients to communicate with the service worker to close all active notifications.
*/
static get workerMessenger(): WorkerMessenger {
if (!(self as any).workerMessenger) {
(self as any).workerMessenger = new WorkerMessenger(null);
}
return (self as any).workerMessenger;
}
/**
* Service worker entry point.
*/
static run() {
self.addEventListener('push', ServiceWorker.onPushReceived);
self.addEventListener('notificationclose', ServiceWorker.onNotificationClosed);
self.addEventListener('notificationclick', event => event.waitUntil(ServiceWorker.onNotificationClicked(event)));
self.addEventListener('install', ServiceWorker.onServiceWorkerInstalled);
self.addEventListener('activate', ServiceWorker.onServiceWorkerActivated);
self.addEventListener('pushsubscriptionchange', (event: PushSubscriptionChangeEvent) => {
event.waitUntil(ServiceWorker.onPushSubscriptionChange(event))
});
self.addEventListener('message', (event: ExtendableMessageEvent) => {
const data: WorkerMessengerMessage = event.data;
if (!data || !data.command) {
return;
}
const payload = data.payload;
switch(data.command) {
case WorkerMessengerCommand.SessionUpsert:
Log.debug("[Service Worker] Received SessionUpsert", payload);
ServiceWorker.debounceRefreshSession(event, payload as UpsertSessionPayload);
break;
case WorkerMessengerCommand.SessionDeactivate:
Log.debug("[Service Worker] Received SessionDeactivate", payload);
ServiceWorker.debounceRefreshSession(event, payload as DeactivateSessionPayload);
break;
default:
return;
}
});
/*
According to
https://w3c.github.io/ServiceWorker/#run-service-worker-algorithm:
"user agents are encouraged to show a warning that the event listeners
must be added on the very first evaluation of the worker script."
We have to register our event handler statically (not within an
asynchronous method) so that the browser can optimize not waking up the
service worker for events that aren't known for sure to be listened for.
Also see: https://github.com/w3c/ServiceWorker/issues/1156
*/
Log.debug('Setting up message listeners.');
// self.addEventListener('message') is statically added inside the listen() method
ServiceWorker.workerMessenger.listen();
// Install messaging event handlers for page <-> service worker communication
ServiceWorker.setupMessageListeners();
}
static async getAppId(): Promise<string> {
if (self.location.search) {
const match = self.location.search.match(/appId=([0-9a-z-]+)&?/i);
// Successful regex matches are at position 1
if (match && match.length > 1) {
const appId = match[1];
return appId;
}
}
const { appId } = await Database.getAppConfig();
return appId;
}
static setupMessageListeners() {
ServiceWorker.workerMessenger.on(WorkerMessengerCommand.WorkerVersion, _ => {
Log.debug('[Service Worker] Received worker version message.');
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.WorkerVersion, Environment.version());
});
ServiceWorker.workerMessenger.on(WorkerMessengerCommand.Subscribe, async (appConfigBundle: any) => {
const appConfig = appConfigBundle;
Log.debug('[Service Worker] Received subscribe message.');
const context = new ContextSW(appConfig);
const rawSubscription = await context.subscriptionManager.subscribe(SubscriptionStrategyKind.ResubscribeExisting);
const subscription = await context.subscriptionManager.registerSubscription(rawSubscription);
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.Subscribe, subscription.serialize());
});
ServiceWorker.workerMessenger.on(WorkerMessengerCommand.SubscribeNew, async (appConfigBundle: any) => {
const appConfig = appConfigBundle;
Log.debug('[Service Worker] Received subscribe new message.');
const context = new ContextSW(appConfig);
const rawSubscription = await context.subscriptionManager.subscribe(SubscriptionStrategyKind.SubscribeNew);
const subscription = await context.subscriptionManager.registerSubscription(rawSubscription);
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.SubscribeNew, subscription.serialize());
});
ServiceWorker.workerMessenger.on(WorkerMessengerCommand.AmpSubscriptionState, async (_appConfigBundle: any) => {
Log.debug('[Service Worker] Received AMP subscription state message.');
const pushSubscription = await self.registration.pushManager.getSubscription();
if (!pushSubscription) {
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpSubscriptionState, false);
} else {
const permission = await self.registration.pushManager.permissionState(pushSubscription.options);
const { optedOut } = await Database.getSubscription();
const isSubscribed = !!pushSubscription && permission === "granted" && optedOut !== true;
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpSubscriptionState, isSubscribed);
}
});
ServiceWorker.workerMessenger.on(WorkerMessengerCommand.AmpSubscribe, async () => {
Log.debug('[Service Worker] Received AMP subscribe message.');
const appId = await ServiceWorker.getAppId();
const appConfig = await ConfigHelper.getAppConfig({ appId }, OneSignalApiSW.downloadServerAppConfig);
const context = new ContextSW(appConfig);
const rawSubscription = await context.subscriptionManager.subscribe(SubscriptionStrategyKind.ResubscribeExisting);
const subscription = await context.subscriptionManager.registerSubscription(rawSubscription);
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpSubscribe, subscription.deviceId);
});
ServiceWorker.workerMessenger.on(WorkerMessengerCommand.AmpUnsubscribe, async () => {
Log.debug('[Service Worker] Received AMP unsubscribe message.');
const appId = await ServiceWorker.getAppId();
const appConfig = await ConfigHelper.getAppConfig({ appId }, OneSignalApiSW.downloadServerAppConfig);
const context = new ContextSW(appConfig);
await context.subscriptionManager.unsubscribe(UnsubscriptionStrategy.MarkUnsubscribed);
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpUnsubscribe, null);
});
ServiceWorker.workerMessenger.on(
WorkerMessengerCommand.AreYouVisibleResponse, async (payload: PageVisibilityResponse) => {
Log.debug('[Service Worker] Received response for AreYouVisible', payload);
if (!self.clientsStatus) { return; }
const timestamp = payload.timestamp;
if (self.clientsStatus.timestamp !== timestamp) { return; }
self.clientsStatus.receivedResponsesCount++;
if (payload.focused) {
self.clientsStatus.hasAnyActiveSessions = true;
}
}
);
ServiceWorker.workerMessenger.on(
WorkerMessengerCommand.SetLogging, async (payload: {shouldLog: boolean}) => {
if (payload.shouldLog) {
self.shouldLog = true;
} else {
self.shouldLog = undefined;
}
}
);
}
/**
* Occurs when a push message is received.
* This method handles the receipt of a push signal on all web browsers except Safari, which uses the OS to handle
* notifications.
*/
static onPushReceived(event: PushEvent): void {
Log.debug(`Called %conPushReceived(${JSON.stringify(event, null, 4)}):`, Utils.getConsoleStyle('code'), event);
event.waitUntil(
ServiceWorker.parseOrFetchNotifications(event)
.then(async (notifications: any) => {
//Display push notifications in the order we received them
const notificationEventPromiseFns = [];
const notificationReceivedPromises: Promise<void>[] = [];
const appId = await Database.get<string>("Ids", "appId");
for (let rawNotification of notifications) {
Log.debug('Raw Notification from OneSignal:', rawNotification);
let notification = ServiceWorker.buildStructuredNotificationObject(rawNotification);
const notificationReceived: NotificationReceived = {
notificationId: notification.id,
appId,
url: notification.url,
timestamp: new Date().getTime(),
};
notificationReceivedPromises.push(Database.put("NotificationReceived", notificationReceived));
// TODO: decide what to do with all the notif received promises
// Probably should have it's own error handling but not blocking the rest of the execution?
// Never nest the following line in a callback from the point of entering from retrieveNotifications
notificationEventPromiseFns.push((notif => {
return ServiceWorker.displayNotification(notif)
.then(() => {
return ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.NotificationDisplayed, notif).catch(e => Log.error(e))
})
.then(() => ServiceWorker.executeWebhooks('notification.displayed', notif)
.then(() => ServiceWorker.sendConfirmedDelivery(notif)).catch(e => Log.error(e)));
}).bind(null, notification));
}
return notificationEventPromiseFns.reduce((p, fn) => {
return p = p.then(fn);
}, Promise.resolve());
})
.catch(e => {
Log.debug('Failed to display a notification:', e);
if (ServiceWorker.UNSUBSCRIBED_FROM_NOTIFICATIONS) {
Log.debug('Because we have just unsubscribed from notifications, we will not show anything.');
return undefined;
}
})
)
}
/**
* Makes a POST call to a specified URL to forward certain events.
* @param event The name of the webhook event. Affects the DB key pulled for settings and the final event the user
* consumes.
* @param notification A JSON object containing notification details the user consumes.
* @returns {Promise}
*/
static async executeWebhooks(event: string, notification: any): Promise<Response | null> {
const webhookTargetUrl = await Database.get<string>('Options', `webhooks.${event}`);
if (!webhookTargetUrl)
return null;
const { deviceId } = await Database.getSubscription();
const isServerCorsEnabled = await Database.get<boolean>('Options', 'webhooks.cors');
// JSON.stringify() does not include undefined values
// Our response will not contain those fields here which have undefined values
const postData = {
event: event,
id: notification.id,
userId: deviceId,
action: notification.action,
buttons: notification.buttons,
heading: notification.heading,
content: notification.content,
url: notification.url,
icon: notification.icon,
data: notification.data
};
const fetchOptions: RequestInit = {
method: 'post',
mode: 'no-cors',
body: JSON.stringify(postData),
};
if (isServerCorsEnabled) {
fetchOptions.mode = 'cors';
fetchOptions.headers = {
'X-OneSignal-Event': event,
'Content-Type': 'application/json'
};
}
Log.debug(
`Executing ${event} webhook ${isServerCorsEnabled ? 'with' : 'without'} CORS %cPOST ${webhookTargetUrl}`,
Utils.getConsoleStyle('code'), ':', postData
);
return await fetch(webhookTargetUrl, fetchOptions);
}
/**
* Makes a PUT call to log the delivery of the notification
* @param notification A JSON object containing notification details.
* @returns {Promise}
*/
static async sendConfirmedDelivery(notification: any): Promise<Response | null> {
if (!notification)
return null;
// Received receipts enabled?
if (notification.rr !== "y")
return null;
const appId = await ServiceWorker.getAppId();
const { deviceId } = await Database.getSubscription();
// app and notification ids are required, decided to exclude deviceId from required params
// In rare case we don't have it we can still report as confirmed to backend to increment count
const hasRequiredParams = !!(appId && notification.id);
if (!hasRequiredParams) {
return null;
}
// JSON.stringify() does not include undefined values
// Our response will not contain those fields here which have undefined values
const postData = {
player_id : deviceId,
app_id : appId
};
Log.debug(`Called %csendConfirmedDelivery(${
JSON.stringify(notification, null, 4)
})`, Utils.getConsoleStyle('code'));
return await OneSignalApiBase.put(`notifications/${notification.id}/report_received`, postData);
}
/**
* Gets an array of active window clients along with whether each window client is the HTTP site's iFrame or an
* HTTPS site page.
* An active window client is a browser tab that is controlled by the service worker.
* Technically, this list should only ever contain clients that are iFrames, or clients that are HTTPS site pages,
* and not both. This doesn't really matter though.
* @returns {Promise}
*/
static async getActiveClients(): Promise<Array<OSWindowClient>> {
const windowClients: ReadonlyArray<Client> = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true
});
const activeClients: Array<OSWindowClient> = [];
for (const client of windowClients) {
const windowClient: OSWindowClient = client as OSWindowClient;
windowClient.isSubdomainIframe = false;
// Test if this window client is the HTTP subdomain iFrame pointing to subdomain.onesignal.com
if (client.frameType && client.frameType === 'nested') {
// Subdomain iFrames point to 'https://subdomain.onesignal.com...'
if (!Utils.contains(client.url, '.os.tc') &&
!Utils.contains(client.url, '.onesignal.com')) {
continue;
}
// Indicates this window client is an HTTP subdomain iFrame
windowClient.isSubdomainIframe = true;
}
activeClients.push(windowClient);
}
return activeClients;
}
static async updateSessionBasedOnHasActive(
event: ExtendableMessageEvent,
hasAnyActiveSessions: boolean, options: DeactivateSessionPayload
) {
if (hasAnyActiveSessions) {
await ServiceWorkerHelper.upsertSession(
options.sessionThreshold,
options.enableSessionDuration,
options.deviceRecord!,
options.deviceId,
options.sessionOrigin,
options.outcomesConfig
);
} else {
const cancelableFinalize = await ServiceWorkerHelper.deactivateSession(
options.sessionThreshold, options.enableSessionDuration, options.outcomesConfig
);
if (cancelableFinalize) {
self.cancel = cancelableFinalize.cancel;
event.waitUntil(cancelableFinalize.promise);
}
}
}
static async refreshSession(event: ExtendableMessageEvent, options: DeactivateSessionPayload): Promise<void> {
Log.debug("[Service Worker] refreshSession");
/**
* if https -> getActiveClients -> check for the first focused
* unfortunately, not enough for safari, it always returns false for focused state of a client
* have to workaround it with messaging to the client.
*
* if http, also have to workaround with messaging:
* SW to iframe -> iframe to page -> page to iframe -> iframe to SW
*/
if (options.isHttps) {
const windowClients: ReadonlyArray<Client> = await self.clients.matchAll(
{ type: "window", includeUncontrolled: false }
);
if (options.isSafari) {
await ServiceWorker.checkIfAnyClientsFocusedAndUpdateSession(event, windowClients, options);
} else {
const hasAnyActiveSessions: boolean = windowClients.some(w => (w as WindowClient).focused);
Log.debug("[Service Worker] isHttps hasAnyActiveSessions", hasAnyActiveSessions);
await ServiceWorker.updateSessionBasedOnHasActive(event, hasAnyActiveSessions, options);
}
return;
} else {
const osClients = await ServiceWorker.getActiveClients();
await ServiceWorker.checkIfAnyClientsFocusedAndUpdateSession(event, osClients, options);
}
}
static async checkIfAnyClientsFocusedAndUpdateSession(
event: ExtendableMessageEvent,
windowClients: ReadonlyArray<Client>,
sessionInfo: DeactivateSessionPayload
): Promise<void> {
const timestamp = new Date().getTime();
self.clientsStatus = {
timestamp,
sentRequestsCount: 0,
receivedResponsesCount: 0,
hasAnyActiveSessions: false,
};
const payload: PageVisibilityRequest = { timestamp };
windowClients.forEach(c => {
if (self.clientsStatus) {
// keeping track of number of sent requests mostly for debugging purposes
self.clientsStatus.sentRequestsCount++;
}
c.postMessage({ command: WorkerMessengerCommand.AreYouVisible, payload });
});
const updateOnHasActive = async () => {
if (!self.clientsStatus) { return; }
if (self.clientsStatus.timestamp !== timestamp) { return; }
Log.debug("updateSessionBasedOnHasActive", self.clientsStatus);
await ServiceWorker.updateSessionBasedOnHasActive(event,
self.clientsStatus.hasAnyActiveSessions, sessionInfo);
self.clientsStatus = undefined;
}
const getClientStatusesCancelable = cancelableTimeout(updateOnHasActive, 0.5);
self.cancel = getClientStatusesCancelable.cancel;
event.waitUntil(getClientStatusesCancelable.promise);
}
static debounceRefreshSession(event: ExtendableMessageEvent, options: DeactivateSessionPayload) {
Log.debug("[Service Worker] debounceRefreshSession", options);
if (self.cancel) {
self.cancel();
self.cancel = undefined;
}
const executeRefreshSession = async () => {
await ServiceWorker.refreshSession(event, options);
};
const cancelableRefreshSession = cancelableTimeout(executeRefreshSession, 1);
self.cancel = cancelableRefreshSession.cancel;
event.waitUntil(cancelableRefreshSession.promise);
}
/**
* Constructs a structured notification object from the raw notification fetched from OneSignal's server. This
* object is passed around from event to event, and is also returned to the host page for notification event details.
* Constructed in onPushReceived, and passed along to other event handlers.
* @param rawNotification The raw notification JSON returned from OneSignal's server.
*/
static buildStructuredNotificationObject(rawNotification) {
let notification: any = {
id: rawNotification.custom.i,
heading: rawNotification.title,
content: rawNotification.alert,
data: rawNotification.custom.a,
url: rawNotification.custom.u,
rr: rawNotification.custom.rr, // received receipts
icon: rawNotification.icon,
image: rawNotification.image,
tag: rawNotification.tag,
badge: rawNotification.badge,
vibrate: rawNotification.vibrate
};
// Add action buttons
if (rawNotification.o) {
notification.buttons = [];
for (let rawButton of rawNotification.o) {
notification.buttons.push({
action: rawButton.i,
title: rawButton.n,
icon: rawButton.p,
url: rawButton.u
});
}
}
return Utils.trimUndefined(notification);
}
/**
* Given an image URL, returns a proxied HTTPS image using the https://images.weserv.nl service.
* For a null image, returns null so that no icon is displayed.
* If the image protocol is HTTPS, or origin contains localhost or starts with 192.168.*.*, we do not proxy the image.
* @param imageUrl An HTTP or HTTPS image URL.
*/
static ensureImageResourceHttps(imageUrl) {
if (imageUrl) {
try {
let parsedImageUrl = new URL(imageUrl);
if (parsedImageUrl.hostname === 'localhost' ||
parsedImageUrl.hostname.indexOf('192.168') !== -1 ||
parsedImageUrl.hostname === '127.0.0.1' ||
parsedImageUrl.protocol === 'https:') {
return imageUrl;
}
if (parsedImageUrl.hostname === 'i0.wp.com' ||
parsedImageUrl.hostname === 'i1.wp.com' ||
parsedImageUrl.hostname === 'i2.wp.com' ||
parsedImageUrl.hostname === 'i3.wp.com') {
/* Their site already uses Jetpack, just make sure Jetpack is HTTPS */
return `https://${parsedImageUrl.hostname}${parsedImageUrl.pathname}`
}
/* HTTPS origin hosts can be used by prefixing the hostname with ssl: */
let replacedImageUrl = parsedImageUrl.host + parsedImageUrl.pathname;
return `https://i0.wp.com/${replacedImageUrl}`;
} catch (e) { }
} else return null;
}
/**
* Given a structured notification object, HTTPS-ifies the notification icons and action button icons, if they exist.
*/
static ensureNotificationResourcesHttps(notification) {
if (notification) {
if (notification.icon) {
notification.icon = ServiceWorker.ensureImageResourceHttps(notification.icon);
}
if (notification.image) {
notification.image = ServiceWorker.ensureImageResourceHttps(notification.image);
}
if (notification.buttons && notification.buttons.length > 0) {
for (let button of notification.buttons) {
if (button.icon) {
button.icon = ServiceWorker.ensureImageResourceHttps(button.icon);
}
}
}
}
}
/**
* Actually displays a visible notification to the user.
* Any event needing to display a notification calls this so that all the display options can be centralized here.
* @param notification A structured notification object.
*/
static async displayNotification(notification, overrides?) {
Log.debug(`Called %cdisplayNotification(${JSON.stringify(notification, null, 4)}):`, Utils.getConsoleStyle('code'), notification);
// Use the default title if one isn't provided
const defaultTitle = await ServiceWorker._getTitle();
// Use the default icon if one isn't provided
const defaultIcon = await Database.get('Options', 'defaultIcon');
// Get option of whether we should leave notification displaying indefinitely
const persistNotification = await Database.get('Options', 'persistNotification');
// Get app ID for tag value
const appId = await ServiceWorker.getAppId();
notification.heading = notification.heading ? notification.heading : defaultTitle;
notification.icon = notification.icon ? notification.icon : (defaultIcon ? defaultIcon : undefined);
const extra: any = {};
extra.tag = notification.tag || appId;
extra.persistNotification = persistNotification !== false;
// Allow overriding some values
if (!overrides)
overrides = {};
notification = {...notification, ...overrides};
ServiceWorker.ensureNotificationResourcesHttps(notification);
let notificationOptions = {
body: notification.content,
icon: notification.icon,
/*
On Chrome 56, a large image can be displayed:
https://bugs.chromium.org/p/chromium/issues/detail?id=614456
*/
image: notification.image,
/*
On Chrome 44+, use this property to store extra information which
you can read back when the notification gets invoked from a
notification click or dismissed event. We serialize the
notification in the 'data' field and read it back in other events.
See:
https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notifications?hl=en
*/
data: notification,
/*
On Chrome 48+, action buttons show below the message body of the
notification. Clicking either button takes the user to a link. See:
https://developers.google.com/web/updates/2016/01/notification-actions
*/
actions: notification.buttons,
/*
Tags are any string value that groups notifications together. Two
or notifications sharing a tag replace each other.
*/
tag: extra.tag,
/*
On Chrome 47+ (desktop), notifications will be dismissed after 20
seconds unless requireInteraction is set to true. See:
https://developers.google.com/web/updates/2015/10/notification-requireInteractiom
*/
requireInteraction: extra.persistNotification,
/*
On Chrome 50+, by default notifications replacing
identically-tagged notifications no longer vibrate/signal the user
that a new notification has come in. This flag allows subsequent
notifications to re-alert the user. See:
https://developers.google.com/web/updates/2016/03/notifications
*/
renotify: true,
/*
On Chrome 53+, returns the URL of the image used to represent the
notification when there is not enough space to display the
notification itself.
The URL of an image to represent the notification when there is not
enough space to display the notification itself such as, for
example, the Android Notification Bar. On Android devices, the
badge should accommodate devices up to 4x resolution, about 96 by
96 px, and the image will be automatically masked.
*/
badge: notification.badge,
/*
A vibration pattern to run with the display of the notification. A
vibration pattern can be an array with as few as one member. The
values are times in milliseconds where the even indices (0, 2, 4,
etc.) indicate how long to vibrate and the odd indices indicate how
long to pause. For example [300, 100, 400] would vibrate 300ms,
pause 100ms, then vibrate 400ms.
*/
vibrate: notification.vibrate
};
notificationOptions = ServiceWorker.fixPlatformSpecificDisplayIssues(notificationOptions);
return self.registration.showNotification(notification.heading, notificationOptions);
}
/**
* Fixes display issue with some notification options causing the notification to never show!
* This happens when setting requireInteraction = true on the following platforms;
* * macOS 10.15+ - Chrome based browsers
* - https://bugs.chromium.org/p/chromium/issues/detail?id=1007418
* * macOS 10.14+ - Opera
* - https://forums.opera.com/topic/31334/push-notifications-with-requireinteraction-true-do-not-display-on-macos
* @param notificationOptions - Value passed to ServiceWorkerRegistration.prototype.showNotification
*/
static fixPlatformSpecificDisplayIssues(notificationOptions: any): any {
const clone = { ...notificationOptions };
const browser = OneSignalUtils.redetectBrowserUserAgent();
if (browser.chrome && browser.mac && Utils.isVersionAtLeast(browser.osversion, 10.15)) {
clone.requireInteraction = false;
}
else if (browser.opera && browser.mac && Utils.isVersionAtLeast(browser.osversion, 10.14)) {
clone.requireInteraction = false;
}
return clone;
}
/**
* Returns false if the given URL matches a few special URLs designed to skip opening a URL when clicking a
* notification. Otherwise returns true and the link will be opened.
* @param url
*/
static shouldOpenNotificationUrl(url) {
return (url !== 'javascript:void(0);' &&
url !== 'do_not_open' &&
!Utils.contains(url, '_osp=do_not_open'));
}
/**
* Occurs when a notification is dismissed by the user (clicking the 'X') or all notifications are cleared.
* Supported on: Chrome 50+ only
*/
static onNotificationClosed(event) {
Log.debug(`Called %conNotificationClosed(${JSON.stringify(event, null, 4)}):`, Utils.getConsoleStyle('code'), event);
let notification = event.notification.data;
ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.NotificationDismissed, notification).catch(e => Log.error(e))
event.waitUntil(
ServiceWorker.executeWebhooks('notification.dismissed', notification)
);
}
/**
* After clicking a notification, determines the URL to open based on whether an action button was clicked or the
* notification body was clicked.
*/
static async getNotificationUrlToOpen(notification): Promise<string> {
// Defaults to the URL the service worker was registered
// TODO: This should be fixed for HTTP sites
let launchUrl = self.registration.scope;
// Use the user-provided default URL if one exists
const { defaultNotificationUrl: dbDefaultNotificationUrl } = await Database.getAppState();
if (dbDefaultNotificationUrl)
launchUrl = dbDefaultNotificationUrl;
// If the user clicked an action button, use the URL provided by the action button
// Unless the action button URL is null
if (notification.action) {
// Find the URL tied to the action button that was clicked
for (let button of notification.buttons) {
if (button.action === notification.action &&
button.url &&
button.url !== '') {
launchUrl = button.url;
}
}
} else if (notification.url &&
notification.url !== '') {
// The user clicked the notification body instead of an action button
launchUrl = notification.url;
}
return launchUrl;
}
/**
* Occurs when the notification's body or action buttons are clicked. Does not occur if the notification is
* dismissed by clicking the 'X' icon. See the notification close event for the dismissal event.
*/
static async onNotificationClicked(event: NotificationEventInit) {
Log.debug(`Called %conNotificationClicked(${JSON.stringify(event, null, 4)}):`, Utils.getConsoleStyle('code'), event);
// Close the notification first here, before we do anything that might fail
event.notification.close();
const notificationData = event.notification.data;
// Chrome 48+: Get the action button that was clicked
if (event.action)
notificationData.action = event.action;
let notificationClickHandlerMatch = 'exact';
let notificationClickHandlerAction = 'navigate';
const matchPreference = await Database.get<string>('Options', 'notificationClickHandlerMatch');
if (matchPreference)
notificationClickHandlerMatch = matchPreference;
const actionPreference = await this.database.get<string>('Options', 'notificationClickHandlerAction');
if (actionPreference)
notificationClickHandlerAction = actionPreference;
const launchUrl: string = await ServiceWorker.getNotificationUrlToOpen(notificationData);
const notificationOpensLink: boolean = ServiceWorker.shouldOpenNotificationUrl(launchUrl);
const appId = await Database.get<string>("Ids", "appId");
const deviceType = DeviceRecord.prototype.getDeliveryPlatform();
let saveNotificationClickedPromise: Promise<void> | undefined;
const notificationClicked: NotificationClicked = {
notificationId: notificationData.id,
appId,
url: launchUrl,
timestamp: new Date().getTime(),
}
Log.info("NotificationClicked", notificationClicked);
saveNotificationClickedPromise = (async (notificationClicked) => {
try {
const existingSession = await Database.getCurrentSession();
if (existingSession && existingSession.status === SessionStatus.Active) {
return;
}
await Database.put("NotificationClicked", notificationClicked);
// upgrade existing session to be directly attributed to the notif
// if it results in re-focusing the site
if (existingSession) {
existingSession.notificationId = notificationClicked.notificationId;
await Database.upsertSession(existingSession);
}
} catch(e) {
Log.error("Failed to save clicked notification.", e);
}
})(notificationClicked);
// Start making REST API requests BEFORE self.clients.openWindow is called.
// It will cause the service worker to stop on Chrome for Android when site is added to the home screen.
const { deviceId } = await Database.getSubscription();
const convertedAPIRequests = ServiceWorker.sendConvertedAPIRequests(appId, deviceId, notificationData, deviceType);
/*
Check if we can focus on an existing tab instead of opening a new url.
If an existing tab with exactly the same URL already exists, then this existing tab is focused instead of
an identical new tab being created. With a special setting, any existing tab matching the origin will
be focused instead of an identical new tab being created.
*/
const activeClients = await ServiceWorker.getActiveClients();
let doNotOpenLink = false;
for (const client of activeClients) {
let clientUrl = client.url;
if ((client as any).isSubdomainIframe) {
const lastKnownHostUrl = await Database.get<string>('Options', 'lastKnownHostUrl');
// TODO: clientUrl is being overwritten by defaultUrl and lastKnownHostUrl.
// Should only use clientUrl if it is not null.
// Also need to decide which to use over the other.
clientUrl = lastKnownHostUrl;
if (!lastKnownHostUrl) {
clientUrl = await Database.get<string>('Options', 'defaultUrl');
}
}
let clientOrigin = '';
try {
clientOrigin = new URL(clientUrl).origin;
} catch (e) {
Log.error(`Failed to get the HTTP site's actual origin:`, e);
}
let launchOrigin = null;
try {
// Check if the launchUrl is valid; it can be null
launchOrigin = new URL(launchUrl).origin;
} catch (e) {}
if ((notificationClickHandlerMatch === 'exact' && clientUrl === launchUrl) ||
(notificationClickHandlerMatch === 'origin' && clientOrigin === launchOrigin)) {
if ((client['isSubdomainIframe'] && clientUrl === launchUrl) ||
(!client['isSubdomainIframe'] && client.url === launchUrl) ||
(notificationClickHandlerAction === 'focus' && clientOrigin === launchOrigin)) {
ServiceWorker.workerMessenger.unicast(WorkerMessengerCommand.NotificationClicked, notificationData, client);
try {
if (client instanceof WindowClient)
await client.focus();
} catch (e) {
Log.error("Failed to focus:", client, e);
}
} else {
/*
We must focus first; once the client navigates away, it may not be to a service worker-controlled page, and
the client ID may change, making it unable to focus.
client.navigate() is available on Chrome 49+ and Firefox 50+.
*/
if (client['isSubdomainIframe']) {
try {
Log.debug('Client is subdomain iFrame. Attempting to focus() client.');
if (client instanceof WindowClient)
await client.focus();
} catch (e) {
Log.error("Failed to focus:", client, e);
}
if (notificationOpensLink) {
Log.debug(`Redirecting HTTP site to ${launchUrl}.`);
await Database.put("NotificationOpened", { url: launchUrl, data: notificationData, timestamp: Date.now() });
ServiceWorker.workerMessenger.unicast(WorkerMessengerCommand.RedirectPage, launchUrl, client);
} else {
Log.debug('Not navigating because link is special.')
}
}
else if (client instanceof WindowClient && client.navigate) {
try {
Log.debug('Client is standard HTTPS site. Attempting to focus() client.');
if (client instanceof WindowClient)
await client.focus();
} catch (e) {
Log.error("Failed to focus:", client, e);
}
try {
if (notificationOpensLink) {
Log.debug(`Redirecting HTTPS site to (${launchUrl}).`)
await Database.put("NotificationOpened", { url: launchUrl, data: notificationData, timestamp: Date.now() });
await client.navigate(launchUrl);
} else {
Log.debug('Not navigating because link is special.')
}
} catch (e) {
Log.error("Failed to navigate:", client, launchUrl, e);
}
} else {
// If client.navigate() isn't available, we have no other option but to open a new tab to the URL.
await Database.put("NotificationOpened", { url: launchUrl, data: notificationData, timestamp: Date.now() });
await ServiceWorker.openUrl(launchUrl);
}
}
doNotOpenLink = true;
break;
}
}
if (notificationOpensLink && !doNotOpenLink) {
await Database.put("NotificationOpened", { url: launchUrl, data: notificationData, timestamp: Date.now() });
await ServiceWorker.openUrl(launchUrl);
}
if (saveNotificationClickedPromise) {
await saveNotificationClickedPromise;
}
return await convertedAPIRequests;
}
/**
* Makes network calls for the notification open event to;
* 1. OneSignal.com to increase the notification open count.
* 2. A website developer defined webhook URL, if set.
*/
static async sendConvertedAPIRequests(
appId: string | undefined | null,
deviceId: string | undefined,
notificationData: any,
deviceType: number): Promise<void> {
if (!notificationData.id) {
console.error("No notification id, skipping networks calls to report open!");
return;
}
let onesignalRestPromise: Promise<any> | undefined;
if (appId) {
onesignalRestPromise = OneSignalApiBase.put(`notifications/${notificationData.id}`, {
app_id: appId,
player_id: deviceId,
opened: true,
device_type: deviceType
});
}
else
console.error("No app Id, skipping OneSignal API call for notification open!");
await ServiceWorker.executeWebhooks('notification.clicked', notificationData);
if (onesignalRestPromise)
await onesignalRestPromise;
}
/**
* Attempts to open the given url in a new browser tab. Called when a notification is clicked.
* @param url May not be well-formed.
*/
static async openUrl(url: string): Promise<Client | null> {
Log.debug('Opening notification URL:', url);
try {
return await self.clients.openWindow(url);
} catch (e) {
Log.warn(`Failed to open the URL '${url}':`, e);
return null;
}
}