aspose_cells_cloud 20.2 → 20.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,488 +1,489 @@
1
- =begin
2
- --------------------------------------------------------------------------------------------------------------------
3
- Copyright (c) 2020 Aspose.Cells Cloud
4
- Permission is hereby granted, free of charge, to any person obtaining a copy
5
- of this software and associated documentation files (the "Software"), to deal
6
- in the Software without restriction, including without limitation the rights
7
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- copies of the Software, and to permit persons to whom the Software is
9
- furnished to do so, subject to the following conditions:
10
- The above copyright notice and this permission notice shall be included in all
11
- copies or substantial portions of the Software.
12
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
- SOFTWARE.
19
- --------------------------------------------------------------------------------------------------------------------
20
-
21
- =end
22
-
23
- require 'date'
24
- require 'json'
25
- require 'logger'
26
- require 'tempfile'
27
- require 'uri'
28
- require 'faraday'
29
- require_relative 'version'
30
- require_relative 'api_error'
31
-
32
- module AsposeCellsCloud
33
- class ApiClient
34
- # The Configuration object holding settings to be used in the API client.
35
- attr_accessor :config
36
-
37
- # Defines the headers to be used in HTTP requests of all API calls by default.
38
- #
39
- # @return [Hash]
40
- attr_accessor :default_headers
41
- attr_accessor :get_access_token_time
42
- # Initializes the ApiClient
43
- # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
44
- def initialize(config = Configuration.default)
45
- @config = config
46
-
47
- @default_headers = {
48
- 'Content-Type' => "application/json",
49
- 'x-aspose-client' => "ruby sdk",
50
- 'x-aspose-version' => "#{ AsposeCellsCloud::VERSION }"
51
- }
52
- end
53
-
54
- def self.default
55
- @@default ||= ApiClient.new
56
- end
57
-
58
- # Call an API with given options.
59
- #
60
- # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
61
- # the data deserialized from response body (could be nil), response status code and response headers.
62
- def call_api(http_method, path, opts = {})
63
- response = build_request(http_method, path, opts)
64
- download_file response if opts[:return_type] == 'File'
65
-
66
- if @config.debugging
67
- @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
68
- end
69
-
70
- unless response.success?
71
-
72
- if response.status == 0
73
- # Errors from libcurl will be made visible here
74
- fail ApiError.new(:code => 0,
75
- :message => response.reason_phrase)
76
- else
77
- fail 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
- if opts[:return_type]
85
- data = deserialize(response, opts[:return_type])
86
- else
87
- data = nil
88
- end
89
- [data, response.status, response.headers]
90
- end
91
-
92
- # Builds the HTTP request
93
- #
94
- # @param [String] http_method HTTP method/verb (e.g. POST)
95
- # @param [String] path URL path (e.g. /account/new)
96
- # @option opts [Hash] :header_params Header parameters
97
- # @option opts [Hash] :query_params Query parameters
98
- # @option opts [Hash] :form_params Query parameters
99
- # @option opts [Object] :body HTTP body (JSON/XML)
100
- # @return [Faraday::Response] A Faraday Response
101
- def build_request(http_method, path, opts = {})
102
- url = build_request_url(path)
103
- http_method = http_method.to_sym.downcase
104
-
105
- header_params = @default_headers.merge(opts[:header_params] || {})
106
- query_params = opts[:query_params] || {}
107
- form_params = opts[:form_params] || {}
108
- body = opts[:body] || {}
109
-
110
- update_params_for_auth! header_params, query_params, opts[:auth_names]
111
-
112
- req_opts = {
113
- :method => http_method,
114
- :headers => header_params,
115
- :params => query_params,
116
- :body => body
117
- }
118
-
119
- if [:post, :patch, :put, :delete].include?(http_method)
120
- req_body = build_request_body(header_params, form_params, opts[:body])
121
- req_opts.update :body => req_body
122
- if @config.debugging
123
- @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
124
- end
125
- end
126
-
127
- # OAuth 2.0
128
- req_opts[:params] = opts[:query_params]
129
-
130
- add_o_auth_token(req_opts)
131
-
132
-
133
- conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
134
- f.request :multipart
135
- f.request :url_encoded
136
- f.adapter Faraday.default_adapter
137
- end
138
-
139
- if req_opts[:body] == {}
140
- req_opts[:body] = nil
141
- end
142
-
143
- case http_method
144
- when :post
145
- return conn.post url, req_opts[:body]
146
- when :put
147
- return conn.put url, req_opts[:body]
148
- when :get
149
- return conn.get url, req_opts[:body]
150
- else
151
- return conn.delete url do |c|
152
- c.body = req_opts[:body]
153
- end
154
- end
155
- end
156
-
157
- # Check if the given MIME is a JSON MIME.
158
- # JSON MIME examples:
159
- # application/json
160
- # application/json; charset=UTF8
161
- # APPLICATION/JSON
162
- # */*
163
- # @param [String] mime MIME
164
- # @return [Boolean] True if the MIME is application/json
165
- def json_mime?(mime)
166
- (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
167
- end
168
-
169
- # Deserialize the response to the given return type.
170
- #
171
- # @param [Response] response HTTP response
172
- # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
173
- def deserialize(response, return_type)
174
- body = response.body
175
-
176
- # handle file downloading - return the File instance processed in request callbacks
177
- # note that response body is empty when the file is written in chunks in request on_body callback
178
- return @tempfile if return_type == 'File'
179
-
180
- return nil if body.nil? || body.empty?
181
-
182
- # return response body directly for String return type
183
- return body if return_type == 'String'
184
-
185
- # ensuring a default content type
186
- content_type = response.headers['Content-Type'] || 'application/json'
187
-
188
- raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
189
-
190
- begin
191
- data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
192
- rescue JSON::ParserError => e
193
- if %w(String Date DateTime).include?(return_type)
194
- data = body
195
- else
196
- raise e
197
- end
198
- end
199
-
200
- convert_to_type data, return_type
201
- end
202
-
203
- # Convert data to the given return type.
204
- # @param [Object] data Data to be converted
205
- # @param [String] return_type Return type
206
- # @return [Mixed] Data in a particular type
207
- def convert_to_type(data, return_type)
208
- return nil if data.nil?
209
- case return_type
210
- when 'String'
211
- data.to_s
212
- when 'Integer'
213
- data.to_i
214
- when 'Float'
215
- data.to_f
216
- when 'BOOLEAN'
217
- data == true
218
- when 'DateTime'
219
- # parse date time (expecting ISO 8601 format)
220
- DateTime.parse data
221
- when 'Date'
222
- # parse date time (expecting ISO 8601 format)
223
- Date.parse data
224
- when 'Object'
225
- # generic object (usually a Hash), return directly
226
- data
227
- when /\AArray<(.+)>\z/
228
- # e.g. Array<Pet>
229
- sub_type = $1
230
- data.map {|item| convert_to_type(item, sub_type) }
231
- when /\AHash\<String, (.+)\>\z/
232
- # e.g. Hash<String, Integer>
233
- sub_type = $1
234
- {}.tap do |hash|
235
- data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
236
- end
237
- else
238
- # models, e.g. Pet
239
- AsposeCellsCloud.const_get(return_type).new.tap do |model|
240
- model.build_from_hash data
241
- end
242
- end
243
- end
244
-
245
- # Save response body into a file in (the defined) temporary folder, using the filename
246
- # from the "Content-Disposition" header if provided, otherwise a random filename.
247
- # The response body is written to the file in chunks in order to handle files which
248
- # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
249
- # process can use.
250
- #
251
- # @see Configuration#temp_folder_path
252
- def download_file(response)
253
- tempfile = nil
254
- encoding = nil
255
-
256
- content_disposition = response.headers['Content-Disposition']
257
- if content_disposition and content_disposition =~ /filename=/i
258
- filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
259
- prefix = sanitize_filename(filename)
260
- else
261
- prefix = 'download-'
262
- end
263
- prefix = prefix + '-' unless prefix.end_with?('-')
264
- encoding = response.body.encoding
265
- tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
266
- @tempfile = tempfile
267
-
268
- tempfile.write(response.body)
269
-
270
- response.on_complete do |resp|
271
- tempfile.close
272
- @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
273
- "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
274
- "will be deleted automatically with GC. It's also recommended to delete the temp file "\
275
- "explicitly with `tempfile.delete`"
276
- end
277
- end
278
-
279
- # Sanitize filename by removing path.
280
- # e.g. ../../sun.gif becomes sun.gif
281
- #
282
- # @param [String] filename the filename to be sanitized
283
- # @return [String] the sanitized filename
284
- def sanitize_filename(filename)
285
- filename.gsub(/.*[\/\\]/, '')
286
- end
287
-
288
- def build_request_url(path)
289
- # Add leading and trailing slashes to path
290
- path = "/#{path}".gsub(/\/+/, '/')
291
- URI.encode(@config.base_url + path)
292
- end
293
-
294
- # Builds the HTTP request body
295
- #
296
- # @param [Hash] header_params Header parameters
297
- # @param [Hash] form_params Query parameters
298
- # @param [Object] body HTTP body (JSON/XML)
299
- # @return [String] HTTP body data in the form of string
300
- def build_request_body(header_params, form_params, body)
301
- # http form
302
- if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
303
- header_params['Content-Type'] == 'multipart/form-data'
304
- data = {}
305
- form_params.each do |key, value|
306
- case value
307
- when ::File
308
- data[key] = Faraday::UploadIO.new(value.path, MimeMagic.by_magic(value).to_s, key)
309
- when ::Array, nil
310
- # let typhoeus handle File, Array and nil parameters
311
- data[key] = value
312
- else
313
- data[key] = value.to_s
314
- end
315
- end
316
- elsif body
317
- data = body.is_a?(String) ? body : body.to_json
318
- else
319
- data = nil
320
- end
321
- data
322
- end
323
-
324
- # Update hearder and query params based on authentication settings.
325
- #
326
- # @param [Hash] header_params Header parameters
327
- # @param [Hash] query_params Query parameters
328
- # @param [String] auth_names Authentication scheme name
329
- def update_params_for_auth!(header_params, query_params, auth_names)
330
- Array(auth_names).each do |auth_name|
331
- auth_setting = @config.auth_settings[auth_name]
332
- next unless auth_setting
333
- case auth_setting[:in]
334
- when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
335
- when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
336
- else raise ArgumentError, 'Authentication token must be in `query` of `header`'
337
- end
338
- end
339
- end
340
-
341
- # Sets user agent in HTTP header
342
- #
343
- # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
344
- def user_agent=(user_agent)
345
- @user_agent = user_agent
346
- @default_headers['User-Agent'] = @user_agent
347
- end
348
-
349
- # Return Accept header based on an array of accepts provided.
350
- # @param [Array] accepts array for Accept
351
- # @return [String] the Accept header (e.g. application/json)
352
- def select_header_accept(accepts)
353
- return nil if accepts.nil? || accepts.empty?
354
- # use JSON when present, otherwise use all of the provided
355
- json_accept = accepts.find { |s| json_mime?(s) }
356
- return json_accept || accepts.join(',')
357
- end
358
-
359
- # Return Content-Type header based on an array of content types provided.
360
- # @param [Array] content_types array for Content-Type
361
- # @return [String] the Content-Type header (e.g. application/json)
362
- def select_header_content_type(content_types)
363
- # use application/json by default
364
- return 'application/json' if content_types.nil? || content_types.empty?
365
- # use JSON when present, otherwise use the first one
366
- json_content_type = content_types.find { |s| json_mime?(s) }
367
- return json_content_type || content_types.first
368
- end
369
-
370
- # Convert object (array, hash, object, etc) to JSON string.
371
- # @param [Object] model object to be converted into JSON string
372
- # @return [String] JSON string representation of the object
373
- def object_to_http_body(model)
374
- return '"' + model + '"' if model.is_a?(String)
375
- return model if model.nil?
376
- local_body = nil
377
- if model.is_a?(Array)
378
- local_body = model.map{|m| object_to_hash(m) }
379
- else
380
- local_body = object_to_hash(model)
381
- end
382
- local_body.to_json
383
- end
384
-
385
- # Convert object(non-array) to hash.
386
- # @param [Object] obj object to be converted into JSON string
387
- # @return [String] JSON string representation of the object
388
- def object_to_hash(obj)
389
- if obj.respond_to?(:to_hash)
390
- obj.to_hash
391
- else
392
- obj
393
- end
394
- end
395
-
396
- # Build parameter value according to the given collection format.
397
- # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
398
- def build_collection_param(param, collection_format)
399
- case collection_format
400
- when :csv
401
- param.join(',')
402
- when :ssv
403
- param.join(' ')
404
- when :tsv
405
- param.join("\t")
406
- when :pipes
407
- param.join('|')
408
- when :multi
409
- # return the array directly as faraday will handle it as expected
410
- param
411
- else
412
- fail "unknown collection format: #{collection_format.inspect}"
413
- end
414
- end
415
-
416
- # Request access and refresh tokens if needed
417
- def request_token_if_needed
418
- # check token exists
419
- if @config.access_token
1
+ =begin
2
+ --------------------------------------------------------------------------------------------------------------------
3
+ Copyright (c) 2020 Aspose.Cells Cloud
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
+ SOFTWARE.
19
+ --------------------------------------------------------------------------------------------------------------------
20
+
21
+ =end
22
+
23
+ require 'date'
24
+ require 'json'
25
+ require 'logger'
26
+ require 'tempfile'
27
+ require 'uri'
28
+ require 'faraday'
29
+ require_relative 'version'
30
+ require_relative 'api_error'
31
+
32
+ module AsposeCellsCloud
33
+ class ApiClient
34
+ # The Configuration object holding settings to be used in the API client.
35
+ attr_accessor :config
36
+
37
+ # Defines the headers to be used in HTTP requests of all API calls by default.
38
+ #
39
+ # @return [Hash]
40
+ attr_accessor :default_headers
41
+
42
+ attr_accessor :get_access_token_time
43
+ # Initializes the ApiClient
44
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
45
+ def initialize(config = Configuration.default)
46
+ @config = config
47
+
48
+ @default_headers = {
49
+ 'Content-Type' => "application/json",
50
+ 'x-aspose-client' => "ruby sdk",
51
+ 'x-aspose-version' => "#{ AsposeCellsCloud::VERSION }"
52
+ }
53
+ end
54
+
55
+ def self.default
56
+ @@default ||= ApiClient.new
57
+ end
58
+
59
+ # Call an API with given options.
60
+ #
61
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
62
+ # the data deserialized from response body (could be nil), response status code and response headers.
63
+ def call_api(http_method, path, opts = {})
64
+ response = build_request(http_method, path, opts)
65
+ download_file response if opts[:return_type] == 'File'
66
+
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
+
73
+ if response.status == 0
74
+ # Errors from libcurl will be made visible here
75
+ fail ApiError.new(:code => 0,
76
+ :message => response.reason_phrase)
77
+ else
78
+ fail ApiError.new(:code => response.status,
79
+ :response_headers => response.headers,
80
+ :response_body => response.body),
81
+ response.reason_phrase
82
+ end
83
+ end
84
+
85
+ if opts[:return_type]
86
+ data = deserialize(response, opts[:return_type])
87
+ else
88
+ data = nil
89
+ end
90
+ [data, response.status, response.headers]
91
+ end
92
+
93
+ # Builds the HTTP request
94
+ #
95
+ # @param [String] http_method HTTP method/verb (e.g. POST)
96
+ # @param [String] path URL path (e.g. /account/new)
97
+ # @option opts [Hash] :header_params Header parameters
98
+ # @option opts [Hash] :query_params Query parameters
99
+ # @option opts [Hash] :form_params Query parameters
100
+ # @option opts [Object] :body HTTP body (JSON/XML)
101
+ # @return [Faraday::Response] A Faraday Response
102
+ def build_request(http_method, path, opts = {})
103
+ url = build_request_url(path)
104
+ http_method = http_method.to_sym.downcase
105
+
106
+ header_params = @default_headers.merge(opts[:header_params] || {})
107
+ query_params = opts[:query_params] || {}
108
+ form_params = opts[:form_params] || {}
109
+ body = opts[:body] || {}
110
+
111
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
112
+
113
+ req_opts = {
114
+ :method => http_method,
115
+ :headers => header_params,
116
+ :params => query_params,
117
+ :body => body
118
+ }
119
+
120
+ if [:post, :patch, :put, :delete].include?(http_method)
121
+ req_body = build_request_body(header_params, form_params, opts[:body])
122
+ req_opts.update :body => req_body
123
+ if @config.debugging
124
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
125
+ end
126
+ end
127
+
128
+ # OAuth 2.0
129
+ req_opts[:params] = opts[:query_params]
130
+
131
+ add_o_auth_token(req_opts)
132
+
133
+ conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
134
+ f.request :multipart
135
+ f.request :url_encoded
136
+ f.adapter Faraday.default_adapter
137
+ end
138
+
139
+ if req_opts[:body] == {}
140
+ req_opts[:body] = nil
141
+ end
142
+
143
+ case http_method
144
+ when :post
145
+ return conn.post url, req_opts[:body]
146
+ when :put
147
+ return conn.put url, req_opts[:body]
148
+ when :get
149
+ return conn.get url, req_opts[:body]
150
+ else
151
+ return conn.delete url do |c|
152
+ c.body = req_opts[:body]
153
+ end
154
+ end
155
+ end
156
+
157
+ # Check if the given MIME is a JSON MIME.
158
+ # JSON MIME examples:
159
+ # application/json
160
+ # application/json; charset=UTF8
161
+ # APPLICATION/JSON
162
+ # */*
163
+ # @param [String] mime MIME
164
+ # @return [Boolean] True if the MIME is application/json
165
+ def json_mime?(mime)
166
+ (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
167
+ end
168
+
169
+ # Deserialize the response to the given return type.
170
+ #
171
+ # @param [Response] response HTTP response
172
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
173
+ def deserialize(response, return_type)
174
+ body = response.body
175
+
176
+ # handle file downloading - return the File instance processed in request callbacks
177
+ # note that response body is empty when the file is written in chunks in request on_body callback
178
+ return @tempfile if return_type == 'File'
179
+
180
+ return nil if body.nil? || body.empty?
181
+
182
+ # return response body directly for String return type
183
+ return body if return_type == 'String'
184
+
185
+ # ensuring a default content type
186
+ content_type = response.headers['Content-Type'] || 'application/json'
187
+
188
+ raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
189
+
190
+ begin
191
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
192
+ rescue JSON::ParserError => e
193
+ if %w(String Date DateTime).include?(return_type)
194
+ data = body
195
+ else
196
+ raise e
197
+ end
198
+ end
199
+
200
+ convert_to_type data, return_type
201
+ end
202
+
203
+ # Convert data to the given return type.
204
+ # @param [Object] data Data to be converted
205
+ # @param [String] return_type Return type
206
+ # @return [Mixed] Data in a particular type
207
+ def convert_to_type(data, return_type)
208
+ return nil if data.nil?
209
+ case return_type
210
+ when 'String'
211
+ data.to_s
212
+ when 'Integer'
213
+ data.to_i
214
+ when 'Float'
215
+ data.to_f
216
+ when 'BOOLEAN'
217
+ data == true
218
+ when 'DateTime'
219
+ # parse date time (expecting ISO 8601 format)
220
+ DateTime.parse data
221
+ when 'Date'
222
+ # parse date time (expecting ISO 8601 format)
223
+ Date.parse data
224
+ when 'Object'
225
+ # generic object (usually a Hash), return directly
226
+ data
227
+ when /\AArray<(.+)>\z/
228
+ # e.g. Array<Pet>
229
+ sub_type = $1
230
+ data.map {|item| convert_to_type(item, sub_type) }
231
+ when /\AHash\<String, (.+)\>\z/
232
+ # e.g. Hash<String, Integer>
233
+ sub_type = $1
234
+ {}.tap do |hash|
235
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
236
+ end
237
+ else
238
+ # models, e.g. Pet
239
+ AsposeCellsCloud.const_get(return_type).new.tap do |model|
240
+ model.build_from_hash data
241
+ end
242
+ end
243
+ end
244
+
245
+ # Save response body into a file in (the defined) temporary folder, using the filename
246
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
247
+ # The response body is written to the file in chunks in order to handle files which
248
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
249
+ # process can use.
250
+ #
251
+ # @see Configuration#temp_folder_path
252
+ def download_file(response)
253
+ tempfile = nil
254
+ encoding = nil
255
+
256
+ content_disposition = response.headers['Content-Disposition']
257
+ if content_disposition and content_disposition =~ /filename=/i
258
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
259
+ prefix = sanitize_filename(filename)
260
+ else
261
+ prefix = 'download-'
262
+ end
263
+ prefix = prefix + '-' unless prefix.end_with?('-')
264
+ encoding = response.body.encoding
265
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
266
+ @tempfile = tempfile
267
+
268
+ tempfile.write(response.body)
269
+
270
+ response.on_complete do |resp|
271
+ tempfile.close
272
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
273
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
274
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
275
+ "explicitly with `tempfile.delete`"
276
+ end
277
+ end
278
+
279
+ # Sanitize filename by removing path.
280
+ # e.g. ../../sun.gif becomes sun.gif
281
+ #
282
+ # @param [String] filename the filename to be sanitized
283
+ # @return [String] the sanitized filename
284
+ def sanitize_filename(filename)
285
+ filename.gsub(/.*[\/\\]/, '')
286
+ end
287
+
288
+ def build_request_url(path)
289
+ # Add leading and trailing slashes to path
290
+ path = "/#{path}".gsub(/\/+/, '/')
291
+ URI.encode(@config.base_url + path)
292
+ end
293
+
294
+ # Builds the HTTP request body
295
+ #
296
+ # @param [Hash] header_params Header parameters
297
+ # @param [Hash] form_params Query parameters
298
+ # @param [Object] body HTTP body (JSON/XML)
299
+ # @return [String] HTTP body data in the form of string
300
+ def build_request_body(header_params, form_params, body)
301
+ # http form
302
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
303
+ header_params['Content-Type'] == 'multipart/form-data'
304
+ data = {}
305
+ form_params.each do |key, value|
306
+ case value
307
+ when ::File
308
+ data[key] = Faraday::UploadIO.new(value.path, MimeMagic.by_magic(value).to_s, key)
309
+ when ::Array, nil
310
+ # let typhoeus handle File, Array and nil parameters
311
+ data[key] = value
312
+ else
313
+ data[key] = value.to_s
314
+ end
315
+ end
316
+ elsif body
317
+ data = body.is_a?(String) ? body : body.to_json
318
+ else
319
+ data = nil
320
+ end
321
+ data
322
+ end
323
+
324
+ # Update hearder and query params based on authentication settings.
325
+ #
326
+ # @param [Hash] header_params Header parameters
327
+ # @param [Hash] query_params Query parameters
328
+ # @param [String] auth_names Authentication scheme name
329
+ def update_params_for_auth!(header_params, query_params, auth_names)
330
+ Array(auth_names).each do |auth_name|
331
+ auth_setting = @config.auth_settings[auth_name]
332
+ next unless auth_setting
333
+ case auth_setting[:in]
334
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
335
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
336
+ else raise ArgumentError, 'Authentication token must be in `query` of `header`'
337
+ end
338
+ end
339
+ end
340
+
341
+ # Sets user agent in HTTP header
342
+ #
343
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
344
+ def user_agent=(user_agent)
345
+ @user_agent = user_agent
346
+ @default_headers['User-Agent'] = @user_agent
347
+ end
348
+
349
+ # Return Accept header based on an array of accepts provided.
350
+ # @param [Array] accepts array for Accept
351
+ # @return [String] the Accept header (e.g. application/json)
352
+ def select_header_accept(accepts)
353
+ return nil if accepts.nil? || accepts.empty?
354
+ # use JSON when present, otherwise use all of the provided
355
+ json_accept = accepts.find { |s| json_mime?(s) }
356
+ return json_accept || accepts.join(',')
357
+ end
358
+
359
+ # Return Content-Type header based on an array of content types provided.
360
+ # @param [Array] content_types array for Content-Type
361
+ # @return [String] the Content-Type header (e.g. application/json)
362
+ def select_header_content_type(content_types)
363
+ # use application/json by default
364
+ return 'application/json' if content_types.nil? || content_types.empty?
365
+ # use JSON when present, otherwise use the first one
366
+ json_content_type = content_types.find { |s| json_mime?(s) }
367
+ return json_content_type || content_types.first
368
+ end
369
+
370
+ # Convert object (array, hash, object, etc) to JSON string.
371
+ # @param [Object] model object to be converted into JSON string
372
+ # @return [String] JSON string representation of the object
373
+ def object_to_http_body(model)
374
+ return '"' + model + '"' if model.is_a?(String)
375
+ return model if model.nil?
376
+ local_body = nil
377
+ if model.is_a?(Array)
378
+ local_body = model.map{|m| object_to_hash(m) }
379
+ else
380
+ local_body = object_to_hash(model)
381
+ end
382
+ local_body.to_json
383
+ end
384
+
385
+ # Convert object(non-array) to hash.
386
+ # @param [Object] obj object to be converted into JSON string
387
+ # @return [String] JSON string representation of the object
388
+ def object_to_hash(obj)
389
+ if obj.respond_to?(:to_hash)
390
+ obj.to_hash
391
+ else
392
+ obj
393
+ end
394
+ end
395
+
396
+ # Build parameter value according to the given collection format.
397
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
398
+ def build_collection_param(param, collection_format)
399
+ case collection_format
400
+ when :csv
401
+ param.join(',')
402
+ when :ssv
403
+ param.join(' ')
404
+ when :tsv
405
+ param.join("\t")
406
+ when :pipes
407
+ param.join('|')
408
+ when :multi
409
+ # return the array directly as faraday will handle it as expected
410
+ param
411
+ else
412
+ fail "unknown collection format: #{collection_format.inspect}"
413
+ end
414
+ end
415
+
416
+ # Request access and refresh tokens if needed
417
+ def request_token_if_needed
418
+
419
+ # check token exists
420
+ if @config.access_token
420
421
  now = Time.now
421
422
  time_difference = now - $get_access_token_time
422
423
  if time_difference < 86300
423
424
  return
424
425
  end
425
- end
426
-
427
- # resource path
428
- local_var_path = "/connect/token"
429
- if @config.api_version === "v1.1"
430
- local_var_path ="/oauth2/token"
431
- end
432
- url = build_request_url(local_var_path).gsub('/'+config.api_version, '')
433
- #url = build_request_url(local_var_path).gsub('/v3.0', '')
434
-
435
- # header parameters
436
- header_params = {}
437
- # HTTP header 'Content-Type'
438
- header_params['Content-Type'] = select_header_content_type(['application/x-www-form-urlencoded'])
439
-
440
- query_params = {}
441
- # form parameters
442
- form_params = {}
443
- form_params["grant_type"] = 'client_credentials'
444
- form_params["client_id"] = @config.app_sid
445
- form_params["client_secret"] = @config.app_key
446
-
447
- body = {}
448
-
449
-
450
- req_opts = {
451
- :headers => header_params,
452
- :params => query_params,
453
- :body => body
454
- }
455
-
456
-
457
- req_body = build_request_body(header_params, form_params, body)
458
- req_opts.update :body => req_body
459
-
460
- req_opts[:params] = query_params
461
-
462
-
463
- conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
464
- f.request :multipart
465
- f.request :url_encoded
466
- f.adapter Faraday.default_adapter
467
- end
468
-
469
- if req_opts[:body] == {}
470
- req_opts[:body] = nil
471
- end
472
-
473
-
474
- response = conn.post url, form_params, req_opts[:body]
475
- data = JSON.parse("[#{response.body}]", :symbolize_names => true)[0]
476
-
477
- @config.access_token = data[:access_token]
478
-
479
- $get_access_token_time = Time.now
480
- end
481
-
482
- # Adds OAuth2.0 token
483
- def add_o_auth_token(req_opts)
484
- req_opts[:headers][:Authorization] = "Bearer " + @config.access_token
485
- end
486
-
487
- end
488
- end
426
+ end
427
+
428
+ # resource path
429
+ local_var_path = "/connect/token"
430
+ if @config.api_version === "v1.1"
431
+ local_var_path ="/oauth2/token"
432
+ end
433
+ url = build_request_url(local_var_path).gsub('/'+config.api_version, '')
434
+ #url = build_request_url(local_var_path).gsub('/v3.0', '')
435
+
436
+ # header parameters
437
+ header_params = {}
438
+ # HTTP header 'Content-Type'
439
+ header_params['Content-Type'] = select_header_content_type(['application/x-www-form-urlencoded'])
440
+
441
+ query_params = {}
442
+ # form parameters
443
+ form_params = {}
444
+ form_params["grant_type"] = 'client_credentials'
445
+ form_params["client_id"] = @config.app_sid
446
+ form_params["client_secret"] = @config.app_key
447
+
448
+ body = {}
449
+
450
+
451
+ req_opts = {
452
+ :headers => header_params,
453
+ :params => query_params,
454
+ :body => body
455
+ }
456
+
457
+
458
+ req_body = build_request_body(header_params, form_params, body)
459
+ req_opts.update :body => req_body
460
+
461
+ req_opts[:params] = query_params
462
+
463
+
464
+ conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
465
+ f.request :multipart
466
+ f.request :url_encoded
467
+ f.adapter Faraday.default_adapter
468
+ end
469
+
470
+ if req_opts[:body] == {}
471
+ req_opts[:body] = nil
472
+ end
473
+
474
+
475
+ response = conn.post url, form_params, req_opts[:body]
476
+ data = JSON.parse("[#{response.body}]", :symbolize_names => true)[0]
477
+
478
+ @config.access_token = data[:access_token]
479
+
480
+ $get_access_token_time = Time.now
481
+ end
482
+
483
+ # Adds OAuth2.0 token
484
+ def add_o_auth_token(req_opts)
485
+ req_opts[:headers][:Authorization] = "Bearer " + @config.access_token
486
+ end
487
+
488
+ end
489
+ end