Request.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2017 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. components.append("-H \"\(field): \(value)\"")
  266. }
  267. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  268. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  269. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  270. components.append("-d \"\(escapedBody)\"")
  271. }
  272. components.append("\"\(url.absoluteString)\"")
  273. return components.joined(separator: " \\\n\t")
  274. }
  275. }
  276. // MARK: -
  277. /// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
  278. open class DataRequest: Request {
  279. // MARK: Helper Types
  280. struct Requestable: TaskConvertible {
  281. let urlRequest: URLRequest
  282. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  283. do {
  284. let urlRequest = try self.urlRequest.adapt(using: adapter)
  285. return queue.sync { session.dataTask(with: urlRequest) }
  286. } catch {
  287. throw AdaptError(error: error)
  288. }
  289. }
  290. }
  291. // MARK: Properties
  292. /// The request sent or to be sent to the server.
  293. open override var request: URLRequest? {
  294. if let request = super.request { return request }
  295. if let requestable = originalTask as? Requestable { return requestable.urlRequest }
  296. return nil
  297. }
  298. /// The progress of fetching the response data from the server for the request.
  299. open var progress: Progress { return dataDelegate.progress }
  300. var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
  301. // MARK: Stream
  302. /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
  303. ///
  304. /// This closure returns the bytes most recently received from the server, not including data from previous calls.
  305. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
  306. /// also important to note that the server data in any `Response` object will be `nil`.
  307. ///
  308. /// - parameter closure: The code to be executed periodically during the lifecycle of the request.
  309. ///
  310. /// - returns: The request.
  311. @discardableResult
  312. open func stream(closure: ((Data) -> Void)? = nil) -> Self {
  313. dataDelegate.dataStream = closure
  314. return self
  315. }
  316. // MARK: Progress
  317. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  318. ///
  319. /// - parameter queue: The dispatch queue to execute the closure on.
  320. /// - parameter closure: The code to be executed periodically as data is read from the server.
  321. ///
  322. /// - returns: The request.
  323. @discardableResult
  324. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  325. dataDelegate.progressHandler = (closure, queue)
  326. return self
  327. }
  328. }
  329. // MARK: -
  330. /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
  331. open class DownloadRequest: Request {
  332. // MARK: Helper Types
  333. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  334. /// destination URL.
  335. public struct DownloadOptions: OptionSet {
  336. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  337. public let rawValue: UInt
  338. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  339. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
  340. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  341. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
  342. /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
  343. ///
  344. /// - parameter rawValue: The raw bitmask value for the option.
  345. ///
  346. /// - returns: A new log level instance.
  347. public init(rawValue: UInt) {
  348. self.rawValue = rawValue
  349. }
  350. }
  351. /// A closure executed once a download request has successfully completed in order to determine where to move the
  352. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  353. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  354. /// the options defining how the file should be moved.
  355. public typealias DownloadFileDestination = (
  356. _ temporaryURL: URL,
  357. _ response: HTTPURLResponse)
  358. -> (destinationURL: URL, options: DownloadOptions)
  359. enum Downloadable: TaskConvertible {
  360. case request(URLRequest)
  361. case resumeData(Data)
  362. // TODO: Ask about this use of queue. Perhaps just to protect session and adapter?
  363. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  364. do {
  365. let task: URLSessionTask
  366. switch self {
  367. case let .request(urlRequest):
  368. let urlRequest = try urlRequest.adapt(using: adapter)
  369. task = queue.sync { session.downloadTask(with: urlRequest) }
  370. case let .resumeData(resumeData):
  371. task = queue.sync { session.downloadTask(withResumeData: resumeData) }
  372. }
  373. return task
  374. } catch {
  375. throw AdaptError(error: error)
  376. }
  377. }
  378. }
  379. // MARK: Properties
  380. /// The request sent or to be sent to the server.
  381. open override var request: URLRequest? {
  382. if let request = super.request { return request }
  383. if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
  384. return urlRequest
  385. }
  386. return nil
  387. }
  388. /// The resume data of the underlying download task if available after a failure.
  389. open var resumeData: Data? { return downloadDelegate.resumeData }
  390. /// The progress of downloading the response data from the server for the request.
  391. open var progress: Progress { return downloadDelegate.progress }
  392. var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
  393. // MARK: State
  394. /// Cancels the request.
  395. open override func cancel() {
  396. downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
  397. NotificationCenter.default.post(
  398. name: Notification.Name.Task.DidCancel,
  399. object: self,
  400. userInfo: [Notification.Key.Task: task as Any]
  401. )
  402. }
  403. // MARK: Progress
  404. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  405. ///
  406. /// - parameter queue: The dispatch queue to execute the closure on.
  407. /// - parameter closure: The code to be executed periodically as data is read from the server.
  408. ///
  409. /// - returns: The request.
  410. @discardableResult
  411. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  412. downloadDelegate.progressHandler = (closure, queue)
  413. return self
  414. }
  415. // MARK: Destination
  416. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  417. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  418. ///
  419. /// - parameter directory: The search path directory. `.DocumentDirectory` by default.
  420. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
  421. ///
  422. /// - returns: A download file destination closure.
  423. open class func suggestedDownloadDestination(
  424. for directory: FileManager.SearchPathDirectory = .documentDirectory,
  425. in domain: FileManager.SearchPathDomainMask = .userDomainMask)
  426. -> DownloadFileDestination
  427. {
  428. return { temporaryURL, response in
  429. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  430. if !directoryURLs.isEmpty {
  431. return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
  432. }
  433. return (temporaryURL, [])
  434. }
  435. }
  436. }
  437. // MARK: -
  438. /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
  439. open class UploadRequest: DataRequest {
  440. // MARK: Helper Types
  441. enum Uploadable: TaskConvertible {
  442. case data(Data, URLRequest)
  443. case file(URL, URLRequest)
  444. case stream(InputStream, URLRequest)
  445. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  446. do {
  447. let task: URLSessionTask
  448. switch self {
  449. case let .data(data, urlRequest):
  450. let urlRequest = try urlRequest.adapt(using: adapter)
  451. task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
  452. case let .file(url, urlRequest):
  453. let urlRequest = try urlRequest.adapt(using: adapter)
  454. task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
  455. case let .stream(_, urlRequest):
  456. let urlRequest = try urlRequest.adapt(using: adapter)
  457. task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
  458. }
  459. return task
  460. } catch {
  461. throw AdaptError(error: error)
  462. }
  463. }
  464. }
  465. // MARK: Properties
  466. /// The request sent or to be sent to the server.
  467. open override var request: URLRequest? {
  468. if let request = super.request { return request }
  469. guard let uploadable = originalTask as? Uploadable else { return nil }
  470. switch uploadable {
  471. case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
  472. return urlRequest
  473. }
  474. }
  475. /// The progress of uploading the payload to the server for the upload request.
  476. open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
  477. var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
  478. // MARK: Upload Progress
  479. /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
  480. /// the server.
  481. ///
  482. /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
  483. /// of data being read from the server.
  484. ///
  485. /// - parameter queue: The dispatch queue to execute the closure on.
  486. /// - parameter closure: The code to be executed periodically as data is sent to the server.
  487. ///
  488. /// - returns: The request.
  489. @discardableResult
  490. open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  491. uploadDelegate.uploadProgressHandler = (closure, queue)
  492. return self
  493. }
  494. }
  495. // MARK: -
  496. #if !os(watchOS)
  497. /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
  498. open class StreamRequest: Request {
  499. enum Streamable: TaskConvertible {
  500. case stream(hostName: String, port: Int)
  501. case netService(NetService)
  502. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  503. let task: URLSessionTask
  504. switch self {
  505. case let .stream(hostName, port):
  506. task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
  507. case let .netService(netService):
  508. task = queue.sync { session.streamTask(with: netService) }
  509. }
  510. return task
  511. }
  512. }
  513. }
  514. #endif