FIRStorage.m 12 KB

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