Module: Maremma

Defined in:
lib/maremma.rb,
lib/maremma/version.rb

Constant Summary collapse

VERSION =
"3.0.1"

Class Method Summary collapse

Class Method Details

.delete(url, options = {}) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/maremma.rb', line 58

def self.delete(url, options={})
  options[:data] ||= {}
  options[:headers] = set_request_headers(url, options)

  conn = faraday_conn(options)

  conn.options[:timeout] = options[:timeout] || DEFAULT_TIMEOUT

  response = conn.delete url, {}, options[:headers]

  OpenStruct.new(body: parse_success_response(response.body),
                 headers: response.headers,
                 status: response.status)
rescue *NETWORKABLE_EXCEPTIONS => error
  OpenStruct.new(body: rescue_faraday_error(error))
end

.faraday_conn(options = {}) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/maremma.rb', line 118

def self.faraday_conn(options = {})
  # make sure we have headers
  options[:headers] ||= {}

  # set redirect limit
  limit = options[:limit] || 10

  Faraday.new do |c|
    c.options.params_encoder = Faraday::FlatParamsEncoder
    c.headers['Content-type'] = options[:headers]['Content-type'] if options[:headers]['Content-type'].present?
    c.headers['Accept'] = options[:headers]['Accept']
    c.headers['User-Agent'] = options[:headers]['User-Agent']
    c.use      FaradayMiddleware::FollowRedirects, limit: limit, cookie: :all
    c.request  :multipart
    c.request  :json if options[:headers]['Accept'] == 'application/json'
    c.use      Faraday::Response::RaiseError
    c.response :encoding
    c.adapter  :excon
  end
end

.from_json(string) ⇒ Object



234
235
236
237
238
# File 'lib/maremma.rb', line 234

def self.from_json(string)
  JSON.parse(string)
rescue JSON::ParserError
  nil
end

.from_string(string) ⇒ Object



240
241
242
# File 'lib/maremma.rb', line 240

def self.from_string(string)
  string.gsub(/\s+\n/, "\n").strip.force_encoding('UTF-8')
end

.from_xml(string) ⇒ Object



226
227
228
229
230
231
232
# File 'lib/maremma.rb', line 226

def self.from_xml(string)
  if Nokogiri::XML(string).errors.empty?
    Hash.from_xml(string)
  else
    nil
  end
end

.get(url, options = {}) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/maremma.rb', line 75

def self.get(url, options={})
  options[:headers] = set_request_headers(url, options)

  conn = faraday_conn(options)

  conn.options[:timeout] = options[:timeout] || DEFAULT_TIMEOUT

  response = conn.get url, {}, options[:headers]

  # return error if we are close to the rate limit, if supported in headers
  if get_rate_limit_remaining(response.headers) < 10
    return OpenStruct.new(body: { "errors" => [{ 'status' => 429, 'title' => "Too many requests" }] },
                          headers: response.headers,
                          status: response.status)
  end
  OpenStruct.new(body: parse_success_response(response.body),
                 headers: response.headers,
                 status: response.status)
rescue *NETWORKABLE_EXCEPTIONS => error
  OpenStruct.new(body: rescue_faraday_error(error))
end

.get_rate_limit_remaining(headers) ⇒ Object

currently supported by Twitter and Github with slightly different header names use arbitrary high value if not supported



222
223
224
# File 'lib/maremma.rb', line 222

def self.get_rate_limit_remaining(headers)
  (headers["X-Rate-Limit-Remaining"] || headers["X-RateLimit-Remaining"] || 100).to_i
end

.head(url, options = {}) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/maremma.rb', line 97

def self.head(url, options={})
  options[:headers] = set_request_headers(url, options)

  conn = faraday_conn(options)

  conn.options[:timeout] = options[:timeout] || DEFAULT_TIMEOUT

  response = conn.head url, {}, options[:headers]

  # return error if we are close to the rate limit, if supported in headers
  if get_rate_limit_remaining(response.headers) < 10
    return OpenStruct.new(body: { "errors" => [{ 'status' => 429, 'title' => "Too many requests" }] },
                          headers: response.headers,
                          status: response.status)
  end
  OpenStruct.new(headers: response.headers,
                 status: response.status)
rescue *NETWORKABLE_EXCEPTIONS => error
  OpenStruct.new(body: rescue_faraday_error(error))
end

.parse_error_response(string) ⇒ Object



205
206
207
208
209
210
211
212
213
# File 'lib/maremma.rb', line 205

def self.parse_error_response(string)
  string = parse_response(string)

  if string.is_a?(Hash) && string['error']
    string['error']
  else
    string
  end
end

.parse_response(string) ⇒ Object



215
216
217
# File 'lib/maremma.rb', line 215

def self.parse_response(string)
  from_json(string) || from_xml(string) || from_string(string)
end

.parse_success_response(string) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/maremma.rb', line 191

def self.parse_success_response(string)
  string = parse_response(string)

  if string.blank?
    { "data" => nil }
  elsif string.is_a?(Hash) && string['hash']
    { "data" => string['hash'] }
  elsif string.is_a?(Hash) && string['data']
    string
  else
    { "data" => string }
  end
end

.post(url, options = {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/maremma.rb', line 22

def self.post(url, options={})
  options[:data] ||= {}
  options[:headers] = set_request_headers(url, options)

  conn = faraday_conn(options)

  conn.options[:timeout] = options[:timeout] || DEFAULT_TIMEOUT

  response = conn.post url, {}, options[:headers] do |request|
    request.body = options[:data]
  end
  OpenStruct.new(body: parse_success_response(response.body),
                 headers: response.headers,
                 status: response.status)
rescue *NETWORKABLE_EXCEPTIONS => error
  OpenStruct.new(body: rescue_faraday_error(error))
end

.put(url, options = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/maremma.rb', line 40

def self.put(url, options={})
  options[:data] ||= {}
  options[:headers] = set_request_headers(url, options)

  conn = faraday_conn(options)

  conn.options[:timeout] = options[:timeout] || DEFAULT_TIMEOUT

  response = conn.put url, {}, options[:headers] do |request|
    request.body = options[:data]
  end
  OpenStruct.new(body: parse_success_response(response.body),
                 headers: response.headers,
                 status: response.status)
rescue *NETWORKABLE_EXCEPTIONS => error
  OpenStruct.new(body: rescue_faraday_error(error))
end

.rescue_faraday_error(error) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
# File 'lib/maremma.rb', line 179

def self.rescue_faraday_error(error)
  if error.is_a?(Faraday::ResourceNotFound)
    { 'errors' => [{ 'status' => 404, 'title' => "Not found" }] }
  elsif error.is_a?(Faraday::ConnectionFailed)
    { 'errors' => [{ 'status' => "403", 'title' => parse_error_response(error.message) }] }
  elsif error.is_a?(Faraday::TimeoutError) || (error.try(:response) && error.response[:status] == 408)
    { 'errors' => [{ 'status' => 408, 'title' =>"Request timeout" }] }
  else
    { 'errors' => [{ 'status' => 400, 'title' => parse_error_response(error.message) }] }
  end
end

.set_request_headers(url, options = {}) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/maremma.rb', line 139

def self.set_request_headers(url, options={})
  options[:headers] ||= {}

  # set useragent
  options[:headers]['User-Agent'] = ENV['HOSTNAME'].present? ? "Maremma - http://#{ENV['HOSTNAME']}" : "Maremma - https://github.com/datacite/maremma"

  # set host, needed for some services behind proxy
  if options[:host]
    options[:headers]['Host'] = URI.parse(url).host
  end

  if options[:content_type].present?
    content_type_headers = { "html" => 'text/html; charset=UTF-8',
                             "xml" => 'application/xml',
                             "json" => 'application/json' }
    options[:headers]['Content-type'] = content_type_headers.fetch(options[:content_type], options[:content_type])
  end

  if options[:accept].present?
    accept_headers = { "html" => 'text/html; charset=UTF-8',
                       "xml" => 'application/xml',
                       "json" => 'application/json' }
    options[:headers]['Accept'] = accept_headers.fetch(options[:accept], options[:accept])
  else
    # accept all content
    options[:headers]['Accept'] ||= "text/html,application/json,application/xml;q=0.9, text/plain;q=0.8,image/png,*/*;q=0.5"
  end

  if options[:bearer].present?
    options[:headers]['Authorization'] = "Bearer #{options[:bearer]}"
  elsif options[:token].present?
    options[:headers]["Authorization"] = "Token token=#{options[:token]}"
  elsif options[:username].present?
    basic = Base64.encode64("#{options[:username]}:#{options[:password].to_s}")
    options[:headers]["Authorization"] = "Basic #{basic}"
  end

  options[:headers]
end