FIRMessaging.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /*
  2. * Copyright 2017 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. #if !__has_feature(objc_arc)
  17. #error FIRMessagingLib should be compiled with ARC.
  18. #endif
  19. #import "FirebaseMessaging/Sources/Public/FirebaseMessaging/FIRMessaging.h"
  20. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  21. #import <GoogleUtilities/GULReachabilityChecker.h>
  22. #import <GoogleUtilities/GULUserDefaults.h>
  23. #import "Firebase/InstanceID/Private/FIRInstanceID_Private.h"
  24. #import "Firebase/InstanceID/Public/FirebaseInstanceID.h"
  25. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  26. #import "FirebaseMessaging/Sources/Interop/FIRMessagingInterop.h"
  27. #import "FirebaseMessaging/Sources/Public/FirebaseMessaging/FIRMessagingExtensionHelper.h"
  28. #import "Interop/Analytics/Public/FIRAnalyticsInterop.h"
  29. #import "FirebaseMessaging/Sources/FIRMessagingAnalytics.h"
  30. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  31. #import "FirebaseMessaging/Sources/FIRMessagingContextManagerService.h"
  32. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  33. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  34. #import "FirebaseMessaging/Sources/FIRMessagingPubSub.h"
  35. #import "FirebaseMessaging/Sources/FIRMessagingRemoteNotificationsProxy.h"
  36. #import "FirebaseMessaging/Sources/FIRMessagingRmqManager.h"
  37. #import "FirebaseMessaging/Sources/FIRMessagingSyncMessageManager.h"
  38. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  39. #import "FirebaseMessaging/Sources/FIRMessagingVersionUtilities.h"
  40. #import "FirebaseMessaging/Sources/FIRMessaging_Private.h"
  41. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  42. static NSString *const kFIRMessagingMessageViaAPNSRootKey = @"aps";
  43. static NSString *const kFIRMessagingReachabilityHostname = @"www.google.com";
  44. static NSString *const kFIRMessagingDefaultTokenScope = @"*";
  45. static NSString *const kFIRMessagingFCMTokenFetchAPNSOption = @"apns_token";
  46. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  47. const NSNotificationName FIRMessagingRegistrationTokenRefreshedNotification =
  48. @"com.firebase.messaging.notif.fcm-token-refreshed";
  49. #else
  50. NSString *const FIRMessagingRegistrationTokenRefreshedNotification =
  51. @"com.firebase.messaging.notif.fcm-token-refreshed";
  52. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  53. NSString *const kFIRMessagingUserDefaultsKeyAutoInitEnabled =
  54. @"com.firebase.messaging.auto-init.enabled"; // Auto Init Enabled key stored in NSUserDefaults
  55. NSString *const kFIRMessagingAPNSTokenType =
  56. @"APNSTokenType"; // APNS Token type key stored in user info.
  57. NSString *const kFIRMessagingPlistAutoInitEnabled =
  58. @"FirebaseMessagingAutoInitEnabled"; // Auto Init Enabled key stored in Info.plist
  59. const BOOL FIRMessagingIsAPNSSyncMessage(NSDictionary *message) {
  60. if ([message[kFIRMessagingMessageViaAPNSRootKey] isKindOfClass:[NSDictionary class]]) {
  61. NSDictionary *aps = message[kFIRMessagingMessageViaAPNSRootKey];
  62. if (aps && [aps isKindOfClass:[NSDictionary class]]) {
  63. return [aps[kFIRMessagingMessageAPNSContentAvailableKey] boolValue];
  64. }
  65. }
  66. return NO;
  67. }
  68. BOOL FIRMessagingIsContextManagerMessage(NSDictionary *message) {
  69. return [FIRMessagingContextManagerService isContextManagerMessage:message];
  70. }
  71. @interface FIRMessagingMessageInfo ()
  72. @property(nonatomic, readwrite, assign) FIRMessagingMessageStatus status;
  73. @end
  74. @implementation FIRMessagingMessageInfo
  75. - (instancetype)init {
  76. FIRMessagingInvalidateInitializer();
  77. }
  78. - (instancetype)initWithStatus:(FIRMessagingMessageStatus)status {
  79. self = [super init];
  80. if (self) {
  81. _status = status;
  82. }
  83. return self;
  84. }
  85. @end
  86. @interface FIRMessaging () <GULReachabilityDelegate>
  87. // FIRApp properties
  88. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  89. @property(nonatomic, readwrite, strong) NSString *defaultFcmToken;
  90. @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
  91. @property(nonatomic, readwrite, strong) FIRMessagingClient *client;
  92. @property(nonatomic, readwrite, strong) GULReachabilityChecker *reachability;
  93. @property(nonatomic, readwrite, strong) FIRMessagingPubSub *pubsub;
  94. @property(nonatomic, readwrite, strong) FIRMessagingRmqManager *rmq2Manager;
  95. @property(nonatomic, readwrite, strong) FIRMessagingSyncMessageManager *syncMessageManager;
  96. @property(nonatomic, readwrite, strong) GULUserDefaults *messagingUserDefaults;
  97. /// Message ID's logged for analytics. This prevents us from logging the same message twice
  98. /// which can happen if the user inadvertently calls `appDidReceiveMessage` along with us
  99. /// calling it implicitly during swizzling.
  100. @property(nonatomic, readwrite, strong) NSMutableSet *loggedMessageIDs;
  101. @property(nonatomic, readwrite, strong) id<FIRAnalyticsInterop> _Nullable analytics;
  102. @end
  103. @interface FIRMessaging () <FIRMessagingInterop, FIRLibrary>
  104. @end
  105. @implementation FIRMessaging
  106. + (FIRMessaging *)messaging {
  107. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  108. id<FIRMessagingInterop> instance = FIR_COMPONENT(FIRMessagingInterop, defaultApp.container);
  109. // We know the instance coming from the container is a FIRMessaging instance, cast it and move on.
  110. return (FIRMessaging *)instance;
  111. }
  112. + (FIRMessagingExtensionHelper *)extensionHelper {
  113. static dispatch_once_t once;
  114. static FIRMessagingExtensionHelper *extensionHelper;
  115. dispatch_once(&once, ^{
  116. extensionHelper = [[FIRMessagingExtensionHelper alloc] init];
  117. });
  118. return extensionHelper;
  119. }
  120. - (instancetype)initWithAnalytics:(nullable id<FIRAnalyticsInterop>)analytics
  121. withInstanceID:(FIRInstanceID *)instanceID
  122. withUserDefaults:(GULUserDefaults *)defaults {
  123. self = [super init];
  124. if (self != nil) {
  125. _loggedMessageIDs = [NSMutableSet set];
  126. _instanceID = instanceID;
  127. _messagingUserDefaults = defaults;
  128. _analytics = analytics;
  129. }
  130. return self;
  131. }
  132. - (void)dealloc {
  133. [self.reachability stop];
  134. [[NSNotificationCenter defaultCenter] removeObserver:self];
  135. [self teardown];
  136. }
  137. #pragma mark - Config
  138. + (void)load {
  139. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  140. withName:@"fire-fcm"
  141. withVersion:FIRMessagingCurrentLibraryVersion()];
  142. }
  143. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  144. FIRDependency *analyticsDep = [FIRDependency dependencyWithProtocol:@protocol(FIRAnalyticsInterop)
  145. isRequired:NO];
  146. FIRComponentCreationBlock creationBlock =
  147. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  148. if (!container.app.isDefaultApp) {
  149. // Only start for the default FIRApp.
  150. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeFIRApp001,
  151. @"Firebase Messaging only works with the default app.");
  152. return nil;
  153. }
  154. // Ensure it's cached so it returns the same instance every time messaging is called.
  155. *isCacheable = YES;
  156. id<FIRAnalyticsInterop> analytics = FIR_COMPONENT(FIRAnalyticsInterop, container);
  157. FIRMessaging *messaging =
  158. [[FIRMessaging alloc] initWithAnalytics:analytics
  159. withInstanceID:[FIRInstanceID instanceID]
  160. withUserDefaults:[GULUserDefaults standardUserDefaults]];
  161. [messaging start];
  162. [messaging configureNotificationSwizzlingIfEnabled];
  163. return messaging;
  164. };
  165. FIRComponent *messagingProvider =
  166. [FIRComponent componentWithProtocol:@protocol(FIRMessagingInterop)
  167. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  168. dependencies:@[ analyticsDep ]
  169. creationBlock:creationBlock];
  170. return @[ messagingProvider ];
  171. }
  172. - (void)configureNotificationSwizzlingIfEnabled {
  173. // Swizzle remote-notification-related methods (app delegate and UNUserNotificationCenter)
  174. if ([FIRMessagingRemoteNotificationsProxy canSwizzleMethods]) {
  175. NSString *docsURLString = @"https://firebase.google.com/docs/cloud-messaging/ios/client"
  176. @"#method_swizzling_in_firebase_messaging";
  177. FIRMessagingLoggerNotice(kFIRMessagingMessageCodeFIRApp000,
  178. @"FIRMessaging Remote Notifications proxy enabled, will swizzle "
  179. @"remote notification receiver handlers. If you'd prefer to manually "
  180. @"integrate Firebase Messaging, add \"%@\" to your Info.plist, "
  181. @"and set it to NO. Follow the instructions at:\n%@\nto ensure "
  182. @"proper integration.",
  183. kFIRMessagingRemoteNotificationsProxyEnabledInfoPlistKey,
  184. docsURLString);
  185. [[FIRMessagingRemoteNotificationsProxy sharedProxy] swizzleMethodsIfPossible];
  186. }
  187. }
  188. - (void)start {
  189. [self setupFileManagerSubDirectory];
  190. [self setupNotificationListeners];
  191. [self setupTopics];
  192. #if !TARGET_OS_WATCH
  193. // Print the library version for logging.
  194. NSString *currentLibraryVersion = FIRMessagingCurrentLibraryVersion();
  195. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessagingPrintLibraryVersion,
  196. @"FIRMessaging library version %@", currentLibraryVersion);
  197. NSString *hostname = kFIRMessagingReachabilityHostname;
  198. self.reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self
  199. withHost:hostname];
  200. [self.reachability start];
  201. // setup FIRMessaging objects
  202. [self setupRmqManager];
  203. [self setupSyncMessageManager];
  204. #endif
  205. }
  206. - (void)setupFileManagerSubDirectory {
  207. if (![[self class] hasSubDirectory:kFIRMessagingSubDirectoryName]) {
  208. [[self class] createSubDirectory:kFIRMessagingSubDirectoryName];
  209. }
  210. }
  211. - (void)setupNotificationListeners {
  212. // To prevent multiple notifications remove self as observer for all events.
  213. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  214. [center removeObserver:self];
  215. [center addObserver:self
  216. selector:@selector(defaultInstanceIDTokenWasRefreshed:)
  217. name:kFIRMessagingRegistrationTokenRefreshNotification
  218. object:nil];
  219. }
  220. - (void)setupRmqManager {
  221. self.rmq2Manager = [[FIRMessagingRmqManager alloc] initWithDatabaseName:@"rmq2"];
  222. [self.rmq2Manager loadRmqId];
  223. }
  224. - (void)setupTopics {
  225. self.pubsub = [[FIRMessagingPubSub alloc] init];
  226. }
  227. - (void)setupSyncMessageManager {
  228. self.syncMessageManager =
  229. [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager];
  230. [self.syncMessageManager removeExpiredSyncMessages];
  231. }
  232. - (void)teardown {
  233. self.pubsub = nil;
  234. self.syncMessageManager = nil;
  235. self.rmq2Manager = nil;
  236. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown");
  237. }
  238. #pragma mark - Messages
  239. - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message {
  240. if (!message.count) {
  241. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown];
  242. }
  243. // For downstream messages that go via MCS we should strip out this key before sending
  244. // the message to the device.
  245. BOOL isOldMessage = NO;
  246. NSString *messageID = message[kFIRMessagingMessageIDKey];
  247. if (messageID.length) {
  248. [self.rmq2Manager saveS2dMessageWithRmqId:messageID];
  249. BOOL isSyncMessage = FIRMessagingIsAPNSSyncMessage(message);
  250. if (isSyncMessage) {
  251. isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message];
  252. }
  253. // Prevent duplicates by keeping a cache of all the logged messages during each session.
  254. // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with
  255. // us swizzling their implementation to call the same method implicitly.
  256. // We need to rule out the contextual message because it shares the same message ID
  257. // as the local notification it will schedule. And because it is also a APNSSync message
  258. // its duplication is already checked previously.
  259. if (!isOldMessage && !FIRMessagingIsContextManagerMessage(message)) {
  260. isOldMessage = [self.loggedMessageIDs containsObject:messageID];
  261. if (!isOldMessage) {
  262. [self.loggedMessageIDs addObject:messageID];
  263. }
  264. }
  265. }
  266. if (!isOldMessage) {
  267. [FIRMessagingAnalytics logMessage:message toAnalytics:_analytics];
  268. [self handleContextManagerMessage:message];
  269. [self handleIncomingLinkIfNeededFromMessage:message];
  270. }
  271. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew];
  272. }
  273. - (BOOL)handleContextManagerMessage:(NSDictionary *)message {
  274. if (FIRMessagingIsContextManagerMessage(message)) {
  275. return [FIRMessagingContextManagerService handleContextManagerMessage:message];
  276. }
  277. return NO;
  278. }
  279. - (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message {
  280. #if TARGET_OS_IOS || TARGET_OS_TV
  281. NSURL *url = [self linkURLFromMessage:message];
  282. if (url == nil) {
  283. return;
  284. }
  285. if (![NSThread isMainThread]) {
  286. dispatch_async(dispatch_get_main_queue(), ^{
  287. [self handleIncomingLinkIfNeededFromMessage:message];
  288. });
  289. return;
  290. }
  291. UIApplication *application = [GULAppDelegateSwizzler sharedApplication];
  292. if (!application) {
  293. return;
  294. }
  295. id<UIApplicationDelegate> appDelegate = application.delegate;
  296. SEL continueUserActivitySelector = @selector(application:
  297. continueUserActivity:restorationHandler:);
  298. SEL openURLWithOptionsSelector = @selector(application:openURL:options:);
  299. SEL openURLWithSourceApplicationSelector = @selector(application:
  300. openURL:sourceApplication:annotation:);
  301. #if TARGET_OS_IOS
  302. SEL handleOpenURLSelector = @selector(application:handleOpenURL:);
  303. #endif
  304. // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or
  305. // not the actual application has implemented
  306. // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user
  307. // if they haven't implemented it.
  308. if ([NSUserActivity class] != nil &&
  309. [appDelegate respondsToSelector:continueUserActivitySelector]) {
  310. NSUserActivity *userActivity =
  311. [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
  312. userActivity.webpageURL = url;
  313. [appDelegate application:application
  314. continueUserActivity:userActivity
  315. restorationHandler:^(NSArray *_Nullable restorableObjects){
  316. // Do nothing, as we don't support the app calling this block
  317. }];
  318. } else if ([appDelegate respondsToSelector:openURLWithOptionsSelector]) {
  319. #pragma clang diagnostic push
  320. #pragma clang diagnostic ignored "-Wunguarded-availability"
  321. [appDelegate application:application openURL:url options:@{}];
  322. #pragma clang diagnostic pop
  323. // Similarly, |application:openURL:sourceApplication:annotation:| will also always be called,
  324. // due to the default swizzling done by FIRAAppDelegateProxy in Firebase Analytics
  325. } else if ([appDelegate respondsToSelector:openURLWithSourceApplicationSelector]) {
  326. #if TARGET_OS_IOS
  327. #pragma clang diagnostic push
  328. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  329. [appDelegate application:application
  330. openURL:url
  331. sourceApplication:FIRMessagingAppIdentifier()
  332. annotation:@{}];
  333. #pragma clang diagnostic pop
  334. } else if ([appDelegate respondsToSelector:handleOpenURLSelector]) {
  335. #pragma clang diagnostic push
  336. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  337. [appDelegate application:application handleOpenURL:url];
  338. #pragma clang diagnostic pop
  339. #endif
  340. }
  341. #endif
  342. }
  343. - (NSURL *)linkURLFromMessage:(NSDictionary *)message {
  344. NSString *urlString = message[kFIRMessagingMessageLinkKey];
  345. if (urlString == nil || ![urlString isKindOfClass:[NSString class]] || urlString.length == 0) {
  346. return nil;
  347. }
  348. NSURL *url = [NSURL URLWithString:urlString];
  349. return url;
  350. }
  351. #pragma mark - APNS
  352. - (NSData *)APNSToken {
  353. return self.apnsTokenData;
  354. }
  355. - (void)setAPNSToken:(NSData *)APNSToken {
  356. [self setAPNSToken:APNSToken type:FIRMessagingAPNSTokenTypeUnknown];
  357. }
  358. - (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type {
  359. if ([apnsToken isEqual:self.apnsTokenData]) {
  360. return;
  361. }
  362. self.apnsTokenData = apnsToken;
  363. // Notify InstanceID that APNS Token has been set.
  364. NSDictionary *userInfo = @{kFIRMessagingAPNSTokenType : @(type)};
  365. NSNotification *notification =
  366. [NSNotification notificationWithName:kFIRMessagingAPNSTokenNotification
  367. object:[apnsToken copy]
  368. userInfo:userInfo];
  369. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  370. }
  371. #pragma mark - FCM
  372. - (BOOL)isAutoInitEnabled {
  373. // Defer to the class method since we're just reading from regular userDefaults and we need to
  374. // read this from IID without instantiating the Messaging singleton.
  375. return [[self class] isAutoInitEnabledWithUserDefaults:_messagingUserDefaults];
  376. }
  377. /// Checks if Messaging auto-init is enabled in the user defaults instance passed in. This is
  378. /// exposed as a class property for IID to fetch the property without instantiating an instance of
  379. /// Messaging. Since Messaging can only be used with the default FIRApp, we can have one point of
  380. /// entry without context of which FIRApp instance is being used.
  381. /// ** THIS METHOD IS DEPENDED ON INTERNALLY BY IID USING REFLECTION. PLEASE DO NOT CHANGE THE
  382. /// SIGNATURE, AS IT WOULD BREAK AUTOINIT FUNCTIONALITY WITHIN IID. **
  383. + (BOOL)isAutoInitEnabledWithUserDefaults:(GULUserDefaults *)userDefaults {
  384. // Check storage
  385. id isAutoInitEnabledObject =
  386. [userDefaults objectForKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  387. if (isAutoInitEnabledObject) {
  388. return [isAutoInitEnabledObject boolValue];
  389. }
  390. // Check Info.plist
  391. isAutoInitEnabledObject =
  392. [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled];
  393. if (isAutoInitEnabledObject) {
  394. return [isAutoInitEnabledObject boolValue];
  395. }
  396. // If none of above exists, we default to the global switch that comes from FIRApp.
  397. return [[FIRApp defaultApp] isDataCollectionDefaultEnabled];
  398. }
  399. - (void)setAutoInitEnabled:(BOOL)autoInitEnabled {
  400. BOOL isFCMAutoInitEnabled = [self isAutoInitEnabled];
  401. [_messagingUserDefaults setBool:autoInitEnabled
  402. forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  403. [_messagingUserDefaults synchronize];
  404. if (!isFCMAutoInitEnabled && autoInitEnabled) {
  405. self.defaultFcmToken = self.instanceID.token;
  406. }
  407. }
  408. - (NSString *)FCMToken {
  409. NSString *token = self.defaultFcmToken;
  410. if (!token) {
  411. // We may not have received it from Instance ID yet (via NSNotification), so extract it directly
  412. token = self.instanceID.token;
  413. }
  414. return token;
  415. }
  416. - (void)tokenWithCompletion:(FIRMessagingFCMTokenFetchCompletion)completion {
  417. FIROptions *options = FIRApp.defaultApp.options;
  418. [self retrieveFCMTokenForSenderID:options.GCMSenderID completion:completion];
  419. }
  420. - (void)deleteTokenWithCompletion:(FIRMessagingDeleteFCMTokenCompletion)completion {
  421. FIROptions *options = FIRApp.defaultApp.options;
  422. [self deleteFCMTokenForSenderID:options.GCMSenderID completion:completion];
  423. }
  424. - (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID
  425. completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion {
  426. if (!senderID.length) {
  427. NSString *description = @"Couldn't fetch token because a Sender ID was not supplied. A valid "
  428. @"Sender ID is required to fetch an FCM token";
  429. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch, @"%@",
  430. description);
  431. if (completion) {
  432. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidRequest
  433. failureReason:description];
  434. completion(nil, error);
  435. }
  436. return;
  437. }
  438. NSDictionary *options = nil;
  439. if (self.APNSToken) {
  440. options = @{kFIRMessagingFCMTokenFetchAPNSOption : self.APNSToken};
  441. } else {
  442. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch,
  443. @"APNS device token not set before retrieving FCM Token for Sender ID "
  444. @"'%@'. Notifications to this FCM Token will not be delivered over APNS."
  445. @"Be sure to re-retrieve the FCM token once the APNS device token is "
  446. @"set.",
  447. senderID);
  448. }
  449. [self.instanceID tokenWithAuthorizedEntity:senderID
  450. scope:kFIRMessagingDefaultTokenScope
  451. options:options
  452. handler:completion];
  453. }
  454. - (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID
  455. completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion {
  456. if (!senderID.length) {
  457. NSString *description = @"Couldn't delete token because a Sender ID was not supplied. A "
  458. @"valid Sender ID is required to delete an FCM token";
  459. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete, @"%@",
  460. description);
  461. if (completion) {
  462. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidRequest
  463. failureReason:description];
  464. completion(error);
  465. }
  466. return;
  467. }
  468. [self.instanceID deleteTokenWithAuthorizedEntity:senderID
  469. scope:kFIRMessagingDefaultTokenScope
  470. handler:completion];
  471. }
  472. - (void)deleteDataWithCompletion:(void (^)(NSError *_Nullable))completion {
  473. FIRMessaging_WEAKIFY(self);
  474. [self.instanceID
  475. deleteTokenWithAuthorizedEntity:@"*"
  476. scope:@"*"
  477. handler:^(NSError *_Nonnull error) {
  478. FIRMessaging_STRONGIFY(self);
  479. if (error) {
  480. completion(error);
  481. return;
  482. }
  483. [self.instanceID
  484. deleteCheckinWithHandler:^(NSError *_Nullable error) {
  485. if (error) {
  486. completion(error);
  487. return;
  488. }
  489. // Only request new token if FCM auto initialization is
  490. // enabled.
  491. if ([self isAutoInitEnabled]) {
  492. // Deletion succeeds! Requesting new checkin, IID and token.
  493. [self tokenWithCompletion:^(NSString *_Nullable token,
  494. NSError *_Nullable error) {
  495. completion(error);
  496. }];
  497. return;
  498. }
  499. completion(nil);
  500. }];
  501. }];
  502. }
  503. #pragma mark - FIRMessagingDelegate helper methods
  504. - (void)setDelegate:(id<FIRMessagingDelegate>)delegate {
  505. _delegate = delegate;
  506. [self validateDelegateConformsToTokenAvailabilityMethods];
  507. }
  508. // Check if the delegate conforms to |didReceiveRegistrationToken:|
  509. // and display a warning to the developer if not.
  510. // NOTE: Once |didReceiveRegistrationToken:| can be made a required method, this
  511. // check can be removed.
  512. - (void)validateDelegateConformsToTokenAvailabilityMethods {
  513. if (self.delegate && ![self.delegate respondsToSelector:@selector(messaging:
  514. didReceiveRegistrationToken:)]) {
  515. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented,
  516. @"The object %@ does not respond to "
  517. @"-messaging:didReceiveRegistrationToken:. Please implement "
  518. @"-messaging:didReceiveRegistrationToken: to be provided with an FCM "
  519. @"token.",
  520. self.delegate.description);
  521. }
  522. }
  523. - (void)notifyDelegateOfFCMTokenAvailability {
  524. __weak FIRMessaging *weakSelf = self;
  525. if (![NSThread isMainThread]) {
  526. dispatch_async(dispatch_get_main_queue(), ^{
  527. [weakSelf notifyDelegateOfFCMTokenAvailability];
  528. });
  529. return;
  530. }
  531. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
  532. [self.delegate messaging:self didReceiveRegistrationToken:self.defaultFcmToken];
  533. }
  534. // Should always trigger the token refresh notification when the delegate method is called
  535. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  536. [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification
  537. object:self.defaultFcmToken];
  538. }
  539. #pragma mark - Topics
  540. + (NSString *)normalizeTopic:(NSString *)topic {
  541. if (!topic.length) {
  542. return nil;
  543. }
  544. if (![FIRMessagingPubSub hasTopicsPrefix:topic]) {
  545. topic = [FIRMessagingPubSub addPrefixToTopic:topic];
  546. }
  547. if ([FIRMessagingPubSub isValidTopicWithPrefix:topic]) {
  548. return [topic copy];
  549. }
  550. return nil;
  551. }
  552. - (void)subscribeToTopic:(NSString *)topic {
  553. [self subscribeToTopic:topic completion:nil];
  554. }
  555. - (void)subscribeToTopic:(NSString *)topic
  556. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  557. if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
  558. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
  559. @"Format '%@' is deprecated. Only '%@' should be used in "
  560. @"subscribeToTopic.",
  561. topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
  562. }
  563. __weak FIRMessaging *weakSelf = self;
  564. [self.instanceID instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result,
  565. NSError *_Nullable error) {
  566. if (error) {
  567. FIRMessagingLoggerError(
  568. kFIRMessagingMessageCodeMessaging010,
  569. @"The subscription operation failed due to an error getting the FCM token: %@.", error);
  570. if (completion) {
  571. completion(error);
  572. }
  573. return;
  574. }
  575. FIRMessaging *strongSelf = weakSelf;
  576. NSString *normalizeTopic = [[strongSelf class] normalizeTopic:topic];
  577. if (normalizeTopic.length) {
  578. [strongSelf.pubsub subscribeToTopic:normalizeTopic handler:completion];
  579. return;
  580. }
  581. NSString *failureReason =
  582. [NSString stringWithFormat:@"Cannot parse topic name: '%@'. Will not subscribe.", topic];
  583. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging009, @"%@", failureReason);
  584. if (completion) {
  585. completion([NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidTopicName
  586. failureReason:failureReason]);
  587. }
  588. }];
  589. }
  590. - (void)unsubscribeFromTopic:(NSString *)topic {
  591. [self unsubscribeFromTopic:topic completion:nil];
  592. }
  593. - (void)unsubscribeFromTopic:(NSString *)topic
  594. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  595. if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
  596. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
  597. @"Format '%@' is deprecated. Only '%@' should be used in "
  598. @"unsubscribeFromTopic.",
  599. topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
  600. }
  601. __weak FIRMessaging *weakSelf = self;
  602. [self.instanceID instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result,
  603. NSError *_Nullable error) {
  604. if (error) {
  605. FIRMessagingLoggerError(
  606. kFIRMessagingMessageCodeMessaging012,
  607. @"The unsubscription operation failed due to an error getting the FCM token: %@.", error);
  608. if (completion) {
  609. completion(error);
  610. }
  611. return;
  612. }
  613. FIRMessaging *strongSelf = weakSelf;
  614. NSString *normalizeTopic = [[strongSelf class] normalizeTopic:topic];
  615. if (normalizeTopic.length) {
  616. [strongSelf.pubsub unsubscribeFromTopic:normalizeTopic handler:completion];
  617. return;
  618. }
  619. NSString *failureReason =
  620. [NSString stringWithFormat:@"Cannot parse topic name: '%@'. Will not unsubscribe.", topic];
  621. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging011, @"%@", failureReason);
  622. if (completion) {
  623. completion([NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidTopicName
  624. failureReason:failureReason]);
  625. }
  626. }];
  627. }
  628. #pragma mark - IID dependencies
  629. + (NSString *)FIRMessagingSDKVersion {
  630. return FIRMessagingCurrentLibraryVersion();
  631. }
  632. + (NSString *)FIRMessagingSDKCurrentLocale {
  633. return [self currentLocale];
  634. }
  635. #pragma mark - GULReachabilityDelegate
  636. - (void)reachability:(GULReachabilityChecker *)reachability
  637. statusChanged:(GULReachabilityStatus)status {
  638. [self onNetworkStatusChanged];
  639. }
  640. #pragma mark - Network
  641. - (void)onNetworkStatusChanged {
  642. if ([self isNetworkAvailable]) {
  643. [self.pubsub scheduleSync:YES];
  644. }
  645. }
  646. - (BOOL)isNetworkAvailable {
  647. GULReachabilityStatus status = self.reachability.reachabilityStatus;
  648. return (status == kGULReachabilityViaCellular || status == kGULReachabilityViaWifi);
  649. }
  650. - (FIRMessagingNetworkStatus)networkType {
  651. GULReachabilityStatus status = self.reachability.reachabilityStatus;
  652. if (![self isNetworkAvailable]) {
  653. return kFIRMessagingReachabilityNotReachable;
  654. } else if (status == kGULReachabilityViaCellular) {
  655. return kFIRMessagingReachabilityReachableViaWWAN;
  656. } else {
  657. return kFIRMessagingReachabilityReachableViaWiFi;
  658. }
  659. }
  660. #pragma mark - Notifications
  661. - (void)defaultInstanceIDTokenWasRefreshed:(NSNotification *)notification {
  662. if (notification.object && ![notification.object isKindOfClass:[NSString class]]) {
  663. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging015,
  664. @"Invalid default FCM token type %@",
  665. NSStringFromClass([notification.object class]));
  666. return;
  667. }
  668. // Retrieve the Instance ID default token, and should notify delegate and
  669. // trigger notification as long as the token is different from previous state.
  670. NSString *oldToken = self.defaultFcmToken;
  671. self.defaultFcmToken = [(NSString *)notification.object copy];
  672. if ((self.defaultFcmToken.length && oldToken.length &&
  673. ![self.defaultFcmToken isEqualToString:oldToken]) ||
  674. self.defaultFcmToken.length != oldToken.length) {
  675. [self notifyDelegateOfFCMTokenAvailability];
  676. [self.pubsub scheduleSync:YES];
  677. }
  678. }
  679. #pragma mark - Application Support Directory
  680. + (BOOL)hasSubDirectory:(NSString *)subDirectoryName {
  681. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  682. BOOL isDirectory;
  683. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  684. isDirectory:&isDirectory]) {
  685. return NO;
  686. } else if (!isDirectory) {
  687. return NO;
  688. }
  689. return YES;
  690. }
  691. + (NSString *)pathForSubDirectory:(NSString *)subDirectoryName {
  692. NSArray *directoryPaths =
  693. NSSearchPathForDirectoriesInDomains(FIRMessagingSupportedDirectory(), NSUserDomainMask, YES);
  694. NSString *dirPath = directoryPaths.lastObject;
  695. NSArray *components = @[ dirPath, subDirectoryName ];
  696. return [NSString pathWithComponents:components];
  697. }
  698. + (BOOL)createSubDirectory:(NSString *)subDirectoryName {
  699. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  700. BOOL hasSubDirectory;
  701. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  702. isDirectory:&hasSubDirectory]) {
  703. NSError *error;
  704. [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
  705. withIntermediateDirectories:YES
  706. attributes:nil
  707. error:&error];
  708. if (error) {
  709. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017,
  710. @"Cannot create directory %@, error: %@", subDirectoryPath, error);
  711. return NO;
  712. }
  713. } else {
  714. if (!hasSubDirectory) {
  715. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018,
  716. @"Found file instead of directory at %@", subDirectoryPath);
  717. return NO;
  718. }
  719. }
  720. return YES;
  721. }
  722. #pragma mark - Locales
  723. + (NSString *)currentLocale {
  724. NSArray *locales = [self firebaseLocales];
  725. NSArray *preferredLocalizations =
  726. [NSBundle preferredLocalizationsFromArray:locales
  727. forPreferences:[NSLocale preferredLanguages]];
  728. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  729. // Use en as the default language
  730. return legalDocsLanguage ? legalDocsLanguage : @"en";
  731. }
  732. + (NSArray *)firebaseLocales {
  733. NSMutableArray *locales = [NSMutableArray array];
  734. NSDictionary *localesMap = [self firebaselocalesMap];
  735. for (NSString *key in localesMap) {
  736. [locales addObjectsFromArray:localesMap[key]];
  737. }
  738. return locales;
  739. }
  740. + (NSDictionary *)firebaselocalesMap {
  741. return @{
  742. // Albanian
  743. @"sq" : @[ @"sq_AL" ],
  744. // Belarusian
  745. @"be" : @[ @"be_BY" ],
  746. // Bulgarian
  747. @"bg" : @[ @"bg_BG" ],
  748. // Catalan
  749. @"ca" : @[ @"ca", @"ca_ES" ],
  750. // Croatian
  751. @"hr" : @[ @"hr", @"hr_HR" ],
  752. // Czech
  753. @"cs" : @[ @"cs", @"cs_CZ" ],
  754. // Danish
  755. @"da" : @[ @"da", @"da_DK" ],
  756. // Estonian
  757. @"et" : @[ @"et_EE" ],
  758. // Finnish
  759. @"fi" : @[ @"fi", @"fi_FI" ],
  760. // Hebrew
  761. @"he" : @[ @"he", @"iw_IL" ],
  762. // Hindi
  763. @"hi" : @[ @"hi_IN" ],
  764. // Hungarian
  765. @"hu" : @[ @"hu", @"hu_HU" ],
  766. // Icelandic
  767. @"is" : @[ @"is_IS" ],
  768. // Indonesian
  769. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  770. // Irish
  771. @"ga" : @[ @"ga_IE" ],
  772. // Korean
  773. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  774. // Latvian
  775. @"lv" : @[ @"lv_LV" ],
  776. // Lithuanian
  777. @"lt" : @[ @"lt_LT" ],
  778. // Macedonian
  779. @"mk" : @[ @"mk_MK" ],
  780. // Malay
  781. @"ms" : @[ @"ms_MY" ],
  782. // Maltese
  783. @"mt" : @[ @"mt_MT" ],
  784. // Polish
  785. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  786. // Romanian
  787. @"ro" : @[ @"ro", @"ro_RO" ],
  788. // Russian
  789. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  790. // Slovak
  791. @"sk" : @[ @"sk", @"sk_SK" ],
  792. // Slovenian
  793. @"sl" : @[ @"sl_SI" ],
  794. // Swedish
  795. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  796. // Turkish
  797. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  798. // Ukrainian
  799. @"uk" : @[ @"uk", @"uk_UA" ],
  800. // Vietnamese
  801. @"vi" : @[ @"vi", @"vi_VN" ],
  802. // The following are groups of locales or locales that sub-divide a
  803. // language).
  804. // Arabic
  805. @"ar" : @[
  806. @"ar", @"ar_DZ", @"ar_BH", @"ar_EG", @"ar_IQ", @"ar_JO", @"ar_KW",
  807. @"ar_LB", @"ar_LY", @"ar_MA", @"ar_OM", @"ar_QA", @"ar_SA", @"ar_SD",
  808. @"ar_SY", @"ar_TN", @"ar_AE", @"ar_YE", @"ar_GB", @"ar-IQ", @"ar_US"
  809. ],
  810. // Simplified Chinese
  811. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  812. // Traditional Chinese
  813. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  814. // Dutch
  815. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  816. // English
  817. @"en" : @[
  818. @"en", @"en_AU", @"en_CA", @"en_IN", @"en_IE", @"en_MT", @"en_NZ", @"en_PH",
  819. @"en_SG", @"en_ZA", @"en_GB", @"en_US", @"en_AE", @"en-AE", @"en_AS", @"en-AU",
  820. @"en_BD", @"en-CA", @"en_EG", @"en_ES", @"en_GB", @"en-GB", @"en_HK", @"en_ID",
  821. @"en-IN", @"en_NG", @"en-PH", @"en_PK", @"en-SG", @"en-US"
  822. ],
  823. // French
  824. @"fr" :
  825. @[ @"fr", @"fr_BE", @"fr_CA", @"fr_FR", @"fr_LU", @"fr_CH", @"fr-CA", @"fr-FR", @"fr_MA" ],
  826. // German
  827. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  828. // Greek
  829. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  830. // Italian
  831. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  832. // Japanese
  833. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  834. // Norwegian
  835. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  836. // Brazilian Portuguese
  837. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  838. // European Portuguese
  839. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  840. // Serbian
  841. @"sr" : @[ @"sr_BA", @"sr_ME", @"sr_RS", @"sr_Latn_BA", @"sr_Latn_ME", @"sr_Latn_RS" ],
  842. // European Spanish
  843. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  844. // Mexican Spanish
  845. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  846. // Latin American Spanish
  847. @"es_419" : @[
  848. @"es_AR", @"es_BO", @"es_CL", @"es_CO", @"es_CR", @"es_DO", @"es_EC",
  849. @"es_SV", @"es_GT", @"es_HN", @"es_NI", @"es_PA", @"es_PY", @"es_PE",
  850. @"es_PR", @"es_UY", @"es_VE", @"es-AR", @"es-CL", @"es-CO"
  851. ],
  852. // Thai
  853. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  854. };
  855. }
  856. @end