-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathlocal-notification.js
1047 lines (905 loc) · 34.3 KB
/
local-notification.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
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
/*
* Apache 2.0 License
*
* Copyright (c) Sebastian Katzer 2017
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*/
var exec = require('cordova/exec'),
channel = require('cordova/channel');
// Options for every platform
exports._commonOptions = {
actions: [],
attachments: [],
// Custom data for the notification. Can be used, when the notification
// is send back to the app, e.g. by clicking on it.
data: null,
id: 0,
launch: true,
silent: false,
text: "",
// In Android 7, this sets the sound uri of a notification.
// Since Android 8, it sets the sound uri of a notification channel.
// The string 'default' represents the default notification sound and is not a path.
sound: 'default',
// If empty, the app name will be used
title: "",
trigger: {type : "calendar"}
}
exports._androidAlarmTypes = {
'RTC_WAKEUP': 0,
'RTC': 1,
'ELAPSED_REALTIME_WAKEUP': 2, // Not supported
'ELAPSED_REALTIME': 3, // Not supported
}
exports._androidChannelImportanceTypes = {
'IMPORTANCE_NONE': 0,
'IMPORTANCE_MIN': 1,
'IMPORTANCE_LOW': 2,
'IMPORTANCE_DEFAULT': 3,
'IMPORTANCE_HIGH': 4,
'IMPORTANCE_MAX': 5
}
// Options only available on Android
exports._androidSpecificOptions = {
androidAlarmType: "RTC_WAKEUP",
// Alarm will be allowed to execute even when the system is in low-power idle (a.k.a. doze) modes.
androidAllowWhileIdle: false,
// Make this notification automatically dismissed when the user touches it
androidAutoCancel : true,
androidChannelEnableLights: false,
androidChannelDescription: null,
androidChannelEnableVibration: false,
androidChannelId: "default_channel",
androidChannelImportance: "IMPORTANCE_DEFAULT",
androidChannelName: "Default channel",
// soundUsage of a channel. Default is USAGE_NOTIFICATION
androidChannelSoundUsage: 5,
// The notification background color for the small icon
androidColor: null,
// Android 7 only: Sets the default notification options
androidDefaults: 0,
androidGroup: null,
androidGroupSummary: false,
androidMessages: null,
androidLargeIcon : null,
// Can be square or circle
androidLargeIconType: "square",
androidLockscreen: true,
androidOngoing: false,
androidOnlyAlertOnce: false,
androidProgressBar: null,
// If the Notification should show the when date
androidShowWhen: true,
androidSmallIcon: 'res://ic_popup_reminder',
androidSummary: null,
// Specifies a duration in milliseconds after which this notification should be canceled,
// if it is not already canceled.
androidTimeoutAfter: 0,
androidTitleCount: "%n%",
// Show the Notification#when field as a stopwatch. Instead of presenting when as a timestamp,
// the notification will show an automatically updating display of the minutes and seconds since when
androidUsesChronometer: false,
androidWakeUpScreen: true,
// Overwrites default
// Increments the badge by the specified number for that notification
badgeNumber: 1,
// Only for Android 7
led: false
}
// Options only available on iOS
exports._iOSSpecificOptions = {
// Overwrites default
// Set the badge directly.
// -1: The badge will not be changed
// 0: The badge will be cleared
badgeNumber: -1,
// Displays notification in foreground, when app is active.
iOSForeground : true
}
exports._deprecatedProperties = {
// Changes since version 1.1.0
autoClear: {newPropertyKey: 'androidAutoCancel', since: "1.1.0"},
badge: {newPropertyKey: 'badgeNumber', since: "1.1.0"},
channelDescription: {newPropertyKey: 'androidChannelDescription', since: "1.1.0"},
channelId: {newPropertyKey: 'androidChannelId', since: "1.1.0"},
channelImportance: {newPropertyKey: 'androidChannelImportance', since: "1.1.0"},
channelName: {newPropertyKey: 'androidChannelName', since: "1.1.0"},
clock: {message: "Use for 'clock: true' = 'androidShowWhen' and clock: 'chronometer' = 'androidUsesChronometer'", since: "1.1.0"},
color: {newPropertyKey: 'androidColor', since: "1.1.0"},
description: {newPropertyKey: 'androidChannelDescription', since: "1.1.0"},
defaults: {newPropertyKey: 'androidDefaults', since: "1.1.0"},
foreground: {newPropertyKey: 'iOSForeground', since: "1.1.0"},
group: {newPropertyKey: 'androidGroup', since: "1.1.0"},
groupSummary: {newPropertyKey: 'androidGroupSummary', since: "1.1.0"},
icon: {newPropertyKey: 'androidLargeIcon', since: "1.1.0"},
iconType: {renanewPropertyKeymedTo: 'androidLargeIconType', since: "1.1.0"},
importance: {newPropertyKey: 'androidChannelImportance', since: "1.1.0"},
lockscreen: {newPropertyKey: 'androidLockscreen', since: "1.1.0"},
mediaSession: {removed: true, since: "1.1.0", additionalMessage: "Not supported anymore."},
onlyAlertOnce: {newPropertyKey: 'androidOnlyAlertOnce', since: "1.1.0"},
prio: {additionalMessage: 'Use androidChannelImportance, androidAlarmType and androidAllowWhileIdle instead.', since: "1.1.0"},
priority: {additionalMessage: 'Use androidChannelImportance, androidAlarmType and androidAllowWhileIdle instead.', since: "1.1.0"},
progressBar: {newPropertyKey: 'androidProgressBar', since: "1.1.0"},
smallIcon: {newPropertyKey: 'androidSmallIcon', since: "1.1.0"},
soundUsage: {newPropertyKey: 'androidChannelSoundUsage', since: "1.1.0"},
sticky: {newPropertyKey: 'androidOngoing', since: "1.1.0"},
ongoing: {newPropertyKey: 'androidOngoing', since: "1.1.0"},
summary: {newPropertyKey: 'androidSummary', since: "1.1.0"},
timeoutAfter: {newPropertyKey: 'androidTimeoutAfter', since: "1.1.0"},
titleCount: {newPropertyKey: 'androidTitleCount', since: "1.1.0"},
vibrate: {newPropertyKey: 'androidChannelEnableVibration', since: "1.1.1"},
wakeup: {newPropertyKey: 'androidWakeUpScreen', since: "1.1.0"},
}
// Defaults
exports._defaults = {
...exports._commonOptions,
meta: {
plugin: 'cordova-plugin-local-notification',
version: '1.1.1-dev'
}
};
/**
* Setting some things before 'deviceready' event has fired.
*/
channel.onCordovaReady.subscribe(function () {
channel.onCordovaInfoReady.subscribe(function () {
console.log("LocalNotification: onCordovaInfoReady");
// Merge defaults for Android
if (device.platform == 'Android') {
exports._defaults = {
...exports._defaults,
...exports._androidSpecificOptions
}
// Merge defaults for iOS
} else if (device.platform == 'iOS') {
exports._defaults = {
...exports._defaults,
...exports._iOSSpecificOptions
}
}
exports._setLaunchDetails();
});
});
// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
console.log("LocalNotification: deviceready");
if (!window.skipLocalNotificationReady) {
exports.fireQueuedEvents();
}
});
/**
* Set the launch details if the app was launched by clicking on a toast.
*/
exports._setLaunchDetails = function () {
exports._exec('launch', null, function (details) {
if (details) {
exports.launchDetails = details;
}
});
};
/**
* ====================
* Plugin methods
* ====================
**/
/**
* Fire queued events once the device is ready and all listeners are registered.
*/
exports.fireQueuedEvents = function() {
exports._exec('ready');
};
// Event listeners
// For an event, multiple listeners can be added.
exports._listeners = {};
/**
* Overwrite default settings.
* @param {Object} newDefaults
*/
exports.setDefaults = function (newDefaults) {
Object.assign(this._defaults, newDefaults);
};
/**
* Android only: Create notification channel
* @param {Object} options channel options
* @param {Function} callback The function to be exec as the callback
* @param {Object} scope The callback function's scope
*/
exports.createChannel = function (options, callback, scope) {
// Correct renamed properties and set defaults
exports._correctOptions(options, true);
exports._exec('createChannel', options, callback, scope);
};
/**
* Android only: Deletes a notification channel.
* If you create a new channel with this same id, the deleted channel will be un-deleted
* with all of the same settings it had before it was deleted
* See: https://developer.android.com/reference/androidx/core/app/NotificationManagerCompat#deleteNotificationChannel(java.lang.String)
*
* @param {string} channelId Channel ID to delete. Has to be a string like "my_channel_id"
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.deleteChannel = function (channelId, callback, scope) {
exports._exec('deleteChannel', channelId, callback, scope);
};
/**
* Check permission to show notifications.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.hasPermission = function (callback, scope) {
exports._exec('hasPermission', null, callback, scope);
};
/**
* Request permission to show notifications.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.requestPermission = function (callback, scope) {
console.log("Requesting permission");
exports._exec('requestPermission', null, callback, scope);
};
/**
* Android only: Check permission to schedule exact alarms.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.canScheduleExactAlarms = function (callback, scope) {
exports._exec('canScheduleExactAlarms', null, callback, scope);
};
/**
* Schedule notifications
* @param {Object|Array} options The notifications to schedule
* @param {Function} callback
* @param {Object} scope The callback function's scope.
* @param {Object} args Optional, can be {skipPermission: true} to skip the permission check
*/
exports.schedule = function (options, callback, scope, args) {
const optionsList = exports._toArray(options);
for (const options of optionsList) {
// Correct renamed properties and set defaults
exports._correctOptions(options, true);
}
// Skip permission check if requested and schedule directly
if (args && args.skipPermission) {
console.log("Skip permission check");
exports._exec('schedule', optionsList, callback, scope);
// Ask for permission
} else {
exports.requestPermission((granted) => {
console.log("Permission granted=" + granted);
if (!granted) {
if (callback) callback.call(scope || this, false);
return;
}
exports._exec('schedule', optionsList, callback, scope);
}, this);
}
};
/**
* Update notifications
* @param {Object|Array} options The notifications to update
* @param {Function} callback
* @param {Object} scope The callback function's scope.
* @param {Object} args Optional, can be {skipPermission: true} to skip the permission check
*/
exports.update = function (options, callback, scope, args) {
const optionsList = exports._toArray(options);
for (const options of optionsList) {
// Correct renamed properties and don't merge defaults
// The defaults are not merged, because otherwise, some values
// could be set back to a default value
exports._correctOptions(options, false);
}
// Skip permission check if requested and update directly
if (args && args.skipPermission) {
exports._exec('update', optionsList, callback, scope);
// Ask for permission
} else {
exports.requestPermission((granted) => {
if (!granted) {
if (callback) callback.call(scope || this, false);
return;
}
exports._exec('update', optionsList, callback, scope);
}, this);
}
};
/**
* Clear one or multiple notifications by id/ids
* @param {Array<number>|number} ids One Id or an array of Ids
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.clear = function (ids, callback, scope) {
exports._exec('clear', exports._convertIdsToNumbers(ids), callback, scope);
};
/**
* Clear all triggered notifications.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.clearAll = function (callback, scope) {
exports._exec('clearAll', null, callback, scope);
};
/**
* Clear one or multiple notifications by id/ids
* @param {Array<number>|number} ids One Id or an array of Ids
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.cancel = function (ids, callback, scope) {
exports._exec('cancel', exports._convertIdsToNumbers(ids), callback, scope);
};
/**
* Cancel all scheduled notifications.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.cancelAll = function (callback, scope) {
exports._exec('cancelAll', null, callback, scope);
};
/**
* Check if a notification is present.
* @param {number} id The ID of the notification.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.isPresent = function (id, callback, scope) {
exports.getType(id, function (type) {
exports._callbackWithScope(callback, scope)(type != 'unknown');
});
};
/**
* Check if a notification is scheduled.
* @param {Int} id The ID of the notification.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.isScheduled = function (id, callback, scope) {
exports.hasType(id, 'scheduled', callback, scope);
};
/**
* Check if a notification was triggered.
* @param {Int} id The ID of the notification.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.isTriggered = function (id, callback, scope) {
exports.hasType(id, 'triggered', callback, scope);
};
/**
* Check if a notification has a given type.
* @param {number} id The ID of the notification.
* @param {string} type The type of the notification.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.hasType = function (id, type, callback, scope) {
exports.getType(id, function (type2) {
exports._callbackWithScope(callback, scope)(type == type2);
});
};
/**
* Get the type (triggered, scheduled) for the notification.
* @param {number} id The ID of the notification.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.getType = function (id, callback, scope) {
exports._exec('type', id, callback, scope);
};
/**
* List of all notification ids.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.getIds = function (callback, scope) {
exports._exec('ids', 0, callback, scope);
};
/**
* List of all scheduled notification IDs.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.getScheduledIds = function (callback, scope) {
exports._exec('ids', 1, callback, scope);
};
/**
* List of all triggered notification IDs.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.getTriggeredIds = function (callback, scope) {
exports._exec('ids', 2, callback, scope);
};
/**
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function () {
var args = Array.apply(null, arguments);
if (typeof args[0] == 'function') {
args.unshift([]);
}
var ids = args[0], callback = args[1], scope = args[2];
if (!Array.isArray(ids)) {
this._exec('notification', Number(ids), callback, scope);
return;
}
this._exec('notifications', [3, exports._convertIdsToNumbers(ids)], callback, scope);
};
/**
* List for all notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this._exec('notifications', 0, callback, scope);
};
/**
* List of all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getScheduled = function (callback, scope) {
this._exec('notifications', 1, callback, scope);
};
/**
* List of all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getTriggered = function (callback, scope) {
this._exec('notifications', 2, callback, scope);
};
/**
* Add an group of actions by id.
*
* @param [ String ] id The Id of the group.
* @param [ Array] actions The action config settings.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.addActions = function (id, actions, callback, scope) {
this._exec('actions', [0, id, actions], callback, scope);
};
/**
* Remove an group of actions by id.
*
* @param [ String ] id The Id of the group.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.removeActions = function (id, callback, scope) {
this._exec('actions', [1, id], callback, scope);
};
/**
* Check if a group of actions is defined.
*
* @param [ String ] id The Id of the group.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.hasActions = function (id, callback, scope) {
this._exec('actions', [2, id], callback, scope);
};
/**
* Open native settings to enable notifications.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.openNotificationSettings = function (callback, scope) {
this._exec('openNotificationSettings', null, callback, scope);
};
/**
* Android only: Open native settings to enable alarms & reminders.
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
*/
exports.openAlarmSettings = function (callback, scope) {
this._exec('openAlarmSettings', null, callback, scope);
};
/**
* iOS only: Clear the badge of the app icon.
* @param {Function} callback
* @param {Object} scope
*/
exports.iOSClearBadge = function (callback, scope) {
this._exec('clearBadge', null, callback, scope);
}
/**
* Register callback for a given event.
* @param {string} event The name of the event.
* @param {Function|string} callback The function to be exec as callback or the
* method name on the scope, which should be called.
* @param {Object} scope The callback function's scope.
*/
exports.on = function (event, callback, scope) {
// If callback is a string, a method on the scope schould be called
if (typeof callback !== 'function' && typeof callback !== 'string') return;
// Create empty array, if there are no listeners already
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push([callback, scope || window]);
};
/**
* Unregister callback for given event
* @param {string} event The name of the event
* @param {Function|string} callback Callback or method name for the scope, which should be unregistered
*/
exports.un = function (event, callback) {
// No listeners added to this event
if (!this._listeners[event]) return;
// Remove all listeners by callback or method name
this._listeners[event] = this._listeners[event].filter((listener) => listener[0] != callback);
};
/**
* Fire the event with given arguments.
* @param {string} event The event's name.
* @param {...Object} args The callback's arguments. The first element, can be the options of a notification.
*/
exports.fireEvent = function (event, ...args) {
// No listeners added for this event
if (!this._listeners[event]) return;
// Convert custom notification data to object
if (args[0] && typeof args[0].data === 'string') {
args[0].data = JSON.parse(args[0].data);
}
for (const listener of this._listeners[event]) {
const callback = listener[0];
const scope = listener[1];
// If callback is a string, a method on the scope schould be called
if (typeof callback === 'string') callback = scope[callback];
callback.apply(scope, args);
}
};
/**
* ====================
* Internal JS Methods for handling options etc.
* ====================
**/
/**
* Correct renamed propertie and merge defaults optionally, also do the following:
* - correct options to their required type
* - warn about wrong smallIcon uri
* - log unknown and deprecated properties
* - Remove null values, because of a Android bug
* @param {Object} options The options to convert
*/
exports._correctOptions = function (options, mergeDefaults = false) {
exports._handleDeprecatedProperties(options)
// Warn about wrong androidSmallIcon uri
if (options.androidSmallIcon && !options.androidSmallIcon.match(/^res:/)) {
console.warn('Property "androidSmallIcon" must be of kind res://...')
}
// Convert custom data to string
options.data = JSON.stringify(options.data)
// No auto cancelling, if the notification is ongoing
if (options.androidOngoing) options.androidAutoCancel = false
exports._convertTrigger(options);
exports._convertActions(options);
exports._convertAndroidProgressBar(options);
if (mergeDefaults) {
for (const key in this._defaults) {
if (options[key] === undefined) options[key] = exports._defaults[key];
}
}
// Convert Enums
// Android: alarmType string to integer
if (typeof options.androidAlarmType === 'string') {
options.androidAlarmType = exports._androidAlarmTypes[options.androidAlarmType]
}
// Android: channelImportance string to integer
if (typeof options.androidChannelImportance === 'string') {
options.androidChannelImportance = exports._androidChannelImportanceTypes[options.androidChannelImportance]
}
// Due to a Android bug, null values have to be removed
exports._removeNullValues(options);
exports._logUnknownProperties(options);
};
/**
* Corrects renamed properties since Plugin version 1.1.0
* @param {Oject} options
*/
exports._handleDeprecatedProperties = function (options) {
if (device.platform == "Android") {
// text as Array to androidMessages, since 1.1.0
if (Array.isArray(options.text)) {
options.androidMessages = options.text
console.log("Property 'text' as array is deprecated since version 1.1.0. Use 'androidMessages' instead.")
}
// "clock: true" to androidShowWhen, since 1.1.0
if (options.clock === true) {
options.androidShowWhen = true
console.log("Property 'clock: true' is deprecated since version 1.1.0. Use 'androidShowWhen: true' instead.")
}
// "clock: 'chronometer'" to androidUsesChronometer, since 1.1.0
if (options.clock == "chronometer") {
options.androidUsesChronometer = true
console.log("Property 'clock: 'chronometer'' is deprecated since version 1.1.0. Use 'androidUsesChronometer: true' instead.")
}
// led replaced by androidChannelEnableLights, since Android 8
if (options.led) options.androidChannelEnableLights = true
// priority changed to androidChannelImportance, androidAlarmType and androidAllowWhileIdle
this._androidHandleOldPropertyPriority(options)
}
// sound: true changed to sound: "default", since 1.1.0
if (options.sound === true) {
options.sound = "default"
console.log(`Property "sound: true" is deprecated since version 1.1.0. Use "sound: 'default'" instead.`)
}
// Handle renamed and removed properties
// Log deprecated properties
for (const key in options) {
// Check if the property is deprecated
const deprecatedProperty = this._deprecatedProperties[key];
// Property not deprecated
if (!deprecatedProperty) continue
let message;
// Check if propert is renamed
if (deprecatedProperty.newPropertyKey) {
message = `Use "${deprecatedProperty.newPropertyKey}" instead.`
// Set deprecated property value to new property
options[deprecatedProperty.newPropertyKey] = options[key]
// Property was removed
} else if (deprecatedProperty.removed) {
message = `Property removed`
}
if (deprecatedProperty.additionalMessage) {
message += ` ${deprecatedProperty.additionalMessage}`
}
console.warn(`Property "${key}" is deprecated since version ${deprecatedProperty.since}. ${message}`)
}
}
/**
* Android: Backward compatibility for property priority.
* Replaced by androidChannelImportance, androidAlarmType and androidAllowWhileIdle
* Removed in plugin version 1.1.0
* If priority is present, it will set androidAlarmType and androidAllowWhileIdle, but not androidChannelImportance.
* @param {Object} options
*/
exports._androidHandleOldPropertyPriority = function (options) {
let priority = options.priority || options.prio;
// Old property not found
if (priority === undefined) return
if (typeof priority === 'string') {
priority = { min: -2, low: -1, high: 1, max: 2 }[priority] || 0;
}
if (options.foreground === true) {
priority = Math.max(priority, 1);
}
if (options.foreground === false) {
priority = Math.min(priority, 0);
}
// PRIORITY_MIN and PRIORITY_LOW
if (priority < 0) {
options.androidAlarmType = "RTC"
options.androidAllowWhileIdle = false
// PRIORITY_DEFAULT and PRIORITY_HIGH
} else if (priority < 2) {
options.androidAlarmType = "RTC_WAKEUP"
options.androidAllowWhileIdle = false
// PRIORITY_MAX
} else {
options.androidAlarmType = "RTC_WAKEUP"
options.androidAllowWhileIdle = true
}
options.priority = priority;
};
/**
* Convert the passed values to their required type, modifying them
* directly for Android and passing the converted list back for iOS.
*
* @param [ Map ] options Set of custom values.
*
* @return [ Map ] Interaction object with category & actions.
*/
exports._convertActions = function (options) {
var actions = [];
if (!options.actions || typeof options.actions === 'string')
return options;
for (var i = 0, len = options.actions.length; i < len; i++) {
var action = options.actions[i];
if (!action.id) {
console.warn('Action with title ' + action.title + ' ' +
'has no id and will not be added.');
continue;
}
action.id = action.id.toString();
actions.push(action);
}
options.actions = actions;
return options;
};
/**
* Convert the passed values for the trigger to their required type.
* @param {Object} options
* @return {Object} Converted options
*/
exports._convertTrigger = function (options) {
if (!options.trigger) return;
let trigger = options.trigger;
trigger.type = trigger.type || trigger.center ? 'location' : 'calendar';
var isCal = trigger.type == 'calendar';
// Get trigger date from trigger
var date = exports._getValueFor(trigger, 'at', 'firstAt', 'date');
// Fallback: Get trigger date from options, if not defined in trigger
if (isCal && !date) {
date = exports._getValueFor(options, 'at', 'firstAt', 'date');
}
// Fallback: Transfer every option to trigger
if (isCal && !trigger.every && options.every) {
trigger.every = options.every;
}
if (isCal && (trigger.in || trigger.every)) {
date = null;
}
var dateToNum = function (date) {
var num = typeof date == 'object' ? date.getTime() : date;
return Math.round(num);
};
if (isCal && date) {
trigger.at = dateToNum(date);
}
if (isCal && trigger.firstAt) {
trigger.firstAt = dateToNum(trigger.firstAt);
}
if (isCal && trigger.before) {
trigger.before = dateToNum(trigger.before);
}
if (isCal && trigger.after) {
trigger.after = dateToNum(trigger.after);
}
if (trigger.count && device.platform == 'iOS') {
console.warn('trigger: { count: } is not supported on iOS.');
}
if (!isCal) {
trigger.notifyOnEntry = !!trigger.notifyOnEntry;
trigger.notifyOnExit = trigger.notifyOnExit === true;
trigger.radius = trigger.radius || 5;
trigger.single = !!trigger.single;
}
if (!isCal || trigger.at) {
delete trigger.every;
}
delete options.every;
delete options.at;
delete options.firstAt;
delete options.date;
options.trigger = trigger;
return options;
};
/**
* Convert the passed values for the progressBar to their required type.
* @param {Object} options
*/
exports._convertAndroidProgressBar = function (options) {
if (options.androidProgressBar === undefined) return
let progressBar = options.androidProgressBar
progressBar.value = progressBar.value || 0;
progressBar.maxValue = progressBar.maxValue || 100;
progressBar.indeterminate = progressBar.indeterminate || false;
// Show the Notification#when field as a stopwatch
if (options.androidShowWhen) options.androidUsesChronometer = true;
};
/**
* On Android exists the bug, that when using JSONObject.optString("key", null),
* it will return "NULL" as string and not plain null. This function removes
* all null values, to workaround this. If this is also a problem on iOS, is not known.
*
* See: https://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null
* @param {Object} options
*/
exports._removeNullValues = function (options) {
for (const key in options) {
if (options[key] === null) delete options[key];
}
}
/**
* Warns about unknown properties in options
* @param {Object} options
*/
exports._logUnknownProperties = function (options) {
for (const key in options) {
// Check if property is missing in defaults and is not a deprecated property
if (this._defaults[key] === undefined && this._deprecatedProperties[key] === undefined) {
console.warn('Unknown property: ' + key);
}
}
}
/**
* Create a callback function to get executed within a specific scope.
*
* @param {Function} callback The function to be exec as the callback.
* @param {Object} scope The callback function's scope.
* @return {Function} The callback function.
*/
exports._callbackWithScope = function (callback, scope) {
if (typeof callback != 'function') return;
return function () {
callback.apply(scope || this, arguments);
};
};
/**
* Convert the IDs to numbers.
* @param {Array|Object} ids Will be turned into an array, if it's not already.
* @return {Array<Number>}
*/
exports._convertIdsToNumbers = function (ids) {
return exports._toArray(ids).map((id) => Number(id))
};
/**