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