SessionDelegate.swift 8.0 KB

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