SessionDelegate.swift 9.3 KB

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