forked from adjust/ios_sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADJUtil.m
1584 lines (1433 loc) · 62.8 KB
/
ADJUtil.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
//
// ADJUtil.m
// Adjust SDK
//
// Created by Christian Wellenbrock (@wellle) on 5th July 2013.
// Copyright (c) 2013-2021 Adjust GmbH. All rights reserved.
//
#include <math.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <sys/xattr.h>
#import <objc/message.h>
#import <sys/utsname.h>
#import <sys/types.h>
#import <sys/sysctl.h>
#import <UIKit/UIKit.h>
#import "ADJUtil.h"
#import "ADJLogger.h"
#import "ADJResponseData.h"
#import "ADJAdjustFactory.h"
#import "NSString+ADJAdditions.h"
#if !ADJUST_NO_IDFA
#import <AdSupport/ASIdentifierManager.h>
#endif
#if !ADJUST_NO_IAD && !TARGET_OS_TV
#import <iAd/iAd.h>
#endif
static NSString *userAgent = nil;
static NSRegularExpression *universalLinkRegex = nil;
static NSNumberFormatter *secondsNumberFormatter = nil;
static NSRegularExpression *optionalRedirectRegex = nil;
static NSRegularExpression *shortUniversalLinkRegex = nil;
static NSRegularExpression *excludedDeeplinkRegex = nil;
static NSString * const kClientSdk = @"ios4.29.6";
static NSString * const kDeeplinkParam = @"deep_link=";
static NSString * const kSchemeDelimiter = @"://";
static NSString * const kDefaultScheme = @"AdjustUniversalScheme";
static NSString * const kUniversalLinkPattern = @"https://[^.]*\\.ulink\\.adjust\\.com/ulink/?(.*)";
static NSString * const kOptionalRedirectPattern = @"adjust_redirect=[^&#]*";
static NSString * const kShortUniversalLinkPattern = @"http[s]?://[a-z0-9]{4}\\.adj\\.st/?(.*)";
static NSString * const kExcludedDeeplinksPattern = @"^(fb|vk)[0-9]{5,}[^:]*://authorize.*access_token=.*";
static NSString * const kDateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'Z";
@implementation ADJUtil
+ (void)initialize {
if (self != [ADJUtil class]) {
return;
}
[self initializeUniversalLinkRegex];
[self initializeSecondsNumberFormatter];
[self initializeShortUniversalLinkRegex];
[self initializeOptionalRedirectRegex];
[self initializeExcludedDeeplinkRegex];
}
+ (void)teardown {
universalLinkRegex = nil;
secondsNumberFormatter = nil;
optionalRedirectRegex = nil;
shortUniversalLinkRegex = nil;
}
+ (void)initializeUniversalLinkRegex {
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kUniversalLinkPattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if ([ADJUtil isNotNull:error]) {
[ADJAdjustFactory.logger error:@"Universal link regex rule error (%@)", [error description]];
return;
}
universalLinkRegex = regex;
}
+ (void)initializeShortUniversalLinkRegex {
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kShortUniversalLinkPattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if ([ADJUtil isNotNull:error]) {
[ADJAdjustFactory.logger error:@"Short Universal link regex rule error (%@)", [error description]];
return;
}
shortUniversalLinkRegex = regex;
}
+ (void)initializeOptionalRedirectRegex {
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kOptionalRedirectPattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if ([ADJUtil isNotNull:error]) {
[ADJAdjustFactory.logger error:@"Optional redirect regex rule error (%@)", [error description]];
return;
}
optionalRedirectRegex = regex;
}
+ (void)initializeExcludedDeeplinkRegex {
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kExcludedDeeplinksPattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if ([ADJUtil isNotNull:error]) {
[ADJAdjustFactory.logger error:@"Excluded deep link regex rule error (%@)", [error description]];
return;
}
excludedDeeplinkRegex = regex;
}
+ (void)initializeSecondsNumberFormatter {
secondsNumberFormatter = [[NSNumberFormatter alloc] init];
[secondsNumberFormatter setPositiveFormat:@"0.0"];
}
+ (void)updateUrlSessionConfiguration:(ADJConfig *)config {
userAgent = config.userAgent;
}
+ (NSString *)clientSdk {
return kClientSdk;
}
+ (NSDateFormatter *)getDateFormatter {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]];
[dateFormatter setDateFormat:kDateFormat];
Class class = NSClassFromString([NSString adjJoin:@"N", @"S", @"locale", nil]);
if (class != nil) {
NSString *keyLwli = [NSString adjJoin:@"locale", @"with", @"locale", @"identifier:", nil];
SEL selLwli = NSSelectorFromString(keyLwli);
if ([class respondsToSelector:selLwli]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id loc = [class performSelector:selLwli withObject:@"en_US"];
[dateFormatter setLocale:loc];
#pragma clang diagnostic pop
}
}
return dateFormatter;
}
// Inspired by https://gist.github.com/kevinbarrett/2002382
+ (void)excludeFromBackup:(NSString *)path {
NSURL *url = [NSURL fileURLWithPath:path];
const char* filePath = [[url path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
id<ADJLogger> logger = ADJAdjustFactory.logger;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
if (&NSURLIsExcludedFromBackupKey == nil) {
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
if (result != 0) {
[logger debug:@"Failed to exclude '%@' from backup", url.lastPathComponent];
}
} else { // iOS 5.0 and higher
// First try and remove the extended attribute if it is present
ssize_t result = getxattr(filePath, attrName, NULL, sizeof(u_int8_t), 0, 0);
if (result != -1) {
// The attribute exists, we need to remove it
int removeResult = removexattr(filePath, attrName, 0);
if (removeResult == 0) {
[logger debug:@"Removed extended attribute on file '%@'", url];
}
}
// Set the new key
NSError *error = nil;
BOOL success = [url setResourceValue:[NSNumber numberWithBool:YES]
forKey:NSURLIsExcludedFromBackupKey
error:&error];
if (!success || error != nil) {
[logger debug:@"Failed to exclude '%@' from backup (%@)", url.lastPathComponent, error.localizedDescription];
}
}
#pragma clang diagnostic pop
}
+ (NSString *)formatSeconds1970:(double)value {
NSDate *date = [NSDate dateWithTimeIntervalSince1970:value];
return [self formatDate:date];
}
+ (NSString *)formatDate:(NSDate *)value {
NSDateFormatter *dateFormatter = [ADJUtil getDateFormatter];
if (dateFormatter == nil) {
return nil;
}
return [dateFormatter stringFromDate:value];
}
+ (id)readObject:(NSString *)fileName
objectName:(NSString *)objectName
class:(Class)classToRead
syncObject:(id)syncObject {
#if TARGET_OS_TV
return nil;
#endif
@synchronized(syncObject) {
NSString *documentsFilePath = [ADJUtil getFilePathInDocumentsDir:fileName];
NSString *appSupportFilePath = [ADJUtil getFilePathInAppSupportDir:fileName];
// Try to read from Application Support directory first.
@try {
id appSupportObject;
if (@available(iOS 11.0, tvOS 11.0, *)) {
NSData *data = [NSData dataWithContentsOfFile:appSupportFilePath];
// API introduced in iOS 11.
NSError *errorUnarchiver = nil;
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data
error:&errorUnarchiver];
if (errorUnarchiver == nil) {
[unarchiver setRequiresSecureCoding:NO];
appSupportObject = [unarchiver decodeObjectOfClass:classToRead forKey:NSKeyedArchiveRootObjectKey];
} else {
// TODO: try to make this error fit the logging flow; if not, remove it
// [[ADJAdjustFactory logger] debug:@"Failed to read %@ with error: %@", objectName, errorUnarchiver.localizedDescription];
}
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// API_DEPRECATED [2.0-12.0]
// "Use +unarchivedObjectOfClass:fromData:error: instead"
appSupportObject = [NSKeyedUnarchiver unarchiveObjectWithFile:appSupportFilePath];
#pragma clang diagnostic pop
}
if (appSupportObject != nil) {
if ([appSupportObject isKindOfClass:classToRead]) {
// Successfully read object from Application Support folder, return it.
if ([appSupportObject isKindOfClass:[NSArray class]]) {
[[ADJAdjustFactory logger] debug:@"Package handler read %d packages", [appSupportObject count]];
} else {
[[ADJAdjustFactory logger] debug:@"Read %@: %@", objectName, appSupportObject];
}
// Just in case check if old file exists in Documents folder and if yes, remove it.
[ADJUtil deleteFileInPath:documentsFilePath];
return appSupportObject;
}
} else {
// [[ADJAdjustFactory logger] error:@"Failed to read %@ file", appSupportFilePath];
[[ADJAdjustFactory logger] debug:@"File %@ not found in \"Application Support/Adjust\" folder", fileName];
}
} @catch (NSException *ex) {
// [[ADJAdjustFactory logger] error:@"Failed to read %@ file (%@)", appSupportFilePath, ex];
[[ADJAdjustFactory logger] error:@"Failed to read %@ file from \"Application Support/Adjust\" folder (%@)", fileName, ex];
}
// If in here, for some reason, reading of file from Application Support folder failed.
// Let's check the Documents folder.
@try {
id documentsObject;
if (@available(iOS 11.0, tvOS 11.0, *)) {
NSData *data = [NSData dataWithContentsOfFile:documentsFilePath];
// API introduced in iOS 11.
NSError *errorUnarchiver = nil;
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data
error:&errorUnarchiver];
if (errorUnarchiver == nil) {
[unarchiver setRequiresSecureCoding:NO];
documentsObject = [unarchiver decodeObjectOfClass:classToRead forKey:NSKeyedArchiveRootObjectKey];
} else {
// TODO: try to make this error fit the logging flow; if not, remove it
// [[ADJAdjustFactory logger] debug:@"Failed to read %@ with error: %@", objectName, errorUnarchiver.localizedDescription];
}
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// API_DEPRECATED [2.0-12.0]
// "Use +unarchivedObjectOfClass:fromData:error: instead"
documentsObject = [NSKeyedUnarchiver unarchiveObjectWithFile:documentsFilePath];
#pragma clang diagnostic pop
}
if (documentsObject != nil) {
// Successfully read object from Documents folder.
if ([documentsObject isKindOfClass:[NSArray class]]) {
[[ADJAdjustFactory logger] debug:@"Package handler read %d packages", [documentsObject count]];
} else {
[[ADJAdjustFactory logger] debug:@"Read %@: %@", objectName, documentsObject];
}
// Do the file migration.
[[ADJAdjustFactory logger] verbose:@"Migrating %@ file from Documents to \"Application Support/Adjust\" folder", fileName];
[ADJUtil migrateFileFromPath:documentsFilePath toPath:appSupportFilePath];
return documentsObject;
} else {
// [[ADJAdjustFactory logger] error:@"Failed to read %@ file", documentsFilePath];
[[ADJAdjustFactory logger] debug:@"File %@ not found in Documents folder", fileName];
}
} @catch (NSException *ex) {
// [[ADJAdjustFactory logger] error:@"Failed to read %@ file (%@)", documentsFilePath, ex];
[[ADJAdjustFactory logger] error:@"Failed to read %@ file from Documents folder (%@)", fileName, ex];
}
return nil;
}
}
+ (void)writeObject:(id)object
fileName:(NSString *)fileName
objectName:(NSString *)objectName
syncObject:(id)syncObject {
#if TARGET_OS_TV
return;
#endif
@synchronized(syncObject) {
@try {
BOOL result;
NSString *filePath = [ADJUtil getFilePathInAppSupportDir:fileName];
if (!filePath) {
[[ADJAdjustFactory logger] error:@"Cannot get filepath from filename: %@, to write %@ file", fileName, objectName];
return;
}
if (@available(iOS 11.0, tvOS 11.0, *)) {
NSError *errorArchiving = nil;
// API introduced in iOS 11.
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object requiringSecureCoding:NO error:&errorArchiving];
if (data && errorArchiving == nil) {
NSError *errorWriting = nil;
result = [data writeToFile:filePath options:NSDataWritingAtomic error:&errorWriting];
result = result && (errorWriting == nil);
} else {
result = NO;
}
} else {
// API_DEPRECATED [2.0-12.0]
// Use +archivedDataWithRootObject:requiringSecureCoding:error: and -writeToURL:options:error: instead
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
result = [NSKeyedArchiver archiveRootObject:object toFile:filePath];
#pragma clang diagnostic pop
}
if (result == YES) {
[ADJUtil excludeFromBackup:filePath];
if ([object isKindOfClass:[NSArray class]]) {
[[ADJAdjustFactory logger] debug:@"Package handler wrote %d packages", [object count]];
} else {
[[ADJAdjustFactory logger] debug:@"Wrote %@: %@", objectName, object];
}
} else {
[[ADJAdjustFactory logger] error:@"Failed to write %@ file", objectName];
}
} @catch (NSException *exception) {
[[ADJAdjustFactory logger] error:@"Failed to write %@ file (%@)", objectName, exception];
}
}
}
+ (BOOL)migrateFileFromPath:(NSString *)oldPath toPath:(NSString *)newPath {
__autoreleasing NSError *error;
__autoreleasing NSError **errorPointer = &error;
Class class = NSClassFromString([NSString adjJoin:@"N", @"S", @"file", @"manager", nil]);
if (class == nil) {
return NO;
}
NSString *keyDm = [NSString adjJoin:@"default", @"manager", nil];
SEL selDm = NSSelectorFromString(keyDm);
if (![class respondsToSelector:selDm]) {
return NO;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id man = [class performSelector:selDm];
#pragma clang diagnostic pop
NSString *keyCpy = [NSString stringWithFormat:@"%@%@%@",
[NSString adjJoin:@"copy", @"item", @"at", @"path", @":", nil],
[NSString adjJoin:@"to", @"path", @":", nil],
[NSString adjJoin:@"error", @":", nil]];
SEL selCpy = NSSelectorFromString(keyCpy);
if (![man respondsToSelector:selCpy]) {
return NO;
}
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[man methodSignatureForSelector:selCpy]];
[inv setSelector:selCpy];
[inv setTarget:man];
[inv setArgument:&oldPath atIndex:2];
[inv setArgument:&newPath atIndex:3];
[inv setArgument:&errorPointer atIndex:4];
[inv invoke];
if (error != nil) {
[[ADJAdjustFactory logger] error:@"Error while copying from %@ to %@", oldPath, newPath];
[[ADJAdjustFactory logger] error:[error description]];
return NO;
}
// Migration successful.
return YES;
}
+ (NSString *)getFilePathInDocumentsDir:(NSString *)fileName {
// Documents directory exists by default inside app bundle, no need to check for it's presence.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *filePath = [documentsDir stringByAppendingPathComponent:fileName];
return filePath;
}
+ (NSString *)getFilePathInAppSupportDir:(NSString *)fileName {
// Application Support directory doesn't exist by default inside app bundle.
// All Adjust files are going to be stored in Adjust sub-directory inside Application Support directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *appSupportDir = [paths firstObject];
NSString *adjustDirName = @"Adjust";
if (![ADJUtil checkForDirectoryPresenceInPath:appSupportDir forFolder:[appSupportDir lastPathComponent]]) {
return nil;
}
NSString *adjustDir = [appSupportDir stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", adjustDirName]];
if (![ADJUtil checkForDirectoryPresenceInPath:adjustDir forFolder:adjustDirName]) {
return nil;
}
NSString *filePath = [adjustDir stringByAppendingPathComponent:fileName];
return filePath;
}
+ (BOOL)checkForDirectoryPresenceInPath:(NSString *)path forFolder:(NSString *)folderName {
// Check for presence of directory first.
// If it doesn't exist, make one.
Class class = NSClassFromString([NSString adjJoin:@"N", @"S", @"file", @"manager", nil]);
if (class == nil) {
return NO;
}
NSString *keyDm = [NSString adjJoin:@"default", @"manager", nil];
SEL selDm = NSSelectorFromString(keyDm);
if (![class respondsToSelector:selDm]) {
return NO;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id man = [class performSelector:selDm];
#pragma clang diagnostic pop
NSString *keyExi = [NSString adjJoin:@"file", @"exists", @"at", @"path", @":", nil];
SEL selExi = NSSelectorFromString(keyExi);
if (![man respondsToSelector:selExi]) {
return NO;
}
NSInvocation *invMan = [NSInvocation invocationWithMethodSignature:[man methodSignatureForSelector:selExi]];
[invMan setSelector:selExi];
[invMan setTarget:man];
[invMan setArgument:&path atIndex:2];
[invMan invoke];
BOOL exists;
[invMan getReturnValue:&exists];
if (!exists) {
[[ADJAdjustFactory logger] debug:@"%@ directory not present and will be created", folderName];
BOOL withIntermediateDirectories = NO;
NSDictionary *attributes = nil;
__autoreleasing NSError *error;
__autoreleasing NSError **errorPointer = &error;
NSString *keyCrt = [NSString stringWithFormat:@"%@%@%@%@",
[NSString adjJoin:@"create", @"directory", @"at", @"path", @":", nil],
[NSString adjJoin:@"with", @"intermediate", @"directories", @":", nil],
[NSString adjJoin:@"attributes", @":", nil],
[NSString adjJoin:@"error", @":", nil]];
SEL selCrt = NSSelectorFromString(keyCrt);
if (![man respondsToSelector:selCrt]) {
return NO;
}
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[man methodSignatureForSelector:selCrt]];
[inv setSelector:selCrt];
[inv setTarget:man];
[inv setArgument:&path atIndex:2];
[inv setArgument:&withIntermediateDirectories atIndex:3];
[inv setArgument:&attributes atIndex:4];
[inv setArgument:&errorPointer atIndex:5];
[inv invoke];
if (error != nil) {
[[ADJAdjustFactory logger] error:@"Error while creating %@ directory", path];
[[ADJAdjustFactory logger] error:[error description]];
return NO;
}
}
return YES;
}
+ (NSString *)queryString:(NSDictionary *)parameters {
return [ADJUtil queryString:parameters queueSize:0];
}
+ (NSString *)queryString:(NSDictionary *)parameters
queueSize:(NSUInteger)queueSize {
NSMutableArray *pairs = [NSMutableArray array];
for (NSString *key in parameters) {
NSString *value = [parameters objectForKey:key];
NSString *escapedValue = [value adjUrlEncode];
NSString *escapedKey = [key adjUrlEncode];
NSString *pair = [NSString stringWithFormat:@"%@=%@", escapedKey, escapedValue];
[pairs addObject:pair];
}
double now = [NSDate.date timeIntervalSince1970];
NSString *dateString = [ADJUtil formatSeconds1970:now];
NSString *escapedDate = [dateString adjUrlEncode];
NSString *sentAtPair = [NSString stringWithFormat:@"%@=%@", @"sent_at", escapedDate];
[pairs addObject:sentAtPair];
if (queueSize > 0) {
unsigned long queueSizeNative = (unsigned long)queueSize;
NSString *queueSizeString = [NSString stringWithFormat:@"%lu", queueSizeNative];
NSString *escapedQueueSize = [queueSizeString adjUrlEncode];
NSString *queueSizePair = [NSString stringWithFormat:@"%@=%@", @"queue_size", escapedQueueSize];
[pairs addObject:queueSizePair];
}
NSString *queryString = [pairs componentsJoinedByString:@"&"];
return queryString;
}
+ (BOOL)isNull:(id)value {
return value == nil || value == (id)[NSNull null];
}
+ (BOOL)isNotNull:(id)value {
return value != nil && value != (id)[NSNull null];
}
// Convert all values to strings, if value is dictionary -> recursive call
+ (NSDictionary *)convertDictionaryValues:(NSDictionary *)dictionary {
NSMutableDictionary *convertedDictionary = [[NSMutableDictionary alloc] initWithCapacity:dictionary.count];
for (NSString *key in dictionary) {
id value = [dictionary objectForKey:key];
if ([value isKindOfClass:[NSDictionary class]]) {
// Dictionary value, recursive call
NSDictionary *dictionaryValue = [ADJUtil convertDictionaryValues:(NSDictionary *)value];
[convertedDictionary setObject:dictionaryValue forKey:key];
} else if ([value isKindOfClass:[NSDate class]]) {
// Format date to our custom format
NSString *dateStingValue = [ADJUtil formatDate:value];
if (dateStingValue != nil) {
[convertedDictionary setObject:dateStingValue forKey:key];
}
} else {
// Convert all other objects directly to string
NSString *stringValue = [NSString stringWithFormat:@"%@", value];
[convertedDictionary setObject:stringValue forKey:key];
}
}
return convertedDictionary;
}
+ (NSURL *)convertUniversalLink:(NSURL *)url scheme:(NSString *)scheme {
id<ADJLogger> logger = ADJAdjustFactory.logger;
if ([ADJUtil isNull:url]) {
[logger error:@"Received universal link is nil"];
return nil;
}
if ([ADJUtil isNull:scheme] || [scheme length] == 0) {
[logger warn:@"Non-empty scheme required, using the scheme \"AdjustUniversalScheme\""];
scheme = kDefaultScheme;
}
NSString *urlString = [url absoluteString];
if ([ADJUtil isNull:urlString]) {
[logger error:@"Parsed universal link is nil"];
return nil;
}
if (universalLinkRegex == nil) {
[logger error:@"Universal link regex not correctly configured"];
return nil;
}
if (shortUniversalLinkRegex == nil) {
[logger error:@"Short Universal link regex not correctly configured"];
return nil;
}
NSArray<NSTextCheckingResult *> *matches = [universalLinkRegex matchesInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if ([matches count] == 0) {
matches = [shortUniversalLinkRegex matchesInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if ([matches count] == 0) {
[logger error:@"Url doesn't match as universal link or short version"];
return nil;
}
}
if ([matches count] > 1) {
[logger error:@"Url match as universal link multiple times"];
return nil;
}
NSTextCheckingResult *match = matches[0];
if ([match numberOfRanges] != 2) {
[logger error:@"Wrong number of ranges matched"];
return nil;
}
NSString *tailSubString = [urlString substringWithRange:[match rangeAtIndex:1]];
NSString *finalTailSubString = [ADJUtil removeOptionalRedirect:tailSubString];
NSString *extractedUrlString = [NSString stringWithFormat:@"%@://%@", scheme, finalTailSubString];
[logger info:@"Converted deeplink from universal link %@", extractedUrlString];
NSURL *extractedUrl = [NSURL URLWithString:extractedUrlString];
if ([ADJUtil isNull:extractedUrl]) {
[logger error:@"Unable to parse converted deeplink from universal link %@", extractedUrlString];
return nil;
}
return extractedUrl;
}
+ (NSString *)removeOptionalRedirect:(NSString *)tailSubString {
id<ADJLogger> logger = ADJAdjustFactory.logger;
if (optionalRedirectRegex == nil) {
[ADJAdjustFactory.logger error:@"Remove Optional Redirect regex not correctly configured"];
return tailSubString;
}
NSArray<NSTextCheckingResult *> *optionalRedirectmatches = [optionalRedirectRegex matchesInString:tailSubString
options:0
range:NSMakeRange(0, [tailSubString length])];
if ([optionalRedirectmatches count] == 0) {
[logger debug:@"Universal link does not contain option adjust_redirect parameter"];
return tailSubString;
}
if ([optionalRedirectmatches count] > 1) {
[logger error:@"Universal link contains multiple option adjust_redirect parameters"];
return tailSubString;
}
NSTextCheckingResult *redirectMatch = optionalRedirectmatches[0];
NSRange redirectRange = [redirectMatch rangeAtIndex:0];
NSString *beforeRedirect = [tailSubString substringToIndex:redirectRange.location];
NSString *afterRedirect = [tailSubString substringFromIndex:(redirectRange.location + redirectRange.length)];
if (beforeRedirect.length > 0 && afterRedirect.length > 0) {
NSString *lastCharacterBeforeRedirect = [beforeRedirect substringFromIndex:beforeRedirect.length - 1];
NSString *firstCharacterAfterRedirect = [afterRedirect substringToIndex:1];
if ([@"&" isEqualToString:lastCharacterBeforeRedirect] &&
[@"&" isEqualToString:firstCharacterAfterRedirect]) {
beforeRedirect = [beforeRedirect substringToIndex:beforeRedirect.length - 1];
}
if ([@"&" isEqualToString:lastCharacterBeforeRedirect] &&
[@"#" isEqualToString:firstCharacterAfterRedirect]) {
beforeRedirect = [beforeRedirect substringToIndex:beforeRedirect.length - 1];
}
if ([@"?" isEqualToString:lastCharacterBeforeRedirect] &&
[@"#" isEqualToString:firstCharacterAfterRedirect]) {
beforeRedirect = [beforeRedirect substringToIndex:beforeRedirect.length - 1];
}
if ([@"?" isEqualToString:lastCharacterBeforeRedirect] &&
[@"&" isEqualToString:firstCharacterAfterRedirect]) {
afterRedirect = [afterRedirect substringFromIndex:1];
}
}
NSString *removedRedirect = [NSString stringWithFormat:@"%@%@", beforeRedirect, afterRedirect];
return removedRedirect;
}
+ (NSString *)secondsNumberFormat:(double)seconds {
// Normalize negative zero
if (seconds < 0) {
seconds = seconds * -1;
}
if (secondsNumberFormatter == nil) {
return nil;
}
return [secondsNumberFormatter stringFromNumber:[NSNumber numberWithDouble:seconds]];
}
+ (double)randomInRange:(double)minRange maxRange:(double)maxRange {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
srand48(arc4random());
});
double random = drand48();
double range = maxRange - minRange;
double scaled = random * range;
double shifted = scaled + minRange;
return shifted;
}
+ (NSTimeInterval)waitingTime:(NSInteger)retries
backoffStrategy:(ADJBackoffStrategy *)backoffStrategy {
if (retries < backoffStrategy.minRetries) {
return 0;
}
// Start with base 0
NSInteger base = retries - backoffStrategy.minRetries;
// Get the exponential Time from the base: 1, 2, 4, 8, 16, ... * times the multiplier
NSTimeInterval exponentialTime = pow(2.0, base) * backoffStrategy.secondMultiplier;
// Limit the maximum allowed time to wait
NSTimeInterval ceilingTime = MIN(exponentialTime, backoffStrategy.maxWait);
// Add 1 to allow maximum value
double randomRange = [ADJUtil randomInRange:backoffStrategy.minRange maxRange:backoffStrategy.maxRange];
// Apply jitter factor
NSTimeInterval waitingTime = ceilingTime * randomRange;
return waitingTime;
}
+ (void)launchInMainThread:(NSObject *)receiver
selector:(SEL)selector
withObject:(id)object {
if (ADJAdjustFactory.testing) {
[ADJAdjustFactory.logger debug:@"Launching in the background for testing"];
[receiver performSelectorInBackground:selector withObject:object];
} else {
[receiver performSelectorOnMainThread:selector
withObject:object
waitUntilDone:NO]; // non-blocking
}
}
+ (void)launchInMainThread:(dispatch_block_t)block {
if (ADJAdjustFactory.testing) {
[ADJAdjustFactory.logger debug:@"Launching in the background for testing"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block);
} else {
dispatch_async(dispatch_get_main_queue(), block);
}
}
+ (BOOL)isMainThread {
return [[NSThread currentThread] isMainThread];
}
+ (BOOL)isInactive {
#if ADJUST_IM
// Assume iMessage extension app can't be started from background.
return NO;
#else
return [[UIApplication sharedApplication] applicationState] != UIApplicationStateActive;
#endif
}
+ (void)launchInMainThreadWithInactive:(isInactiveInjected)isInactiveblock {
dispatch_block_t block = ^void(void) {
__block BOOL isInactive = [ADJUtil isInactive];
isInactiveblock(isInactive);
};
if ([ADJUtil isMainThread]) {
block();
return;
}
if (ADJAdjustFactory.testing) {
[ADJAdjustFactory.logger debug:@"Launching in the background for testing"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block);
} else {
dispatch_async(dispatch_get_main_queue(), block);
}
}
+ (BOOL)isValidParameter:(NSString *)attribute
attributeType:(NSString *)attributeType
parameterName:(NSString *)parameterName {
if ([ADJUtil isNull:attribute]) {
[ADJAdjustFactory.logger error:@"%@ parameter %@ is missing", parameterName, attributeType];
return NO;
}
if ([attribute isEqualToString:@""]) {
[ADJAdjustFactory.logger error:@"%@ parameter %@ is empty", parameterName, attributeType];
return NO;
}
return YES;
}
+ (NSDictionary *)mergeParameters:(NSDictionary *)target
source:(NSDictionary *)source
parameterName:(NSString *)parameterName {
if (target == nil) {
return source;
}
if (source == nil) {
return target;
}
NSMutableDictionary *mergedParameters = [NSMutableDictionary dictionaryWithDictionary:target];
[source enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *oldValue = [mergedParameters objectForKey:key];
if (oldValue != nil) {
[ADJAdjustFactory.logger warn:@"Key %@ with value %@ from %@ parameter was replaced by value %@",
key, oldValue, parameterName, obj];
}
[mergedParameters setObject:obj forKey:key];
}];
return (NSDictionary *)mergedParameters;
}
+ (void)launchInQueue:(dispatch_queue_t)queue
selfInject:(id)selfInject
block:(selfInjectedBlock)block {
if (queue == nil) {
return;
}
__weak __typeof__(selfInject) weakSelf = selfInject;
dispatch_async(queue, ^{
__typeof__(selfInject) strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
block(strongSelf);
});
}
+ (void)launchSynchronisedWithObject:(id)synchronisationObject
block:(synchronisedBlock)block {
@synchronized (synchronisationObject) {
block();
}
}
+ (BOOL)deleteFileWithName:(NSString *)fileName {
NSString *documentsFilePath = [ADJUtil getFilePathInDocumentsDir:fileName];
NSString *appSupportFilePath = [ADJUtil getFilePathInAppSupportDir:fileName];
BOOL deletedDocumentsFilePath = [ADJUtil deleteFileInPath:documentsFilePath];
BOOL deletedAppSupportFilePath = [ADJUtil deleteFileInPath:appSupportFilePath];
return deletedDocumentsFilePath || deletedAppSupportFilePath;
}
+ (BOOL)deleteFileInPath:(NSString *)filePath {
Class class = NSClassFromString([NSString adjJoin:@"N", @"S", @"file", @"manager", nil]);
if (class == nil) {
return NO;
}
NSString *keyDm = [NSString adjJoin:@"default", @"manager", nil];
SEL selDm = NSSelectorFromString(keyDm);
if (![class respondsToSelector:selDm]) {
return NO;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id man = [class performSelector:selDm];
#pragma clang diagnostic pop
NSString *keyExi = [NSString adjJoin:@"file", @"exists", @"at", @"path", @":", nil];
SEL selExi = NSSelectorFromString(keyExi);
if (![man respondsToSelector:selExi]) {
return NO;
}
NSMethodSignature *msExi = [man methodSignatureForSelector:selExi];
NSInvocation *invExi = [NSInvocation invocationWithMethodSignature:msExi];
[invExi setSelector:selExi];
[invExi setTarget:man];
[invExi setArgument:&filePath atIndex:2];
[invExi invoke];
BOOL exists;
[invExi getReturnValue:&exists];
if (!exists) {
return YES;
}
__autoreleasing NSError *error;
__autoreleasing NSError **errorPointer = &error;
NSString *keyRm = [NSString stringWithFormat:@"%@%@",
[NSString adjJoin:@"remove", @"item", @"at", @"path", @":", nil],
[NSString adjJoin:@"error", @":", nil]];
SEL selRm = NSSelectorFromString(keyRm);
if (![man respondsToSelector:selRm]) {
return NO;
}
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[man methodSignatureForSelector:selRm]];
[inv setSelector:selRm];
[inv setTarget:man];
[inv setArgument:&filePath atIndex:2];
[inv setArgument:&errorPointer atIndex:3];
[inv invoke];
BOOL deleted;
[inv getReturnValue:&deleted];
if (!deleted) {
[[ADJAdjustFactory logger] verbose:@"Unable to delete file at path %@", filePath];
}
if (error) {
[[ADJAdjustFactory logger] error:@"Error while deleting file at path %@", filePath];
}
return deleted;
}
+ (void)launchDeepLinkMain:(NSURL *)deepLinkUrl {
#if ADJUST_IM
// No deep linking in iMessage extension apps.
return;
#else
UIApplication *sharedUIApplication = [UIApplication sharedApplication];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
SEL openUrlSelector = @selector(openURL:options:completionHandler:);
#pragma clang diagnostic pop
if ([sharedUIApplication respondsToSelector:openUrlSelector]) {
/*
[sharedUIApplication openURL:deepLinkUrl options:@{} completionHandler:^(BOOL success) {
if (!success) {
[ADJAdjustFactory.logger error:@"Unable to open deep link (%@)", deepLinkUrl];
}
}];
*/
NSMethodSignature *methSig = [sharedUIApplication methodSignatureForSelector:openUrlSelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methSig];
[invocation setSelector: openUrlSelector];
[invocation setTarget: sharedUIApplication];
NSDictionary *emptyDictionary = @{};
void (^completion)(BOOL) = ^(BOOL success) {
if (!success) {
[ADJAdjustFactory.logger error:@"Unable to open deep link (%@)", deepLinkUrl];
}
};
[invocation setArgument:&deepLinkUrl atIndex: 2];
[invocation setArgument:&emptyDictionary atIndex: 3];
[invocation setArgument:&completion atIndex: 4];
[invocation invoke];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
BOOL success = [sharedUIApplication openURL:deepLinkUrl];
#pragma clang diagnostic pop
if (!success) {
[ADJAdjustFactory.logger error:@"Unable to open deep link without completionHandler (%@)", deepLinkUrl];
}
}
#endif
}
// adapted from https://stackoverflow.com/a/9084784
+ (NSString *)convertDeviceToken:(NSData *)deviceToken {
NSUInteger dataLength = [deviceToken length];
if (dataLength == 0) {
return nil;
}
const unsigned char *dataBuffer = (const unsigned char *)[deviceToken bytes];
if (!dataBuffer) {
return nil;
}
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (NSUInteger i = 0; i < dataLength; ++i) {
[hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
}
return [hexString copy];
}
+ (BOOL)checkAttributionDetails:(NSDictionary *)attributionDetails {
if ([ADJUtil isNull:attributionDetails]) {
return NO;
}
NSDictionary *details = [attributionDetails objectForKey:@"Version3.1"];
if ([ADJUtil isNull:details]) {
return YES;
}
// Common fields for both iAd3 and Apple Search Ads
if (![ADJUtil contains:details key:@"iad-org-name" value:@"OrgName"] ||
![ADJUtil contains:details key:@"iad-campaign-id" value:@"1234567890"] ||
![ADJUtil contains:details key:@"iad-campaign-name" value:@"CampaignName"] ||
![ADJUtil contains:details key:@"iad-lineitem-id" value:@"1234567890"] ||
![ADJUtil contains:details key:@"iad-lineitem-name" value:@"LineName"]) {
[ADJAdjustFactory.logger debug:@"iAd attribution details has dummy common fields for both iAd3 and Apple Search Ads"];
return YES;
}
// Apple Search Ads fields
if ([ADJUtil contains:details key:@"iad-adgroup-id" value:@"1234567890"] &&
[ADJUtil contains:details key:@"iad-keyword" value:@"Keyword"] && (
[ADJUtil contains:details key:@"iad-adgroup-name" value:@"AdgroupName"] ||
[ADJUtil contains:details key:@"iad-adgroup-name" value:@"AdGroupName"]
)) {
[ADJAdjustFactory.logger debug:@"iAd attribution details has dummy Apple Search Ads fields"];
return NO;
}
// iAd3 fields
if ([ADJUtil contains:details key:@"iad-adgroup-id" value:@"1234567890"] &&
[ADJUtil contains:details key:@"iad-creative-name" value:@"CreativeName"]) {
[ADJAdjustFactory.logger debug:@"iAd attribution details has dummy iAd3 fields"];
return NO;
}
return YES;
}
+ (BOOL)contains:(NSDictionary *)dictionary
key:(NSString *)key
value:(NSString *)value {
id readValue = [dictionary objectForKey:key];
if ([ADJUtil isNull:readValue]) {