Validation.swift 9.7 KB

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