aspose_html 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +12 -0
  3. data/Gemfile.lock +92 -0
  4. data/LICENSE +21 -0
  5. data/README.md +181 -0
  6. data/Rakefile +8 -0
  7. data/aspose_html.gemspec +58 -0
  8. data/docs/ConversionApi.md +837 -0
  9. data/docs/DocumentApi.md +386 -0
  10. data/docs/OcrApi.md +128 -0
  11. data/docs/SummarizationApi.md +111 -0
  12. data/docs/TranslationApi.md +126 -0
  13. data/docs/storage/DiscUsage.md +9 -0
  14. data/docs/storage/DiscUsageResponse.md +10 -0
  15. data/docs/storage/FileApi.md +240 -0
  16. data/docs/storage/FileDetail.md +13 -0
  17. data/docs/storage/FileDetailsResponse.md +10 -0
  18. data/docs/storage/FileExist.md +9 -0
  19. data/docs/storage/FileExistResponse.md +10 -0
  20. data/docs/storage/FileVersion.md +15 -0
  21. data/docs/storage/FileVersionsResponse.md +10 -0
  22. data/docs/storage/FolderApi.md +229 -0
  23. data/docs/storage/MessageResponse.md +9 -0
  24. data/docs/storage/MoveFileResponse.md +9 -0
  25. data/docs/storage/MoveFolderResponse.md +9 -0
  26. data/docs/storage/RemoveFileResponse.md +9 -0
  27. data/docs/storage/RemoveFolderResponse.md +9 -0
  28. data/docs/storage/StorageApi.md +217 -0
  29. data/docs/storage/StorageExistResponse.md +10 -0
  30. data/lib/aspose_html.rb +68 -0
  31. data/lib/aspose_html/api/html_api.rb +1900 -0
  32. data/lib/aspose_html/api/storage_api.rb +774 -0
  33. data/lib/aspose_html/api_client.rb +386 -0
  34. data/lib/aspose_html/api_error.rb +54 -0
  35. data/lib/aspose_html/configuration.rb +175 -0
  36. data/lib/aspose_html/models/disc_usage.rb +223 -0
  37. data/lib/aspose_html/models/disc_usage_response.rb +260 -0
  38. data/lib/aspose_html/models/file_detail.rb +254 -0
  39. data/lib/aspose_html/models/file_details_response.rb +262 -0
  40. data/lib/aspose_html/models/file_exist.rb +223 -0
  41. data/lib/aspose_html/models/file_exist_response.rb +274 -0
  42. data/lib/aspose_html/models/file_version.rb +273 -0
  43. data/lib/aspose_html/models/file_versions_response.rb +262 -0
  44. data/lib/aspose_html/models/message_response.rb +251 -0
  45. data/lib/aspose_html/models/move_file_response.rb +251 -0
  46. data/lib/aspose_html/models/move_folder_response.rb +251 -0
  47. data/lib/aspose_html/models/remove_file_response.rb +251 -0
  48. data/lib/aspose_html/models/remove_folder_response.rb +251 -0
  49. data/lib/aspose_html/models/storage_exist_response.rb +260 -0
  50. data/lib/aspose_html/version.rb +31 -0
  51. data/spec/api/html_api_spec.rb +971 -0
  52. data/spec/api/model_spec.rb +622 -0
  53. data/spec/api/storage_api_spec.rb +596 -0
  54. data/spec/spec_helper.rb +169 -0
  55. data/testdata/test.txt +1 -0
  56. data/testdata/test1.html +19 -0
  57. data/testdata/test1.html.zip +0 -0
  58. data/testdata/test2.html +46 -0
  59. data/testdata/test2.html.zip +0 -0
  60. data/testdata/test3.html.zip +0 -0
  61. data/testdata/test4.html.zip +0 -0
  62. data/testdata/test_download.jpg +0 -0
  63. data/testdata/test_en.html +46 -0
  64. data/testdata/test_for_delete.html +46 -0
  65. data/testdata/test_for_move.html +46 -0
  66. data/testdata/test_get_doc.zip +0 -0
  67. data/testdata/test_ocr.jpg +0 -0
  68. data/testdata/test_ocr.png +0 -0
  69. data/testdata/test_put_create.html +19 -0
  70. data/testdata/test_put_create.jpg +0 -0
  71. data/testresult/Convert_html.bmp +0 -0
  72. data/testresult/Convert_html.pdf +0 -0
  73. data/testresult/Convert_html.xps +0 -0
  74. data/testresult/Convert_url.pdf +0 -0
  75. data/testresult/Convert_url.png +0 -0
  76. data/testresult/Convert_url.xps +0 -0
  77. data/testresult/Get_document.zip +0 -0
  78. data/testresult/Get_fragment_css_by_url.html +447 -0
  79. data/testresult/Get_fragment_doc.html +9 -0
  80. data/testresult/Get_fragment_doc_css.html +9 -0
  81. data/testresult/Get_fragment_xpath_by_url.html +38 -0
  82. data/testresult/Get_images_doc.zip +0 -0
  83. data/testresult/Get_images_from_url.zip +0 -0
  84. data/testresult/Keyword_by_doc.json +1 -0
  85. data/testresult/Keyword_by_url.json +1 -0
  86. data/testresult/Recognize_en_png.html +10 -0
  87. data/testresult/Translate_url_en_fr.zip +0 -0
  88. data/testresult/putTest.pdf +0 -0
  89. data/testresult/putTest.png +0 -0
  90. data/testresult/putTest.xps +0 -0
  91. data/testresult/putTestDoc.pdf +0 -0
  92. data/testresult/putTestDoc.tiff +0 -0
  93. data/testresult/putTestDoc.xps +0 -0
  94. data/testresult/test_download.jpg +0 -0
  95. metadata +320 -0
@@ -0,0 +1,386 @@
1
+ # -*- coding: utf-8 -*-
2
+ =begin
3
+ --------------------------------------------------------------------------------------------------------------------
4
+ <copyright company="Aspose" file="aspose_html.rb">
5
+ </copyright>
6
+ Copyright (c) 2018 Aspose.HTML for Cloud
7
+ <summary>
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
25
+ </summary>
26
+ --------------------------------------------------------------------------------------------------------------------
27
+ =end
28
+
29
+ require 'date'
30
+ require 'json'
31
+ require 'logger'
32
+ require 'tempfile'
33
+ require 'typhoeus'
34
+ require 'uri'
35
+
36
+
37
+ module AsposeHtml
38
+ class ApiClient
39
+ # The Configuration object holding settings to be used in the API client.
40
+ attr_accessor :config
41
+
42
+ # Defines the headers to be used in HTTP requests of all API calls by default.
43
+ #
44
+ # @return [Hash]
45
+ attr_accessor :default_headers
46
+
47
+ # Initializes the ApiClient
48
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
49
+ def initialize(config)
50
+ @config = config
51
+ @user_agent = "Aspose SDK"
52
+ @default_headers = {
53
+ 'Content-Type' => "application/json",
54
+ 'User-Agent' => @user_agent,
55
+ 'Authorization' => "Bearer #{@config.access_token}"
56
+ }
57
+ end
58
+
59
+ def self.default(args)
60
+ @@default ||= ApiClient.new(Configuration.new(args))
61
+ end
62
+
63
+ # Call an API with given options.
64
+ #
65
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
66
+ # the data deserialized from response body (could be nil), response status code and response headers.
67
+ def call_api(http_method, path, opts = {})
68
+ request = build_request(http_method, path, opts)
69
+ response = request.run
70
+
71
+ if @config.debug
72
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
73
+ end
74
+
75
+ unless response.success?
76
+ if response.timed_out?
77
+ fail ApiError.new('Connection timed out')
78
+ elsif response.code == 0
79
+ # Errors from libcurl will be made visible here
80
+ fail ApiError.new(:code => 0,
81
+ :message => response.return_message)
82
+ else
83
+ fail ApiError.new(:code => response.code,
84
+ :response_headers => response.headers,
85
+ :response_body => response.body),
86
+ response.status_message
87
+ end
88
+ end
89
+
90
+ if opts[:return_type]
91
+ data = deserialize(response, opts[:return_type])
92
+ else
93
+ data = nil
94
+ end
95
+ return data, response.code, response.headers
96
+ end
97
+
98
+ # Builds the HTTP request
99
+ #
100
+ # @param [String] http_method HTTP method/verb (e.g. POST)
101
+ # @param [String] path URL path (e.g. /account/new)
102
+ # @option opts [Hash] :header_params Header parameters
103
+ # @option opts [Hash] :query_params Query parameters
104
+ # @option opts [Hash] :form_params Query parameters
105
+ # @option opts [Object] :body HTTP body (JSON/XML)
106
+ # @return [Typhoeus::Request] A Typhoeus Request
107
+ def build_request(http_method, path, opts = {})
108
+ url = build_request_url(path)
109
+ http_method = http_method.to_sym.downcase
110
+
111
+ header_params = @default_headers.merge(opts[:header_params] || {})
112
+ query_params = opts[:query_params] || {}
113
+ form_params = opts[:form_params] || {}
114
+
115
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
116
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
117
+
118
+ req_opts = {
119
+ :method => http_method,
120
+ :headers => header_params,
121
+ :params => query_params,
122
+ :params_encoding => @config.params_encoding,
123
+ :timeout => @config.timeout,
124
+ :ssl_verifypeer => @config.verify_ssl,
125
+ :ssl_verifyhost => _verify_ssl_host,
126
+ :sslcert => @config.cert_file,
127
+ :sslkey => @config.key_file,
128
+ :verbose => @config.debug
129
+ }
130
+
131
+ # set custom cert, if provided
132
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
133
+
134
+ if [:post, :patch, :put, :delete].include?(http_method)
135
+ req_body = build_request_body(header_params, form_params, opts[:body])
136
+ req_opts.update :body => req_body
137
+ if @config.debug
138
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
139
+ end
140
+ end
141
+
142
+ request = Typhoeus::Request.new(url, req_opts)
143
+ download_file(request) if opts[:return_type] == 'File'
144
+ request
145
+ end
146
+
147
+ # Check if the given MIME is a JSON MIME.
148
+ # JSON MIME examples:
149
+ # application/json
150
+ # application/json; charset=UTF8
151
+ # APPLICATION/JSON
152
+ # */*
153
+ # @param [String] mime MIME
154
+ # @return [Boolean] True if the MIME is application/json
155
+ def json_mime?(mime)
156
+ (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
157
+ end
158
+
159
+ # Deserialize the response to the given return type.
160
+ #
161
+ # @param [Response] response HTTP response
162
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
163
+ def deserialize(response, return_type)
164
+ body = response.body
165
+
166
+ # handle file downloading - return the File instance processed in request callbacks
167
+ # note that response body is empty when the file is written in chunks in request on_body callback
168
+ return @tempfile if return_type == 'File'
169
+
170
+ return nil if body.nil? || body.empty?
171
+
172
+ # return response body directly for String return type
173
+ return body if return_type == 'String'
174
+
175
+ # ensuring a default content type
176
+ content_type = response.headers['Content-Type'] || 'application/json'
177
+
178
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
179
+
180
+ begin
181
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
182
+ rescue JSON::ParserError => e
183
+ if %w(String Date DateTime).include?(return_type)
184
+ data = body
185
+ else
186
+ raise e
187
+ end
188
+ end
189
+
190
+ convert_to_type data, return_type
191
+ end
192
+
193
+ # Convert data to the given return type.
194
+ # @param [Object] data Data to be converted
195
+ # @param [String] return_type Return type
196
+ # @return [Mixed] Data in a particular type
197
+ def convert_to_type(data, return_type)
198
+ return nil if data.nil?
199
+ case return_type
200
+ when 'String'
201
+ data.to_s
202
+ when 'Integer'
203
+ data.to_i
204
+ when 'Float'
205
+ data.to_f
206
+ when 'BOOLEAN'
207
+ data == true
208
+ when 'DateTime'
209
+ # parse date time (expecting ISO 8601 format)
210
+ DateTime.parse data
211
+ when 'Date'
212
+ # parse date time (expecting ISO 8601 format)
213
+ Date.parse data
214
+ when 'Object'
215
+ # generic object (usually a Hash), return directly
216
+ data
217
+ when /\AArray<(.+)>\z/
218
+ # e.g. Array<Pet>
219
+ sub_type = $1
220
+ data.map {|item| convert_to_type(item, sub_type) }
221
+ when /\AHash\<String, (.+)\>\z/
222
+ # e.g. Hash<String, Integer>
223
+ sub_type = $1
224
+ {}.tap do |hash|
225
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
226
+ end
227
+ else
228
+ # models
229
+ AsposeHtml.const_get(return_type).new.tap do |model|
230
+ model.build_from_hash data
231
+ end
232
+ end
233
+ end
234
+
235
+ # Save response body into a file in (the defined) temporary folder, using the filename
236
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
237
+ # The response body is written to the file in chunks in order to handle files which
238
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
239
+ # process can use.
240
+ #
241
+ # @see Configuration#temp_folder_path
242
+ def download_file(request)
243
+ tempfile = nil
244
+ encoding = nil
245
+ request.on_headers do |response|
246
+ content_disposition = response.headers['Content-Disposition']
247
+ if content_disposition and content_disposition =~ /filename=/i
248
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
249
+ prefix = sanitize_filename(filename)
250
+ else
251
+ prefix = 'download'
252
+ end
253
+ tempfile = File.open(@config.temp_folder_path + "/" + prefix, "wb")
254
+ @tempfile = tempfile
255
+ end
256
+ request.on_body do |chunk|
257
+ tempfile.write(chunk)
258
+ end
259
+ request.on_complete do |response|
260
+ tempfile.close
261
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
262
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
263
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
264
+ "explicitly with `tempfile.delete`"
265
+ end
266
+ end
267
+
268
+ # Sanitize filename by removing path.
269
+ # e.g. ../../sun.gif becomes sun.gif
270
+ #
271
+ # @param [String] filename the filename to be sanitized
272
+ # @return [String] the sanitized filename
273
+ def sanitize_filename(filename)
274
+ filename.gsub(/.*[\/\\]/, '')
275
+ end
276
+
277
+ def build_request_url(path)
278
+ # Add leading and trailing slashes to path
279
+ path = "/#{path}".gsub(/\/+/, '/')
280
+ URI.encode(@config.base_url + path)
281
+ end
282
+
283
+ # Builds the HTTP request body
284
+ #
285
+ # @param [Hash] header_params Header parameters
286
+ # @param [Hash] form_params Query parameters
287
+ # @param [Object] body HTTP body (JSON/XML)
288
+ # @return [String] HTTP body data in the form of string
289
+ def build_request_body(header_params, form_params, body)
290
+ # http form
291
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
292
+ header_params['Content-Type'] == 'multipart/form-data'
293
+ data = {}
294
+ form_params.each do |key, value|
295
+ case value
296
+ when ::File, ::Array, nil
297
+ # let typhoeus handle File, Array and nil parameters
298
+ data[key] = value
299
+ else
300
+ data[key] = value.to_s
301
+ end
302
+ end
303
+ elsif body
304
+ data = body.is_a?(String) ? body : body.to_json
305
+ else
306
+ data = nil
307
+ end
308
+ data
309
+ end
310
+
311
+ # Sets user agent in HTTP header
312
+ #
313
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
314
+ def user_agent=(user_agent)
315
+ @user_agent = user_agent
316
+ @default_headers['User-Agent'] = @user_agent
317
+ end
318
+
319
+ # Return Accept header based on an array of accepts provided.
320
+ # @param [Array] accepts array for Accept
321
+ # @return [String] the Accept header (e.g. application/json)
322
+ def select_header_accept(accepts)
323
+ return nil if accepts.nil? || accepts.empty?
324
+ # use JSON when present, otherwise use all of the provided
325
+ json_accept = accepts.find { |s| json_mime?(s) }
326
+ return json_accept || accepts.join(',')
327
+ end
328
+
329
+ # Return Content-Type header based on an array of content types provided.
330
+ # @param [Array] content_types array for Content-Type
331
+ # @return [String] the Content-Type header (e.g. application/json)
332
+ def select_header_content_type(content_types)
333
+ # use application/json by default
334
+ return 'application/json' if content_types.nil? || content_types.empty?
335
+ # use JSON when present, otherwise use the first one
336
+ json_content_type = content_types.find { |s| json_mime?(s) }
337
+ return json_content_type || content_types.first
338
+ end
339
+
340
+ # Convert object (array, hash, object, etc) to JSON string.
341
+ # @param [Object] model object to be converted into JSON string
342
+ # @return [String] JSON string representation of the object
343
+ def object_to_http_body(model)
344
+ return model if model.nil? || model.is_a?(String)
345
+ local_body = nil
346
+ if model.is_a?(Array)
347
+ local_body = model.map{|m| object_to_hash(m) }
348
+ else
349
+ local_body = object_to_hash(model)
350
+ end
351
+ local_body.to_json
352
+ end
353
+
354
+ # Convert object(non-array) to hash.
355
+ # @param [Object] obj object to be converted into JSON string
356
+ # @return [String] JSON string representation of the object
357
+ def object_to_hash(obj)
358
+ if obj.respond_to?(:to_hash)
359
+ obj.to_hash
360
+ else
361
+ obj
362
+ end
363
+ end
364
+
365
+ # Build parameter value according to the given collection format.
366
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
367
+ def build_collection_param(param, collection_format)
368
+ case collection_format
369
+ when :csv
370
+ param.join(',')
371
+ when :ssv
372
+ param.join(' ')
373
+ when :tsv
374
+ param.join("\t")
375
+ when :pipes
376
+ param.join('|')
377
+ when :multi
378
+ # return the array directly as typhoeus will handle it as expected
379
+ param
380
+ else
381
+ fail "unknown collection format: #{collection_format.inspect}"
382
+ end
383
+ end
384
+ end
385
+ end
386
+
@@ -0,0 +1,54 @@
1
+ # -*- coding: utf-8 -*-
2
+ =begin
3
+ --------------------------------------------------------------------------------------------------------------------
4
+ <copyright company="Aspose" file="api_error.rb">
5
+ </copyright>
6
+ Copyright (c) 2018 Aspose.HTML for Cloud
7
+ <summary>
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
25
+ </summary>
26
+ --------------------------------------------------------------------------------------------------------------------
27
+ =end
28
+
29
+ module AsposeHtml
30
+ class ApiError < StandardError
31
+ attr_reader :code, :response_headers, :response_body
32
+
33
+ # Usage examples:
34
+ # ApiError.new
35
+ # ApiError.new("message")
36
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
37
+ # ApiError.new(:code => 404, :message => "Not Found")
38
+ def initialize(arg = nil)
39
+ if arg.is_a? Hash
40
+ if arg.key?(:message) || arg.key?('message')
41
+ super(arg[:message] || arg['message'])
42
+ else
43
+ super arg
44
+ end
45
+
46
+ arg.each do |k, v|
47
+ instance_variable_set "@#{k}", v
48
+ end
49
+ else
50
+ super arg
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,175 @@
1
+ # -*- coding: utf-8 -*-
2
+ =begin
3
+ --------------------------------------------------------------------------------------------------------------------
4
+ <copyright company="Aspose" file="configuration.rb">
5
+ </copyright>
6
+ Copyright (c) 2018 Aspose.HTML for Cloud
7
+ <summary>
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
25
+ </summary>
26
+ --------------------------------------------------------------------------------------------------------------------
27
+ =end
28
+
29
+ require 'uri'
30
+ require 'tmpdir'
31
+ require 'json'
32
+ require 'typhoeus'
33
+
34
+
35
+ module AsposeHtml
36
+ class Configuration
37
+
38
+
39
+ # Defines the access token (Bearer) used with OAuth2.
40
+ attr_accessor :access_token
41
+
42
+ # Defines the logger used for debugging.
43
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
44
+ #
45
+ # @return [#debug]
46
+ attr_accessor :logger
47
+
48
+ # Defines the temporary folder to store downloaded files
49
+ # (for API endpoints that have file response).
50
+ # Default to use `Tempfile`.
51
+ #
52
+ # @return [String]
53
+ attr_accessor :temp_folder_path
54
+
55
+ # The time limit for HTTP request in seconds.
56
+ # Default to 0 (never times out).
57
+ attr_accessor :timeout
58
+
59
+ # Set this to false to skip client side validation in the operation.
60
+ # Default to true.
61
+ # @return [true, false]
62
+ attr_accessor :client_side_validation
63
+
64
+ ### TLS/SSL setting
65
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
66
+ # Default to true.
67
+ #
68
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
69
+ #
70
+ # @return [true, false]
71
+ attr_accessor :verify_ssl
72
+
73
+ ### TLS/SSL setting
74
+ # Set this to false to skip verifying SSL host name
75
+ # Default to true.
76
+ #
77
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
78
+ #
79
+ # @return [true, false]
80
+ attr_accessor :verify_ssl_host
81
+
82
+ ### TLS/SSL setting
83
+ # Set this to customize the certificate file to verify the peer.
84
+ #
85
+ # @return [String] the path to the certificate file
86
+ #
87
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
88
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
89
+ attr_accessor :ssl_ca_cert
90
+
91
+ ### TLS/SSL setting
92
+ # Client certificate file (for client certificate)
93
+ attr_accessor :cert_file
94
+
95
+ ### TLS/SSL setting
96
+ # Client private key file (for client certificate)
97
+ attr_accessor :key_file
98
+
99
+ # Set this to customize parameters encoding of array parameter with multi collectionFormat.
100
+ # Default to nil.
101
+ #
102
+ # @see The params_encoding option of Ethon. Related source code:
103
+ # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
104
+ attr_accessor :params_encoding
105
+
106
+ attr_accessor :inject_format
107
+
108
+ attr_accessor :force_ending_format
109
+
110
+ def initialize(params)
111
+ self.class.class_eval {attr_accessor *params.keys}
112
+ params.each {|key,value| send("#{key}=",value)}
113
+
114
+ @timeout = 0
115
+ @temp_folder_path = Dir.tmpdir()
116
+ @access_token = req_token
117
+ @client_side_validation = true
118
+ @verify_ssl = true
119
+ @verify_ssl_host = true
120
+ @params_encoding = nil
121
+ @cert_file = nil
122
+ @key_file = nil
123
+ @inject_format = false
124
+ @force_ending_format = false
125
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
126
+
127
+ yield(self) if block_given?
128
+ end
129
+
130
+ # The default Configuration object.
131
+ def self.default(args)
132
+ @@default ||= Configuration.new(args)
133
+ end
134
+
135
+ def configure
136
+ yield(self) if block_given?
137
+ end
138
+
139
+ def base_url
140
+ url = @basePath
141
+ URI.encode(url)
142
+ end
143
+
144
+ # Request token
145
+ def req_token
146
+ tries = 0
147
+ begin
148
+ Typhoeus::Config.user_agent = "Aspose SDK"
149
+ tries += 1
150
+ response = Typhoeus::Request.new(@authPath,
151
+ method: :post,
152
+ body: {grant_type: "client_credentials",
153
+ client_id: @appSID,
154
+ client_secret: @apiKey
155
+ },
156
+ headers: {Accept: "application/json",
157
+ ContentType: "application/x-www-form-urlencoded"
158
+ },
159
+ verbose: @debug
160
+ ).run
161
+ hash = JSON.parse(response.body, symbolize_names: true)
162
+ hash[:access_token]
163
+ rescue => ex
164
+ puts "#{ex.class}: #{ex.message}"
165
+ puts "Try connect - #{tries}"
166
+ if (tries<5)
167
+ sleep(2**tries)
168
+ retry
169
+ end
170
+ raise "Can not connect to server #{@authPath}"
171
+ end
172
+ end
173
+ end
174
+ end
175
+