SessionDelegate.swift 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. open 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. let onValidStatusCode = Delegate<Int, Bool>()
  44. let onDownloadingFinished = Delegate<(URL, Result<URLResponse, KingfisherError>), Void>()
  45. let onDidDownloadData = Delegate<SessionDataTask, Data?>()
  46. let onReceiveSessionChallenge = Delegate<SessionChallengeFunc, Void>()
  47. let onReceiveSessionTaskChallenge = Delegate<SessionTaskChallengeFunc, Void>()
  48. func add(
  49. _ dataTask: URLSessionDataTask,
  50. url: URL,
  51. callback: SessionDataTask.TaskCallback) -> DownloadTask
  52. {
  53. lock.lock()
  54. defer { lock.unlock() }
  55. // Create a new task if necessary.
  56. let task = SessionDataTask(task: dataTask)
  57. task.onCallbackCancelled.delegate(on: self) { [weak task] (self, value) in
  58. guard let task = task else { return }
  59. let (token, callback) = value
  60. let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token))
  61. task.onTaskDone.call((.failure(error), [callback]))
  62. // No other callbacks waiting, we can clear the task now.
  63. if !task.containsCallbacks {
  64. let dataTask = task.task
  65. self.cancelTask(dataTask)
  66. self.remove(task)
  67. }
  68. }
  69. let token = task.addCallback(callback)
  70. tasks[url] = task
  71. return DownloadTask(sessionTask: task, cancelToken: token)
  72. }
  73. private func cancelTask(_ dataTask: URLSessionDataTask) {
  74. lock.lock()
  75. defer { lock.unlock() }
  76. dataTask.cancel()
  77. }
  78. func append(
  79. _ task: SessionDataTask,
  80. callback: SessionDataTask.TaskCallback) -> DownloadTask
  81. {
  82. let token = task.addCallback(callback)
  83. return DownloadTask(sessionTask: task, cancelToken: token)
  84. }
  85. private func remove(_ task: SessionDataTask) {
  86. lock.lock()
  87. defer { lock.unlock() }
  88. guard let url = task.originalURL else {
  89. return
  90. }
  91. task.removeAllCallbacks()
  92. tasks[url] = nil
  93. }
  94. private func task(for task: URLSessionTask) -> SessionDataTask? {
  95. lock.lock()
  96. defer { lock.unlock() }
  97. guard let url = task.originalRequest?.url else {
  98. return nil
  99. }
  100. guard let sessionTask = tasks[url] else {
  101. return nil
  102. }
  103. guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
  104. return nil
  105. }
  106. return sessionTask
  107. }
  108. func task(for url: URL) -> SessionDataTask? {
  109. lock.lock()
  110. defer { lock.unlock() }
  111. return tasks[url]
  112. }
  113. func cancelAll() {
  114. lock.lock()
  115. let taskValues = tasks.values
  116. lock.unlock()
  117. for task in taskValues {
  118. task.forceCancel()
  119. }
  120. }
  121. func cancel(url: URL) {
  122. lock.lock()
  123. let task = tasks[url]
  124. lock.unlock()
  125. task?.forceCancel()
  126. }
  127. }
  128. extension SessionDelegate: URLSessionDataDelegate {
  129. open func urlSession(
  130. _ session: URLSession,
  131. dataTask: URLSessionDataTask,
  132. didReceive response: URLResponse,
  133. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  134. {
  135. guard let httpResponse = response as? HTTPURLResponse else {
  136. let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response))
  137. onCompleted(task: dataTask, result: .failure(error))
  138. completionHandler(.cancel)
  139. return
  140. }
  141. let httpStatusCode = httpResponse.statusCode
  142. guard onValidStatusCode.call(httpStatusCode) == true else {
  143. let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse))
  144. onCompleted(task: dataTask, result: .failure(error))
  145. completionHandler(.cancel)
  146. return
  147. }
  148. completionHandler(.allow)
  149. }
  150. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  151. guard let task = self.task(for: dataTask) else {
  152. return
  153. }
  154. task.didReceiveData(data)
  155. task.callbacks.forEach { callback in
  156. callback.options.onDataReceived?.forEach { sideEffect in
  157. sideEffect.onDataReceived(session, task: task, data: data)
  158. }
  159. }
  160. }
  161. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  162. guard let sessionTask = self.task(for: task) else { return }
  163. if let url = sessionTask.originalURL {
  164. let result: Result<URLResponse, KingfisherError>
  165. if let error = error {
  166. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  167. } else if let response = task.response {
  168. result = .success(response)
  169. } else {
  170. result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask)))
  171. }
  172. onDownloadingFinished.call((url, result))
  173. }
  174. let result: Result<(Data, URLResponse?), KingfisherError>
  175. if let error = error {
  176. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  177. } else {
  178. if let data = onDidDownloadData.call(sessionTask) {
  179. result = .success((data, task.response))
  180. } else {
  181. result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask)))
  182. }
  183. }
  184. onCompleted(task: task, result: result)
  185. }
  186. open func urlSession(
  187. _ session: URLSession,
  188. didReceive challenge: URLAuthenticationChallenge,
  189. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  190. {
  191. onReceiveSessionChallenge.call((session, challenge, completionHandler))
  192. }
  193. open func urlSession(
  194. _ session: URLSession,
  195. task: URLSessionTask,
  196. didReceive challenge: URLAuthenticationChallenge,
  197. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  198. {
  199. onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler))
  200. }
  201. open func urlSession(
  202. _ session: URLSession,
  203. task: URLSessionTask,
  204. willPerformHTTPRedirection response: HTTPURLResponse,
  205. newRequest request: URLRequest,
  206. completionHandler: @escaping (URLRequest?) -> Void)
  207. {
  208. guard let sessionDataTask = self.task(for: task),
  209. let redirectHandler = Array(sessionDataTask.callbacks).last?.options.redirectHandler else
  210. {
  211. completionHandler(request)
  212. return
  213. }
  214. redirectHandler.handleHTTPRedirection(
  215. for: sessionDataTask,
  216. response: response,
  217. newRequest: request,
  218. completionHandler: completionHandler)
  219. }
  220. private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) {
  221. guard let sessionTask = self.task(for: task) else {
  222. return
  223. }
  224. sessionTask.onTaskDone.call((result, sessionTask.callbacks))
  225. remove(sessionTask)
  226. }
  227. }