SessionDelegate.swift 8.8 KB

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