-
Notifications
You must be signed in to change notification settings - Fork 25
/
Countly.js
2181 lines (2056 loc) · 74 KB
/
Countly.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
/**
* Countly SDK React Native Bridge
* https://github.com/Countly/countly-sdk-react-native-bridge
* @Countly
*/
import { Platform, NativeModules, NativeEventEmitter } from "react-native";
import CountlyConfig from "./CountlyConfig.js";
import CountlyState from "./CountlyState.js";
import Feedback from "./Feedback.js";
import Event from "./Event.js";
import * as L from "./Logger.js";
import * as Utils from "./Utils.js";
import * as Validate from "./Validators.js";
const { CountlyReactNative } = NativeModules;
const eventEmitter = new NativeEventEmitter(CountlyReactNative);
const Countly = {};
Countly.serverUrl = "";
Countly.appKey = "";
let _state = CountlyState;
CountlyState.CountlyReactNative = CountlyReactNative;
CountlyState.eventEmitter = eventEmitter;
Countly.feedback = new Feedback(CountlyState);
Countly.events = new Event(CountlyState);
let _isCrashReportingEnabled = false;
Countly.userData = {}; // userData interface
Countly.userDataBulk = {}; // userDataBulk interface
let _isPushInitialized = false;
/*
* Listener for rating widget callback, when callback recieve we will remove the callback using listener.
*/
let _ratingWidgetListener;
const ratingWidgetCallbackName = "ratingWidgetCallback";
const pushNotificationCallbackName = "pushNotificationCallback";
Countly.messagingMode = { DEVELOPMENT: "1", PRODUCTION: "0", ADHOC: "2" };
if (/android/.exec(Platform.OS)) {
Countly.messagingMode.DEVELOPMENT = "2";
}
Countly.TemporaryDeviceIDString = "TemporaryDeviceID";
/**
* Initialize Countly
*
* @deprecated in 23.02.0 : use 'initWithConfig' instead of 'init'.
*
* @function Countly.init should be used to initialize countly
* @param {string} serverURL server url
* @param {string} appKey application key
* @param {string} deviceId device ID
*/
Countly.init = async function (serverUrl, appKey, deviceId) {
L.w("Countly.init is deprecated, use Countly.initWithConfig instead");
const countlyConfig = new CountlyConfig(serverUrl, appKey).setDeviceID(deviceId);
await Countly.initWithConfig(countlyConfig);
};
/**
* Initialize Countly
*
* @function Countly.initWithConfig should be used to initialize countly with config
* @param {CountlyConfig} countlyConfig countly config object
*/
Countly.initWithConfig = async function (countlyConfig) {
if (_state.isInitialized) {
L.d("init, SDK is already initialized");
return;
}
if (countlyConfig.deviceID == "") {
L.e("init, Device ID during init can't be an empty string. Value will be ignored.");
countlyConfig.deviceId = null;
}
if (countlyConfig.serverURL == "") {
L.e("init, Server URL during init can't be an empty string");
return;
}
if (countlyConfig.appKey == "") {
L.e("init, App Key during init can't be an empty string");
return;
}
L.d("initWithConfig, Initializing Countly");
const args = [];
const argsMap = Utils.configToJson(countlyConfig);
const argsString = JSON.stringify(argsMap);
args.push(argsString);
await CountlyReactNative.init(args);
_state.isInitialized = true;
};
/**
*
* Checks if the sdk is initialized;
*
* @return {boolean} if true, countly sdk has been initialized
*/
Countly.isInitialized = async function () {
_state.isInitialized = await CountlyReactNative.isInitialized();
L.d(`isInitialized, isInitialized: [${_state.isInitialized}]`);
return _state.isInitialized;
};
/**
*
* Checks if the Countly SDK onStart function has been called
*
* @deprecated in 23.6.0. This will be removed.
*
* @return {boolean | string} boolean or error message
*/
Countly.hasBeenCalledOnStart = function () {
if (!_state.isInitialized) {
const message = "'init' must be called before 'hasBeenCalledOnStart'";
L.e(`hasBeenCalledOnStart, ${message}`);
return message;
}
L.w("hasBeenCalledOnStart, This call is deprecated and will be removed with no replacement.");
return CountlyReactNative.hasBeenCalledOnStart();
};
/**
* Sends an event to the server
*
* @deprecated in 24.4.0 : use 'Countly.events.recordEvent' instead of this.
*
* @param {CountlyEventOptions} options event options.
* CountlyEventOptions {
* eventName: string;
* eventCount?: number;
* eventSum?: number | string;
* segments?: Segmentation;
* }
* @return {string | void} error message or void
*/
Countly.sendEvent = function (options) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'sendEvent'";
L.w(`sendEvent, ${msg}`);
return msg;
}
L.w("sendEvent, This method is deprecated, use 'Countly.events.recordEvent' instead");
if (!options) {
const message = "no event object provided!";
L.w(`sendEvent, ${message}`);
return message;
}
// previous implementation was not clear about the data types of eventCount and eventSum
// here parse them to make sure they are in correct format for the new method
// parser will return a false value (NaN) in case of invalid data (like undefined, null, empty string, etc.)
options.eventCount = parseInt(options.eventCount, 10) || 1;
options.eventSum = parseFloat(options.eventSum) || 0;
Countly.events.recordEvent(options.eventName, options.segments, options.eventCount, options.eventSum);
};
/**
* Record custom view to Countly.
*
* @param {string} recordView - name of the view
* @param {object} segments - allows to add optional segmentation,
* Supported data type for segments values are string, int, double and boolean
* @return {string | void} error message or void
*/
Countly.recordView = function (recordView, segments) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'recordView'";
L.e(`recordView, ${msg}`);
return msg;
}
const message = Validate.String(recordView, "view name", "recordView");
if (message) {
return message;
}
L.d(`recordView, Recording view: ${recordView}]`);
const args = [];
args.push(String(recordView));
if (!segments) {
segments = {};
}
for (const key in segments) {
args.push(key);
args.push(segments[key]);
}
CountlyReactNative.recordView(args);
};
/**
* Disable push notifications feature, by default it is enabled.
* Currently implemented for iOS only
* Should be called before Countly init
*
* @return {string | void} error message or void
*/
Countly.disablePushNotifications = function () {
if (!/ios/.exec(Platform.OS)) {
L.e("disablePushNotifications, " + "disablePushNotifications is not implemented for Android");
return "disablePushNotifications : To be implemented";
}
L.d("disablePushNotifications, Disabling push notifications");
CountlyReactNative.disablePushNotifications();
};
/**
* @deprecated in 23.02.0 : use 'countlyConfig.pushTokenType' instead of 'pushTokenType'.
*
* Set messaging mode for push notifications
* Should be called before Countly init
*
* @return {string | void} error message or void
*/
Countly.pushTokenType = function (tokenType, channelName, channelDescription) {
const message = Validate.String(tokenType, "tokenType", "pushTokenType");
if (message) {
return message;
}
L.w("pushTokenType, pushTokenType is deprecated, use countlyConfig.pushTokenType instead");
const args = [];
args.push(tokenType);
args.push(channelName || "");
args.push(channelDescription || "");
CountlyReactNative.pushTokenType(args);
};
/**
*
* Send push token
* @param {object} options - object containing the push token
* {token: string}
*
* @return {string | void} error message or void
*/
Countly.sendPushToken = function (options) {
L.d(`sendPushToken, Sending push token: [${JSON.stringify(options)}]`);
const args = [];
args.push(options.token || "");
CountlyReactNative.sendPushToken(args);
};
/**
* This method will ask for permission, enables push notification and send push token to countly server.
*
* @param {string} customSoundPath - name of custom sound for push notifications (Only for Android)
* Custom sound should be place at 'your_project_root/android/app/src/main/res/raw'
* Should be called after Countly init
*
* @return {string | void} error message or void
*/
Countly.askForNotificationPermission = function (customSoundPath = "null") {
if (!_state.isInitialized) {
const message = "'init' must be called before 'askForNotificationPermission'";
L.e(`askForNotificationPermission, ${message}`);
return message;
}
L.d(`askForNotificationPermission, Asking for notification permission at: [${customSoundPath}]`);
CountlyReactNative.askForNotificationPermission([customSoundPath]);
_isPushInitialized = true;
};
/**
*
* Set callback to receive push notifications
* @param {callback listener } theListener
* @return {NativeEventEmitter} event
*/
Countly.registerForNotification = function (theListener) {
L.d("registerForNotification, Registering for notification");
const event = eventEmitter.addListener(pushNotificationCallbackName, theListener);
CountlyReactNative.registerForNotification([]);
return event;
};
/**
* @deprecated in 23.02.0 : use 'countlyConfig.configureIntentRedirectionCheck' instead of 'configureIntentRedirectionCheck'.
*
* Configure intent redirection checks for push notification
* Should be called before Countly "askForNotificationPermission"
*
* @param {string[]} allowedIntentClassNames allowed intent class names
* @param {string[]} allowedIntentPackageNames allowed intent package names
* @param {boolean} useAdditionalIntentRedirectionChecks to check additional intent checks. The default value is "true"
* @return {string | void} error message or void
*/
Countly.configureIntentRedirectionCheck = function (allowedIntentClassNames = [], allowedIntentPackageNames = [], useAdditionalIntentRedirectionChecks = true) {
if (/ios/.exec(Platform.OS)) {
L.e("configureIntentRedirectionCheck, configureIntentRedirectionCheck is not required for iOS");
return "configureIntentRedirectionCheck : not required for iOS";
}
if (_isPushInitialized) {
let message = "'configureIntentRedirectionCheck' must be called before 'askForNotificationPermission'";
L.e(`configureIntentRedirectionCheck, ${message}`);
return message;
}
L.w("configureIntentRedirectionCheck, configureIntentRedirectionCheck is deprecated, use countlyConfig.configureIntentRedirectionCheck instead");
if (!Array.isArray(allowedIntentClassNames)) {
L.w("configureIntentRedirectionCheck, " + `Ignoring, unsupported data type '${typeof allowedIntentClassNames}' 'allowedIntentClassNames' should be an array of String`);
allowedIntentClassNames = [];
}
if (!Array.isArray(allowedIntentPackageNames)) {
L.w("configureIntentRedirectionCheck, " + `Ignoring, unsupported data type '${typeof allowedIntentPackageNames}' 'allowedIntentPackageNames' should be an array of String`);
allowedIntentPackageNames = [];
}
if (typeof useAdditionalIntentRedirectionChecks !== "boolean") {
L.w("configureIntentRedirectionCheck, " + `Ignoring, unsupported data type '${typeof useAdditionalIntentRedirectionChecks}' 'useAdditionalIntentRedirectionChecks' should be a boolean`);
useAdditionalIntentRedirectionChecks = true;
}
const _allowedIntentClassNames = [];
for (const className of allowedIntentClassNames) {
let message = Validate.String(className, "class name", "configureIntentRedirectionCheck");
if (message == null) {
_allowedIntentClassNames.push(className);
}
}
const _allowedIntentPackageNames = [];
for (const packageName of allowedIntentPackageNames) {
let message = Validate.String(packageName, "package name", "configureIntentRedirectionCheck");
if (message == null) {
_allowedIntentPackageNames.push(packageName);
}
}
CountlyReactNative.configureIntentRedirectionCheck(_allowedIntentClassNames, _allowedIntentPackageNames, useAdditionalIntentRedirectionChecks);
};
/**
* @deprecated at 23.6.0 - Automatic sessions are handled by underlying SDK, this function will do nothing.
*
* Countly start for android
*
*/
Countly.start = function () {
L.w("start, Automatic sessions are handled by underlying SDK, this function will do nothing.");
};
/**
* @deprecated at 23.6.0 - Automatic sessions are handled by underlying SDK, this function will do nothing.
*
* Countly stop for android
*
*/
Countly.stop = function () {
L.w("stop, Automatic sessions are handled by underlying SDK, this function will do nothing.");
};
/**
* Enable countly internal debugging logs
* Should be called before Countly init
*
* @deprecated in 20.04.6
*
* @function Countly.setLoggingEnabled should be used to enable/disable countly internal debugging logs
*
*/
Countly.enableLogging = function () {
L.w("enableLogging, enableLogging is deprecated, use countlyConfig.enableLogging instead");
CountlyReactNative.setLoggingEnabled([true]);
};
/**
* Disable countly internal debugging logs
*
* @deprecated in 20.04.6
*
* @function Countly.setLoggingEnabled should be used to enable/disable countly internal debugging logs
*
*/
Countly.disableLogging = function () {
L.w("disableLogging, disableLogging is deprecated, use countlyConfig.enableLogging instead");
CountlyReactNative.setLoggingEnabled([false]);
};
/**
* Set to true if you want to enable countly internal debugging logs
* Should be called before Countly init
*
* @param {[boolean = true]} enabled server url
*/
Countly.setLoggingEnabled = function (enabled = true) {
// TODO: init check
L.d(`setLoggingEnabled, Setting logging enabled to: [${enabled}]`);
CountlyReactNative.setLoggingEnabled([enabled]);
};
/**
* @deprecated in 23.02.0 : use 'countlyConfig.setLocation' instead of 'setLocationInit'.
*
* Set user initial location
* Should be called before init
* @param {string | null} countryCode ISO Country code for the user's country
* @param {string | null} city Name of the user's city
* @param {string | null} location comma separate lat and lng values. For example, "56.42345,123.45325"
* @param {string | null} ipAddress IP address of user's
*/
Countly.setLocationInit = function (countryCode, city, location, ipAddress) {
L.w("setLocationInit, setLocationInit is deprecated, use countlyConfig.setLocation instead");
const args = [];
args.push(countryCode || "null");
args.push(city || "null");
args.push(location || "null");
args.push(ipAddress || "null");
CountlyReactNative.setLocationInit(args);
};
/**
*
* Set user location
* @param {string | null} countryCode ISO Country code for the user's country
* @param {string | null} city Name of the user's city
* @param {string | null} location comma separate lat and lng values. For example, "56.42345,123.45325"
* @param {string | null} ipAddress IP address of user's
* @return {string | void} error message or void
*/
Countly.setLocation = function (countryCode, city, location, ipAddress) {
if (!_state.isInitialized) {
const message = "'init' must be called before 'setLocation'";
L.e(`setLocation, ${message}`);
return message;
}
L.d(`setLocation, Setting location: [${countryCode}, ${city}, ${location}, ${ipAddress}]`);
const args = [];
args.push(countryCode || "null");
args.push(city || "null");
args.push(location || "null");
args.push(ipAddress || "null");
CountlyReactNative.setLocation(args);
};
/**
*
* Disable user location
*
* @return {string | void} error message or void
*/
Countly.disableLocation = function () {
if (!_state.isInitialized) {
const message = "'init' must be called before 'disableLocation'";
L.e(`disableLocation, ${message}`);
return message;
}
L.d("disableLocation, Disabling location");
CountlyReactNative.disableLocation();
};
/**
*
* Get currently used device Id.
* Should be called after Countly init
*
* @return {string} device id or error message
*/
Countly.getCurrentDeviceId = async function () {
if (!_state.isInitialized) {
const message = "'init' must be called before 'getCurrentDeviceId'";
L.e(`getCurrentDeviceId, ${message}`);
return message;
}
L.d("getCurrentDeviceId, Getting current device id");
const result = await CountlyReactNative.getCurrentDeviceId();
return result;
};
/**
* Get currently used device Id type.
* Should be called after Countly init
*
* @return {DeviceIdType | null} deviceIdType or null
*/
Countly.getDeviceIDType = async function () {
if (!_state.isInitialized) {
L.e("getDeviceIDType, 'init' must be called before 'getDeviceIDType'");
return null;
}
L.d("getDeviceIDType, Getting device id type");
const result = await CountlyReactNative.getDeviceIDType();
return Utils.intToDeviceIDType(result);
};
/**
* Change the current device id
*
* @param {string} newDeviceID id new device id
* @param {boolean} onServer merge device id
* @return {string | void} error message or void
*/
Countly.changeDeviceId = function (newDeviceID, onServer) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'changeDeviceId'";
L.e(`changeDeviceId, ${msg}`);
return msg;
}
const message = Validate.String(newDeviceID, "newDeviceID", "changeDeviceId");
if (message) {
return message;
}
L.d(`changeDeviceId, Changing to new device id: [${newDeviceID}], with merge: [${onServer}]`);
if (!onServer) {
onServer = "0";
} else {
onServer = "1";
}
newDeviceID = newDeviceID.toString();
CountlyReactNative.changeDeviceId([newDeviceID, onServer]);
};
/**
*
* Set to "true" if you want HTTP POST to be used for all requests
* Should be called before Countly init
* @param {boolean} forceHttp force http post for all requests.
*/
Countly.setHttpPostForced = function (boolean = true) {
L.d(`setHttpPostForced, Setting http post forced to: [${boolean}]`);
const args = [];
args.push(boolean ? "1" : "0");
CountlyReactNative.setHttpPostForced(args);
};
/**
* @deprecated in 23.02.0 : use 'countlyConfig.enableCrashReporting' instead of 'enableCrashReporting'.
*
* Enable crash reporting to report unhandled crashes to Countly
* Should be called before Countly init
*/
Countly.enableCrashReporting = async function () {
L.w("enableCrashReporting, enableCrashReporting is deprecated, use countlyConfig.enableCrashReporting instead");
CountlyReactNative.enableCrashReporting();
if (ErrorUtils && !_isCrashReportingEnabled) {
L.i("enableCrashReporting, Adding Countly JS error handler.");
const previousHandler = ErrorUtils.getGlobalHandler();
ErrorUtils.setGlobalHandler((error, isFatal) => {
const jsStackTrace = Utils.getStackTrace(error);
let errorTitle;
let stackArr;
if (jsStackTrace == null) {
errorTitle = error.name;
stackArr = error.stack;
} else {
let fname = jsStackTrace[0].file;
if (fname.startsWith("http")) {
const chunks = fname.split("/");
fname = chunks[chunks.length - 1].split("?")[0];
}
errorTitle = `${error.name} (${jsStackTrace[0].methodName}@${fname})`;
const regExp = "(.*)(@?)http(s?).*/(.*)\\?(.*):(.*):(.*)";
stackArr = error.stack.split("\n").map((row) => {
row = row.trim();
if (!row.includes("http")) {
return row;
}
const matches = row.match(regExp);
return matches && matches.length == 8 ? `${matches[1]}${matches[2]}${matches[4]}(${matches[6]}:${matches[7]})` : row;
});
stackArr = stackArr.join("\n");
}
CountlyReactNative.logJSException(errorTitle, error.message.trim(), stackArr);
if (previousHandler) {
previousHandler(error, isFatal);
}
});
}
_isCrashReportingEnabled = true;
};
/**
*
* Add crash log for Countly
*
* @param {string} crashLog crash log
* @return {string | void} error message or void
*/
Countly.addCrashLog = function (crashLog) {
if (!_state.isInitialized) {
const message = "'init' must be called before 'addCrashLog'";
L.e(`addCrashLog, ${message}`);
return message;
}
L.d(`addCrashLog, Adding crash log: [${crashLog}]`);
CountlyReactNative.addCrashLog([crashLog]);
};
/**
*
* Log exception for Countly
*
* @param {string} exception exception
* @param {boolean} nonfatal nonfatal
* @param {object} segments segments
* @return {string | void} error message or void
*/
Countly.logException = function (exception, nonfatal, segments) {
if (!_state.isInitialized) {
const message = "'init' must be called before 'logException'";
L.e(`logException, ${message}`);
return message;
}
L.d(`logException, Logging exception: [${exception}], with nonfatal: [${nonfatal}], with segments: [${JSON.stringify(segments)}]`);
const exceptionArray = exception.split("\n");
let exceptionString = "";
for (let i = 0, il = exceptionArray.length; i < il; i++) {
exceptionString += `${exceptionArray[i]}\n`;
}
const args = [];
args.push(exceptionString || "");
args.push(nonfatal || false);
for (const key in segments) {
args.push(key);
args.push(segments[key].toString());
}
CountlyReactNative.logException(args);
};
/**
*
* Set custom crash segment for Countly
*
* @param {object} segments segments
*/
Countly.setCustomCrashSegments = function (segments) {
L.d(`setCustomCrashSegments, Setting custom crash segments: [${JSON.stringify(segments)}]`);
const args = [];
for (const key in segments) {
args.push(key.toString());
args.push(segments[key].toString());
}
CountlyReactNative.setCustomCrashSegments(args);
};
/**
*
* Start session tracking
*
* @return {string | void} error message or void
*/
Countly.startSession = function () {
if (!_state.isInitialized) {
const message = "'init' must be called before 'startSession'";
L.e(`startSession, ${message}`);
return message;
}
L.d("startSession, Starting session");
CountlyReactNative.startSession();
};
/**
*
* End session tracking
*
* @return {string | void} error message or void
*/
Countly.endSession = function () {
if (!_state.isInitialized) {
const message = "'init' must be called before 'endSession'";
L.e(`endSession, ${message}`);
return message;
}
L.d("endSession, Ending session");
CountlyReactNative.endSession();
};
/**
* @deprecated in 23.02.0 : use 'countlyConfig.enableParameterTamperingProtection' instead of 'enableParameterTamperingProtection'.
*
* Set the optional salt to be used for calculating the checksum of requested data which will be sent with each request, using the &checksum field
* Should be called before Countly init
*
* @param {string} salt salt
* @return {string | void} error message or void
*/
Countly.enableParameterTamperingProtection = function (salt) {
const message = Validate.String(salt, "salt", "enableParameterTamperingProtection");
if (message) {
return message;
}
L.w(`enableParameterTamperingProtection, enableParameterTamperingProtection is deprecated, use countlyConfig.enableParameterTamperingProtection instead. Salt : [${salt}]`);
CountlyReactNative.enableParameterTamperingProtection([salt.toString()]);
};
/**
*
* It will ensure that connection is made with one of the public keys specified
* Should be called before Countly init
*
* @return {string | void} error message or void
*/
Countly.pinnedCertificates = function (certificateName) {
const message = Validate.String(certificateName, "certificateName", "pinnedCertificates");
if (message) {
return message;
}
L.d(`pinnedCertificates, Setting pinned certificates: [${certificateName}]`);
CountlyReactNative.pinnedCertificates([certificateName]);
};
/**
* Start a Timed Event
* @deprecated in 24.4.0 : use 'Countly.events.startEvent' instead of this.
*
* @param {string} eventName name of event
* @return {string | void} error message or void
*/
Countly.startEvent = function (eventName) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'startEvent'";
L.e(`startEventLegacy, ${msg}`);
return msg;
}
L.w("startEventLegacy, This method is deprecated, use 'Countly.events.startEvent' instead");
Countly.events.startEvent(eventName);
};
/**
* Cancel a Timed Event
* @deprecated in 24.4.0 : use 'Countly.events.cancelEvent' instead of this.
*
* @param {string} eventName name of event
* @return {string | void} error message or void
*/
Countly.cancelEvent = function (eventName) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'cancelEvent'";
L.e(`cancelEventLegacy, ${msg}`);
return msg;
}
L.w("cancelEventLegacy, This method is deprecated, use 'Countly.events.cancelEvent' instead");
Countly.events.cancelEvent(eventName);
};
/**
* End a Timed Event
* @deprecated in 24.4.0 : use 'Countly.events.endEvent' instead of this.
*
* @param {string | CountlyEventOptions} options event options.
* CountlyEventOptions {
* eventName: string;
* eventCount?: number;
* eventSum?: number | string;
* segments?: Segmentation;
* }
* @return {string | void} error message or void
*/
Countly.endEvent = function (options) {
if (!_state.isInitialized) {
const message = "'init' must be called before 'endEvent'";
L.e(`endEventLegacy, ${message}`);
return message;
}
L.w("endEventLegacy, This method is deprecated, use 'Countly.events.endEvent' instead");
if (!options) {
const message = "no event object or event name provided!";
L.w(`endEventLegacy, ${message}`);
return message;
}
if (typeof options === "string") {
options = { eventName: options };
}
// previous implementation was not clear about the data types of eventCount and eventSum
// here parse them to make sure they are in correct format for the new method
// parser will return a false value (NaN) in case of invalid data (like undefined, null, empty string, etc.)
options.eventCount = parseInt(options.eventCount, 10) || 1;
options.eventSum = parseFloat(options.eventSum) || 0;
Countly.events.endEvent(options.eventName, options.segments, options.eventCount, options.eventSum);
};
/**
*
* Used to send user data
*
* @param {object} userData user data
* @return {string | void} error message or void
*/
Countly.setUserData = async function (userData) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'setUserData'";
L.e(`setUserData, ${msg}`);
return msg;
}
L.d(`setUserData, Setting user data: [${JSON.stringify(userData)}]`);
let message = null;
if (!userData) {
message = "User profile data should not be null or undefined";
L.e(`setUserData, ${message}`);
return message;
}
if (typeof userData !== "object") {
message = `unsupported data type of user data '${typeof userData}'`;
L.w(`setUserData, ${message}`);
return message;
}
const args = [];
for (const key in userData) {
if (typeof userData[key] !== "string" && key.toString() != "byear") {
L.w("setUserData, " + `skipping value for key '${key.toString()}', due to unsupported data type '${typeof userData[key]}', its data type should be 'string'`);
}
}
if (userData.org && !userData.organization) {
userData.organization = userData.org;
delete userData.org;
}
if (userData.byear) {
Validate.ParseInt(userData.byear, "key byear", "setUserData");
userData.byear = userData.byear.toString();
}
args.push(userData);
await CountlyReactNative.setUserData(args);
};
/**
*
* Set custom key and value pair for the current user.
*
* @param {string} keyName user property key
* @param {object} keyValue user property value
* @return {string | void} error message or void
*/
Countly.userData.setProperty = async function (keyName, keyValue) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'setProperty'";
L.e(`setProperty, ${msg}`);
return msg;
}
L.d(`setProperty, Setting user property: [${keyName}, ${keyValue}]`);
let message = Validate.String(keyName, "key", "setProperty");
if (message) {
return message;
}
message = Validate.ValidUserData(keyValue, "value", "setProperty");
if (message) {
return message;
}
keyName = keyName.toString();
keyValue = keyValue.toString();
if (keyName && (keyValue || keyValue == "")) {
await CountlyReactNative.userData_setProperty([keyName, keyValue]);
}
};
/**
*
* Increment custom user data by 1
*
* @param {string} keyName user property key
* @return {string | void} error message or void
*/
Countly.userData.increment = async function (keyName) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'increment'";
L.e(`increment, ${msg}`);
return msg;
}
L.d(`increment, Incrementing user property: [${keyName}]`);
const message = Validate.String(keyName, "key", "increment");
if (message) {
return message;
}
keyName = keyName.toString();
if (keyName) {
await CountlyReactNative.userData_increment([keyName]);
}
};
/**
*
* Increment custom user data by a specified value
*
* @param {string} keyName user property key
* @param {string} keyValue value to increment user property by
* @return {string | void} error message or void
*/
Countly.userData.incrementBy = async function (keyName, keyValue) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'incrementBy'";
L.e(`incrementBy, ${msg}`);
return msg;
}
L.d(`incrementBy, Incrementing user property: [${keyName}, ${keyValue}]`);
let message = Validate.String(keyName, "key", "incrementBy");
if (message) {
return message;
}
message = Validate.UserDataValue(keyValue, "value", "incrementBy");
if (message) {
return message;
}
const intValue = parseInt(keyValue, 10).toString();
await CountlyReactNative.userData_incrementBy([keyName, intValue]);
};
/**
*
* Multiply custom user data by a specified value
*
* @param {string} keyName user property key
* @param {string} keyValue value to multiply user property by
* @return {string | void} error message or void
*/
Countly.userData.multiply = async function (keyName, keyValue) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'multiply'";
L.e(`multiply, ${msg}`);
return msg;
}
L.d(`multiply, Multiplying user property: [${keyName}, ${keyValue}]`);
let message = Validate.String(keyName, "key", "multiply");
if (message) {
return message;
}
message = Validate.UserDataValue(keyValue, "value", "multiply");
if (message) {
return message;
}
const intValue = parseInt(keyValue, 10).toString();
await CountlyReactNative.userData_multiply([keyName, intValue]);
};
/**
*
* Save the max value between current and provided value.
*
* @param {string} keyName user property key
* @param {string} keyValue user property value
* @return {string | void} error message or void
*/
Countly.userData.saveMax = async function (keyName, keyValue) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'saveMax'";
L.e(`saveMax, ${msg}`);
return msg;
}
L.d(`saveMax, Saving max user property: [${keyName}, ${keyValue}]`);
let message = Validate.String(keyName, "key", "saveMax");
if (message) {
return message;
}
message = Validate.UserDataValue(keyValue, "value", "saveMax");
if (message) {
return message;
}
const intValue = parseInt(keyValue, 10).toString();
await CountlyReactNative.userData_saveMax([keyName, intValue]);
};
/**
*
* Save the min value between current and provided value.
*
* @param {string} keyName user property key
* @param {string} keyValue user property value
* @return {string | void} error message or void
*/
Countly.userData.saveMin = async function (keyName, keyValue) {
if (!_state.isInitialized) {
const msg = "'init' must be called before 'saveMin'";
L.e(`saveMin, ${msg}`);
return msg;
}
L.d(`saveMin, Saving min user property: [${keyName}, ${keyValue}]`);
let message = Validate.String(keyName, "key", "saveMin");
if (message) {
return message;
}
message = Validate.UserDataValue(keyValue, "value", "saveMin");
if (message) {
return message;
}
const intValue = parseInt(keyValue, 10).toString();
await CountlyReactNative.userData_saveMin([keyName, intValue]);
};
/**
*
* Set the property value if it does not exist.
*
* @param {string} keyName user property key
* @param {string} keyValue user property value
* @return {string | void} error message or void
*/
Countly.userData.setOnce = async function (keyName, keyValue) {
if (!_state.isInitialized) {