aspose_email_cloud 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,335 @@
1
+ require 'date'
2
+ require 'json'
3
+ require 'logger'
4
+ require 'tempfile'
5
+ require 'typhoeus'
6
+ require 'uri'
7
+ require 'openssl'
8
+ require 'base64'
9
+ require 'rexml/document'
10
+
11
+ module AsposeEmailCloud
12
+ class ApiClient
13
+
14
+ include AsposeStorageCloud
15
+
16
+ attr_accessor :host
17
+
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
+
23
+ # Stores the HTTP response from the last API call using this API client.
24
+ attr_accessor :last_response
25
+
26
+ def initialize(host = nil)
27
+ @host = host || Configuration.base_url
28
+ @format = 'json'
29
+ @user_agent = "ruby-swagger-#{VERSION}"
30
+ @default_headers = {
31
+ 'Content-Type' => "application/#{@format.downcase}",
32
+ 'User-Agent' => @user_agent
33
+ }
34
+ end
35
+
36
+ def call_api(http_method, path, opts = {})
37
+ request = build_request(http_method, path, opts)
38
+ response = request.run
39
+
40
+ # record as last response
41
+ @last_response = response
42
+
43
+ if Configuration.debugging
44
+ Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
45
+ end
46
+
47
+ unless response.success?
48
+ fail ApiError.new(:code => response.code,
49
+ :response_headers => response.headers,
50
+ :response_body => response.body),
51
+ response.status_message
52
+ end
53
+
54
+ if opts[:return_type]
55
+ deserialize(response, opts[:return_type])
56
+ else
57
+ nil
58
+ end
59
+ end
60
+
61
+ def build_request(http_method, path, opts = {})
62
+ url = build_request_url(path)
63
+ http_method = http_method.to_sym.downcase
64
+
65
+ header_params = @default_headers.merge(opts[:header_params] || {})
66
+ query_params = {}
67
+ form_params = opts[:form_params] || {}
68
+
69
+ req_opts = {
70
+ :method => http_method,
71
+ :headers => header_params,
72
+ :params => query_params,
73
+ :ssl_verifypeer => Configuration.verify_ssl,
74
+ :sslcert => Configuration.cert_file,
75
+ :sslkey => Configuration.key_file,
76
+ :cainfo => Configuration.ssl_ca_cert,
77
+ :verbose => Configuration.debugging
78
+ }
79
+
80
+ if [:post, :patch, :put, :delete].include?(http_method)
81
+ req_body = build_request_body(header_params, form_params, opts[:body])
82
+ req_opts.update :body => req_body
83
+ if Configuration.debugging
84
+ Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
85
+ end
86
+ end
87
+
88
+ url = sign(url, opts[:query_params])
89
+ Typhoeus::Request.new(url, req_opts)
90
+
91
+ end
92
+
93
+ # Signs a URI with your appSID and Key.
94
+ # * :url describes the URL to sign
95
+
96
+ def sign(url, query_params)
97
+
98
+ fail "Please set Aspose App key and SID first. You can get App key and App SID from https://cloud.aspose.com" if AsposeApp.app_key.nil? || AsposeApp.app_sid.nil?
99
+
100
+ url = url[0..-2] if url[-1].eql? '/'
101
+
102
+ unless query_params.empty?
103
+ url = "#{url}?"
104
+ query_params.each { |key, value|
105
+ url = "#{url}#{key}=#{value}&"
106
+ }
107
+ url = url[0..-2]
108
+ end
109
+
110
+ url = URI.escape(url)
111
+ parsed_url = URI.parse(url)
112
+
113
+ url_to_sign = "#{parsed_url.scheme}://#{parsed_url.host}#{parsed_url.path}"
114
+ url_to_sign += "?#{parsed_url.query}" if parsed_url.query
115
+ if parsed_url.query
116
+ url_to_sign += "&appSID=#{AsposeApp.app_sid}"
117
+ else
118
+ url_to_sign += "?appSID=#{AsposeApp.app_sid}"
119
+ end
120
+
121
+ # create a signature using the private key and the URL
122
+ raw_signature = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha1'), AsposeApp.app_key, url_to_sign)
123
+
124
+ #Convert raw to encoded string
125
+ signature = Base64.strict_encode64(raw_signature).tr('+/', '-_')
126
+
127
+ #remove invalid character
128
+ signature = signature.gsub(/[=_-]/, '=' => '', '_' => '%2f', '-' => '%2b')
129
+
130
+ #Define expression
131
+ pat = Regexp.new('%[0-9a-f]{2}')
132
+
133
+ #Replace the portion matched to the above pattern to upper case
134
+ 6.times do
135
+ signature = signature.sub(pat, pat.match(signature).to_s.upcase)
136
+ end
137
+
138
+ # prepend the server and append the signature.
139
+ url_to_sign + "&signature=#{signature}"
140
+
141
+ end
142
+
143
+ # Deserialize the response to the given return type.
144
+ #
145
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
146
+ def deserialize(response, return_type)
147
+ body = response.body
148
+ return nil if body.nil? || body.empty?
149
+
150
+ # handle file downloading - save response body into a tmp file and return the File instance
151
+ return download_file(response) if return_type == 'File'
152
+
153
+ # ensuring a default content type
154
+ content_type = response.headers['Content-Type'] || 'application/json'
155
+
156
+ unless content_type.start_with?('application/json')
157
+ fail "Content-Type is not supported: #{content_type}"
158
+ end
159
+
160
+ begin
161
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
162
+ rescue JSON::ParserError => e
163
+ if %w(String Date DateTime).include?(return_type)
164
+ data = body
165
+ else
166
+ raise e
167
+ end
168
+ end
169
+
170
+ convert_to_type data, return_type
171
+ end
172
+
173
+ # Convert data to the given return type.
174
+ def convert_to_type(data, return_type)
175
+ return nil if data.nil?
176
+ case return_type
177
+ when 'String'
178
+ data.to_s
179
+ when 'Integer'
180
+ data.to_i
181
+ when 'Float'
182
+ data.to_f
183
+ when 'BOOLEAN'
184
+ data == true
185
+ when 'DateTime'
186
+ # parse date time (expecting ISO 8601 format)
187
+ DateTime.parse data
188
+ when 'Date'
189
+ # parse date time (expecting ISO 8601 format)
190
+ Date.parse data
191
+ when 'Object'
192
+ # generic object, return directly
193
+ data
194
+ when /\AArray<(.+)>\z/
195
+ # e.g. Array<Pet>
196
+ sub_type = $1
197
+ data.map {|item| convert_to_type(item, sub_type) }
198
+ when /\AHash\<String, (.+)\>\z/
199
+ # e.g. Hash<String, Integer>
200
+ sub_type = $1
201
+ {}.tap do |hash|
202
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
203
+ end
204
+ else
205
+ # models, e.g. Pet
206
+ AsposeEmailCloud.const_get(return_type).new.tap do |model|
207
+ model.build_from_hash data
208
+ end
209
+ end
210
+ end
211
+
212
+ # Save response body into a file in (the defined) temporary folder, using the filename
213
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
214
+ #
215
+ # @see Configuration#temp_folder_path
216
+ # @return [File] the file downloaded
217
+ def download_file(response)
218
+ tmp_file = Tempfile.new '', Configuration.temp_folder_path
219
+ content_disposition = response.headers['Content-Disposition']
220
+
221
+ if content_disposition
222
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
223
+ path = File.join File.dirname(tmp_file), filename
224
+ else
225
+ path = tmp_file.path
226
+ end
227
+ # close and delete temp file
228
+ tmp_file.close!
229
+
230
+ File.open(path, 'w') { |file| file.write(response.body) }
231
+ Configuration.logger.info "File written to #{path}. Please move the file to a proper "\
232
+ "folder for further processing and delete the temp afterwards"
233
+ File.new(path)
234
+ end
235
+
236
+ def build_request_url(path)
237
+ # Add leading and trailing slashes to path
238
+ path = "/#{path}".gsub(/\/+/, '/')
239
+ URI.encode(host + path)
240
+ end
241
+
242
+ def build_request_body(header_params, form_params, body)
243
+ # http form
244
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
245
+ header_params['Content-Type'] == 'multipart/form-data'
246
+
247
+ data = form_params.dup
248
+ data.each do |key, value|
249
+ if key.eql? "file"
250
+ data = value
251
+ break
252
+ else
253
+ data[key] = value.to_s if value && !value.is_a?(File)
254
+ end
255
+ end
256
+ elsif body
257
+ data = body.is_a?(String) ? body : body.to_json
258
+ else
259
+ data = nil
260
+ end
261
+ data
262
+ end
263
+
264
+ # Update hearder and query params based on authentication settings.
265
+ def update_params_for_auth!(header_params, query_params, auth_names)
266
+ Array(auth_names).each do |auth_name|
267
+ auth_setting = Configuration.auth_settings[auth_name]
268
+ next unless auth_setting
269
+ case auth_setting[:in]
270
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
271
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
272
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
273
+ end
274
+ end
275
+ end
276
+
277
+ def user_agent=(user_agent)
278
+ @user_agent = user_agent
279
+ @default_headers['User-Agent'] = @user_agent
280
+ end
281
+
282
+ # Return Accept header based on an array of accepts provided.
283
+ # @param [Array] accepts array for Accept
284
+ # @return [String] the Accept header (e.g. application/json)
285
+ def select_header_accept(accepts)
286
+ if accepts.empty?
287
+ return
288
+ elsif accepts.any?{ |s| s.casecmp('application/json') == 0 }
289
+ 'application/json' # look for json data by default
290
+ else
291
+ accepts.join(',')
292
+ end
293
+ end
294
+
295
+ # Return Content-Type header based on an array of content types provided.
296
+ # @param [Array] content_types array for Content-Type
297
+ # @return [String] the Content-Type header (e.g. application/json)
298
+ def select_header_content_type(content_types)
299
+ if content_types.empty?
300
+ 'application/json' # use application/json by default
301
+ elsif content_types.any?{ |s| s.casecmp('application/json')==0 }
302
+ 'application/json' # use application/json if it's included
303
+ else
304
+ content_types[0] # otherwise, use the first one
305
+ end
306
+ end
307
+
308
+ # Convert object (array, hash, object, etc) to JSON string.
309
+ # @param [Object] model object to be converted into JSON string
310
+ # @return [String] JSON string representation of the object
311
+ def object_to_http_body(model)
312
+ return if model.nil?
313
+ _body = nil
314
+ if model.is_a?(Array)
315
+ _body = model.map{|m| object_to_hash(m) }
316
+ else
317
+ _body = object_to_hash(model)
318
+ end
319
+ _body.to_json
320
+ end
321
+
322
+ # Convert object(non-array) to hash.
323
+ # @param [Object] obj object to be converted into JSON string
324
+ # @return [String] JSON string representation of the object
325
+ def object_to_hash(obj)
326
+ if obj.respond_to?(:to_hash)
327
+ obj.to_hash
328
+ else
329
+ obj
330
+ end
331
+ end
332
+
333
+
334
+ end
335
+ end
@@ -0,0 +1,24 @@
1
+ module AsposeEmailCloud
2
+ class ApiError < StandardError
3
+ attr_reader :code, :response_headers, :response_body
4
+
5
+ # Usage examples:
6
+ # ApiError.new
7
+ # ApiError.new("message")
8
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
9
+ # ApiError.new(:code => 404, :message => "Not Found")
10
+ def initialize(arg = nil)
11
+ if arg.is_a? Hash
12
+ arg.each do |k, v|
13
+ if k.to_s == 'message'
14
+ super v
15
+ else
16
+ instance_variable_set "@#{k}", v
17
+ end
18
+ end
19
+ else
20
+ super arg
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,166 @@
1
+ require 'uri'
2
+ require 'singleton'
3
+
4
+ module AsposeEmailCloud
5
+ class Configuration
6
+
7
+ include Singleton
8
+
9
+ # Default api client
10
+ attr_accessor :api_client
11
+
12
+ # Defines url scheme
13
+ attr_accessor :scheme
14
+
15
+ # Defines url host
16
+ attr_accessor :host
17
+
18
+ # Defines url base path
19
+ attr_accessor :base_path
20
+
21
+ # Defines API keys used with API Key authentications.
22
+ #
23
+ # @return [Hash] key: parameter name, value: parameter value (API key)
24
+ #
25
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
26
+ # config.api_key['api_key'] = 'xxx'
27
+ attr_accessor :api_key
28
+
29
+ # Defines API key prefixes used with API Key authentications.
30
+ #
31
+ # @return [Hash] key: parameter name, value: API key prefix
32
+ #
33
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
34
+ # config.api_key_prefix['api_key'] = 'Token'
35
+ attr_accessor :api_key_prefix
36
+
37
+ # Defines the username used with HTTP basic authentication.
38
+ #
39
+ # @return [String]
40
+ attr_accessor :username
41
+
42
+ # Defines the password used with HTTP basic authentication.
43
+ #
44
+ # @return [String]
45
+ attr_accessor :password
46
+
47
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
48
+ # details will be logged with `logger.debug` (see the `logger` attribute).
49
+ # Default to false.
50
+ #
51
+ # @return [true, false]
52
+ attr_accessor :debugging
53
+
54
+ # Defines the logger used for debugging.
55
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
56
+ #
57
+ # @return [#debug]
58
+ attr_accessor :logger
59
+
60
+ # Defines the temporary folder to store downloaded files
61
+ # (for API endpoints that have file response).
62
+ # Default to use `Tempfile`.
63
+ #
64
+ # @return [String]
65
+ attr_accessor :temp_folder_path
66
+
67
+ ### TLS/SSL
68
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
69
+ # Default to true.
70
+ #
71
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
72
+ #
73
+ # @return [true, false]
74
+ attr_accessor :verify_ssl
75
+
76
+ # Set this to customize the certificate file to verify the peer.
77
+ #
78
+ # @return [String] the path to the certificate file
79
+ #
80
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
81
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
82
+ attr_accessor :ssl_ca_cert
83
+
84
+ # Client certificate file (for client certificate)
85
+ attr_accessor :cert_file
86
+
87
+ # Client private key file (for client certificate)
88
+ attr_accessor :key_file
89
+
90
+ attr_accessor :inject_format
91
+
92
+ attr_accessor :force_ending_format
93
+
94
+ class << self
95
+ def method_missing(method_name, *args, &block)
96
+ config = Configuration.instance
97
+ if config.respond_to?(method_name)
98
+ config.send(method_name, *args, &block)
99
+ else
100
+ super
101
+ end
102
+ end
103
+ end
104
+
105
+ def initialize
106
+ @scheme = 'http'
107
+ @host = 'api.aspose.com'
108
+ @base_path = '/v1.1'
109
+ @api_key = {}
110
+ @api_key_prefix = {}
111
+ @verify_ssl = true
112
+ @cert_file = nil
113
+ @key_file = nil
114
+ @debugging = false
115
+ @inject_format = false
116
+ @force_ending_format = false
117
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
118
+ end
119
+
120
+ def api_client
121
+ @api_client ||= ApiClient.new
122
+ end
123
+
124
+ def scheme=(scheme)
125
+ # remove :// from scheme
126
+ @scheme = scheme.sub(/:\/\//, '')
127
+ end
128
+
129
+ def host=(host)
130
+ # remove http(s):// and anything after a slash
131
+ @host = host.sub(/https?:\/\//, '').split('/').first
132
+ end
133
+
134
+ def base_path=(base_path)
135
+ # Add leading and trailing slashes to base_path
136
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
137
+ @base_path = "" if @base_path == "/"
138
+ end
139
+
140
+ def base_url
141
+ url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
142
+ URI.encode(url)
143
+ end
144
+
145
+ # Gets API key (with prefix if set).
146
+ # @param [String] param_name the parameter name of API key auth
147
+ def api_key_with_prefix(param_name)
148
+ if @api_key_prefix[param_name]
149
+ "#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
150
+ else
151
+ @api_key[param_name]
152
+ end
153
+ end
154
+
155
+ # Gets Basic Auth token string
156
+ def basic_auth_token
157
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
158
+ end
159
+
160
+ # Returns Auth Settings hash for api client.
161
+ def auth_settings
162
+ {
163
+ }
164
+ end
165
+ end
166
+ end