FIRMessaging.m 36 KB

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