You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1137 lines
39 KiB

6 years ago
  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 "FIRMessaging.h"
  20. #import "FIRMessaging_Private.h"
  21. #import <UIKit/UIKit.h>
  22. #import "FIRMessagingClient.h"
  23. #import "FIRMessagingConstants.h"
  24. #import "FIRMessagingContextManagerService.h"
  25. #import "FIRMessagingDataMessageManager.h"
  26. #import "FIRMessagingDefines.h"
  27. #import "FIRMessagingLogger.h"
  28. #import "FIRMessagingPubSub.h"
  29. #import "FIRMessagingReceiver.h"
  30. #import "FIRMessagingRmqManager.h"
  31. #import "FIRMessagingSyncMessageManager.h"
  32. #import "FIRMessagingUtilities.h"
  33. #import "FIRMessagingVersionUtilities.h"
  34. #import <FirebaseCore/FIRReachabilityChecker.h>
  35. #import <FirebaseInstanceID/FirebaseInstanceID.h>
  36. #import "NSError+FIRMessaging.h"
  37. static NSString *const kFIRMessagingMessageViaAPNSRootKey = @"aps";
  38. static NSString *const kFIRMessagingReachabilityHostname = @"www.google.com";
  39. static NSString *const kFIRMessagingDefaultTokenScope = @"*";
  40. static NSString *const kFIRMessagingFCMTokenFetchAPNSOption = @"apns_token";
  41. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  42. const NSNotificationName FIRMessagingSendSuccessNotification =
  43. @"com.firebase.messaging.notif.send-success";
  44. const NSNotificationName FIRMessagingSendErrorNotification =
  45. @"com.firebase.messaging.notif.send-error";
  46. const NSNotificationName FIRMessagingMessagesDeletedNotification =
  47. @"com.firebase.messaging.notif.messages-deleted";
  48. const NSNotificationName FIRMessagingConnectionStateChangedNotification =
  49. @"com.firebase.messaging.notif.connection-state-changed";
  50. const NSNotificationName FIRMessagingRegistrationTokenRefreshedNotification =
  51. @"com.firebase.messaging.notif.fcm-token-refreshed";
  52. #else
  53. NSString *const FIRMessagingSendSuccessNotification =
  54. @"com.firebase.messaging.notif.send-success";
  55. NSString *const FIRMessagingSendErrorNotification =
  56. @"com.firebase.messaging.notif.send-error";
  57. NSString * const FIRMessagingMessagesDeletedNotification =
  58. @"com.firebase.messaging.notif.messages-deleted";
  59. NSString * const FIRMessagingConnectionStateChangedNotification =
  60. @"com.firebase.messaging.notif.connection-state-changed";
  61. NSString * const FIRMessagingRegistrationTokenRefreshedNotification =
  62. @"com.firebase.messaging.notif.fcm-token-refreshed";
  63. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  64. NSString *const kFIRMessagingUserDefaultsKeyAutoInitEnabled =
  65. @"com.firebase.messaging.auto-init.enabled"; // Auto Init Enabled key stored in NSUserDefaults
  66. NSString *const kFIRMessagingAPNSTokenType = @"APNSTokenType"; // APNS Token type key stored in user info.
  67. NSString *const kFIRMessagingPlistAutoInitEnabled =
  68. @"FirebaseMessagingAutoInitEnabled"; // Auto Init Enabled key stored in Info.plist
  69. @interface FIRMessagingMessageInfo ()
  70. @property(nonatomic, readwrite, assign) FIRMessagingMessageStatus status;
  71. @end
  72. @implementation FIRMessagingMessageInfo
  73. - (instancetype)init {
  74. FIRMessagingInvalidateInitializer();
  75. }
  76. - (instancetype)initWithStatus:(FIRMessagingMessageStatus)status {
  77. self = [super init];
  78. if (self) {
  79. _status = status;
  80. }
  81. return self;
  82. }
  83. @end
  84. #pragma mark - for iOS 10 compatibility
  85. @implementation FIRMessagingRemoteMessage
  86. - (instancetype)init {
  87. self = [super init];
  88. if (self) {
  89. _appData = [[NSMutableDictionary alloc] init];
  90. }
  91. return self;
  92. }
  93. - (instancetype)initWithMessage:(FIRMessagingRemoteMessage *)message {
  94. self = [self init];
  95. if (self) {
  96. _appData = [message.appData copy];
  97. }
  98. return self;
  99. }
  100. @end
  101. @interface FIRMessaging ()<FIRMessagingClientDelegate, FIRMessagingReceiverDelegate,
  102. FIRReachabilityDelegate>
  103. // FIRApp properties
  104. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  105. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  106. @property(nonatomic, readwrite, strong) NSString *defaultFcmToken;
  107. @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
  108. @property(nonatomic, readwrite, assign) BOOL isClientSetup;
  109. @property(nonatomic, readwrite, strong) FIRMessagingClient *client;
  110. @property(nonatomic, readwrite, strong) FIRReachabilityChecker *reachability;
  111. @property(nonatomic, readwrite, strong) FIRMessagingDataMessageManager *dataMessageManager;
  112. @property(nonatomic, readwrite, strong) FIRMessagingPubSub *pubsub;
  113. @property(nonatomic, readwrite, strong) FIRMessagingRmqManager *rmq2Manager;
  114. @property(nonatomic, readwrite, strong) FIRMessagingReceiver *receiver;
  115. @property(nonatomic, readwrite, strong) FIRMessagingSyncMessageManager *syncMessageManager;
  116. @property(nonatomic, readwrite, strong) NSUserDefaults *messagingUserDefaults;
  117. /// Message ID's logged for analytics. This prevents us from logging the same message twice
  118. /// which can happen if the user inadvertently calls `appDidReceiveMessage` along with us
  119. /// calling it implicitly during swizzling.
  120. @property(nonatomic, readwrite, strong) NSMutableSet *loggedMessageIDs;
  121. - (instancetype)initWithInstanceID:(FIRInstanceID *)instanceID
  122. userDefaults:(NSUserDefaults *)defaults NS_DESIGNATED_INITIALIZER;
  123. @end
  124. @implementation FIRMessaging
  125. + (FIRMessaging *)messaging {
  126. static FIRMessaging *messaging;
  127. static dispatch_once_t onceToken;
  128. dispatch_once(&onceToken, ^{
  129. messaging = [[FIRMessaging alloc] initPrivately];
  130. [messaging start];
  131. });
  132. return messaging;
  133. }
  134. - (instancetype)initWithInstanceID:(FIRInstanceID *)instanceID
  135. userDefaults:(NSUserDefaults *)defaults {
  136. self = [super init];
  137. if (self != nil) {
  138. _loggedMessageIDs = [NSMutableSet set];
  139. _instanceID = instanceID;
  140. _messagingUserDefaults = defaults;
  141. // TODO: Remove this once the race condition with FIRApp configuring and InstanceID
  142. // is fixed. This must be fixed before Core's flag becomes public.
  143. _globalAutomaticDataCollectionEnabled = YES;
  144. }
  145. return self;
  146. }
  147. - (instancetype)initPrivately {
  148. return [self initWithInstanceID:[FIRInstanceID instanceID]
  149. userDefaults:[NSUserDefaults standardUserDefaults]];
  150. }
  151. - (void)dealloc {
  152. [self.reachability stop];
  153. [[NSNotificationCenter defaultCenter] removeObserver:self];
  154. [self teardown];
  155. }
  156. #pragma mark - Config
  157. - (void)start {
  158. // Print the library version for logging.
  159. NSString *currentLibraryVersion = FIRMessagingCurrentLibraryVersion();
  160. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessagingPrintLibraryVersion,
  161. @"FIRMessaging library version %@",
  162. currentLibraryVersion);
  163. [self setupReceiver];
  164. NSString *hostname = kFIRMessagingReachabilityHostname;
  165. self.reachability = [[FIRReachabilityChecker alloc] initWithReachabilityDelegate:self
  166. loggerDelegate:nil
  167. withHost:hostname];
  168. [self.reachability start];
  169. [self setupApplicationSupportSubDirectory];
  170. // setup FIRMessaging objects
  171. [self setupRmqManager];
  172. [self setupClient];
  173. [self setupSyncMessageManager];
  174. [self setupDataMessageManager];
  175. [self setupTopics];
  176. self.isClientSetup = YES;
  177. [self setupNotificationListeners];
  178. }
  179. - (void)setupApplicationSupportSubDirectory {
  180. NSString *messagingSubDirectory = kFIRMessagingApplicationSupportSubDirectory;
  181. if (![[self class] hasApplicationSupportSubDirectory:messagingSubDirectory]) {
  182. [[self class] createApplicationSupportSubDirectory:messagingSubDirectory];
  183. }
  184. }
  185. - (void)setupNotificationListeners {
  186. // To prevent multiple notifications remove self as observer for all events.
  187. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  188. [center removeObserver:self];
  189. [center addObserver:self
  190. selector:@selector(didReceiveDefaultInstanceIDToken:)
  191. name:kFIRMessagingFCMTokenNotification
  192. object:nil];
  193. [center addObserver:self
  194. selector:@selector(defaultInstanceIDTokenWasRefreshed:)
  195. name:kFIRMessagingRegistrationTokenRefreshNotification
  196. object:nil];
  197. [center addObserver:self
  198. selector:@selector(applicationStateChanged)
  199. name:UIApplicationDidBecomeActiveNotification
  200. object:nil];
  201. [center addObserver:self
  202. selector:@selector(applicationStateChanged)
  203. name:UIApplicationDidEnterBackgroundNotification
  204. object:nil];
  205. }
  206. - (void)setupReceiver {
  207. self.receiver = [[FIRMessagingReceiver alloc] init];
  208. self.receiver.delegate = self;
  209. }
  210. - (void)setupClient {
  211. self.client = [[FIRMessagingClient alloc] initWithDelegate:self
  212. reachability:self.reachability
  213. rmq2Manager:self.rmq2Manager];
  214. }
  215. - (void)setupDataMessageManager {
  216. self.dataMessageManager =
  217. [[FIRMessagingDataMessageManager alloc] initWithDelegate:self.receiver
  218. client:self.client
  219. rmq2Manager:self.rmq2Manager
  220. syncMessageManager:self.syncMessageManager];
  221. [self.dataMessageManager refreshDelayedMessages];
  222. [self.client setDataMessageManager:self.dataMessageManager];
  223. }
  224. - (void)setupRmqManager {
  225. self.rmq2Manager = [[FIRMessagingRmqManager alloc] initWithDatabaseName:@"rmq2"];
  226. [self.rmq2Manager loadRmqId];
  227. }
  228. - (void)setupTopics {
  229. _FIRMessagingDevAssert(self.client, @"Invalid nil client before init pubsub.");
  230. self.pubsub = [[FIRMessagingPubSub alloc] initWithClient:self.client];
  231. }
  232. - (void)setupSyncMessageManager {
  233. self.syncMessageManager =
  234. [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager];
  235. // Delete the expired messages with a delay. We don't want to block startup with a somewhat
  236. // expensive db call.
  237. FIRMessaging_WEAKIFY(self);
  238. dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
  239. dispatch_after(time, dispatch_get_main_queue(), ^{
  240. FIRMessaging_STRONGIFY(self);
  241. [self.syncMessageManager removeExpiredSyncMessages];
  242. });
  243. }
  244. - (void)teardown {
  245. _FIRMessagingDevAssert([NSThread isMainThread],
  246. @"FIRMessaging should be called from main thread only.");
  247. [self.client teardown];
  248. self.pubsub = nil;
  249. self.syncMessageManager = nil;
  250. self.rmq2Manager = nil;
  251. self.dataMessageManager = nil;
  252. self.client = nil;
  253. self.isClientSetup = NO;
  254. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown");
  255. }
  256. #pragma mark - Messages
  257. - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message {
  258. if (!message.count) {
  259. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown];
  260. }
  261. // For downstream messages that go via MCS we should strip out this key before sending
  262. // the message to the device.
  263. BOOL isOldMessage = NO;
  264. NSString *messageID = message[kFIRMessagingMessageIDKey];
  265. if ([messageID length]) {
  266. [self.rmq2Manager saveS2dMessageWithRmqId:messageID];
  267. BOOL isSyncMessage = [[self class] isAPNSSyncMessage:message];
  268. if (isSyncMessage) {
  269. isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message];
  270. }
  271. }
  272. // Prevent duplicates by keeping a cache of all the logged messages during each session.
  273. // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with
  274. // us swizzling their implementation to call the same method implicitly.
  275. if (!isOldMessage && messageID.length) {
  276. isOldMessage = [self.loggedMessageIDs containsObject:messageID];
  277. if (!isOldMessage) {
  278. [self.loggedMessageIDs addObject:messageID];
  279. }
  280. }
  281. if (!isOldMessage) {
  282. Class firMessagingLogClass = NSClassFromString(@"FIRMessagingLog");
  283. SEL logMessageSelector = NSSelectorFromString(@"logMessage:");
  284. if ([firMessagingLogClass respondsToSelector:logMessageSelector]) {
  285. #pragma clang diagnostic push
  286. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  287. [firMessagingLogClass performSelector:logMessageSelector
  288. withObject:message];
  289. }
  290. #pragma clang diagnostic pop
  291. [self handleContextManagerMessage:message];
  292. [self handleIncomingLinkIfNeededFromMessage:message];
  293. }
  294. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew];
  295. }
  296. - (BOOL)handleContextManagerMessage:(NSDictionary *)message {
  297. if ([FIRMessagingContextManagerService isContextManagerMessage:message]) {
  298. return [FIRMessagingContextManagerService handleContextManagerMessage:message];
  299. }
  300. return NO;
  301. }
  302. + (BOOL)isAPNSSyncMessage:(NSDictionary *)message {
  303. if ([message[kFIRMessagingMessageViaAPNSRootKey] isKindOfClass:[NSDictionary class]]) {
  304. NSDictionary *aps = message[kFIRMessagingMessageViaAPNSRootKey];
  305. return [aps[kFIRMessagingMessageAPNSContentAvailableKey] boolValue];
  306. }
  307. return NO;
  308. }
  309. - (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message {
  310. NSURL *url = [self linkURLFromMessage:message];
  311. if (url == nil) {
  312. return;
  313. }
  314. if (![NSThread isMainThread]) {
  315. dispatch_async(dispatch_get_main_queue(), ^{
  316. [self handleIncomingLinkIfNeededFromMessage:message];
  317. });
  318. return;
  319. }
  320. UIApplication *application = [UIApplication sharedApplication];
  321. id<UIApplicationDelegate> appDelegate = application.delegate;
  322. SEL continueUserActivitySelector =
  323. @selector(application:continueUserActivity:restorationHandler:);
  324. SEL openURLWithOptionsSelector = @selector(application:openURL:options:);
  325. SEL openURLWithSourceApplicationSelector =
  326. @selector(application:openURL:sourceApplication:annotation:);
  327. SEL handleOpenURLSelector = @selector(application:handleOpenURL:);
  328. // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or
  329. // not the actual application has implemented
  330. // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user
  331. // if they haven't implemented it.
  332. if ([NSUserActivity class] != nil &&
  333. [appDelegate respondsToSelector:continueUserActivitySelector]) {
  334. NSUserActivity *userActivity =
  335. [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
  336. userActivity.webpageURL = url;
  337. [appDelegate application:application
  338. continueUserActivity:userActivity
  339. restorationHandler:^(NSArray * _Nullable restorableObjects) {
  340. // Do nothing, as we don't support the app calling this block
  341. }];
  342. } else if ([appDelegate respondsToSelector:openURLWithOptionsSelector]) {
  343. #pragma clang diagnostic push
  344. #pragma clang diagnostic ignored "-Wunguarded-availability"
  345. [appDelegate application:application openURL:url options:@{}];
  346. #pragma clang diagnostic pop
  347. // Similarly, |application:openURL:sourceApplication:annotation:| will also always be called, due
  348. // to the default swizzling done by FIRAAppDelegateProxy in Firebase Analytics
  349. } else if ([appDelegate respondsToSelector:openURLWithSourceApplicationSelector]) {
  350. #pragma clang diagnostic push
  351. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  352. [appDelegate application:application
  353. openURL:url
  354. sourceApplication:FIRMessagingAppIdentifier()
  355. annotation:@{}];
  356. #pragma clang diagnostic pop
  357. } else if ([appDelegate respondsToSelector:handleOpenURLSelector]) {
  358. #pragma clang diagnostic push
  359. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  360. [appDelegate application:application handleOpenURL:url];
  361. #pragma clang diagnostic pop
  362. }
  363. }
  364. - (NSURL *)linkURLFromMessage:(NSDictionary *)message {
  365. NSString *urlString = message[kFIRMessagingMessageLinkKey];
  366. if (urlString == nil || ![urlString isKindOfClass:[NSString class]] || urlString.length == 0) {
  367. return nil;
  368. }
  369. NSURL *url = [NSURL URLWithString:urlString];
  370. return url;
  371. }
  372. #pragma mark - APNS
  373. - (NSData *)APNSToken {
  374. return self.apnsTokenData;
  375. }
  376. - (void)setAPNSToken:(NSData *)APNSToken {
  377. [self setAPNSToken:APNSToken type:FIRMessagingAPNSTokenTypeUnknown];
  378. }
  379. - (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type {
  380. if ([apnsToken isEqual:self.apnsTokenData]) {
  381. return;
  382. }
  383. self.apnsTokenData = apnsToken;
  384. // Notify InstanceID that APNS Token has been set.
  385. NSDictionary *userInfo = @{kFIRMessagingAPNSTokenType : @(type)};
  386. NSNotification *notification =
  387. [NSNotification notificationWithName:kFIRMessagingAPNSTokenNotification
  388. object:[apnsToken copy]
  389. userInfo:userInfo];
  390. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  391. }
  392. #pragma mark - FCM
  393. - (BOOL)isAutoInitEnabled {
  394. // Check storage
  395. id isAutoInitEnabledObject =
  396. [_messagingUserDefaults objectForKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  397. if (isAutoInitEnabledObject) {
  398. return [isAutoInitEnabledObject boolValue];
  399. }
  400. // Check Info.plist
  401. isAutoInitEnabledObject =
  402. [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled];
  403. if (isAutoInitEnabledObject) {
  404. return [isAutoInitEnabledObject boolValue];
  405. }
  406. // If none of above exists, we default to the global switch that comes from FIRApp.
  407. return self.isGlobalAutomaticDataCollectionEnabled;
  408. }
  409. - (void)setAutoInitEnabled:(BOOL)autoInitEnabled {
  410. BOOL isFCMAutoInitEnabled = [self isAutoInitEnabled];
  411. [_messagingUserDefaults setBool:autoInitEnabled
  412. forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  413. if (!isFCMAutoInitEnabled && autoInitEnabled) {
  414. #pragma clang diagnostic push
  415. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  416. self.defaultFcmToken = self.instanceID.token;
  417. #pragma clang diagnostic pop
  418. }
  419. }
  420. - (NSString *)FCMToken {
  421. NSString *token = self.defaultFcmToken;
  422. if (!token) {
  423. // We may not have received it from Instance ID yet (via NSNotification), so extract it directly
  424. #pragma clang diagnostic push
  425. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  426. token = self.instanceID.token;
  427. #pragma clang diagnostic pop
  428. }
  429. return token;
  430. }
  431. - (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID
  432. completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion {
  433. if (!senderID.length) {
  434. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch,
  435. @"Sender ID not supplied. It is required for a token fetch, "
  436. @"to identify the sender.");
  437. if (completion) {
  438. NSString *description = @"Couldn't fetch token because a Sender ID was not supplied. A valid "
  439. @"Sender ID is required to fetch an FCM token";
  440. NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest
  441. userInfo:@{NSLocalizedDescriptionKey : description}];
  442. completion(nil, error);
  443. }
  444. return;
  445. }
  446. NSDictionary *options = nil;
  447. if (self.APNSToken) {
  448. options = @{kFIRMessagingFCMTokenFetchAPNSOption : self.APNSToken};
  449. } else {
  450. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch,
  451. @"APNS device token not set before retrieving FCM Token for Sender ID "
  452. @"'%@'. Notifications to this FCM Token will not be delivered over APNS."
  453. @"Be sure to re-retrieve the FCM token once the APNS device token is "
  454. @"set.", senderID);
  455. }
  456. [self.instanceID tokenWithAuthorizedEntity:senderID
  457. scope:kFIRMessagingDefaultTokenScope
  458. options:options
  459. handler:completion];
  460. }
  461. - (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID
  462. completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion {
  463. if (!senderID.length) {
  464. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete,
  465. @"Sender ID not supplied. It is required to delete an FCM token.");
  466. if (completion) {
  467. NSString *description = @"Couldn't delete token because a Sender ID was not supplied. A "
  468. @"valid Sender ID is required to delete an FCM token";
  469. NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest
  470. userInfo:@{NSLocalizedDescriptionKey : description}];
  471. completion(error);
  472. }
  473. return;
  474. }
  475. [self.instanceID deleteTokenWithAuthorizedEntity:senderID
  476. scope:kFIRMessagingDefaultTokenScope
  477. handler:completion];
  478. }
  479. #pragma mark - FIRMessagingDelegate helper methods
  480. - (void)setDelegate:(id<FIRMessagingDelegate>)delegate {
  481. _delegate = delegate;
  482. [self validateDelegateConformsToTokenAvailabilityMethods];
  483. }
  484. // Check if the delegate conforms to |didReceiveRegistrationToken:|
  485. // and display a warning to the developer if not.
  486. // NOTE: Once |didReceiveRegistrationToken:| can be made a required method, this
  487. // check can be removed.
  488. - (void)validateDelegateConformsToTokenAvailabilityMethods {
  489. if (self.delegate &&
  490. ![self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
  491. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented,
  492. @"The object %@ does not respond to "
  493. @"-messaging:didReceiveRegistrationToken:. Please implement "
  494. @"-messaging:didReceiveRegistrationToken: to be provided with an FCM "
  495. @"token.", self.delegate.description);
  496. }
  497. }
  498. - (void)notifyDelegateOfFCMTokenAvailability {
  499. __weak FIRMessaging *weakSelf = self;
  500. if (![NSThread isMainThread]) {
  501. dispatch_async(dispatch_get_main_queue(), ^{
  502. [weakSelf notifyDelegateOfFCMTokenAvailability];
  503. });
  504. return;
  505. }
  506. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
  507. [self.delegate messaging:self didReceiveRegistrationToken:self.defaultFcmToken];
  508. }
  509. }
  510. #pragma mark - Application State Changes
  511. - (void)applicationStateChanged {
  512. if (self.shouldEstablishDirectChannel) {
  513. [self updateAutomaticClientConnection];
  514. }
  515. }
  516. #pragma mark - Direct Channel
  517. - (void)setShouldEstablishDirectChannel:(BOOL)shouldEstablishDirectChannel {
  518. if (_shouldEstablishDirectChannel == shouldEstablishDirectChannel) {
  519. return;
  520. }
  521. _shouldEstablishDirectChannel = shouldEstablishDirectChannel;
  522. [self updateAutomaticClientConnection];
  523. }
  524. - (BOOL)isDirectChannelEstablished {
  525. return self.client.isConnectionActive;
  526. }
  527. - (BOOL)shouldBeConnectedAutomatically {
  528. // We require a token from Instance ID
  529. NSString *token = self.defaultFcmToken;
  530. // Only on foreground connections
  531. UIApplicationState applicationState = [UIApplication sharedApplication].applicationState;
  532. BOOL shouldBeConnected = _shouldEstablishDirectChannel &&
  533. (token.length > 0) &&
  534. applicationState == UIApplicationStateActive;
  535. return shouldBeConnected;
  536. }
  537. - (void)updateAutomaticClientConnection {
  538. if (![NSThread isMainThread]) {
  539. // Call this method from the main thread
  540. dispatch_async(dispatch_get_main_queue(), ^{
  541. [self updateAutomaticClientConnection];
  542. });
  543. return;
  544. }
  545. BOOL shouldBeConnected = [self shouldBeConnectedAutomatically];
  546. if (shouldBeConnected && !self.client.isConnected) {
  547. [self.client connectWithHandler:^(NSError *error) {
  548. if (!error) {
  549. // It means we connected. Fire connection change notification
  550. [self notifyOfDirectChannelConnectionChange];
  551. }
  552. }];
  553. } else if (!shouldBeConnected && self.client.isConnected) {
  554. [self.client disconnect];
  555. [self notifyOfDirectChannelConnectionChange];
  556. }
  557. }
  558. - (void)notifyOfDirectChannelConnectionChange {
  559. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  560. [center postNotificationName:FIRMessagingConnectionStateChangedNotification object:self];
  561. }
  562. #pragma mark - Connect
  563. - (void)connectWithCompletion:(FIRMessagingConnectCompletion)handler {
  564. _FIRMessagingDevAssert([NSThread isMainThread],
  565. @"FIRMessaging connect should be called from main thread only.");
  566. _FIRMessagingDevAssert(self.isClientSetup, @"FIRMessaging client not setup.");
  567. [self.client connectWithHandler:^(NSError *error) {
  568. if (handler) {
  569. handler(error);
  570. }
  571. if (!error) {
  572. // It means we connected. Fire connection change notification
  573. [self notifyOfDirectChannelConnectionChange];
  574. }
  575. }];
  576. }
  577. - (void)disconnect {
  578. _FIRMessagingDevAssert([NSThread isMainThread],
  579. @"FIRMessaging should be called from main thread only.");
  580. if ([self.client isConnected]) {
  581. [self.client disconnect];
  582. [self notifyOfDirectChannelConnectionChange];
  583. }
  584. }
  585. #pragma mark - Topics
  586. + (NSString *)normalizeTopic:(NSString *)topic {
  587. if (![FIRMessagingPubSub hasTopicsPrefix:topic]) {
  588. topic = [FIRMessagingPubSub addPrefixToTopic:topic];
  589. }
  590. if ([FIRMessagingPubSub isValidTopicWithPrefix:topic]) {
  591. return [topic copy];
  592. }
  593. return nil;
  594. }
  595. - (void)subscribeToTopic:(NSString *)topic {
  596. [self subscribeToTopic:topic completion:nil];
  597. }
  598. - (void)subscribeToTopic:(NSString *)topic
  599. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  600. if (self.defaultFcmToken.length && topic.length) {
  601. NSString *normalizeTopic = [[self class ] normalizeTopic:topic];
  602. if (normalizeTopic.length) {
  603. [self.pubsub subscribeToTopic:normalizeTopic handler:completion];
  604. } else {
  605. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging009,
  606. @"Cannot parse topic name %@. Will not subscribe.", topic);
  607. }
  608. } else {
  609. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging010,
  610. @"Cannot subscribe to topic: %@ with token: %@", topic,
  611. self.defaultFcmToken);
  612. }
  613. }
  614. - (void)unsubscribeFromTopic:(NSString *)topic {
  615. [self unsubscribeFromTopic:topic completion:nil];
  616. }
  617. - (void)unsubscribeFromTopic:(NSString *)topic
  618. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  619. if (self.defaultFcmToken.length && topic.length) {
  620. NSString *normalizeTopic = [[self class] normalizeTopic:topic];
  621. if (normalizeTopic.length) {
  622. [self.pubsub unsubscribeFromTopic:normalizeTopic handler:completion];
  623. } else {
  624. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging011,
  625. @"Cannot parse topic name %@. Will not unsubscribe.", topic);
  626. }
  627. } else {
  628. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging012,
  629. @"Cannot unsubscribe to topic: %@ with token: %@", topic,
  630. self.defaultFcmToken);
  631. }
  632. }
  633. #pragma mark - Send
  634. - (void)sendMessage:(NSDictionary *)message
  635. to:(NSString *)to
  636. withMessageID:(NSString *)messageID
  637. timeToLive:(int64_t)ttl {
  638. _FIRMessagingDevAssert([to length] != 0, @"Invalid receiver id for FIRMessaging-message");
  639. NSMutableDictionary *fcmMessage = [[self class] createFIRMessagingMessageWithMessage:message
  640. to:to
  641. withID:messageID
  642. timeToLive:ttl
  643. delay:0];
  644. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessaging013, @"Sending message: %@ with id: %@",
  645. message, messageID);
  646. [self.dataMessageManager sendDataMessageStanza:fcmMessage];
  647. }
  648. + (NSMutableDictionary *)createFIRMessagingMessageWithMessage:(NSDictionary *)message
  649. to:(NSString *)to
  650. withID:(NSString *)msgID
  651. timeToLive:(int64_t)ttl
  652. delay:(int)delay {
  653. NSMutableDictionary *fcmMessage = [NSMutableDictionary dictionary];
  654. fcmMessage[kFIRMessagingSendTo] = [to copy];
  655. fcmMessage[kFIRMessagingSendMessageID] = msgID ? [msgID copy] : @"";
  656. fcmMessage[kFIRMessagingSendTTL] = @(ttl);
  657. fcmMessage[kFIRMessagingSendDelay] = @(delay);
  658. fcmMessage[KFIRMessagingSendMessageAppData] =
  659. [NSMutableDictionary dictionaryWithDictionary:message];
  660. return fcmMessage;
  661. }
  662. #pragma mark - IID dependencies
  663. + (NSString *)FIRMessagingSDKVersion {
  664. return FIRMessagingCurrentLibraryVersion();
  665. }
  666. + (NSString *)FIRMessagingSDKCurrentLocale {
  667. return [self currentLocale];
  668. }
  669. #pragma mark - FIRMessagingReceiverDelegate
  670. - (void)receiver:(FIRMessagingReceiver *)receiver
  671. receivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  672. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveMessage:)]) {
  673. #pragma clang diagnostic push
  674. #pragma clang diagnostic ignored "-Wunguarded-availability"
  675. [self.delegate messaging:self didReceiveMessage:remoteMessage];
  676. #pragma pop
  677. } else {
  678. // Delegate methods weren't implemented, so messages are being dropped, log a warning
  679. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeRemoteMessageDelegateMethodNotImplemented,
  680. @"FIRMessaging received data-message, but FIRMessagingDelegate's"
  681. @"-messaging:didReceiveMessage: not implemented");
  682. }
  683. }
  684. #pragma mark - FIRReachabilityDelegate
  685. - (void)reachability:(FIRReachabilityChecker *)reachability
  686. statusChanged:(FIRReachabilityStatus)status {
  687. [self onNetworkStatusChanged];
  688. }
  689. #pragma mark - Network
  690. - (void)onNetworkStatusChanged {
  691. if (![self.client isConnected] && [self isNetworkAvailable]) {
  692. if (self.client.shouldStayConnected) {
  693. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging014,
  694. @"Attempting to establish direct channel.");
  695. [self.client retryConnectionImmediately:YES];
  696. }
  697. [self.pubsub scheduleSync:YES];
  698. }
  699. }
  700. - (BOOL)isNetworkAvailable {
  701. FIRReachabilityStatus status = self.reachability.reachabilityStatus;
  702. return (status == kFIRReachabilityViaCellular || status == kFIRReachabilityViaWifi);
  703. }
  704. - (FIRMessagingNetworkStatus)networkType {
  705. FIRReachabilityStatus status = self.reachability.reachabilityStatus;
  706. if (![self isNetworkAvailable]) {
  707. return kFIRMessagingReachabilityNotReachable;
  708. } else if (status == kFIRReachabilityViaCellular) {
  709. return kFIRMessagingReachabilityReachableViaWWAN;
  710. } else {
  711. return kFIRMessagingReachabilityReachableViaWiFi;
  712. }
  713. }
  714. #pragma mark - Notifications
  715. - (void)didReceiveDefaultInstanceIDToken:(NSNotification *)notification {
  716. if (notification.object && ![notification.object isKindOfClass:[NSString class]]) {
  717. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging015,
  718. @"Invalid default FCM token type %@",
  719. NSStringFromClass([notification.object class]));
  720. return;
  721. }
  722. NSString *oldToken = self.defaultFcmToken;
  723. self.defaultFcmToken = [(NSString *)notification.object copy];
  724. if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) {
  725. [self notifyDelegateOfFCMTokenAvailability];
  726. }
  727. [self.pubsub scheduleSync:YES];
  728. if (self.shouldEstablishDirectChannel) {
  729. [self updateAutomaticClientConnection];
  730. }
  731. }
  732. - (void)defaultInstanceIDTokenWasRefreshed:(NSNotification *)notification {
  733. // Retrieve the Instance ID default token, and if it is non-nil, post it
  734. #pragma clang diagnostic push
  735. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  736. NSString *token = self.instanceID.token;
  737. #pragma clang diagnostic pop
  738. // Sometimes Instance ID doesn't yet have a token, so wait until the default
  739. // token is fetched, and then notify. This ensures that this token should not
  740. // be nil when the developer accesses it.
  741. if (token != nil) {
  742. NSString *oldToken = self.defaultFcmToken;
  743. self.defaultFcmToken = [token copy];
  744. if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) {
  745. [self notifyDelegateOfFCMTokenAvailability];
  746. }
  747. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  748. [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification object:nil];
  749. }
  750. }
  751. #pragma mark - Application Support Directory
  752. + (BOOL)hasApplicationSupportSubDirectory:(NSString *)subDirectoryName {
  753. NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName];
  754. BOOL isDirectory;
  755. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  756. isDirectory:&isDirectory]) {
  757. return NO;
  758. } else if (!isDirectory) {
  759. return NO;
  760. }
  761. return YES;
  762. }
  763. + (NSString *)pathForApplicationSupportSubDirectory:(NSString *)subDirectoryName {
  764. NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
  765. NSUserDomainMask, YES);
  766. NSString *applicationSupportDirPath = directoryPaths.lastObject;
  767. NSArray *components = @[applicationSupportDirPath, subDirectoryName];
  768. return [NSString pathWithComponents:components];
  769. }
  770. + (BOOL)createApplicationSupportSubDirectory:(NSString *)subDirectoryName {
  771. NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName];
  772. BOOL hasSubDirectory;
  773. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  774. isDirectory:&hasSubDirectory]) {
  775. NSError *error;
  776. [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
  777. withIntermediateDirectories:YES
  778. attributes:nil
  779. error:&error];
  780. if (error) {
  781. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017,
  782. @"Cannot create directory %@, error: %@", subDirectoryPath, error);
  783. return NO;
  784. }
  785. } else {
  786. if (!hasSubDirectory) {
  787. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018,
  788. @"Found file instead of directory at %@", subDirectoryPath);
  789. return NO;
  790. }
  791. }
  792. return YES;
  793. }
  794. #pragma mark - Locales
  795. + (NSString *)currentLocale {
  796. NSArray *locales = [self firebaseLocales];
  797. NSArray *preferredLocalizations =
  798. [NSBundle preferredLocalizationsFromArray:locales
  799. forPreferences:[NSLocale preferredLanguages]];
  800. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  801. // Use en as the default language
  802. return legalDocsLanguage ? legalDocsLanguage : @"en";
  803. }
  804. + (NSArray *)firebaseLocales {
  805. NSMutableArray *locales = [NSMutableArray array];
  806. NSDictionary *localesMap = [self firebaselocalesMap];
  807. for (NSString *key in localesMap) {
  808. [locales addObjectsFromArray:localesMap[key]];
  809. }
  810. return locales;
  811. }
  812. + (NSDictionary *)firebaselocalesMap {
  813. return @{
  814. // Albanian
  815. @"sq" : @[ @"sq_AL" ],
  816. // Belarusian
  817. @"be" : @[ @"be_BY" ],
  818. // Bulgarian
  819. @"bg" : @[ @"bg_BG" ],
  820. // Catalan
  821. @"ca" : @[ @"ca", @"ca_ES" ],
  822. // Croatian
  823. @"hr" : @[ @"hr", @"hr_HR" ],
  824. // Czech
  825. @"cs" : @[ @"cs", @"cs_CZ" ],
  826. // Danish
  827. @"da" : @[ @"da", @"da_DK" ],
  828. // Estonian
  829. @"et" : @[ @"et_EE" ],
  830. // Finnish
  831. @"fi" : @[ @"fi", @"fi_FI" ],
  832. // Hebrew
  833. @"he" : @[ @"he", @"iw_IL" ],
  834. // Hindi
  835. @"hi" : @[ @"hi_IN" ],
  836. // Hungarian
  837. @"hu" : @[ @"hu", @"hu_HU" ],
  838. // Icelandic
  839. @"is" : @[ @"is_IS" ],
  840. // Indonesian
  841. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  842. // Irish
  843. @"ga" : @[ @"ga_IE" ],
  844. // Korean
  845. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  846. // Latvian
  847. @"lv" : @[ @"lv_LV" ],
  848. // Lithuanian
  849. @"lt" : @[ @"lt_LT" ],
  850. // Macedonian
  851. @"mk" : @[ @"mk_MK" ],
  852. // Malay
  853. @"ms" : @[ @"ms_MY" ],
  854. // Maltese
  855. @"ms" : @[ @"mt_MT" ],
  856. // Polish
  857. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  858. // Romanian
  859. @"ro" : @[ @"ro", @"ro_RO" ],
  860. // Russian
  861. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  862. // Slovak
  863. @"sk" : @[ @"sk", @"sk_SK" ],
  864. // Slovenian
  865. @"sl" : @[ @"sl_SI" ],
  866. // Swedish
  867. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  868. // Turkish
  869. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  870. // Ukrainian
  871. @"uk" : @[ @"uk", @"uk_UA" ],
  872. // Vietnamese
  873. @"vi" : @[ @"vi", @"vi_VN" ],
  874. // The following are groups of locales or locales that sub-divide a
  875. // language).
  876. // Arabic
  877. @"ar" : @[
  878. @"ar",
  879. @"ar_DZ",
  880. @"ar_BH",
  881. @"ar_EG",
  882. @"ar_IQ",
  883. @"ar_JO",
  884. @"ar_KW",
  885. @"ar_LB",
  886. @"ar_LY",
  887. @"ar_MA",
  888. @"ar_OM",
  889. @"ar_QA",
  890. @"ar_SA",
  891. @"ar_SD",
  892. @"ar_SY",
  893. @"ar_TN",
  894. @"ar_AE",
  895. @"ar_YE",
  896. @"ar_GB",
  897. @"ar-IQ",
  898. @"ar_US"
  899. ],
  900. // Simplified Chinese
  901. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  902. // Traditional Chinese
  903. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  904. // Dutch
  905. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  906. // English
  907. @"en" : @[
  908. @"en",
  909. @"en_AU",
  910. @"en_CA",
  911. @"en_IN",
  912. @"en_IE",
  913. @"en_MT",
  914. @"en_NZ",
  915. @"en_PH",
  916. @"en_SG",
  917. @"en_ZA",
  918. @"en_GB",
  919. @"en_US",
  920. @"en_AE",
  921. @"en-AE",
  922. @"en_AS",
  923. @"en-AU",
  924. @"en_BD",
  925. @"en-CA",
  926. @"en_EG",
  927. @"en_ES",
  928. @"en_GB",
  929. @"en-GB",
  930. @"en_HK",
  931. @"en_ID",
  932. @"en-IN",
  933. @"en_NG",
  934. @"en-PH",
  935. @"en_PK",
  936. @"en-SG",
  937. @"en-US"
  938. ],
  939. // French
  940. @"fr" : @[
  941. @"fr",
  942. @"fr_BE",
  943. @"fr_CA",
  944. @"fr_FR",
  945. @"fr_LU",
  946. @"fr_CH",
  947. @"fr-CA",
  948. @"fr-FR",
  949. @"fr_MA"
  950. ],
  951. // German
  952. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  953. // Greek
  954. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  955. // Italian
  956. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  957. // Japanese
  958. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  959. // Norwegian
  960. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  961. // Brazilian Portuguese
  962. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  963. // European Portuguese
  964. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  965. // Serbian
  966. @"sr" : @[
  967. @"sr_BA",
  968. @"sr_ME",
  969. @"sr_RS",
  970. @"sr_Latn_BA",
  971. @"sr_Latn_ME",
  972. @"sr_Latn_RS"
  973. ],
  974. // European Spanish
  975. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  976. // Mexican Spanish
  977. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  978. // Latin American Spanish
  979. @"es_419" : @[
  980. @"es_AR",
  981. @"es_BO",
  982. @"es_CL",
  983. @"es_CO",
  984. @"es_CR",
  985. @"es_DO",
  986. @"es_EC",
  987. @"es_SV",
  988. @"es_GT",
  989. @"es_HN",
  990. @"es_NI",
  991. @"es_PA",
  992. @"es_PY",
  993. @"es_PE",
  994. @"es_PR",
  995. @"es_UY",
  996. @"es_VE",
  997. @"es-AR",
  998. @"es-CL",
  999. @"es-CO"
  1000. ],
  1001. // Thai
  1002. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  1003. };
  1004. }
  1005. @end