FIRStorage.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 "FirebaseStorage/Sources/Public/FirebaseStorage/FIRStorage.h"
  15. #import "FirebaseStorage/Sources/Public/FirebaseStorage/FIRStorageReference.h"
  16. #import "FirebaseStorage/Sources/FIRStorageComponent.h"
  17. #import "FirebaseStorage/Sources/FIRStorageConstants_Private.h"
  18. #import "FirebaseStorage/Sources/FIRStoragePath.h"
  19. #import "FirebaseStorage/Sources/FIRStorageReference_Private.h"
  20. #import "FirebaseStorage/Sources/FIRStorageTokenAuthorizer.h"
  21. #import "FirebaseStorage/Sources/FIRStorageUtils.h"
  22. #import "FirebaseStorage/Sources/FIRStorage_Private.h"
  23. #import "FirebaseAppCheck/Sources/Interop/FIRAppCheckInterop.h"
  24. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  25. #import "Interop/Auth/Public/FIRAuthInterop.h"
  26. #if SWIFT_PACKAGE
  27. @import GTMSessionFetcherCore;
  28. #else
  29. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  30. #import <GTMSessionFetcher/GTMSessionFetcherLogging.h>
  31. #endif
  32. static NSMutableDictionary<
  33. NSString * /* app name */,
  34. NSMutableDictionary<NSString * /* bucket */, GTMSessionFetcherService *> *> *_fetcherServiceMap;
  35. static GTMSessionFetcherRetryBlock _retryWhenOffline;
  36. @interface FIRStorage () {
  37. /// Stored Auth reference, if it exists. This needs to be stored for `copyWithZone:`.
  38. id<FIRAuthInterop> _Nullable _auth;
  39. id<FIRAppCheckInterop> _Nullable _appCheck;
  40. NSTimeInterval _maxUploadRetryTime;
  41. NSTimeInterval _maxDownloadRetryTime;
  42. NSTimeInterval _maxOperationRetryTime;
  43. }
  44. @end
  45. @implementation FIRStorage
  46. + (void)initialize {
  47. static dispatch_once_t onceToken;
  48. dispatch_once(&onceToken, ^{
  49. _retryWhenOffline = ^(BOOL suggestedWillRetry, NSError *GTM_NULLABLE_TYPE error,
  50. GTMSessionFetcherRetryResponse response) {
  51. bool shouldRetry = suggestedWillRetry;
  52. // GTMSessionFetcher does not consider being offline a retryable error, but we do, so we
  53. // special-case it here.
  54. if (!shouldRetry && error) {
  55. shouldRetry = error.code == NSURLErrorNotConnectedToInternet;
  56. }
  57. response(shouldRetry);
  58. };
  59. _fetcherServiceMap = [[NSMutableDictionary alloc] init];
  60. });
  61. }
  62. + (GTMSessionFetcherService *)fetcherServiceForApp:(FIRApp *)app
  63. bucket:(NSString *)bucket
  64. auth:(nullable id<FIRAuthInterop>)auth
  65. appCheck:(nullable id<FIRAppCheckInterop>)appCheck {
  66. @synchronized(_fetcherServiceMap) {
  67. NSMutableDictionary *bucketMap = _fetcherServiceMap[app.name];
  68. if (!bucketMap) {
  69. bucketMap = [[NSMutableDictionary alloc] init];
  70. _fetcherServiceMap[app.name] = bucketMap;
  71. }
  72. GTMSessionFetcherService *fetcherService = bucketMap[bucket];
  73. if (!fetcherService) {
  74. fetcherService = [[GTMSessionFetcherService alloc] init];
  75. [fetcherService setRetryEnabled:YES];
  76. [fetcherService setRetryBlock:_retryWhenOffline];
  77. [fetcherService setAllowLocalhostRequest:YES];
  78. FIRStorageTokenAuthorizer *authorizer =
  79. [[FIRStorageTokenAuthorizer alloc] initWithGoogleAppID:app.options.googleAppID
  80. fetcherService:fetcherService
  81. authProvider:auth
  82. appCheck:appCheck];
  83. [fetcherService setAuthorizer:authorizer];
  84. bucketMap[bucket] = fetcherService;
  85. }
  86. return fetcherService;
  87. }
  88. }
  89. + (void)setGTMSessionFetcherLoggingEnabled:(BOOL)isLoggingEnabled {
  90. [GTMSessionFetcher setLoggingEnabled:isLoggingEnabled];
  91. }
  92. + (instancetype)storage {
  93. return [self storageForApp:[FIRApp defaultApp]];
  94. }
  95. + (instancetype)storageForApp:(FIRApp *)app {
  96. if (app.options.storageBucket) {
  97. NSString *url = [app.options.storageBucket isEqualToString:@""]
  98. ? @""
  99. : [@"gs://" stringByAppendingString:app.options.storageBucket];
  100. return [self storageForApp:app URL:url];
  101. } else {
  102. NSString *const kAppNotConfiguredMessage =
  103. @"No default Storage bucket found. Did you configure Firebase Storage properly?";
  104. [NSException raise:NSInvalidArgumentException format:kAppNotConfiguredMessage];
  105. return nil;
  106. }
  107. }
  108. + (instancetype)storageWithURL:(NSString *)url {
  109. return [self storageForApp:[FIRApp defaultApp] URL:url];
  110. }
  111. + (instancetype)storageForApp:(FIRApp *)app URL:(NSString *)url {
  112. NSString *bucket;
  113. if ([url isEqualToString:@""]) {
  114. bucket = @"";
  115. } else {
  116. FIRStoragePath *path;
  117. @try {
  118. path = [FIRStoragePath pathFromGSURI:url];
  119. } @catch (NSException *e) {
  120. [NSException raise:NSInternalInconsistencyException
  121. format:@"URI must be in the form of gs://<bucket>/"];
  122. }
  123. if (path.object != nil && ![path.object isEqualToString:@""]) {
  124. [NSException raise:NSInternalInconsistencyException
  125. format:@"Storage bucket cannot be initialized with a path"];
  126. }
  127. bucket = path.bucket;
  128. }
  129. // Retrieve the instance provider from the app's container to inject dependencies as needed.
  130. id<FIRStorageMultiBucketProvider> provider =
  131. FIR_COMPONENT(FIRStorageMultiBucketProvider, app.container);
  132. return [provider storageForBucket:bucket];
  133. }
  134. - (instancetype)initWithApp:(FIRApp *)app
  135. bucket:(NSString *)bucket
  136. auth:(nullable id<FIRAuthInterop>)auth
  137. appCheck:(nullable id<FIRAppCheckInterop>)appCheck {
  138. self = [super init];
  139. if (self) {
  140. _app = app;
  141. _auth = auth;
  142. _appCheck = appCheck;
  143. _storageBucket = bucket;
  144. _host = kFIRStorageHost;
  145. _scheme = kFIRStorageScheme;
  146. _port = @(kFIRStoragePort);
  147. _fetcherServiceForApp = nil; // Configured in `ensureConfigured()`
  148. _dispatchQueue = dispatch_queue_create("com.google.firebase.storage", DISPATCH_QUEUE_SERIAL);
  149. _maxDownloadRetryTime = 600.0;
  150. _maxDownloadRetryInterval =
  151. [FIRStorageUtils computeRetryIntervalFromRetryTime:_maxDownloadRetryTime];
  152. _maxOperationRetryTime = 120.0;
  153. _maxOperationRetryInterval =
  154. [FIRStorageUtils computeRetryIntervalFromRetryTime:_maxOperationRetryTime];
  155. _maxUploadRetryTime = 600.0;
  156. _maxUploadRetryInterval =
  157. [FIRStorageUtils computeRetryIntervalFromRetryTime:_maxUploadRetryTime];
  158. }
  159. return self;
  160. }
  161. - (instancetype)init {
  162. NSAssert(false, @"Storage cannot be directly instantiated, use "
  163. "Storage.storage() or Storage.storage(app:) instead");
  164. return nil;
  165. }
  166. #pragma mark - NSObject overrides
  167. - (instancetype)copyWithZone:(NSZone *)zone {
  168. FIRStorage *storage = [[[self class] allocWithZone:zone] initWithApp:_app
  169. bucket:_storageBucket
  170. auth:_auth
  171. appCheck:_appCheck];
  172. storage.callbackQueue = self.callbackQueue;
  173. return storage;
  174. }
  175. // Two FIRStorage objects are equal if they use the same app
  176. - (BOOL)isEqual:(id)object {
  177. if (self == object) {
  178. return YES;
  179. }
  180. if (![object isKindOfClass:[FIRStorage class]]) {
  181. return NO;
  182. }
  183. BOOL isEqualObject = [self isEqualToFIRStorage:(FIRStorage *)object];
  184. return isEqualObject;
  185. }
  186. - (BOOL)isEqualToFIRStorage:(FIRStorage *)storage {
  187. BOOL isEqual =
  188. [_app isEqual:storage.app] && [_storageBucket isEqualToString:storage.storageBucket];
  189. return isEqual;
  190. }
  191. - (NSUInteger)hash {
  192. NSUInteger hash = [_app hash] ^ [self.callbackQueue hash];
  193. return hash;
  194. }
  195. - (NSString *)description {
  196. return [NSString stringWithFormat:@"%@ %p: %@", [self class], self, _app];
  197. }
  198. #pragma mark - Retry time intervals
  199. - (void)setMaxUploadRetryTime:(NSTimeInterval)maxUploadRetryTime {
  200. @synchronized(self) {
  201. _maxUploadRetryTime = maxUploadRetryTime;
  202. _maxUploadRetryInterval =
  203. [FIRStorageUtils computeRetryIntervalFromRetryTime:maxUploadRetryTime];
  204. }
  205. }
  206. - (NSTimeInterval)maxDownloadRetryTime {
  207. @synchronized(self) {
  208. return _maxDownloadRetryTime;
  209. }
  210. }
  211. - (void)setMaxDownloadRetryTime:(NSTimeInterval)maxDownloadRetryTime {
  212. @synchronized(self) {
  213. _maxDownloadRetryTime = maxDownloadRetryTime;
  214. _maxDownloadRetryInterval =
  215. [FIRStorageUtils computeRetryIntervalFromRetryTime:maxDownloadRetryTime];
  216. }
  217. }
  218. - (NSTimeInterval)maxUploadRetryTime {
  219. @synchronized(self) {
  220. return _maxUploadRetryTime;
  221. }
  222. }
  223. - (void)setMaxOperationRetryTime:(NSTimeInterval)maxOperationRetryTime {
  224. @synchronized(self) {
  225. _maxOperationRetryTime = maxOperationRetryTime;
  226. _maxOperationRetryInterval =
  227. [FIRStorageUtils computeRetryIntervalFromRetryTime:maxOperationRetryTime];
  228. }
  229. }
  230. - (NSTimeInterval)maxOperationRetryTime {
  231. @synchronized(self) {
  232. return _maxOperationRetryTime;
  233. }
  234. }
  235. #pragma mark - Public methods
  236. - (FIRStorageReference *)reference {
  237. [self ensureConfigured];
  238. FIRStoragePath *path = [[FIRStoragePath alloc] initWithBucket:_storageBucket object:nil];
  239. return [[FIRStorageReference alloc] initWithStorage:self path:path];
  240. }
  241. - (FIRStorageReference *)referenceForURL:(NSString *)string {
  242. [self ensureConfigured];
  243. FIRStoragePath *path = [FIRStoragePath pathFromString:string];
  244. // If no default bucket exists (empty string), accept anything.
  245. if ([_storageBucket isEqual:@""]) {
  246. FIRStorageReference *reference = [[FIRStorageReference alloc] initWithStorage:self path:path];
  247. return reference;
  248. }
  249. // If there exists a default bucket, throw if provided a different bucket.
  250. if (![path.bucket isEqual:_storageBucket]) {
  251. NSString *const kInvalidBucketFormat =
  252. @"Provided bucket: %@ does not match the Storage bucket of the current instance: %@";
  253. [NSException raise:NSInvalidArgumentException
  254. format:kInvalidBucketFormat, path.bucket, _storageBucket];
  255. }
  256. FIRStorageReference *reference = [[FIRStorageReference alloc] initWithStorage:self path:path];
  257. return reference;
  258. }
  259. - (FIRStorageReference *)referenceWithPath:(NSString *)string {
  260. FIRStorageReference *reference = [[self reference] child:string];
  261. return reference;
  262. }
  263. - (dispatch_queue_t)callbackQueue {
  264. [self ensureConfigured];
  265. return _fetcherServiceForApp.callbackQueue;
  266. }
  267. - (void)setCallbackQueue:(dispatch_queue_t)callbackQueue {
  268. [self ensureConfigured];
  269. _fetcherServiceForApp.callbackQueue = callbackQueue;
  270. }
  271. - (void)useEmulatorWithHost:(NSString *)host port:(NSInteger)port {
  272. if (host.length == 0) {
  273. [NSException raise:NSInvalidArgumentException format:@"Cannot connect to nil or empty host."];
  274. }
  275. if (port < 0) {
  276. [NSException raise:NSInvalidArgumentException
  277. format:@"Port must be greater than or equal to zero."];
  278. }
  279. if (_fetcherServiceForApp != nil) {
  280. [NSException raise:NSInternalInconsistencyException
  281. format:@"Cannot connect to emulator after Storage SDK initialization. "
  282. @"Call useEmulator(host:port:) before creating a Storage "
  283. @"reference or trying to load data."];
  284. }
  285. _scheme = @"http";
  286. _host = host;
  287. _port = @(port);
  288. }
  289. #pragma mark - Background tasks
  290. + (void)enableBackgroundTasks:(BOOL)isEnabled {
  291. [NSException raise:NSGenericException format:@"enableBackgroundTasks not implemented"];
  292. }
  293. - (NSArray<FIRStorageUploadTask *> *)uploadTasks {
  294. [NSException raise:NSGenericException format:@"getUploadTasks not implemented"];
  295. return nil;
  296. }
  297. - (NSArray<FIRStorageDownloadTask *> *)downloadTasks {
  298. [NSException raise:NSGenericException format:@"getDownloadTasks not implemented"];
  299. return nil;
  300. }
  301. - (void)ensureConfigured {
  302. if (!_fetcherServiceForApp) {
  303. _fetcherServiceForApp = [FIRStorage fetcherServiceForApp:_app
  304. bucket:_storageBucket
  305. auth:_auth
  306. appCheck:_appCheck];
  307. }
  308. }
  309. @end