Validation.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. {
  70. if acceptableStatusCodes.contains(response.statusCode) {
  71. return .success(())
  72. } else {
  73. let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
  74. return .failure(AFError.responseValidationFailed(reason: reason))
  75. }
  76. }
  77. // MARK: Content Type
  78. fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
  79. response: HTTPURLResponse,
  80. data: Data?)
  81. -> ValidationResult
  82. where S.Iterator.Element == String
  83. {
  84. guard let data = data, !data.isEmpty else { return .success(()) }
  85. return validate(contentType: acceptableContentTypes, response: response)
  86. }
  87. fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
  88. response: HTTPURLResponse)
  89. -> ValidationResult
  90. where S.Iterator.Element == String
  91. {
  92. guard
  93. let responseContentType = response.mimeType,
  94. let responseMIMEType = MIMEType(responseContentType)
  95. else {
  96. for contentType in acceptableContentTypes {
  97. if let mimeType = MIMEType(contentType), mimeType.isWildcard {
  98. return .success(())
  99. }
  100. }
  101. let error: AFError = {
  102. let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))
  103. return AFError.responseValidationFailed(reason: reason)
  104. }()
  105. return .failure(error)
  106. }
  107. for contentType in acceptableContentTypes {
  108. if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
  109. return .success(())
  110. }
  111. }
  112. let error: AFError = {
  113. let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes),
  114. responseContentType: responseContentType)
  115. return AFError.responseValidationFailed(reason: reason)
  116. }()
  117. return .failure(error)
  118. }
  119. }
  120. // MARK: -
  121. public extension DataRequest {
  122. /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
  123. /// request was valid.
  124. typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
  125. /// Validates that the response has a status code in the specified sequence.
  126. ///
  127. /// If validation fails, subsequent calls to response handlers will have an associated error.
  128. ///
  129. /// - Parameter statusCode: `Sequence` of acceptable response status codes.
  130. ///
  131. /// - Returns: The instance.
  132. @discardableResult
  133. func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  134. validate { [unowned self] _, response, _ in
  135. self.validate(statusCode: acceptableStatusCodes, response: response)
  136. }
  137. }
  138. /// Validates that the response has a content type in the specified sequence.
  139. ///
  140. /// If validation fails, subsequent calls to response handlers will have an associated error.
  141. ///
  142. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  143. ///
  144. /// - returns: The request.
  145. @discardableResult
  146. func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
  147. validate { [unowned self] _, response, data in
  148. self.validate(contentType: acceptableContentTypes(), response: response, data: data)
  149. }
  150. }
  151. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  152. /// type matches any specified in the Accept HTTP header field.
  153. ///
  154. /// If validation fails, subsequent calls to response handlers will have an associated error.
  155. ///
  156. /// - returns: The request.
  157. @discardableResult
  158. func validate() -> Self {
  159. let contentTypes: () -> [String] = { [unowned self] in
  160. self.acceptableContentTypes
  161. }
  162. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  163. }
  164. }
  165. public extension DataStreamRequest {
  166. /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the
  167. /// request was valid.
  168. typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult
  169. /// Validates that the response has a status code in the specified sequence.
  170. ///
  171. /// If validation fails, subsequent calls to response handlers will have an associated error.
  172. ///
  173. /// - Parameter statusCode: `Sequence` of acceptable response status codes.
  174. ///
  175. /// - Returns: The instance.
  176. @discardableResult
  177. func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  178. validate { [unowned self] _, response in
  179. self.validate(statusCode: acceptableStatusCodes, response: response)
  180. }
  181. }
  182. /// Validates that the response has a content type in the specified sequence.
  183. ///
  184. /// If validation fails, subsequent calls to response handlers will have an associated error.
  185. ///
  186. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  187. ///
  188. /// - returns: The request.
  189. @discardableResult
  190. func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
  191. validate { [unowned self] _, response in
  192. self.validate(contentType: acceptableContentTypes(), response: response)
  193. }
  194. }
  195. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  196. /// type matches any specified in the Accept HTTP header field.
  197. ///
  198. /// If validation fails, subsequent calls to response handlers will have an associated error.
  199. ///
  200. /// - Returns: The instance.
  201. @discardableResult
  202. func validate() -> Self {
  203. let contentTypes: () -> [String] = { [unowned self] in
  204. self.acceptableContentTypes
  205. }
  206. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  207. }
  208. }
  209. // MARK: -
  210. public extension DownloadRequest {
  211. /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
  212. /// destination URL, and returns whether the request was valid.
  213. typealias Validation = (_ request: URLRequest?,
  214. _ response: HTTPURLResponse,
  215. _ fileURL: URL?)
  216. -> ValidationResult
  217. /// Validates that the response has a status code in the specified sequence.
  218. ///
  219. /// If validation fails, subsequent calls to response handlers will have an associated error.
  220. ///
  221. /// - Parameter statusCode: `Sequence` of acceptable response status codes.
  222. ///
  223. /// - Returns: The instance.
  224. @discardableResult
  225. func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  226. validate { [unowned self] _, response, _ in
  227. self.validate(statusCode: acceptableStatusCodes, response: response)
  228. }
  229. }
  230. /// Validates that the response has a content type in the specified sequence.
  231. ///
  232. /// If validation fails, subsequent calls to response handlers will have an associated error.
  233. ///
  234. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  235. ///
  236. /// - returns: The request.
  237. @discardableResult
  238. func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
  239. validate { [unowned self] _, response, fileURL in
  240. guard let validFileURL = fileURL else {
  241. return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
  242. }
  243. do {
  244. let data = try Data(contentsOf: validFileURL)
  245. return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
  246. } catch {
  247. return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
  248. }
  249. }
  250. }
  251. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  252. /// type matches any specified in the Accept HTTP header field.
  253. ///
  254. /// If validation fails, subsequent calls to response handlers will have an associated error.
  255. ///
  256. /// - returns: The request.
  257. @discardableResult
  258. func validate() -> Self {
  259. let contentTypes = { [unowned self] in
  260. self.acceptableContentTypes
  261. }
  262. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  263. }
  264. }