Module: ApiBucket::Amazon::Client::Http

Included in:
ApiBucket::Amazon::Client
Defined in:
lib/api_bucket/amazon/client/http.rb

Instance Method Summary collapse

Instance Method Details

#camelize(s) ⇒ Object



56
57
58
# File 'lib/api_bucket/amazon/client/http.rb', line 56

def camelize(s)
  s.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
end

#prepare_query(options) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/api_bucket/amazon/client/http.rb', line 25

def prepare_query(options)
  query = ''

  secret_key = options.delete(:a_w_s_secret_key)
  request_host = URI.parse(REQUEST_URL).host

  options = options.sort do |c,d|
    c[0].to_s <=> d[0].to_s
  end

  options = options.collect do |a,b|
    [camelize(a.to_s), b.to_s]
  end

  options.each do |key, value|
    next if value.nil?
    query << "&#{key}=#{self.url_encode(value)}"
  end

  query.slice!(0)

  # only amazon
  signature = ''
  unless secret_key.nil?
    request_to_sign="GET\n#{request_host}\n/onca/xml\n#{query}"
    signature = "&Signature=#{sign_request(request_to_sign, secret_key)}"
  end

  "#{query}#{signature}"
end

#send_request(options) ⇒ Object



4
5
6
7
8
9
# File 'lib/api_bucket/amazon/client/http.rb', line 4

def send_request(options)
  request_url = "#{REQUEST_URL}?#{self.prepare_query(options)}"
  uri = URI::parse(request_url)
  res = Net::HTTP.get_response(uri)
  res.body
end

#sign_request(url, key) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/api_bucket/amazon/client/http.rb', line 11

def sign_request(url, key)
  openssl_digest = OpenSSL::Digest::Digest.new( 'sha256' )
  signature = OpenSSL::HMAC.digest(openssl_digest, key, url)
  signature = [signature].pack('m').chomp
  signature = URI.escape(signature, Regexp.new("[+=]"))
  return signature
end

#url_encode(string) ⇒ Object



19
20
21
22
23
# File 'lib/api_bucket/amazon/client/http.rb', line 19

def url_encode(string)
  string.gsub( /([^a-zA-Z0-9_.~-]+)/ ) do
    '%' + $1.unpack( 'H2' * $1.bytesize ).join( '%' ).upcase
  end
end