Validation.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //
  2. // Validation.swift
  3. //
  4. // Copyright (c) 2014-2016 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.ValidationFailureReason
  28. /// Used to represent whether validation was successful or encountered an error resulting in a failure.
  29. ///
  30. /// - success: The validation was successful.
  31. /// - failure: The validation failed encountering the provided error.
  32. public enum ValidationResult {
  33. case success
  34. case failure(Error)
  35. }
  36. fileprivate struct MIMEType {
  37. let type: String
  38. let subtype: String
  39. init?(_ string: String) {
  40. let components: [String] = {
  41. let stripped = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  42. let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
  43. return split.components(separatedBy: "/")
  44. }()
  45. if let type = components.first, let subtype = components.last {
  46. self.type = type
  47. self.subtype = subtype
  48. } else {
  49. return nil
  50. }
  51. }
  52. func matches(_ mime: MIMEType) -> Bool {
  53. switch (type, subtype) {
  54. case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
  55. return true
  56. default:
  57. return false
  58. }
  59. }
  60. }
  61. // MARK: Properties
  62. fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) }
  63. fileprivate var acceptableContentTypes: [String] {
  64. if let accept = request?.value(forHTTPHeaderField: "Accept") {
  65. return accept.components(separatedBy: ",")
  66. }
  67. return ["*/*"]
  68. }
  69. // MARK: Status Code
  70. fileprivate func validate<S: Sequence>(
  71. statusCode acceptableStatusCodes: S,
  72. response: HTTPURLResponse)
  73. -> ValidationResult
  74. where S.Iterator.Element == Int
  75. {
  76. if acceptableStatusCodes.contains(response.statusCode) {
  77. return .success
  78. } else {
  79. let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
  80. return .failure(AFError.responseValidationFailed(reason: reason))
  81. }
  82. }
  83. // MARK: Content Type
  84. fileprivate func validate<S: Sequence>(
  85. contentType acceptableContentTypes: S,
  86. response: HTTPURLResponse,
  87. data: Data?)
  88. -> ValidationResult
  89. where S.Iterator.Element == String
  90. {
  91. guard let data = data, data.count > 0 else { return .success }
  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.type == "*" && mimeType.subtype == "*" {
  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(
  114. acceptableContentTypes: Array(acceptableContentTypes),
  115. responseContentType: responseContentType
  116. )
  117. return AFError.responseValidationFailed(reason: reason)
  118. }()
  119. return .failure(error)
  120. }
  121. }
  122. // MARK: -
  123. extension DataRequest {
  124. /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
  125. /// request was valid.
  126. public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
  127. /// Validates the request, using the specified closure.
  128. ///
  129. /// If validation fails, subsequent calls to response handlers will have an associated error.
  130. ///
  131. /// - parameter validation: A closure to validate the request.
  132. ///
  133. /// - returns: The request.
  134. @discardableResult
  135. public func validate(_ validation: Validation) -> Self {
  136. let validationExecution: () -> Void = {
  137. if
  138. let response = self.response,
  139. self.delegate.error == nil,
  140. case let .failure(error) = validation(self.request, response, self.delegate.data)
  141. {
  142. self.delegate.error = error
  143. }
  144. }
  145. validations.append(validationExecution)
  146. return self
  147. }
  148. /// Validates that the response has a status code in the specified sequence.
  149. ///
  150. /// If validation fails, subsequent calls to response handlers will have an associated error.
  151. ///
  152. /// - parameter range: The range of acceptable status codes.
  153. ///
  154. /// - returns: The request.
  155. @discardableResult
  156. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  157. return validate { _, response, _ in
  158. return self.validate(statusCode: acceptableStatusCodes, response: response)
  159. }
  160. }
  161. /// Validates that the response has a content type in the specified sequence.
  162. ///
  163. /// If validation fails, subsequent calls to response handlers will have an associated error.
  164. ///
  165. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  166. ///
  167. /// - returns: The request.
  168. @discardableResult
  169. public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
  170. return validate { _, response, data in
  171. return self.validate(contentType: acceptableContentTypes, response: response, data: data)
  172. }
  173. }
  174. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  175. /// type matches any specified in the Accept HTTP header field.
  176. ///
  177. /// If validation fails, subsequent calls to response handlers will have an associated error.
  178. ///
  179. /// - returns: The request.
  180. @discardableResult
  181. public func validate() -> Self {
  182. return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes)
  183. }
  184. }
  185. // MARK: -
  186. extension DownloadRequest {
  187. /// A closure used to validate a request that takes a URL request, a URL response and destination URL, and returns
  188. /// whether the request was valid.
  189. public typealias Validation = (URLRequest?, HTTPURLResponse, URL?) -> ValidationResult
  190. /// Validates the request, using the specified closure.
  191. ///
  192. /// If validation fails, subsequent calls to response handlers will have an associated error.
  193. ///
  194. /// - parameter validation: A closure to validate the request.
  195. ///
  196. /// - returns: The request.
  197. @discardableResult
  198. public func validate(_ validation: Validation) -> Self {
  199. let validationExecution: () -> Void = {
  200. if
  201. let response = self.response,
  202. self.delegate.error == nil,
  203. case let .failure(error) = validation(self.request, response, self.downloadDelegate.destinationURL)
  204. {
  205. self.delegate.error = error
  206. }
  207. }
  208. validations.append(validationExecution)
  209. return self
  210. }
  211. /// Validates that the response has a status code in the specified sequence.
  212. ///
  213. /// If validation fails, subsequent calls to response handlers will have an associated error.
  214. ///
  215. /// - parameter range: The range of acceptable status codes.
  216. ///
  217. /// - returns: The request.
  218. @discardableResult
  219. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  220. return validate { _, response, _ in
  221. return self.validate(statusCode: acceptableStatusCodes, response: response)
  222. }
  223. }
  224. /// Validates that the response has a content type in the specified sequence.
  225. ///
  226. /// If validation fails, subsequent calls to response handlers will have an associated error.
  227. ///
  228. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  229. ///
  230. /// - returns: The request.
  231. @discardableResult
  232. public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
  233. return validate { _, response, fileURL in
  234. guard let fileURL = fileURL else {
  235. return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
  236. }
  237. do {
  238. let data = try Data(contentsOf: fileURL)
  239. return self.validate(contentType: acceptableContentTypes, response: response, data: data)
  240. } catch {
  241. return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: fileURL)))
  242. }
  243. }
  244. }
  245. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  246. /// type matches any specified in the Accept HTTP header field.
  247. ///
  248. /// If validation fails, subsequent calls to response handlers will have an associated error.
  249. ///
  250. /// - returns: The request.
  251. @discardableResult
  252. public func validate() -> Self {
  253. return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes)
  254. }
  255. }