You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

391 lines
13 KiB

2 years ago
  1. =begin
  2. #Seaweedfs Master Server API
  3. #The Seaweedfs Master Server API allows you to store blobs
  4. The version of the OpenAPI document: 3.43.0
  5. Generated by: https://openapi-generator.tech
  6. OpenAPI Generator version: 6.4.0
  7. =end
  8. require 'date'
  9. require 'json'
  10. require 'logger'
  11. require 'tempfile'
  12. require 'time'
  13. require 'typhoeus'
  14. module OpenapiClient
  15. class ApiClient
  16. # The Configuration object holding settings to be used in the API client.
  17. attr_accessor :config
  18. # Defines the headers to be used in HTTP requests of all API calls by default.
  19. #
  20. # @return [Hash]
  21. attr_accessor :default_headers
  22. # Initializes the ApiClient
  23. # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
  24. def initialize(config = Configuration.default)
  25. @config = config
  26. @user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
  27. @default_headers = {
  28. 'Content-Type' => 'application/json',
  29. 'User-Agent' => @user_agent
  30. }
  31. end
  32. def self.default
  33. @@default ||= ApiClient.new
  34. end
  35. # Call an API with given options.
  36. #
  37. # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
  38. # the data deserialized from response body (could be nil), response status code and response headers.
  39. def call_api(http_method, path, opts = {})
  40. request = build_request(http_method, path, opts)
  41. response = request.run
  42. if @config.debugging
  43. @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
  44. end
  45. unless response.success?
  46. if response.timed_out?
  47. fail ApiError.new('Connection timed out')
  48. elsif response.code == 0
  49. # Errors from libcurl will be made visible here
  50. fail ApiError.new(:code => 0,
  51. :message => response.return_message)
  52. else
  53. fail ApiError.new(:code => response.code,
  54. :response_headers => response.headers,
  55. :response_body => response.body),
  56. response.status_message
  57. end
  58. end
  59. if opts[:return_type]
  60. data = deserialize(response, opts[:return_type])
  61. else
  62. data = nil
  63. end
  64. return data, response.code, response.headers
  65. end
  66. # Builds the HTTP request
  67. #
  68. # @param [String] http_method HTTP method/verb (e.g. POST)
  69. # @param [String] path URL path (e.g. /account/new)
  70. # @option opts [Hash] :header_params Header parameters
  71. # @option opts [Hash] :query_params Query parameters
  72. # @option opts [Hash] :form_params Query parameters
  73. # @option opts [Object] :body HTTP body (JSON/XML)
  74. # @return [Typhoeus::Request] A Typhoeus Request
  75. def build_request(http_method, path, opts = {})
  76. url = build_request_url(path, opts)
  77. http_method = http_method.to_sym.downcase
  78. header_params = @default_headers.merge(opts[:header_params] || {})
  79. query_params = opts[:query_params] || {}
  80. form_params = opts[:form_params] || {}
  81. follow_location = opts[:follow_location] || true
  82. # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
  83. _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
  84. req_opts = {
  85. :method => http_method,
  86. :headers => header_params,
  87. :params => query_params,
  88. :params_encoding => @config.params_encoding,
  89. :timeout => @config.timeout,
  90. :ssl_verifypeer => @config.verify_ssl,
  91. :ssl_verifyhost => _verify_ssl_host,
  92. :sslcert => @config.cert_file,
  93. :sslkey => @config.key_file,
  94. :verbose => @config.debugging,
  95. :followlocation => follow_location
  96. }
  97. # set custom cert, if provided
  98. req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
  99. if [:post, :patch, :put, :delete].include?(http_method)
  100. req_body = build_request_body(header_params, form_params, opts[:body])
  101. req_opts.update :body => req_body
  102. if @config.debugging
  103. @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
  104. end
  105. end
  106. request = Typhoeus::Request.new(url, req_opts)
  107. download_file(request) if opts[:return_type] == 'File'
  108. request
  109. end
  110. # Builds the HTTP request body
  111. #
  112. # @param [Hash] header_params Header parameters
  113. # @param [Hash] form_params Query parameters
  114. # @param [Object] body HTTP body (JSON/XML)
  115. # @return [String] HTTP body data in the form of string
  116. def build_request_body(header_params, form_params, body)
  117. # http form
  118. if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
  119. header_params['Content-Type'] == 'multipart/form-data'
  120. data = {}
  121. form_params.each do |key, value|
  122. case value
  123. when ::File, ::Array, nil
  124. # let typhoeus handle File, Array and nil parameters
  125. data[key] = value
  126. else
  127. data[key] = value.to_s
  128. end
  129. end
  130. elsif body
  131. data = body.is_a?(String) ? body : body.to_json
  132. else
  133. data = nil
  134. end
  135. data
  136. end
  137. # Save response body into a file in (the defined) temporary folder, using the filename
  138. # from the "Content-Disposition" header if provided, otherwise a random filename.
  139. # The response body is written to the file in chunks in order to handle files which
  140. # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
  141. # process can use.
  142. #
  143. # @see Configuration#temp_folder_path
  144. def download_file(request)
  145. tempfile = nil
  146. encoding = nil
  147. request.on_headers do |response|
  148. content_disposition = response.headers['Content-Disposition']
  149. if content_disposition && content_disposition =~ /filename=/i
  150. filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
  151. prefix = sanitize_filename(filename)
  152. else
  153. prefix = 'download-'
  154. end
  155. prefix = prefix + '-' unless prefix.end_with?('-')
  156. encoding = response.body.encoding
  157. tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
  158. @tempfile = tempfile
  159. end
  160. request.on_body do |chunk|
  161. chunk.force_encoding(encoding)
  162. tempfile.write(chunk)
  163. end
  164. request.on_complete do |response|
  165. if tempfile
  166. tempfile.close
  167. @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
  168. "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
  169. "will be deleted automatically with GC. It's also recommended to delete the temp file "\
  170. "explicitly with `tempfile.delete`"
  171. end
  172. end
  173. end
  174. # Check if the given MIME is a JSON MIME.
  175. # JSON MIME examples:
  176. # application/json
  177. # application/json; charset=UTF8
  178. # APPLICATION/JSON
  179. # */*
  180. # @param [String] mime MIME
  181. # @return [Boolean] True if the MIME is application/json
  182. def json_mime?(mime)
  183. (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
  184. end
  185. # Deserialize the response to the given return type.
  186. #
  187. # @param [Response] response HTTP response
  188. # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
  189. def deserialize(response, return_type)
  190. body = response.body
  191. # handle file downloading - return the File instance processed in request callbacks
  192. # note that response body is empty when the file is written in chunks in request on_body callback
  193. return @tempfile if return_type == 'File'
  194. return nil if body.nil? || body.empty?
  195. # return response body directly for String return type
  196. return body if return_type == 'String'
  197. # ensuring a default content type
  198. content_type = response.headers['Content-Type'] || 'application/json'
  199. fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
  200. begin
  201. data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
  202. rescue JSON::ParserError => e
  203. if %w(String Date Time).include?(return_type)
  204. data = body
  205. else
  206. raise e
  207. end
  208. end
  209. convert_to_type data, return_type
  210. end
  211. # Convert data to the given return type.
  212. # @param [Object] data Data to be converted
  213. # @param [String] return_type Return type
  214. # @return [Mixed] Data in a particular type
  215. def convert_to_type(data, return_type)
  216. return nil if data.nil?
  217. case return_type
  218. when 'String'
  219. data.to_s
  220. when 'Integer'
  221. data.to_i
  222. when 'Float'
  223. data.to_f
  224. when 'Boolean'
  225. data == true
  226. when 'Time'
  227. # parse date time (expecting ISO 8601 format)
  228. Time.parse data
  229. when 'Date'
  230. # parse date time (expecting ISO 8601 format)
  231. Date.parse data
  232. when 'Object'
  233. # generic object (usually a Hash), return directly
  234. data
  235. when /\AArray<(.+)>\z/
  236. # e.g. Array<Pet>
  237. sub_type = $1
  238. data.map { |item| convert_to_type(item, sub_type) }
  239. when /\AHash\<String, (.+)\>\z/
  240. # e.g. Hash<String, Integer>
  241. sub_type = $1
  242. {}.tap do |hash|
  243. data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
  244. end
  245. else
  246. # models (e.g. Pet) or oneOf
  247. klass = OpenapiClient.const_get(return_type)
  248. klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
  249. end
  250. end
  251. # Sanitize filename by removing path.
  252. # e.g. ../../sun.gif becomes sun.gif
  253. #
  254. # @param [String] filename the filename to be sanitized
  255. # @return [String] the sanitized filename
  256. def sanitize_filename(filename)
  257. filename.gsub(/.*[\/\\]/, '')
  258. end
  259. def build_request_url(path, opts = {})
  260. # Add leading and trailing slashes to path
  261. path = "/#{path}".gsub(/\/+/, '/')
  262. @config.base_url(opts[:operation]) + path
  263. end
  264. # Update header and query params based on authentication settings.
  265. #
  266. # @param [Hash] header_params Header parameters
  267. # @param [Hash] query_params Query parameters
  268. # @param [String] auth_names Authentication scheme name
  269. def update_params_for_auth!(header_params, query_params, auth_names)
  270. Array(auth_names).each do |auth_name|
  271. auth_setting = @config.auth_settings[auth_name]
  272. next unless auth_setting
  273. case auth_setting[:in]
  274. when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
  275. when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
  276. else fail ArgumentError, 'Authentication token must be in `query` or `header`'
  277. end
  278. end
  279. end
  280. # Sets user agent in HTTP header
  281. #
  282. # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
  283. def user_agent=(user_agent)
  284. @user_agent = user_agent
  285. @default_headers['User-Agent'] = @user_agent
  286. end
  287. # Return Accept header based on an array of accepts provided.
  288. # @param [Array] accepts array for Accept
  289. # @return [String] the Accept header (e.g. application/json)
  290. def select_header_accept(accepts)
  291. return nil if accepts.nil? || accepts.empty?
  292. # use JSON when present, otherwise use all of the provided
  293. json_accept = accepts.find { |s| json_mime?(s) }
  294. json_accept || accepts.join(',')
  295. end
  296. # Return Content-Type header based on an array of content types provided.
  297. # @param [Array] content_types array for Content-Type
  298. # @return [String] the Content-Type header (e.g. application/json)
  299. def select_header_content_type(content_types)
  300. # return nil by default
  301. return if content_types.nil? || content_types.empty?
  302. # use JSON when present, otherwise use the first one
  303. json_content_type = content_types.find { |s| json_mime?(s) }
  304. json_content_type || content_types.first
  305. end
  306. # Convert object (array, hash, object, etc) to JSON string.
  307. # @param [Object] model object to be converted into JSON string
  308. # @return [String] JSON string representation of the object
  309. def object_to_http_body(model)
  310. return model if model.nil? || model.is_a?(String)
  311. local_body = nil
  312. if model.is_a?(Array)
  313. local_body = model.map { |m| object_to_hash(m) }
  314. else
  315. local_body = object_to_hash(model)
  316. end
  317. local_body.to_json
  318. end
  319. # Convert object(non-array) to hash.
  320. # @param [Object] obj object to be converted into JSON string
  321. # @return [String] JSON string representation of the object
  322. def object_to_hash(obj)
  323. if obj.respond_to?(:to_hash)
  324. obj.to_hash
  325. else
  326. obj
  327. end
  328. end
  329. # Build parameter value according to the given collection format.
  330. # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
  331. def build_collection_param(param, collection_format)
  332. case collection_format
  333. when :csv
  334. param.join(',')
  335. when :ssv
  336. param.join(' ')
  337. when :tsv
  338. param.join("\t")
  339. when :pipes
  340. param.join('|')
  341. when :multi
  342. # return the array directly as typhoeus will handle it as expected
  343. param
  344. else
  345. fail "unknown collection format: #{collection_format.inspect}"
  346. end
  347. end
  348. end
  349. end