Class: Teapi::Sender

Inherits:
Object
  • Object
show all
Defined in:
lib/teapi/sender.rb

Constant Summary collapse

BASE_URL =
'/v1/'
HEADERS =
{'Accept' => 'application/json'}

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Sender

Returns a new instance of Sender.



14
15
16
# File 'lib/teapi/sender.rb', line 14

def initialize(configuration)
  @configuration = configuration
end

Instance Method Details

#gzip(body) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/teapi/sender.rb', line 44

def gzip(body)
  io = StringIO.new("w")
  gz = Zlib::GzipWriter.new(io)
  gz.write(body)
  gz.close
  io.string
end

#request(method, resource, args = {}, date = nil) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/teapi/sender.rb', line 18

def request(method, resource, args = {}, date = nil)
  url = BASE_URL + resource.to_s
  d = date || Time.now.httpdate
  args[:headers] = (args[:headers] || {}).merge({
    'Date' => d,
    'Authorization' => sign(url, d, args),
  })
  if args[:body] != nil && args[:body].length > 1024 then
    args[:body] = gzip(args[:body])
    args[:headers]['Content-Encoding'] = 'gzip'
  end
  scheme = @configuration.secure ? "https" : "http"
  res = HTTParty.send(method, "#{scheme}://#{@configuration.host}#{url}", args)
  if res.code == 401 && res.parsed_response.include?('date') && date.nil?
    return request(method, resource, args, res.parsed_response['date'])
  end
  res
end

#sign(url, date, args) ⇒ Object



37
38
39
40
41
42
# File 'lib/teapi/sender.rb', line 37

def sign(url, date, args)
  data = url + date
  data += args[:body] if args.include?(:body)
  signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @configuration.sync_secret, data)
  "HMAC-SHA256 Credential=#{@configuration.sync_key},Signature=#{signature}"
end