Validation.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 = AFResult<Void>
  30. fileprivate struct MIMEType {
  31. let type: String
  32. let subtype: String
  33. var isWildcard: Bool { return 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> { return 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>(
  66. statusCode acceptableStatusCodes: S,
  67. response: HTTPURLResponse)
  68. -> ValidationResult
  69. where S.Iterator.Element == Int
  70. {
  71. if acceptableStatusCodes.contains(response.statusCode) {
  72. return .success(Void())
  73. } else {
  74. let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
  75. return .failure(AFError.responseValidationFailed(reason: reason))
  76. }
  77. }
  78. // MARK: Content Type
  79. fileprivate func validate<S: Sequence>(
  80. contentType acceptableContentTypes: S,
  81. response: HTTPURLResponse,
  82. data: Data?)
  83. -> ValidationResult
  84. where S.Iterator.Element == String
  85. {
  86. guard let data = data, data.count > 0 else { return .success(Void()) }
  87. guard
  88. let responseContentType = response.mimeType,
  89. let responseMIMEType = MIMEType(responseContentType)
  90. else {
  91. for contentType in acceptableContentTypes {
  92. if let mimeType = MIMEType(contentType), mimeType.isWildcard {
  93. return .success(Void())
  94. }
  95. }
  96. let error: AFError = {
  97. let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))
  98. return AFError.responseValidationFailed(reason: reason)
  99. }()
  100. return .failure(error)
  101. }
  102. for contentType in acceptableContentTypes {
  103. if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
  104. return .success(Void())
  105. }
  106. }
  107. let error: AFError = {
  108. let reason: ErrorReason = .unacceptableContentType(
  109. acceptableContentTypes: Array(acceptableContentTypes),
  110. responseContentType: responseContentType
  111. )
  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 range: The range of acceptable status codes.
  127. ///
  128. /// - returns: The request.
  129. @discardableResult
  130. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  131. return validate { [unowned self] _, response, _ in
  132. return 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. return validate { [unowned self] _, response, data in
  145. return 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. return self.acceptableContentTypes
  158. }
  159. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  160. }
  161. }
  162. // MARK: -
  163. extension DownloadRequest {
  164. /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
  165. /// destination URL, and returns whether the request was valid.
  166. public typealias Validation = (
  167. _ request: URLRequest?,
  168. _ response: HTTPURLResponse,
  169. _ fileURL: URL?)
  170. -> ValidationResult
  171. /// Validates that the response has a status code in the specified sequence.
  172. ///
  173. /// If validation fails, subsequent calls to response handlers will have an associated error.
  174. ///
  175. /// - parameter range: The range of acceptable status codes.
  176. ///
  177. /// - returns: The request.
  178. @discardableResult
  179. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
  180. return validate { [unowned self] (_, response, _) in
  181. return self.validate(statusCode: acceptableStatusCodes, response: response)
  182. }
  183. }
  184. /// Validates that the response has a content type in the specified sequence.
  185. ///
  186. /// If validation fails, subsequent calls to response handlers will have an associated error.
  187. ///
  188. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  189. ///
  190. /// - returns: The request.
  191. @discardableResult
  192. public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
  193. return validate { [unowned self] (_, response, fileURL) in
  194. guard let validFileURL = fileURL else {
  195. return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
  196. }
  197. do {
  198. let data = try Data(contentsOf: validFileURL)
  199. return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
  200. } catch {
  201. return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
  202. }
  203. }
  204. }
  205. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  206. /// type matches any specified in the Accept HTTP header field.
  207. ///
  208. /// If validation fails, subsequent calls to response handlers will have an associated error.
  209. ///
  210. /// - returns: The request.
  211. @discardableResult
  212. public func validate() -> Self {
  213. let contentTypes = { [unowned self] in
  214. return self.acceptableContentTypes
  215. }
  216. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  217. }
  218. }