Request.swift 22 KB

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