forked from zo0r/react-native-push-notification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
607 lines (507 loc) · 17.7 KB
/
index.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
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
/**
* @providesModule Notifications
*/
'use strict';
import { AppState, Platform } from 'react-native';
import { component } from './component';
const Notifications = {
handler: component,
onRegister: false,
onRegistrationError: false,
onNotification: false,
onAction: false,
onRemoteFetch: false,
isLoaded: false,
isPopInitialNotification: false,
isPermissionsRequestPending: false,
permissions: {
alert: true,
badge: true,
sound: true
}
};
Notifications.callNative = function(name, params) {
if ( typeof this.handler[name] === 'function' ) {
if ( typeof params !== 'array' &&
typeof params !== 'object' ) {
params = [];
}
return this.handler[name](...params);
} else {
return null;
}
};
/**
* Configure local and remote notifications
* @param {Object} options
* @param {function} options.onRegister - Fired when the user registers for remote notifications.
* @param {function} options.onNotification - Fired when a remote notification is received.
* @param {function} options.onAction - Fired when a remote notification is received.
* @param {function} options.onRegistrationError - Fired when the user fails to register for remote notifications.
* @param {Object} options.permissions - Permissions list
* @param {Boolean} options.requestPermissions - Check permissions when register
*/
Notifications.configure = function(options) {
if ( typeof options.onRegister !== 'undefined' ) {
this.onRegister = options.onRegister;
}
if ( typeof options.onRegistrationError !== 'undefined' ) {
this.onRegistrationError = options.onRegistrationError;
}
if ( typeof options.onNotification !== 'undefined' ) {
this.onNotification = options.onNotification;
}
if ( typeof options.onAction !== 'undefined' ) {
this.onAction = options.onAction;
}
if ( typeof options.permissions !== 'undefined' ) {
this.permissions = options.permissions;
}
if ( typeof options.onRemoteFetch !== 'undefined' ) {
this.onRemoteFetch = options.onRemoteFetch;
}
if ( this.isLoaded === false ) {
this._onRegister = this._onRegister.bind(this);
this._onRegistrationError = this._onRegistrationError.bind(this);
this._onNotification = this._onNotification.bind(this);
this._onRemoteFetch = this._onRemoteFetch.bind(this);
this._onAction = this._onAction.bind(this);
this.callNative( 'addEventListener', [ 'register', this._onRegister ] );
this.callNative( 'addEventListener', [ 'registrationError', this._onRegistrationError ] );
this.callNative( 'addEventListener', [ 'notification', this._onNotification ] );
this.callNative( 'addEventListener', [ 'localNotification', this._onNotification ] );
Platform.OS === 'android' ? this.callNative( 'addEventListener', [ 'action', this._onAction ] ) : null
Platform.OS === 'android' ? this.callNative( 'addEventListener', [ 'remoteFetch', this._onRemoteFetch ] ) : null
this.isLoaded = true;
}
const handlePopInitialNotification = (state) => {
if('active' !== state) {
return;
}
if (options.popInitialNotification === undefined || options.popInitialNotification === true) {
this.popInitialNotification(function(firstNotification) {
if(this.isPopInitialNotification) {
return;
}
this.isPopInitialNotification = true;
if (!firstNotification || false === firstNotification.userInteraction) {
return;
}
this._onNotification(firstNotification, true);
}.bind(this));
}
}
AppState.addEventListener('change', handlePopInitialNotification.bind(this));
handlePopInitialNotification(AppState.currentState);
if ( options.requestPermissions !== false ) {
this._requestPermissions();
}
};
/* Unregister */
Notifications.unregister = function() {
this.callNative( 'removeEventListener', [ 'register', this._onRegister ] )
this.callNative( 'removeEventListener', [ 'registrationError', this._onRegistrationError ] )
this.callNative( 'removeEventListener', [ 'notification', this._onNotification ] )
this.callNative( 'removeEventListener', [ 'localNotification', this._onNotification ] )
Platform.OS === 'android' ? this.callNative( 'removeEventListener', [ 'action', this._onAction ] ) : null
Platform.OS === 'android' ? this.callNative( 'removeEventListener', [ 'remoteFetch', this._onRemoteFetch ] ) : null
this.isLoaded = false;
};
/**
* Local Notifications
* @param {Object} details
* @param {String} details.title - The title displayed in the notification alert.
* @param {String} details.message - The message displayed in the notification alert.
* @param {String} details.ticker - ANDROID ONLY: The ticker displayed in the status bar.
* @param {Object} details.userInfo - iOS ONLY: The userInfo used in the notification alert.
*/
Notifications.localNotification = function({...details}) {
if ('android' === Platform.os && details && !details.channelId) {
console.warn('No channel id passed, notifications may not work.');
}
if (details && typeof details.id === 'number') {
if (isNaN(details.id)) {
console.warn('NaN value has been passed as id');
delete details.id;
}
else {
details.id = '' + details.id;
}
}
if (details.userInfo) {
details.userInfo.id = details.userInfo.id || details.id;
} else {
details.userInfo = {id: details.id};
}
if (Platform.OS === 'ios') {
// https://developer.apple.com/reference/uikit/uilocalnotification
let soundName = details.soundName ? details.soundName : 'default'; // play sound (and vibrate) as default behaviour
if (details.hasOwnProperty('playSound') && !details.playSound) {
soundName = ''; // empty string results in no sound (and no vibration)
}
// for valid fields see: https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html
this.handler.addNotificationRequest({
id: (!details.id ? Math.floor(Math.random() * Math.pow(2, 32)).toString() : details.id),
title: details.title,
body: details.message,
badge: details.number,
sound: soundName,
isSilent: details.playSound === false,
category: details.category,
userInfo: details.userInfo
});
} else {
if (details && typeof details.number === 'number') {
if(isNaN(details.number)) {
console.warn('NaN value has been passed as number');
delete details.number;
}
else {
details.number = '' + details.number;
}
}
if (details && typeof details.shortcutId === 'number') {
if(isNaN(details.shortcutId)) {
console.warn('NaN value has been passed as shortcutId');
delete details.shortcutId;
}
else {
details.shortcutId = '' + details.shortcutId;
}
}
if(details && Array.isArray(details.actions)) {
details.actions = JSON.stringify(details.actions);
}
if(details.userInfo) {
details.userInfo = JSON.stringify(details.userInfo);
}
this.handler.presentLocalNotification(details);
}
};
/**
* Local Notifications Schedule
* @param {Object} details (same as localNotification)
* @param {Date} details.date - The date and time when the system should deliver the notification
*/
Notifications.localNotificationSchedule = function({...details}) {
if ('android' === Platform.os && details && !details.channelId) {
console.warn('No channel id passed, notifications may not work.');
}
if (details && typeof details.id === 'number') {
if(isNaN(details.id)) {
console.warn('NaN value has been passed as id');
delete details.id;
}
else {
details.id = '' + details.id;
}
}
if (details.userInfo) {
details.userInfo.id = details.userInfo.id || details.id;
} else {
details.userInfo = {id: details.id};
}
if (Platform.OS === 'ios') {
let soundName = details.soundName ? details.soundName : 'default'; // play sound (and vibrate) as default behaviour
if (details.hasOwnProperty('playSound') && !details.playSound) {
soundName = ''; // empty string results in no sound (and no vibration)
}
const iosDetails = {
id: (!details.id ? Math.floor(Math.random() * Math.pow(2, 32)).toString() : details.id),
fireDate: details.date.toISOString(),
title: details.title,
body: details.message,
sound: soundName,
isSilent: details.playSound === false,
category: details.category,
userInfo: details.userInfo,
repeats: (details.repeatType && details.repeatType == "day"),
};
if (details.number) {
iosDetails.badge = parseInt(details.number, 10);
}
this.handler.addNotificationRequest(iosDetails);
} else {
if (details && typeof details.number === 'number') {
if (isNaN(details.number)) {
console.warn('NaN value has been passed as number');
delete details.number;
}
else {
details.number = '' + details.number;
}
}
if (details && typeof details.shortcutId === 'number') {
if (isNaN(details.shortcutId)) {
console.warn('NaN value has been passed as shortcutId');
delete details.shortcutId;
}
else {
details.shortcutId = '' + details.shortcutId;
}
}
if(details && Array.isArray(details.actions)) {
details.actions = JSON.stringify(details.actions);
}
if(details.userInfo) {
details.userInfo = JSON.stringify(details.userInfo);
}
details.fireDate = details.date.getTime();
delete details.date;
// ignore iOS only repeatType
if (['year'].includes(details.repeatType)) {
delete details.repeatType;
}
this.handler.scheduleLocalNotification(details);
}
};
/* Internal Functions */
Notifications._onRegister = function(token) {
if ( this.onRegister !== false ) {
this.onRegister({
token: token,
os: Platform.OS
});
}
};
Notifications._onRegistrationError = function(err) {
if ( this.onRegistrationError !== false ) {
this.onRegistrationError(err);
}
};
Notifications._onRemoteFetch = function(notificationData) {
if ( this.onRemoteFetch !== false ) {
this.onRemoteFetch(notificationData)
}
};
Notifications._onAction = function({...notification}) {
if ( typeof notification.data === 'string' ) {
try {
notification.data = JSON.parse(notificationData.data);
} catch(e) {
/* void */
}
}
this.onAction(notification);
}
Notifications._transformNotificationObject = function(data, isFromBackground = null) {
if(!data) {
return;
}
if ( isFromBackground === null ) {
isFromBackground = (
data.foreground === false ||
AppState.currentState === 'background' ||
AppState.currentState === 'unknown'
);
}
let _notification;
if ( Platform.OS === 'ios' ) {
const notifData = data.getData();
_notification = {
id: notifData?.id,
foreground: !isFromBackground,
userInteraction: notifData?.userInteraction === 1 || false,
message: data.getMessage(),
data: notifData,
badge: data.getBadgeCount(),
title: data.getTitle(),
soundName: data.getSound(),
fireDate: Date.parse(data._fireDate),
action: data.getActionIdentifier(),
reply_text: data.getUserText(),
finish: (res) => data.finish(res)
};
if(isNaN(_notification.fireDate)) {
delete _notification.fireDate;
}
} else {
_notification = {
foreground: !isFromBackground,
finish: () => {},
...data,
};
if ( typeof _notification.data === 'string' ) {
try {
_notification.data = JSON.parse(_notification.data);
} catch(e) {
/* void */
}
}
if ( typeof _notification.userInfo === 'string' ) {
try {
_notification.userInfo = JSON.parse(_notification.userInfo);
} catch(e) {
/* void */
}
}
_notification.data = {
...(typeof _notification.userInfo === 'object' ? _notification.userInfo : {}),
...(typeof _notification.data === 'object' ? _notification.data : {}),
};
delete _notification.userInfo;
delete _notification.notificationId;
}
return _notification;
}
Notifications._onNotification = function(data, initialNotification = false) {
if ( this.onNotification !== false ) {
let notification = data;
if(!initialNotification) {
notification = this._transformNotificationObject(data);
}
this.onNotification(notification);
}
};
/* onResultPermissionResult */
Notifications._onPermissionResult = function() {
this.isPermissionsRequestPending = false;
};
// Prevent requestPermissions called twice if ios result is pending
Notifications._requestPermissions = function() {
if ( Platform.OS === 'ios' ) {
if ( this.isPermissionsRequestPending === false ) {
this.isPermissionsRequestPending = true;
return this.callNative( 'requestPermissions', [ this.permissions ])
.then(this._onPermissionResult.bind(this))
.catch(this._onPermissionResult.bind(this));
}
} else if (Platform.OS === 'android') {
return this.callNative( 'requestPermissions', []);
}
};
// Stock requestPermissions function
Notifications.requestPermissions = function() {
if ( Platform.OS === 'ios' ) {
return this.callNative( 'requestPermissions', [ this.permissions ]);
} else if (Platform.OS === 'android') {
return this.callNative( 'requestPermissions', []);
}
};
/* Fallback functions */
Notifications.subscribeToTopic = function() {
return this.callNative('subscribeToTopic', arguments);
};
Notifications.unsubscribeFromTopic = function () {
return this.callNative('unsubscribeFromTopic', arguments);
};
Notifications.presentLocalNotification = function() {
return this.callNative('presentLocalNotification', arguments);
};
Notifications.scheduleLocalNotification = function() {
return this.callNative('scheduleLocalNotification', arguments);
};
Notifications.cancelLocalNotifications = function(userInfo) {
if ( Platform.OS === 'ios' ) {
return this.callNative('removePendingNotificationRequests', [[userInfo.id]]);
} else {
return this.callNative('cancelLocalNotifications', [userInfo]);
}
};
Notifications.clearLocalNotification = function() {
return this.callNative('clearLocalNotification', arguments);
};
Notifications.cancelAllLocalNotifications = function() {
if ( Platform.OS === 'ios' ) {
return this.callNative('removeAllPendingNotificationRequests', arguments);
} else if (Platform.OS === 'android') {
return this.callNative('cancelAllLocalNotifications', arguments);
}
};
Notifications.setApplicationIconBadgeNumber = function() {
return this.callNative('setApplicationIconBadgeNumber', arguments);
};
Notifications.getApplicationIconBadgeNumber = function() {
return this.callNative('getApplicationIconBadgeNumber', arguments);
};
Notifications.popInitialNotification = function(handler) {
this.callNative('getInitialNotification').then((result) => {
handler(
this._transformNotificationObject(result, true)
);
});
};
Notifications.checkPermissions = function() {
return this.callNative('checkPermissions', arguments);
};
/* Abandon Permissions */
Notifications.abandonPermissions = function() {
return this.callNative('abandonPermissions', arguments);
}
Notifications.clearAllNotifications = function() {
// Only available for Android
return this.callNative('clearAllNotifications', arguments)
}
Notifications.removeAllDeliveredNotifications = function() {
return this.callNative('removeAllDeliveredNotifications', arguments);
}
Notifications.getDeliveredNotifications = function() {
return this.callNative('getDeliveredNotifications', arguments);
}
Notifications.getScheduledLocalNotifications = function(callback) {
const mapNotifications = (notifications) => {
let mappedNotifications = [];
if(notifications?.length > 0) {
if(Platform.OS === 'ios'){
mappedNotifications = notifications.map(notif => {
return ({
soundName: notif?.sound,
id: notif.id,
date: (notif.date ? new Date(notif.date) : null),
number: notif?.badge,
message: notif?.body,
title: notif?.title,
data: notif?.userInfo
})
})
} else if(Platform.OS === 'android') {
mappedNotifications = notifications.map(notif => {
try {
notif.data = JSON.parse(notif.data);
} catch(e) { }
return ({
soundName: notif.soundName,
repeatInterval: notif.repeatInterval,
id: notif.id,
date: new Date(notif.date),
number: notif.number,
message: notif.message,
title: notif.title,
data: notif.data,
})
})
}
}
callback(mappedNotifications);
}
if(Platform.OS === 'ios'){
return this.callNative('getPendingNotificationRequests', [mapNotifications]);
} else {
return this.callNative('getScheduledLocalNotifications', [mapNotifications]);
}
}
Notifications.removeDeliveredNotifications = function() {
return this.callNative('removeDeliveredNotifications', arguments);
}
Notifications.invokeApp = function() {
return this.callNative('invokeApp', arguments);
};
Notifications.getChannels = function() {
return this.callNative('getChannels', arguments);
};
Notifications.channelExists = function() {
return this.callNative('channelExists', arguments);
};
Notifications.createChannel = function() {
return this.callNative('createChannel', arguments);
};
Notifications.channelBlocked = function() {
return this.callNative('channelBlocked', arguments);
};
Notifications.deleteChannel = function() {
return this.callNative('deleteChannel', arguments);
};
Notifications.setNotificationCategories = function() {
return this.callNative('setNotificationCategories', arguments);
}
module.exports = Notifications;