Request.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2016 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 asychronous. 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 {
  77. taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
  78. return taskDelegate
  79. }
  80. set {
  81. taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
  82. taskDelegate = newValue
  83. }
  84. }
  85. /// The underlying task.
  86. open var task: URLSessionTask? { return delegate.task }
  87. /// The session belonging to the underlying task.
  88. open let session: URLSession
  89. /// The request sent or to be sent to the server.
  90. open var request: URLRequest? { return task?.originalRequest }
  91. /// The response received from the server, if any.
  92. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
  93. let originalTask: TaskConvertible?
  94. var startTime: CFAbsoluteTime?
  95. var endTime: CFAbsoluteTime?
  96. var validations: [() -> Void] = []
  97. private var taskDelegate: TaskDelegate
  98. private var taskDelegateLock = NSLock()
  99. // MARK: Lifecycle
  100. init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
  101. self.session = session
  102. switch requestTask {
  103. case .data(let originalTask, let task):
  104. taskDelegate = DataTaskDelegate(task: task)
  105. self.originalTask = originalTask
  106. case .download(let originalTask, let task):
  107. taskDelegate = DownloadTaskDelegate(task: task)
  108. self.originalTask = originalTask
  109. case .upload(let originalTask, let task):
  110. taskDelegate = UploadTaskDelegate(task: task)
  111. self.originalTask = originalTask
  112. case .stream(let originalTask, let task):
  113. taskDelegate = TaskDelegate(task: task)
  114. self.originalTask = originalTask
  115. }
  116. delegate.error = error
  117. delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
  118. }
  119. // MARK: Authentication
  120. /// Associates an HTTP Basic credential with the request.
  121. ///
  122. /// - parameter user: The user.
  123. /// - parameter password: The password.
  124. /// - parameter persistence: The URL credential persistence. `.ForSession` by default.
  125. ///
  126. /// - returns: The request.
  127. @discardableResult
  128. open func authenticate(
  129. user: String,
  130. password: String,
  131. persistence: URLCredential.Persistence = .forSession)
  132. -> Self
  133. {
  134. let credential = URLCredential(user: user, password: password, persistence: persistence)
  135. return authenticate(usingCredential: credential)
  136. }
  137. /// Associates a specified credential with the request.
  138. ///
  139. /// - parameter credential: The credential.
  140. ///
  141. /// - returns: The request.
  142. @discardableResult
  143. open func authenticate(usingCredential credential: URLCredential) -> Self {
  144. delegate.credential = credential
  145. return self
  146. }
  147. /// Returns a base64 encoded basic authentication credential as an authorization header tuple.
  148. ///
  149. /// - parameter user: The user.
  150. /// - parameter password: The password.
  151. ///
  152. /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
  153. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
  154. guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
  155. let credential = data.base64EncodedString(options: [])
  156. return (key: "Authorization", value: "Basic \(credential)")
  157. }
  158. // MARK: State
  159. /// Resumes the request.
  160. open func resume() {
  161. guard let task = task else { delegate.queue.isSuspended = false ; return }
  162. if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
  163. task.resume()
  164. NotificationCenter.default.post(
  165. name: Notification.Name.Task.DidResume,
  166. object: self,
  167. userInfo: [Notification.Key.Task: task]
  168. )
  169. }
  170. /// Suspends the request.
  171. open func suspend() {
  172. guard let task = task else { return }
  173. task.suspend()
  174. NotificationCenter.default.post(
  175. name: Notification.Name.Task.DidSuspend,
  176. object: self,
  177. userInfo: [Notification.Key.Task: task]
  178. )
  179. }
  180. /// Cancels the request.
  181. open func cancel() {
  182. guard let task = task else { return }
  183. task.cancel()
  184. NotificationCenter.default.post(
  185. name: Notification.Name.Task.DidCancel,
  186. object: self,
  187. userInfo: [Notification.Key.Task: task]
  188. )
  189. }
  190. }
  191. // MARK: - CustomStringConvertible
  192. extension Request: CustomStringConvertible {
  193. /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
  194. /// well as the response status code if a response has been received.
  195. open var description: String {
  196. var components: [String] = []
  197. if let HTTPMethod = request?.httpMethod {
  198. components.append(HTTPMethod)
  199. }
  200. if let urlString = request?.url?.absoluteString {
  201. components.append(urlString)
  202. }
  203. if let response = response {
  204. components.append("(\(response.statusCode))")
  205. }
  206. return components.joined(separator: " ")
  207. }
  208. }
  209. // MARK: - CustomDebugStringConvertible
  210. extension Request: CustomDebugStringConvertible {
  211. /// The textual representation used when written to an output stream, in the form of a cURL command.
  212. open var debugDescription: String {
  213. return cURLRepresentation()
  214. }
  215. func cURLRepresentation() -> String {
  216. var components = ["$ curl -i"]
  217. guard let request = self.request,
  218. let url = request.url,
  219. let host = url.host
  220. else {
  221. return "$ curl command could not be created"
  222. }
  223. if let httpMethod = request.httpMethod, httpMethod != "GET" {
  224. components.append("-X \(httpMethod)")
  225. }
  226. if let credentialStorage = self.session.configuration.urlCredentialStorage {
  227. let protectionSpace = URLProtectionSpace(
  228. host: host,
  229. port: url.port ?? 0,
  230. protocol: url.scheme,
  231. realm: host,
  232. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  233. )
  234. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  235. for credential in credentials {
  236. components.append("-u \(credential.user!):\(credential.password!)")
  237. }
  238. } else {
  239. if let credential = delegate.credential {
  240. components.append("-u \(credential.user!):\(credential.password!)")
  241. }
  242. }
  243. }
  244. if session.configuration.httpShouldSetCookies {
  245. if
  246. let cookieStorage = session.configuration.httpCookieStorage,
  247. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  248. {
  249. let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
  250. components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
  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. let urlRequest = try self.urlRequest.adapt(using: adapter)
  284. return queue.syncResult { session.dataTask(with: urlRequest) }
  285. }
  286. }
  287. // MARK: Properties
  288. /// The progress of fetching the response data from the server for the request.
  289. open var progress: Progress { return dataDelegate.progress }
  290. var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
  291. // MARK: Stream
  292. /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
  293. ///
  294. /// This closure returns the bytes most recently received from the server, not including data from previous calls.
  295. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
  296. /// also important to note that the server data in any `Response` object will be `nil`.
  297. ///
  298. /// - parameter closure: The code to be executed periodically during the lifecycle of the request.
  299. ///
  300. /// - returns: The request.
  301. @discardableResult
  302. open func stream(closure: ((Data) -> Void)? = nil) -> Self {
  303. dataDelegate.dataStream = closure
  304. return self
  305. }
  306. // MARK: Progress
  307. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  308. ///
  309. /// - parameter queue: The dispatch queue to execute the closure on.
  310. /// - parameter closure: The code to be executed periodically as data is read from the server.
  311. ///
  312. /// - returns: The request.
  313. @discardableResult
  314. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  315. dataDelegate.progressHandler = (closure, queue)
  316. return self
  317. }
  318. }
  319. // MARK: -
  320. /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
  321. open class DownloadRequest: Request {
  322. // MARK: Helper Types
  323. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  324. /// destination URL.
  325. public struct DownloadOptions: OptionSet {
  326. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  327. public let rawValue: UInt
  328. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  329. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
  330. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  331. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
  332. /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
  333. ///
  334. /// - parameter rawValue: The raw bitmask value for the option.
  335. ///
  336. /// - returns: A new log level instance.
  337. public init(rawValue: UInt) {
  338. self.rawValue = rawValue
  339. }
  340. }
  341. /// A closure executed once a download request has successfully completed in order to determine where to move the
  342. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  343. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  344. /// the options defining how the file should be moved.
  345. public typealias DownloadFileDestination = (
  346. _ temporaryURL: URL,
  347. _ response: HTTPURLResponse)
  348. -> (destinationURL: URL, options: DownloadOptions)
  349. enum Downloadable: TaskConvertible {
  350. case request(URLRequest)
  351. case resumeData(Data)
  352. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  353. let task: URLSessionTask
  354. switch self {
  355. case let .request(urlRequest):
  356. let urlRequest = try urlRequest.adapt(using: adapter)
  357. task = queue.syncResult { session.downloadTask(with: urlRequest) }
  358. case let .resumeData(resumeData):
  359. task = queue.syncResult { session.downloadTask(withResumeData: resumeData) }
  360. }
  361. return task
  362. }
  363. }
  364. // MARK: Properties
  365. /// The resume data of the underlying download task if available after a failure.
  366. open var resumeData: Data? { return downloadDelegate.resumeData }
  367. /// The progress of downloading the response data from the server for the request.
  368. open var progress: Progress { return downloadDelegate.progress }
  369. var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
  370. // MARK: State
  371. /// Cancels the request.
  372. open override func cancel() {
  373. downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
  374. NotificationCenter.default.post(
  375. name: Notification.Name.Task.DidCancel,
  376. object: self,
  377. userInfo: [Notification.Key.Task: task]
  378. )
  379. }
  380. // MARK: Progress
  381. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  382. ///
  383. /// - parameter queue: The dispatch queue to execute the closure on.
  384. /// - parameter closure: The code to be executed periodically as data is read from the server.
  385. ///
  386. /// - returns: The request.
  387. @discardableResult
  388. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  389. downloadDelegate.progressHandler = (closure, queue)
  390. return self
  391. }
  392. // MARK: Destination
  393. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  394. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  395. ///
  396. /// - parameter directory: The search path directory. `.DocumentDirectory` by default.
  397. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
  398. ///
  399. /// - returns: A download file destination closure.
  400. open class func suggestedDownloadDestination(
  401. for directory: FileManager.SearchPathDirectory = .documentDirectory,
  402. in domain: FileManager.SearchPathDomainMask = .userDomainMask)
  403. -> DownloadFileDestination
  404. {
  405. return { temporaryURL, response in
  406. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  407. if !directoryURLs.isEmpty {
  408. return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
  409. }
  410. return (temporaryURL, [])
  411. }
  412. }
  413. }
  414. // MARK: -
  415. /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
  416. open class UploadRequest: DataRequest {
  417. // MARK: Helper Types
  418. enum Uploadable: TaskConvertible {
  419. case data(Data, URLRequest)
  420. case file(URL, URLRequest)
  421. case stream(InputStream, URLRequest)
  422. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  423. let task: URLSessionTask
  424. switch self {
  425. case let .data(data, urlRequest):
  426. let urlRequest = try urlRequest.adapt(using: adapter)
  427. task = queue.syncResult { session.uploadTask(with: urlRequest, from: data) }
  428. case let .file(url, urlRequest):
  429. let urlRequest = try urlRequest.adapt(using: adapter)
  430. task = queue.syncResult { session.uploadTask(with: urlRequest, fromFile: url) }
  431. case let .stream(_, urlRequest):
  432. let urlRequest = try urlRequest.adapt(using: adapter)
  433. task = queue.syncResult { session.uploadTask(withStreamedRequest: urlRequest) }
  434. }
  435. return task
  436. }
  437. }
  438. // MARK: Properties
  439. /// The progress of uploading the payload to the server for the upload request.
  440. open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
  441. var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
  442. // MARK: Upload Progress
  443. /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
  444. /// the server.
  445. ///
  446. /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
  447. /// of data being read from the server.
  448. ///
  449. /// - parameter queue: The dispatch queue to execute the closure on.
  450. /// - parameter closure: The code to be executed periodically as data is sent to the server.
  451. ///
  452. /// - returns: The request.
  453. @discardableResult
  454. open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  455. uploadDelegate.uploadProgressHandler = (closure, queue)
  456. return self
  457. }
  458. }
  459. // MARK: -
  460. #if !os(watchOS)
  461. /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
  462. open class StreamRequest: Request {
  463. enum Streamable: TaskConvertible {
  464. case stream(hostName: String, port: Int)
  465. case netService(NetService)
  466. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  467. let task: URLSessionTask
  468. switch self {
  469. case let .stream(hostName, port):
  470. task = queue.syncResult { session.streamTask(withHostName: hostName, port: port) }
  471. case let .netService(netService):
  472. task = queue.syncResult { session.streamTask(with: netService) }
  473. }
  474. return task
  475. }
  476. }
  477. }
  478. #endif