Class: Tml::Api::Client

Inherits:
Base
  • Object
show all
Defined in:
lib/tml/api/client.rb

Direct Known Subclasses

PostOffice

Constant Summary collapse

API_PATH =
'/v1'

Instance Attribute Summary

Attributes inherited from Base

#attributes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

attributes, belongs_to, has_many, #hash_value, hash_value, #initialize, #method_missing, #to_hash, #update_attributes

Constructor Details

This class inherits a constructor from Tml::Base

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Tml::Base

Class Method Details

.error?(data) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/tml/api/client.rb', line 63

def self.error?(data)
  not data['error'].nil?
end

Instance Method Details

#api(path, params = {}, opts = {}) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/tml/api/client.rb', line 146

def api(path, params = {}, opts = {})
  # inline mode should always bypass API calls
  # get request uses local cache, then CDN, the API
  if enable_cache?(opts)
    verify_cache_version
    data = Tml.cache.fetch(opts[:cache_key]) do
      if Tml.cache.read_only?
        nil
      else
        get_from_cdn(opts[:cache_key]) || execute_request(path, params, opts)
      end
    end
    process_response(data, opts)
  else
    process_response(execute_request(path, params, opts), opts)
  end
end

#cdn_connectionObject



91
92
93
94
95
96
# File 'lib/tml/api/client.rb', line 91

def cdn_connection
  @cdn_connection ||= Faraday.new(:url => application.cdn_host) do |faraday|
    faraday.request(:url_encoded)               # form-encode POST params
    faraday.adapter(Faraday.default_adapter)    # make requests with Net::HTTP
  end
end

#connectionObject



67
68
69
70
71
72
73
# File 'lib/tml/api/client.rb', line 67

def connection
  @connection ||= Faraday.new(:url => application.host) do |faraday|
    faraday.request(:url_encoded)               # form-encode POST params
    # faraday.response :logger                  # log requests to STDOUT
    faraday.adapter(Faraday.default_adapter)    # make requests with Net::HTTP
  end
end

#delete(path, params = {}, opts = {}) ⇒ Object



59
60
61
# File 'lib/tml/api/client.rb', line 59

def delete(path, params = {}, opts = {})
  api(path, params, opts.merge(:method => :delete))
end

#enable_cache?(opts) ⇒ Boolean

Returns:

  • (Boolean)


137
138
139
140
141
142
143
144
# File 'lib/tml/api/client.rb', line 137

def enable_cache?(opts)
  return false unless opts[:method] == :get
  return false if opts[:cache_key].nil?
  return false unless Tml.cache.enabled?
  return false if live_translations_request?(opts[:cache_key])
  return false if Tml.session.inline_mode?
  true
end

#execute_request(path, params = {}, opts = {}) ⇒ Object

Raises:



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/tml/api/client.rb', line 199

def execute_request(path, params = {}, opts = {})
  response = nil
  error = nil

  # oauth path is separate from versioned APIs
  path = prepare_api_path(path)
  params = params.merge(:access_token => application.token) unless path.index('oauth')

  if opts[:method] == :post
    params = params.merge(:api_key => application.key)
  end

  @compressed = false
  trace_api_call(path, params, opts.merge(:host => application.host)) do
    begin
      if opts[:method] == :post
        response = connection.post(path, params)
      elsif opts[:method] == :put
        response = connection.put(path, params)
      elsif opts[:method] == :delete
        response = connection.delete(path, params)
      else
        response = connection.get do |request|
          @compressed = true
          prepare_request(request, path, params)
        end
      end
    rescue Exception => ex
      Tml.logger.error("Failed to execute request: #{ex.message[0..255]}")
      error = ex
      nil
    end
  end
  raise Tml::Exception.new("Error: #{error}") if error

  if response.status >= 500 and response.status < 600
    raise Tml::Exception.new("Error: #{response.body}")
  end

  if @compressed
    compressed_data = response.body
    return if compressed_data.nil? or compressed_data == ''

    data = Zlib::GzipReader.new(StringIO.new(compressed_data.to_s)).read
    Tml.logger.debug("Compressed: #{compressed_data.length} Uncompressed: #{data.length}")
  else
    data = response.body
  end

  return data if opts[:raw]

  begin
    data = JSON.parse(data)
  rescue Exception => ex
    raise Tml::Exception.new("Failed to parse response: #{ex.message[0..255]}")
  end

  if data.is_a?(Hash) and not data['error'].nil?
    raise Tml::Exception.new("Error: #{data['error']}")
  end

  data
end

#get(path, params = {}, opts = {}) ⇒ Object



47
48
49
# File 'lib/tml/api/client.rb', line 47

def get(path, params = {}, opts = {})
  api(path, params, opts.merge(:method => :get))
end

#get_cache_versionObject



75
76
77
# File 'lib/tml/api/client.rb', line 75

def get_cache_version
  execute_request('projects/current/version', {}, {:raw => true})
end

#get_from_cdn(key, params = {}, opts = {}) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/tml/api/client.rb', line 98

def get_from_cdn(key, params = {}, opts = {})
  return nil if Tml.cache.version == 'undefined' || Tml.cache.version.to_s == '0'

  response = nil
  cdn_path = "/#{application.key}/#{Tml.cache.version}/#{key}.json.gz"
  trace_api_call(cdn_path, params, opts.merge(:host => application.cdn_host)) do
    begin
      response = cdn_connection.get do |request|
        prepare_request(request, cdn_path, params)
      end
    rescue Exception => ex
      Tml.logger.error("Failed to execute request: #{ex.message[0..255]}")
      return nil
    end
  end
  return if response.status >= 500 and response.status < 600
  return if response.body.nil? or response.body == '' or response.body.match(/xml/)

  compressed_data = response.body
  return if compressed_data.nil? or compressed_data == ''

  data = Zlib::GzipReader.new(StringIO.new(compressed_data.to_s)).read
  Tml.logger.debug("Compressed: #{compressed_data.length} Uncompressed: #{data.length}")

  begin
    data = JSON.parse(data)
  rescue Exception => ex
    return nil
  end

  data
end

#live_translations_request?(cache_key) ⇒ Boolean

Returns:

  • (Boolean)


131
132
133
134
135
# File 'lib/tml/api/client.rb', line 131

def live_translations_request?(cache_key)
  return if cache_key.blank?
  return unless Tml.session.block_option(:live)
  cache_key.index('sources') or cache_key.index('keys')
end

#object_class(opts) ⇒ Object



263
264
265
266
# File 'lib/tml/api/client.rb', line 263

def object_class(opts)
  return unless opts[:class]
  opts[:class].is_a?(String) ? opts[:class].constantize : opts[:class]
end

#paginate(path, params = {}, opts = {}) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/tml/api/client.rb', line 164

def paginate(path, params = {}, opts = {})
  data = get(path, params, opts.merge({'raw' => true}))

  while data
    if data['results'].is_a?(Array)
      data['results'].each do |result|
        yield(result)
      end
    else
      yield(data['results'])
    end

    if data['pagination'] and data['pagination']['links']['next']
      data = get(data['pagination']['links']['next'], {}, opts.merge({'raw' => true}))
    else
      data = nil
    end
  end
end

#post(path, params = {}, opts = {}) ⇒ Object



51
52
53
# File 'lib/tml/api/client.rb', line 51

def post(path, params = {}, opts = {})
  api(path, params, opts.merge(:method => :post))
end

#prepare_api_path(path) ⇒ Object



184
185
186
187
188
# File 'lib/tml/api/client.rb', line 184

def prepare_api_path(path)
  return path if path.index('oauth')
  return path if path.match(/^https?:\/\//)
  "#{API_PATH}#{path[0] == '/' ? '' : '/'}#{path}"
end

#prepare_request(request, path, params) ⇒ Object



190
191
192
193
194
195
196
197
# File 'lib/tml/api/client.rb', line 190

def prepare_request(request, path, params)
  request.options.timeout = 5
  request.options.open_timeout = 2
  request.headers['User-Agent']       = "tml-ruby v#{Tml::VERSION} (Faraday v#{Faraday::VERSION})"
  request.headers['Accept']           = 'application/json'
  request.headers['Accept-Encoding']  = 'gzip, deflate'
  request.url(path, params)
end

#process_response(data, opts) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/tml/api/client.rb', line 268

def process_response(data, opts)
  return nil if data.nil?
  return data if opts[:raw] or opts[:raw_json]

  if data.is_a?(Hash) and data['results']
    #Tml.logger.debug("received #{data['results'].size} result(s)")
    return data['results'] unless object_class(opts)
    objects = []
    data['results'].each do |data|
      objects << object_class(opts).new(data.merge(opts[:attributes] || {}))
    end
    return objects
  end

  return data unless object_class(opts)
  object_class(opts).new(data.merge(opts[:attributes] || {}))
end

#put(path, params = {}, opts = {}) ⇒ Object



55
56
57
# File 'lib/tml/api/client.rb', line 55

def put(path, params = {}, opts = {})
  api(path, params, opts.merge(:method => :put))
end

#results(path, params = {}, opts = {}) ⇒ Object

get results from api



43
44
45
# File 'lib/tml/api/client.rb', line 43

def results(path, params = {}, opts = {})
  get(path, params, opts)['results']
end

#to_query(hash) ⇒ Object



286
287
288
289
290
291
292
# File 'lib/tml/api/client.rb', line 286

def to_query(hash)
  query = []
  hash.each do |key, value|
    query << "#{key}=#{value}"
  end
  query.join('&')
end

#trace_api_call(path, params, opts = {}) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/tml/api/client.rb', line 294

def trace_api_call(path, params, opts = {})
  #[:client_secret, :access_token].each do |param|
  #  params = params.merge(param => "##filtered##") if params[param]
  #end

  path = "#{path[0] == '/' ? '' : '/'}#{path}"

  if opts[:method] == :post
    Tml.logger.debug("post: #{opts[:host]}#{path}")
  else
    if params.any?
      Tml.logger.debug("get: #{opts[:host]}#{path}?#{to_query(params)}")
    else
      Tml.logger.debug("get: #{opts[:host]}#{path}")
    end
  end

  t0 = Time.now
  if block_given?
    ret = yield
  end
  t1 = Time.now

  Tml.logger.debug("call took #{t1 - t0} seconds")
  ret
end

#verify_cache_versionObject



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/tml/api/client.rb', line 79

def verify_cache_version
  return if Tml.cache.version and Tml.cache.version != 'undefined'

  current_version = Tml.cache.fetch_version
  if current_version == 'undefined'
    Tml.cache.store_version(get_cache_version)
  else
    Tml.cache.version = current_version
  end
  Tml.logger.info("Version: #{Tml.cache.version}")
end