FIRMessaging.m 44 KB

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