-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathFIRInstanceID.m
1124 lines (982 loc) · 42.7 KB
/
FIRInstanceID.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
/*
* Copyright 2019 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FIRInstanceID.h"
#import <FirebaseInstallations/FIRInstallations.h>
#import <FirebaseCore/FIRAppInternal.h>
#import <FirebaseCore/FIRComponent.h>
#import <FirebaseCore/FIRComponentContainer.h>
#import <FirebaseCore/FIRLibrary.h>
#import <FirebaseCore/FIROptions.h>
#import <GoogleUtilities/GULAppEnvironmentUtil.h>
#import <GoogleUtilities/GULUserDefaults.h>
#import "FIRInstanceID+Private.h"
#import "FIRInstanceIDAuthService.h"
#import "FIRInstanceIDCheckinPreferences.h"
#import "FIRInstanceIDCombinedHandler.h"
#import "FIRInstanceIDConstants.h"
#import "FIRInstanceIDDefines.h"
#import "FIRInstanceIDLogger.h"
#import "FIRInstanceIDStore.h"
#import "FIRInstanceIDTokenInfo.h"
#import "FIRInstanceIDTokenManager.h"
#import "FIRInstanceIDUtilities.h"
#import "FIRInstanceIDVersionUtilities.h"
#import "NSError+FIRInstanceID.h"
// Public constants
NSString *const kFIRInstanceIDScopeFirebaseMessaging = @"fcm";
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
const NSNotificationName kFIRInstanceIDTokenRefreshNotification =
@"com.firebase.iid.notif.refresh-token";
#else
NSString *const kFIRInstanceIDTokenRefreshNotification = @"com.firebase.iid.notif.refresh-token";
#endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
NSString *const kFIRInstanceIDInvalidNilHandlerError = @"Invalid nil handler.";
// Private constants
int64_t const kMaxRetryIntervalForDefaultTokenInSeconds = 20 * 60; // 20 minutes
int64_t const kMinRetryIntervalForDefaultTokenInSeconds = 10; // 10 seconds
// we retry only a max 5 times.
// TODO(chliangGoogle): If we still fail we should listen for the network change notification
// since GCM would have started Reachability. We only start retrying after we see a configuration
// change.
NSInteger const kMaxRetryCountForDefaultToken = 5;
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
#else
static NSString *const kEntitlementsAPSEnvironmentKey =
@"Entitlements.com.apple.developer.aps-environment";
#endif
static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
/// FIRMessaging selector that returns the current FIRMessaging auto init
/// enabled flag.
static NSString *const kFIRInstanceIDFCMSelectorAutoInitEnabled =
@"isAutoInitEnabledWithUserDefaults:";
static NSString *const kFIRInstanceIDAPNSTokenType = @"APNSTokenType";
static NSString *const kFIRIIDAppReadyToConfigureSDKNotification =
@"FIRAppReadyToConfigureSDKNotification";
static NSString *const kFIRIIDAppNameKey = @"FIRAppNameKey";
static NSString *const kFIRIIDErrorDomain = @"com.firebase.instanceid";
static NSString *const kFIRIIDServiceInstanceID = @"InstanceID";
/**
* The APNS token type for the app. If the token type is set to `UNKNOWN`
* InstanceID will implicitly try to figure out what the actual token type
* is from the provisioning profile.
* This must match FIRMessagingAPNSTokenType in FIRMessaging.h
*/
typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) {
/// Unknown token type.
FIRInstanceIDAPNSTokenTypeUnknown,
/// Sandbox token type.
FIRInstanceIDAPNSTokenTypeSandbox,
/// Production token type.
FIRInstanceIDAPNSTokenTypeProd,
} NS_SWIFT_NAME(InstanceIDAPNSTokenType);
@interface FIRInstanceIDResult ()
@property(nonatomic, readwrite, copy) NSString *instanceID;
@property(nonatomic, readwrite, copy) NSString *token;
@end
@interface FIRInstanceID ()
// FIRApp configuration objects.
@property(nonatomic, readwrite, copy) NSString *fcmSenderID;
@property(nonatomic, readwrite, copy) NSString *firebaseAppID;
// Raw APNS token data
@property(nonatomic, readwrite, strong) NSData *apnsTokenData;
@property(nonatomic, readwrite) FIRInstanceIDAPNSTokenType apnsTokenType;
// String-based, internal representation of APNS token
@property(nonatomic, readwrite, copy) NSString *APNSTupleString;
// Token fetched from the server automatically for the default app.
@property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
@property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
@property(nonatomic, readwrite, strong) FIRInstallations *installations;
// backoff and retry for default token
@property(nonatomic, readwrite, assign) NSInteger retryCountForDefaultToken;
@property(atomic, strong, nullable)
FIRInstanceIDCombinedHandler<NSString *> *defaultTokenFetchHandler;
/// A cached value of FID. Should be used only for `-[FIRInstanceID appInstanceID:]`.
@property(atomic, copy, nullable) NSString *firebaseInstallationsID;
@end
// InstanceID doesn't provide any functionality to other components,
// so it provides a private, empty protocol that it conforms to and use it for registration.
@protocol FIRInstanceIDInstanceProvider
@end
@interface FIRInstanceID () <FIRInstanceIDInstanceProvider, FIRLibrary>
@end
@implementation FIRInstanceIDResult
- (id)copyWithZone:(NSZone *)zone {
FIRInstanceIDResult *result = [[[self class] allocWithZone:zone] init];
result.instanceID = self.instanceID;
result.token = self.token;
return result;
}
@end
@implementation FIRInstanceID
// File static to support InstanceID tests that call [FIRInstanceID instanceID] after
// [FIRInstanceID instanceIDForTests].
static FIRInstanceID *gInstanceID;
+ (instancetype)instanceID {
// If the static instance was created, return it. This should only be set in tests and we should
// eventually use proper dependency injection for a better test structure.
if (gInstanceID != nil) {
return gInstanceID;
}
FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
FIRInstanceID *instanceID =
(FIRInstanceID *)FIR_COMPONENT(FIRInstanceIDInstanceProvider, defaultApp.container);
return instanceID;
}
- (instancetype)initPrivately {
self = [super init];
if (self != nil) {
// Use automatic detection of sandbox, unless otherwise set by developer
_apnsTokenType = FIRInstanceIDAPNSTokenTypeUnknown;
}
return self;
}
+ (FIRInstanceID *)instanceIDForTests {
gInstanceID = [[FIRInstanceID alloc] initPrivately];
[gInstanceID start];
return gInstanceID;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Tokens
- (NSString *)token {
if (!self.fcmSenderID.length) {
return nil;
}
NSString *cachedToken = [self cachedTokenIfAvailable];
if (cachedToken) {
return cachedToken;
} else {
// If we've never had a cached default token, we should fetch one because unrelatedly,
// this request will help us determine whether the locally-generated Instance ID keypair is not
// unique, and therefore generate a new one.
[self defaultTokenWithHandler:nil];
return nil;
}
}
- (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler {
FIRInstanceID_WEAKIFY(self);
[self getIDWithHandler:^(NSString *identity, NSError *error) {
FIRInstanceID_STRONGIFY(self);
// This is in main queue already
if (error) {
if (handler) {
handler(nil, error);
}
return;
}
FIRInstanceIDResult *result = [[FIRInstanceIDResult alloc] init];
result.instanceID = identity;
NSString *cachedToken = [self cachedTokenIfAvailable];
if (cachedToken) {
if (handler) {
result.token = cachedToken;
handler(result, nil);
}
// If no handler, simply return since client has generated iid and token.
return;
}
[self defaultTokenWithHandler:^(NSString *_Nullable token, NSError *_Nullable error) {
if (handler) {
if (error) {
handler(nil, error);
return;
}
result.token = token;
handler(result, nil);
}
}];
}];
}
- (NSString *)cachedTokenIfAvailable {
FIRInstanceIDTokenInfo *cachedTokenInfo =
[self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
scope:kFIRInstanceIDDefaultTokenScope];
return cachedTokenInfo.token;
}
- (void)setDefaultFCMToken:(NSString *)defaultFCMToken {
// Sending this notification out will ensure that FIRMessaging and FIRInstanceID has the updated
// default FCM token.
// Only notify of token refresh if we have a new valid token that's different than before
if ((defaultFCMToken.length && _defaultFCMToken.length &&
![defaultFCMToken isEqualToString:_defaultFCMToken]) ||
defaultFCMToken.length != _defaultFCMToken.length) {
NSNotification *tokenRefreshNotification =
[NSNotification notificationWithName:kFIRInstanceIDTokenRefreshNotification
object:[defaultFCMToken copy]];
[[NSNotificationQueue defaultQueue] enqueueNotification:tokenRefreshNotification
postingStyle:NSPostASAP];
}
_defaultFCMToken = defaultFCMToken;
}
- (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity
scope:(NSString *)scope
options:(NSDictionary *)options
handler:(FIRInstanceIDTokenHandler)handler {
if (!handler) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID000,
kFIRInstanceIDInvalidNilHandlerError);
return;
}
// Add internal options
NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
if (options.count) {
[tokenOptions addEntriesFromDictionary:options];
}
NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
if (tokenOptions[APNSKey] != nil && tokenOptions[serverTypeKey] == nil) {
// APNS key was given, but server type is missing. Supply the server type with automatic
// checking. This can happen when the token is requested from FCM, which does not include a
// server type during its request.
tokenOptions[serverTypeKey] = @([self isSandboxApp]);
}
if (self.firebaseAppID) {
tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
}
// comparing enums to ints directly throws a warning
FIRInstanceIDErrorCode noError = INT_MAX;
FIRInstanceIDErrorCode errorCode = noError;
if (FIRInstanceIDIsValidGCMScope(scope) && !tokenOptions[APNSKey]) {
errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken;
} else if (FIRInstanceIDIsValidGCMScope(scope) &&
![tokenOptions[APNSKey] isKindOfClass:[NSData class]]) {
errorCode = kFIRInstanceIDErrorCodeInvalidRequest;
} else if (![authorizedEntity length]) {
errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
} else if (![scope length]) {
errorCode = kFIRInstanceIDErrorCodeInvalidScope;
} else if (!self.installations) {
errorCode = kFIRInstanceIDErrorCodeInvalidStart;
}
FIRInstanceIDTokenHandler newHandler = ^(NSString *token, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(token, error);
});
};
if (errorCode != noError) {
newHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:errorCode]);
return;
}
FIRInstanceID_WEAKIFY(self);
FIRInstanceIDAuthService *authService = self.tokenManager.authService;
[authService fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences,
NSError *error) {
FIRInstanceID_STRONGIFY(self);
if (error) {
newHandler(nil, error);
return;
}
FIRInstanceID_WEAKIFY(self);
[self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
NSError *_Nullable error) {
FIRInstanceID_STRONGIFY(self);
if (error) {
NSError *newError =
[NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
newHandler(nil, newError);
} else {
FIRInstanceIDTokenInfo *cachedTokenInfo =
[self.tokenManager cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
if (cachedTokenInfo) {
FIRInstanceIDAPNSInfo *optionsAPNSInfo =
[[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
// Check if APNS Info is changed
if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
[cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
// check if token is fresh
if ([cachedTokenInfo isFreshWithIID:identifier]) {
newHandler(cachedTokenInfo.token, nil);
return;
}
}
}
[self.tokenManager fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
scope:[scope copy]
instanceID:identifier
options:tokenOptions
handler:newHandler];
}
}];
}];
}
- (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
scope:(NSString *)scope
handler:(FIRInstanceIDDeleteTokenHandler)handler {
if (!handler) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID001,
kFIRInstanceIDInvalidNilHandlerError);
return;
}
// comparing enums to ints directly throws a warning
FIRInstanceIDErrorCode noError = INT_MAX;
FIRInstanceIDErrorCode errorCode = noError;
if (![authorizedEntity length]) {
errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
} else if (![scope length]) {
errorCode = kFIRInstanceIDErrorCodeInvalidScope;
} else if (!self.installations) {
errorCode = kFIRInstanceIDErrorCodeInvalidStart;
}
FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
// If a default token is deleted successfully, reset the defaultFCMToken too.
if (!error && [authorizedEntity isEqualToString:self.fcmSenderID] &&
[scope isEqualToString:kFIRInstanceIDDefaultTokenScope]) {
self.defaultFCMToken = nil;
}
dispatch_async(dispatch_get_main_queue(), ^{
handler(error);
});
};
if (errorCode != noError) {
newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
return;
}
FIRInstanceID_WEAKIFY(self);
FIRInstanceIDAuthService *authService = self.tokenManager.authService;
[authService
fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
FIRInstanceID_STRONGIFY(self);
if (error) {
newHandler(error);
return;
}
FIRInstanceID_WEAKIFY(self);
[self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
NSError *_Nullable error) {
FIRInstanceID_STRONGIFY(self);
if (error) {
NSError *newError =
[NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
newHandler(newError);
} else {
[self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
scope:scope
instanceID:identifier
handler:newHandler];
}
}];
}];
}
#pragma mark - Identity
- (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
if (!handler) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID003,
kFIRInstanceIDInvalidNilHandlerError);
return;
}
FIRInstanceID_WEAKIFY(self);
[self.installations
installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
FIRInstanceID_STRONGIFY(self);
// When getID is explicitly called, trigger getToken to make sure token always exists.
// This is to avoid ID conflict (ID is not checked for conflict until we generate a token)
if (identifier) {
[self token];
}
handler(identifier, error);
}];
}
- (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
if (!handler) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
kFIRInstanceIDInvalidNilHandlerError);
return;
}
void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
if ([NSThread isMainThread]) {
handler(error);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
handler(error);
});
};
if (!self.installations) {
FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
return;
}
FIRInstanceID_WEAKIFY(self);
void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
FIRInstanceID_STRONGIFY(self);
if (error) {
callHandlerOnMainThread(error);
return;
}
[self deleteIdentityWithHandler:^(NSError *error) {
callHandlerOnMainThread(error);
}];
};
[self.installations
installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
FIRInstanceID_STRONGIFY(self);
if (error) {
NSError *newError =
[NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
callHandlerOnMainThread(newError);
} else {
[self.tokenManager deleteAllTokensWithInstanceID:identifier handler:deleteTokensHandler];
}
}];
}
- (void)notifyIdentityReset {
[self deleteIdentityWithHandler:nil];
}
// Delete all the local cache checkin, IID and token.
- (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
// Delete tokens.
[self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
// Reset FCM token.
self.defaultFCMToken = nil;
if (deleteTokenError) {
if (handler) {
handler(deleteTokenError);
}
return;
}
// Delete Instance ID.
[self.installations deleteWithCompletion:^(NSError *_Nullable error) {
if (error) {
if (handler) {
handler(error);
}
return;
}
[self.tokenManager.authService resetCheckinWithHandler:^(NSError *error) {
if (error) {
if (handler) {
handler(error);
}
return;
}
// Only request new token if FCM auto initialization is
// enabled.
if ([self isFCMAutoInitEnabled]) {
// Deletion succeeds! Requesting new checkin, IID and token.
// TODO(chliangGoogle) see if dispatch_after is necessary
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[self defaultTokenWithHandler:nil];
});
}
if (handler) {
handler(nil);
}
}];
}];
}];
}
#pragma mark - Checkin
- (BOOL)tryToLoadValidCheckinInfo {
FIRInstanceIDCheckinPreferences *checkinPreferences =
[self.tokenManager.authService checkinPreferences];
return [checkinPreferences hasValidCheckinInfo];
}
- (NSString *)deviceAuthID {
return [self.tokenManager.authService checkinPreferences].deviceID;
}
- (NSString *)secretToken {
return [self.tokenManager.authService checkinPreferences].secretToken;
}
- (NSString *)versionInfo {
return [self.tokenManager.authService checkinPreferences].versionInfo;
}
#pragma mark - Config
+ (void)load {
[FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
withName:@"fire-iid"
withVersion:FIRInstanceIDCurrentLibraryVersion()];
}
+ (nonnull NSArray<FIRComponent *> *)componentsToRegister {
FIRComponentCreationBlock creationBlock =
^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
// InstanceID only works with the default app.
if (!container.app.isDefaultApp) {
// Only configure for the default FIRApp.
FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
@"Firebase Instance ID only works with the default app.");
return nil;
}
// Ensure it's cached so it returns the same instance every time instanceID is called.
*isCacheable = YES;
FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
[instanceID start];
[instanceID configureInstanceIDWithOptions:container.app.options];
return instanceID;
};
FIRComponent *instanceIDProvider =
[FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
dependencies:@[]
creationBlock:creationBlock];
return @[ instanceIDProvider ];
}
- (void)configureInstanceIDWithOptions:(FIROptions *)options {
NSString *GCMSenderID = options.GCMSenderID;
if (!GCMSenderID.length) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
@"Firebase not set up correctly, nil or empty senderID.");
[NSException raise:kFIRIIDErrorDomain
format:@"Could not configure Firebase InstanceID. GCMSenderID must not be nil or "
@"empty."];
}
self.fcmSenderID = GCMSenderID;
self.firebaseAppID = options.googleAppID;
[self updateFirebaseInstallationID];
// FCM generates a FCM token during app start for sending push notification to device.
// This is not needed for app extension except for watch.
#if TARGET_OS_WATCH
[self didCompleteConfigure];
#else
if (![GULAppEnvironmentUtil isAppExtension]) {
[self didCompleteConfigure];
}
#endif
}
// This is used to start any operations when we receive FirebaseSDK setup notification
// from FIRCore.
- (void)didCompleteConfigure {
NSString *cachedToken = [self cachedTokenIfAvailable];
// When there is a cached token, do the token refresh.
if (cachedToken) {
// Clean up expired tokens by checking the token refresh policy.
[self.installations
installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
if ([self.tokenManager checkTokenRefreshPolicyWithIID:identifier]) {
// Default token is expired, fetch default token from server.
[self defaultTokenWithHandler:nil];
}
// Notify FCM with the default token.
self.defaultFCMToken = [self token];
}];
} else if ([self isFCMAutoInitEnabled]) {
// When there is no cached token, must check auto init is enabled.
// If it's disabled, don't initiate token generation/refresh.
// If no cache token and auto init is enabled, fetch a token from server.
[self defaultTokenWithHandler:nil];
// Notify FCM with the default token.
self.defaultFCMToken = [self token];
}
// ONLY checkin when auto data collection is turned on.
if ([self isFCMAutoInitEnabled]) {
[self.tokenManager.authService scheduleCheckin:YES];
}
}
- (BOOL)isFCMAutoInitEnabled {
Class messagingClass = NSClassFromString(kFIRInstanceIDFCMSDKClassString);
// Firebase Messaging is not installed, auto init should be disabled since it's for FCM.
if (!messagingClass) {
return NO;
}
// Messaging doesn't have the class method, auto init should be enabled since FCM exists.
SEL autoInitSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorAutoInitEnabled);
if (![messagingClass respondsToSelector:autoInitSelector]) {
return YES;
}
// Get the autoInitEnabled class method.
IMP isAutoInitEnabledIMP = [messagingClass methodForSelector:autoInitSelector];
BOOL(*isAutoInitEnabled)
(Class, SEL, GULUserDefaults *) = (BOOL(*)(id, SEL, GULUserDefaults *))isAutoInitEnabledIMP;
// Check FCM's isAutoInitEnabled property.
return isAutoInitEnabled(messagingClass, autoInitSelector,
[GULUserDefaults standardUserDefaults]);
}
// Actually makes InstanceID instantiate both the IID and Token-related subsystems.
- (void)start {
if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
[FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
}
[self setupTokenManager];
self.installations = [FIRInstallations installations];
[self setupNotificationListeners];
}
// Creates the token manager, which is used for fetching, caching, and retrieving tokens.
- (void)setupTokenManager {
self.tokenManager = [[FIRInstanceIDTokenManager alloc] init];
}
- (void)setupNotificationListeners {
// To prevent double notifications remove observer from all events during setup.
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self];
[center addObserver:self
selector:@selector(notifyIdentityReset)
name:kFIRInstanceIDIdentityInvalidatedNotification
object:nil];
[center addObserver:self
selector:@selector(notifyAPNSTokenIsSet:)
name:kFIRInstanceIDAPNSTokenNotification
object:nil];
[self observeFirebaseInstallationIDChanges];
}
#pragma mark - Private Helpers
/// Maximum retry count to fetch the default token.
+ (int64_t)maxRetryCountForDefaultToken {
return kMaxRetryCountForDefaultToken;
}
/// Minimum interval in seconds between retries to fetch the default token.
+ (int64_t)minIntervalForDefaultTokenRetry {
return kMinRetryIntervalForDefaultTokenInSeconds;
}
/// Maximum retry interval between retries to fetch default token.
+ (int64_t)maxRetryIntervalForDefaultTokenInSeconds {
return kMaxRetryIntervalForDefaultTokenInSeconds;
}
- (NSInteger)retryIntervalToFetchDefaultToken {
if (self.retryCountForDefaultToken >= [[self class] maxRetryCountForDefaultToken]) {
return (NSInteger)[[self class] maxRetryIntervalForDefaultTokenInSeconds];
}
// exponential backoff with a fixed initial retry time
// 11s, 22s, 44s, 88s ...
int64_t minInterval = [[self class] minIntervalForDefaultTokenRetry];
return (NSInteger)MIN(
(1 << self.retryCountForDefaultToken) + minInterval * self.retryCountForDefaultToken,
kMaxRetryIntervalForDefaultTokenInSeconds);
}
- (void)defaultTokenWithHandler:(nullable FIRInstanceIDTokenHandler)aHandler {
[self defaultTokenWithRetry:NO handler:aHandler];
}
/**
* @param retry Indicates if the method is called to perform a retry after a failed attempt.
* If `YES`, then actual token request will be performed even if `self.defaultTokenFetchHandler !=
* nil`
*/
- (void)defaultTokenWithRetry:(BOOL)retry handler:(nullable FIRInstanceIDTokenHandler)aHandler {
BOOL shouldPerformRequest = retry || self.defaultTokenFetchHandler == nil;
if (!self.defaultTokenFetchHandler) {
self.defaultTokenFetchHandler = [[FIRInstanceIDCombinedHandler<NSString *> alloc] init];
}
if (aHandler) {
[self.defaultTokenFetchHandler addHandler:aHandler];
}
if (!shouldPerformRequest) {
return;
}
NSDictionary *instanceIDOptions = @{};
BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
if (hasFirebaseMessaging && self.apnsTokenData) {
BOOL isSandboxApp = (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeSandbox);
if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
isSandboxApp = [self isSandboxApp];
}
instanceIDOptions = @{
kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp),
};
}
FIRInstanceID_WEAKIFY(self);
FIRInstanceIDTokenHandler newHandler = ^void(NSString *token, NSError *error) {
FIRInstanceID_STRONGIFY(self);
if (error) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID009,
@"Failed to fetch default token %@", error);
// This notification can be sent multiple times since we can't guarantee success at any point
// of time.
NSNotification *tokenFetchFailNotification =
[NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenFailNotification
object:[error copy]];
[[NSNotificationQueue defaultQueue] enqueueNotification:tokenFetchFailNotification
postingStyle:NSPostASAP];
self.retryCountForDefaultToken = (NSInteger)MIN(self.retryCountForDefaultToken + 1,
[[self class] maxRetryCountForDefaultToken]);
// Do not retry beyond the maximum limit.
if (self.retryCountForDefaultToken < [[self class] maxRetryCountForDefaultToken]) {
NSInteger retryInterval = [self retryIntervalToFetchDefaultToken];
[self retryGetDefaultTokenAfter:retryInterval];
} else {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID007,
@"Failed to retrieve the default FCM token after %ld retries",
(long)self.retryCountForDefaultToken);
[self performDefaultTokenHandlerWithToken:nil error:error];
}
} else {
// If somebody updated IID with APNS token while our initial request did not have it
// set we need to update it on the server.
NSData *deviceTokenInRequest = instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSKey];
BOOL isSandboxInRequest =
[instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue];
// Note that APNSTupleStringInRequest will be nil if deviceTokenInRequest is nil
NSString *APNSTupleStringInRequest = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
deviceTokenInRequest, isSandboxInRequest);
// If the APNs value either remained nil, or was the same non-nil value, the APNs value
// did not change.
BOOL APNSRemainedSameDuringFetch =
(self.APNSTupleString == nil && APNSTupleStringInRequest == nil) ||
([self.APNSTupleString isEqualToString:APNSTupleStringInRequest]);
if (!APNSRemainedSameDuringFetch && hasFirebaseMessaging) {
// APNs value did change mid-fetch, so the token should be re-fetched with the current APNs
// value.
[self retryGetDefaultTokenAfter:0];
FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
@"Received APNS token while fetching default token. "
@"Refetching default token.");
// Do not notify and handle completion handler since this is a retry.
// Simply return.
return;
} else {
FIRInstanceIDLoggerInfo(kFIRInstanceIDMessageCodeInstanceID010,
@"Successfully fetched default token.");
}
// Post the required notifications if somebody is waiting.
FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID008, @"Got default token %@",
token);
// Update default FCM token, this method also triggers sending notification if token has
// changed.
self.defaultFCMToken = token;
[self performDefaultTokenHandlerWithToken:token error:nil];
}
};
[self tokenWithAuthorizedEntity:self.fcmSenderID
scope:kFIRInstanceIDDefaultTokenScope
options:instanceIDOptions
handler:newHandler];
}
/**
*
*/
- (void)performDefaultTokenHandlerWithToken:(NSString *)token error:(NSError *)error {
if (!self.defaultTokenFetchHandler) {
return;
}
[self.defaultTokenFetchHandler combinedHandler](token, error);
self.defaultTokenFetchHandler = nil;
}
- (void)retryGetDefaultTokenAfter:(NSTimeInterval)retryInterval {
FIRInstanceID_WEAKIFY(self);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
FIRInstanceID_STRONGIFY(self);
// Pass nil: no new handlers to be added, currently existing handlers
// will be called
[self defaultTokenWithRetry:YES handler:nil];
});
}
#pragma mark - APNS Token
// This should only be triggered from FCM.
- (void)notifyAPNSTokenIsSet:(NSNotification *)notification {
NSData *token = notification.object;
if (!token || ![token isKindOfClass:[NSData class]]) {
FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal002, @"Invalid APNS token type %@",
NSStringFromClass([notification.object class]));
return;
}
NSInteger type = [notification.userInfo[kFIRInstanceIDAPNSTokenType] integerValue];
// The APNS token is being added, or has changed (rare)
if ([self.apnsTokenData isEqualToData:token]) {
FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID011,
@"Trying to reset APNS token to the same value. Will return");
return;
}
// Use this token type for when we have to automatically fetch tokens in the future
self.apnsTokenType = type;
BOOL isSandboxApp = (type == FIRInstanceIDAPNSTokenTypeSandbox);
if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
isSandboxApp = [self isSandboxApp];
}
self.apnsTokenData = [token copy];
self.APNSTupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(token, isSandboxApp);
// Pro-actively invalidate the default token, if the APNs change makes it
// invalid. Previously, we invalidated just before fetching the token.
NSArray<FIRInstanceIDTokenInfo *> *invalidatedTokens =
[self.tokenManager updateTokensToAPNSDeviceToken:self.apnsTokenData isSandbox:isSandboxApp];
// Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
// they are up-to-date.
if (invalidatedTokens.count > 0) {
FIRInstanceID_WEAKIFY(self);
[self.installations
installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
FIRInstanceID_STRONGIFY(self);
if (self == nil) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID017,
@"Instance ID shut down during token reset. Aborting");
return;
}
if (self.apnsTokenData == nil) {
FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID018,
@"apnsTokenData was set to nil during token reset. Aborting");
return;
}
NSMutableDictionary *tokenOptions = [@{
kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
} mutableCopy];
if (self.firebaseAppID) {
tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
}
for (FIRInstanceIDTokenInfo *tokenInfo in invalidatedTokens) {
if ([tokenInfo.token isEqualToString:self.defaultFCMToken]) {
// We will perform a special fetch for the default FCM token, so that the delegate
// methods are called. For all others, we will do an internal re-fetch.
[self defaultTokenWithHandler:nil];
} else {
[self.tokenManager fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
scope:tokenInfo.scope
instanceID:identifier
options:tokenOptions
handler:^(NSString *_Nullable token,
NSError *_Nullable error){
}];
}
}
}];
}
}
- (BOOL)isSandboxApp {
static BOOL isSandboxApp = YES;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
isSandboxApp = ![self isProductionApp];
});
return isSandboxApp;
}
- (BOOL)isProductionApp {
const BOOL defaultAppTypeProd = YES;
NSError *error = nil;
if ([GULAppEnvironmentUtil isSimulator]) {
[self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
@"Use prod profile by default."];
return defaultAppTypeProd;
}
if ([GULAppEnvironmentUtil isFromAppStore]) {
// Apps distributed via AppStore or TestFlight use the Production APNS certificates.
return defaultAppTypeProd;
}
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
stringByAppendingPathComponent:@"embedded.provisionprofile"];
#elif TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
NSString *path = [[[NSBundle mainBundle] bundlePath]
stringByAppendingPathComponent:@"embedded.mobileprovision"];
#endif
if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
// Distributed via TestFlight
return defaultAppTypeProd;
}
NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
if (!profileData.length || error) {
NSString *errorString =
[NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
[self logAPNSConfigurationError:errorString];
return defaultAppTypeProd;
}