2
0

SessionDelegate.swift 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. url: URL,
  81. callback: SessionDataTask.TaskCallback) -> DownloadTask
  82. {
  83. let token = task.addCallback(callback)
  84. return DownloadTask(sessionTask: task, cancelToken: token)
  85. }
  86. private func remove(_ task: SessionDataTask) {
  87. lock.lock()
  88. defer { lock.unlock() }
  89. guard let url = task.originalURL else {
  90. return
  91. }
  92. task.removeAllCallbacks()
  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. open 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. open 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. open 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. open 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. open 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. open 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. sessionTask.onTaskDone.call((result, sessionTask.callbacks))
  226. remove(sessionTask)
  227. }
  228. }