2
0

Request.swift 21 KB

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