You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

251 lines
8.7 KiB

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