StorageUploadTask.swift 9.0 KB

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