FIRMessaging.m 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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:kFIRMessagingRegistrationTokenRefreshNotification
  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. if (![NSThread isMainThread]) {
  465. // Call this method from the main thread
  466. dispatch_async(dispatch_get_main_queue(), ^{
  467. [self updateAutomaticClientConnection];
  468. });
  469. return;
  470. }
  471. BOOL shouldBeConnected = [self shouldBeConnectedAutomatically];
  472. if (shouldBeConnected && !self.client.isConnected) {
  473. [self.client connectWithHandler:^(NSError *error) {
  474. if (!error) {
  475. // It means we connected. Fire connection change notification
  476. [self notifyOfDirectChannelConnectionChange];
  477. }
  478. }];
  479. } else if (!shouldBeConnected && self.client.isConnected) {
  480. [self.client disconnect];
  481. [self notifyOfDirectChannelConnectionChange];
  482. }
  483. }
  484. - (void)notifyOfDirectChannelConnectionChange {
  485. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  486. [center postNotificationName:FIRMessagingConnectionStateChangedNotification object:self];
  487. }
  488. #pragma mark - Connect
  489. - (void)connectWithCompletion:(FIRMessagingConnectCompletion)handler {
  490. _FIRMessagingDevAssert([NSThread isMainThread],
  491. @"FIRMessaging connect should be called from main thread only.");
  492. _FIRMessagingDevAssert(self.isClientSetup, @"FIRMessaging client not setup.");
  493. [self.client connectWithHandler:^(NSError *error) {
  494. if (handler) {
  495. handler(error);
  496. }
  497. if (!error) {
  498. // It means we connected. Fire connection change notification
  499. [self notifyOfDirectChannelConnectionChange];
  500. }
  501. }];
  502. }
  503. - (void)disconnect {
  504. _FIRMessagingDevAssert([NSThread isMainThread],
  505. @"FIRMessaging should be called from main thread only.");
  506. if ([self.client isConnected]) {
  507. [self.client disconnect];
  508. [self notifyOfDirectChannelConnectionChange];
  509. }
  510. }
  511. #pragma mark - Topics
  512. + (NSString *)normalizeTopic:(NSString *)topic {
  513. if (![FIRMessagingPubSub hasTopicsPrefix:topic]) {
  514. topic = [FIRMessagingPubSub addPrefixToTopic:topic];
  515. }
  516. if ([FIRMessagingPubSub isValidTopicWithPrefix:topic]) {
  517. return [topic copy];
  518. }
  519. return nil;
  520. }
  521. - (void)subscribeToTopic:(NSString *)topic {
  522. if (self.defaultFcmToken.length && topic.length) {
  523. NSString *normalizeTopic = [[self class ] normalizeTopic:topic];
  524. if (normalizeTopic.length) {
  525. [self.pubsub subscribeToTopic:normalizeTopic];
  526. } else {
  527. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging009,
  528. @"Cannot parse topic name %@. Will not subscribe.", topic);
  529. }
  530. } else {
  531. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging010,
  532. @"Cannot subscribe to topic: %@ with token: %@", topic,
  533. self.defaultFcmToken);
  534. }
  535. }
  536. - (void)unsubscribeFromTopic:(NSString *)topic {
  537. if (self.defaultFcmToken.length && topic.length) {
  538. NSString *normalizeTopic = [[self class] normalizeTopic:topic];
  539. if (normalizeTopic.length) {
  540. [self.pubsub unsubscribeFromTopic:normalizeTopic];
  541. } else {
  542. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging011,
  543. @"Cannot parse topic name %@. Will not unsubscribe.", topic);
  544. }
  545. } else {
  546. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging012,
  547. @"Cannot unsubscribe to topic: %@ with token: %@", topic,
  548. self.defaultFcmToken);
  549. }
  550. }
  551. #pragma mark - Send
  552. - (void)sendMessage:(NSDictionary *)message
  553. to:(NSString *)to
  554. withMessageID:(NSString *)messageID
  555. timeToLive:(int64_t)ttl {
  556. _FIRMessagingDevAssert([to length] != 0, @"Invalid receiver id for FIRMessaging-message");
  557. NSMutableDictionary *fcmMessage = [[self class] createFIRMessagingMessageWithMessage:message
  558. to:to
  559. withID:messageID
  560. timeToLive:ttl
  561. delay:0];
  562. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessaging013, @"Sending message: %@ with id: %@",
  563. message, messageID);
  564. [self.dataMessageManager sendDataMessageStanza:fcmMessage];
  565. }
  566. + (NSMutableDictionary *)createFIRMessagingMessageWithMessage:(NSDictionary *)message
  567. to:(NSString *)to
  568. withID:(NSString *)msgID
  569. timeToLive:(int64_t)ttl
  570. delay:(int)delay {
  571. NSMutableDictionary *fcmMessage = [NSMutableDictionary dictionary];
  572. fcmMessage[kFIRMessagingSendTo] = [to copy];
  573. fcmMessage[kFIRMessagingSendMessageID] = msgID ? [msgID copy] : @"";
  574. fcmMessage[kFIRMessagingSendTTL] = @(ttl);
  575. fcmMessage[kFIRMessagingSendDelay] = @(delay);
  576. fcmMessage[KFIRMessagingSendMessageAppData] =
  577. [NSMutableDictionary dictionaryWithDictionary:message];
  578. return fcmMessage;
  579. }
  580. #pragma mark - IID dependencies
  581. // FIRMessagingInternalUtilities.h to see usage.
  582. + (NSString *)FIRMessagingSDKVersion {
  583. NSString *semanticVersion = FIRMessagingCurrentLibraryVersion();
  584. // Use prefix fcm for all FCM libs. This allows us to differentiate b/w
  585. // the new and old FCM registrations.
  586. return [NSString stringWithFormat:@"fcm-%@", semanticVersion];
  587. }
  588. + (NSString *)FIRMessagingSDKCurrentLocale {
  589. return [self currentLocale];
  590. }
  591. - (void)setAPNSToken:(NSData *)apnsToken error:(NSError *)error {
  592. if (apnsToken) {
  593. self.apnsTokenData = [apnsToken copy];
  594. }
  595. }
  596. #pragma mark - FIRMessagingReceiverDelegate
  597. - (void)receiver:(FIRMessagingReceiver *)receiver
  598. receivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  599. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveMessage:)]) {
  600. [self.delegate messaging:self didReceiveMessage:remoteMessage];
  601. } else if ([self.delegate respondsToSelector:@selector(applicationReceivedRemoteMessage:)]) {
  602. #pragma clang diagnostic push
  603. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  604. [self.delegate applicationReceivedRemoteMessage:remoteMessage];
  605. #pragma clang diagnostic pop
  606. } else {
  607. // Delegate methods weren't implemented, so messages are being dropped, log a warning
  608. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeRemoteMessageDelegateMethodNotImplemented,
  609. @"FIRMessaging received data-message, but FIRMessagingDelegate's"
  610. @"-messaging:didReceiveMessage: not implemented");
  611. }
  612. }
  613. #pragma mark - FIRReachabilityDelegate
  614. - (void)reachability:(FIRReachabilityChecker *)reachability
  615. statusChanged:(FIRReachabilityStatus)status {
  616. [self onNetworkStatusChanged];
  617. }
  618. #pragma mark - Network
  619. - (BOOL)isNetworkAvailable {
  620. FIRReachabilityStatus status = self.reachability.reachabilityStatus;
  621. return (status == kFIRReachabilityViaCellular || status == kFIRReachabilityViaWifi);
  622. }
  623. - (FIRMessagingNetworkStatus)networkType {
  624. FIRReachabilityStatus status = self.reachability.reachabilityStatus;
  625. if (![self isNetworkAvailable]) {
  626. return kFIRMessagingReachabilityNotReachable;
  627. } else if (status == kFIRReachabilityViaCellular) {
  628. return kFIRMessagingReachabilityReachableViaWWAN;
  629. } else {
  630. return kFIRMessagingReachabilityReachableViaWiFi;
  631. }
  632. }
  633. #pragma mark - Notifications
  634. - (void)onNetworkStatusChanged {
  635. if (![self.client isConnected] && [self isNetworkAvailable]) {
  636. if (self.client.shouldStayConnected) {
  637. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging014,
  638. @"Attempting to establish direct channel.");
  639. [self.client retryConnectionImmediately:YES];
  640. }
  641. [self.pubsub scheduleSync:YES];
  642. }
  643. }
  644. #pragma mark - Notifications
  645. - (void)didReceiveDefaultInstanceIDToken:(NSNotification *)notification {
  646. if (![notification.object isKindOfClass:[NSString class]]) {
  647. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging015,
  648. @"Invalid default FCM token type %@",
  649. NSStringFromClass([notification.object class]));
  650. return;
  651. }
  652. self.defaultFcmToken = [(NSString *)notification.object copy];
  653. [self.pubsub scheduleSync:YES];
  654. if (self.shouldEstablishDirectChannel) {
  655. [self updateAutomaticClientConnection];
  656. }
  657. }
  658. - (void)defaultInstanceIDTokenWasRefreshed:(NSNotification *)notification {
  659. // Retrieve the Instance ID default token, and if it is non-nil, post it
  660. NSString *token = [self.instanceIDProxy token];
  661. // Sometimes Instance ID doesn't yet have a token, so wait until the default
  662. // token is fetched, and then notify. This ensures that this token should not
  663. // be nil when the developer accesses it.
  664. if (token != nil) {
  665. self.defaultFcmToken = [token copy];
  666. [self.delegate messaging:self didRefreshRegistrationToken:token];
  667. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  668. [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification object:nil];
  669. }
  670. }
  671. - (void)didReceiveAPNSToken:(NSNotification *)notification {
  672. NSData *apnsToken = notification.object;
  673. if (![apnsToken isKindOfClass:[NSData class]]) {
  674. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging016, @"Invalid APNS token type %@",
  675. NSStringFromClass([notification.object class]));
  676. return;
  677. }
  678. // Set this value directly, and since this came from InstanceID, don't set it back to InstanceID
  679. self.apnsTokenData = [apnsToken copy];
  680. }
  681. #pragma mark - Application Support Directory
  682. + (BOOL)hasApplicationSupportSubDirectory:(NSString *)subDirectoryName {
  683. NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName];
  684. BOOL isDirectory;
  685. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  686. isDirectory:&isDirectory]) {
  687. return NO;
  688. } else if (!isDirectory) {
  689. return NO;
  690. }
  691. return YES;
  692. }
  693. + (NSString *)pathForApplicationSupportSubDirectory:(NSString *)subDirectoryName {
  694. NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
  695. NSUserDomainMask, YES);
  696. NSString *applicationSupportDirPath = directoryPaths.lastObject;
  697. NSArray *components = @[applicationSupportDirPath, subDirectoryName];
  698. return [NSString pathWithComponents:components];
  699. }
  700. + (BOOL)createApplicationSupportSubDirectory:(NSString *)subDirectoryName {
  701. NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName];
  702. BOOL hasSubDirectory;
  703. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  704. isDirectory:&hasSubDirectory]) {
  705. NSError *error;
  706. [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
  707. withIntermediateDirectories:YES
  708. attributes:nil
  709. error:&error];
  710. if (error) {
  711. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017,
  712. @"Cannot create directory %@, error: %@", subDirectoryPath, error);
  713. return NO;
  714. }
  715. } else {
  716. if (!hasSubDirectory) {
  717. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018,
  718. @"Found file instead of directory at %@", subDirectoryPath);
  719. return NO;
  720. }
  721. }
  722. return YES;
  723. }
  724. #pragma mark - Locales
  725. + (NSString *)currentLocale {
  726. NSArray *locales = [self firebaseLocales];
  727. NSArray *preferredLocalizations =
  728. [NSBundle preferredLocalizationsFromArray:locales
  729. forPreferences:[NSLocale preferredLanguages]];
  730. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  731. // Use en as the default language
  732. return legalDocsLanguage ? legalDocsLanguage : @"en";
  733. }
  734. + (NSArray *)firebaseLocales {
  735. NSMutableArray *locales = [NSMutableArray array];
  736. NSDictionary *localesMap = [self firebaselocalesMap];
  737. for (NSString *key in localesMap) {
  738. [locales addObjectsFromArray:localesMap[key]];
  739. }
  740. return locales;
  741. }
  742. + (NSDictionary *)firebaselocalesMap {
  743. return @{
  744. // Albanian
  745. @"sq" : @[ @"sq_AL" ],
  746. // Belarusian
  747. @"be" : @[ @"be_BY" ],
  748. // Bulgarian
  749. @"bg" : @[ @"bg_BG" ],
  750. // Catalan
  751. @"ca" : @[ @"ca", @"ca_ES" ],
  752. // Croatian
  753. @"hr" : @[ @"hr", @"hr_HR" ],
  754. // Czech
  755. @"cs" : @[ @"cs", @"cs_CZ" ],
  756. // Danish
  757. @"da" : @[ @"da", @"da_DK" ],
  758. // Estonian
  759. @"et" : @[ @"et_EE" ],
  760. // Finnish
  761. @"fi" : @[ @"fi", @"fi_FI" ],
  762. // Hebrew
  763. @"he" : @[ @"he", @"iw_IL" ],
  764. // Hindi
  765. @"hi" : @[ @"hi_IN" ],
  766. // Hungarian
  767. @"hu" : @[ @"hu", @"hu_HU" ],
  768. // Icelandic
  769. @"is" : @[ @"is_IS" ],
  770. // Indonesian
  771. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  772. // Irish
  773. @"ga" : @[ @"ga_IE" ],
  774. // Korean
  775. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  776. // Latvian
  777. @"lv" : @[ @"lv_LV" ],
  778. // Lithuanian
  779. @"lt" : @[ @"lt_LT" ],
  780. // Macedonian
  781. @"mk" : @[ @"mk_MK" ],
  782. // Malay
  783. @"ms" : @[ @"ms_MY" ],
  784. // Maltese
  785. @"ms" : @[ @"mt_MT" ],
  786. // Polish
  787. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  788. // Romanian
  789. @"ro" : @[ @"ro", @"ro_RO" ],
  790. // Russian
  791. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  792. // Slovak
  793. @"sk" : @[ @"sk", @"sk_SK" ],
  794. // Slovenian
  795. @"sl" : @[ @"sl_SI" ],
  796. // Swedish
  797. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  798. // Turkish
  799. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  800. // Ukrainian
  801. @"uk" : @[ @"uk", @"uk_UA" ],
  802. // Vietnamese
  803. @"vi" : @[ @"vi", @"vi_VN" ],
  804. // The following are groups of locales or locales that sub-divide a
  805. // language).
  806. // Arabic
  807. @"ar" : @[
  808. @"ar",
  809. @"ar_DZ",
  810. @"ar_BH",
  811. @"ar_EG",
  812. @"ar_IQ",
  813. @"ar_JO",
  814. @"ar_KW",
  815. @"ar_LB",
  816. @"ar_LY",
  817. @"ar_MA",
  818. @"ar_OM",
  819. @"ar_QA",
  820. @"ar_SA",
  821. @"ar_SD",
  822. @"ar_SY",
  823. @"ar_TN",
  824. @"ar_AE",
  825. @"ar_YE",
  826. @"ar_GB",
  827. @"ar-IQ",
  828. @"ar_US"
  829. ],
  830. // Simplified Chinese
  831. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  832. // Traditional Chinese
  833. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  834. // Dutch
  835. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  836. // English
  837. @"en" : @[
  838. @"en",
  839. @"en_AU",
  840. @"en_CA",
  841. @"en_IN",
  842. @"en_IE",
  843. @"en_MT",
  844. @"en_NZ",
  845. @"en_PH",
  846. @"en_SG",
  847. @"en_ZA",
  848. @"en_GB",
  849. @"en_US",
  850. @"en_AE",
  851. @"en-AE",
  852. @"en_AS",
  853. @"en-AU",
  854. @"en_BD",
  855. @"en-CA",
  856. @"en_EG",
  857. @"en_ES",
  858. @"en_GB",
  859. @"en-GB",
  860. @"en_HK",
  861. @"en_ID",
  862. @"en-IN",
  863. @"en_NG",
  864. @"en-PH",
  865. @"en_PK",
  866. @"en-SG",
  867. @"en-US"
  868. ],
  869. // French
  870. @"fr" : @[
  871. @"fr",
  872. @"fr_BE",
  873. @"fr_CA",
  874. @"fr_FR",
  875. @"fr_LU",
  876. @"fr_CH",
  877. @"fr-CA",
  878. @"fr-FR",
  879. @"fr_MA"
  880. ],
  881. // German
  882. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  883. // Greek
  884. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  885. // Italian
  886. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  887. // Japanese
  888. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  889. // Norwegian
  890. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  891. // Brazilian Portuguese
  892. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  893. // European Portuguese
  894. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  895. // Serbian
  896. @"sr" : @[
  897. @"sr_BA",
  898. @"sr_ME",
  899. @"sr_RS",
  900. @"sr_Latn_BA",
  901. @"sr_Latn_ME",
  902. @"sr_Latn_RS"
  903. ],
  904. // European Spanish
  905. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  906. // Mexican Spanish
  907. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  908. // Latin American Spanish
  909. @"es_419" : @[
  910. @"es_AR",
  911. @"es_BO",
  912. @"es_CL",
  913. @"es_CO",
  914. @"es_CR",
  915. @"es_DO",
  916. @"es_EC",
  917. @"es_SV",
  918. @"es_GT",
  919. @"es_HN",
  920. @"es_NI",
  921. @"es_PA",
  922. @"es_PY",
  923. @"es_PE",
  924. @"es_PR",
  925. @"es_UY",
  926. @"es_VE",
  927. @"es-AR",
  928. @"es-CL",
  929. @"es-CO"
  930. ],
  931. // Thai
  932. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  933. };
  934. }
  935. @end