SessionDelegate.swift 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. // Try to reuse existing task.
  55. if let task = tasks[url] {
  56. let token = task.addCallback(callback)
  57. return DownloadTask(sessionTask: task, cancelToken: token)
  58. } else {
  59. // Create a new task if necessary.
  60. let task = SessionDataTask(task: dataTask)
  61. task.onCallbackCancelled.delegate(on: self) { [unowned task] (self, value) in
  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.remove(dataTask, acquireLock: true)
  69. }
  70. }
  71. let token = task.addCallback(callback)
  72. tasks[url] = task
  73. return DownloadTask(sessionTask: task, cancelToken: token)
  74. }
  75. }
  76. func remove(_ task: URLSessionTask, acquireLock: Bool) {
  77. guard let url = task.originalRequest?.url else {
  78. return
  79. }
  80. if acquireLock { lock.lock() }
  81. tasks[url] = nil
  82. if acquireLock { lock.unlock() }
  83. }
  84. func task(for task: URLSessionTask) -> SessionDataTask? {
  85. guard let url = task.originalRequest?.url else {
  86. return nil
  87. }
  88. guard let sessionTask = tasks[url] else {
  89. return nil
  90. }
  91. guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
  92. return nil
  93. }
  94. return sessionTask
  95. }
  96. func cancelAll() {
  97. for task in tasks.values {
  98. task.forceCancel()
  99. }
  100. }
  101. func cancel(url: URL) {
  102. let task = tasks[url]
  103. task?.forceCancel()
  104. }
  105. }
  106. extension SessionDelegate: URLSessionDataDelegate {
  107. func urlSession(
  108. _ session: URLSession,
  109. dataTask: URLSessionDataTask,
  110. didReceive response: URLResponse,
  111. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  112. {
  113. lock.lock()
  114. defer { lock.unlock() }
  115. guard let httpResponse = response as? HTTPURLResponse else {
  116. let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response))
  117. onCompleted(task: dataTask, result: .failure(error))
  118. completionHandler(.cancel)
  119. return
  120. }
  121. let httpStatusCode = httpResponse.statusCode
  122. guard onValidStatusCode.call(httpStatusCode) == true else {
  123. let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse))
  124. onCompleted(task: dataTask, result: .failure(error))
  125. completionHandler(.cancel)
  126. return
  127. }
  128. completionHandler(.allow)
  129. }
  130. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  131. lock.lock()
  132. defer { lock.unlock() }
  133. guard let task = self.task(for: dataTask) else {
  134. return
  135. }
  136. task.didReceiveData(data)
  137. if let expectedContentLength = dataTask.response?.expectedContentLength, expectedContentLength != -1 {
  138. DispatchQueue.main.async {
  139. task.callbacks.forEach { callback in
  140. callback.onProgress?.call((Int64(task.mutableData.count), expectedContentLength))
  141. }
  142. }
  143. }
  144. }
  145. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  146. lock.lock()
  147. defer { lock.unlock() }
  148. guard let sessionTask = self.task(for: task) else { return }
  149. if let url = task.originalRequest?.url {
  150. let result: Result<URLResponse, KingfisherError>
  151. if let error = error {
  152. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  153. } else if let response = task.response {
  154. result = .success(response)
  155. } else {
  156. result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask)))
  157. }
  158. onDownloadingFinished.call((url, result))
  159. }
  160. let result: Result<(Data, URLResponse?), KingfisherError>
  161. if let error = error {
  162. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  163. } else {
  164. if let data = onDidDownloadData.call(sessionTask), let finalData = data {
  165. result = .success((finalData, task.response))
  166. } else {
  167. result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask)))
  168. }
  169. }
  170. onCompleted(task: task, result: result)
  171. }
  172. func urlSession(
  173. _ session: URLSession,
  174. didReceive challenge: URLAuthenticationChallenge,
  175. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  176. {
  177. onReceiveSessionChallenge.call((session, challenge, completionHandler))
  178. }
  179. func urlSession(
  180. _ session: URLSession,
  181. task: URLSessionTask,
  182. didReceive challenge: URLAuthenticationChallenge,
  183. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  184. {
  185. onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler))
  186. }
  187. private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) {
  188. guard let sessionTask = self.task(for: task) else {
  189. return
  190. }
  191. // The lock should be already acquired in the session delege queue
  192. // by the caller `urlSession(_:task:didCompleteWithError:)`.
  193. remove(task, acquireLock: false)
  194. sessionTask.onTaskDone.call((result, Array(sessionTask.callbacks)))
  195. }
  196. }