FIRStorageUploadTask.m 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 "FIRStorageUploadTask.h"
  15. #import "FIRStorageConstants_Private.h"
  16. #import "FIRStorageMetadata_Private.h"
  17. #import "FIRStorageObservableTask_Private.h"
  18. #import "FIRStorageTask_Private.h"
  19. #import "FIRStorageUploadTask_Private.h"
  20. #import "GTMSessionUploadFetcher.h"
  21. @implementation FIRStorageUploadTask
  22. @synthesize progress = _progress;
  23. @synthesize fetcherCompletion = _fetcherCompletion;
  24. - (instancetype)initWithReference:(FIRStorageReference *)reference
  25. fetcherService:(GTMSessionFetcherService *)service
  26. data:(NSData *)uploadData
  27. metadata:(FIRStorageMetadata *)metadata {
  28. self = [super initWithReference:reference fetcherService:service];
  29. if (self) {
  30. _uploadMetadata = [metadata copy];
  31. _uploadData = [uploadData copy];
  32. _progress = [NSProgress progressWithTotalUnitCount:[_uploadData length]];
  33. if (!_uploadMetadata.contentType) {
  34. _uploadMetadata.contentType = @"application/octet-stream";
  35. }
  36. }
  37. return self;
  38. }
  39. - (instancetype)initWithReference:(FIRStorageReference *)reference
  40. fetcherService:(GTMSessionFetcherService *)service
  41. file:(NSURL *)fileURL
  42. metadata:(FIRStorageMetadata *)metadata {
  43. self = [super initWithReference:reference fetcherService:service];
  44. if (self) {
  45. _uploadMetadata = [metadata copy];
  46. _fileURL = [fileURL copy];
  47. _progress = [NSProgress progressWithTotalUnitCount:0];
  48. NSString *mimeType = [FIRStorageUtils MIMETypeForExtension:[_fileURL pathExtension]];
  49. if (!_uploadMetadata.contentType) {
  50. _uploadMetadata.contentType = mimeType ?: @"application/octet-stream";
  51. }
  52. }
  53. return self;
  54. }
  55. - (void) dealloc {
  56. [_uploadFetcher stopFetching];
  57. }
  58. - (void)enqueue {
  59. NSAssert([NSThread isMainThread], @"Upload attempting to execute on non main queue! Please only "
  60. @"execute this method on the main queue.");
  61. self.state = FIRStorageTaskStateQueueing;
  62. NSMutableURLRequest *request = [self.baseRequest mutableCopy];
  63. request.HTTPMethod = @"POST";
  64. request.timeoutInterval = self.reference.storage.maxUploadRetryTime;
  65. NSData *bodyData = [NSData frs_dataFromJSONDictionary:[_uploadMetadata dictionaryRepresentation]];
  66. request.HTTPBody = bodyData;
  67. [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  68. NSString *contentLengthString = [NSString stringWithFormat:@"%zu",
  69. (unsigned long)[bodyData length]];
  70. [request setValue:contentLengthString forHTTPHeaderField:@"Content-Length"];
  71. NSURLComponents *components =
  72. [NSURLComponents componentsWithURL:request.URL resolvingAgainstBaseURL:NO];
  73. if ([components.host isEqual:kGCSHost]) {
  74. [components setPercentEncodedPath:[@"/upload" stringByAppendingString:components.path]];
  75. }
  76. NSDictionary *queryParams = @{ @"uploadType" : @"resumable", @"name" : self.uploadMetadata.path };
  77. [components setPercentEncodedQuery:[FIRStorageUtils queryStringForDictionary:queryParams]];
  78. request.URL = components.URL;
  79. GTMSessionUploadFetcher *uploadFetcher =
  80. [GTMSessionUploadFetcher uploadFetcherWithRequest:request
  81. uploadMIMEType:_uploadMetadata.contentType
  82. chunkSize:kGTMSessionUploadFetcherStandardChunkSize
  83. fetcherService:self.fetcherService];
  84. if (_uploadData) {
  85. [uploadFetcher setUploadData:_uploadData];
  86. uploadFetcher.comment = @"Data UploadTask";
  87. } else if (_fileURL) {
  88. [uploadFetcher setUploadFileURL:_fileURL];
  89. uploadFetcher.comment = @"File UploadTask";
  90. }
  91. uploadFetcher.maxRetryInterval = self.reference.storage.maxUploadRetryTime;
  92. __weak FIRStorageUploadTask* weakSelf = self;
  93. [uploadFetcher setSendProgressBlock:^(int64_t bytesSent, int64_t totalBytesSent,
  94. int64_t totalBytesExpectedToSend) {
  95. weakSelf.state = FIRStorageTaskStateProgress;
  96. weakSelf.progress.completedUnitCount = totalBytesSent;
  97. weakSelf.progress.totalUnitCount = totalBytesExpectedToSend;
  98. weakSelf.metadata = _uploadMetadata;
  99. [weakSelf fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:weakSelf.snapshot];
  100. weakSelf.state = FIRStorageTaskStateRunning;
  101. }];
  102. _uploadFetcher = uploadFetcher;
  103. // Process fetches
  104. self.state = FIRStorageTaskStateRunning;
  105. #pragma clang diagnostic push
  106. #pragma clang diagnostic ignored "-Warc-retain-cycles"
  107. _fetcherCompletion = ^(NSData *_Nullable data,
  108. NSError *_Nullable error) {
  109. // Fire last progress updates
  110. [self fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:self.snapshot];
  111. // Handle potential issues with upload
  112. if (error) {
  113. self.state = FIRStorageTaskStateFailed;
  114. self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference];
  115. self.metadata = _uploadMetadata;
  116. [self fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:self.snapshot];
  117. [self removeAllObservers];
  118. _fetcherCompletion = nil;
  119. return;
  120. }
  121. // Upload completed successfully, fire completion callbacks
  122. self.state = FIRStorageTaskStateSuccess;
  123. NSDictionary *responseDictionary = [NSDictionary frs_dictionaryFromJSONData:data];
  124. if (responseDictionary) {
  125. FIRStorageMetadata *metadata =
  126. [[FIRStorageMetadata alloc] initWithDictionary:responseDictionary];
  127. [metadata setType:FIRStorageMetadataTypeFile];
  128. self.metadata = metadata;
  129. } else {
  130. NSString *returnedData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  131. NSString *invalidDataString =
  132. [NSString stringWithFormat:kFIRStorageInvalidDataFormat, returnedData];
  133. NSDictionary *dict;
  134. if (invalidDataString.length > 0) {
  135. dict = @{NSLocalizedFailureReasonErrorKey : invalidDataString};
  136. }
  137. self.error =
  138. [FIRStorageErrors errorWithCode:FIRStorageErrorCodeUnknown infoDictionary:dict];
  139. }
  140. [self fireHandlersForStatus:FIRStorageTaskStatusSuccess snapshot:self.snapshot];
  141. [self removeAllObservers];
  142. _fetcherCompletion = nil;
  143. };
  144. #pragma clang diagnostic pop
  145. [_uploadFetcher beginFetchWithCompletionHandler:^(NSData *_Nullable data,
  146. NSError *_Nullable error) {
  147. weakSelf.fetcherCompletion(data, error);
  148. }];
  149. }
  150. #pragma mark - Upload Management
  151. - (void)cancel {
  152. NSAssert([NSThread isMainThread], @"Cancel attempting to execute on non main queue! Please only "
  153. @"execute this method on the main queue.");
  154. self.state = FIRStorageTaskStateCancelled;
  155. [_uploadFetcher stopFetching];
  156. if (self.state != FIRStorageTaskStateSuccess) {
  157. self.metadata = _uploadMetadata;
  158. }
  159. self.error = [FIRStorageErrors errorWithCode:FIRStorageErrorCodeCancelled];
  160. [self fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:self.snapshot];
  161. }
  162. - (void)pause {
  163. NSAssert([NSThread isMainThread], @"Pause attempting to execute on non main queue! Please only "
  164. @"execute this method on the main queue.");
  165. self.state = FIRStorageTaskStatePaused;
  166. [_uploadFetcher pauseFetching];
  167. if (self.state != FIRStorageTaskStateSuccess) {
  168. self.metadata = _uploadMetadata;
  169. }
  170. [self fireHandlersForStatus:FIRStorageTaskStatusPause snapshot:self.snapshot];
  171. }
  172. - (void)resume {
  173. NSAssert([NSThread isMainThread], @"Resume attempting to execute on non main queue! Please only "
  174. @"execute this method on the main queue.");
  175. self.state = FIRStorageTaskStateResuming;
  176. [_uploadFetcher resumeFetching];
  177. if (self.state != FIRStorageTaskStateSuccess) {
  178. self.metadata = _uploadMetadata;
  179. }
  180. [self fireHandlersForStatus:FIRStorageTaskStatusResume snapshot:self.snapshot];
  181. self.state = FIRStorageTaskStateRunning;
  182. }
  183. @end