FIRMessaging.m 38 KB

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