Validation.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 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[..<(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 that the response has a status code in the specified sequence.
  129. ///
  130. /// If validation fails, subsequent calls to response handlers will have an associated error.
  131. ///
  132. /// - parameter range: The range of acceptable status codes.
  133. ///
  134. /// - returns: The request.
  135. @discardableResult
  136. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  137. return validate { [unowned self] _, response, _ in
  138. return self.validate(statusCode: acceptableStatusCodes, response: response)
  139. }
  140. }
  141. /// Validates that the response has a content type in the specified sequence.
  142. ///
  143. /// If validation fails, subsequent calls to response handlers will have an associated error.
  144. ///
  145. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  146. ///
  147. /// - returns: The request.
  148. @discardableResult
  149. public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
  150. return validate { [unowned self] _, response, data in
  151. return self.validate(contentType: acceptableContentTypes, response: response, data: data)
  152. }
  153. }
  154. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  155. /// type matches any specified in the Accept HTTP header field.
  156. ///
  157. /// If validation fails, subsequent calls to response handlers will have an associated error.
  158. ///
  159. /// - returns: The request.
  160. @discardableResult
  161. public func validate() -> Self {
  162. return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes)
  163. }
  164. }
  165. // MARK: -
  166. extension DownloadRequest {
  167. /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
  168. /// destination URL, and returns whether the request was valid.
  169. public typealias Validation = (
  170. _ request: URLRequest?,
  171. _ response: HTTPURLResponse,
  172. _ temporaryURL: URL?,
  173. _ destinationURL: URL?)
  174. -> ValidationResult
  175. /// Validates that the response has a status code in the specified sequence.
  176. ///
  177. /// If validation fails, subsequent calls to response handlers will have an associated error.
  178. ///
  179. /// - parameter range: The range of acceptable status codes.
  180. ///
  181. /// - returns: The request.
  182. @discardableResult
  183. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  184. return validate { [unowned self] _, response, _, _ in
  185. return self.validate(statusCode: acceptableStatusCodes, response: response)
  186. }
  187. }
  188. /// Validates that the response has a content type in the specified sequence.
  189. ///
  190. /// If validation fails, subsequent calls to response handlers will have an associated error.
  191. ///
  192. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  193. ///
  194. /// - returns: The request.
  195. @discardableResult
  196. public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
  197. return validate { [unowned self] _, response, _, _ in
  198. let fileURL = self.fileURL
  199. guard let validFileURL = fileURL else {
  200. return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
  201. }
  202. do {
  203. let data = try Data(contentsOf: validFileURL)
  204. return self.validate(contentType: acceptableContentTypes, response: response, data: data)
  205. } catch {
  206. return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
  207. }
  208. }
  209. }
  210. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  211. /// type matches any specified in the Accept HTTP header field.
  212. ///
  213. /// If validation fails, subsequent calls to response handlers will have an associated error.
  214. ///
  215. /// - returns: The request.
  216. @discardableResult
  217. public func validate() -> Self {
  218. return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes)
  219. }
  220. }