Repositorio del curso CCOM4030 el semestre B91 del proyecto Trolley

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. //
  2. // SessionDelegate.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. /// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features.
  26. open class SessionDelegate: NSObject {
  27. private let fileManager: FileManager
  28. weak var stateProvider: SessionStateProvider?
  29. var eventMonitor: EventMonitor?
  30. /// Creates an instance from the given `FileManager`.
  31. ///
  32. /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files.
  33. /// `.default` by default.
  34. public init(fileManager: FileManager = .default) {
  35. self.fileManager = fileManager
  36. }
  37. }
  38. /// Type which provides various `Session` state values.
  39. protocol SessionStateProvider: AnyObject {
  40. var serverTrustManager: ServerTrustManager? { get }
  41. var redirectHandler: RedirectHandler? { get }
  42. var cachedResponseHandler: CachedResponseHandler? { get }
  43. func request(for task: URLSessionTask) -> Request?
  44. func didGatherMetricsForTask(_ task: URLSessionTask)
  45. func didCompleteTask(_ task: URLSessionTask)
  46. func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential?
  47. func cancelRequestsForSessionInvalidation(with error: Error?)
  48. }
  49. // MARK: URLSessionDelegate
  50. extension SessionDelegate: URLSessionDelegate {
  51. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  52. eventMonitor?.urlSession(session, didBecomeInvalidWithError: error)
  53. stateProvider?.cancelRequestsForSessionInvalidation(with: error)
  54. }
  55. }
  56. // MARK: URLSessionTaskDelegate
  57. extension SessionDelegate: URLSessionTaskDelegate {
  58. /// Result of a `URLAuthenticationChallenge` evaluation.
  59. typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?)
  60. open func urlSession(_ session: URLSession,
  61. task: URLSessionTask,
  62. didReceive challenge: URLAuthenticationChallenge,
  63. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  64. eventMonitor?.urlSession(session, task: task, didReceive: challenge)
  65. let evaluation: ChallengeEvaluation
  66. switch challenge.protectionSpace.authenticationMethod {
  67. case NSURLAuthenticationMethodServerTrust:
  68. evaluation = attemptServerTrustAuthentication(with: challenge)
  69. case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate:
  70. evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task)
  71. // case NSURLAuthenticationMethodClientCertificate:
  72. // Alamofire doesn't currently support client certificate validation.
  73. default:
  74. evaluation = (.performDefaultHandling, nil, nil)
  75. }
  76. if let error = evaluation.error {
  77. stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error)
  78. }
  79. completionHandler(evaluation.disposition, evaluation.credential)
  80. }
  81. /// Evaluates the server trust `URLAuthenticationChallenge` received.
  82. ///
  83. /// - Parameter challenge: The `URLAuthenticationChallenge`.
  84. ///
  85. /// - Returns: The `ChallengeEvaluation`.
  86. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation {
  87. let host = challenge.protectionSpace.host
  88. guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
  89. let trust = challenge.protectionSpace.serverTrust
  90. else {
  91. return (.performDefaultHandling, nil, nil)
  92. }
  93. do {
  94. guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else {
  95. return (.performDefaultHandling, nil, nil)
  96. }
  97. try evaluator.evaluate(trust, forHost: host)
  98. return (.useCredential, URLCredential(trust: trust), nil)
  99. } catch {
  100. return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error))))
  101. }
  102. }
  103. /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`.
  104. ///
  105. /// - Parameters:
  106. /// - challenge: The `URLAuthenticationChallenge`.
  107. /// - task: The `URLSessionTask` which received the challenge.
  108. ///
  109. /// - Returns: The `ChallengeEvaluation`.
  110. func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge,
  111. belongingTo task: URLSessionTask) -> ChallengeEvaluation {
  112. guard challenge.previousFailureCount == 0 else {
  113. return (.rejectProtectionSpace, nil, nil)
  114. }
  115. guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else {
  116. return (.performDefaultHandling, nil, nil)
  117. }
  118. return (.useCredential, credential, nil)
  119. }
  120. open func urlSession(_ session: URLSession,
  121. task: URLSessionTask,
  122. didSendBodyData bytesSent: Int64,
  123. totalBytesSent: Int64,
  124. totalBytesExpectedToSend: Int64) {
  125. eventMonitor?.urlSession(session,
  126. task: task,
  127. didSendBodyData: bytesSent,
  128. totalBytesSent: totalBytesSent,
  129. totalBytesExpectedToSend: totalBytesExpectedToSend)
  130. stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent,
  131. totalBytesExpectedToSend: totalBytesExpectedToSend)
  132. }
  133. open func urlSession(_ session: URLSession,
  134. task: URLSessionTask,
  135. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  136. eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task)
  137. guard let request = stateProvider?.request(for: task) as? UploadRequest else {
  138. fatalError("needNewBodyStream for request that isn't UploadRequest.")
  139. }
  140. completionHandler(request.inputStream())
  141. }
  142. open func urlSession(_ session: URLSession,
  143. task: URLSessionTask,
  144. willPerformHTTPRedirection response: HTTPURLResponse,
  145. newRequest request: URLRequest,
  146. completionHandler: @escaping (URLRequest?) -> Void) {
  147. eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request)
  148. if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler {
  149. redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler)
  150. } else {
  151. completionHandler(request)
  152. }
  153. }
  154. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  155. eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics)
  156. stateProvider?.request(for: task)?.didGatherMetrics(metrics)
  157. stateProvider?.didGatherMetricsForTask(task)
  158. }
  159. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  160. eventMonitor?.urlSession(session, task: task, didCompleteWithError: error)
  161. stateProvider?.request(for: task)?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) })
  162. stateProvider?.didCompleteTask(task)
  163. }
  164. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  165. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  166. eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task)
  167. }
  168. }
  169. // MARK: URLSessionDataDelegate
  170. extension SessionDelegate: URLSessionDataDelegate {
  171. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  172. eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data)
  173. guard let request = stateProvider?.request(for: dataTask) as? DataRequest else {
  174. fatalError("dataTask received data for incorrect Request subclass: \(String(describing: stateProvider?.request(for: dataTask)))")
  175. }
  176. request.didReceive(data: data)
  177. }
  178. open func urlSession(_ session: URLSession,
  179. dataTask: URLSessionDataTask,
  180. willCacheResponse proposedResponse: CachedURLResponse,
  181. completionHandler: @escaping (CachedURLResponse?) -> Void) {
  182. eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse)
  183. if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler {
  184. handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler)
  185. } else {
  186. completionHandler(proposedResponse)
  187. }
  188. }
  189. }
  190. // MARK: URLSessionDownloadDelegate
  191. extension SessionDelegate: URLSessionDownloadDelegate {
  192. open func urlSession(_ session: URLSession,
  193. downloadTask: URLSessionDownloadTask,
  194. didResumeAtOffset fileOffset: Int64,
  195. expectedTotalBytes: Int64) {
  196. eventMonitor?.urlSession(session,
  197. downloadTask: downloadTask,
  198. didResumeAtOffset: fileOffset,
  199. expectedTotalBytes: expectedTotalBytes)
  200. guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  201. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  202. }
  203. downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
  204. totalBytesExpectedToWrite: expectedTotalBytes)
  205. }
  206. open func urlSession(_ session: URLSession,
  207. downloadTask: URLSessionDownloadTask,
  208. didWriteData bytesWritten: Int64,
  209. totalBytesWritten: Int64,
  210. totalBytesExpectedToWrite: Int64) {
  211. eventMonitor?.urlSession(session,
  212. downloadTask: downloadTask,
  213. didWriteData: bytesWritten,
  214. totalBytesWritten: totalBytesWritten,
  215. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  216. guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  217. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  218. }
  219. downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
  220. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  221. }
  222. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  223. eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
  224. guard let request = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  225. fatalError("Download finished but either no request found or request wasn't DownloadRequest")
  226. }
  227. guard let response = request.response else {
  228. fatalError("URLSessionDownloadTask finished downloading with no response.")
  229. }
  230. let (destination, options) = (request.destination)(location, response)
  231. eventMonitor?.request(request, didCreateDestinationURL: destination)
  232. do {
  233. if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) {
  234. try fileManager.removeItem(at: destination)
  235. }
  236. if options.contains(.createIntermediateDirectories) {
  237. let directory = destination.deletingLastPathComponent()
  238. try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
  239. }
  240. try fileManager.moveItem(at: location, to: destination)
  241. request.didFinishDownloading(using: downloadTask, with: .success(destination))
  242. } catch {
  243. request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, source: location, destination: destination)))
  244. }
  245. }
  246. }