Request.swift 23 KB

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