groupdocs_comparison_cloud 18.9

Sign up to get free protection for your applications and to get access to all the features.
Files changed (30) hide show
  1. checksums.yaml +7 -0
  2. data/lib/groupdocs_comparison_cloud.rb +76 -0
  3. data/lib/groupdocs_comparison_cloud/api/changes_api.rb +470 -0
  4. data/lib/groupdocs_comparison_cloud/api/comparison_api.rb +365 -0
  5. data/lib/groupdocs_comparison_cloud/api_client.rb +390 -0
  6. data/lib/groupdocs_comparison_cloud/api_error.rb +56 -0
  7. data/lib/groupdocs_comparison_cloud/configuration.rb +95 -0
  8. data/lib/groupdocs_comparison_cloud/models/color.rb +1404 -0
  9. data/lib/groupdocs_comparison_cloud/models/comparison_change.rb +265 -0
  10. data/lib/groupdocs_comparison_cloud/models/comparison_changes_category_dto.rb +218 -0
  11. data/lib/groupdocs_comparison_cloud/models/comparison_file_info.rb +226 -0
  12. data/lib/groupdocs_comparison_cloud/models/comparison_metadata_values.rb +226 -0
  13. data/lib/groupdocs_comparison_cloud/models/comparison_request.rb +240 -0
  14. data/lib/groupdocs_comparison_cloud/models/comparison_request_settings.rb +378 -0
  15. data/lib/groupdocs_comparison_cloud/models/comparison_style_change.rb +206 -0
  16. data/lib/groupdocs_comparison_cloud/models/link.rb +236 -0
  17. data/lib/groupdocs_comparison_cloud/models/requests/comparison_images_request.rb +49 -0
  18. data/lib/groupdocs_comparison_cloud/models/requests/comparison_images_stream_request.rb +45 -0
  19. data/lib/groupdocs_comparison_cloud/models/requests/comparison_request.rb +49 -0
  20. data/lib/groupdocs_comparison_cloud/models/requests/comparison_stream_request.rb +45 -0
  21. data/lib/groupdocs_comparison_cloud/models/requests/post_categories_changes_request.rb +49 -0
  22. data/lib/groupdocs_comparison_cloud/models/requests/post_changes_request.rb +45 -0
  23. data/lib/groupdocs_comparison_cloud/models/requests/put_changes_document_request.rb +49 -0
  24. data/lib/groupdocs_comparison_cloud/models/requests/put_changes_document_stream_request.rb +45 -0
  25. data/lib/groupdocs_comparison_cloud/models/requests/put_changes_images_request.rb +49 -0
  26. data/lib/groupdocs_comparison_cloud/models/requests/put_changes_images_stream_request.rb +45 -0
  27. data/lib/groupdocs_comparison_cloud/models/style_settings_values.rb +231 -0
  28. data/lib/groupdocs_comparison_cloud/models/value_type.rb +196 -0
  29. data/lib/groupdocs_comparison_cloud/version.rb +29 -0
  30. metadata +160 -0
@@ -0,0 +1,365 @@
1
+ # -----------------------------------------------------------------------------------
2
+ # <copyright company="Aspose Pty Ltd" file="comparison.rb">
3
+ # Copyright (c) 2003-2018 Aspose Pty Ltd
4
+ # </copyright>
5
+ # <summary>
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 all
14
+ # 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 THE
22
+ # SOFTWARE.
23
+ # </summary>
24
+ # -----------------------------------------------------------------------------------
25
+
26
+ require 'uri'
27
+ require 'date'
28
+
29
+ module GroupDocsComparisonCloud
30
+ #
31
+ # GroupDocs.Comparison Cloud API
32
+ #
33
+ class ComparisonApi
34
+ attr_accessor :config
35
+
36
+ #make ComparisonApi.new private
37
+ private_class_method :new
38
+
39
+ # Initializes new instance of ComparisonApi
40
+ #
41
+ # @param [config] Configuration
42
+ # @return [ComparisonApi] New instance of ComparisonApi
43
+ def initialize(config)
44
+ @config = config
45
+ @api_client = ApiClient.new(config)
46
+ require_all '../models/requests'
47
+
48
+ @access_token = nil
49
+ end
50
+
51
+ # Initializes new instance of ComparisonApi
52
+ #
53
+ # @param [app_sid] Application identifier (App SID)
54
+ # @param [app_key] Application private key (App Key)
55
+ # @return [ComparisonApi] New instance of ComparisonApi
56
+ def self.from_keys(app_sid, app_key)
57
+ config = Configuration.new(app_sid, app_key)
58
+ return new(config)
59
+ end
60
+
61
+ # Initializes new instance of ComparisonApi
62
+ #
63
+ # @param [config] Configuration
64
+ # @return [ComparisonApi] New instance of ComparisonApi
65
+ def self.from_config(config)
66
+ return new(config)
67
+ end
68
+
69
+ # Returns document with the result of comparison
70
+ #
71
+ # @param request comparison_request
72
+ # @return [Link]
73
+ def comparison(request)
74
+ data, _status_code, _headers = comparison_with_http_info(request)
75
+ data
76
+ end
77
+
78
+ # Returns document with the result of comparison
79
+ #
80
+ # @param request comparison_request
81
+ # @return [Array<(Link, Fixnum, Hash)>]
82
+ # Link data, response status code and response headers
83
+ def comparison_with_http_info(request)
84
+ raise ArgumentError, 'Incorrect request type' unless request.is_a? ComparisonRequest1
85
+
86
+ @api_client.config.logger.debug 'Calling API: ComparisonApi.comparison ...' if @api_client.config.debugging
87
+ # resource path
88
+ local_var_path = '/comparison/compareDocuments'
89
+
90
+ # query parameters
91
+ query_params = {}
92
+ if local_var_path.include? ('{' + downcase_first_letter('OutPath') + '}')
93
+ local_var_path = local_var_path.sub('{' + downcase_first_letter('OutPath') + '}', request.out_path.to_s)
94
+ else
95
+ query_params[downcase_first_letter('OutPath')] = request.out_path unless request.out_path.nil?
96
+ end
97
+
98
+ # header parameters
99
+ header_params = {}
100
+ # HTTP header 'Accept' (if needed)
101
+ header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
102
+ # HTTP header 'Content-Type'
103
+ header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
104
+
105
+ # form parameters
106
+ form_params = {}
107
+
108
+ # http body (model)
109
+ post_body = @api_client.object_to_http_body(request.request)
110
+ data, status_code, headers = @api_client.call_api(:POST, local_var_path,
111
+ header_params: header_params,
112
+ query_params: query_params,
113
+ form_params: form_params,
114
+ body: post_body,
115
+ access_token: get_access_token,
116
+ return_type: 'Link')
117
+ if @api_client.config.debugging
118
+ @api_client.config.logger.debug "API called:
119
+ ComparisonApi#comparison\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
120
+ end
121
+ [data, status_code, headers]
122
+ end
123
+
124
+ # Returns images of document with the result of comparison
125
+ #
126
+ # @param request comparison_images_request
127
+ # @return [Array<Link>]
128
+ def comparison_images(request)
129
+ data, _status_code, _headers = comparison_images_with_http_info(request)
130
+ data
131
+ end
132
+
133
+ # Returns images of document with the result of comparison
134
+ #
135
+ # @param request comparison_images_request
136
+ # @return [Array<(Array<Link>, Fixnum, Hash)>]
137
+ # Array<Link> data, response status code and response headers
138
+ def comparison_images_with_http_info(request)
139
+ raise ArgumentError, 'Incorrect request type' unless request.is_a? ComparisonImagesRequest
140
+
141
+ @api_client.config.logger.debug 'Calling API: ComparisonApi.comparison_images ...' if @api_client.config.debugging
142
+ # resource path
143
+ local_var_path = '/comparison/compareDocuments/images'
144
+
145
+ # query parameters
146
+ query_params = {}
147
+ if local_var_path.include? ('{' + downcase_first_letter('OutFolder') + '}')
148
+ local_var_path = local_var_path.sub('{' + downcase_first_letter('OutFolder') + '}', request.out_folder.to_s)
149
+ else
150
+ query_params[downcase_first_letter('OutFolder')] = request.out_folder unless request.out_folder.nil?
151
+ end
152
+
153
+ # header parameters
154
+ header_params = {}
155
+ # HTTP header 'Accept' (if needed)
156
+ header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
157
+ # HTTP header 'Content-Type'
158
+ header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
159
+
160
+ # form parameters
161
+ form_params = {}
162
+
163
+ # http body (model)
164
+ post_body = @api_client.object_to_http_body(request.request)
165
+ data, status_code, headers = @api_client.call_api(:POST, local_var_path,
166
+ header_params: header_params,
167
+ query_params: query_params,
168
+ form_params: form_params,
169
+ body: post_body,
170
+ access_token: get_access_token,
171
+ return_type: 'Array<Link>')
172
+ if @api_client.config.debugging
173
+ @api_client.config.logger.debug "API called:
174
+ ComparisonApi#comparison_images\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
175
+ end
176
+ [data, status_code, headers]
177
+ end
178
+
179
+ # Returns image's streams of document with the result of comparison
180
+ #
181
+ # @param request comparison_images_stream_request
182
+ # @return [File]
183
+ def comparison_images_stream(request)
184
+ data, _status_code, _headers = comparison_images_stream_with_http_info(request)
185
+ data
186
+ end
187
+
188
+ # Returns image&#39;s streams of document with the result of comparison
189
+ #
190
+ # @param request comparison_images_stream_request
191
+ # @return [Array<(File, Fixnum, Hash)>]
192
+ # File data, response status code and response headers
193
+ def comparison_images_stream_with_http_info(request)
194
+ raise ArgumentError, 'Incorrect request type' unless request.is_a? ComparisonImagesStreamRequest
195
+
196
+ @api_client.config.logger.debug 'Calling API: ComparisonApi.comparison_images_stream ...' if @api_client.config.debugging
197
+ # resource path
198
+ local_var_path = '/comparison/compareDocuments/stream/images'
199
+
200
+ # query parameters
201
+ query_params = {}
202
+
203
+ # header parameters
204
+ header_params = {}
205
+ # HTTP header 'Accept' (if needed)
206
+ header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
207
+ # HTTP header 'Content-Type'
208
+ header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
209
+
210
+ # form parameters
211
+ form_params = {}
212
+
213
+ # http body (model)
214
+ post_body = @api_client.object_to_http_body(request.request)
215
+ data, status_code, headers = @api_client.call_api(:POST, local_var_path,
216
+ header_params: header_params,
217
+ query_params: query_params,
218
+ form_params: form_params,
219
+ body: post_body,
220
+ access_token: get_access_token,
221
+ return_type: 'File')
222
+ if @api_client.config.debugging
223
+ @api_client.config.logger.debug "API called:
224
+ ComparisonApi#comparison_images_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
225
+ end
226
+ [data, status_code, headers]
227
+ end
228
+
229
+ # Returns stream of document with the result of comparison
230
+ #
231
+ # @param request comparison_stream_request
232
+ # @return [File]
233
+ def comparison_stream(request)
234
+ data, _status_code, _headers = comparison_stream_with_http_info(request)
235
+ data
236
+ end
237
+
238
+ # Returns stream of document with the result of comparison
239
+ #
240
+ # @param request comparison_stream_request
241
+ # @return [Array<(File, Fixnum, Hash)>]
242
+ # File data, response status code and response headers
243
+ def comparison_stream_with_http_info(request)
244
+ raise ArgumentError, 'Incorrect request type' unless request.is_a? ComparisonStreamRequest
245
+
246
+ @api_client.config.logger.debug 'Calling API: ComparisonApi.comparison_stream ...' if @api_client.config.debugging
247
+ # resource path
248
+ local_var_path = '/comparison/compareDocuments/stream'
249
+
250
+ # query parameters
251
+ query_params = {}
252
+
253
+ # header parameters
254
+ header_params = {}
255
+ # HTTP header 'Accept' (if needed)
256
+ header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
257
+ # HTTP header 'Content-Type'
258
+ header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
259
+
260
+ # form parameters
261
+ form_params = {}
262
+
263
+ # http body (model)
264
+ post_body = @api_client.object_to_http_body(request.request)
265
+ data, status_code, headers = @api_client.call_api(:POST, local_var_path,
266
+ header_params: header_params,
267
+ query_params: query_params,
268
+ form_params: form_params,
269
+ body: post_body,
270
+ access_token: get_access_token,
271
+ return_type: 'File')
272
+ if @api_client.config.debugging
273
+ @api_client.config.logger.debug "API called:
274
+ ComparisonApi#comparison_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
275
+ end
276
+ [data, status_code, headers]
277
+ end
278
+
279
+ #
280
+ # Helper method to convert first letter to downcase
281
+ #
282
+ private def downcase_first_letter(str)
283
+ value = str[0].downcase + str[1..-1]
284
+ value
285
+ end
286
+
287
+ #
288
+ # Retrieves access token
289
+ #
290
+ private def get_access_token
291
+ if @access_token.nil? then
292
+ request_access_token
293
+ else
294
+ access_token_expired = @access_token_expires_at < DateTime.now
295
+ if access_token_expired then
296
+ reset_access_token
297
+ end
298
+ end
299
+
300
+ @access_token
301
+ end
302
+
303
+ #
304
+ # Gets a access token from server
305
+ #
306
+ private def request_access_token
307
+ auth_config = Configuration.new(@config.app_sid, @config.app_key)
308
+ auth_config.api_base_url = @config.api_base_url
309
+ auth_config.debugging = @config.debugging
310
+ auth_config.logger = @config.logger
311
+ auth_config.temp_folder_path = @config.temp_folder_path
312
+ auth_config.client_side_validation = @config.client_side_validation
313
+ auth_config.api_version = ''
314
+
315
+ auth_api_client = ApiClient.new(auth_config)
316
+
317
+ request_url = "/oauth2/token"
318
+ post_data = "grant_type=client_credentials&client_id=#{@config.app_sid}&client_secret=#{@config.app_key}"
319
+
320
+ data, _status_code, _header = auth_api_client.call_api(:POST, request_url, :body => post_data, :return_type => 'Object')
321
+
322
+ @access_token = data[:access_token]
323
+ @refresh_token = data[:refresh_token]
324
+
325
+ expires_in_seconds = data[:expires_in].to_i - 5 * 60
326
+ expires_in_days = Rational(expires_in_seconds, 60 * 60 * 24)
327
+ @access_token_expires_at = DateTime.now + expires_in_days
328
+ end
329
+
330
+ #
331
+ # Resets access token
332
+ #
333
+ private def reset_access_token
334
+ auth_config = Configuration.new(@config.app_sid, @config.app_key)
335
+ auth_config.api_base_url = @config.api_base_url
336
+ auth_config.debugging = @config.debugging
337
+ auth_config.logger = @config.logger
338
+ auth_config.temp_folder_path = @config.temp_folder_path
339
+ auth_config.client_side_validation = @config.client_side_validation
340
+ auth_config.api_version = ''
341
+
342
+ auth_api_client = ApiClient.new(auth_config)
343
+
344
+ request_url = "/oauth2/token"
345
+ post_data = "grant_type=refresh_token&refresh_token=#{@refresh_token}"
346
+
347
+ data, _status_code, _header = auth_api_client.call_api(:POST, request_url, :body => post_data, :return_type => 'Object')
348
+
349
+ @access_token = data[:access_token]
350
+ @refresh_token = data[:refresh_token]
351
+
352
+ expires_in_seconds = data[:expires_in].to_i - 5 * 60
353
+ expires_in_days = Rational(expires_in_seconds, 60 * 60 * 24)
354
+ @access_token_expires_at = DateTime.now + expires_in_days
355
+ end
356
+
357
+ # requires all files inside a directory from current dir
358
+ # @param _dir can be relative path like '/lib' or "../lib"
359
+ private def require_all(_dir)
360
+ Dir[File.expand_path(File.join(File.dirname(File.absolute_path(__FILE__)), _dir)) + "/*.rb"].each do |file|
361
+ require file
362
+ end
363
+ end
364
+ end
365
+ end
@@ -0,0 +1,390 @@
1
+ # -----------------------------------------------------------------------------------
2
+ # <copyright company="Aspose Pty Ltd" file="api_client.rb">
3
+ # Copyright (c) 2003-2018 Aspose Pty Ltd
4
+ # </copyright>
5
+ # <summary>
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 all
14
+ # 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 THE
22
+ # SOFTWARE.
23
+ # </summary>
24
+ # -----------------------------------------------------------------------------------
25
+
26
+ require 'date'
27
+ require 'json'
28
+ require 'logger'
29
+ require 'tempfile'
30
+ require 'faraday'
31
+ require 'mimemagic'
32
+ require 'addressable'
33
+ require_relative 'version'
34
+ require_relative 'api_error'
35
+
36
+ module GroupDocsComparisonCloud
37
+ #
38
+ # api client is mainly responsible for making the HTTP call to the API backend.
39
+ #
40
+ class ApiClient
41
+ # The Configuration object holding settings to be used in the API client.
42
+ attr_accessor :config
43
+
44
+ # Defines the headers to be used in HTTP requests of all API calls by default.
45
+ #
46
+ # @return [Hash]
47
+ attr_accessor :default_headers
48
+
49
+ # Initializes the ApiClient
50
+ # @option config [Configuration] Configuration for initializing the object
51
+ def initialize(config)
52
+ @config = config
53
+ @default_headers = {
54
+ 'Content-Type' => "application/json",
55
+ 'x-groupdocs-client' => "ruby sdk",
56
+ 'x-groupdocs-version' => GroupDocsComparisonCloud::VERSION.to_s
57
+ }
58
+ end
59
+
60
+ # Call an API with given options.
61
+ #
62
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
63
+ # the data deserialized from response body (could be nil), response status code and response headers.
64
+ def call_api(http_method, path, opts = {})
65
+ response = build_request(http_method, path, opts)
66
+ download_file response if opts[:return_type] == 'File'
67
+ if @config.debugging
68
+ @config.logger.debug "'HTTP' response body '~BEGIN~'\n #{response.body}\n'~END~'\n"
69
+ end
70
+
71
+ unless response.success?
72
+ if response.status == 0
73
+ # Errors from libcurl will be made visible here
74
+ raise ApiError.new(:code => 0,
75
+ :message => response.reason_phrase)
76
+ else
77
+ raise ApiError.new(:code => response.status,
78
+ :response_headers => response.headers,
79
+ :response_body => response.body),
80
+ response.reason_phrase
81
+ end
82
+ end
83
+
84
+
85
+ data = deserialize(response, opts[:return_type]) if opts[:return_type]
86
+ [data, response.status, response.headers]
87
+ end
88
+
89
+ # Builds the HTTP request
90
+ #
91
+ # @param [String] http_method HTTP method/verb (e.g. POST)
92
+ # @param [String] path URL path (e.g. /account/new)
93
+ # @option opts [Hash] :header_params Header parameters
94
+ # @option opts [Hash] :query_params Query parameters
95
+ # @option opts [Hash] :form_params Query parameters
96
+ # @option opts [Object] :body HTTP body (JSON/XML)
97
+ # @return [Faraday::Response] A Faraday Response
98
+ def build_request(http_method, path, opts = {})
99
+ url = build_request_url(path)
100
+ http_method = http_method.to_sym.downcase
101
+
102
+ header_params = @default_headers.merge(opts[:header_params] || {})
103
+ query_params = opts[:query_params] || {}
104
+ form_params = opts[:form_params] || {}
105
+ body = opts[:body] if opts[:body] || nil?
106
+
107
+ update_params_for_oauth! header_params, opts[:access_token]
108
+
109
+ req_opts = {
110
+ :method => http_method,
111
+ :headers => header_params,
112
+ :params => query_params,
113
+ :body => body
114
+ }
115
+
116
+ if [:post, :patch, :put, :delete].include?(http_method)
117
+ req_body = build_request_body(header_params, form_params, opts[:body])
118
+ req_opts.update :body => req_body
119
+ if @config.debugging
120
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
121
+ end
122
+ end
123
+
124
+ conn = Faraday.new url, { :params => query_params, :headers => header_params } do |f|
125
+ f.request :multipart
126
+ f.request :url_encoded
127
+ f.adapter Faraday.default_adapter
128
+ end
129
+
130
+ case http_method
131
+ when :post
132
+ return conn.post url, req_opts[:body]
133
+ when :put
134
+ return conn.put url, req_opts[:body]
135
+ when :get
136
+ return conn.get url, req_opts[:body]
137
+ else
138
+ return conn.delete url do |c|
139
+ c.body = req_opts[:body]
140
+ end
141
+ end
142
+ end
143
+
144
+ # Check if the given MIME is a JSON MIME.
145
+ # JSON MIME examples:
146
+ # application/json
147
+ # application/json; charset=UTF8
148
+ # APPLICATION/JSON
149
+ # */*
150
+ # @param [String] mime MIME
151
+ # @return [Boolean] True if the MIME is application/json
152
+ def json_mime?(mime)
153
+ (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
154
+ end
155
+
156
+ # Deserialize the response to the given return type.
157
+ #
158
+ # @param [Response] response HTTP response
159
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
160
+ def deserialize(response, return_type)
161
+ body = response.body
162
+
163
+ # handle file downloading - return the File instance processed in request callbacks
164
+ # note that response body is empty when the file is written in chunks in request on_body callback
165
+ return @tempfile if return_type == 'File'
166
+
167
+ return nil if body.nil? || body.empty?
168
+
169
+ # return response body directly for String return type
170
+ return body if return_type == 'String'
171
+
172
+ # ensuring a default content type
173
+ content_type = response.headers['Content-Type'] || 'application/json'
174
+
175
+ raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
176
+
177
+ begin
178
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
179
+ rescue JSON::ParserError => e
180
+ if %w[String Date DateTime].include?(return_type)
181
+ data = body
182
+ else
183
+ raise e
184
+ end
185
+ end
186
+
187
+ convert_to_type data, return_type
188
+ end
189
+
190
+ # Convert data to the given return type.
191
+ # @param [Object] data Data to be converted
192
+ # @param [String] return_type Return type
193
+ # @return [Mixed] Data in a particular type
194
+ def convert_to_type(data, return_type)
195
+ return nil if data.nil?
196
+ case return_type
197
+ when 'String'
198
+ data.to_s
199
+ when 'Integer'
200
+ data.to_i
201
+ when 'Float'
202
+ data.to_f
203
+ when 'BOOLEAN'
204
+ data == true
205
+ when 'DateTime'
206
+ # parse date time (expecting ISO 8601 format)
207
+ DateTime.parse data
208
+ when 'Date'
209
+ # parse date time (expecting ISO 8601 format)
210
+ Date.parse data
211
+ when 'Object'
212
+ # generic object (usually a Hash), return directly
213
+ data
214
+ when /\AArray<(.+)>\z/
215
+ # e.g. Array<Pet>
216
+ sub_type = $1
217
+ data.map {|item| convert_to_type(item, sub_type) }
218
+ when /\AHash\<String, (.+)\>\z/
219
+ # e.g. Hash<String, Integer>
220
+ sub_type = $1
221
+ {}.tap do |hash|
222
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
223
+ end
224
+ else
225
+ # models, e.g. Pet
226
+ GroupDocsComparisonCloud.const_get(return_type).new.tap do |model|
227
+ model.build_from_hash data
228
+ end
229
+ end
230
+ end
231
+
232
+ # Save response body into a file in (the defined) temporary folder, using the filename
233
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
234
+ # The response body is written to the file in chunks in order to handle files which
235
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
236
+ # process can use.
237
+ #
238
+ # @see Configuration#temp_folder_path
239
+ def download_file(response)
240
+ tempfile = nil
241
+ encoding = nil
242
+ content_disposition = response.headers['Content-Disposition']
243
+ if content_disposition and content_disposition =~ /filename=/i
244
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
245
+ prefix = sanitize_filename(filename)
246
+ else
247
+ prefix = 'download-'
248
+ end
249
+ prefix += '-' unless prefix.end_with?('-')
250
+ encoding = response.body.encoding
251
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
252
+ @tempfile = tempfile
253
+ IO.binwrite(tempfile, response.body)
254
+ response.on_complete do |resp|
255
+ tempfile.close
256
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
257
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
258
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
259
+ "explicitly with `tempfile.delete`"
260
+ end
261
+ end
262
+
263
+ # Sanitize filename by removing path.
264
+ # e.g. ../../sun.gif becomes sun.gif
265
+ #
266
+ # @param [String] filename the filename to be sanitized
267
+ # @return [String] the sanitized filename
268
+ def sanitize_filename(filename)
269
+ filename.gsub(/.*[\/\\]/, '')
270
+ end
271
+
272
+ def build_request_url(path)
273
+ # Add leading and trailing slashes to path
274
+ path = "/#{path}".gsub(/\/+/, '/')
275
+ Addressable::URI.encode(@config.api_base_url + @config.api_version + path)
276
+ end
277
+
278
+ # Builds the HTTP request body
279
+ #
280
+ # @param [Hash] header_params Header parameters
281
+ # @param [Hash] form_params Query parameters
282
+ # @param [Object] body HTTP body (JSON/XML)
283
+ # @return [String] HTTP body data in the form of string
284
+ def build_request_body(header_params, form_params, body)
285
+ # http form
286
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
287
+ header_params['Content-Type'] == 'multipart/form-data'
288
+ data = {}
289
+ form_params.each do |key, value|
290
+ case value
291
+ when ::File
292
+ data[key] = Faraday::UploadIO.new(value.path, MimeMagic.by_magic(value).to_s, key)
293
+ when ::Array, nil
294
+ data[key] = value
295
+ else
296
+ data[key] = value.to_s
297
+ end
298
+ end
299
+ elsif body
300
+ data = body.is_a?(String) ? body : body.to_json
301
+ else
302
+ data = nil
303
+ end
304
+ data
305
+ end
306
+
307
+ # Update hearder and query params based on authentication settings.
308
+ #
309
+ # @param [Hash] header_params Header parameters
310
+ # @param [String] access_token OAuth access token
311
+ def update_params_for_oauth!(header_params, access_token)
312
+ header_params["Authorization"] = "Bearer #{access_token}"
313
+ end
314
+
315
+ # Sets user agent in HTTP header
316
+ #
317
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
318
+ def user_agent=(user_agent)
319
+ @user_agent = user_agent
320
+ @default_headers['User-Agent'] = @user_agent
321
+ end
322
+
323
+ # Return Accept header based on an array of accepts provided.
324
+ # @param [Array] accepts array for Accept
325
+ # @return [String] the Accept header (e.g. application/json)
326
+ def select_header_accept(accepts)
327
+ return nil if accepts.nil? || accepts.empty?
328
+ # use JSON when present, otherwise use all of the provided
329
+ json_accept = accepts.find { |s| json_mime?(s) }
330
+ return json_accept || accepts.join(',')
331
+ end
332
+
333
+ # Return Content-Type header based on an array of content types provided.
334
+ # @param [Array] content_types array for Content-Type
335
+ # @return [String] the Content-Type header (e.g. application/json)
336
+ def select_header_content_type(content_types)
337
+ # use application/json by default
338
+ return 'application/json' if content_types.nil? || content_types.empty?
339
+ # use JSON when present, otherwise use the first one
340
+ json_content_type = content_types.find { |s| json_mime?(s) }
341
+ return json_content_type || content_types.first
342
+ end
343
+
344
+ # Convert object (array, hash, object, etc) to JSON string.
345
+ # @param [Object] model object to be converted into JSON string
346
+ # @return [String] JSON string representation of the object
347
+ def object_to_http_body(model)
348
+ return '"' + model + '"' if model.is_a?(String)
349
+ return model if model.nil?
350
+ local_body = nil
351
+ if model.is_a?(Array)
352
+ local_body = model.map { |m| object_to_hash(m) }
353
+ else
354
+ local_body = object_to_hash(model)
355
+ end
356
+ local_body.to_json
357
+ end
358
+
359
+ # Convert object(non-array) to hash.
360
+ # @param [Object] obj object to be converted into JSON string
361
+ # @return [String] JSON string representation of the object
362
+ def object_to_hash(obj)
363
+ if obj.respond_to?(:to_hash)
364
+ obj.to_hash
365
+ else
366
+ obj
367
+ end
368
+ end
369
+
370
+ # Build parameter value according to the given collection format.
371
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
372
+ def build_collection_param(param, collection_format)
373
+ case collection_format
374
+ when :csv
375
+ param.join(',')
376
+ when :ssv
377
+ param.join(' ')
378
+ when :tsv
379
+ param.join("\t")
380
+ when :pipes
381
+ param.join('|')
382
+ when :multi
383
+ # return the array directly as faraday will handle it as expected
384
+ param
385
+ else
386
+ raise "unknown collection format: #{collection_format.inspect}"
387
+ end
388
+ end
389
+ end
390
+ end