Request.swift 13 KB

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