FIRStorageUploadTask.m 8.2 KB

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