FIRMessaging.m 47 KB

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