StorageDownloadTask.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // Copyright 2022 Google LLC
  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 Foundation
  15. #if COCOAPODS
  16. @preconcurrency import GTMSessionFetcher
  17. #else
  18. @preconcurrency import GTMSessionFetcherCore
  19. #endif
  20. /**
  21. * `StorageDownloadTask` implements resumable downloads from an object in Firebase Storage.
  22. *
  23. * Downloads can be returned on completion with a completion handler, and can be monitored
  24. * by attaching observers, or controlled by calling `pause()`, `resume()`,
  25. * or `cancel()`.
  26. *
  27. * Downloads can currently be returned as `Data` in memory, or as a `URL` to a file on disk.
  28. *
  29. * Downloads are performed on a background queue, and callbacks are raised on the developer
  30. * specified `callbackQueue` in Storage, or the main queue if left unspecified.
  31. */
  32. @objc(FIRStorageDownloadTask)
  33. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  34. open class StorageDownloadTask: StorageObservableTask, StorageTaskManagement,
  35. @unchecked Sendable /* TODO: sendable */ {
  36. /**
  37. * Prepares a task and begins execution.
  38. */
  39. @objc open func enqueue() {
  40. Task {
  41. await enqueueImplementation()
  42. }
  43. }
  44. /**
  45. * Pauses a task currently in progress. Calling this on a paused task has no effect.
  46. */
  47. @objc open func pause() {
  48. dispatchQueue.async { [weak self] in
  49. guard let self = self else { return }
  50. if self.state == .paused || self.state == .pausing {
  51. return
  52. }
  53. self.state = .pausing
  54. // Use the resume callback to confirm pause status since it always runs after the last
  55. // NSURLSession update.
  56. self.fetcher?.resumeDataBlock = { [weak self] (data: Data) in
  57. guard let self = self else { return }
  58. self.downloadData = data
  59. self.state = .paused
  60. self.fire(for: .pause, snapshot: self.snapshot)
  61. }
  62. self.fetcher?.stopFetching()
  63. }
  64. }
  65. /**
  66. * Cancels a task.
  67. */
  68. @objc open func cancel() {
  69. cancel(withError: StorageError.cancelled as NSError)
  70. }
  71. /**
  72. * Resumes a paused task. Calling this on a running task has no effect.
  73. */
  74. @objc open func resume() {
  75. dispatchQueue.async { [weak self] in
  76. guard let self = self else { return }
  77. self.state = .resuming
  78. self.fire(for: .resume, snapshot: self.snapshot)
  79. self.state = .running
  80. Task {
  81. await self.enqueueImplementation(resumeWith: self.downloadData)
  82. }
  83. }
  84. }
  85. private var fetcher: GTMSessionFetcher?
  86. var downloadData: Data?
  87. // Hold completion in object to force it to be retained until completion block is called.
  88. var completionData: ((Data?, Error?) -> Void)?
  89. var completionURL: ((URL?, Error?) -> Void)?
  90. // MARK: - Internal Implementations
  91. override init(reference: StorageReference,
  92. queue: DispatchQueue,
  93. file: URL?) {
  94. super.init(reference: reference, queue: queue, file: file)
  95. }
  96. deinit {
  97. self.fetcher?.stopFetching()
  98. }
  99. private func enqueueImplementation(resumeWith resumeData: Data? = nil) async {
  100. state = .queueing
  101. var request = baseRequest
  102. request.httpMethod = "GET"
  103. request.timeoutInterval = reference.storage.maxDownloadRetryTime
  104. var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)
  105. components?.query = "alt=media"
  106. request.url = components?.url
  107. var fetcher: GTMSessionFetcher
  108. if let resumeData {
  109. fetcher = GTMSessionFetcher(downloadResumeData: resumeData)
  110. fetcher.comment = "Resuming DownloadTask"
  111. } else {
  112. let fetcherService = await StorageFetcherService.shared.service(reference.storage)
  113. fetcher = fetcherService.fetcher(with: request)
  114. fetcher.comment = "Starting DownloadTask"
  115. }
  116. fetcher.maxRetryInterval = reference.storage.maxDownloadRetryInterval
  117. if let fileURL {
  118. // Handle file downloads
  119. fetcher.destinationFileURL = fileURL
  120. fetcher.downloadProgressBlock = { [weak self] (bytesWritten: Int64,
  121. totalBytesWritten: Int64,
  122. totalBytesExpectedToWrite: Int64) in
  123. guard let self = self else { return }
  124. self.state = .progress
  125. self.progress.completedUnitCount = totalBytesWritten
  126. self.progress.totalUnitCount = totalBytesExpectedToWrite
  127. self.fire(for: .progress, snapshot: self.snapshot)
  128. self.state = .running
  129. }
  130. } else {
  131. // Handle data downloads
  132. fetcher.receivedProgressBlock = { [weak self] (bytesWritten: Int64,
  133. totalBytesWritten: Int64) in
  134. guard let self = self else { return }
  135. self.state = .progress
  136. self.progress.completedUnitCount = totalBytesWritten
  137. if let totalLength = self.fetcher?.response?.expectedContentLength {
  138. self.progress.totalUnitCount = totalLength
  139. }
  140. self.fire(for: .progress, snapshot: self.snapshot)
  141. self.state = .running
  142. }
  143. }
  144. self.fetcher = fetcher
  145. state = .running
  146. do {
  147. let data = try await self.fetcher?.beginFetch()
  148. // Fire last progress updates
  149. fire(for: .progress, snapshot: snapshot)
  150. // Download completed successfully, fire completion callbacks
  151. state = .success
  152. if let data {
  153. downloadData = data
  154. }
  155. fire(for: .success, snapshot: snapshot)
  156. } catch {
  157. fire(for: .progress, snapshot: snapshot)
  158. state = .failed
  159. self.error = StorageErrorCode.error(
  160. withServerError: error as NSError,
  161. ref: reference
  162. )
  163. fire(for: .failure, snapshot: snapshot)
  164. }
  165. removeAllObservers()
  166. }
  167. func cancel(withError error: NSError) {
  168. dispatchQueue.async { [weak self] in
  169. guard let self = self else { return }
  170. self.state = .cancelled
  171. self.fetcher?.stopFetching()
  172. self.error = error
  173. self.fire(for: .failure, snapshot: self.snapshot)
  174. self.removeAllObservers()
  175. }
  176. }
  177. }