SessionDelegate.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //
  2. // SessionDelegate.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/11/1.
  6. //
  7. // Copyright (c) 2018年 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) { [unowned task] (self, value) in
  57. let (token, callback) = value
  58. let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token))
  59. task.onTaskDone.call((.failure(error), [callback]))
  60. // No other callbacks waiting, we can clear the task now.
  61. if !task.containsCallbacks {
  62. let dataTask = task.task
  63. self.remove(dataTask, acquireLock: true)
  64. }
  65. }
  66. let token = task.addCallback(callback)
  67. tasks[url] = task
  68. return DownloadTask(sessionTask: task, cancelToken: token)
  69. }
  70. func append(
  71. _ task: SessionDataTask,
  72. url: URL,
  73. callback: SessionDataTask.TaskCallback) -> DownloadTask
  74. {
  75. lock.lock()
  76. defer { lock.unlock() }
  77. let token = task.addCallback(callback)
  78. return DownloadTask(sessionTask: task, cancelToken: token)
  79. }
  80. func remove(_ task: URLSessionTask, acquireLock: Bool) {
  81. guard let url = task.originalRequest?.url else {
  82. return
  83. }
  84. if acquireLock { lock.lock() }
  85. tasks[url] = nil
  86. if acquireLock { lock.unlock() }
  87. }
  88. func task(for task: URLSessionTask) -> SessionDataTask? {
  89. guard let url = task.originalRequest?.url else {
  90. return nil
  91. }
  92. guard let sessionTask = tasks[url] else {
  93. return nil
  94. }
  95. guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
  96. return nil
  97. }
  98. return sessionTask
  99. }
  100. func task(for url: URL) -> SessionDataTask? {
  101. return tasks[url]
  102. }
  103. func cancelAll() {
  104. for task in tasks.values {
  105. task.forceCancel()
  106. }
  107. }
  108. func cancel(url: URL) {
  109. let task = tasks[url]
  110. task?.forceCancel()
  111. }
  112. }
  113. extension SessionDelegate: URLSessionDataDelegate {
  114. func urlSession(
  115. _ session: URLSession,
  116. dataTask: URLSessionDataTask,
  117. didReceive response: URLResponse,
  118. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  119. {
  120. lock.lock()
  121. defer { lock.unlock() }
  122. guard let httpResponse = response as? HTTPURLResponse else {
  123. let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response))
  124. onCompleted(task: dataTask, result: .failure(error))
  125. completionHandler(.cancel)
  126. return
  127. }
  128. let httpStatusCode = httpResponse.statusCode
  129. guard onValidStatusCode.call(httpStatusCode) == true else {
  130. let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse))
  131. onCompleted(task: dataTask, result: .failure(error))
  132. completionHandler(.cancel)
  133. return
  134. }
  135. completionHandler(.allow)
  136. }
  137. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  138. lock.lock()
  139. defer { lock.unlock() }
  140. guard let task = self.task(for: dataTask) else {
  141. return
  142. }
  143. task.didReceiveData(data)
  144. if let expectedContentLength = dataTask.response?.expectedContentLength, expectedContentLength != -1 {
  145. DispatchQueue.main.async {
  146. task.callbacks.forEach { callback in
  147. callback.onProgress?.call((Int64(task.mutableData.count), expectedContentLength))
  148. }
  149. }
  150. }
  151. }
  152. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  153. lock.lock()
  154. defer { lock.unlock() }
  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(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void)
  195. {
  196. guard let url = response.url,
  197. let sessionDataTask = self.task(for: url),
  198. let options = Array(sessionDataTask.callbacks).last?.options else {
  199. completionHandler(request)
  200. return
  201. }
  202. options.redirectHandler.handleHTTPRedirection(for: sessionDataTask, response: response, newRequest: request, completionHandler: completionHandler)
  203. }
  204. private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) {
  205. guard let sessionTask = self.task(for: task) else {
  206. return
  207. }
  208. // The lock should be already acquired in the session delegate queue
  209. // by the caller `urlSession(_:task:didCompleteWithError:)`.
  210. remove(task, acquireLock: false)
  211. sessionTask.onTaskDone.call((result, Array(sessionTask.callbacks)))
  212. }
  213. }