Request.swift 13 KB

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