-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathCountlyServerConfig.m
More file actions
1031 lines (895 loc) · 36.6 KB
/
Copy pathCountlyServerConfig.m
File metadata and controls
1031 lines (895 loc) · 36.6 KB
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
// CountlyServerConfig.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyCommon.h"
@interface CountlyServerConfig () {
NSTimer *_requestTimer;
}
@property (nonatomic) BOOL trackingEnabled;
@property (nonatomic) BOOL networkingEnabled;
@property (nonatomic) BOOL crashReportingEnabled;
@property (nonatomic) BOOL loggingEnabled;
@property (nonatomic) BOOL customEventTrackingEnabled;
@property (nonatomic) BOOL viewTrackingEnabled;
@property (nonatomic) BOOL sessionTrackingEnabled;
@property (nonatomic) BOOL enterContentZone;
@property (nonatomic) BOOL consentRequired;
@property (nonatomic) BOOL locationTracking;
@property (nonatomic) BOOL refreshContentZone;
@property (nonatomic) BOOL backoffMechanism;
@property (nonatomic) NSInteger limitKeyLength;
@property (nonatomic) NSInteger limitValueSize;
@property (nonatomic) NSInteger limitSegValues;
@property (nonatomic) NSInteger limitBreadcrumb;
@property (nonatomic) NSInteger limitTraceLine;
@property (nonatomic) NSInteger limitTraceLength;
@property (nonatomic) NSInteger sessionInterval;
@property (nonatomic) NSInteger eventQueueSize;
@property (nonatomic) NSInteger requestQueueSize;
@property (nonatomic) NSInteger contentZoneInterval;
@property (nonatomic) NSInteger dropOldRequestTime;
@property (nonatomic) NSInteger serverConfigUpdateInterval;
@property (nonatomic) NSInteger currentServerConfigUpdateInterval;
@property (nonatomic) NSInteger bomAcceptedTimeoutSeconds;
@property (nonatomic) double bomRQPercentage;
@property (nonatomic) NSInteger bomRequestAge;
@property (nonatomic) NSInteger bomDuration;
@property (nonatomic) NSInteger requestTimeoutDuration;
@property (nonatomic) NSSet<NSString *> *eventFilterSet;
@property (nonatomic) BOOL eventFilterIsWhitelist;
@property (nonatomic) NSSet<NSString *> *userPropertyFilterSet;
@property (nonatomic) BOOL userPropertyFilterIsWhitelist;
@property (nonatomic) NSInteger userPropertyCacheLimit;
@property (nonatomic) NSSet<NSString *> *segmentationFilterSet;
@property (nonatomic) BOOL segmentationFilterIsWhitelist;
@property (nonatomic) NSDictionary<NSString *, NSSet<NSString *> *> *eventSegmentationFilterMap;
@property (nonatomic) BOOL eventSegmentationFilterIsWhitelist;
@property (nonatomic) NSSet<NSString *> *journeyTriggerEvents;
@property (nonatomic) NSInteger version;
@property (nonatomic) long long timestamp;
@property (nonatomic) long long lastFetchTimestamp;
@property (nonatomic) BOOL serverConfigUpdatesDisabled;
@end
NSString *const kCountlySCKeySC = @"sc";
NSString *const kTracking = @"tracking";
NSString *const kNetworking = @"networking";
// request keys
NSString *const kRTimestamp = @"t";
NSString *const kRVersion = @"v";
NSString *const kRConfig = @"c";
NSString *const kRReqQueueSize = @"rqs";
NSString *const kREventQueueSize = @"eqs";
NSString *const kRLogging = @"log";
NSString *const kRSessionUpdateInterval = @"sui";
NSString *const kRSessionTracking = @"st";
NSString *const kRViewTracking = @"vt";
NSString *const kRLocationTracking = @"lt";
NSString *const kRRefreshContentZone = @"rcz";
NSString *const kRbackoffMechanism = @"bom";
NSString *const kRLimitKeyLength = @"lkl";
NSString *const kRLimitValueSize = @"lvs";
NSString *const kRLimitSegValues = @"lsv";
NSString *const kRLimitBreadcrumb = @"lbc";
NSString *const kRLimitTraceLine = @"ltlpt";
NSString *const kRLimitTraceLength = @"ltl";
NSString *const kRCustomEventTracking = @"cet";
NSString *const kREnterContentZone = @"ecz";
NSString *const kRContentZoneInterval = @"czi";
NSString *const kRConsentRequired = @"cr";
NSString *const kRDropOldRequestTime = @"dort";
NSString *const kRCrashReporting = @"crt";
NSString *const kRServerConfigUpdateInterval = @"scui";
NSString *const kRBOMAcceptedTimeout = @"bom_at";
NSString *const kRBOMRQPercentage = @"bom_rqp";
NSString *const kRBOMRequestAge = @"bom_ra";
NSString *const kRBOMDuration = @"bom_d";
NSString *const kREventBlacklist = @"eb";
NSString *const kREventWhitelist = @"ew";
NSString *const kRUserPropertyBlacklist = @"upb";
NSString *const kRUserPropertyWhitelist = @"upw";
NSString *const kRUserPropertyCacheLimit = @"upcl";
NSString *const kRSegmentationBlacklist = @"sb";
NSString *const kRSegmentationWhitelist = @"sw";
NSString *const kREventSegmentationBlacklist = @"esb";
NSString *const kREventSegmentationWhitelist = @"esw";
NSString *const kRJourneyTriggerEvents = @"jte";
static CountlyServerConfig *s_sharedInstance = nil;
static dispatch_once_t onceToken;
@implementation CountlyServerConfig
+ (instancetype)sharedInstance
{
if (!CountlyCommon.sharedInstance.hasStarted)
return nil;
dispatch_once(&onceToken, ^{
s_sharedInstance = self.new;
});
return s_sharedInstance;
}
- (instancetype)init
{
self = [super init];
if (self)
{
_timestamp = 0;
_version = 0;
_currentServerConfigUpdateInterval = 4;
_requestTimer = nil;
_serverConfigUpdatesDisabled = NO;
_requestTimeoutDuration = 30;
[self setDefaultValues];
}
return self;
}
- (void)resetInstance
{
CLY_LOG_I(@"%s", __FUNCTION__);
_timestamp = 0;
_version = 0;
_currentServerConfigUpdateInterval = 4;
_serverConfigUpdatesDisabled = NO;
_requestTimeoutDuration = 30;
_lastFetchTimestamp = 0;
if (_requestTimer)
{
[_requestTimer invalidate];
_requestTimer = nil;
}
[self setDefaultValues];
onceToken = 0;
s_sharedInstance = nil;
}
- (void)retrieveServerConfigFromStorage:(CountlyConfig *)config
{
NSMutableDictionary *persistentBehaviorSettings = [CountlyPersistency.sharedInstance retrieveServerConfig];
if (persistentBehaviorSettings.count == 0 && config.sdkBehaviorSettings)
{
NSError *error = nil;
id parsed = [NSJSONSerialization JSONObjectWithData:[config.sdkBehaviorSettings cly_dataUTF8] options:0 error:&error];
if ([parsed isKindOfClass:[NSDictionary class]]) {
persistentBehaviorSettings = [(NSDictionary *)parsed mutableCopy];
} else {
CLY_LOG_W(@"%s, Failed to parse sdkBehaviorSettings or not a dictionary: %@", __FUNCTION__, error);
}
}
[self populateServerConfig:persistentBehaviorSettings withConfig:config];
[CountlyPersistency.sharedInstance storeServerConfig:persistentBehaviorSettings];
}
- (void)mergeBehaviorSettings:(NSMutableDictionary *)baseConfig
withConfig:(NSDictionary *)newConfig
{
// c, t and v paramters must exist
if(newConfig.count != 3 || !newConfig[kRConfig]) {
CLY_LOG_D(@"%s, missing entries for a behavior settings omitting", __FUNCTION__);
return;
}
if (!newConfig[kRVersion] || !newConfig[kRTimestamp])
{
CLY_LOG_D(@"%s, version or timestamp is missing in the behavioır settings omitting", __FUNCTION__);
return;
}
if(!([newConfig[kRConfig] isKindOfClass:[NSDictionary class]]) || ((NSDictionary *)newConfig[kRConfig]).count == 0){
CLY_LOG_D(@"%s, invalid behavior settings omitting", __FUNCTION__);
return;
}
id timestamp = newConfig[kRTimestamp];
if (timestamp) {
baseConfig[kRTimestamp] = timestamp;
}
id version = newConfig[kRVersion];
if (version) {
baseConfig[kRVersion] = version;
}
NSDictionary *cBase = baseConfig[kRConfig] ?: NSMutableDictionary.new;
NSDictionary *cNew = newConfig[kRConfig];
if ([cBase isKindOfClass:[NSDictionary class]] || [cNew isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *cMerged = [cBase mutableCopy];
[cNew enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (obj != nil && obj != [NSNull null]) {
cMerged[key] = obj;
}
}];
[self removeConflictingFilterKeys:cMerged newConfig:cNew];
baseConfig[kRConfig] = cMerged;
}
}
- (void)setBoolProperty:(BOOL *)property fromDictionary:(NSMutableDictionary *)dictionary key:(NSString *)key logString:(NSMutableString *)logString
{
id value = dictionary[key];
if (!value)
return;
if (CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID())
{
*property = [value boolValue];
[logString appendFormat:@"%@: %@, ", key, *property ? @"YES" : @"NO"];
}
else
{
CLY_LOG_W(@"%s, Invalid type for bool key '%@', removing", __FUNCTION__, key);
[dictionary removeObjectForKey:key];
}
}
- (void)setIntegerProperty:(NSInteger *)property fromDictionary:(NSMutableDictionary *)dictionary key:(NSString *)key logString:(NSMutableString *)logString
{
[self setIntegerProperty:property fromDictionary:dictionary key:key minValue:1 logString:logString];
}
- (void)setIntegerProperty:(NSInteger *)property fromDictionary:(NSMutableDictionary *)dictionary key:(NSString *)key minValue:(NSInteger)minValue logString:(NSMutableString *)logString
{
id value = dictionary[key];
if (!value)
return;
if ([value isKindOfClass:[NSNumber class]] && CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID())
{
NSInteger intVal = [value integerValue];
if (intVal >= minValue)
{
*property = intVal;
[logString appendFormat:@"%@: %ld, ", key, (long)*property];
}
else
{
CLY_LOG_W(@"%s, Invalid value (%ld) for integer key '%@' (min: %ld), removing", __FUNCTION__, (long)intVal, key, (long)minValue);
[dictionary removeObjectForKey:key];
}
}
else
{
CLY_LOG_W(@"%s, Invalid type for integer key '%@', removing", __FUNCTION__, key);
[dictionary removeObjectForKey:key];
}
}
- (void)setDoubleProperty:(double *)property fromDictionary:(NSMutableDictionary *)dictionary key:(NSString *)key logString:(NSMutableString *)logString
{
id value = dictionary[key];
if (!value)
return;
if ([value isKindOfClass:[NSNumber class]] && CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID())
{
double dblVal = [value doubleValue];
if (dblVal > 0.0 && dblVal < 1.0)
{
*property = dblVal;
[logString appendFormat:@"%@: %lf, ", key, (double)*property];
}
else
{
CLY_LOG_W(@"%s, Invalid value (%lf) for double key '%@', removing", __FUNCTION__, dblVal, key);
[dictionary removeObjectForKey:key];
}
}
else
{
CLY_LOG_W(@"%s, Invalid type for double key '%@', removing", __FUNCTION__, key);
[dictionary removeObjectForKey:key];
}
}
- (void)populateServerConfig:(NSMutableDictionary *)serverConfig withConfig:(CountlyConfig *)config
{
if(config.requestTimeoutDuration <= 0) {
config.requestTimeoutDuration = 1;
}
_requestTimeoutDuration = config.requestTimeoutDuration;
if (!serverConfig[kRConfig])
{
CLY_LOG_D(@"%s, config key is missing in the server configuration omitting", __FUNCTION__);
return;
}
NSMutableDictionary *dictionary;
if ([serverConfig[kRConfig] isKindOfClass:[NSDictionary class]])
{
dictionary = [serverConfig[kRConfig] mutableCopy];
}
else
{
CLY_LOG_D(@"%s, config is not a dictionary, omitting", __FUNCTION__);
return;
}
if (!serverConfig[kRVersion] || !serverConfig[kRTimestamp])
{
CLY_LOG_D(@"%s, version or timestamp is missing in the server configuration omitting", __FUNCTION__);
return;
}
_version = [serverConfig[kRVersion] integerValue];
_timestamp = [serverConfig[kRTimestamp] longLongValue];
NSMutableString *logString = [NSMutableString stringWithString:@"Server Config: "];
// Known keys set — used to remove unknown keys after validation
NSMutableSet *knownKeys = [NSMutableSet setWithArray:@[
kTracking,
kNetworking,
kRSessionUpdateInterval,
kRReqQueueSize,
kREventQueueSize,
kRCrashReporting,
kRSessionTracking,
kRLogging,
kRLimitKeyLength,
kRLimitValueSize,
kRLimitSegValues,
kRLimitBreadcrumb,
kRLimitTraceLine,
kRLimitTraceLength,
kRCustomEventTracking,
kRViewTracking,
kREnterContentZone,
kRContentZoneInterval,
kRConsentRequired,
kRDropOldRequestTime,
kRServerConfigUpdateInterval,
kRLocationTracking,
kRRefreshContentZone,
kRbackoffMechanism,
kRBOMAcceptedTimeout,
kRBOMRQPercentage,
kRBOMRequestAge,
kRBOMDuration,
kRUserPropertyCacheLimit,
kREventBlacklist,
kREventWhitelist,
kRUserPropertyBlacklist,
kRUserPropertyWhitelist,
kRSegmentationBlacklist,
kRSegmentationWhitelist,
kREventSegmentationBlacklist,
kREventSegmentationWhitelist,
kRJourneyTriggerEvents
]];
// Remove unknown keys
for (NSString *key in dictionary.allKeys)
{
if (![knownKeys containsObject:key])
{
CLY_LOG_W(@"%s, Unknown config key '%@', removing", __FUNCTION__, key);
[dictionary removeObjectForKey:key];
}
}
[self setBoolProperty:&_trackingEnabled fromDictionary:dictionary key:kTracking logString:logString];
[self setBoolProperty:&_networkingEnabled fromDictionary:dictionary key:kNetworking logString:logString];
[self setIntegerProperty:&_sessionInterval fromDictionary:dictionary key:kRSessionUpdateInterval logString:logString];
[self setIntegerProperty:&_requestQueueSize fromDictionary:dictionary key:kRReqQueueSize logString:logString];
[self setIntegerProperty:&_eventQueueSize fromDictionary:dictionary key:kREventQueueSize logString:logString];
[self setBoolProperty:&_crashReportingEnabled fromDictionary:dictionary key:kRCrashReporting logString:logString];
[self setBoolProperty:&_sessionTrackingEnabled fromDictionary:dictionary key:kRSessionTracking logString:logString];
[self setBoolProperty:&_loggingEnabled fromDictionary:dictionary key:kRLogging logString:logString];
[self setIntegerProperty:&_limitKeyLength fromDictionary:dictionary key:kRLimitKeyLength logString:logString];
[self setIntegerProperty:&_limitValueSize fromDictionary:dictionary key:kRLimitValueSize logString:logString];
[self setIntegerProperty:&_limitSegValues fromDictionary:dictionary key:kRLimitSegValues logString:logString];
[self setIntegerProperty:&_limitBreadcrumb fromDictionary:dictionary key:kRLimitBreadcrumb logString:logString];
[self setIntegerProperty:&_limitTraceLine fromDictionary:dictionary key:kRLimitTraceLine logString:logString];
[self setIntegerProperty:&_limitTraceLength fromDictionary:dictionary key:kRLimitTraceLength logString:logString];
[self setBoolProperty:&_customEventTrackingEnabled fromDictionary:dictionary key:kRCustomEventTracking logString:logString];
[self setBoolProperty:&_viewTrackingEnabled fromDictionary:dictionary key:kRViewTracking logString:logString];
[self setBoolProperty:&_enterContentZone fromDictionary:dictionary key:kREnterContentZone logString:logString];
[self setIntegerProperty:&_contentZoneInterval fromDictionary:dictionary key:kRContentZoneInterval minValue:16 logString:logString];
[self setBoolProperty:&_consentRequired fromDictionary:dictionary key:kRConsentRequired logString:logString];
[self setIntegerProperty:&_dropOldRequestTime fromDictionary:dictionary key:kRDropOldRequestTime minValue:0 logString:logString];
[self setIntegerProperty:&_serverConfigUpdateInterval fromDictionary:dictionary key:kRServerConfigUpdateInterval logString:logString];
[self setBoolProperty:&_locationTracking fromDictionary:dictionary key:kRLocationTracking logString:logString];
[self setBoolProperty:&_refreshContentZone fromDictionary:dictionary key:kRRefreshContentZone logString:logString];
[self setBoolProperty:&_backoffMechanism fromDictionary:dictionary key:kRbackoffMechanism logString:logString];
[self setIntegerProperty:&_bomAcceptedTimeoutSeconds fromDictionary:dictionary key:kRBOMAcceptedTimeout logString:logString];
[self setDoubleProperty:&_bomRQPercentage fromDictionary:dictionary key:kRBOMRQPercentage logString:logString];
[self setIntegerProperty:&_bomRequestAge fromDictionary:dictionary key:kRBOMRequestAge logString:logString];
[self setIntegerProperty:&_bomDuration fromDictionary:dictionary key:kRBOMDuration logString:logString];
[self setIntegerProperty:&_userPropertyCacheLimit fromDictionary:dictionary key:kRUserPropertyCacheLimit logString:logString];
[self updateListingFilters:dictionary logString:logString];
// Update the config dictionary with cleaned values
serverConfig[kRConfig] = dictionary;
if(![logString isEqualToString: @"Server Config: "]){
// means new config gotten, if that is the case notify SDK
[self notifySdkConfigChange: config];
}
CLY_LOG_D(@"%s, version:[%li], timestamp:[%lli], %@", __FUNCTION__, _version, _timestamp, logString);
}
- (void)notifySdkConfigChange:(CountlyConfig *)config
{
config.enableDebug = _loggingEnabled || config.enableDebug;
CountlyCommon.sharedInstance.enableDebug = config.enableDebug;
// Limits could be moved to another function, but letting them stay here serves us a monopolized view of notify
if (config.maxKeyLength != kCountlyMaxKeyLength)
{
[config.sdkInternalLimits setMaxKeyLength:config.maxKeyLength];
}
if (config.maxValueLength != kCountlyMaxValueSize)
{
[config.sdkInternalLimits setMaxValueSize:config.maxValueLength];
}
if (config.maxSegmentationValues != kCountlyMaxSegmentationValues)
{
[config.sdkInternalLimits setMaxSegmentationValues:config.maxSegmentationValues];
}
if (config.crashLogLimit != kCountlyMaxBreadcrumbCount)
{
[config.sdkInternalLimits setMaxBreadcrumbCount:config.crashLogLimit];
}
[config.sdkInternalLimits setMaxKeyLength:_limitKeyLength ?: config.sdkInternalLimits.getMaxKeyLength];
[config.sdkInternalLimits setMaxValueSize:_limitValueSize ?: config.sdkInternalLimits.getMaxValueSize];
[config.sdkInternalLimits setMaxSegmentationValues:_limitSegValues ?: config.sdkInternalLimits.getMaxSegmentationValues];
[config.sdkInternalLimits setMaxBreadcrumbCount:_limitBreadcrumb ?: config.sdkInternalLimits.getMaxBreadcrumbCount];
[config.sdkInternalLimits setMaxStackTraceLineLength:_limitTraceLength ?: config.sdkInternalLimits.getMaxStackTraceLineLength];
[config.sdkInternalLimits setMaxStackTraceLinesPerThread:_limitTraceLine ?: config.sdkInternalLimits.getMaxStackTraceLinesPerThread];
CountlyCommon.sharedInstance.maxKeyLength = config.sdkInternalLimits.getMaxKeyLength;
CountlyCommon.sharedInstance.maxValueLength = config.sdkInternalLimits.getMaxValueSize;
CountlyCommon.sharedInstance.maxValueLengthPicture = config.sdkInternalLimits.getMaxValueSizePicture;
CountlyCommon.sharedInstance.maxSegmentationValues = config.sdkInternalLimits.getMaxSegmentationValues;
config.eventSendThreshold = _eventQueueSize ?: config.eventSendThreshold;
config.requestDropAgeHours = _dropOldRequestTime ?: config.requestDropAgeHours;
config.storedRequestsLimit = _requestQueueSize ?: config.storedRequestsLimit;
CountlyPersistency.sharedInstance.eventSendThreshold = config.eventSendThreshold;
CountlyPersistency.sharedInstance.requestDropAgeHours = config.requestDropAgeHours;
CountlyPersistency.sharedInstance.storedRequestsLimit = MAX(1, config.storedRequestsLimit);
config.updateSessionPeriod = _sessionInterval ?: config.updateSessionPeriod;
_sessionInterval = config.updateSessionPeriod;
BOOL consentDidChange = !config.requiresConsent && _consentRequired;
config.requiresConsent = _consentRequired ?: config.requiresConsent;
CountlyConsentManager.sharedInstance.requiresConsent = config.requiresConsent;
if(consentDidChange && CountlyCommon.sharedInstance.hasFinishedInit){
[CountlyConsentManager.sharedInstance sendConsents];
if (!CountlyConsentManager.sharedInstance.consentForLocation)
{
[CountlyConnectionManager.sharedInstance sendLocationInfo];
}
}
#if (TARGET_OS_IOS)
[config.content setZoneTimerInterval:_contentZoneInterval ?: config.content.getZoneTimerInterval];
if (config.content.getZoneTimerInterval)
{
CountlyContentBuilderInternal.sharedInstance.zoneTimerInterval = config.content.getZoneTimerInterval;
}
if (!_enterContentZone)
{
dispatch_async(dispatch_get_main_queue(), ^{
[CountlyContentBuilderInternal.sharedInstance exitContentZone];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[CountlyContentBuilderInternal.sharedInstance exitContentZone];
[CountlyContentBuilderInternal.sharedInstance enterContentZone:@[]];
});
}
#endif
CountlyCrashReporter.sharedInstance.crashLogLimit = config.sdkInternalLimits.getMaxBreadcrumbCount;
if (_serverConfigUpdateInterval && _serverConfigUpdateInterval != _currentServerConfigUpdateInterval && _requestTimer)
{
_currentServerConfigUpdateInterval = _serverConfigUpdateInterval;
[_requestTimer invalidate];
_requestTimer = nil;
_requestTimer = [NSTimer timerWithTimeInterval:_currentServerConfigUpdateInterval * 60 * 60 target:self selector:@selector(fetchServerConfigTimer:) userInfo:config repeats:YES];
[NSRunLoop.mainRunLoop addTimer:_requestTimer forMode:NSRunLoopCommonModes];
}
if (!_locationTracking && !CountlyLocationManager.sharedInstance.isLocationInfoDisabled)
{
[CountlyLocationManager.sharedInstance disableLocation];
[CountlyConnectionManager.sharedInstance sendLocationInfo];
}
if(_backoffMechanism && config.disableBackoffMechanism){
_backoffMechanism = NO;
}
}
- (void)fetchServerConfigTimer:(NSTimer *)timer
{
CountlyConfig *config = (CountlyConfig *)timer.userInfo; // Retrieve CountlyConfig from userInfo
if (config)
{
[self fetchServerConfig:config];
}
}
- (void)fetchServerConfigIfTimeIsUp
{
if (_serverConfigUpdatesDisabled) {
return;
}
if (_lastFetchTimestamp)
{
long long currentTime = NSDate.date.timeIntervalSince1970 * 1000;
long long timePassed = currentTime - _lastFetchTimestamp;
if (timePassed > _currentServerConfigUpdateInterval * 60 * 60 * 1000)
{
[self fetchServerConfig:CountlyConfig.new];
}
}
}
- (void)fetchServerConfig:(CountlyConfig *)config
{
CLY_LOG_D(@"%s, fetching sdk behavior settings", __FUNCTION__);
if (_serverConfigUpdatesDisabled) {
CLY_LOG_D(@"%s, sdk behavior settings updates disabled, omitting fetch", __FUNCTION__);
return;
}
if (CountlyDeviceInfo.sharedInstance.isDeviceIDTemporary)
{
CLY_LOG_W(@"%s, fetch is skipped while in temporary device ID mode", __FUNCTION__);
return;
}
_lastFetchTimestamp = NSDate.date.timeIntervalSince1970 * 1000;
if (!_requestTimer)
{
_requestTimer = [NSTimer timerWithTimeInterval:_currentServerConfigUpdateInterval * 60 * 60 target:self selector:@selector(fetchServerConfigTimer:) userInfo:config repeats:YES];
[NSRunLoop.mainRunLoop addTimer:_requestTimer forMode:NSRunLoopCommonModes];
}
id handler = ^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *serverConfigResponse = nil;
if (!error)
{
serverConfigResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
CLY_LOG_D(@"Server Config Fetched: %@", serverConfigResponse.description);
}
if (!error)
{
if (((NSHTTPURLResponse *)response).statusCode != 200)
{
NSMutableDictionary *serverConfig = serverConfigResponse.mutableCopy;
serverConfig[NSLocalizedDescriptionKey] = @"Server configuration general API error";
error = [NSError errorWithDomain:kCountlyErrorDomain code:CLYErrorServerConfigGeneralAPIError userInfo:serverConfig];
}
}
if (error)
{
CLY_LOG_E(@"Error while fetching server configs: %@", error.description);
}
if (serverConfigResponse[kRConfig] != nil)
{
NSMutableDictionary *persistentBehaviorSettings = [CountlyPersistency.sharedInstance retrieveServerConfig];
[self mergeBehaviorSettings:persistentBehaviorSettings withConfig:serverConfigResponse];
[self populateServerConfig:persistentBehaviorSettings withConfig:config];
[CountlyPersistency.sharedInstance storeServerConfig:persistentBehaviorSettings];
}
};
// Set default values
NSURLSessionTask *task = [CountlyCommon.sharedInstance.ImmediateURLSession dataTaskWithRequest:[self serverConfigRequest] completionHandler:handler];
// IMMEDIATE REQUEST to find them better in search
[task resume];
}
- (NSURLRequest *)serverConfigRequest
{
NSString *queryString = [CountlyConnectionManager.sharedInstance queryEssentials];
queryString = [queryString stringByAppendingFormat:@"&%@=%@", kCountlyQSKeyMethod, kCountlySCKeySC];
queryString = [queryString stringByAppendingFormat:@"&%@=%@", kCountlyAppVersionKey, CountlyDeviceInfo.appVersion];
queryString = [CountlyConnectionManager.sharedInstance appendChecksum:queryString];
NSMutableString *URL = CountlyConnectionManager.sharedInstance.host.mutableCopy;
[URL appendString:kCountlyEndpointO];
[URL appendString:kCountlyEndpointSDK];
if (queryString.length > kCountlyGETRequestMaxLength || CountlyConnectionManager.sharedInstance.alwaysUsePOST)
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
request.HTTPMethod = @"POST";
request.HTTPBody = [queryString cly_dataUTF8];
return request.copy;
}
else
{
[URL appendFormat:@"?%@", queryString];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
return request;
}
CLY_LOG_D(@"serverConfigRequest URL :%@", URL);
}
- (void)setDefaultValues {
_trackingEnabled = YES;
_networkingEnabled = YES;
_crashReportingEnabled = YES;
_customEventTrackingEnabled = YES;
_enterContentZone = NO;
_locationTracking = YES;
_viewTrackingEnabled = YES;
_sessionTrackingEnabled = YES;
_loggingEnabled = NO;
_refreshContentZone = YES;
_backoffMechanism = YES;
_bomAcceptedTimeoutSeconds = 10;
_bomRQPercentage = 0.5;
_bomRequestAge = 24;
_bomDuration = 60;
_eventQueueSize = 0;
_requestQueueSize = 0;
_sessionInterval = 0;
_limitKeyLength = 0;
_limitValueSize = 0;
_limitSegValues = 0;
_limitBreadcrumb = 0;
_limitTraceLine = 0;
_limitTraceLength = 0;
_consentRequired = NO;
_dropOldRequestTime = 0;
_contentZoneInterval = 0;
_eventFilterSet = [NSSet set];
_eventFilterIsWhitelist = NO;
_userPropertyFilterSet = [NSSet set];
_userPropertyFilterIsWhitelist = NO;
_userPropertyCacheLimit = 100;
_segmentationFilterSet = [NSSet set];
_segmentationFilterIsWhitelist = NO;
_eventSegmentationFilterMap = @{};
_eventSegmentationFilterIsWhitelist = NO;
_journeyTriggerEvents = [NSSet set];
}
- (void)disableSDKBehaviourSettings {
_serverConfigUpdatesDisabled = YES;
}
- (BOOL)trackingEnabled
{
return _trackingEnabled;
}
- (BOOL)networkingEnabled
{
return _networkingEnabled;
}
- (NSInteger)sessionInterval
{
return _sessionInterval;
}
- (NSInteger)requestQueueSize
{
return _requestQueueSize;
}
- (NSInteger)eventQueueSize
{
return _eventQueueSize;
}
- (BOOL)crashReportingEnabled
{
return _crashReportingEnabled;
}
- (BOOL)sessionTrackingEnabled
{
return _sessionTrackingEnabled;
}
- (BOOL)loggingEnabled
{
return _loggingEnabled;
}
- (NSInteger)limitKeyLength
{
return _limitKeyLength;
}
- (NSInteger)limitValueSize
{
return _limitValueSize;
}
- (NSInteger)limitSegValues
{
return _limitSegValues;
}
- (NSInteger)limitBreadcrumb
{
return _limitBreadcrumb;
}
- (NSInteger)limitTraceLine
{
return _limitTraceLine;
}
- (NSInteger)limitTraceLength
{
return _limitTraceLength;
}
- (BOOL)customEventTrackingEnabled
{
return _customEventTrackingEnabled;
}
- (BOOL)viewTrackingEnabled
{
return _viewTrackingEnabled;
}
- (BOOL)enterContentZone
{
return _enterContentZone;
}
- (NSInteger)contentZoneInterval
{
return _contentZoneInterval;
}
- (BOOL)consentRequired
{
return _consentRequired;
}
- (NSInteger)dropOldRequestTime
{
return _dropOldRequestTime;
}
- (BOOL)locationTrackingEnabled
{
return _locationTracking;
}
- (BOOL)refreshContentZoneEnabled
{
return _refreshContentZone;
}
- (BOOL)backoffMechanism
{
return _backoffMechanism;
}
- (NSInteger)bomAcceptedTimeoutSeconds
{
return _bomAcceptedTimeoutSeconds;
}
- (double)bomRQPercentage
{
return _bomRQPercentage;
}
- (NSInteger)bomRequestAge
{
return _bomRequestAge;
}
- (NSInteger)bomDuration
{
return _bomDuration;
}
- (NSInteger)requestTimeoutDuration
{
return _requestTimeoutDuration;
}
- (NSInteger)userPropertyCacheLimit
{
return _userPropertyCacheLimit;
}
#pragma mark - Listing Filters
- (void)removeConflictingFilterKeys:(NSMutableDictionary *)mergedConfig newConfig:(NSDictionary *)newConfig
{
// Remove conflicting filter keys per category.
// Within each category, if new config provides a blacklist, remove stored whitelist (and vice versa).
NSArray *filterPairs = @[
@[kREventBlacklist, kREventWhitelist],
@[kRSegmentationBlacklist, kRSegmentationWhitelist],
@[kREventSegmentationBlacklist, kREventSegmentationWhitelist],
@[kRUserPropertyBlacklist, kRUserPropertyWhitelist],
];
for (NSArray *pair in filterPairs)
{
NSString *blacklistKey = pair[0];
NSString *whitelistKey = pair[1];
// Only consider valid filter values (arrays/dicts) for conflict resolution
id blacklistVal = newConfig[blacklistKey];
id whitelistVal = newConfig[whitelistKey];
BOOL hasValidBlacklist = [blacklistVal isKindOfClass:NSArray.class] || [blacklistVal isKindOfClass:NSDictionary.class];
BOOL hasValidWhitelist = [whitelistVal isKindOfClass:NSArray.class] || [whitelistVal isKindOfClass:NSDictionary.class];
if (hasValidBlacklist)
{
[mergedConfig removeObjectForKey:whitelistKey];
}
if (hasValidWhitelist)
{
[mergedConfig removeObjectForKey:blacklistKey];
}
}
}
- (void)updateListingFilters:(NSMutableDictionary *)dictionary logString:(NSMutableString *)logString
{
// Event filter (eb/ew) - blacklist takes precedence
NSArray *eb = dictionary[kREventBlacklist];
NSArray *ew = dictionary[kREventWhitelist];
if ([eb isKindOfClass:NSArray.class]) {
_eventFilterSet = [NSSet setWithArray:eb];
_eventFilterIsWhitelist = NO;
[logString appendFormat:@"%@: %@, ", kREventBlacklist, eb];
if (ew)
[dictionary removeObjectForKey:kREventWhitelist]; // blacklist takes precedence
} else if ([ew isKindOfClass:NSArray.class]) {
_eventFilterSet = [NSSet setWithArray:ew];
_eventFilterIsWhitelist = YES;
[logString appendFormat:@"%@: %@, ", kREventWhitelist, ew];
} else {
if (eb)
[dictionary removeObjectForKey:kREventBlacklist];
if (ew)
[dictionary removeObjectForKey:kREventWhitelist];
}
// User property filter (upb/upw) - blacklist takes precedence
NSArray *upb = dictionary[kRUserPropertyBlacklist];
NSArray *upw = dictionary[kRUserPropertyWhitelist];
if ([upb isKindOfClass:NSArray.class]) {
_userPropertyFilterSet = [NSSet setWithArray:upb];
_userPropertyFilterIsWhitelist = NO;
[logString appendFormat:@"%@: %@, ", kRUserPropertyBlacklist, upb];
if (upw)
[dictionary removeObjectForKey:kRUserPropertyWhitelist];
} else if ([upw isKindOfClass:NSArray.class]) {
_userPropertyFilterSet = [NSSet setWithArray:upw];
_userPropertyFilterIsWhitelist = YES;
[logString appendFormat:@"%@: %@, ", kRUserPropertyWhitelist, upw];
} else {
if (upb)
[dictionary removeObjectForKey:kRUserPropertyBlacklist];
if (upw)
[dictionary removeObjectForKey:kRUserPropertyWhitelist];
}
// Segmentation filter (sb/sw) - blacklist takes precedence
NSArray *sb = dictionary[kRSegmentationBlacklist];
NSArray *sw = dictionary[kRSegmentationWhitelist];
if ([sb isKindOfClass:NSArray.class]) {
_segmentationFilterSet = [NSSet setWithArray:sb];
_segmentationFilterIsWhitelist = NO;
[logString appendFormat:@"%@: %@, ", kRSegmentationBlacklist, sb];
if (sw)
[dictionary removeObjectForKey:kRSegmentationWhitelist];
} else if ([sw isKindOfClass:NSArray.class]) {
_segmentationFilterSet = [NSSet setWithArray:sw];
_segmentationFilterIsWhitelist = YES;
[logString appendFormat:@"%@: %@, ", kRSegmentationWhitelist, sw];
} else {
if (sb)
[dictionary removeObjectForKey:kRSegmentationBlacklist];
if (sw)
[dictionary removeObjectForKey:kRSegmentationWhitelist];
}
// Event segmentation filter (esb/esw) - blacklist takes precedence
NSDictionary *esb = dictionary[kREventSegmentationBlacklist];
NSDictionary *esw = dictionary[kREventSegmentationWhitelist];
if ([esb isKindOfClass:NSDictionary.class]) {
NSMutableDictionary *map = NSMutableDictionary.new;
[esb enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray *obj, BOOL *stop) {
if ([obj isKindOfClass:NSArray.class]) {
map[key] = [NSSet setWithArray:obj];
}
}];
_eventSegmentationFilterMap = map.copy;
_eventSegmentationFilterIsWhitelist = NO;
[logString appendFormat:@"%@: %@, ", kREventSegmentationBlacklist, esb];
if (esw)
[dictionary removeObjectForKey:kREventSegmentationWhitelist];
} else if ([esw isKindOfClass:NSDictionary.class]) {
NSMutableDictionary *map = NSMutableDictionary.new;
[esw enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray *obj, BOOL *stop) {
if ([obj isKindOfClass:NSArray.class]) {
map[key] = [NSSet setWithArray:obj];
}
}];
_eventSegmentationFilterMap = map.copy;
_eventSegmentationFilterIsWhitelist = YES;
[logString appendFormat:@"%@: %@, ", kREventSegmentationWhitelist, esw];
} else {
if (esb)
[dictionary removeObjectForKey:kREventSegmentationBlacklist];
if (esw)
[dictionary removeObjectForKey:kREventSegmentationWhitelist];
}
// Journey trigger events (jte)
NSArray *jte = dictionary[kRJourneyTriggerEvents];
if ([jte isKindOfClass:NSArray.class]) {
_journeyTriggerEvents = [NSSet setWithArray:jte];
[logString appendFormat:@"%@: %@, ", kRJourneyTriggerEvents, jte];
} else {
if (jte)
[dictionary removeObjectForKey:kRJourneyTriggerEvents];
}
}
- (BOOL)shouldRecordEvent:(NSString *)eventKey
{
if (_eventFilterSet.count == 0) return YES;
return _eventFilterIsWhitelist == [_eventFilterSet containsObject:eventKey];
}
- (BOOL)shouldRecordUserProperty:(NSString *)propertyKey
{
if (_userPropertyFilterSet.count == 0) return YES;
return _userPropertyFilterIsWhitelist == [_userPropertyFilterSet containsObject:propertyKey];
}
- (NSDictionary *)filterSegmentation:(NSDictionary *)segmentation eventKey:(NSString *)eventKey
{
if (!segmentation) {
return segmentation;