SessionDelegate.swift 8.8 KB

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