StorageUploadTask.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. @_implementationOnly import GoogleUtilities
  17. #else
  18. @_implementationOnly import GoogleUtilities_Environment
  19. #endif // COCOAPODS
  20. #if COCOAPODS
  21. import GTMSessionFetcher
  22. #else
  23. import GTMSessionFetcherCore
  24. #endif
  25. /**
  26. * `StorageUploadTask` implements resumable uploads to a file in Firebase Storage.
  27. *
  28. * Uploads can be returned on completion with a completion callback, and can be monitored
  29. * by attaching observers, or controlled by calling `pause()`, `resume()`,
  30. * or `cancel()`.
  31. *
  32. * Uploads can be initialized from `Data` in memory, or a URL to a file on disk.
  33. *
  34. * Uploads are performed on a background queue, and callbacks are raised on the developer
  35. * specified `callbackQueue` in Storage, or the main queue if unspecified.
  36. */
  37. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  38. @objc(FIRStorageUploadTask) open class StorageUploadTask: StorageObservableTask,
  39. StorageTaskManagement {
  40. /**
  41. * Prepares a task and begins execution.
  42. */
  43. @objc open func enqueue() {
  44. // Capturing self so that the upload is done whether or not there is a callback.
  45. dispatchQueue.async { [self] in
  46. if let contentValidationError = self.contentUploadError() {
  47. self.error = contentValidationError
  48. self.finishTaskWithStatus(status: .failure, snapshot: self.snapshot)
  49. return
  50. }
  51. self.state = .queueing
  52. var request = self.baseRequest
  53. request.httpMethod = "POST"
  54. request.timeoutInterval = self.reference.storage.maxUploadRetryTime
  55. let dataRepresentation = self.uploadMetadata.dictionaryRepresentation()
  56. let bodyData = try? JSONSerialization.data(withJSONObject: dataRepresentation)
  57. request.httpBody = bodyData
  58. request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
  59. if let count = bodyData?.count {
  60. request.setValue("\(count)", forHTTPHeaderField: "Content-Length")
  61. }
  62. var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)
  63. if components?.host == "www.googleapis.com",
  64. let path = components?.path {
  65. components?.percentEncodedPath = "/upload\(path)"
  66. }
  67. guard let path = self.GCSEscapedString(self.uploadMetadata.path) else {
  68. fatalError("Internal error enqueueing a Storage task")
  69. }
  70. components?.percentEncodedQuery = "uploadType=resumable&name=\(path)"
  71. request.url = components?.url
  72. guard let contentType = self.uploadMetadata.contentType else {
  73. fatalError("Internal error enqueueing a Storage task")
  74. }
  75. let uploadFetcher = GTMSessionUploadFetcher(
  76. request: request,
  77. uploadMIMEType: contentType,
  78. chunkSize: self.reference.storage.uploadChunkSizeBytes,
  79. fetcherService: self.fetcherService
  80. )
  81. if let uploadData {
  82. uploadFetcher.uploadData = uploadData
  83. uploadFetcher.comment = "Data UploadTask"
  84. } else if let fileURL {
  85. uploadFetcher.uploadFileURL = fileURL
  86. uploadFetcher.comment = "File UploadTask"
  87. if GULAppEnvironmentUtil.isAppExtension() {
  88. uploadFetcher.useBackgroundSession = false
  89. }
  90. }
  91. uploadFetcher.maxRetryInterval = self.reference.storage.maxUploadRetryInterval
  92. uploadFetcher.sendProgressBlock = { [weak self] (bytesSent: Int64, totalBytesSent: Int64,
  93. totalBytesExpectedToSend: Int64) in
  94. guard let self = self else { return }
  95. self.state = .progress
  96. self.progress.completedUnitCount = totalBytesSent
  97. self.progress.totalUnitCount = totalBytesExpectedToSend
  98. self.metadata = self.uploadMetadata
  99. self.fire(for: .progress, snapshot: self.snapshot)
  100. self.state = .running
  101. }
  102. self.uploadFetcher = uploadFetcher
  103. // Process fetches
  104. self.state = .running
  105. self.fetcherCompletion = { [self] (data: Data?, error: NSError?) in
  106. // Fire last progress updates
  107. self.fire(for: .progress, snapshot: self.snapshot)
  108. // Handle potential issues with upload
  109. if let error {
  110. self.state = .failed
  111. self.error = StorageErrorCode.error(withServerError: error, ref: self.reference)
  112. self.metadata = self.uploadMetadata
  113. self.finishTaskWithStatus(status: .failure, snapshot: self.snapshot)
  114. return
  115. }
  116. // Upload completed successfully, fire completion callbacks
  117. self.state = .success
  118. guard let data = data else {
  119. fatalError("Internal Error: fetcherCompletion returned with nil data and nil error")
  120. }
  121. if let responseDictionary = try? JSONSerialization
  122. .jsonObject(with: data) as? [String: AnyHashable] {
  123. let metadata = StorageMetadata(dictionary: responseDictionary)
  124. metadata.fileType = .file
  125. self.metadata = metadata
  126. } else {
  127. self.error = StorageErrorCode.error(withInvalidRequest: data)
  128. }
  129. self.finishTaskWithStatus(status: .success, snapshot: self.snapshot)
  130. }
  131. self.uploadFetcher?.beginFetch { [weak self] (data: Data?, error: Error?) in
  132. self?.fetcherCompletion?(data, error as NSError?)
  133. }
  134. }
  135. }
  136. /**
  137. * Pauses a task currently in progress.
  138. */
  139. @objc open func pause() {
  140. dispatchQueue.async { [weak self] in
  141. guard let self = self else { return }
  142. self.state = .paused
  143. self.uploadFetcher?.pauseFetching()
  144. if self.state != .success {
  145. self.metadata = self.uploadMetadata
  146. }
  147. self.fire(for: .pause, snapshot: self.snapshot)
  148. }
  149. }
  150. /**
  151. * Cancels a task.
  152. */
  153. @objc open func cancel() {
  154. dispatchQueue.async { [weak self] in
  155. guard let self = self else { return }
  156. self.state = .cancelled
  157. self.uploadFetcher?.stopFetching()
  158. if self.state != .success {
  159. self.metadata = self.uploadMetadata
  160. }
  161. self.error = StorageErrorCode.error(
  162. withServerError: StorageErrorCode.cancelled as NSError,
  163. ref: self.reference
  164. )
  165. self.fire(for: .failure, snapshot: self.snapshot)
  166. }
  167. }
  168. /**
  169. * Resumes a paused task.
  170. */
  171. @objc open func resume() {
  172. dispatchQueue.async { [weak self] in
  173. guard let self = self else { return }
  174. self.state = .resuming
  175. self.uploadFetcher?.resumeFetching()
  176. if self.state != .success {
  177. self.metadata = self.uploadMetadata
  178. }
  179. self.fire(for: .resume, snapshot: self.snapshot)
  180. self.state = .running
  181. }
  182. }
  183. private var uploadFetcher: GTMSessionUploadFetcher?
  184. private var fetcherCompletion: ((Data?, NSError?) -> Void)?
  185. private var uploadMetadata: StorageMetadata
  186. private var uploadData: Data?
  187. // Hold completion in object to force it to be retained until completion block is called.
  188. var completionMetadata: ((StorageMetadata?, Error?) -> Void)?
  189. // MARK: - Internal Implementations
  190. init(reference: StorageReference,
  191. service: GTMSessionFetcherService,
  192. queue: DispatchQueue,
  193. file: URL? = nil,
  194. data: Data? = nil,
  195. metadata: StorageMetadata) {
  196. uploadMetadata = metadata
  197. uploadData = data
  198. super.init(reference: reference, service: service, queue: queue, file: file)
  199. if uploadMetadata.contentType == nil {
  200. uploadMetadata.contentType = StorageUtils.MIMETypeForExtension(file?.pathExtension)
  201. }
  202. }
  203. deinit {
  204. self.uploadFetcher?.stopFetching()
  205. }
  206. private func contentUploadError() -> NSError? {
  207. if uploadData != nil {
  208. return nil
  209. }
  210. if let resourceValues = try? fileURL?.resourceValues(forKeys: [.isRegularFileKey]),
  211. let isFile = resourceValues.isRegularFile,
  212. isFile == true {
  213. return nil
  214. }
  215. return StorageError.unknown(message: "File at URL: \(fileURL?.absoluteString ?? "") is " +
  216. "not reachable. Ensure file URL is not " +
  217. "a directory, symbolic link, or invalid url.",
  218. serverError: [:]) as NSError
  219. }
  220. func finishTaskWithStatus(status: StorageTaskStatus, snapshot: StorageTaskSnapshot) {
  221. fire(for: status, snapshot: snapshot)
  222. removeAllObservers()
  223. fetcherCompletion = nil
  224. }
  225. private func GCSEscapedString(_ input: String?) -> String? {
  226. guard let input = input else {
  227. return nil
  228. }
  229. let GCSObjectAllowedCharacterSet =
  230. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*,=:@"
  231. let allowedCharacters = CharacterSet(charactersIn: GCSObjectAllowedCharacterSet)
  232. return input.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
  233. }
  234. }