Request.swift 15 KB

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