SessionDelegate.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //
  2. // SessionDelegate.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/11/1.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. // Represents the delegate object of downloader session. It also behave like a task manager for downloading.
  28. @objc(KFSessionDelegate) // Fix for ObjC header name conflicting. https://github.com/onevcat/Kingfisher/issues/1530
  29. class SessionDelegate: NSObject {
  30. typealias SessionChallengeFunc = (
  31. URLSession,
  32. URLAuthenticationChallenge,
  33. (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
  34. )
  35. typealias SessionTaskChallengeFunc = (
  36. URLSession,
  37. URLSessionTask,
  38. URLAuthenticationChallenge,
  39. (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
  40. )
  41. private var tasks: [URL: SessionDataTask] = [:]
  42. private let lock = NSLock()
  43. public var extralHandler: URLSessionDataDelegate?
  44. let onValidStatusCode = Delegate<Int, Bool>()
  45. let onDownloadingFinished = Delegate<(URL, Result<URLResponse, KingfisherError>), Void>()
  46. let onDidDownloadData = Delegate<SessionDataTask, Data?>()
  47. let onReceiveSessionChallenge = Delegate<SessionChallengeFunc, Void>()
  48. let onReceiveSessionTaskChallenge = Delegate<SessionTaskChallengeFunc, Void>()
  49. func add(
  50. _ dataTask: URLSessionDataTask,
  51. url: URL,
  52. callback: SessionDataTask.TaskCallback) -> DownloadTask
  53. {
  54. lock.lock()
  55. defer { lock.unlock() }
  56. // Create a new task if necessary.
  57. let task = SessionDataTask(task: dataTask)
  58. task.onCallbackCancelled.delegate(on: self) { [weak task] (self, value) in
  59. guard let task = task else { return }
  60. let (token, callback) = value
  61. let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token))
  62. task.onTaskDone.call((.failure(error), [callback]))
  63. // No other callbacks waiting, we can clear the task now.
  64. if !task.containsCallbacks {
  65. let dataTask = task.task
  66. self.cancelTask(dataTask)
  67. self.remove(task)
  68. }
  69. }
  70. let token = task.addCallback(callback)
  71. tasks[url] = task
  72. return DownloadTask(sessionTask: task, cancelToken: token)
  73. }
  74. private func cancelTask(_ dataTask: URLSessionDataTask) {
  75. lock.lock()
  76. defer { lock.unlock() }
  77. dataTask.cancel()
  78. }
  79. func append(
  80. _ task: SessionDataTask,
  81. url: URL,
  82. callback: SessionDataTask.TaskCallback) -> DownloadTask
  83. {
  84. let token = task.addCallback(callback)
  85. return DownloadTask(sessionTask: task, cancelToken: token)
  86. }
  87. private func remove(_ task: SessionDataTask) {
  88. lock.lock()
  89. defer { lock.unlock() }
  90. guard let url = task.originalURL else {
  91. return
  92. }
  93. tasks[url] = nil
  94. }
  95. private func task(for task: URLSessionTask) -> SessionDataTask? {
  96. lock.lock()
  97. defer { lock.unlock() }
  98. guard let url = task.originalRequest?.url else {
  99. return nil
  100. }
  101. guard let sessionTask = tasks[url] else {
  102. return nil
  103. }
  104. guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
  105. return nil
  106. }
  107. return sessionTask
  108. }
  109. func task(for url: URL) -> SessionDataTask? {
  110. lock.lock()
  111. defer { lock.unlock() }
  112. return tasks[url]
  113. }
  114. func cancelAll() {
  115. lock.lock()
  116. let taskValues = tasks.values
  117. lock.unlock()
  118. for task in taskValues {
  119. task.forceCancel()
  120. }
  121. }
  122. func cancel(url: URL) {
  123. lock.lock()
  124. let task = tasks[url]
  125. lock.unlock()
  126. task?.forceCancel()
  127. }
  128. }
  129. extension SessionDelegate: URLSessionDataDelegate {
  130. func urlSession(
  131. _ session: URLSession,
  132. dataTask: URLSessionDataTask,
  133. didReceive response: URLResponse,
  134. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  135. {
  136. guard let httpResponse = response as? HTTPURLResponse else {
  137. let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response))
  138. onCompleted(task: dataTask, result: .failure(error))
  139. completionHandler(.cancel)
  140. return
  141. }
  142. let httpStatusCode = httpResponse.statusCode
  143. guard onValidStatusCode.call(httpStatusCode) == true else {
  144. let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse))
  145. onCompleted(task: dataTask, result: .failure(error))
  146. completionHandler(.cancel)
  147. return
  148. }
  149. completionHandler(.allow)
  150. }
  151. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  152. guard let task = self.task(for: dataTask) else {
  153. return
  154. }
  155. task.didReceiveData(data)
  156. task.callbacks.forEach { callback in
  157. callback.options.onDataReceived?.forEach { sideEffect in
  158. sideEffect.onDataReceived(session, task: task, data: data)
  159. }
  160. }
  161. }
  162. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  163. guard let sessionTask = self.task(for: task) else { return }
  164. if let url = sessionTask.originalURL {
  165. let result: Result<URLResponse, KingfisherError>
  166. if let error = error {
  167. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  168. } else if let response = task.response {
  169. result = .success(response)
  170. } else {
  171. result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask)))
  172. }
  173. onDownloadingFinished.call((url, result))
  174. }
  175. let result: Result<(Data, URLResponse?), KingfisherError>
  176. if let error = error {
  177. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  178. } else {
  179. if let data = onDidDownloadData.call(sessionTask) {
  180. result = .success((data, task.response))
  181. } else {
  182. result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask)))
  183. }
  184. }
  185. onCompleted(task: task, result: result)
  186. }
  187. func urlSession(
  188. _ session: URLSession,
  189. didReceive challenge: URLAuthenticationChallenge,
  190. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  191. {
  192. onReceiveSessionChallenge.call((session, challenge, completionHandler))
  193. }
  194. func urlSession(
  195. _ session: URLSession,
  196. task: URLSessionTask,
  197. didReceive challenge: URLAuthenticationChallenge,
  198. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  199. {
  200. onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler))
  201. }
  202. func urlSession(
  203. _ session: URLSession,
  204. task: URLSessionTask,
  205. willPerformHTTPRedirection response: HTTPURLResponse,
  206. newRequest request: URLRequest,
  207. completionHandler: @escaping (URLRequest?) -> Void)
  208. {
  209. guard let sessionDataTask = self.task(for: task),
  210. let redirectHandler = Array(sessionDataTask.callbacks).last?.options.redirectHandler else
  211. {
  212. completionHandler(request)
  213. return
  214. }
  215. redirectHandler.handleHTTPRedirection(
  216. for: sessionDataTask,
  217. response: response,
  218. newRequest: request,
  219. completionHandler: completionHandler)
  220. }
  221. private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) {
  222. guard let sessionTask = self.task(for: task) else {
  223. return
  224. }
  225. remove(sessionTask)
  226. sessionTask.onTaskDone.call((result, sessionTask.callbacks))
  227. }
  228. // MARK: - ExtralHandler
  229. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  230. extralHandler?.urlSessionDidFinishEvents?(forBackgroundURLSession: session)
  231. }
  232. func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  233. extralHandler?.urlSession?(session, didBecomeInvalidWithError: error)
  234. }
  235. @available(iOS 11.0, OSX 10.13, tvOS 11.0, watchOS 4.0, *)
  236. func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  237. extralHandler?.urlSession?(session, taskIsWaitingForConnectivity: task)
  238. }
  239. func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  240. extralHandler?.urlSession?(session, task: task, didFinishCollecting: metrics)
  241. }
  242. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome streamTask: URLSessionStreamTask) {
  243. extralHandler?.urlSession?(session, dataTask: dataTask, didBecome: streamTask)
  244. }
  245. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) {
  246. extralHandler?.urlSession?(session, dataTask: dataTask, didBecome: downloadTask)
  247. }
  248. func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  249. extralHandler?.urlSession?(session, task: task, needNewBodyStream: completionHandler)
  250. }
  251. func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  252. extralHandler?.urlSession?(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
  253. }
  254. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
  255. extralHandler?.urlSession?(session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler)
  256. }
  257. @available(iOS 11.0, OSX 10.13, tvOS 11.0, watchOS 4.0, *)
  258. func urlSession(_ session: URLSession, task: URLSessionTask, willBeginDelayedRequest request: URLRequest, completionHandler: @escaping (URLSession.DelayedRequestDisposition, URLRequest?) -> Void) {
  259. extralHandler?.urlSession?(session, task: task, willBeginDelayedRequest: request, completionHandler: completionHandler)
  260. }
  261. }