Validation.swift 11 KB

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