Validation.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. //
  2. // Validation.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. extension Request {
  26. // MARK: Helper Types
  27. fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason
  28. /// Used to represent whether a validation succeeded or failed.
  29. public typealias ValidationResult = Result<Void, Error>
  30. fileprivate struct MIMEType {
  31. let type: String
  32. let subtype: String
  33. var isWildcard: Bool { type == "*" && subtype == "*" }
  34. init?(_ string: String) {
  35. let components: [String] = {
  36. let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
  37. let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
  38. return split.components(separatedBy: "/")
  39. }()
  40. if let type = components.first, let subtype = components.last {
  41. self.type = type
  42. self.subtype = subtype
  43. } else {
  44. return nil
  45. }
  46. }
  47. func matches(_ mime: MIMEType) -> Bool {
  48. switch (type, subtype) {
  49. case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
  50. return true
  51. default:
  52. return false
  53. }
  54. }
  55. }
  56. // MARK: Properties
  57. fileprivate var acceptableStatusCodes: Range<Int> { 200..<300 }
  58. fileprivate var acceptableContentTypes: [String] {
  59. if let accept = request?.value(forHTTPHeaderField: "Accept") {
  60. return accept.components(separatedBy: ",")
  61. }
  62. return ["*/*"]
  63. }
  64. // MARK: Status Code
  65. fileprivate func validate<S: Sequence>(statusCode acceptableStatusCodes: S,
  66. response: HTTPURLResponse)
  67. -> ValidationResult
  68. where S.Iterator.Element == Int {
  69. if acceptableStatusCodes.contains(response.statusCode) {
  70. return .success(())
  71. } else {
  72. let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
  73. return .failure(AFError.responseValidationFailed(reason: reason))
  74. }
  75. }
  76. // MARK: Content Type
  77. fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
  78. response: HTTPURLResponse,
  79. data: Data?)
  80. -> ValidationResult
  81. where S.Iterator.Element == String {
  82. guard let data = data, !data.isEmpty else { return .success(()) }
  83. return validate(contentType: acceptableContentTypes, response: response)
  84. }
  85. fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
  86. response: HTTPURLResponse)
  87. -> ValidationResult
  88. where S.Iterator.Element == String {
  89. guard
  90. let responseContentType = response.mimeType,
  91. let responseMIMEType = MIMEType(responseContentType)
  92. else {
  93. for contentType in acceptableContentTypes {
  94. if let mimeType = MIMEType(contentType), mimeType.isWildcard {
  95. return .success(())
  96. }
  97. }
  98. let error: AFError = {
  99. let reason: ErrorReason = .missingContentType(acceptableContentTypes: acceptableContentTypes.sorted())
  100. return AFError.responseValidationFailed(reason: reason)
  101. }()
  102. return .failure(error)
  103. }
  104. for contentType in acceptableContentTypes {
  105. if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
  106. return .success(())
  107. }
  108. }
  109. let error: AFError = {
  110. let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: acceptableContentTypes.sorted(),
  111. responseContentType: responseContentType)
  112. return AFError.responseValidationFailed(reason: reason)
  113. }()
  114. return .failure(error)
  115. }
  116. }
  117. // MARK: -
  118. extension DataRequest {
  119. /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
  120. /// request was valid.
  121. public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
  122. /// Validates that the response has a status code in the specified sequence.
  123. ///
  124. /// If validation fails, subsequent calls to response handlers will have an associated error.
  125. ///
  126. /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
  127. ///
  128. /// - Returns: The instance.
  129. @discardableResult
  130. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  131. validate { [unowned self] _, response, _ in
  132. self.validate(statusCode: acceptableStatusCodes, response: response)
  133. }
  134. }
  135. /// Validates that the response has a content type in the specified sequence.
  136. ///
  137. /// If validation fails, subsequent calls to response handlers will have an associated error.
  138. ///
  139. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  140. ///
  141. /// - returns: The request.
  142. @discardableResult
  143. public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
  144. validate { [unowned self] _, response, data in
  145. self.validate(contentType: acceptableContentTypes(), response: response, data: data)
  146. }
  147. }
  148. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  149. /// type matches any specified in the Accept HTTP header field.
  150. ///
  151. /// If validation fails, subsequent calls to response handlers will have an associated error.
  152. ///
  153. /// - returns: The request.
  154. @discardableResult
  155. public func validate() -> Self {
  156. let contentTypes: () -> [String] = { [unowned self] in
  157. acceptableContentTypes
  158. }
  159. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  160. }
  161. }
  162. extension DataStreamRequest {
  163. /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the
  164. /// request was valid.
  165. public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult
  166. /// Validates that the response has a status code in the specified sequence.
  167. ///
  168. /// If validation fails, subsequent calls to response handlers will have an associated error.
  169. ///
  170. /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
  171. ///
  172. /// - Returns: The instance.
  173. @discardableResult
  174. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  175. validate { [unowned self] _, response in
  176. self.validate(statusCode: acceptableStatusCodes, response: response)
  177. }
  178. }
  179. /// Validates that the response has a content type in the specified sequence.
  180. ///
  181. /// If validation fails, subsequent calls to response handlers will have an associated error.
  182. ///
  183. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  184. ///
  185. /// - returns: The request.
  186. @discardableResult
  187. public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
  188. validate { [unowned self] _, response in
  189. self.validate(contentType: acceptableContentTypes(), response: response)
  190. }
  191. }
  192. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  193. /// type matches any specified in the Accept HTTP header field.
  194. ///
  195. /// If validation fails, subsequent calls to response handlers will have an associated error.
  196. ///
  197. /// - Returns: The instance.
  198. @discardableResult
  199. public func validate() -> Self {
  200. let contentTypes: () -> [String] = { [unowned self] in
  201. acceptableContentTypes
  202. }
  203. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  204. }
  205. }
  206. // MARK: -
  207. extension DownloadRequest {
  208. /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
  209. /// destination URL, and returns whether the request was valid.
  210. public typealias Validation = (_ request: URLRequest?,
  211. _ response: HTTPURLResponse,
  212. _ fileURL: URL?)
  213. -> ValidationResult
  214. /// Validates that the response has a status code in the specified sequence.
  215. ///
  216. /// If validation fails, subsequent calls to response handlers will have an associated error.
  217. ///
  218. /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
  219. ///
  220. /// - Returns: The instance.
  221. @discardableResult
  222. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  223. validate { [unowned self] _, response, _ in
  224. self.validate(statusCode: acceptableStatusCodes, response: response)
  225. }
  226. }
  227. /// Validates that the response has a content type in the specified sequence.
  228. ///
  229. /// If validation fails, subsequent calls to response handlers will have an associated error.
  230. ///
  231. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  232. ///
  233. /// - returns: The request.
  234. @discardableResult
  235. public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
  236. validate { [unowned self] _, response, fileURL in
  237. guard let validFileURL = fileURL else {
  238. return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
  239. }
  240. do {
  241. let data = try Data(contentsOf: validFileURL)
  242. return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
  243. } catch {
  244. return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
  245. }
  246. }
  247. }
  248. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  249. /// type matches any specified in the Accept HTTP header field.
  250. ///
  251. /// If validation fails, subsequent calls to response handlers will have an associated error.
  252. ///
  253. /// - returns: The request.
  254. @discardableResult
  255. public func validate() -> Self {
  256. let contentTypes = { [unowned self] in
  257. acceptableContentTypes
  258. }
  259. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  260. }
  261. }