FIRStorage.m 8.8 KB

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