FIRStorage.m 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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/FIRStorage.h"
  15. #import "FirebaseStorage/Sources/Public/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 "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  24. #import "Interop/Auth/Public/FIRAuthInterop.h"
  25. #if SWIFT_PACKAGE
  26. @import GTMSessionFetcherCore;
  27. #else
  28. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  29. #import <GTMSessionFetcher/GTMSessionFetcherLogging.h>
  30. #endif
  31. static NSMutableDictionary<
  32. NSString * /* app name */,
  33. NSMutableDictionary<NSString * /* bucket */, GTMSessionFetcherService *> *> *_fetcherServiceMap;
  34. static GTMSessionFetcherRetryBlock _retryWhenOffline;
  35. @interface FIRStorage () {
  36. /// Stored Auth reference, if it exists. This needs to be stored for `copyWithZone:`.
  37. id<FIRAuthInterop> _Nullable _auth;
  38. }
  39. @end
  40. @implementation FIRStorage
  41. + (void)initialize {
  42. static dispatch_once_t onceToken;
  43. dispatch_once(&onceToken, ^{
  44. _retryWhenOffline = ^(BOOL suggestedWillRetry, NSError *GTM_NULLABLE_TYPE error,
  45. GTMSessionFetcherRetryResponse response) {
  46. bool shouldRetry = suggestedWillRetry;
  47. // GTMSessionFetcher does not consider being offline a retryable error, but we do, so we
  48. // special-case it here.
  49. if (!shouldRetry && error) {
  50. shouldRetry = error.code == NSURLErrorNotConnectedToInternet;
  51. }
  52. response(shouldRetry);
  53. };
  54. _fetcherServiceMap = [[NSMutableDictionary alloc] init];
  55. });
  56. }
  57. + (GTMSessionFetcherService *)fetcherServiceForApp:(FIRApp *)app
  58. bucket:(NSString *)bucket
  59. auth:(nullable id<FIRAuthInterop>)auth {
  60. @synchronized(_fetcherServiceMap) {
  61. NSMutableDictionary *bucketMap = _fetcherServiceMap[app.name];
  62. if (!bucketMap) {
  63. bucketMap = [[NSMutableDictionary alloc] init];
  64. _fetcherServiceMap[app.name] = bucketMap;
  65. }
  66. GTMSessionFetcherService *fetcherService = bucketMap[bucket];
  67. if (!fetcherService) {
  68. fetcherService = [[GTMSessionFetcherService alloc] init];
  69. [fetcherService setRetryEnabled:YES];
  70. [fetcherService setRetryBlock:_retryWhenOffline];
  71. FIRStorageTokenAuthorizer *authorizer =
  72. [[FIRStorageTokenAuthorizer alloc] initWithGoogleAppID:app.options.googleAppID
  73. fetcherService:fetcherService
  74. authProvider:auth];
  75. [fetcherService setAuthorizer:authorizer];
  76. bucketMap[bucket] = fetcherService;
  77. }
  78. return fetcherService;
  79. }
  80. }
  81. + (void)setGTMSessionFetcherLoggingEnabled:(BOOL)isLoggingEnabled {
  82. [GTMSessionFetcher setLoggingEnabled:isLoggingEnabled];
  83. }
  84. + (instancetype)storage {
  85. return [self storageForApp:[FIRApp defaultApp]];
  86. }
  87. + (instancetype)storageForApp:(FIRApp *)app {
  88. if (app.options.storageBucket) {
  89. NSString *url = [app.options.storageBucket isEqualToString:@""]
  90. ? @""
  91. : [@"gs://" stringByAppendingString:app.options.storageBucket];
  92. return [self storageForApp:app URL:url];
  93. } else {
  94. NSString *const kAppNotConfiguredMessage =
  95. @"No default Storage bucket found. Did you configure Firebase Storage properly?";
  96. [NSException raise:NSInvalidArgumentException format:kAppNotConfiguredMessage];
  97. return nil;
  98. }
  99. }
  100. + (instancetype)storageWithURL:(NSString *)url {
  101. return [self storageForApp:[FIRApp defaultApp] URL:url];
  102. }
  103. + (instancetype)storageForApp:(FIRApp *)app URL:(NSString *)url {
  104. NSString *bucket;
  105. if ([url isEqualToString:@""]) {
  106. bucket = @"";
  107. } else {
  108. FIRStoragePath *path;
  109. @try {
  110. path = [FIRStoragePath pathFromGSURI:url];
  111. } @catch (NSException *e) {
  112. [NSException raise:NSInternalInconsistencyException
  113. format:@"URI must be in the form of gs://<bucket>/"];
  114. }
  115. if (path.object != nil && ![path.object isEqualToString:@""]) {
  116. [NSException raise:NSInternalInconsistencyException
  117. format:@"Storage bucket cannot be initialized with a path"];
  118. }
  119. bucket = path.bucket;
  120. }
  121. // Retrieve the instance provider from the app's container to inject dependencies as needed.
  122. id<FIRStorageMultiBucketProvider> provider =
  123. FIR_COMPONENT(FIRStorageMultiBucketProvider, app.container);
  124. return [provider storageForBucket:bucket];
  125. }
  126. - (instancetype)initWithApp:(FIRApp *)app
  127. bucket:(NSString *)bucket
  128. auth:(nullable id<FIRAuthInterop>)auth {
  129. self = [super init];
  130. if (self) {
  131. _app = app;
  132. _auth = auth;
  133. _storageBucket = bucket;
  134. _dispatchQueue = dispatch_queue_create("com.google.firebase.storage", DISPATCH_QUEUE_SERIAL);
  135. _fetcherServiceForApp = [FIRStorage fetcherServiceForApp:_app bucket:bucket auth:auth];
  136. _maxDownloadRetryTime = 600.0;
  137. _maxOperationRetryTime = 120.0;
  138. _maxUploadRetryTime = 600.0;
  139. }
  140. return self;
  141. }
  142. - (instancetype)init {
  143. NSAssert(false, @"Storage cannot be directly instantiated, use "
  144. "Storage.storage() or Storage.storage(app:) instead");
  145. return nil;
  146. }
  147. #pragma mark - NSObject overrides
  148. - (instancetype)copyWithZone:(NSZone *)zone {
  149. FIRStorage *storage = [[[self class] allocWithZone:zone] initWithApp:_app
  150. bucket:_storageBucket
  151. auth:_auth];
  152. storage.callbackQueue = self.callbackQueue;
  153. return storage;
  154. }
  155. // Two FIRStorage objects are equal if they use the same app
  156. - (BOOL)isEqual:(id)object {
  157. if (self == object) {
  158. return YES;
  159. }
  160. if (![object isKindOfClass:[FIRStorage class]]) {
  161. return NO;
  162. }
  163. BOOL isEqualObject = [self isEqualToFIRStorage:(FIRStorage *)object];
  164. return isEqualObject;
  165. }
  166. - (BOOL)isEqualToFIRStorage:(FIRStorage *)storage {
  167. BOOL isEqual =
  168. [_app isEqual:storage.app] && [_storageBucket isEqualToString:storage.storageBucket];
  169. return isEqual;
  170. }
  171. - (NSUInteger)hash {
  172. NSUInteger hash = [_app hash] ^ [self.callbackQueue hash];
  173. return hash;
  174. }
  175. - (NSString *)description {
  176. return [NSString stringWithFormat:@"%@ %p: %@", [self class], self, _app];
  177. }
  178. #pragma mark - Public methods
  179. - (FIRStorageReference *)reference {
  180. FIRStoragePath *path = [[FIRStoragePath alloc] initWithBucket:_storageBucket object:nil];
  181. return [[FIRStorageReference alloc] initWithStorage:self path:path];
  182. }
  183. - (FIRStorageReference *)referenceForURL:(NSString *)string {
  184. FIRStoragePath *path = [FIRStoragePath pathFromString:string];
  185. // If no default bucket exists (empty string), accept anything.
  186. if ([_storageBucket isEqual:@""]) {
  187. FIRStorageReference *reference = [[FIRStorageReference alloc] initWithStorage:self path:path];
  188. return reference;
  189. }
  190. // If there exists a default bucket, throw if provided a different bucket.
  191. if (![path.bucket isEqual:_storageBucket]) {
  192. NSString *const kInvalidBucketFormat =
  193. @"Provided bucket: %@ does not match the Storage bucket of the current instance: %@";
  194. [NSException raise:NSInvalidArgumentException
  195. format:kInvalidBucketFormat, path.bucket, _storageBucket];
  196. }
  197. FIRStorageReference *reference = [[FIRStorageReference alloc] initWithStorage:self path:path];
  198. return reference;
  199. }
  200. - (FIRStorageReference *)referenceWithPath:(NSString *)string {
  201. FIRStorageReference *reference = [[self reference] child:string];
  202. return reference;
  203. }
  204. - (dispatch_queue_t)callbackQueue {
  205. return _fetcherServiceForApp.callbackQueue;
  206. }
  207. - (void)setCallbackQueue:(dispatch_queue_t)callbackQueue {
  208. _fetcherServiceForApp.callbackQueue = callbackQueue;
  209. }
  210. #pragma mark - Background tasks
  211. + (void)enableBackgroundTasks:(BOOL)isEnabled {
  212. [NSException raise:NSGenericException format:@"enableBackgroundTasks not implemented"];
  213. }
  214. - (NSArray<FIRStorageUploadTask *> *)uploadTasks {
  215. [NSException raise:NSGenericException format:@"getUploadTasks not implemented"];
  216. return nil;
  217. }
  218. - (NSArray<FIRStorageDownloadTask *> *)downloadTasks {
  219. [NSException raise:NSGenericException format:@"getDownloadTasks not implemented"];
  220. return nil;
  221. }
  222. @end