aylien_news_api 0.0.1

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 (112) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +3 -0
  3. data/Gemfile.lock +67 -0
  4. data/LICENSE +13 -0
  5. data/README.md +133 -0
  6. data/Rakefile +8 -0
  7. data/aylien_news_api.gemspec +33 -0
  8. data/docs/Author.md +10 -0
  9. data/docs/Autocomplete.md +9 -0
  10. data/docs/Autocompletes.md +8 -0
  11. data/docs/Category.md +13 -0
  12. data/docs/CategoryLinks.md +9 -0
  13. data/docs/Coverages.md +12 -0
  14. data/docs/DefaultApi.md +829 -0
  15. data/docs/Entities.md +9 -0
  16. data/docs/Entity.md +12 -0
  17. data/docs/EntityLinks.md +8 -0
  18. data/docs/Error.md +13 -0
  19. data/docs/ErrorLinks.md +8 -0
  20. data/docs/Errors.md +8 -0
  21. data/docs/HistogramInterval.md +9 -0
  22. data/docs/Histograms.md +12 -0
  23. data/docs/Location.md +10 -0
  24. data/docs/Media.md +9 -0
  25. data/docs/RelatedStories.md +11 -0
  26. data/docs/Scope.md +11 -0
  27. data/docs/Sentiment.md +9 -0
  28. data/docs/Sentiments.md +9 -0
  29. data/docs/ShareCount.md +9 -0
  30. data/docs/ShareCounts.md +11 -0
  31. data/docs/Source.md +13 -0
  32. data/docs/Stories.md +10 -0
  33. data/docs/Story.md +27 -0
  34. data/docs/StoryCluster.md +12 -0
  35. data/docs/StoryLinks.md +10 -0
  36. data/docs/Summary.md +8 -0
  37. data/docs/TimeSeries.md +9 -0
  38. data/docs/TimeSeriesList.md +11 -0
  39. data/docs/Trend.md +9 -0
  40. data/docs/Trends.md +9 -0
  41. data/lib/aylien_news_api.rb +74 -0
  42. data/lib/aylien_news_api/api/default_api.rb +1171 -0
  43. data/lib/aylien_news_api/api_client.rb +365 -0
  44. data/lib/aylien_news_api/api_error.rb +38 -0
  45. data/lib/aylien_news_api/configuration.rb +191 -0
  46. data/lib/aylien_news_api/models/author.rb +192 -0
  47. data/lib/aylien_news_api/models/autocomplete.rb +183 -0
  48. data/lib/aylien_news_api/models/autocompletes.rb +176 -0
  49. data/lib/aylien_news_api/models/category.rb +229 -0
  50. data/lib/aylien_news_api/models/category_links.rb +183 -0
  51. data/lib/aylien_news_api/models/coverages.rb +212 -0
  52. data/lib/aylien_news_api/models/entities.rb +187 -0
  53. data/lib/aylien_news_api/models/entity.rb +214 -0
  54. data/lib/aylien_news_api/models/entity_links.rb +174 -0
  55. data/lib/aylien_news_api/models/error.rb +213 -0
  56. data/lib/aylien_news_api/models/error_links.rb +173 -0
  57. data/lib/aylien_news_api/models/errors.rb +175 -0
  58. data/lib/aylien_news_api/models/histogram_interval.rb +183 -0
  59. data/lib/aylien_news_api/models/histograms.rb +211 -0
  60. data/lib/aylien_news_api/models/location.rb +192 -0
  61. data/lib/aylien_news_api/models/media.rb +193 -0
  62. data/lib/aylien_news_api/models/related_stories.rb +203 -0
  63. data/lib/aylien_news_api/models/scope.rb +211 -0
  64. data/lib/aylien_news_api/models/sentiment.rb +193 -0
  65. data/lib/aylien_news_api/models/sentiments.rb +183 -0
  66. data/lib/aylien_news_api/models/share_count.rb +183 -0
  67. data/lib/aylien_news_api/models/share_counts.rb +209 -0
  68. data/lib/aylien_news_api/models/source.rb +223 -0
  69. data/lib/aylien_news_api/models/stories.rb +196 -0
  70. data/lib/aylien_news_api/models/story.rb +353 -0
  71. data/lib/aylien_news_api/models/story_cluster.rb +214 -0
  72. data/lib/aylien_news_api/models/story_links.rb +192 -0
  73. data/lib/aylien_news_api/models/summary.rb +176 -0
  74. data/lib/aylien_news_api/models/time_series.rb +183 -0
  75. data/lib/aylien_news_api/models/time_series_list.rb +203 -0
  76. data/lib/aylien_news_api/models/trend.rb +183 -0
  77. data/lib/aylien_news_api/models/trends.rb +185 -0
  78. data/lib/aylien_news_api/version.rb +17 -0
  79. data/spec/api/default_api_spec.rb +357 -0
  80. data/spec/models/author_spec.rb +66 -0
  81. data/spec/models/autocomplete_spec.rb +56 -0
  82. data/spec/models/autocompletes_spec.rb +46 -0
  83. data/spec/models/category_links_spec.rb +56 -0
  84. data/spec/models/category_spec.rb +96 -0
  85. data/spec/models/coverages_spec.rb +86 -0
  86. data/spec/models/entities_spec.rb +56 -0
  87. data/spec/models/entity_links_spec.rb +46 -0
  88. data/spec/models/entity_spec.rb +86 -0
  89. data/spec/models/error_links_spec.rb +46 -0
  90. data/spec/models/error_spec.rb +96 -0
  91. data/spec/models/errors_spec.rb +46 -0
  92. data/spec/models/histogram_interval_spec.rb +56 -0
  93. data/spec/models/histograms_spec.rb +86 -0
  94. data/spec/models/location_spec.rb +66 -0
  95. data/spec/models/media_spec.rb +56 -0
  96. data/spec/models/related_stories_spec.rb +76 -0
  97. data/spec/models/scope_spec.rb +76 -0
  98. data/spec/models/sentiment_spec.rb +56 -0
  99. data/spec/models/sentiments_spec.rb +56 -0
  100. data/spec/models/share_count_spec.rb +56 -0
  101. data/spec/models/share_counts_spec.rb +76 -0
  102. data/spec/models/source_spec.rb +96 -0
  103. data/spec/models/stories_spec.rb +66 -0
  104. data/spec/models/story_cluster_spec.rb +86 -0
  105. data/spec/models/story_links_spec.rb +66 -0
  106. data/spec/models/story_spec.rb +236 -0
  107. data/spec/models/summary_spec.rb +46 -0
  108. data/spec/models/time_series_list_spec.rb +76 -0
  109. data/spec/models/time_series_spec.rb +56 -0
  110. data/spec/models/trend_spec.rb +56 -0
  111. data/spec/models/trends_spec.rb +56 -0
  112. metadata +391 -0
@@ -0,0 +1,365 @@
1
+ # Copyright 2016 Aylien, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'date'
16
+ require 'json'
17
+ require 'logger'
18
+ require 'tempfile'
19
+ require 'typhoeus'
20
+ require 'uri'
21
+
22
+ module AylienNewsApi
23
+ class ApiClient
24
+ # The Configuration object holding settings to be used in the API client.
25
+ attr_accessor :config
26
+
27
+ # Defines the headers to be used in HTTP requests of all API calls by default.
28
+ #
29
+ # @return [Hash]
30
+ attr_accessor :default_headers
31
+
32
+ # Initializes the ApiClient
33
+ # @option config [Configuration] Configuraiton for initializing the object, default to Configuration.default
34
+ def initialize(config = Configuration.default)
35
+ @config = config
36
+ @user_agent = "aylien-news-api/#{VERSION}/ruby"
37
+ @default_headers = {
38
+ 'Content-Type' => "application/json",
39
+ 'User-Agent' => @user_agent
40
+ }
41
+ end
42
+
43
+ def self.default
44
+ @@default ||= ApiClient.new
45
+ end
46
+
47
+ # Call an API with given options.
48
+ #
49
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
50
+ # the data deserialized from response body (could be nil), response status code and response headers.
51
+ def call_api(http_method, path, opts = {})
52
+ request = build_request(http_method, path, opts)
53
+ response = request.run
54
+
55
+ if @config.debugging
56
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
57
+ end
58
+
59
+ unless response.success?
60
+ fail ApiError.new(:code => response.code,
61
+ :response_headers => response.headers,
62
+ :response_body => response.body),
63
+ response.status_message
64
+ end
65
+
66
+ if opts[:return_type]
67
+ data = deserialize(response, opts[:return_type])
68
+ else
69
+ data = nil
70
+ end
71
+ return data, response.code, response.headers
72
+ end
73
+
74
+ # Builds the HTTP request
75
+ #
76
+ # @param [String] http_method HTTP method/verb (e.g. POST)
77
+ # @param [String] path URL path (e.g. /account/new)
78
+ # @option opts [Hash] :header_params Header parameters
79
+ # @option opts [Hash] :query_params Query parameters
80
+ # @option opts [Hash] :form_params Query parameters
81
+ # @option opts [Object] :body HTTP body (JSON/XML)
82
+ # @return [Typhoeus::Request] A Typhoeus Request
83
+ def build_request(http_method, path, opts = {})
84
+ url = build_request_url(path)
85
+ http_method = http_method.to_sym.downcase
86
+
87
+ header_params = @default_headers.merge(opts[:header_params] || {})
88
+ query_params = opts[:query_params] || {}
89
+ form_params = opts[:form_params] || {}
90
+
91
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
92
+
93
+ req_opts = {
94
+ :params_encoding => :multi,
95
+ :method => http_method,
96
+ :headers => header_params,
97
+ :params => query_params,
98
+ :timeout => @config.timeout,
99
+ :ssl_verifypeer => @config.verify_ssl,
100
+ :sslcert => @config.cert_file,
101
+ :sslkey => @config.key_file,
102
+ :verbose => @config.debugging
103
+ }
104
+
105
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
106
+
107
+ if [:post, :patch, :put, :delete].include?(http_method)
108
+ req_body = build_request_body(header_params, form_params, opts[:body])
109
+ req_opts.update :body => req_body
110
+ if @config.debugging
111
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
112
+ end
113
+ end
114
+
115
+ Typhoeus::Request.new(url, req_opts)
116
+ end
117
+
118
+ # Check if the given MIME is a JSON MIME.
119
+ # JSON MIME examples:
120
+ # application/json
121
+ # application/json; charset=UTF8
122
+ # APPLICATION/JSON
123
+ # @param [String] mime MIME
124
+ # @return [Boolean] True if the MIME is applicaton/json
125
+ def json_mime?(mime)
126
+ !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil?
127
+ end
128
+
129
+ # Deserialize the response to the given return type.
130
+ #
131
+ # @param [Response] response HTTP response
132
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
133
+ def deserialize(response, return_type)
134
+ body = response.body
135
+ return nil if body.nil? || body.empty?
136
+
137
+ # return response body directly for String return type
138
+ return body if return_type == 'String'
139
+
140
+ # handle file downloading - save response body into a tmp file and return the File instance
141
+ return download_file(response) if return_type == 'File'
142
+
143
+ # ensuring a default content type
144
+ content_type = response.headers['Content-Type'] || 'application/json'
145
+
146
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
147
+
148
+ begin
149
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
150
+ rescue JSON::ParserError => e
151
+ if %w(String Date DateTime).include?(return_type)
152
+ data = body
153
+ else
154
+ raise e
155
+ end
156
+ end
157
+
158
+ convert_to_type data, return_type
159
+ end
160
+
161
+ # Convert data to the given return type.
162
+ # @param [Object] data Data to be converted
163
+ # @param [String] return_type Return type
164
+ # @return [Mixed] Data in a particular type
165
+ def convert_to_type(data, return_type)
166
+ return nil if data.nil?
167
+ case return_type
168
+ when 'String'
169
+ data.to_s
170
+ when 'Integer'
171
+ data.to_i
172
+ when 'Float'
173
+ data.to_f
174
+ when 'BOOLEAN'
175
+ data == true
176
+ when 'DateTime'
177
+ # parse date time (expecting ISO 8601 format)
178
+ DateTime.parse data
179
+ when 'Date'
180
+ # parse date time (expecting ISO 8601 format)
181
+ Date.parse data
182
+ when 'Object'
183
+ # generic object (usually a Hash), return directly
184
+ data
185
+ when /\AArray<(.+)>\z/
186
+ # e.g. Array<Pet>
187
+ sub_type = $1
188
+ data.map {|item| convert_to_type(item, sub_type) }
189
+ when /\AHash\<String, (.+)\>\z/
190
+ # e.g. Hash<String, Integer>
191
+ sub_type = $1
192
+ {}.tap do |hash|
193
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
194
+ end
195
+ else
196
+ # models, e.g. Pet
197
+ AylienNewsApi.const_get(return_type).new.tap do |model|
198
+ model.build_from_hash data
199
+ end
200
+ end
201
+ end
202
+
203
+ # Save response body into a file in (the defined) temporary folder, using the filename
204
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
205
+ #
206
+ # @see Configuration#temp_folder_path
207
+ # @return [Tempfile] the file downloaded
208
+ def download_file(response)
209
+ content_disposition = response.headers['Content-Disposition']
210
+ if content_disposition
211
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
212
+ prefix = sanitize_filename(filename)
213
+ else
214
+ prefix = 'download-'
215
+ end
216
+ prefix = prefix + '-' unless prefix.end_with?('-')
217
+
218
+ tempfile = nil
219
+ encoding = response.body.encoding
220
+ Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) do |file|
221
+ file.write(response.body)
222
+ tempfile = file
223
+ end
224
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
225
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
226
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
227
+ "explicitly with `tempfile.delete`"
228
+ tempfile
229
+ end
230
+
231
+ # Sanitize filename by removing path.
232
+ # e.g. ../../sun.gif becomes sun.gif
233
+ #
234
+ # @param [String] filename the filename to be sanitized
235
+ # @return [String] the sanitized filename
236
+ def sanitize_filename(filename)
237
+ filename.gsub(/.*[\/\\]/, '')
238
+ end
239
+
240
+ def build_request_url(path)
241
+ # Add leading and trailing slashes to path
242
+ path = "/#{path}".gsub(/\/+/, '/')
243
+ URI.encode(@config.base_url + path)
244
+ end
245
+
246
+ # Builds the HTTP request body
247
+ #
248
+ # @param [Hash] header_params Header parameters
249
+ # @param [Hash] form_params Query parameters
250
+ # @param [Object] body HTTP body (JSON/XML)
251
+ # @return [String] HTTP body data in the form of string
252
+ def build_request_body(header_params, form_params, body)
253
+ # http form
254
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
255
+ header_params['Content-Type'] == 'multipart/form-data'
256
+ data = {}
257
+ form_params.each do |key, value|
258
+ case value
259
+ when File, Array, nil
260
+ # let typhoeus handle File, Array and nil parameters
261
+ data[key] = value
262
+ else
263
+ data[key] = value.to_s
264
+ end
265
+ end
266
+ elsif body
267
+ data = body.is_a?(String) ? body : body.to_json
268
+ else
269
+ data = nil
270
+ end
271
+ data
272
+ end
273
+
274
+ # Update hearder and query params based on authentication settings.
275
+ #
276
+ # @param [Hash] header_params Header parameters
277
+ # @param [Hash] form_params Query parameters
278
+ # @param [String] auth_names Authentication scheme name
279
+ def update_params_for_auth!(header_params, query_params, auth_names)
280
+ Array(auth_names).each do |auth_name|
281
+ auth_setting = @config.auth_settings[auth_name]
282
+ next unless auth_setting
283
+ case auth_setting[:in]
284
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
285
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
286
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
287
+ end
288
+ end
289
+ end
290
+
291
+ # Sets user agent in HTTP header
292
+ #
293
+ # @param [String] user_agent User agent
294
+ def user_agent=(user_agent)
295
+ @user_agent = user_agent
296
+ @default_headers['User-Agent'] = @user_agent
297
+ end
298
+
299
+ # Return Accept header based on an array of accepts provided.
300
+ # @param [Array] accepts array for Accept
301
+ # @return [String] the Accept header (e.g. application/json)
302
+ def select_header_accept(accepts)
303
+ return nil if accepts.nil? || accepts.empty?
304
+ # use JSON when present, otherwise use all of the provided
305
+ json_accept = accepts.find { |s| json_mime?(s) }
306
+ return json_accept || accepts.join(',')
307
+ end
308
+
309
+ # Return Content-Type header based on an array of content types provided.
310
+ # @param [Array] content_types array for Content-Type
311
+ # @return [String] the Content-Type header (e.g. application/json)
312
+ def select_header_content_type(content_types)
313
+ # use application/json by default
314
+ return 'application/json' if content_types.nil? || content_types.empty?
315
+ # use JSON when present, otherwise use the first one
316
+ json_content_type = content_types.find { |s| json_mime?(s) }
317
+ return json_content_type || content_types.first
318
+ end
319
+
320
+ # Convert object (array, hash, object, etc) to JSON string.
321
+ # @param [Object] model object to be converted into JSON string
322
+ # @return [String] JSON string representation of the object
323
+ def object_to_http_body(model)
324
+ return model if model.nil? || model.is_a?(String)
325
+ local_body = nil
326
+ if model.is_a?(Array)
327
+ local_body = model.map{|m| object_to_hash(m) }
328
+ else
329
+ local_body = object_to_hash(model)
330
+ end
331
+ local_body.to_json
332
+ end
333
+
334
+ # Convert object(non-array) to hash.
335
+ # @param [Object] obj object to be converted into JSON string
336
+ # @return [String] JSON string representation of the object
337
+ def object_to_hash(obj)
338
+ if obj.respond_to?(:to_hash)
339
+ obj.to_hash
340
+ else
341
+ obj
342
+ end
343
+ end
344
+
345
+ # Build parameter value according to the given collection format.
346
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
347
+ def build_collection_param(param, collection_format)
348
+ case collection_format
349
+ when :csv
350
+ param.join(',')
351
+ when :ssv
352
+ param.join(' ')
353
+ when :tsv
354
+ param.join("\t")
355
+ when :pipes
356
+ param.join('|')
357
+ when :multi
358
+ # return the array directly as typhoeus will handle it as expected
359
+ param
360
+ else
361
+ fail "unknown collection format: #{collection_format.inspect}"
362
+ end
363
+ end
364
+ end
365
+ end
@@ -0,0 +1,38 @@
1
+ # Copyright 2016 Aylien, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ module AylienNewsApi
16
+ class ApiError < StandardError
17
+ attr_reader :code, :response_headers, :response_body
18
+
19
+ # Usage examples:
20
+ # ApiError.new
21
+ # ApiError.new("message")
22
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
23
+ # ApiError.new(:code => 404, :message => "Not Found")
24
+ def initialize(arg = nil)
25
+ if arg.is_a? Hash
26
+ arg.each do |k, v|
27
+ if k.to_s == 'message'
28
+ super v
29
+ else
30
+ instance_variable_set "@#{k}", v
31
+ end
32
+ end
33
+ else
34
+ super arg
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,191 @@
1
+ # Copyright 2016 Aylien, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'uri'
16
+
17
+ module AylienNewsApi
18
+ class Configuration
19
+ # Defines url scheme
20
+ attr_accessor :scheme
21
+
22
+ # Defines url host
23
+ attr_accessor :host
24
+
25
+ # Defines url base path
26
+ attr_accessor :base_path
27
+
28
+ # Defines API keys used with API Key authentications.
29
+ #
30
+ # @return [Hash] key: parameter name, value: parameter value (API key)
31
+ #
32
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
33
+ # config.api_key['api_key'] = 'xxx'
34
+ attr_accessor :api_key
35
+
36
+ # Defines API key prefixes used with API Key authentications.
37
+ #
38
+ # @return [Hash] key: parameter name, value: API key prefix
39
+ #
40
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
41
+ # config.api_key_prefix['api_key'] = 'Token'
42
+ attr_accessor :api_key_prefix
43
+
44
+ # Defines the username used with HTTP basic authentication.
45
+ #
46
+ # @return [String]
47
+ attr_accessor :username
48
+
49
+ # Defines the password used with HTTP basic authentication.
50
+ #
51
+ # @return [String]
52
+ attr_accessor :password
53
+
54
+ # Defines the access token (Bearer) used with OAuth2.
55
+ attr_accessor :access_token
56
+
57
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
58
+ # details will be logged with `logger.debug` (see the `logger` attribute).
59
+ # Default to false.
60
+ #
61
+ # @return [true, false]
62
+ attr_accessor :debugging
63
+
64
+ # Defines the logger used for debugging.
65
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
66
+ #
67
+ # @return [#debug]
68
+ attr_accessor :logger
69
+
70
+ # Defines the temporary folder to store downloaded files
71
+ # (for API endpoints that have file response).
72
+ # Default to use `Tempfile`.
73
+ #
74
+ # @return [String]
75
+ attr_accessor :temp_folder_path
76
+
77
+ # The time limit for HTTP request in seconds.
78
+ # Default to 0 (never times out).
79
+ attr_accessor :timeout
80
+
81
+ ### TLS/SSL
82
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
83
+ # Default to true.
84
+ #
85
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
86
+ #
87
+ # @return [true, false]
88
+ attr_accessor :verify_ssl
89
+
90
+ # Set this to customize the certificate file to verify the peer.
91
+ #
92
+ # @return [String] the path to the certificate file
93
+ #
94
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
95
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
96
+ attr_accessor :ssl_ca_cert
97
+
98
+ # Client certificate file (for client certificate)
99
+ attr_accessor :cert_file
100
+
101
+ # Client private key file (for client certificate)
102
+ attr_accessor :key_file
103
+
104
+ attr_accessor :inject_format
105
+
106
+ attr_accessor :force_ending_format
107
+
108
+ def initialize
109
+ @scheme = 'https'
110
+ @host = 'api.newsapi.aylien.com'
111
+ @base_path = '/api/v1'
112
+ @api_key = {}
113
+ @api_key_prefix = {}
114
+ @timeout = 0
115
+ @verify_ssl = true
116
+ @cert_file = nil
117
+ @key_file = nil
118
+ @debugging = false
119
+ @inject_format = false
120
+ @force_ending_format = false
121
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
122
+
123
+ yield(self) if block_given?
124
+ end
125
+
126
+ # The default Configuration object.
127
+ def self.default
128
+ @@default ||= Configuration.new
129
+ end
130
+
131
+ def configure
132
+ yield(self) if block_given?
133
+ end
134
+
135
+ def scheme=(scheme)
136
+ # remove :// from scheme
137
+ @scheme = scheme.sub(/:\/\//, '')
138
+ end
139
+
140
+ def host=(host)
141
+ # remove http(s):// and anything after a slash
142
+ @host = host.sub(/https?:\/\//, '').split('/').first
143
+ end
144
+
145
+ def base_path=(base_path)
146
+ # Add leading and trailing slashes to base_path
147
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
148
+ @base_path = "" if @base_path == "/"
149
+ end
150
+
151
+ def base_url
152
+ url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
153
+ URI.encode(url)
154
+ end
155
+
156
+ # Gets API key (with prefix if set).
157
+ # @param [String] param_name the parameter name of API key auth
158
+ def api_key_with_prefix(param_name)
159
+ if @api_key_prefix[param_name]
160
+ "#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
161
+ else
162
+ @api_key[param_name]
163
+ end
164
+ end
165
+
166
+ # Gets Basic Auth token string
167
+ def basic_auth_token
168
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
169
+ end
170
+
171
+ # Returns Auth Settings hash for api client.
172
+ def auth_settings
173
+ {
174
+ 'app_key' =>
175
+ {
176
+ type: 'api_key',
177
+ in: 'header',
178
+ key: 'X-AYLIEN-NewsAPI-Application-Key',
179
+ value: api_key_with_prefix('X-AYLIEN-NewsAPI-Application-Key')
180
+ },
181
+ 'app_id' =>
182
+ {
183
+ type: 'api_key',
184
+ in: 'header',
185
+ key: 'X-AYLIEN-NewsAPI-Application-ID',
186
+ value: api_key_with_prefix('X-AYLIEN-NewsAPI-Application-ID')
187
+ },
188
+ }
189
+ end
190
+ end
191
+ end