Request.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2018 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. /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
  26. public protocol RequestAdapter {
  27. /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
  28. ///
  29. /// - parameter urlRequest: The URL request to adapt.
  30. ///
  31. /// - throws: An `Error` if the adaptation encounters an error.
  32. ///
  33. /// - returns: The adapted `URLRequest`.
  34. func adapt(_ urlRequest: URLRequest) throws -> URLRequest
  35. }
  36. // MARK: -
  37. /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
  38. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
  39. /// A type that determines whether a request should be retried after being executed by the specified session manager
  40. /// and encountering an error.
  41. public protocol RequestRetrier {
  42. /// Determines whether the `Request` should be retried by calling the `completion` closure.
  43. ///
  44. /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
  45. /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
  46. /// cleaned up after.
  47. ///
  48. /// - parameter manager: The session manager the request was executed on.
  49. /// - parameter request: The request that failed due to the encountered error.
  50. /// - parameter error: The error encountered when executing the request.
  51. /// - parameter completion: The completion closure to be executed when retry decision has been determined.
  52. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
  53. }
  54. // MARK: -
  55. protocol TaskConvertible {
  56. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
  57. }
  58. /// A dictionary of headers to apply to a `URLRequest`.
  59. public typealias HTTPHeaders = [String: String]
  60. // MARK: -
  61. /// Responsible for sending a request and receiving the response and associated data from the server, as well as
  62. /// managing its underlying `URLSessionTask`.
  63. open class Request {
  64. // MARK: Helper Types
  65. /// A closure executed when monitoring upload or download progress of a request.
  66. public typealias ProgressHandler = (Progress) -> Void
  67. enum RequestTask {
  68. case data(TaskConvertible?, URLSessionTask?)
  69. case download(TaskConvertible?, URLSessionTask?)
  70. case upload(TaskConvertible?, URLSessionTask?)
  71. case stream(TaskConvertible?, URLSessionTask?)
  72. }
  73. // MARK: Properties
  74. /// The delegate for the underlying task.
  75. open internal(set) var delegate: TaskDelegate {
  76. get { return protectedDelegate.directValue }
  77. set { protectedDelegate.directValue = newValue }
  78. }
  79. /// The underlying task.
  80. open var task: URLSessionTask? { return delegate.task }
  81. /// The session belonging to the underlying task.
  82. open let session: URLSession
  83. /// The request sent or to be sent to the server.
  84. open var request: URLRequest? { return task?.originalRequest }
  85. /// The response received from the server, if any.
  86. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
  87. /// The number of times the request has been retried.
  88. open internal(set) var retryCount: UInt = 0
  89. let originalTask: TaskConvertible?
  90. var startTime: CFAbsoluteTime?
  91. var endTime: CFAbsoluteTime?
  92. var validations: [() -> Void] = []
  93. private var protectedDelegate: Protector<TaskDelegate>
  94. // MARK: Lifecycle
  95. init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
  96. self.session = session
  97. switch requestTask {
  98. case .data(let originalTask, let task):
  99. protectedDelegate = Protector(DataTaskDelegate(task: task))
  100. self.originalTask = originalTask
  101. case .download(let originalTask, let task):
  102. protectedDelegate = Protector(DownloadTaskDelegate(task: task))
  103. self.originalTask = originalTask
  104. case .upload(let originalTask, let task):
  105. protectedDelegate = Protector(UploadTaskDelegate(task: task))
  106. self.originalTask = originalTask
  107. case .stream(let originalTask, let task):
  108. protectedDelegate = Protector(TaskDelegate(task: task))
  109. self.originalTask = originalTask
  110. }
  111. delegate.error = error
  112. delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
  113. }
  114. // MARK: Authentication
  115. /// Associates an HTTP Basic credential with the request.
  116. ///
  117. /// - parameter user: The user.
  118. /// - parameter password: The password.
  119. /// - parameter persistence: The URL credential persistence. `.ForSession` by default.
  120. ///
  121. /// - returns: The request.
  122. @discardableResult
  123. open func authenticate(
  124. user: String,
  125. password: String,
  126. persistence: URLCredential.Persistence = .forSession)
  127. -> Self
  128. {
  129. let credential = URLCredential(user: user, password: password, persistence: persistence)
  130. return authenticate(usingCredential: credential)
  131. }
  132. /// Associates a specified credential with the request.
  133. ///
  134. /// - parameter credential: The credential.
  135. ///
  136. /// - returns: The request.
  137. @discardableResult
  138. open func authenticate(usingCredential credential: URLCredential) -> Self {
  139. delegate.credential = credential
  140. return self
  141. }
  142. /// Returns a base64 encoded basic authentication credential as an authorization header tuple.
  143. ///
  144. /// - parameter user: The user.
  145. /// - parameter password: The password.
  146. ///
  147. /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
  148. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
  149. guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
  150. let credential = data.base64EncodedString(options: [])
  151. return (key: "Authorization", value: "Basic \(credential)")
  152. }
  153. // MARK: State
  154. /// Resumes the request.
  155. open func resume() {
  156. guard let task = task else { delegate.queue.isSuspended = false ; return }
  157. if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
  158. task.resume()
  159. NotificationCenter.default.post(
  160. name: Notification.Name.Task.DidResume,
  161. object: self,
  162. userInfo: [Notification.Key.Task: task]
  163. )
  164. }
  165. /// Suspends the request.
  166. open func suspend() {
  167. guard let task = task else { return }
  168. task.suspend()
  169. NotificationCenter.default.post(
  170. name: Notification.Name.Task.DidSuspend,
  171. object: self,
  172. userInfo: [Notification.Key.Task: task]
  173. )
  174. }
  175. /// Cancels the request.
  176. open func cancel() {
  177. guard let task = task else { return }
  178. task.cancel()
  179. NotificationCenter.default.post(
  180. name: Notification.Name.Task.DidCancel,
  181. object: self,
  182. userInfo: [Notification.Key.Task: task]
  183. )
  184. }
  185. }
  186. // MARK: - CustomStringConvertible
  187. extension Request: CustomStringConvertible {
  188. /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
  189. /// well as the response status code if a response has been received.
  190. open var description: String {
  191. var components: [String] = []
  192. if let HTTPMethod = request?.httpMethod {
  193. components.append(HTTPMethod)
  194. }
  195. if let urlString = request?.url?.absoluteString {
  196. components.append(urlString)
  197. }
  198. if let response = response {
  199. components.append("(\(response.statusCode))")
  200. }
  201. return components.joined(separator: " ")
  202. }
  203. }
  204. // MARK: - CustomDebugStringConvertible
  205. extension Request: CustomDebugStringConvertible {
  206. /// The textual representation used when written to an output stream, in the form of a cURL command.
  207. open var debugDescription: String {
  208. return cURLRepresentation()
  209. }
  210. func cURLRepresentation() -> String {
  211. var components = ["$ curl -v"]
  212. guard let request = self.request,
  213. let url = request.url,
  214. let host = url.host
  215. else {
  216. return "$ curl command could not be created"
  217. }
  218. if let httpMethod = request.httpMethod, httpMethod != "GET" {
  219. components.append("-X \(httpMethod)")
  220. }
  221. if let credentialStorage = self.session.configuration.urlCredentialStorage {
  222. let protectionSpace = URLProtectionSpace(
  223. host: host,
  224. port: url.port ?? 0,
  225. protocol: url.scheme,
  226. realm: host,
  227. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  228. )
  229. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  230. for credential in credentials {
  231. guard let user = credential.user, let password = credential.password else { continue }
  232. components.append("-u \(user):\(password)")
  233. }
  234. } else {
  235. if let credential = delegate.credential, let user = credential.user, let password = credential.password {
  236. components.append("-u \(user):\(password)")
  237. }
  238. }
  239. }
  240. if session.configuration.httpShouldSetCookies {
  241. if
  242. let cookieStorage = session.configuration.httpCookieStorage,
  243. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  244. {
  245. let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
  246. #if swift(>=3.2)
  247. components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
  248. #else
  249. components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
  250. #endif
  251. }
  252. }
  253. var headers: [AnyHashable: Any] = [:]
  254. if let additionalHeaders = session.configuration.httpAdditionalHeaders {
  255. for (field, value) in additionalHeaders where field != AnyHashable("Cookie") {
  256. headers[field] = value
  257. }
  258. }
  259. if let headerFields = request.allHTTPHeaderFields {
  260. for (field, value) in headerFields where field != "Cookie" {
  261. headers[field] = value
  262. }
  263. }
  264. for (field, value) in headers {
  265. let escapedValue = String(describing: value).replacingOccurrences(of: "\"", with: "\\\"")
  266. components.append("-H \"\(field): \(escapedValue)\"")
  267. }
  268. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  269. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  270. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  271. components.append("-d \"\(escapedBody)\"")
  272. }
  273. components.append("\"\(url.absoluteString)\"")
  274. return components.joined(separator: " \\\n\t")
  275. }
  276. }
  277. // MARK: -
  278. /// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
  279. open class DataRequest: Request {
  280. // MARK: Helper Types
  281. struct Requestable: TaskConvertible {
  282. let urlRequest: URLRequest
  283. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  284. do {
  285. let urlRequest = try self.urlRequest.adapt(using: adapter)
  286. return queue.sync { session.dataTask(with: urlRequest) }
  287. } catch {
  288. throw AdaptError(error: error)
  289. }
  290. }
  291. }
  292. // MARK: Properties
  293. /// The request sent or to be sent to the server.
  294. open override var request: URLRequest? {
  295. if let request = super.request { return request }
  296. if let requestable = originalTask as? Requestable { return requestable.urlRequest }
  297. return nil
  298. }
  299. /// The progress of fetching the response data from the server for the request.
  300. open var progress: Progress { return dataDelegate.progress }
  301. var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
  302. // MARK: Stream
  303. /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
  304. ///
  305. /// This closure returns the bytes most recently received from the server, not including data from previous calls.
  306. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
  307. /// also important to note that the server data in any `Response` object will be `nil`.
  308. ///
  309. /// - parameter closure: The code to be executed periodically during the lifecycle of the request.
  310. ///
  311. /// - returns: The request.
  312. @discardableResult
  313. open func stream(closure: ((Data) -> Void)? = nil) -> Self {
  314. dataDelegate.dataStream = closure
  315. return self
  316. }
  317. // MARK: Progress
  318. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  319. ///
  320. /// - parameter queue: The dispatch queue to execute the closure on.
  321. /// - parameter closure: The code to be executed periodically as data is read from the server.
  322. ///
  323. /// - returns: The request.
  324. @discardableResult
  325. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  326. dataDelegate.progressHandler = (closure, queue)
  327. return self
  328. }
  329. }
  330. // MARK: -
  331. /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
  332. open class DownloadRequest: Request {
  333. // MARK: Helper Types
  334. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  335. /// destination URL.
  336. public struct DownloadOptions: OptionSet {
  337. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  338. public let rawValue: UInt
  339. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  340. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
  341. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  342. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
  343. /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
  344. ///
  345. /// - parameter rawValue: The raw bitmask value for the option.
  346. ///
  347. /// - returns: A new log level instance.
  348. public init(rawValue: UInt) {
  349. self.rawValue = rawValue
  350. }
  351. }
  352. /// A closure executed once a download request has successfully completed in order to determine where to move the
  353. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  354. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  355. /// the options defining how the file should be moved.
  356. public typealias DownloadFileDestination = (
  357. _ temporaryURL: URL,
  358. _ response: HTTPURLResponse)
  359. -> (destinationURL: URL, options: DownloadOptions)
  360. enum Downloadable: TaskConvertible {
  361. case request(URLRequest)
  362. case resumeData(Data)
  363. // TODO: Ask about this use of queue. Perhaps just to protect session and adapter?
  364. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  365. do {
  366. let task: URLSessionTask
  367. switch self {
  368. case let .request(urlRequest):
  369. let urlRequest = try urlRequest.adapt(using: adapter)
  370. task = queue.sync { session.downloadTask(with: urlRequest) }
  371. case let .resumeData(resumeData):
  372. task = queue.sync { session.downloadTask(withResumeData: resumeData) }
  373. }
  374. return task
  375. } catch {
  376. throw AdaptError(error: error)
  377. }
  378. }
  379. }
  380. // MARK: Properties
  381. /// The request sent or to be sent to the server.
  382. open override var request: URLRequest? {
  383. if let request = super.request { return request }
  384. if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
  385. return urlRequest
  386. }
  387. return nil
  388. }
  389. /// The resume data of the underlying download task if available after a failure.
  390. open var resumeData: Data? { return downloadDelegate.resumeData }
  391. /// The progress of downloading the response data from the server for the request.
  392. open var progress: Progress { return downloadDelegate.progress }
  393. var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
  394. // MARK: State
  395. /// Cancels the request.
  396. open override func cancel() {
  397. downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
  398. NotificationCenter.default.post(
  399. name: Notification.Name.Task.DidCancel,
  400. object: self,
  401. userInfo: [Notification.Key.Task: task as Any]
  402. )
  403. }
  404. // MARK: Progress
  405. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  406. ///
  407. /// - parameter queue: The dispatch queue to execute the closure on.
  408. /// - parameter closure: The code to be executed periodically as data is read from the server.
  409. ///
  410. /// - returns: The request.
  411. @discardableResult
  412. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  413. downloadDelegate.progressHandler = (closure, queue)
  414. return self
  415. }
  416. // MARK: Destination
  417. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  418. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  419. ///
  420. /// - parameter directory: The search path directory. `.DocumentDirectory` by default.
  421. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
  422. ///
  423. /// - returns: A download file destination closure.
  424. open class func suggestedDownloadDestination(
  425. for directory: FileManager.SearchPathDirectory = .documentDirectory,
  426. in domain: FileManager.SearchPathDomainMask = .userDomainMask)
  427. -> DownloadFileDestination
  428. {
  429. return { temporaryURL, response in
  430. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  431. if !directoryURLs.isEmpty {
  432. return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
  433. }
  434. return (temporaryURL, [])
  435. }
  436. }
  437. }
  438. // MARK: -
  439. /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
  440. open class UploadRequest: DataRequest {
  441. // MARK: Helper Types
  442. enum Uploadable: TaskConvertible {
  443. case data(Data, URLRequest)
  444. case file(URL, URLRequest)
  445. case stream(InputStream, URLRequest)
  446. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  447. do {
  448. let task: URLSessionTask
  449. switch self {
  450. case let .data(data, urlRequest):
  451. let urlRequest = try urlRequest.adapt(using: adapter)
  452. task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
  453. case let .file(url, urlRequest):
  454. let urlRequest = try urlRequest.adapt(using: adapter)
  455. task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
  456. case let .stream(_, urlRequest):
  457. let urlRequest = try urlRequest.adapt(using: adapter)
  458. task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
  459. }
  460. return task
  461. } catch {
  462. throw AdaptError(error: error)
  463. }
  464. }
  465. }
  466. // MARK: Properties
  467. /// The request sent or to be sent to the server.
  468. open override var request: URLRequest? {
  469. if let request = super.request { return request }
  470. guard let uploadable = originalTask as? Uploadable else { return nil }
  471. switch uploadable {
  472. case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
  473. return urlRequest
  474. }
  475. }
  476. /// The progress of uploading the payload to the server for the upload request.
  477. open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
  478. var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
  479. // MARK: Upload Progress
  480. /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
  481. /// the server.
  482. ///
  483. /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
  484. /// of data being read from the server.
  485. ///
  486. /// - parameter queue: The dispatch queue to execute the closure on.
  487. /// - parameter closure: The code to be executed periodically as data is sent to the server.
  488. ///
  489. /// - returns: The request.
  490. @discardableResult
  491. open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  492. uploadDelegate.uploadProgressHandler = (closure, queue)
  493. return self
  494. }
  495. }
  496. // MARK: -
  497. #if !os(watchOS)
  498. /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
  499. open class StreamRequest: Request {
  500. enum Streamable: TaskConvertible {
  501. case stream(hostName: String, port: Int)
  502. case netService(NetService)
  503. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  504. let task: URLSessionTask
  505. switch self {
  506. case let .stream(hostName, port):
  507. task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
  508. case let .netService(netService):
  509. task = queue.sync { session.streamTask(with: netService) }
  510. }
  511. return task
  512. }
  513. }
  514. }
  515. #endif