SessionDelegate.swift 8.3 KB

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