FIRFirestore.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. #import "FIRFirestore.h"
  17. #import <FirebaseCore/FIRApp.h>
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <FirebaseCore/FIRComponentContainer.h>
  20. #import <FirebaseCore/FIRLogger.h>
  21. #import <FirebaseCore/FIROptions.h>
  22. #include <memory>
  23. #include <string>
  24. #include <utility>
  25. #import "FIRFirestore.h"
  26. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  27. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  28. #import "Firestore/Source/API/FSTFirestoreComponent.h"
  29. #import "Firestore/Source/API/FSTUserDataConverter.h"
  30. #import "Firestore/Source/Util/FSTUsageValidation.h"
  31. #include "Firestore/core/src/firebase/firestore/api/firestore.h"
  32. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  33. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  34. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  35. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  36. #include "Firestore/core/src/firebase/firestore/util/delayed_constructor.h"
  37. #include "Firestore/core/src/firebase/firestore/util/log.h"
  38. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  39. namespace util = firebase::firestore::util;
  40. using firebase::firestore::api::DocumentReference;
  41. using firebase::firestore::api::Firestore;
  42. using firebase::firestore::auth::CredentialsProvider;
  43. using firebase::firestore::model::DatabaseId;
  44. using firebase::firestore::util::AsyncQueue;
  45. using firebase::firestore::util::DelayedConstructor;
  46. NS_ASSUME_NONNULL_BEGIN
  47. extern "C" NSString *const FIRFirestoreErrorDomain = @"FIRFirestoreErrorDomain";
  48. #pragma mark - FIRFirestore
  49. @interface FIRFirestore ()
  50. @property(nonatomic, strong, readonly) FSTUserDataConverter *dataConverter;
  51. @end
  52. @implementation FIRFirestore {
  53. DelayedConstructor<Firestore> _firestore;
  54. }
  55. + (NSMutableDictionary<NSString *, FIRFirestore *> *)instances {
  56. static dispatch_once_t token = 0;
  57. static NSMutableDictionary<NSString *, FIRFirestore *> *instances;
  58. dispatch_once(&token, ^{
  59. instances = [NSMutableDictionary dictionary];
  60. });
  61. return instances;
  62. }
  63. + (void)initialize {
  64. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  65. [center addObserverForName:kFIRAppDeleteNotification
  66. object:nil
  67. queue:nil
  68. usingBlock:^(NSNotification *_Nonnull note) {
  69. NSString *appName = note.userInfo[kFIRAppNameKey];
  70. if (appName == nil) return;
  71. NSMutableDictionary *instances = [self instances];
  72. @synchronized(instances) {
  73. // Since the key for instances isn't just the app name, iterate over all the
  74. // keys to get the one(s) we have to delete. There could be multiple in case
  75. // the user calls firestoreForApp:database:.
  76. NSMutableArray *keysToDelete = [[NSMutableArray alloc] init];
  77. NSString *keyPrefix = [NSString stringWithFormat:@"%@|", appName];
  78. for (NSString *key in instances.allKeys) {
  79. if ([key hasPrefix:keyPrefix]) {
  80. [keysToDelete addObject:key];
  81. }
  82. }
  83. // Loop through the keys found and delete them from the stored instances.
  84. for (NSString *key in keysToDelete) {
  85. [instances removeObjectForKey:key];
  86. }
  87. }
  88. }];
  89. }
  90. + (instancetype)firestore {
  91. FIRApp *app = [FIRApp defaultApp];
  92. if (!app) {
  93. FSTThrowInvalidUsage(@"FIRAppNotConfiguredException",
  94. @"Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  95. @"before using Firestore");
  96. }
  97. return [self firestoreForApp:app database:util::WrapNSString(DatabaseId::kDefault)];
  98. }
  99. + (instancetype)firestoreForApp:(FIRApp *)app {
  100. return [self firestoreForApp:app database:util::WrapNSString(DatabaseId::kDefault)];
  101. }
  102. // TODO(b/62410906): make this public
  103. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  104. if (!app) {
  105. FSTThrowInvalidArgument(@"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd "
  106. "like to use the default FirebaseApp instance.");
  107. }
  108. if (!database) {
  109. FSTThrowInvalidArgument(@"database identifier may not be nil. Use '%s' if you want the default "
  110. "database",
  111. DatabaseId::kDefault);
  112. }
  113. id<FSTFirestoreMultiDBProvider> provider =
  114. FIR_COMPONENT(FSTFirestoreMultiDBProvider, app.container);
  115. return [provider firestoreForDatabase:database];
  116. }
  117. - (instancetype)initWithProjectID:(std::string)projectID
  118. database:(std::string)database
  119. persistenceKey:(std::string)persistenceKey
  120. credentialsProvider:(std::unique_ptr<CredentialsProvider>)credentialsProvider
  121. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue
  122. firebaseApp:(FIRApp *)app {
  123. if (self = [super init]) {
  124. _firestore.Init(std::move(projectID), std::move(database), std::move(persistenceKey),
  125. std::move(credentialsProvider), std::move(workerQueue), (__bridge void *)self);
  126. _app = app;
  127. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  128. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  129. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  130. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  131. databaseID:documentReference.firestore.databaseID];
  132. } else {
  133. return input;
  134. }
  135. };
  136. _dataConverter = [[FSTUserDataConverter alloc] initWithDatabaseID:&_firestore->database_id()
  137. preConverter:block];
  138. }
  139. return self;
  140. }
  141. - (FIRFirestoreSettings *)settings {
  142. return _firestore->settings();
  143. }
  144. - (void)setSettings:(FIRFirestoreSettings *)settings {
  145. _firestore->set_settings(settings);
  146. }
  147. /**
  148. * Ensures that the FirestoreClient is configured and returns it.
  149. */
  150. - (FSTFirestoreClient *)client {
  151. return _firestore->client();
  152. }
  153. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  154. if (!collectionPath) {
  155. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  156. }
  157. if ([collectionPath containsString:@"//"]) {
  158. FSTThrowInvalidArgument(@"Invalid path (%@). Paths must not contain // in them.",
  159. collectionPath);
  160. }
  161. return _firestore->GetCollection(util::MakeString(collectionPath));
  162. }
  163. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  164. if (!documentPath) {
  165. FSTThrowInvalidArgument(@"Document path cannot be nil.");
  166. }
  167. if ([documentPath containsString:@"//"]) {
  168. FSTThrowInvalidArgument(@"Invalid path (%@). Paths must not contain // in them.", documentPath);
  169. }
  170. DocumentReference documentReference = _firestore->GetDocument(util::MakeString(documentPath));
  171. return [[FIRDocumentReference alloc] initWithReference:std::move(documentReference)];
  172. }
  173. - (FIRWriteBatch *)batch {
  174. return _firestore->GetBatch();
  175. }
  176. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  177. dispatchQueue:(dispatch_queue_t)queue
  178. completion:
  179. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  180. // We wrap the function they provide in order to use internal implementation classes for
  181. // transaction, and to run the user callback block on the proper queue.
  182. if (!updateBlock) {
  183. FSTThrowInvalidArgument(@"Transaction block cannot be nil.");
  184. } else if (!completion) {
  185. FSTThrowInvalidArgument(@"Transaction completion block cannot be nil.");
  186. }
  187. _firestore->RunTransaction(updateBlock, queue, completion);
  188. }
  189. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  190. completion:
  191. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  192. static dispatch_queue_t transactionDispatchQueue;
  193. static dispatch_once_t onceToken;
  194. dispatch_once(&onceToken, ^{
  195. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  196. DISPATCH_QUEUE_CONCURRENT);
  197. });
  198. [self runTransactionWithBlock:updateBlock
  199. dispatchQueue:transactionDispatchQueue
  200. completion:completion];
  201. }
  202. + (void)enableLogging:(BOOL)logging {
  203. FIRSetLoggerLevel(logging ? FIRLoggerLevelDebug : FIRLoggerLevelNotice);
  204. }
  205. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  206. _firestore->EnableNetwork(completion);
  207. }
  208. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  209. _firestore->DisableNetwork(completion);
  210. }
  211. @end
  212. @implementation FIRFirestore (Internal)
  213. - (Firestore *)wrapped {
  214. return _firestore.get();
  215. }
  216. - (AsyncQueue *)workerQueue {
  217. return _firestore->worker_queue();
  218. }
  219. - (const DatabaseId *)databaseID {
  220. return &_firestore->database_id();
  221. }
  222. + (BOOL)isLoggingEnabled {
  223. return FIRIsLoggableLevel(FIRLoggerLevelDebug, NO);
  224. }
  225. + (FIRFirestore *)recoverFromFirestore:(Firestore *)firestore {
  226. return (__bridge FIRFirestore *)firestore->extension();
  227. }
  228. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID {
  229. if (!collectionID) {
  230. FSTThrowInvalidArgument(@"Collection ID cannot be nil.");
  231. }
  232. if ([collectionID containsString:@"/"]) {
  233. FSTThrowInvalidArgument(
  234. @"Invalid collection ID (%@). Collection IDs must not contain / in them.", collectionID);
  235. }
  236. return _firestore->GetCollectionGroup(collectionID);
  237. }
  238. - (void)shutdownWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  239. _firestore->Shutdown(completion);
  240. }
  241. @end
  242. NS_ASSUME_NONNULL_END