Request.swift 18 KB

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