FIRMessaging.m 37 KB

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