-
Notifications
You must be signed in to change notification settings - Fork 244
/
CountlyConnectionManager.m
1093 lines (847 loc) · 36.5 KB
/
CountlyConnectionManager.m
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
// CountlyConnectionManager.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyCommon.h"
@interface CountlyConnectionManager ()
{
NSTimeInterval unsentSessionLength;
NSTimeInterval lastSessionStartTime;
BOOL isCrashing;
BOOL isSessionStarted;
}
@property (nonatomic) NSURLSession* URLSession;
@property (nonatomic, strong) NSDate *startTime;
@end
NSString* const kCountlyQSKeyAppKey = @"app_key";
NSString* const kCountlyQSKeyDeviceID = @"device_id";
NSString* const kCountlyQSKeyDeviceIDOld = @"old_device_id";
NSString* const kCountlyQSKeyDeviceIDType = @"t";
NSString* const kCountlyQSKeyTimestamp = @"timestamp";
NSString* const kCountlyQSKeyTimeZone = @"tz";
NSString* const kCountlyQSKeyTimeHourOfDay = @"hour";
NSString* const kCountlyQSKeyTimeDayOfWeek = @"dow";
NSString* const kCountlyQSKeySDKVersion = @"sdk_version";
NSString* const kCountlyQSKeySDKName = @"sdk_name";
NSString* const kCountlyQSKeySessionBegin = @"begin_session";
NSString* const kCountlyQSKeySessionDuration = @"session_duration";
NSString* const kCountlyQSKeySessionEnd = @"end_session";
NSString* const kCountlyQSKeyPushTokenSession = @"token_session";
NSString* const kCountlyQSKeyPushTokeniOS = @"ios_token";
NSString* const kCountlyQSKeyPushTestMode = @"test_mode";
NSString* const kCountlyQSKeyLocation = @"location";
NSString* const kCountlyQSKeyLocationCity = @"city";
NSString* const kCountlyQSKeyLocationCountry = @"country_code";
NSString* const kCountlyQSKeyLocationIP = @"ip_address";
NSString* const kCountlyQSKeyAttributionID = @"aid";
NSString* const kCountlyQSKeyIDFA = @"idfa";
NSString* const kCountlyQSKeyADID = @"adid";
NSString* const kCountlyQSKeyCampaignID = @"campaign_id";
NSString* const kCountlyQSKeyCampaignUser = @"campaign_user";
NSString* const kCountlyQSKeyAttributionData = @"attribution_data";
NSString* const kCountlyQSKeyMetrics = @"metrics";
NSString* const kCountlyQSKeyEvents = @"events";
NSString* const kCountlyQSKeyUserDetails = @"user_details";
NSString* const kCountlyQSKeyCrash = @"crash";
NSString* const kCountlyQSKeyChecksum256 = @"checksum256";
NSString* const kCountlyQSKeyConsent = @"consent";
NSString* const kCountlyQSKeyAPM = @"apm";
NSString* const kCountlyQSKeyRemainingRequest = @"rr";
NSString* const kCountlyQSKeyMethod = @"method";
NSString* const kCountlyRCKeyABOptIn = @"ab";
NSString* const kCountlyRCKeyABOptOut = @"ab_opt_out";
NSString* const kCountlyEndPointOverrideTag = @"&new_end_point=";
NSString* const kCountlyNewEndPoint = @"new_end_point";
CLYAttributionKey const CLYAttributionKeyIDFA = kCountlyQSKeyIDFA;
CLYAttributionKey const CLYAttributionKeyADID = kCountlyQSKeyADID;
NSString* const kCountlyUploadBoundary = @"0cae04a8b698d63ff6ea55d168993f21";
NSString* const kCountlyEndpointI = @"/i"; //NOTE: input endpoint
NSString* const kCountlyEndpointO = @"/o"; //NOTE: output endpoint
NSString* const kCountlyEndpointSDK = @"/sdk";
NSString* const kCountlyEndpointFeedback = @"/feedback";
NSString* const kCountlyEndpointWidget = @"/widget";
NSString* const kCountlyEndpointSurveys = @"/surveys";
const NSInteger kCountlyGETRequestMaxLength = 2048;
@implementation CountlyConnectionManager : NSObject
static CountlyConnectionManager *s_sharedInstance = nil;
static dispatch_once_t onceToken;
+ (instancetype)sharedInstance
{
if (!CountlyCommon.sharedInstance.hasStarted)
return nil;
dispatch_once(&onceToken, ^{s_sharedInstance = self.new;});
return s_sharedInstance;
}
- (instancetype)init
{
if (self = [super init])
{
unsentSessionLength = 0.0;
isSessionStarted = NO;
}
return self;
}
- (BOOL)isSessionStarted {
return isSessionStarted;
}
- (void)resetInstance {
CLY_LOG_I(@"%s", __FUNCTION__);
onceToken = 0;
s_sharedInstance = nil;
isSessionStarted = NO;
}
- (void)setHost:(NSString *)host
{
if ([host hasSuffix:@"/"])
{
CLY_LOG_W(@"Host has an extra \"/\" at the end! It will be removed by the SDK.\
But please make sure you fix it to avoid this warning in the future.");
_host = [host substringToIndex:host.length - 1];
}
else
{
_host = host;
}
}
- (void)setURLSessionConfiguration:(NSURLSessionConfiguration *)URLSessionConfiguration
{
if (URLSessionConfiguration != nil)
{
_URLSessionConfiguration = URLSessionConfiguration;
_URLSession = nil;
}
}
- (void)proceedOnQueue
{
CLY_LOG_D(@"Proceeding on queue...");
if (!CountlyServerConfig.sharedInstance.networkingEnabled)
{
CLY_LOG_D(@"Proceeding on queue is aborted: SDK Networking is disabled from server config!");
return;
}
if (self.connection)
{
CLY_LOG_D(@"Proceeding on queue is aborted: Already has a request in process!");
return;
}
if (isCrashing)
{
CLY_LOG_D(@"Proceeding on queue is aborted: Application is crashing!");
return;
}
if (self.isTerminating)
{
CLY_LOG_D(@"Proceeding on queue is aborted: Application is terminating!");
return;
}
if (CountlyPersistency.sharedInstance.isQueueBeingModified)
{
CLY_LOG_D(@"Proceeding on queue is aborted: Queue is being modified!");
return;
}
if (!self.startTime) {
self.startTime = [NSDate date]; // Record start time only when it's not already recorded
CLY_LOG_D(@"Proceeding on queue started, queued request count %lu", [CountlyPersistency.sharedInstance remainingRequestCount]);
}
NSString* firstItemInQueue = [CountlyPersistency.sharedInstance firstItemInQueue];
if (!firstItemInQueue)
{
// Calculate total time when the queue becomes empty
NSTimeInterval elapsedTime = -[self.startTime timeIntervalSinceNow];
CLY_LOG_D(@"Queue is empty. All requests are processed. Total time taken: %.2f seconds", elapsedTime);
// Reset start time for future queue processing
self.startTime = nil;
return;
}
BOOL isOldRequest = [CountlyPersistency.sharedInstance isOldRequest:firstItemInQueue];
if(isOldRequest)
{
[CountlyPersistency.sharedInstance removeFromQueue:firstItemInQueue];
[CountlyPersistency.sharedInstance saveToFile];
[self proceedOnQueue];
return;
}
NSString* temporaryDeviceIDQueryString = [NSString stringWithFormat:@"&%@=%@", kCountlyQSKeyDeviceID, CLYTemporaryDeviceID];
if ([firstItemInQueue containsString:temporaryDeviceIDQueryString])
{
CLY_LOG_D(@"Proceeding on queue is aborted: Device ID in request is CLYTemporaryDeviceID!");
return;
}
NSString* queryString = firstItemInQueue;
NSString* endPoint = kCountlyEndpointI;
NSString* overrideEndPoint = [self extractAndRemoveOverrideEndPoint:&queryString];
if(overrideEndPoint) {
endPoint = overrideEndPoint;
}
[CountlyCommon.sharedInstance startBackgroundTask];
queryString = [self appendRemainingRequest:queryString];
NSMutableData* pictureUploadData = [self pictureUploadDataForQueryString:queryString];
if (!pictureUploadData)
{
queryString = [self appendChecksum:queryString];
}
NSString* serverInputEndpoint = [self.host stringByAppendingString:endPoint];
NSMutableURLRequest* request;
if (pictureUploadData)
{
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverInputEndpoint]];
NSString *contentType = [@"multipart/form-data; boundary=" stringByAppendingString:kCountlyUploadBoundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSArray *query = [queryString componentsSeparatedByString:@"&"];
NSEnumerator *e = [query objectEnumerator];
NSString* kvString;
while (kvString = [e nextObject]) {
NSArray *kv = [kvString componentsSeparatedByString:@"="];
[self addMultipart:pictureUploadData andKey:[kv[0] stringByRemovingPercentEncoding] andValue:[kv[1] stringByRemovingPercentEncoding]];
}
if (self.secretSalt)
{
NSString* checksum = [[[queryString stringByRemovingPercentEncoding] stringByAppendingString:self.secretSalt] cly_SHA256];
[self addMultipart:pictureUploadData andKey:kCountlyQSKeyChecksum256 andValue:checksum];
}
NSString* boundaryEnd = [NSString stringWithFormat:@"\r\n--%@--\r\n", kCountlyUploadBoundary];
[pictureUploadData appendData:[boundaryEnd cly_dataUTF8]];
request.HTTPMethod = @"POST";
request.HTTPBody = pictureUploadData;
}
else if (queryString.length > kCountlyGETRequestMaxLength || self.alwaysUsePOST)
{
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverInputEndpoint]];
request.HTTPMethod = @"POST";
request.HTTPBody = [queryString cly_dataUTF8];
}
else
{
NSString* fullRequestURL = [serverInputEndpoint stringByAppendingFormat:@"?%@", queryString];
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullRequestURL]];
}
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
self.connection = [self.URLSession dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error)
{
self.connection = nil;
CLY_LOG_V(@"Approximate received data size for request <%p> is %ld bytes.", (id)request, (long)data.length);
if(response) {
NSInteger code = ((NSHTTPURLResponse*)response).statusCode;
CLY_LOG_V(@"%s, Response received from server with status code:[ %ld ] request:[ %@ ]", __FUNCTION__, (long)code, ((NSHTTPURLResponse*)response).URL);
}
if (!error)
{
if ([self isRequestSuccessful:response data:data])
{
CLY_LOG_D(@"Request <%p> successfully completed.", request);
[CountlyPersistency.sharedInstance removeFromQueue:firstItemInQueue];
[CountlyPersistency.sharedInstance saveToFile];
[self proceedOnQueue];
}
else
{
CLY_LOG_D(@"%s, request:[ <%p> ] failed! response:[ %@ ]", __FUNCTION__, request, [data cly_stringUTF8]);
self.startTime = nil;
}
}
else
{
CLY_LOG_D(@"%s, request:[ <%p> ] failed! error:[ %@ ]", __FUNCTION__, request, error);
#if (TARGET_OS_WATCH)
[CountlyPersistency.sharedInstance saveToFile];
#endif
self.startTime = nil;
}
}];
[self.connection resume];
[self logRequest:request];
}
- (NSString*)extractAndRemoveOverrideEndPoint:(NSString **)queryString
{
if([*queryString containsString:kCountlyNewEndPoint]) {
NSString* overrideEndPoint = [*queryString cly_valueForQueryStringKey:kCountlyNewEndPoint];
if(overrideEndPoint) {
NSString* stringToRemove = [kCountlyEndPointOverrideTag stringByAppendingString:overrideEndPoint];
*queryString = [*queryString stringByReplacingOccurrencesOfString:stringToRemove withString:@""];
return overrideEndPoint;
}
}
return nil;
}
- (void)logRequest:(NSURLRequest *)request
{
NSString* bodyAsString = @"";
NSInteger sentSize = request.URL.absoluteString.length;
if (request.HTTPBody)
{
bodyAsString = [request.HTTPBody cly_stringUTF8];
if (!bodyAsString)
bodyAsString = @"Picture uploading...";
sentSize += request.HTTPBody.length;
}
CLY_LOG_D(@"%s, request:[ <%p> ] started. [%@] %@ %@", __FUNCTION__, (id)request, request.HTTPMethod, request.URL.absoluteString, bodyAsString);
CLY_LOG_V(@"Approximate sent data size for request <%p> is %ld bytes.", (id)request, (long)sentSize);
}
#pragma mark ---
- (void)beginSession
{
if (!CountlyConsentManager.sharedInstance.consentForSessions)
return;
if (isSessionStarted) {
CLY_LOG_W(@"%s A session is already running, this 'beginSession' will be ignored", __FUNCTION__);
return;
}
#if TARGET_OS_IOS || TARGET_OS_TV
if (!CountlyCommon.sharedInstance.manualSessionHandling && [UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
CLY_LOG_W(@"%s App is in the background, 'beginSession' will be ignored", __FUNCTION__);
return;
}
#elif TARGET_OS_OSX
if (!CountlyCommon.sharedInstance.manualSessionHandling && ![NSApplication sharedApplication].isActive) {
CLY_LOG_W(@"%s App is not active, 'beginSession' will be ignored", __FUNCTION__);
return;
}
#elif TARGET_OS_WATCH
if (!CountlyCommon.sharedInstance.manualSessionHandling && [WKExtension sharedExtension].applicationState == WKApplicationStateBackground) {
CLY_LOG_W(@"%s App is in the background, 'beginSession' will be ignored", __FUNCTION__);
return;
}
#endif
isSessionStarted = YES;
lastSessionStartTime = NSDate.date.timeIntervalSince1970;
unsentSessionLength = 0.0;
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@&%@=%@",
kCountlyQSKeySessionBegin, @"1",
kCountlyQSKeyMetrics, [CountlyDeviceInfo metrics]];
NSString* locationRelatedInfoQueryString = [self locationRelatedInfoQueryString];
if (locationRelatedInfoQueryString)
queryString = [queryString stringByAppendingString:locationRelatedInfoQueryString];
NSString* attributionQueryString = [self attributionQueryString];
if (attributionQueryString)
queryString = [queryString stringByAppendingString:attributionQueryString];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[CountlyCommon.sharedInstance recordOrientation];
[self proceedOnQueue];
}
- (void)updateSession
{
if (!CountlyConsentManager.sharedInstance.consentForSessions)
return;
if (!isSessionStarted) {
CLY_LOG_W(@"%s No session is running, this 'updateSession' will be ignored", __FUNCTION__);
return;
}
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%d",
kCountlyQSKeySessionDuration, (int)[self sessionLengthInSeconds]];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
- (void)endSession
{
if (!CountlyConsentManager.sharedInstance.consentForSessions)
return;
if (!isSessionStarted) {
CLY_LOG_W(@"%s No session is running, this 'endSession' will be ignored", __FUNCTION__);
return;
}
isSessionStarted = NO;
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@&%@=%d",
kCountlyQSKeySessionEnd, @"1",
kCountlyQSKeySessionDuration, (int)[self sessionLengthInSeconds]];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
[CountlyViewTrackingInternal.sharedInstance resetFirstView];
}
#pragma mark ---
- (void)sendEventsWithSaveIfNeeded
{
if([Countly.user hasUnsyncedChanges])
{
[Countly.user save];
}
else
{
[self sendEventsInternal];
}
}
- (void)sendEvents
{
[self sendEventsInternal];
}
- (void)attemptToSendStoredRequests
{
[self addEventsToQueue];
[CountlyPersistency.sharedInstance saveToFileSync];
[self proceedOnQueue];
}
- (void)sendEventsInternal
{
[self addEventsToQueue];
[self proceedOnQueue];
}
- (void)addEventsToQueue
{
NSString* events = [CountlyPersistency.sharedInstance serializedRecordedEvents];
if (!events)
return;
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@",
kCountlyQSKeyEvents, events];
[CountlyPersistency.sharedInstance addToQueue:queryString];
}
#pragma mark ---
- (void)sendPushToken:(NSString *)token
{
#ifndef COUNTLY_EXCLUDE_PUSHNOTIFICATIONS
NSInteger testMode = 0; //NOTE: default is 0: Production - not test mode
if ([CountlyPushNotifications.sharedInstance.pushTestMode isEqualToString:CLYPushTestModeDevelopment])
testMode = 1; //NOTE: 1: Developement/Debug builds - standard test mode using Sandbox APNs
else if ([CountlyPushNotifications.sharedInstance.pushTestMode isEqualToString:CLYPushTestModeTestFlightOrAdHoc])
testMode = 2; //NOTE: 2: TestFlight/AdHoc builds - special test mode using Production APNs
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@&%@=%@&%@=%ld",
kCountlyQSKeyPushTokenSession, @"1",
kCountlyQSKeyPushTokeniOS, token,
kCountlyQSKeyPushTestMode, (long)testMode];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
#endif
}
- (void)sendLocationInfo
{
NSString* locationRelatedInfoQueryString = [self locationRelatedInfoQueryString];
if (!locationRelatedInfoQueryString)
return;
NSString* queryString = [[self queryEssentials] stringByAppendingString:locationRelatedInfoQueryString];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
- (void)sendUserDetails:(NSString *)userDetails
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@",
kCountlyQSKeyUserDetails, userDetails];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
- (void)sendCrashReport:(NSString *)report immediately:(BOOL)immediately;
{
if (!CountlyServerConfig.sharedInstance.networkingEnabled)
{
CLY_LOG_D(@"'sendCrashReport' is aborted: SDK Networking is disabled from server config!");
return;
}
if (!report)
{
CLY_LOG_W(@"Crash report is nil. Converting to JSON may have failed due to custom objects in initial config's crashSegmentation property.");
return;
}
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@",
kCountlyQSKeyCrash, report];
if (!immediately)
{
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
return;
}
//NOTE: Prevent `event` and `end_session` requests from being started, after `sendEvents` and `endSession` calls below.
isCrashing = YES;
[self sendEventsWithSaveIfNeeded];
if (!CountlyCommon.sharedInstance.manualSessionHandling)
[self endSession];
if (CountlyDeviceInfo.sharedInstance.isDeviceIDTemporary)
{
CLY_LOG_D(@"Device ID is set as CLYTemporaryDeviceID! Crash report stored to be sent later!");
[CountlyPersistency.sharedInstance addToQueue:queryString];
[CountlyPersistency.sharedInstance saveToFileSync];
return;
}
[CountlyPersistency.sharedInstance saveToFileSync];
queryString = [queryString stringByAppendingFormat:@"&%@=%@",
kCountlyAppVersionKey, CountlyDeviceInfo.appVersion];
NSString* serverInputEndpoint = [self.host stringByAppendingString:kCountlyEndpointI];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverInputEndpoint]];
request.HTTPMethod = @"POST";
request.HTTPBody = [[self appendChecksum:queryString] cly_dataUTF8];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[[self.URLSession dataTaskWithRequest:request completionHandler:^(NSData* data, NSURLResponse* response, NSError* error)
{
if (error || ![self isRequestSuccessful:response data:data])
{
CLY_LOG_D(@"%s, request: [ %p ] failed! %@: %@", __FUNCTION__, request, error ? @"Error" : @"Server reply", error ?: [data cly_stringUTF8]);
[CountlyPersistency.sharedInstance addToQueue:queryString];
[CountlyPersistency.sharedInstance saveToFileSync];
}
else
{
CLY_LOG_D(@"Request <%p> successfully completed.", request);
}
dispatch_semaphore_signal(semaphore);
}] resume];
[self logRequest:request];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
- (void)sendOldDeviceID:(NSString *)oldDeviceID
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@",
kCountlyQSKeyDeviceIDOld, oldDeviceID.cly_URLEscaped];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
- (void)sendAttribution
{
NSString * attributionQueryString = [self attributionQueryString];
if (!attributionQueryString)
return;
NSString* queryString = [[self queryEssentials] stringByAppendingString:attributionQueryString];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
- (void)sendDirectAttributionWithCampaignID:(NSString *)campaignID andCampaignUserID:(NSString *)campaignUserID
{
NSMutableString* queryString = [self queryEssentials].mutableCopy;
[queryString appendFormat:@"&%@=%@", kCountlyQSKeyCampaignID, campaignID];
if (campaignUserID.length)
{
[queryString appendFormat:@"&%@=%@", kCountlyQSKeyCampaignUser, campaignUserID];
}
[CountlyPersistency.sharedInstance addToQueue:queryString.copy];
[self proceedOnQueue];
}
- (void)sendAttributionData:(NSString *)attributionData
{
NSMutableString* queryString = [self queryEssentials].mutableCopy;
[queryString appendFormat:@"&%@=%@", kCountlyQSKeyAttributionData, [attributionData cly_URLEscaped]];
[CountlyPersistency.sharedInstance addToQueue:queryString.copy];
[self proceedOnQueue];
}
- (void)sendIndirectAttribution:(NSDictionary *)attribution
{
NSMutableString* queryString = [self queryEssentials].mutableCopy;
[queryString appendFormat:@"&%@=%@", kCountlyQSKeyAttributionID, [attribution cly_JSONify]];
[CountlyPersistency.sharedInstance addToQueue:queryString.copy];
[self proceedOnQueue];
}
- (void)sendConsents:(NSString *)consents
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@",
kCountlyQSKeyConsent, consents];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
- (void)sendPerformanceMonitoringTrace:(NSString *)trace
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@",
kCountlyQSKeyAPM, trace];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
#pragma mark ---
- (void)sendEnrollABRequestForKeys:(NSArray*)keys
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@", kCountlyQSKeyMethod, kCountlyRCKeyABOptIn];
if (keys)
{
queryString = [queryString stringByAppendingFormat:@"&%@=%@", kCountlyRCKeyKeys, [keys cly_JSONify]];
}
queryString = [queryString stringByAppendingFormat:@"%@%@%@", kCountlyEndPointOverrideTag, kCountlyEndpointO, kCountlyEndpointSDK];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
- (void)sendExitABRequestForKeys:(NSArray*)keys
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&%@=%@", kCountlyQSKeyMethod, kCountlyRCKeyABOptOut];
if (keys)
{
queryString = [queryString stringByAppendingFormat:@"&%@=%@", kCountlyRCKeyKeys, [keys cly_JSONify]];
}
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self proceedOnQueue];
}
#pragma mark ---
- (void)addDirectRequest:(NSDictionary<NSString *, NSString *> *)requestParameters
{
if (!CountlyConsentManager.sharedInstance.hasAnyConsent)
return;
NSMutableDictionary* mutableRequestParameters = requestParameters.mutableCopy;
for (NSString * reservedKey in self.reservedQueryStringKeys)
{
if (mutableRequestParameters[reservedKey])
{
CLY_LOG_W(@"A reserved query string key detected in direct request parameters and it will be removed: %@", reservedKey);
[mutableRequestParameters removeObjectForKey:reservedKey];
}
}
mutableRequestParameters[@"dr"] = [NSNumber numberWithInt:1];
NSMutableString* queryString = [self queryEssentials].mutableCopy;
[mutableRequestParameters enumerateKeysAndObjectsUsingBlock:^(NSString * key, NSString * value, BOOL * stop)
{
[queryString appendFormat:@"&%@=%@", key, value];
}];
[CountlyPersistency.sharedInstance addToQueue:queryString.copy];
[self proceedOnQueue];
}
#pragma mark ---
- (NSString *)queryEssentials
{
return [NSString stringWithFormat:@"%@=%@&%@=%@&%@=%d&%@=%lld&%@=%d&%@=%d&%@=%d&%@=%@&%@=%@",
kCountlyQSKeyAppKey, self.appKey.cly_URLEscaped,
kCountlyQSKeyDeviceID, CountlyDeviceInfo.sharedInstance.deviceID.cly_URLEscaped,
kCountlyQSKeyDeviceIDType, (int)CountlyDeviceInfo.sharedInstance.deviceIDTypeValue,
kCountlyQSKeyTimestamp, (long long)(CountlyCommon.sharedInstance.uniqueTimestamp * 1000),
kCountlyQSKeyTimeHourOfDay, (int)CountlyCommon.sharedInstance.hourOfDay,
kCountlyQSKeyTimeDayOfWeek, (int)CountlyCommon.sharedInstance.dayOfWeek,
kCountlyQSKeyTimeZone, (int)CountlyCommon.sharedInstance.timeZone,
kCountlyQSKeySDKVersion, CountlyCommon.sharedInstance.SDKVersion,
kCountlyQSKeySDKName, CountlyCommon.sharedInstance.SDKName];
}
- (NSArray *)reservedQueryStringKeys
{
return
@[
kCountlyQSKeyAppKey,
kCountlyQSKeyDeviceID,
kCountlyQSKeyDeviceIDType,
kCountlyQSKeyTimestamp,
kCountlyQSKeyTimeHourOfDay,
kCountlyQSKeyTimeDayOfWeek,
kCountlyQSKeyTimeZone,
kCountlyQSKeySDKVersion,
kCountlyQSKeySDKName,
kCountlyQSKeyDeviceID,
kCountlyQSKeyDeviceIDOld,
kCountlyQSKeyChecksum256,
];
}
- (NSString *)locationRelatedInfoQueryString
{
if (!CountlyConsentManager.sharedInstance.consentForLocation || CountlyLocationManager.sharedInstance.isLocationInfoDisabled)
{
//NOTE: Return empty string for location. This is a server requirement to disable IP based location inferring.
return [NSString stringWithFormat:@"&%@=%@", kCountlyQSKeyLocation, @""];
}
NSString* location = CountlyLocationManager.sharedInstance.location.cly_URLEscaped;
NSString* city = CountlyLocationManager.sharedInstance.city.cly_URLEscaped;
NSString* ISOCountryCode = CountlyLocationManager.sharedInstance.ISOCountryCode.cly_URLEscaped;
NSString* IP = CountlyLocationManager.sharedInstance.IP.cly_URLEscaped;
NSMutableString* locationInfoQueryString = NSMutableString.new;
if (location)
[locationInfoQueryString appendFormat:@"&%@=%@", kCountlyQSKeyLocation, location];
if (city)
[locationInfoQueryString appendFormat:@"&%@=%@", kCountlyQSKeyLocationCity, city];
if (ISOCountryCode)
[locationInfoQueryString appendFormat:@"&%@=%@", kCountlyQSKeyLocationCountry, ISOCountryCode];
if (IP)
[locationInfoQueryString appendFormat:@"&%@=%@", kCountlyQSKeyLocationIP, IP];
if (locationInfoQueryString.length)
return locationInfoQueryString.copy;
return nil;
}
- (NSString *)attributionQueryString
{
if (!CountlyConsentManager.sharedInstance.consentForAttribution)
return nil;
if (!CountlyCommon.sharedInstance.attributionID)
return nil;
NSDictionary* attribution = @{kCountlyQSKeyIDFA: CountlyCommon.sharedInstance.attributionID};
return [NSString stringWithFormat:@"&%@=%@", kCountlyQSKeyAttributionID, [attribution cly_JSONify]];
}
- (NSMutableData *)pictureUploadDataForQueryString:(NSString *)queryString
{
#if (TARGET_OS_IOS || TARGET_OS_VISION)
NSString* localPicturePath = nil;
NSString* userDetails = [queryString cly_valueForQueryStringKey:kCountlyQSKeyUserDetails];
NSString* unescapedUserDetails = [userDetails stringByRemovingPercentEncoding];
if (!unescapedUserDetails)
return nil;
NSDictionary* pathDictionary = [NSJSONSerialization JSONObjectWithData:[unescapedUserDetails cly_dataUTF8] options:0 error:nil];
localPicturePath = pathDictionary[kCountlyLocalPicturePath];
if (!localPicturePath.length)
return nil;
CLY_LOG_D(@"Local picture path successfully extracted from query string: %@", localPicturePath);
NSArray* allowedFileTypes = @[@"gif", @"png", @"jpg", @"jpeg"];
NSString* fileExt = localPicturePath.pathExtension.lowercaseString;
NSInteger fileExtIndex = [allowedFileTypes indexOfObject:fileExt];
if (fileExtIndex == NSNotFound)
{
CLY_LOG_W(@"Unsupported file extension for picture upload: %@", fileExt);
return nil;
}
NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:localPicturePath]];
if (!imageData)
{
CLY_LOG_W(@"Local picture data can not be read!");
return nil;
}
CLY_LOG_D(@"Local picture data read successfully.");
//NOTE: Overcome failing PNG file upload if data is directly read from disk
if (fileExtIndex == 1)
imageData = UIImagePNGRepresentation([UIImage imageWithData:imageData]);
//NOTE: Remap content type from jpg to jpeg
if (fileExtIndex == 2)
fileExtIndex = 3;
NSString* boundaryStart = [NSString stringWithFormat:@"--%@\r\n", kCountlyUploadBoundary];
NSString* contentDisposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"pictureFile\"; filename=\"%@\"\r\n", localPicturePath.lastPathComponent];
NSString* contentType = [NSString stringWithFormat:@"Content-Type: image/%@\r\n\r\n", allowedFileTypes[fileExtIndex]];
NSMutableData* uploadData = NSMutableData.new;
[uploadData appendData:[boundaryStart cly_dataUTF8]];
[uploadData appendData:[contentDisposition cly_dataUTF8]];
[uploadData appendData:[contentType cly_dataUTF8]];
[uploadData appendData:imageData];
return uploadData;
#endif
return nil;
}
- (void)addMultipart:(NSMutableData *)uploadData andKey:(NSString *)key andValue:(NSString *)value
{
NSString* boundaryStart = [NSString stringWithFormat:@"\r\n--%@\r\n", kCountlyUploadBoundary];
NSString* contentDisposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\n\r\n", key];
[uploadData appendData:[boundaryStart cly_dataUTF8]];
[uploadData appendData:[contentDisposition cly_dataUTF8]];
[uploadData appendData:[value cly_dataUTF8]];
}
- (NSString *)appendChecksum:(NSString *)queryString
{
if (self.secretSalt)
{
NSString* checksum = [[queryString stringByAppendingString:self.secretSalt] cly_SHA256];
return [queryString stringByAppendingFormat:@"&%@=%@", kCountlyQSKeyChecksum256, checksum];
}
return queryString;
}
- (NSString *)appendRemainingRequest:(NSString *)queryString
{
NSUInteger rrCount = [CountlyPersistency.sharedInstance remainingRequestCount] - 1;
return [queryString stringByAppendingFormat:@"&%@=%lu", kCountlyQSKeyRemainingRequest, (unsigned long)rrCount];
return queryString;
}
- (BOOL)isRequestSuccessful:(NSURLResponse *)response data:(NSData *)data
{
if (!response)
return NO;
NSInteger code = ((NSHTTPURLResponse*)response).statusCode;
if (code >= 200 && code < 300)
{
NSError* error = nil;
NSDictionary* serverReply = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error)
{
CLY_LOG_W(@"Server reply is not a valid JSON!");
return NO;
}
CLY_LOG_V(@"%s, response:[ %@ ] request:[ %@ ]", __FUNCTION__, serverReply, ((NSHTTPURLResponse*)response).URL);
NSString* result = serverReply[@"result"];
if(result)
{
return YES;
}
return NO;
}
else
{
CLY_LOG_V(@"HTTP status code is not 2XX series.");
return NO;
}
}
- (NSInteger)sessionLengthInSeconds
{
NSTimeInterval currentTime = NSDate.date.timeIntervalSince1970;
unsentSessionLength += (currentTime - lastSessionStartTime);
lastSessionStartTime = currentTime;
int sessionLengthInSeconds = (int)unsentSessionLength;
unsentSessionLength -= sessionLengthInSeconds;
return sessionLengthInSeconds;
}
#pragma mark ---
- (NSURLSession *)URLSession
{
if (!_URLSession)
{
if (self.pinnedCertificates)
{
CLY_LOG_D(@"%d pinned certificate(s) specified in config.", (int)self.pinnedCertificates.count);
_URLSession = [NSURLSession sessionWithConfiguration:self.URLSessionConfiguration delegate:self delegateQueue:nil];
}
else
{
_URLSession = [NSURLSession sessionWithConfiguration:self.URLSessionConfiguration];
}
}
return _URLSession;
}
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
SecPolicyRef policy = SecPolicyCreateSSL(true, (__bridge CFStringRef)challenge.protectionSpace.host);
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecKeyRef serverKey = NULL;
if (@available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *))
{