FIRInstanceID.m 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "Firebase/InstanceID/Public/FIRInstanceID.h"
  17. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  18. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  19. #import <GoogleUtilities/GULUserDefaults.h>
  20. #import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
  21. #import "Firebase/InstanceID/FIRInstanceIDCombinedHandler.h"
  22. #import "Firebase/InstanceID/FIRInstanceIDConstants.h"
  23. #import "Firebase/InstanceID/FIRInstanceIDDefines.h"
  24. #import "Firebase/InstanceID/FIRInstanceIDLogger.h"
  25. #import "Firebase/InstanceID/FIRInstanceIDStore.h"
  26. #import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
  27. #import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
  28. #import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
  29. #import "Firebase/InstanceID/FIRInstanceIDVersionUtilities.h"
  30. #import "Firebase/InstanceID/NSError+FIRInstanceID.h"
  31. #import "Firebase/InstanceID/Private/FIRInstanceID+Private.h"
  32. #import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
  33. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  34. // Public constants
  35. NSString *const kFIRInstanceIDScopeFirebaseMessaging = @"fcm";
  36. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  37. const NSNotificationName kFIRInstanceIDTokenRefreshNotification =
  38. @"com.firebase.iid.notif.refresh-token";
  39. #else
  40. NSString *const kFIRInstanceIDTokenRefreshNotification = @"com.firebase.iid.notif.refresh-token";
  41. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  42. NSString *const kFIRInstanceIDInvalidNilHandlerError = @"Invalid nil handler.";
  43. // Private constants
  44. int64_t const kMaxRetryIntervalForDefaultTokenInSeconds = 20 * 60; // 20 minutes
  45. int64_t const kMinRetryIntervalForDefaultTokenInSeconds = 10; // 10 seconds
  46. // we retry only a max 5 times.
  47. // TODO(chliangGoogle): If we still fail we should listen for the network change notification
  48. // since GCM would have started Reachability. We only start retrying after we see a configuration
  49. // change.
  50. NSInteger const kMaxRetryCountForDefaultToken = 5;
  51. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  52. static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
  53. #else
  54. static NSString *const kEntitlementsAPSEnvironmentKey =
  55. @"Entitlements.com.apple.developer.aps-environment";
  56. #endif
  57. static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
  58. /// FIRMessaging selector that returns the current FIRMessaging auto init
  59. /// enabled flag.
  60. static NSString *const kFIRInstanceIDFCMSelectorAutoInitEnabled =
  61. @"isAutoInitEnabledWithUserDefaults:";
  62. static NSString *const kFIRInstanceIDAPNSTokenType = @"APNSTokenType";
  63. static NSString *const kFIRIIDAppReadyToConfigureSDKNotification =
  64. @"FIRAppReadyToConfigureSDKNotification";
  65. static NSString *const kFIRIIDAppNameKey = @"FIRAppNameKey";
  66. static NSString *const kFIRIIDErrorDomain = @"com.firebase.instanceid";
  67. static NSString *const kFIRIIDServiceInstanceID = @"InstanceID";
  68. /**
  69. * The APNS token type for the app. If the token type is set to `UNKNOWN`
  70. * InstanceID will implicitly try to figure out what the actual token type
  71. * is from the provisioning profile.
  72. * This must match FIRMessagingAPNSTokenType in FIRMessaging.h
  73. */
  74. typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) {
  75. /// Unknown token type.
  76. FIRInstanceIDAPNSTokenTypeUnknown,
  77. /// Sandbox token type.
  78. FIRInstanceIDAPNSTokenTypeSandbox,
  79. /// Production token type.
  80. FIRInstanceIDAPNSTokenTypeProd,
  81. } NS_SWIFT_NAME(InstanceIDAPNSTokenType);
  82. @interface FIRInstanceIDResult ()
  83. @property(nonatomic, readwrite, copy) NSString *instanceID;
  84. @property(nonatomic, readwrite, copy) NSString *token;
  85. @end
  86. @interface FIRInstanceID ()
  87. // FIRApp configuration objects.
  88. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  89. @property(nonatomic, readwrite, copy) NSString *firebaseAppID;
  90. // Raw APNS token data
  91. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  92. @property(nonatomic, readwrite) FIRInstanceIDAPNSTokenType apnsTokenType;
  93. // String-based, internal representation of APNS token
  94. @property(nonatomic, readwrite, copy) NSString *APNSTupleString;
  95. // Token fetched from the server automatically for the default app.
  96. @property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
  97. @property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
  98. @property(nonatomic, readwrite, strong) FIRInstallations *installations;
  99. // backoff and retry for default token
  100. @property(nonatomic, readwrite, assign) NSInteger retryCountForDefaultToken;
  101. @property(atomic, strong, nullable)
  102. FIRInstanceIDCombinedHandler<NSString *> *defaultTokenFetchHandler;
  103. /// A cached value of FID. Should be used only for `-[FIRInstanceID appInstanceID:]`.
  104. @property(atomic, copy, nullable) NSString *firebaseInstallationsID;
  105. @end
  106. // InstanceID doesn't provide any functionality to other components,
  107. // so it provides a private, empty protocol that it conforms to and use it for registration.
  108. @protocol FIRInstanceIDInstanceProvider
  109. @end
  110. @interface FIRInstanceID () <FIRInstanceIDInstanceProvider, FIRLibrary>
  111. @end
  112. #pragma clang diagnostic push
  113. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  114. @implementation FIRInstanceIDResult
  115. #pragma clang diagnostic pop
  116. - (id)copyWithZone:(NSZone *)zone {
  117. FIRInstanceIDResult *result = [[[self class] allocWithZone:zone] init];
  118. result.instanceID = self.instanceID;
  119. result.token = self.token;
  120. return result;
  121. }
  122. @end
  123. #pragma clang diagnostic push
  124. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  125. @implementation FIRInstanceID
  126. #pragma clang diagnostic pop
  127. // File static to support InstanceID tests that call [FIRInstanceID instanceID] after
  128. // [FIRInstanceID instanceIDForTests].
  129. static FIRInstanceID *gInstanceID;
  130. + (instancetype)instanceID {
  131. // If the static instance was created, return it. This should only be set in tests and we should
  132. // eventually use proper dependency injection for a better test structure.
  133. if (gInstanceID != nil) {
  134. return gInstanceID;
  135. }
  136. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  137. FIRInstanceID *instanceID =
  138. (FIRInstanceID *)FIR_COMPONENT(FIRInstanceIDInstanceProvider, defaultApp.container);
  139. return instanceID;
  140. }
  141. - (instancetype)initPrivately {
  142. self = [super init];
  143. if (self != nil) {
  144. // Use automatic detection of sandbox, unless otherwise set by developer
  145. _apnsTokenType = FIRInstanceIDAPNSTokenTypeUnknown;
  146. }
  147. return self;
  148. }
  149. + (FIRInstanceID *)instanceIDForTests {
  150. gInstanceID = [[FIRInstanceID alloc] initPrivately];
  151. [gInstanceID start];
  152. return gInstanceID;
  153. }
  154. - (void)dealloc {
  155. [[NSNotificationCenter defaultCenter] removeObserver:self];
  156. }
  157. #pragma mark - Tokens
  158. - (NSString *)token {
  159. if (!self.fcmSenderID.length) {
  160. return nil;
  161. }
  162. NSString *cachedToken = [self cachedTokenIfAvailable];
  163. if (cachedToken) {
  164. return cachedToken;
  165. } else {
  166. // If we've never had a cached default token, we should fetch one because unrelatedly,
  167. // this request will help us determine whether the locally-generated Instance ID keypair is not
  168. // unique, and therefore generate a new one.
  169. [self defaultTokenWithHandler:nil];
  170. return nil;
  171. }
  172. }
  173. - (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler {
  174. FIRInstanceID_WEAKIFY(self);
  175. [self getIDWithHandler:^(NSString *identity, NSError *error) {
  176. FIRInstanceID_STRONGIFY(self);
  177. // This is in main queue already
  178. if (error) {
  179. if (handler) {
  180. handler(nil, error);
  181. }
  182. return;
  183. }
  184. FIRInstanceIDResult *result = [[FIRInstanceIDResult alloc] init];
  185. result.instanceID = identity;
  186. NSString *cachedToken = [self cachedTokenIfAvailable];
  187. if (cachedToken) {
  188. if (handler) {
  189. result.token = cachedToken;
  190. handler(result, nil);
  191. }
  192. // If no handler, simply return since client has generated iid and token.
  193. return;
  194. }
  195. [self defaultTokenWithHandler:^(NSString *_Nullable token, NSError *_Nullable error) {
  196. if (handler) {
  197. if (error) {
  198. handler(nil, error);
  199. return;
  200. }
  201. result.token = token;
  202. handler(result, nil);
  203. }
  204. }];
  205. }];
  206. }
  207. - (NSString *)cachedTokenIfAvailable {
  208. FIRInstanceIDTokenInfo *cachedTokenInfo =
  209. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
  210. scope:kFIRInstanceIDDefaultTokenScope];
  211. return cachedTokenInfo.token;
  212. }
  213. - (void)setDefaultFCMToken:(NSString *)defaultFCMToken {
  214. // Sending this notification out will ensure that FIRMessaging and FIRInstanceID has the updated
  215. // default FCM token.
  216. // Only notify of token refresh if we have a new valid token that's different than before
  217. if ((defaultFCMToken.length && _defaultFCMToken.length &&
  218. ![defaultFCMToken isEqualToString:_defaultFCMToken]) ||
  219. defaultFCMToken.length != _defaultFCMToken.length) {
  220. NSNotification *tokenRefreshNotification =
  221. [NSNotification notificationWithName:kFIRInstanceIDTokenRefreshNotification
  222. object:[defaultFCMToken copy]];
  223. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenRefreshNotification
  224. postingStyle:NSPostASAP];
  225. }
  226. _defaultFCMToken = defaultFCMToken;
  227. }
  228. - (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity
  229. scope:(NSString *)scope
  230. options:(NSDictionary *)options
  231. handler:(FIRInstanceIDTokenHandler)handler {
  232. if (!handler) {
  233. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID000,
  234. kFIRInstanceIDInvalidNilHandlerError);
  235. return;
  236. }
  237. // Add internal options
  238. NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
  239. if (options.count) {
  240. [tokenOptions addEntriesFromDictionary:options];
  241. }
  242. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  243. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  244. if (tokenOptions[APNSKey] != nil && tokenOptions[serverTypeKey] == nil) {
  245. // APNS key was given, but server type is missing. Supply the server type with automatic
  246. // checking. This can happen when the token is requested from FCM, which does not include a
  247. // server type during its request.
  248. tokenOptions[serverTypeKey] = @([self isSandboxApp]);
  249. }
  250. if (self.firebaseAppID) {
  251. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  252. }
  253. // comparing enums to ints directly throws a warning
  254. FIRInstanceIDErrorCode noError = INT_MAX;
  255. FIRInstanceIDErrorCode errorCode = noError;
  256. if (FIRInstanceIDIsValidGCMScope(scope) && !tokenOptions[APNSKey]) {
  257. errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken;
  258. } else if (FIRInstanceIDIsValidGCMScope(scope) &&
  259. ![tokenOptions[APNSKey] isKindOfClass:[NSData class]]) {
  260. errorCode = kFIRInstanceIDErrorCodeInvalidRequest;
  261. } else if (![authorizedEntity length]) {
  262. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  263. } else if (![scope length]) {
  264. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  265. } else if (!self.installations) {
  266. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  267. }
  268. FIRInstanceIDTokenHandler newHandler = ^(NSString *token, NSError *error) {
  269. if (!error && [self isDefaultTokenWithAuthorizedEntity:authorizedEntity scope:scope]) {
  270. // The local cache should be updated as it is critical for sending token updates.
  271. self.defaultFCMToken = token;
  272. }
  273. dispatch_async(dispatch_get_main_queue(), ^{
  274. handler(token, error);
  275. });
  276. };
  277. if (errorCode != noError) {
  278. newHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  279. return;
  280. }
  281. FIRInstanceID_WEAKIFY(self);
  282. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  283. [authService fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences,
  284. NSError *error) {
  285. FIRInstanceID_STRONGIFY(self);
  286. if (error) {
  287. newHandler(nil, error);
  288. return;
  289. }
  290. FIRInstanceID_WEAKIFY(self);
  291. [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  292. NSError *_Nullable error) {
  293. FIRInstanceID_STRONGIFY(self);
  294. if (error) {
  295. NSError *newError =
  296. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  297. newHandler(nil, newError);
  298. } else {
  299. FIRInstanceIDTokenInfo *cachedTokenInfo =
  300. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
  301. if (cachedTokenInfo) {
  302. FIRInstanceIDAPNSInfo *optionsAPNSInfo =
  303. [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  304. // Check if APNS Info is changed
  305. if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
  306. [cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
  307. // check if token is fresh
  308. if ([cachedTokenInfo isFreshWithIID:identifier]) {
  309. newHandler(cachedTokenInfo.token, nil);
  310. return;
  311. }
  312. }
  313. }
  314. [self.tokenManager fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
  315. scope:[scope copy]
  316. instanceID:identifier
  317. options:tokenOptions
  318. handler:newHandler];
  319. }
  320. }];
  321. }];
  322. }
  323. - (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  324. scope:(NSString *)scope
  325. handler:(FIRInstanceIDDeleteTokenHandler)handler {
  326. if (!handler) {
  327. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID001,
  328. kFIRInstanceIDInvalidNilHandlerError);
  329. return;
  330. }
  331. // comparing enums to ints directly throws a warning
  332. FIRInstanceIDErrorCode noError = INT_MAX;
  333. FIRInstanceIDErrorCode errorCode = noError;
  334. if (![authorizedEntity length]) {
  335. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  336. } else if (![scope length]) {
  337. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  338. } else if (!self.installations) {
  339. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  340. }
  341. FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
  342. // If a default token is deleted successfully, reset the defaultFCMToken too.
  343. if (!error) {
  344. if ([self isDefaultTokenWithAuthorizedEntity:authorizedEntity scope:scope] ||
  345. [authorizedEntity isEqualToString:@"*"]) {
  346. self.defaultFCMToken = nil;
  347. }
  348. }
  349. dispatch_async(dispatch_get_main_queue(), ^{
  350. handler(error);
  351. });
  352. };
  353. if (errorCode != noError) {
  354. newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  355. return;
  356. }
  357. FIRInstanceID_WEAKIFY(self);
  358. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  359. [authService
  360. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  361. FIRInstanceID_STRONGIFY(self);
  362. if (error) {
  363. newHandler(error);
  364. return;
  365. }
  366. FIRInstanceID_WEAKIFY(self);
  367. [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  368. NSError *_Nullable error) {
  369. FIRInstanceID_STRONGIFY(self);
  370. if (error) {
  371. NSError *newError =
  372. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  373. newHandler(newError);
  374. } else {
  375. [self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
  376. scope:scope
  377. instanceID:identifier
  378. handler:newHandler];
  379. }
  380. }];
  381. }];
  382. }
  383. #pragma mark - Identity
  384. - (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
  385. if (!handler) {
  386. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID003,
  387. kFIRInstanceIDInvalidNilHandlerError);
  388. return;
  389. }
  390. FIRInstanceID_WEAKIFY(self);
  391. [self.installations
  392. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  393. FIRInstanceID_STRONGIFY(self);
  394. // When getID is explicitly called, trigger getToken to make sure token always exists.
  395. // This is to avoid ID conflict (ID is not checked for conflict until we generate a token)
  396. if (identifier) {
  397. [self token];
  398. }
  399. handler(identifier, error);
  400. }];
  401. }
  402. - (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
  403. if (!handler) {
  404. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
  405. kFIRInstanceIDInvalidNilHandlerError);
  406. return;
  407. }
  408. void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
  409. if ([NSThread isMainThread]) {
  410. handler(error);
  411. return;
  412. }
  413. dispatch_async(dispatch_get_main_queue(), ^{
  414. handler(error);
  415. });
  416. };
  417. if (!self.installations) {
  418. FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
  419. callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
  420. return;
  421. }
  422. FIRInstanceID_WEAKIFY(self);
  423. void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
  424. FIRInstanceID_STRONGIFY(self);
  425. if (error) {
  426. callHandlerOnMainThread(error);
  427. return;
  428. }
  429. [self deleteIdentityWithHandler:^(NSError *error) {
  430. callHandlerOnMainThread(error);
  431. }];
  432. };
  433. [self.installations
  434. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  435. FIRInstanceID_STRONGIFY(self);
  436. if (error) {
  437. NSError *newError =
  438. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  439. callHandlerOnMainThread(newError);
  440. } else {
  441. [self.tokenManager deleteAllTokensWithInstanceID:identifier handler:deleteTokensHandler];
  442. }
  443. }];
  444. }
  445. - (void)notifyIdentityReset {
  446. [self deleteIdentityWithHandler:nil];
  447. }
  448. // Delete all the local cache checkin, IID and token.
  449. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
  450. // Delete tokens.
  451. [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
  452. // Reset FCM token.
  453. self.defaultFCMToken = nil;
  454. if (deleteTokenError) {
  455. if (handler) {
  456. handler(deleteTokenError);
  457. }
  458. return;
  459. }
  460. // Delete Instance ID.
  461. [self.installations deleteWithCompletion:^(NSError *_Nullable error) {
  462. if (error) {
  463. if (handler) {
  464. handler(error);
  465. }
  466. return;
  467. }
  468. [self deleteCheckinWithHandler:^(NSError *_Nullable error) {
  469. if (error) {
  470. if (handler) {
  471. handler(error);
  472. }
  473. return;
  474. }
  475. // Only request new token if FCM auto initialization is
  476. // enabled.
  477. if ([self isFCMAutoInitEnabled]) {
  478. // Deletion succeeds! Requesting new checkin, IID and token.
  479. // TODO(chliangGoogle) see if dispatch_after is necessary
  480. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
  481. dispatch_get_main_queue(), ^{
  482. [self defaultTokenWithHandler:nil];
  483. });
  484. }
  485. if (handler) {
  486. handler(nil);
  487. }
  488. }];
  489. }];
  490. }];
  491. }
  492. #pragma mark - Checkin
  493. - (void)deleteCheckinWithHandler:(void (^)(NSError *error))handler {
  494. [self.tokenManager.authService resetCheckinWithHandler:handler];
  495. }
  496. - (BOOL)tryToLoadValidCheckinInfo {
  497. FIRInstanceIDCheckinPreferences *checkinPreferences =
  498. [self.tokenManager.authService checkinPreferences];
  499. return [checkinPreferences hasValidCheckinInfo];
  500. }
  501. - (NSString *)deviceAuthID {
  502. return [self.tokenManager.authService checkinPreferences].deviceID;
  503. }
  504. - (NSString *)secretToken {
  505. return [self.tokenManager.authService checkinPreferences].secretToken;
  506. }
  507. - (NSString *)versionInfo {
  508. return [self.tokenManager.authService checkinPreferences].versionInfo;
  509. }
  510. #pragma mark - Config
  511. + (void)load {
  512. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  513. withName:@"fire-iid"
  514. withVersion:FIRInstanceIDCurrentLibraryVersion()];
  515. }
  516. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  517. FIRComponentCreationBlock creationBlock =
  518. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  519. // InstanceID only works with the default app.
  520. if (!container.app.isDefaultApp) {
  521. // Only configure for the default FIRApp.
  522. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
  523. @"Firebase Instance ID only works with the default app.");
  524. return nil;
  525. }
  526. // Ensure it's cached so it returns the same instance every time instanceID is called.
  527. *isCacheable = YES;
  528. FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
  529. [instanceID start];
  530. [instanceID configureInstanceIDWithOptions:container.app.options];
  531. return instanceID;
  532. };
  533. FIRComponent *instanceIDProvider =
  534. [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
  535. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  536. dependencies:@[]
  537. creationBlock:creationBlock];
  538. return @[ instanceIDProvider ];
  539. }
  540. - (void)configureInstanceIDWithOptions:(FIROptions *)options {
  541. NSString *GCMSenderID = options.GCMSenderID;
  542. if (!GCMSenderID.length) {
  543. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
  544. @"Firebase not set up correctly, nil or empty senderID.");
  545. [NSException raise:kFIRIIDErrorDomain
  546. format:@"Could not configure Firebase InstanceID. GCMSenderID must not be nil or "
  547. @"empty."];
  548. }
  549. self.fcmSenderID = GCMSenderID;
  550. self.firebaseAppID = options.googleAppID;
  551. [self updateFirebaseInstallationID];
  552. // FCM generates a FCM token during app start for sending push notification to device.
  553. // This is not needed for app extension except for watch.
  554. #if TARGET_OS_WATCH
  555. [self didCompleteConfigure];
  556. #else
  557. if (![GULAppEnvironmentUtil isAppExtension]) {
  558. [self didCompleteConfigure];
  559. }
  560. #endif
  561. }
  562. // This is used to start any operations when we receive FirebaseSDK setup notification
  563. // from FIRCore.
  564. - (void)didCompleteConfigure {
  565. NSString *cachedToken = [self cachedTokenIfAvailable];
  566. // When there is a cached token, do the token refresh.
  567. if (cachedToken) {
  568. // Clean up expired tokens by checking the token refresh policy.
  569. [self.installations
  570. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  571. if ([self.tokenManager checkTokenRefreshPolicyWithIID:identifier]) {
  572. // Default token is expired, fetch default token from server.
  573. [self defaultTokenWithHandler:nil];
  574. }
  575. // Notify FCM with the default token.
  576. self.defaultFCMToken = [self token];
  577. }];
  578. } else if ([self isFCMAutoInitEnabled]) {
  579. // When there is no cached token, must check auto init is enabled.
  580. // If it's disabled, don't initiate token generation/refresh.
  581. // If no cache token and auto init is enabled, fetch a token from server.
  582. [self defaultTokenWithHandler:nil];
  583. // Notify FCM with the default token.
  584. self.defaultFCMToken = [self token];
  585. }
  586. // ONLY checkin when auto data collection is turned on.
  587. if ([self isFCMAutoInitEnabled]) {
  588. [self.tokenManager.authService scheduleCheckin:YES];
  589. }
  590. }
  591. - (BOOL)isFCMAutoInitEnabled {
  592. Class messagingClass = NSClassFromString(kFIRInstanceIDFCMSDKClassString);
  593. // Firebase Messaging is not installed, auto init should be disabled since it's for FCM.
  594. if (!messagingClass) {
  595. return NO;
  596. }
  597. // Messaging doesn't have the class method, auto init should be enabled since FCM exists.
  598. SEL autoInitSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorAutoInitEnabled);
  599. if (![messagingClass respondsToSelector:autoInitSelector]) {
  600. return YES;
  601. }
  602. // Get the autoInitEnabled class method.
  603. IMP isAutoInitEnabledIMP = [messagingClass methodForSelector:autoInitSelector];
  604. BOOL(*isAutoInitEnabled)
  605. (Class, SEL, GULUserDefaults *) = (BOOL(*)(id, SEL, GULUserDefaults *))isAutoInitEnabledIMP;
  606. // Check FCM's isAutoInitEnabled property.
  607. return isAutoInitEnabled(messagingClass, autoInitSelector,
  608. [GULUserDefaults standardUserDefaults]);
  609. }
  610. // Actually makes InstanceID instantiate both the IID and Token-related subsystems.
  611. - (void)start {
  612. if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
  613. [FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
  614. }
  615. [self setupTokenManager];
  616. self.installations = [FIRInstallations installations];
  617. [self setupNotificationListeners];
  618. }
  619. // Creates the token manager, which is used for fetching, caching, and retrieving tokens.
  620. - (void)setupTokenManager {
  621. self.tokenManager = [[FIRInstanceIDTokenManager alloc] init];
  622. }
  623. - (void)setupNotificationListeners {
  624. // To prevent double notifications remove observer from all events during setup.
  625. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  626. [center removeObserver:self];
  627. [center addObserver:self
  628. selector:@selector(notifyIdentityReset)
  629. name:kFIRInstanceIDIdentityInvalidatedNotification
  630. object:nil];
  631. [center addObserver:self
  632. selector:@selector(notifyAPNSTokenIsSet:)
  633. name:kFIRInstanceIDAPNSTokenNotification
  634. object:nil];
  635. [self observeFirebaseInstallationIDChanges];
  636. [self observeFirebaseMessagingTokenChanges];
  637. }
  638. #pragma mark - Private Helpers
  639. /// Maximum retry count to fetch the default token.
  640. + (int64_t)maxRetryCountForDefaultToken {
  641. return kMaxRetryCountForDefaultToken;
  642. }
  643. /// Minimum interval in seconds between retries to fetch the default token.
  644. + (int64_t)minIntervalForDefaultTokenRetry {
  645. return kMinRetryIntervalForDefaultTokenInSeconds;
  646. }
  647. /// Maximum retry interval between retries to fetch default token.
  648. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds {
  649. return kMaxRetryIntervalForDefaultTokenInSeconds;
  650. }
  651. - (NSInteger)retryIntervalToFetchDefaultToken {
  652. if (self.retryCountForDefaultToken >= [[self class] maxRetryCountForDefaultToken]) {
  653. return (NSInteger)[[self class] maxRetryIntervalForDefaultTokenInSeconds];
  654. }
  655. // exponential backoff with a fixed initial retry time
  656. // 11s, 22s, 44s, 88s ...
  657. int64_t minInterval = [[self class] minIntervalForDefaultTokenRetry];
  658. return (NSInteger)MIN(
  659. (1 << self.retryCountForDefaultToken) + minInterval * self.retryCountForDefaultToken,
  660. kMaxRetryIntervalForDefaultTokenInSeconds);
  661. }
  662. - (void)defaultTokenWithHandler:(nullable FIRInstanceIDTokenHandler)aHandler {
  663. [self defaultTokenWithRetry:NO handler:aHandler];
  664. }
  665. /**
  666. * @param retry Indicates if the method is called to perform a retry after a failed attempt.
  667. * If `YES`, then actual token request will be performed even if `self.defaultTokenFetchHandler !=
  668. * nil`
  669. */
  670. - (void)defaultTokenWithRetry:(BOOL)retry handler:(nullable FIRInstanceIDTokenHandler)aHandler {
  671. BOOL shouldPerformRequest = retry || self.defaultTokenFetchHandler == nil;
  672. if (!self.defaultTokenFetchHandler) {
  673. self.defaultTokenFetchHandler = [[FIRInstanceIDCombinedHandler<NSString *> alloc] init];
  674. }
  675. if (aHandler) {
  676. [self.defaultTokenFetchHandler addHandler:aHandler];
  677. }
  678. if (!shouldPerformRequest) {
  679. return;
  680. }
  681. NSDictionary *instanceIDOptions = @{};
  682. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  683. if (hasFirebaseMessaging) {
  684. instanceIDOptions = [self defaultTokenOptions];
  685. }
  686. FIRInstanceID_WEAKIFY(self);
  687. FIRInstanceIDTokenHandler newHandler = ^void(NSString *token, NSError *error) {
  688. FIRInstanceID_STRONGIFY(self);
  689. if (error) {
  690. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID009,
  691. @"Failed to fetch default token %@", error);
  692. // This notification can be sent multiple times since we can't guarantee success at any point
  693. // of time.
  694. NSNotification *tokenFetchFailNotification =
  695. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenFailNotification
  696. object:[error copy]];
  697. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenFetchFailNotification
  698. postingStyle:NSPostASAP];
  699. self.retryCountForDefaultToken = (NSInteger)MIN(self.retryCountForDefaultToken + 1,
  700. [[self class] maxRetryCountForDefaultToken]);
  701. // Do not retry beyond the maximum limit.
  702. if (self.retryCountForDefaultToken < [[self class] maxRetryCountForDefaultToken]) {
  703. NSInteger retryInterval = [self retryIntervalToFetchDefaultToken];
  704. [self retryGetDefaultTokenAfter:retryInterval];
  705. } else {
  706. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID007,
  707. @"Failed to retrieve the default FCM token after %ld retries",
  708. (long)self.retryCountForDefaultToken);
  709. [self performDefaultTokenHandlerWithToken:nil error:error];
  710. }
  711. } else {
  712. // If somebody updated IID with APNS token while our initial request did not have it
  713. // set we need to update it on the server.
  714. NSData *deviceTokenInRequest = instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSKey];
  715. BOOL isSandboxInRequest =
  716. [instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue];
  717. // Note that APNSTupleStringInRequest will be nil if deviceTokenInRequest is nil
  718. NSString *APNSTupleStringInRequest = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
  719. deviceTokenInRequest, isSandboxInRequest);
  720. // If the APNs value either remained nil, or was the same non-nil value, the APNs value
  721. // did not change.
  722. BOOL APNSRemainedSameDuringFetch =
  723. (self.APNSTupleString == nil && APNSTupleStringInRequest == nil) ||
  724. ([self.APNSTupleString isEqualToString:APNSTupleStringInRequest]);
  725. if (!APNSRemainedSameDuringFetch && hasFirebaseMessaging) {
  726. // APNs value did change mid-fetch, so the token should be re-fetched with the current APNs
  727. // value.
  728. [self retryGetDefaultTokenAfter:0];
  729. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
  730. @"Received APNS token while fetching default token. "
  731. @"Refetching default token.");
  732. // Do not notify and handle completion handler since this is a retry.
  733. // Simply return.
  734. return;
  735. } else {
  736. FIRInstanceIDLoggerInfo(kFIRInstanceIDMessageCodeInstanceID010,
  737. @"Successfully fetched default token.");
  738. }
  739. // Post the required notifications if somebody is waiting.
  740. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID008, @"Got default token %@",
  741. token);
  742. // Update default FCM token, this method also triggers sending notification if token has
  743. // changed.
  744. self.defaultFCMToken = token;
  745. [self performDefaultTokenHandlerWithToken:token error:nil];
  746. }
  747. };
  748. [self tokenWithAuthorizedEntity:self.fcmSenderID
  749. scope:kFIRInstanceIDDefaultTokenScope
  750. options:instanceIDOptions
  751. handler:newHandler];
  752. }
  753. /**
  754. *
  755. */
  756. - (void)performDefaultTokenHandlerWithToken:(NSString *)token error:(NSError *)error {
  757. if (!self.defaultTokenFetchHandler) {
  758. return;
  759. }
  760. [self.defaultTokenFetchHandler combinedHandler](token, error);
  761. self.defaultTokenFetchHandler = nil;
  762. }
  763. - (void)retryGetDefaultTokenAfter:(NSTimeInterval)retryInterval {
  764. FIRInstanceID_WEAKIFY(self);
  765. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)),
  766. dispatch_get_main_queue(), ^{
  767. FIRInstanceID_STRONGIFY(self);
  768. // Pass nil: no new handlers to be added, currently existing handlers
  769. // will be called
  770. [self defaultTokenWithRetry:YES handler:nil];
  771. });
  772. }
  773. - (BOOL)isDefaultTokenWithAuthorizedEntity:(NSString *)authorizedEntity scope:(NSString *)scope {
  774. return [authorizedEntity isEqualToString:self.fcmSenderID] &&
  775. [scope isEqualToString:kFIRInstanceIDDefaultTokenScope];
  776. }
  777. #pragma mark - APNS Token
  778. // This should only be triggered from FCM.
  779. - (void)notifyAPNSTokenIsSet:(NSNotification *)notification {
  780. NSData *token = notification.object;
  781. if (!token || ![token isKindOfClass:[NSData class]]) {
  782. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal002, @"Invalid APNS token type %@",
  783. NSStringFromClass([notification.object class]));
  784. return;
  785. }
  786. NSInteger type = [notification.userInfo[kFIRInstanceIDAPNSTokenType] integerValue];
  787. // The APNS token is being added, or has changed (rare)
  788. if ([self.apnsTokenData isEqualToData:token]) {
  789. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID011,
  790. @"Trying to reset APNS token to the same value. Will return");
  791. return;
  792. }
  793. // Use this token type for when we have to automatically fetch tokens in the future
  794. self.apnsTokenType = type;
  795. BOOL isSandboxApp = (type == FIRInstanceIDAPNSTokenTypeSandbox);
  796. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  797. isSandboxApp = [self isSandboxApp];
  798. }
  799. self.apnsTokenData = [token copy];
  800. self.APNSTupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(token, isSandboxApp);
  801. // Pro-actively invalidate the default token, if the APNs change makes it
  802. // invalid. Previously, we invalidated just before fetching the token.
  803. NSArray<FIRInstanceIDTokenInfo *> *invalidatedTokens =
  804. [self.tokenManager updateTokensToAPNSDeviceToken:self.apnsTokenData isSandbox:isSandboxApp];
  805. // Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
  806. // they are up-to-date.
  807. if (invalidatedTokens.count > 0) {
  808. FIRInstanceID_WEAKIFY(self);
  809. [self.installations
  810. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  811. FIRInstanceID_STRONGIFY(self);
  812. if (self == nil) {
  813. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID017,
  814. @"Instance ID shut down during token reset. Aborting");
  815. return;
  816. }
  817. if (self.apnsTokenData == nil) {
  818. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID018,
  819. @"apnsTokenData was set to nil during token reset. Aborting");
  820. return;
  821. }
  822. NSMutableDictionary *tokenOptions = [@{
  823. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  824. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
  825. } mutableCopy];
  826. if (self.firebaseAppID) {
  827. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  828. }
  829. for (FIRInstanceIDTokenInfo *tokenInfo in invalidatedTokens) {
  830. if ([tokenInfo.token isEqualToString:self.defaultFCMToken]) {
  831. // We will perform a special fetch for the default FCM token, so that the delegate
  832. // methods are called. For all others, we will do an internal re-fetch.
  833. [self defaultTokenWithHandler:nil];
  834. } else {
  835. [self.tokenManager fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
  836. scope:tokenInfo.scope
  837. instanceID:identifier
  838. options:tokenOptions
  839. handler:^(NSString *_Nullable token,
  840. NSError *_Nullable error){
  841. }];
  842. }
  843. }
  844. }];
  845. }
  846. }
  847. - (BOOL)isSandboxApp {
  848. static BOOL isSandboxApp = YES;
  849. static dispatch_once_t onceToken;
  850. dispatch_once(&onceToken, ^{
  851. isSandboxApp = ![self isProductionApp];
  852. });
  853. return isSandboxApp;
  854. }
  855. - (BOOL)isProductionApp {
  856. const BOOL defaultAppTypeProd = YES;
  857. NSError *error = nil;
  858. if ([GULAppEnvironmentUtil isSimulator]) {
  859. [self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
  860. @"Use prod profile by default."];
  861. return defaultAppTypeProd;
  862. }
  863. if ([GULAppEnvironmentUtil isFromAppStore]) {
  864. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  865. return defaultAppTypeProd;
  866. }
  867. #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
  868. NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
  869. stringByAppendingPathComponent:@"embedded.provisionprofile"];
  870. #elif TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  871. NSString *path = [[[NSBundle mainBundle] bundlePath]
  872. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  873. #endif
  874. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
  875. // Distributed via TestFlight
  876. return defaultAppTypeProd;
  877. }
  878. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  879. if (!profileData.length || error) {
  880. NSString *errorString =
  881. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  882. [self logAPNSConfigurationError:errorString];
  883. return defaultAppTypeProd;
  884. }
  885. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  886. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  887. // ASCII. Replace any 0s or invalid characters in the input.
  888. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  889. for (int i = 0; i < profileData.length; i++) {
  890. uint8_t currentByte = profileBytes[i];
  891. if (!currentByte || currentByte > 127) {
  892. profileBytes[i] = '.';
  893. }
  894. }
  895. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  896. length:profileData.length
  897. encoding:NSASCIIStringEncoding
  898. freeWhenDone:NO];
  899. if (error || !embeddedProfile.length) {
  900. NSString *errorString =
  901. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  902. [self logAPNSConfigurationError:errorString];
  903. return defaultAppTypeProd;
  904. }
  905. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  906. NSString *plistContents;
  907. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  908. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  909. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  910. }
  911. }
  912. if (!plistContents.length) {
  913. return defaultAppTypeProd;
  914. }
  915. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  916. if (!data.length) {
  917. [self logAPNSConfigurationError:@"Couldn't read plist fetched from embedded mobileprovision"];
  918. return defaultAppTypeProd;
  919. }
  920. NSError *plistMapError;
  921. id plistData = [NSPropertyListSerialization propertyListWithData:data
  922. options:NSPropertyListImmutable
  923. format:nil
  924. error:&plistMapError];
  925. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  926. NSString *errorString =
  927. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  928. plistMapError.localizedDescription];
  929. [self logAPNSConfigurationError:errorString];
  930. return defaultAppTypeProd;
  931. }
  932. NSDictionary *plistMap = (NSDictionary *)plistData;
  933. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  934. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID012,
  935. @"Provisioning profile has specifically provisioned devices, "
  936. @"most likely a Dev profile.");
  937. }
  938. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  939. NSString *debugString __unused =
  940. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  941. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID013, @"%@", debugString);
  942. // No aps-environment in the profile.
  943. if (!apsEnvironment.length) {
  944. [self logAPNSConfigurationError:@"No aps-environment set. If testing on a device APNS is not "
  945. @"correctly configured. Please recheck your provisioning "
  946. @"profiles. If testing on a simulator this is fine since APNS "
  947. @"doesn't work on the simulator."];
  948. return defaultAppTypeProd;
  949. }
  950. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  951. return NO;
  952. }
  953. return defaultAppTypeProd;
  954. }
  955. /// Log error messages only when Messaging exists in the pod.
  956. - (void)logAPNSConfigurationError:(NSString *)errorString {
  957. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  958. if (hasFirebaseMessaging) {
  959. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID014, @"%@", errorString);
  960. } else {
  961. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID015, @"%@", errorString);
  962. }
  963. }
  964. #pragma mark - Sync InstanceID
  965. - (void)updateFirebaseInstallationID {
  966. FIRInstanceID_WEAKIFY(self);
  967. [self.installations
  968. installationIDWithCompletion:^(NSString *_Nullable installationID, NSError *_Nullable error) {
  969. FIRInstanceID_STRONGIFY(self);
  970. self.firebaseInstallationsID = installationID;
  971. }];
  972. }
  973. - (void)installationIDDidChangeNotificationReceived:(NSNotification *)notification {
  974. NSString *installationAppID =
  975. notification.userInfo[kFIRInstallationIDDidChangeNotificationAppNameKey];
  976. if ([installationAppID isKindOfClass:[NSString class]] &&
  977. [installationAppID isEqual:self.firebaseAppID]) {
  978. [self updateFirebaseInstallationID];
  979. }
  980. }
  981. - (void)observeFirebaseInstallationIDChanges {
  982. [[NSNotificationCenter defaultCenter] removeObserver:self
  983. name:FIRInstallationIDDidChangeNotification
  984. object:nil];
  985. [[NSNotificationCenter defaultCenter]
  986. addObserver:self
  987. selector:@selector(installationIDDidChangeNotificationReceived:)
  988. name:FIRInstallationIDDidChangeNotification
  989. object:nil];
  990. }
  991. - (void)observeFirebaseMessagingTokenChanges {
  992. [[NSNotificationCenter defaultCenter]
  993. removeObserver:self
  994. name:kFIRInstanceIDMessagingUpdateTokenNotification
  995. object:nil];
  996. [[NSNotificationCenter defaultCenter]
  997. addObserver:self
  998. selector:@selector(messagingTokenDidChangeNotificationReceived:)
  999. name:kFIRInstanceIDMessagingUpdateTokenNotification
  1000. object:nil];
  1001. }
  1002. - (void)messagingTokenDidChangeNotificationReceived:(NSNotification *)notification {
  1003. NSString *tokenUpdatedFromMessaging = notification.object;
  1004. if (!tokenUpdatedFromMessaging || [tokenUpdatedFromMessaging isKindOfClass:[NSString class]]) {
  1005. self.defaultFCMToken = tokenUpdatedFromMessaging;
  1006. [self.tokenManager saveDefaultToken:tokenUpdatedFromMessaging
  1007. withOptions:[self defaultTokenOptions]];
  1008. }
  1009. }
  1010. - (NSDictionary *)defaultTokenOptions {
  1011. NSDictionary *tokenOptions = @{};
  1012. if (self.apnsTokenData) {
  1013. BOOL isSandboxApp = (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeSandbox);
  1014. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  1015. isSandboxApp = [self isSandboxApp];
  1016. }
  1017. tokenOptions = @{
  1018. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  1019. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp),
  1020. };
  1021. }
  1022. return tokenOptions;
  1023. }
  1024. @end