UploadRequest.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. //
  2. // UploadRequest.swift
  3. //
  4. // Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  26. public final class UploadRequest: DataRequest {
  27. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  28. public enum Uploadable {
  29. /// Upload from the provided `Data` value.
  30. case data(Data)
  31. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  32. /// automatically removed once uploaded.
  33. case file(URL, shouldRemove: Bool)
  34. /// Upload from the provided `InputStream`.
  35. case stream(InputStream)
  36. }
  37. // MARK: Initial State
  38. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  39. public let upload: UploadableConvertible
  40. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  41. /// to disk.
  42. public let fileManager: FileManager
  43. // MARK: Mutable State
  44. /// `Uploadable` value used by the instance.
  45. public var uploadable: Uploadable?
  46. /// Creates an `UploadRequest` using the provided parameters.
  47. ///
  48. /// - Parameters:
  49. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  50. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  51. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  52. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  53. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  54. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  55. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  56. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  57. /// encoded payloads written to disk.
  58. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  59. init(id: UUID = UUID(),
  60. convertible: UploadConvertible,
  61. underlyingQueue: DispatchQueue,
  62. serializationQueue: DispatchQueue,
  63. eventMonitor: EventMonitor?,
  64. interceptor: RequestInterceptor?,
  65. fileManager: FileManager,
  66. delegate: RequestDelegate) {
  67. upload = convertible
  68. self.fileManager = fileManager
  69. super.init(id: id,
  70. convertible: convertible,
  71. underlyingQueue: underlyingQueue,
  72. serializationQueue: serializationQueue,
  73. eventMonitor: eventMonitor,
  74. interceptor: interceptor,
  75. delegate: delegate)
  76. }
  77. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  78. ///
  79. /// - Parameter uploadable: The `Uploadable` that was created.
  80. func didCreateUploadable(_ uploadable: Uploadable) {
  81. self.uploadable = uploadable
  82. eventMonitor?.request(self, didCreateUploadable: uploadable)
  83. }
  84. /// Called when the `Uploadable` value could not be created.
  85. ///
  86. /// - Parameter error: `AFError` produced by the failure.
  87. func didFailToCreateUploadable(with error: AFError) {
  88. self.error = error
  89. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  90. retryOrFinish(error: error)
  91. }
  92. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  93. guard let uploadable else {
  94. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  95. }
  96. switch uploadable {
  97. case let .data(data): return session.uploadTask(with: request, from: data)
  98. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  99. case .stream: return session.uploadTask(withStreamedRequest: request)
  100. }
  101. }
  102. override func reset() {
  103. // Uploadable must be recreated on every retry.
  104. uploadable = nil
  105. super.reset()
  106. }
  107. /// Produces the `InputStream` from `uploadable`, if it can.
  108. ///
  109. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  110. ///
  111. /// - Returns: The `InputStream`.
  112. func inputStream() -> InputStream {
  113. guard let uploadable else {
  114. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  115. }
  116. guard case let .stream(stream) = uploadable else {
  117. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  118. }
  119. eventMonitor?.request(self, didProvideInputStream: stream)
  120. return stream
  121. }
  122. override public func cleanup() {
  123. defer { super.cleanup() }
  124. guard
  125. let uploadable,
  126. case let .file(url, shouldRemove) = uploadable,
  127. shouldRemove
  128. else { return }
  129. try? fileManager.removeItem(at: url)
  130. }
  131. }
  132. /// A type that can produce an `UploadRequest.Uploadable` value.
  133. public protocol UploadableConvertible {
  134. /// Produces an `UploadRequest.Uploadable` value from the instance.
  135. ///
  136. /// - Returns: The `UploadRequest.Uploadable`.
  137. /// - Throws: Any `Error` produced during creation.
  138. func createUploadable() throws -> UploadRequest.Uploadable
  139. }
  140. extension UploadRequest.Uploadable: UploadableConvertible {
  141. public func createUploadable() throws -> UploadRequest.Uploadable {
  142. self
  143. }
  144. }
  145. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  146. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}