You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

654 lines
24 KiB

6 years ago
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2018 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. /// - throws: An `Error` if the adaptation encounters an error.
  32. ///
  33. /// - returns: The adapted `URLRequest`.
  34. func adapt(_ urlRequest: URLRequest) throws -> URLRequest
  35. }
  36. // MARK: -
  37. /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
  38. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
  39. /// A type that determines whether a request should be retried after being executed by the specified session manager
  40. /// and encountering an error.
  41. public protocol RequestRetrier {
  42. /// Determines whether the `Request` should be retried by calling the `completion` closure.
  43. ///
  44. /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
  45. /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
  46. /// cleaned up after.
  47. ///
  48. /// - parameter manager: The session manager the request was executed on.
  49. /// - parameter request: The request that failed due to the encountered error.
  50. /// - parameter error: The error encountered when executing the request.
  51. /// - parameter completion: The completion closure to be executed when retry decision has been determined.
  52. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
  53. }
  54. // MARK: -
  55. protocol TaskConvertible {
  56. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
  57. }
  58. /// A dictionary of headers to apply to a `URLRequest`.
  59. public typealias HTTPHeaders = [String: String]
  60. // MARK: -
  61. /// Responsible for sending a request and receiving the response and associated data from the server, as well as
  62. /// managing its underlying `URLSessionTask`.
  63. open class Request {
  64. // MARK: Helper Types
  65. /// A closure executed when monitoring upload or download progress of a request.
  66. public typealias ProgressHandler = (Progress) -> Void
  67. enum RequestTask {
  68. case data(TaskConvertible?, URLSessionTask?)
  69. case download(TaskConvertible?, URLSessionTask?)
  70. case upload(TaskConvertible?, URLSessionTask?)
  71. case stream(TaskConvertible?, URLSessionTask?)
  72. }
  73. // MARK: Properties
  74. /// The delegate for the underlying task.
  75. open internal(set) var delegate: TaskDelegate {
  76. get {
  77. taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
  78. return taskDelegate
  79. }
  80. set {
  81. taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
  82. taskDelegate = newValue
  83. }
  84. }
  85. /// The underlying task.
  86. open var task: URLSessionTask? { return delegate.task }
  87. /// The session belonging to the underlying task.
  88. open let session: URLSession
  89. /// The request sent or to be sent to the server.
  90. open var request: URLRequest? { return task?.originalRequest }
  91. /// The response received from the server, if any.
  92. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
  93. /// The number of times the request has been retried.
  94. open internal(set) var retryCount: UInt = 0
  95. let originalTask: TaskConvertible?
  96. var startTime: CFAbsoluteTime?
  97. var endTime: CFAbsoluteTime?
  98. var validations: [() -> Void] = []
  99. private var taskDelegate: TaskDelegate
  100. private var taskDelegateLock = NSLock()
  101. // MARK: Lifecycle
  102. init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
  103. self.session = session
  104. switch requestTask {
  105. case .data(let originalTask, let task):
  106. taskDelegate = DataTaskDelegate(task: task)
  107. self.originalTask = originalTask
  108. case .download(let originalTask, let task):
  109. taskDelegate = DownloadTaskDelegate(task: task)
  110. self.originalTask = originalTask
  111. case .upload(let originalTask, let task):
  112. taskDelegate = UploadTaskDelegate(task: task)
  113. self.originalTask = originalTask
  114. case .stream(let originalTask, let task):
  115. taskDelegate = TaskDelegate(task: task)
  116. self.originalTask = originalTask
  117. }
  118. delegate.error = error
  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 tuple.
  150. ///
  151. /// - parameter user: The user.
  152. /// - parameter password: The password.
  153. ///
  154. /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
  155. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
  156. guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
  157. let credential = data.base64EncodedString(options: [])
  158. return (key: "Authorization", value: "Basic \(credential)")
  159. }
  160. // MARK: State
  161. /// Resumes the request.
  162. open func resume() {
  163. guard let task = task else { delegate.queue.isSuspended = false ; return }
  164. if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
  165. task.resume()
  166. NotificationCenter.default.post(
  167. name: Notification.Name.Task.DidResume,
  168. object: self,
  169. userInfo: [Notification.Key.Task: task]
  170. )
  171. }
  172. /// Suspends the request.
  173. open func suspend() {
  174. guard let task = task else { return }
  175. task.suspend()
  176. NotificationCenter.default.post(
  177. name: Notification.Name.Task.DidSuspend,
  178. object: self,
  179. userInfo: [Notification.Key.Task: task]
  180. )
  181. }
  182. /// Cancels the request.
  183. open func cancel() {
  184. guard let task = task else { return }
  185. task.cancel()
  186. NotificationCenter.default.post(
  187. name: Notification.Name.Task.DidCancel,
  188. object: self,
  189. userInfo: [Notification.Key.Task: task]
  190. )
  191. }
  192. }
  193. // MARK: - CustomStringConvertible
  194. extension Request: CustomStringConvertible {
  195. /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
  196. /// well as the response status code if a response has been received.
  197. open var description: String {
  198. var components: [String] = []
  199. if let HTTPMethod = request?.httpMethod {
  200. components.append(HTTPMethod)
  201. }
  202. if let urlString = request?.url?.absoluteString {
  203. components.append(urlString)
  204. }
  205. if let response = response {
  206. components.append("(\(response.statusCode))")
  207. }
  208. return components.joined(separator: " ")
  209. }
  210. }
  211. // MARK: - CustomDebugStringConvertible
  212. extension Request: CustomDebugStringConvertible {
  213. /// The textual representation used when written to an output stream, in the form of a cURL command.
  214. open var debugDescription: String {
  215. return cURLRepresentation()
  216. }
  217. func cURLRepresentation() -> String {
  218. var components = ["$ curl -v"]
  219. guard let request = self.request,
  220. let url = request.url,
  221. let host = url.host
  222. else {
  223. return "$ curl command could not be created"
  224. }
  225. if let httpMethod = request.httpMethod, httpMethod != "GET" {
  226. components.append("-X \(httpMethod)")
  227. }
  228. if let credentialStorage = self.session.configuration.urlCredentialStorage {
  229. let protectionSpace = URLProtectionSpace(
  230. host: host,
  231. port: url.port ?? 0,
  232. protocol: url.scheme,
  233. realm: host,
  234. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  235. )
  236. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  237. for credential in credentials {
  238. guard let user = credential.user, let password = credential.password else { continue }
  239. components.append("-u \(user):\(password)")
  240. }
  241. } else {
  242. if let credential = delegate.credential, let user = credential.user, let password = credential.password {
  243. components.append("-u \(user):\(password)")
  244. }
  245. }
  246. }
  247. if session.configuration.httpShouldSetCookies {
  248. if
  249. let cookieStorage = session.configuration.httpCookieStorage,
  250. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  251. {
  252. let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
  253. #if swift(>=3.2)
  254. components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
  255. #else
  256. components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
  257. #endif
  258. }
  259. }
  260. var headers: [AnyHashable: Any] = [:]
  261. if let additionalHeaders = session.configuration.httpAdditionalHeaders {
  262. for (field, value) in additionalHeaders where field != AnyHashable("Cookie") {
  263. headers[field] = value
  264. }
  265. }
  266. if let headerFields = request.allHTTPHeaderFields {
  267. for (field, value) in headerFields where field != "Cookie" {
  268. headers[field] = value
  269. }
  270. }
  271. for (field, value) in headers {
  272. let escapedValue = String(describing: value).replacingOccurrences(of: "\"", with: "\\\"")
  273. components.append("-H \"\(field): \(escapedValue)\"")
  274. }
  275. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  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. // MARK: Helper Types
  288. struct Requestable: TaskConvertible {
  289. let urlRequest: URLRequest
  290. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  291. do {
  292. let urlRequest = try self.urlRequest.adapt(using: adapter)
  293. return queue.sync { session.dataTask(with: urlRequest) }
  294. } catch {
  295. throw AdaptError(error: error)
  296. }
  297. }
  298. }
  299. // MARK: Properties
  300. /// The request sent or to be sent to the server.
  301. open override var request: URLRequest? {
  302. if let request = super.request { return request }
  303. if let requestable = originalTask as? Requestable { return requestable.urlRequest }
  304. return nil
  305. }
  306. /// The progress of fetching the response data from the server for the request.
  307. open var progress: Progress { return dataDelegate.progress }
  308. var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
  309. // MARK: Stream
  310. /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
  311. ///
  312. /// This closure returns the bytes most recently received from the server, not including data from previous calls.
  313. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
  314. /// also important to note that the server data in any `Response` object will be `nil`.
  315. ///
  316. /// - parameter closure: The code to be executed periodically during the lifecycle of the request.
  317. ///
  318. /// - returns: The request.
  319. @discardableResult
  320. open func stream(closure: ((Data) -> Void)? = nil) -> Self {
  321. dataDelegate.dataStream = closure
  322. return self
  323. }
  324. // MARK: Progress
  325. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  326. ///
  327. /// - parameter queue: The dispatch queue to execute the closure on.
  328. /// - parameter closure: The code to be executed periodically as data is read from the server.
  329. ///
  330. /// - returns: The request.
  331. @discardableResult
  332. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  333. dataDelegate.progressHandler = (closure, queue)
  334. return self
  335. }
  336. }
  337. // MARK: -
  338. /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
  339. open class DownloadRequest: Request {
  340. // MARK: Helper Types
  341. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  342. /// destination URL.
  343. public struct DownloadOptions: OptionSet {
  344. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  345. public let rawValue: UInt
  346. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  347. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
  348. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  349. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
  350. /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
  351. ///
  352. /// - parameter rawValue: The raw bitmask value for the option.
  353. ///
  354. /// - returns: A new log level instance.
  355. public init(rawValue: UInt) {
  356. self.rawValue = rawValue
  357. }
  358. }
  359. /// A closure executed once a download request has successfully completed in order to determine where to move the
  360. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  361. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  362. /// the options defining how the file should be moved.
  363. public typealias DownloadFileDestination = (
  364. _ temporaryURL: URL,
  365. _ response: HTTPURLResponse)
  366. -> (destinationURL: URL, options: DownloadOptions)
  367. enum Downloadable: TaskConvertible {
  368. case request(URLRequest)
  369. case resumeData(Data)
  370. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  371. do {
  372. let task: URLSessionTask
  373. switch self {
  374. case let .request(urlRequest):
  375. let urlRequest = try urlRequest.adapt(using: adapter)
  376. task = queue.sync { session.downloadTask(with: urlRequest) }
  377. case let .resumeData(resumeData):
  378. task = queue.sync { session.downloadTask(withResumeData: resumeData) }
  379. }
  380. return task
  381. } catch {
  382. throw AdaptError(error: error)
  383. }
  384. }
  385. }
  386. // MARK: Properties
  387. /// The request sent or to be sent to the server.
  388. open override var request: URLRequest? {
  389. if let request = super.request { return request }
  390. if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
  391. return urlRequest
  392. }
  393. return nil
  394. }
  395. /// The resume data of the underlying download task if available after a failure.
  396. open var resumeData: Data? { return downloadDelegate.resumeData }
  397. /// The progress of downloading the response data from the server for the request.
  398. open var progress: Progress { return downloadDelegate.progress }
  399. var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
  400. // MARK: State
  401. /// Cancels the request.
  402. open override func cancel() {
  403. downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
  404. NotificationCenter.default.post(
  405. name: Notification.Name.Task.DidCancel,
  406. object: self,
  407. userInfo: [Notification.Key.Task: task as Any]
  408. )
  409. }
  410. // MARK: Progress
  411. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  412. ///
  413. /// - parameter queue: The dispatch queue to execute the closure on.
  414. /// - parameter closure: The code to be executed periodically as data is read from the server.
  415. ///
  416. /// - returns: The request.
  417. @discardableResult
  418. open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  419. downloadDelegate.progressHandler = (closure, queue)
  420. return self
  421. }
  422. // MARK: Destination
  423. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  424. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  425. ///
  426. /// - parameter directory: The search path directory. `.DocumentDirectory` by default.
  427. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
  428. ///
  429. /// - returns: A download file destination closure.
  430. open class func suggestedDownloadDestination(
  431. for directory: FileManager.SearchPathDirectory = .documentDirectory,
  432. in domain: FileManager.SearchPathDomainMask = .userDomainMask)
  433. -> DownloadFileDestination
  434. {
  435. return { temporaryURL, response in
  436. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  437. if !directoryURLs.isEmpty {
  438. return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
  439. }
  440. return (temporaryURL, [])
  441. }
  442. }
  443. }
  444. // MARK: -
  445. /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
  446. open class UploadRequest: DataRequest {
  447. // MARK: Helper Types
  448. enum Uploadable: TaskConvertible {
  449. case data(Data, URLRequest)
  450. case file(URL, URLRequest)
  451. case stream(InputStream, URLRequest)
  452. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  453. do {
  454. let task: URLSessionTask
  455. switch self {
  456. case let .data(data, urlRequest):
  457. let urlRequest = try urlRequest.adapt(using: adapter)
  458. task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
  459. case let .file(url, urlRequest):
  460. let urlRequest = try urlRequest.adapt(using: adapter)
  461. task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
  462. case let .stream(_, urlRequest):
  463. let urlRequest = try urlRequest.adapt(using: adapter)
  464. task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
  465. }
  466. return task
  467. } catch {
  468. throw AdaptError(error: error)
  469. }
  470. }
  471. }
  472. // MARK: Properties
  473. /// The request sent or to be sent to the server.
  474. open override var request: URLRequest? {
  475. if let request = super.request { return request }
  476. guard let uploadable = originalTask as? Uploadable else { return nil }
  477. switch uploadable {
  478. case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
  479. return urlRequest
  480. }
  481. }
  482. /// The progress of uploading the payload to the server for the upload request.
  483. open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
  484. var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
  485. // MARK: Upload Progress
  486. /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
  487. /// the server.
  488. ///
  489. /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
  490. /// of data being read from the server.
  491. ///
  492. /// - parameter queue: The dispatch queue to execute the closure on.
  493. /// - parameter closure: The code to be executed periodically as data is sent to the server.
  494. ///
  495. /// - returns: The request.
  496. @discardableResult
  497. open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
  498. uploadDelegate.uploadProgressHandler = (closure, queue)
  499. return self
  500. }
  501. }
  502. // MARK: -
  503. #if !os(watchOS)
  504. /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
  505. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
  506. open class StreamRequest: Request {
  507. enum Streamable: TaskConvertible {
  508. case stream(hostName: String, port: Int)
  509. case netService(NetService)
  510. func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
  511. let task: URLSessionTask
  512. switch self {
  513. case let .stream(hostName, port):
  514. task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
  515. case let .netService(netService):
  516. task = queue.sync { session.streamTask(with: netService) }
  517. }
  518. return task
  519. }
  520. }
  521. }
  522. #endif