Class: Google::AMP::Cache::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/google/amp/cache/client.rb

Constant Summary collapse

UPDATE_CACHE_API_DOMAIN_SUFFIX =
'cdn.ampproject.org'
DIGEST =
OpenSSL::Digest::SHA256.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil, private_key = nil) ⇒ Client

Returns a new instance of Client.



15
16
17
18
# File 'lib/google/amp/cache/client.rb', line 15

def initialize(api_key = nil, private_key = nil)
  @google_api_key = api_key
  @private_key = OpenSSL::PKey::RSA.new(private_key) if private_key
end

Instance Attribute Details

#google_api_keyObject (readonly)

Returns the value of attribute google_api_key.



13
14
15
# File 'lib/google/amp/cache/client.rb', line 13

def google_api_key
  @google_api_key
end

#private_keyObject (readonly)

Returns the value of attribute private_key.



13
14
15
# File 'lib/google/amp/cache/client.rb', line 13

def private_key
  @private_key
end

Instance Method Details

#batch_get(urls, lookup_strategy = :FETCH_LIVE_DOC) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/google/amp/cache/client.rb', line 20

def batch_get(urls, lookup_strategy = :FETCH_LIVE_DOC)
  post('/ampUrls:batchGet',
    body: {
      urls: Array(urls),
      lookupStrategy: lookup_strategy
    }.to_json,
    headers: {
      'Content-Type' => 'application/json',
      "X-Goog-Api-Key" => google_api_key
    })
end

#format_domain(url) ⇒ Object



61
62
63
# File 'lib/google/amp/cache/client.rb', line 61

def format_domain(url)
  url.gsub('-', '--').tr('.', '-')
end

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



65
66
67
68
# File 'lib/google/amp/cache/client.rb', line 65

def post(path, opts={})
  response = self.class.post(path, opts)
  response.parsed_response
end

#short_content_type(type) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/google/amp/cache/client.rb', line 50

def short_content_type(type)
  case type.to_sym
  when :document
    'c'
  when :image
    'i'
  when :resource
    'r'
  end
end

#update_cache(url, content_type = :document) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/google/amp/cache/client.rb', line 32

def update_cache(url, content_type = :document)
  page_uri = URI.parse(url)
  subdomain = format_domain(page_uri.host)

  api_host = URI.parse(["https://", subdomain, '.', UPDATE_CACHE_API_DOMAIN_SUFFIX].join)
  params = {
    amp_action: 'flush',
    amp_ts: Time.now.to_i
  }

  api_path = "/update-cache/#{short_content_type(content_type)}/#{'s/' if page_uri.scheme.match?('https')}#{page_uri.host}#{page_uri.path}?#{Rack::Utils.build_query(params)}"
  sig = private_key.sign(DIGEST, api_path)
  signature = Base64.urlsafe_encode64(sig)

  result = self.class.get("#{api_host}#{api_path}&amp_url_signature=#{signature}")
  result.ok?
end