FIROptions.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. #pragma mark - Private class methods
  90. + (NSDictionary *)defaultOptionsDictionary {
  91. dispatch_once(&sDefaultOptionsDictionaryOnceToken, ^{
  92. NSString *plistFilePath = [FIROptions plistFilePathWithName:kServiceInfoFileName];
  93. if (plistFilePath == nil) {
  94. return;
  95. }
  96. sDefaultOptionsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistFilePath];
  97. if (sDefaultOptionsDictionary == nil) {
  98. FIRLogError(kFIRLoggerCore, @"I-COR000011",
  99. @"The configuration file is not a dictionary: "
  100. @"'%@.%@'.",
  101. kServiceInfoFileName, kServiceInfoFileType);
  102. }
  103. });
  104. return sDefaultOptionsDictionary;
  105. }
  106. // Returns the path of the plist file with a given file name.
  107. + (NSString *)plistFilePathWithName:(NSString *)fileName {
  108. NSArray *bundles = [FIRBundleUtil relevantBundles];
  109. NSString *plistFilePath =
  110. [FIRBundleUtil optionsDictionaryPathWithResourceName:fileName
  111. andFileType:kServiceInfoFileType
  112. inBundles:bundles];
  113. if (plistFilePath == nil) {
  114. FIRLogError(kFIRLoggerCore, @"I-COR000012", @"Could not locate configuration file: '%@.%@'.",
  115. fileName, kServiceInfoFileType);
  116. }
  117. return plistFilePath;
  118. }
  119. + (void)resetDefaultOptions {
  120. sDefaultOptions = nil;
  121. sDefaultOptionsDictionary = nil;
  122. sDefaultOptionsOnceToken = 0;
  123. sDefaultOptionsDictionaryOnceToken = 0;
  124. }
  125. #pragma mark - Private instance methods
  126. - (instancetype)initInternalWithOptionsDictionary:(NSDictionary *)optionsDictionary {
  127. self = [super init];
  128. if (self) {
  129. _optionsDictionary = [optionsDictionary mutableCopy];
  130. _usingOptionsFromDefaultPlist = YES;
  131. }
  132. return self;
  133. }
  134. - (id)copyWithZone:(NSZone *)zone {
  135. FIROptions *newOptions = [(FIROptions *)[[self class] allocWithZone:zone]
  136. initInternalWithOptionsDictionary:self.optionsDictionary];
  137. if (newOptions) {
  138. newOptions.deepLinkURLScheme = self.deepLinkURLScheme;
  139. newOptions.appGroupID = self.appGroupID;
  140. newOptions.editingLocked = self.isEditingLocked;
  141. newOptions.usingOptionsFromDefaultPlist = self.usingOptionsFromDefaultPlist;
  142. }
  143. return newOptions;
  144. }
  145. #pragma mark - Public instance methods
  146. - (instancetype)init {
  147. // Unavailable.
  148. [self doesNotRecognizeSelector:_cmd];
  149. return nil;
  150. }
  151. - (instancetype)initWithContentsOfFile:(NSString *)plistPath {
  152. self = [super init];
  153. if (self) {
  154. if (plistPath == nil) {
  155. FIRLogError(kFIRLoggerCore, @"I-COR000013", @"The plist file path is nil.");
  156. return nil;
  157. }
  158. _optionsDictionary = [[NSDictionary dictionaryWithContentsOfFile:plistPath] mutableCopy];
  159. if (_optionsDictionary == nil) {
  160. FIRLogError(kFIRLoggerCore, @"I-COR000014",
  161. @"The configuration file at %@ does not exist or "
  162. @"is not a well-formed plist file.",
  163. plistPath);
  164. return nil;
  165. }
  166. // TODO: Do we want to validate the dictionary here? It says we do that already in
  167. // the public header.
  168. }
  169. return self;
  170. }
  171. - (instancetype)initWithGoogleAppID:(NSString *)googleAppID GCMSenderID:(NSString *)GCMSenderID {
  172. self = [super init];
  173. if (self) {
  174. NSMutableDictionary *mutableOptionsDict = [NSMutableDictionary dictionary];
  175. [mutableOptionsDict setValue:googleAppID forKey:kFIRGoogleAppID];
  176. [mutableOptionsDict setValue:GCMSenderID forKey:kFIRGCMSenderID];
  177. [mutableOptionsDict setValue:[[NSBundle mainBundle] bundleIdentifier] forKey:kFIRBundleID];
  178. self.optionsDictionary = mutableOptionsDict;
  179. }
  180. return self;
  181. }
  182. - (NSString *)APIKey {
  183. return self.optionsDictionary[kFIRAPIKey];
  184. }
  185. - (void)checkEditingLocked {
  186. if (self.isEditingLocked) {
  187. [NSException raise:kFirebaseCoreErrorDomain format:kFIRExceptionBadModification];
  188. }
  189. }
  190. - (void)setAPIKey:(NSString *)APIKey {
  191. [self checkEditingLocked];
  192. _optionsDictionary[kFIRAPIKey] = [APIKey copy];
  193. }
  194. - (NSString *)clientID {
  195. return self.optionsDictionary[kFIRClientID];
  196. }
  197. - (void)setClientID:(NSString *)clientID {
  198. [self checkEditingLocked];
  199. _optionsDictionary[kFIRClientID] = [clientID copy];
  200. }
  201. - (NSString *)trackingID {
  202. return self.optionsDictionary[kFIRTrackingID];
  203. }
  204. - (void)setTrackingID:(NSString *)trackingID {
  205. [self checkEditingLocked];
  206. _optionsDictionary[kFIRTrackingID] = [trackingID copy];
  207. }
  208. - (NSString *)GCMSenderID {
  209. return self.optionsDictionary[kFIRGCMSenderID];
  210. }
  211. - (void)setGCMSenderID:(NSString *)GCMSenderID {
  212. [self checkEditingLocked];
  213. _optionsDictionary[kFIRGCMSenderID] = [GCMSenderID copy];
  214. }
  215. - (NSString *)projectID {
  216. return self.optionsDictionary[kFIRProjectID];
  217. }
  218. - (void)setProjectID:(NSString *)projectID {
  219. [self checkEditingLocked];
  220. _optionsDictionary[kFIRProjectID] = [projectID copy];
  221. }
  222. - (NSString *)androidClientID {
  223. return self.optionsDictionary[kFIRAndroidClientID];
  224. }
  225. - (void)setAndroidClientID:(NSString *)androidClientID {
  226. [self checkEditingLocked];
  227. _optionsDictionary[kFIRAndroidClientID] = [androidClientID copy];
  228. }
  229. - (NSString *)googleAppID {
  230. return self.optionsDictionary[kFIRGoogleAppID];
  231. }
  232. - (void)setGoogleAppID:(NSString *)googleAppID {
  233. [self checkEditingLocked];
  234. _optionsDictionary[kFIRGoogleAppID] = [googleAppID copy];
  235. }
  236. - (NSString *)libraryVersionID {
  237. static dispatch_once_t onceToken;
  238. dispatch_once(&onceToken, ^{
  239. // The unit tests are set up to catch anything that does not properly convert.
  240. NSString *version = FIRFirebaseVersion();
  241. NSArray *components = [version componentsSeparatedByString:@"."];
  242. NSString *major = [components objectAtIndex:0];
  243. NSString *minor = [NSString stringWithFormat:@"%02d", [[components objectAtIndex:1] intValue]];
  244. NSString *patch = [NSString stringWithFormat:@"%02d", [[components objectAtIndex:2] intValue]];
  245. kFIRLibraryVersionID = [NSString stringWithFormat:@"%@%@%@000", major, minor, patch];
  246. });
  247. return kFIRLibraryVersionID;
  248. }
  249. - (void)setLibraryVersionID:(NSString *)libraryVersionID {
  250. _optionsDictionary[kFIRLibraryVersionID] = [libraryVersionID copy];
  251. }
  252. - (NSString *)databaseURL {
  253. return self.optionsDictionary[kFIRDatabaseURL];
  254. }
  255. - (void)setDatabaseURL:(NSString *)databaseURL {
  256. [self checkEditingLocked];
  257. _optionsDictionary[kFIRDatabaseURL] = [databaseURL copy];
  258. }
  259. - (NSString *)storageBucket {
  260. return self.optionsDictionary[kFIRStorageBucket];
  261. }
  262. - (void)setStorageBucket:(NSString *)storageBucket {
  263. [self checkEditingLocked];
  264. _optionsDictionary[kFIRStorageBucket] = [storageBucket copy];
  265. }
  266. - (void)setDeepLinkURLScheme:(NSString *)deepLinkURLScheme {
  267. [self checkEditingLocked];
  268. _deepLinkURLScheme = [deepLinkURLScheme copy];
  269. }
  270. - (NSString *)bundleID {
  271. return self.optionsDictionary[kFIRBundleID];
  272. }
  273. - (void)setBundleID:(NSString *)bundleID {
  274. [self checkEditingLocked];
  275. _optionsDictionary[kFIRBundleID] = [bundleID copy];
  276. }
  277. - (void)setAppGroupID:(NSString *)appGroupID {
  278. [self checkEditingLocked];
  279. _appGroupID = [appGroupID copy];
  280. }
  281. #pragma mark - Equality
  282. - (BOOL)isEqual:(id)object {
  283. if (!object || ![object isKindOfClass:[FIROptions class]]) {
  284. return NO;
  285. }
  286. return [self isEqualToOptions:(FIROptions *)object];
  287. }
  288. - (BOOL)isEqualToOptions:(FIROptions *)options {
  289. // Skip any non-FIROptions classes.
  290. if (![options isKindOfClass:[FIROptions class]]) {
  291. return NO;
  292. }
  293. // Check the internal dictionary and custom properties for differences.
  294. if (![options.optionsDictionary isEqualToDictionary:self.optionsDictionary]) {
  295. return NO;
  296. }
  297. // Validate extra properties not contained in the dictionary. Only validate it if one of the
  298. // objects has the property set.
  299. if ((options.deepLinkURLScheme != nil || self.deepLinkURLScheme != nil) &&
  300. ![options.deepLinkURLScheme isEqualToString:self.deepLinkURLScheme]) {
  301. return NO;
  302. }
  303. if ((options.appGroupID != nil || self.appGroupID != nil) &&
  304. ![options.appGroupID isEqualToString:self.appGroupID]) {
  305. return NO;
  306. }
  307. // Validate the Analytics options haven't changed with the Info.plist.
  308. if (![options.analyticsOptionsDictionary isEqualToDictionary:self.analyticsOptionsDictionary]) {
  309. return NO;
  310. }
  311. // We don't care about the `editingLocked` or `usingOptionsFromDefaultPlist` properties since
  312. // those relate to lifecycle and construction, we only care if the contents of the options
  313. // themselves are equal.
  314. return YES;
  315. }
  316. - (NSUInteger)hash {
  317. // This is strongly recommended for any object that implements a custom `isEqual:` method to
  318. // ensure that dictionary and set behavior matches other `isEqual:` checks.
  319. // Note: `self.analyticsOptionsDictionary` was left out here since it solely relies on the
  320. // contents of the main bundle's `Info.plist`. We should avoid reading that file and the contents
  321. // should be identical.
  322. return self.optionsDictionary.hash ^ self.deepLinkURLScheme.hash ^ self.appGroupID.hash;
  323. }
  324. #pragma mark - Internal instance methods
  325. - (NSDictionary *)analyticsOptionsDictionaryWithInfoDictionary:(NSDictionary *)infoDictionary {
  326. if (_analyticsOptionsDictionary == nil) {
  327. NSMutableDictionary *tempAnalyticsOptions = [[NSMutableDictionary alloc] init];
  328. NSArray *measurementKeys = @[
  329. kFIRIsMeasurementEnabled, kFIRIsAnalyticsCollectionEnabled,
  330. kFIRIsAnalyticsCollectionDeactivated
  331. ];
  332. for (NSString *key in measurementKeys) {
  333. id value = infoDictionary[key] ?: self.optionsDictionary[key] ?: nil;
  334. if (!value) {
  335. continue;
  336. }
  337. tempAnalyticsOptions[key] = value;
  338. }
  339. _analyticsOptionsDictionary = tempAnalyticsOptions;
  340. }
  341. return _analyticsOptionsDictionary;
  342. }
  343. - (NSDictionary *)analyticsOptionsDictionary {
  344. return [self analyticsOptionsDictionaryWithInfoDictionary:[NSBundle mainBundle].infoDictionary];
  345. }
  346. /**
  347. * Whether or not Measurement was enabled. Measurement is enabled unless explicitly disabled in
  348. * GoogleService-Info.plist. This uses the old plist flag IS_MEASUREMENT_ENABLED, which should still
  349. * be supported.
  350. */
  351. - (BOOL)isMeasurementEnabled {
  352. if (self.isAnalyticsCollectionDeactivated) {
  353. return NO;
  354. }
  355. NSNumber *value = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled];
  356. if (value == nil) {
  357. // TODO: This could probably be cleaned up since FIROptions shouldn't know about FIRApp or have
  358. // to check if it's the default app. The FIROptions instance can't be modified after
  359. // `+configure` is called, so it's not a good place to copy it either in case the flag is
  360. // changed at runtime.
  361. // If no values are set for Analytics, fall back to the global collection switch in FIRApp.
  362. // Analytics only supports the default FIRApp, so check that first.
  363. if (![FIRApp isDefaultAppConfigured]) {
  364. return NO;
  365. }
  366. // Fall back to the default app's collection switch when the key is not in the dictionary.
  367. return [FIRApp defaultApp].isDataCollectionDefaultEnabled;
  368. }
  369. return [value boolValue];
  370. }
  371. - (BOOL)isAnalyticsCollectionExplicitlySet {
  372. // If it's de-activated, it classifies as explicity set. If not, it's not a good enough indication
  373. // that the developer wants FirebaseAnalytics enabled so continue checking.
  374. if (self.isAnalyticsCollectionDeactivated) {
  375. return YES;
  376. }
  377. // Check if the current Analytics flag is set.
  378. id collectionEnabledObject = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled];
  379. if (collectionEnabledObject && [collectionEnabledObject isKindOfClass:[NSNumber class]]) {
  380. // It doesn't matter what the value is, it's explicitly set.
  381. return YES;
  382. }
  383. // Check if the old measurement flag is set.
  384. id measurementEnabledObject = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled];
  385. if (measurementEnabledObject && [measurementEnabledObject isKindOfClass:[NSNumber class]]) {
  386. // It doesn't matter what the value is, it's explicitly set.
  387. return YES;
  388. }
  389. // No flags are set to explicitly enable or disable FirebaseAnalytics.
  390. return NO;
  391. }
  392. - (BOOL)isAnalyticsCollectionEnabled {
  393. if (self.isAnalyticsCollectionDeactivated) {
  394. return NO;
  395. }
  396. NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled];
  397. if (value == nil) {
  398. return self.isMeasurementEnabled; // Fall back to older plist flag.
  399. }
  400. return [value boolValue];
  401. }
  402. - (BOOL)isAnalyticsCollectionDeactivated {
  403. NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionDeactivated];
  404. if (value == nil) {
  405. return NO; // Analytics Collection is not deactivated when the key is not in the dictionary.
  406. }
  407. return [value boolValue];
  408. }
  409. @end