FIRStorageDownloadTask.m 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 "FIRStorageDownloadTask.h"
  15. #import "FIRStorageConstants_Private.h"
  16. #import "FIRStorageDownloadTask_Private.h"
  17. #import "FIRStorageObservableTask_Private.h"
  18. #import "FIRStorageTask_Private.h"
  19. @implementation FIRStorageDownloadTask
  20. @synthesize progress = _progress;
  21. @synthesize fetcher = _fetcher;
  22. - (instancetype)initWithReference:(FIRStorageReference *)reference
  23. fetcherService:(GTMSessionFetcherService *)service
  24. file:(nullable NSURL *)fileURL {
  25. self = [super initWithReference:reference fetcherService:service];
  26. if (self) {
  27. _fileURL = [fileURL copy];
  28. _progress = [NSProgress progressWithTotalUnitCount:0];
  29. }
  30. return self;
  31. }
  32. - (void)enqueue {
  33. [self enqueueWithData:nil];
  34. }
  35. - (void)enqueueWithData:(nullable NSData *)resumeData {
  36. NSAssert([NSThread isMainThread], @"Download attempting to execute on non main queue! Please "
  37. @"only execute this method on the main queue.");
  38. self.state = FIRStorageTaskStateQueueing;
  39. NSMutableURLRequest *request = [self.baseRequest mutableCopy];
  40. request.HTTPMethod = @"GET";
  41. request.timeoutInterval = self.reference.storage.maxDownloadRetryTime;
  42. NSURLComponents *components =
  43. [NSURLComponents componentsWithURL:request.URL resolvingAgainstBaseURL:NO];
  44. [components setQuery:@"alt=media"];
  45. request.URL = components.URL;
  46. GTMSessionFetcher *fetcher;
  47. if (resumeData) {
  48. fetcher = [GTMSessionFetcher fetcherWithDownloadResumeData:resumeData];
  49. fetcher.comment = @"Resuming DownloadTask";
  50. } else {
  51. fetcher = [self.fetcherService fetcherWithRequest:request];
  52. fetcher.comment = @"Starting DownloadTask";
  53. }
  54. [fetcher setResumeDataBlock:^(NSData *data) {
  55. if (data) {
  56. _downloadData = data;
  57. }
  58. }];
  59. fetcher.maxRetryInterval = self.reference.storage.maxDownloadRetryTime;
  60. if (_fileURL) {
  61. // Handle file downloads
  62. [fetcher setDestinationFileURL:_fileURL];
  63. [fetcher setDownloadProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten,
  64. int64_t totalBytesExpectedToWrite) {
  65. self.state = FIRStorageTaskStateProgress;
  66. self.progress.completedUnitCount = totalBytesWritten;
  67. self.progress.totalUnitCount = totalBytesExpectedToWrite;
  68. FIRStorageTaskSnapshot *snapshot = self.snapshot;
  69. [self fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:snapshot];
  70. self.state = FIRStorageTaskStateRunning;
  71. }];
  72. } else {
  73. // Handle data downloads
  74. [fetcher setReceivedProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten) {
  75. self.state = FIRStorageTaskStateProgress;
  76. self.progress.completedUnitCount = totalBytesWritten;
  77. int64_t totalLength = [[self.fetcher response] expectedContentLength];
  78. self.progress.totalUnitCount = totalLength;
  79. FIRStorageTaskSnapshot *snapshot = self.snapshot;
  80. [self fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:snapshot];
  81. self.state = FIRStorageTaskStateRunning;
  82. }];
  83. }
  84. _fetcher = fetcher;
  85. self.state = FIRStorageTaskStateRunning;
  86. [self.fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  87. // Fire last progress updates
  88. [self fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:self.snapshot];
  89. // Handle potential issues with download
  90. if (error) {
  91. self.state = FIRStorageTaskStateFailed;
  92. self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference];
  93. [self fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:self.snapshot];
  94. [self removeAllObservers];
  95. return;
  96. }
  97. // Download completed successfully, fire completion callbacks
  98. self.state = FIRStorageTaskStateSuccess;
  99. if (data) {
  100. _downloadData = data;
  101. }
  102. [self fireHandlersForStatus:FIRStorageTaskStatusSuccess snapshot:self.snapshot];
  103. [self removeAllObservers];
  104. }];
  105. }
  106. #pragma mark - Download Management
  107. - (void)cancel {
  108. NSError *error = [FIRStorageErrors errorWithCode:FIRStorageErrorCodeCancelled];
  109. [self cancelWithError:error];
  110. }
  111. - (void)cancelWithError:(NSError *)error {
  112. NSAssert([NSThread isMainThread], @"Cancel attempting to execute on non main queue! Please only "
  113. @"execute this method on the main queue.");
  114. self.state = FIRStorageTaskStateCancelled;
  115. [self.fetcher stopFetching];
  116. self.error = error;
  117. [self fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:self.snapshot];
  118. }
  119. - (void)pause {
  120. NSAssert([NSThread isMainThread], @"Pause attempting to execute on non main queue! Please only "
  121. @"execute this method on the main queue.");
  122. self.state = FIRStorageTaskStatePausing;
  123. [self.fetcher stopFetching];
  124. // Give the resume callback a chance to run (if scheduled)
  125. [self.fetcher waitForCompletionWithTimeout:0.001];
  126. self.state = FIRStorageTaskStatePaused;
  127. FIRStorageTaskSnapshot *snapshot = self.snapshot;
  128. [self fireHandlersForStatus:FIRStorageTaskStatusPause snapshot:snapshot];
  129. }
  130. - (void)resume {
  131. NSAssert([NSThread isMainThread], @"Resume attempting to execute on non main queue! Please only "
  132. @"execute this method on the main queue.");
  133. self.state = FIRStorageTaskStateResuming;
  134. FIRStorageTaskSnapshot *snapshot = self.snapshot;
  135. [self fireHandlersForStatus:FIRStorageTaskStatusResume snapshot:snapshot];
  136. self.state = FIRStorageTaskStateRunning;
  137. [self enqueueWithData:_downloadData];
  138. }
  139. @end