FIRMessaging.m 38 KB

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