FIROptions.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FirebaseCore/Extension/FIRAppInternal.h"
  15. #import "FirebaseCore/Extension/FIRLogger.h"
  16. #import "FirebaseCore/Extension/FIROptionsInternal.h"
  17. #import "FirebaseCore/Sources/FIRBundleUtil.h"
  18. #import "FirebaseCore/Sources/Public/FirebaseCore/FIRVersion.h"
  19. // Keys for the strings in the plist file.
  20. NSString *const kFIRAPIKey = @"API_KEY";
  21. NSString *const kFIRTrackingID = @"TRACKING_ID";
  22. NSString *const kFIRGoogleAppID = @"GOOGLE_APP_ID";
  23. NSString *const kFIRClientID = @"CLIENT_ID";
  24. NSString *const kFIRGCMSenderID = @"GCM_SENDER_ID";
  25. NSString *const kFIRAndroidClientID = @"ANDROID_CLIENT_ID";
  26. NSString *const kFIRDatabaseURL = @"DATABASE_URL";
  27. NSString *const kFIRStorageBucket = @"STORAGE_BUCKET";
  28. // The key to locate the expected bundle identifier in the plist file.
  29. NSString *const kFIRBundleID = @"BUNDLE_ID";
  30. // The key to locate the project identifier in the plist file.
  31. NSString *const kFIRProjectID = @"PROJECT_ID";
  32. NSString *const kFIRIsMeasurementEnabled = @"IS_MEASUREMENT_ENABLED";
  33. NSString *const kFIRIsAnalyticsCollectionEnabled = @"FIREBASE_ANALYTICS_COLLECTION_ENABLED";
  34. NSString *const kFIRIsAnalyticsCollectionDeactivated = @"FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED";
  35. // Library version ID formatted like:
  36. // @"5" // Major version (one or more digits)
  37. // @"04" // Minor version (exactly 2 digits)
  38. // @"01" // Build number (exactly 2 digits)
  39. // @"000"; // Fixed "000"
  40. NSString *kFIRLibraryVersionID;
  41. // Plist file name.
  42. NSString *const kServiceInfoFileName = @"GoogleService-Info";
  43. // Plist file type.
  44. NSString *const kServiceInfoFileType = @"plist";
  45. // Exception raised from attempting to modify a FIROptions after it's been copied to a FIRApp.
  46. NSString *const kFIRExceptionBadModification =
  47. @"Attempted to modify options after it's set on FIRApp. Please modify all properties before "
  48. @"initializing FIRApp.";
  49. @interface FIROptions ()
  50. /**
  51. * This property maintains the actual configuration key-value pairs.
  52. */
  53. @property(nonatomic, readwrite) NSMutableDictionary *optionsDictionary;
  54. /**
  55. * Calls `analyticsOptionsDictionaryWithInfoDictionary:` using [NSBundle mainBundle].infoDictionary.
  56. * It combines analytics options from both the infoDictionary and the GoogleService-Info.plist.
  57. * Values which are present in the main plist override values from the GoogleService-Info.plist.
  58. */
  59. @property(nonatomic, readonly) NSDictionary *analyticsOptionsDictionary;
  60. /**
  61. * Combination of analytics options from both the infoDictionary and the GoogleService-Info.plist.
  62. * Values which are present in the infoDictionary override values from the GoogleService-Info.plist.
  63. */
  64. - (NSDictionary *)analyticsOptionsDictionaryWithInfoDictionary:(NSDictionary *)infoDictionary;
  65. /**
  66. * Throw exception if editing is locked when attempting to modify an option.
  67. */
  68. - (void)checkEditingLocked;
  69. @end
  70. @implementation FIROptions {
  71. /// Backing variable for self.analyticsOptionsDictionary.
  72. NSDictionary *_analyticsOptionsDictionary;
  73. }
  74. static FIROptions *sDefaultOptions = nil;
  75. static NSDictionary *sDefaultOptionsDictionary = nil;
  76. static dispatch_once_t sDefaultOptionsOnceToken;
  77. static dispatch_once_t sDefaultOptionsDictionaryOnceToken;
  78. #pragma mark - Public only for internal class methods
  79. + (FIROptions *)defaultOptions {
  80. dispatch_once(&sDefaultOptionsOnceToken, ^{
  81. NSDictionary *defaultOptionsDictionary = [self defaultOptionsDictionary];
  82. if (defaultOptionsDictionary != nil) {
  83. sDefaultOptions =
  84. [[FIROptions alloc] initInternalWithOptionsDictionary:defaultOptionsDictionary];
  85. }
  86. });
  87. return sDefaultOptions;
  88. }
  89. + (FIROptions *)defaultOptionsWithFirebaseKey:(NSString *)key {
  90. dispatch_once(&sDefaultOptionsOnceToken, ^{
  91. NSDictionary *defaultOptionsDictionary = [self defaultOptionsDictionaryWithFirebaseKey:key];
  92. if (defaultOptionsDictionary != nil) {
  93. sDefaultOptions =
  94. [[FIROptions alloc] initInternalWithOptionsDictionary:defaultOptionsDictionary];
  95. }
  96. });
  97. return sDefaultOptions;
  98. }
  99. #pragma mark - Private class methods
  100. + (NSDictionary *)defaultOptionsDictionary {
  101. dispatch_once(&sDefaultOptionsDictionaryOnceToken, ^{
  102. NSString *plistFilePath = [FIROptions plistFilePathWithName:kServiceInfoFileName];
  103. if (plistFilePath == nil) {
  104. return;
  105. }
  106. sDefaultOptionsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistFilePath];
  107. if (sDefaultOptionsDictionary == nil) {
  108. FIRLogError(kFIRLoggerCore, @"I-COR000011",
  109. @"The configuration file is not a dictionary: "
  110. @"'%@.%@'.",
  111. kServiceInfoFileName, kServiceInfoFileType);
  112. }
  113. });
  114. return sDefaultOptionsDictionary;
  115. }
  116. + (NSDictionary *)defaultOptionsDictionaryWithFirebaseKey:(NSString *)key {
  117. dispatch_once(&sDefaultOptionsDictionaryOnceToken, ^{
  118. NSArray *items = [key componentsSeparatedByString:@" "];
  119. if (items.count != 2) {
  120. FIRLogError(kFIRLoggerCore, @"I-COR000015",
  121. @"The configuration key is not valid Firebase key"
  122. @"'%@'.",
  123. key);
  124. return;
  125. }
  126. NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:items[0] options:0];
  127. NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
  128. NSLog(@"%@", decodedString);
  129. //TODO: compare bundle ID
  130. NSArray *configItems = [decodedString componentsSeparatedByString:@","];
  131. if (configItems.count != 5) {
  132. FIRLogError(kFIRLoggerCore, @"I-COR000015",
  133. @"The configuration key is not valid Firebase key"
  134. @"'%@'.",
  135. key);
  136. return;
  137. }
  138. NSArray *appIDItems = [configItems[1] componentsSeparatedByString:@":"];
  139. if (appIDItems.count != 4) {
  140. FIRLogError(kFIRLoggerCore, @"I-COR000015",
  141. @"The configuration key is not valid Firebase key"
  142. @"'%@'.",
  143. key);
  144. return;
  145. }
  146. sDefaultOptionsDictionary = @{kFIRAPIKey: configItems[0], kFIRGoogleAppID: configItems[1],kFIRProjectID: configItems[2],kFIRStorageBucket: configItems[3],kFIRDatabaseURL: configItems[4], kFIRBundleID: items[1], kFIRGCMSenderID: appIDItems[1]};
  147. if (sDefaultOptionsDictionary == nil) {
  148. FIRLogError(kFIRLoggerCore, @"I-COR000011",
  149. @"The configuration file is not a dictionary: "
  150. @"'%@.%@'.",
  151. kServiceInfoFileName, kServiceInfoFileType);
  152. }
  153. });
  154. return sDefaultOptionsDictionary;
  155. }
  156. // Returns the path of the plist file with a given file name.
  157. + (NSString *)plistFilePathWithName:(NSString *)fileName {
  158. NSArray *bundles = [FIRBundleUtil relevantBundles];
  159. NSString *plistFilePath =
  160. [FIRBundleUtil optionsDictionaryPathWithResourceName:fileName
  161. andFileType:kServiceInfoFileType
  162. inBundles:bundles];
  163. if (plistFilePath == nil) {
  164. FIRLogError(kFIRLoggerCore, @"I-COR000012", @"Could not locate configuration file: '%@.%@'.",
  165. fileName, kServiceInfoFileType);
  166. }
  167. return plistFilePath;
  168. }
  169. + (void)resetDefaultOptions {
  170. sDefaultOptions = nil;
  171. sDefaultOptionsDictionary = nil;
  172. sDefaultOptionsOnceToken = 0;
  173. sDefaultOptionsDictionaryOnceToken = 0;
  174. }
  175. #pragma mark - Private instance methods
  176. - (instancetype)initInternalWithOptionsDictionary:(NSDictionary *)optionsDictionary {
  177. self = [super init];
  178. if (self) {
  179. _optionsDictionary = [optionsDictionary mutableCopy];
  180. _usingOptionsFromDefaultPlist = YES;
  181. }
  182. return self;
  183. }
  184. - (id)copyWithZone:(NSZone *)zone {
  185. FIROptions *newOptions = [(FIROptions *)[[self class] allocWithZone:zone]
  186. initInternalWithOptionsDictionary:self.optionsDictionary];
  187. if (newOptions) {
  188. newOptions.deepLinkURLScheme = self.deepLinkURLScheme;
  189. newOptions.appGroupID = self.appGroupID;
  190. newOptions.editingLocked = self.isEditingLocked;
  191. newOptions.usingOptionsFromDefaultPlist = self.usingOptionsFromDefaultPlist;
  192. }
  193. return newOptions;
  194. }
  195. #pragma mark - Public instance methods
  196. - (instancetype)init {
  197. // Unavailable.
  198. [self doesNotRecognizeSelector:_cmd];
  199. return nil;
  200. }
  201. - (instancetype)initWithContentsOfFile:(NSString *)plistPath {
  202. self = [super init];
  203. if (self) {
  204. if (plistPath == nil) {
  205. FIRLogError(kFIRLoggerCore, @"I-COR000013", @"The plist file path is nil.");
  206. return nil;
  207. }
  208. _optionsDictionary = [[NSDictionary dictionaryWithContentsOfFile:plistPath] mutableCopy];
  209. if (_optionsDictionary == nil) {
  210. FIRLogError(kFIRLoggerCore, @"I-COR000014",
  211. @"The configuration file at %@ does not exist or "
  212. @"is not a well-formed plist file.",
  213. plistPath);
  214. return nil;
  215. }
  216. // TODO: Do we want to validate the dictionary here? It says we do that already in
  217. // the public header.
  218. }
  219. return self;
  220. }
  221. - (instancetype)initWithGoogleAppID:(NSString *)googleAppID GCMSenderID:(NSString *)GCMSenderID {
  222. self = [super init];
  223. if (self) {
  224. NSMutableDictionary *mutableOptionsDict = [NSMutableDictionary dictionary];
  225. [mutableOptionsDict setValue:googleAppID forKey:kFIRGoogleAppID];
  226. [mutableOptionsDict setValue:GCMSenderID forKey:kFIRGCMSenderID];
  227. [mutableOptionsDict setValue:[[NSBundle mainBundle] bundleIdentifier] forKey:kFIRBundleID];
  228. self.optionsDictionary = mutableOptionsDict;
  229. }
  230. return self;
  231. }
  232. - (NSString *)APIKey {
  233. return self.optionsDictionary[kFIRAPIKey];
  234. }
  235. - (void)checkEditingLocked {
  236. if (self.isEditingLocked) {
  237. [NSException raise:kFirebaseCoreErrorDomain format:kFIRExceptionBadModification];
  238. }
  239. }
  240. - (void)setAPIKey:(NSString *)APIKey {
  241. [self checkEditingLocked];
  242. _optionsDictionary[kFIRAPIKey] = [APIKey copy];
  243. }
  244. - (NSString *)clientID {
  245. return self.optionsDictionary[kFIRClientID];
  246. }
  247. - (void)setClientID:(NSString *)clientID {
  248. [self checkEditingLocked];
  249. _optionsDictionary[kFIRClientID] = [clientID copy];
  250. }
  251. - (NSString *)trackingID {
  252. return self.optionsDictionary[kFIRTrackingID];
  253. }
  254. - (void)setTrackingID:(NSString *)trackingID {
  255. [self checkEditingLocked];
  256. _optionsDictionary[kFIRTrackingID] = [trackingID copy];
  257. }
  258. - (NSString *)GCMSenderID {
  259. return self.optionsDictionary[kFIRGCMSenderID];
  260. }
  261. - (void)setGCMSenderID:(NSString *)GCMSenderID {
  262. [self checkEditingLocked];
  263. _optionsDictionary[kFIRGCMSenderID] = [GCMSenderID copy];
  264. }
  265. - (NSString *)projectID {
  266. return self.optionsDictionary[kFIRProjectID];
  267. }
  268. - (void)setProjectID:(NSString *)projectID {
  269. [self checkEditingLocked];
  270. _optionsDictionary[kFIRProjectID] = [projectID copy];
  271. }
  272. - (NSString *)androidClientID {
  273. return self.optionsDictionary[kFIRAndroidClientID];
  274. }
  275. - (void)setAndroidClientID:(NSString *)androidClientID {
  276. [self checkEditingLocked];
  277. _optionsDictionary[kFIRAndroidClientID] = [androidClientID copy];
  278. }
  279. - (NSString *)googleAppID {
  280. return self.optionsDictionary[kFIRGoogleAppID];
  281. }
  282. - (void)setGoogleAppID:(NSString *)googleAppID {
  283. [self checkEditingLocked];
  284. _optionsDictionary[kFIRGoogleAppID] = [googleAppID copy];
  285. }
  286. - (NSString *)libraryVersionID {
  287. static dispatch_once_t onceToken;
  288. dispatch_once(&onceToken, ^{
  289. // The unit tests are set up to catch anything that does not properly convert.
  290. NSString *version = FIRFirebaseVersion();
  291. NSArray *components = [version componentsSeparatedByString:@"."];
  292. NSString *major = [components objectAtIndex:0];
  293. NSString *minor = [NSString stringWithFormat:@"%02d", [[components objectAtIndex:1] intValue]];
  294. NSString *patch = [NSString stringWithFormat:@"%02d", [[components objectAtIndex:2] intValue]];
  295. kFIRLibraryVersionID = [NSString stringWithFormat:@"%@%@%@000", major, minor, patch];
  296. });
  297. return kFIRLibraryVersionID;
  298. }
  299. - (void)setLibraryVersionID:(NSString *)libraryVersionID {
  300. _optionsDictionary[kFIRLibraryVersionID] = [libraryVersionID copy];
  301. }
  302. - (NSString *)databaseURL {
  303. return self.optionsDictionary[kFIRDatabaseURL];
  304. }
  305. - (void)setDatabaseURL:(NSString *)databaseURL {
  306. [self checkEditingLocked];
  307. _optionsDictionary[kFIRDatabaseURL] = [databaseURL copy];
  308. }
  309. - (NSString *)storageBucket {
  310. return self.optionsDictionary[kFIRStorageBucket];
  311. }
  312. - (void)setStorageBucket:(NSString *)storageBucket {
  313. [self checkEditingLocked];
  314. _optionsDictionary[kFIRStorageBucket] = [storageBucket copy];
  315. }
  316. - (void)setDeepLinkURLScheme:(NSString *)deepLinkURLScheme {
  317. [self checkEditingLocked];
  318. _deepLinkURLScheme = [deepLinkURLScheme copy];
  319. }
  320. - (NSString *)bundleID {
  321. return self.optionsDictionary[kFIRBundleID];
  322. }
  323. - (void)setBundleID:(NSString *)bundleID {
  324. [self checkEditingLocked];
  325. _optionsDictionary[kFIRBundleID] = [bundleID copy];
  326. }
  327. - (void)setAppGroupID:(NSString *)appGroupID {
  328. [self checkEditingLocked];
  329. _appGroupID = [appGroupID copy];
  330. }
  331. #pragma mark - Equality
  332. - (BOOL)isEqual:(id)object {
  333. if (!object || ![object isKindOfClass:[FIROptions class]]) {
  334. return NO;
  335. }
  336. return [self isEqualToOptions:(FIROptions *)object];
  337. }
  338. - (BOOL)isEqualToOptions:(FIROptions *)options {
  339. // Skip any non-FIROptions classes.
  340. if (![options isKindOfClass:[FIROptions class]]) {
  341. return NO;
  342. }
  343. // Check the internal dictionary and custom properties for differences.
  344. if (![options.optionsDictionary isEqualToDictionary:self.optionsDictionary]) {
  345. return NO;
  346. }
  347. // Validate extra properties not contained in the dictionary. Only validate it if one of the
  348. // objects has the property set.
  349. if ((options.deepLinkURLScheme != nil || self.deepLinkURLScheme != nil) &&
  350. ![options.deepLinkURLScheme isEqualToString:self.deepLinkURLScheme]) {
  351. return NO;
  352. }
  353. if ((options.appGroupID != nil || self.appGroupID != nil) &&
  354. ![options.appGroupID isEqualToString:self.appGroupID]) {
  355. return NO;
  356. }
  357. // Validate the Analytics options haven't changed with the Info.plist.
  358. if (![options.analyticsOptionsDictionary isEqualToDictionary:self.analyticsOptionsDictionary]) {
  359. return NO;
  360. }
  361. // We don't care about the `editingLocked` or `usingOptionsFromDefaultPlist` properties since
  362. // those relate to lifecycle and construction, we only care if the contents of the options
  363. // themselves are equal.
  364. return YES;
  365. }
  366. - (NSUInteger)hash {
  367. // This is strongly recommended for any object that implements a custom `isEqual:` method to
  368. // ensure that dictionary and set behavior matches other `isEqual:` checks.
  369. // Note: `self.analyticsOptionsDictionary` was left out here since it solely relies on the
  370. // contents of the main bundle's `Info.plist`. We should avoid reading that file and the contents
  371. // should be identical.
  372. return self.optionsDictionary.hash ^ self.deepLinkURLScheme.hash ^ self.appGroupID.hash;
  373. }
  374. #pragma mark - Internal instance methods
  375. - (NSDictionary *)analyticsOptionsDictionaryWithInfoDictionary:(NSDictionary *)infoDictionary {
  376. if (_analyticsOptionsDictionary == nil) {
  377. NSMutableDictionary *tempAnalyticsOptions = [[NSMutableDictionary alloc] init];
  378. NSArray *measurementKeys = @[
  379. kFIRIsMeasurementEnabled, kFIRIsAnalyticsCollectionEnabled,
  380. kFIRIsAnalyticsCollectionDeactivated
  381. ];
  382. for (NSString *key in measurementKeys) {
  383. id value = infoDictionary[key] ?: self.optionsDictionary[key] ?: nil;
  384. if (!value) {
  385. continue;
  386. }
  387. tempAnalyticsOptions[key] = value;
  388. }
  389. _analyticsOptionsDictionary = tempAnalyticsOptions;
  390. }
  391. return _analyticsOptionsDictionary;
  392. }
  393. - (NSDictionary *)analyticsOptionsDictionary {
  394. return [self analyticsOptionsDictionaryWithInfoDictionary:[NSBundle mainBundle].infoDictionary];
  395. }
  396. /**
  397. * Whether or not Measurement was enabled. Measurement is enabled unless explicitly disabled in
  398. * GoogleService-Info.plist. This uses the old plist flag IS_MEASUREMENT_ENABLED, which should still
  399. * be supported.
  400. */
  401. - (BOOL)isMeasurementEnabled {
  402. if (self.isAnalyticsCollectionDeactivated) {
  403. return NO;
  404. }
  405. NSNumber *value = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled];
  406. if (value == nil) {
  407. // TODO: This could probably be cleaned up since FIROptions shouldn't know about FIRApp or have
  408. // to check if it's the default app. The FIROptions instance can't be modified after
  409. // `+configure` is called, so it's not a good place to copy it either in case the flag is
  410. // changed at runtime.
  411. // If no values are set for Analytics, fall back to the global collection switch in FIRApp.
  412. // Analytics only supports the default FIRApp, so check that first.
  413. if (![FIRApp isDefaultAppConfigured]) {
  414. return NO;
  415. }
  416. // Fall back to the default app's collection switch when the key is not in the dictionary.
  417. return [FIRApp defaultApp].isDataCollectionDefaultEnabled;
  418. }
  419. return [value boolValue];
  420. }
  421. - (BOOL)isAnalyticsCollectionExplicitlySet {
  422. // If it's de-activated, it classifies as explicity set. If not, it's not a good enough indication
  423. // that the developer wants FirebaseAnalytics enabled so continue checking.
  424. if (self.isAnalyticsCollectionDeactivated) {
  425. return YES;
  426. }
  427. // Check if the current Analytics flag is set.
  428. id collectionEnabledObject = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled];
  429. if (collectionEnabledObject && [collectionEnabledObject isKindOfClass:[NSNumber class]]) {
  430. // It doesn't matter what the value is, it's explicitly set.
  431. return YES;
  432. }
  433. // Check if the old measurement flag is set.
  434. id measurementEnabledObject = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled];
  435. if (measurementEnabledObject && [measurementEnabledObject isKindOfClass:[NSNumber class]]) {
  436. // It doesn't matter what the value is, it's explicitly set.
  437. return YES;
  438. }
  439. // No flags are set to explicitly enable or disable FirebaseAnalytics.
  440. return NO;
  441. }
  442. - (BOOL)isAnalyticsCollectionEnabled {
  443. if (self.isAnalyticsCollectionDeactivated) {
  444. return NO;
  445. }
  446. NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled];
  447. if (value == nil) {
  448. return self.isMeasurementEnabled; // Fall back to older plist flag.
  449. }
  450. return [value boolValue];
  451. }
  452. - (BOOL)isAnalyticsCollectionDeactivated {
  453. NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionDeactivated];
  454. if (value == nil) {
  455. return NO; // Analytics Collection is not deactivated when the key is not in the dictionary.
  456. }
  457. return [value boolValue];
  458. }
  459. @end