FIRMessaging.m 44 KB

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