Skip to content

Instantly share code, notes, and snippets.

@yoshuki
Created October 31, 2008 19:29
Show Gist options
  • Save yoshuki/21403 to your computer and use it in GitHub Desktop.
Save yoshuki/21403 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -Ku
require 'net/http'; Net::HTTP.version_1_2
require 'rexml/document'
module Atok_plugin
AWS_ACCESS_KEY_ID = '0123456789ABCDEFGHIJ' # あなたの「AWS Access Key ID」に置き換えてください。
def run_process(request)
doc = REXML::Document.new(fetch_amazon(request['composition_string']))
candidates = doc.elements.to_a('/ItemSearchResponse/Items/Item').map do |item|
candidate = {'hyoki' => '',
'comment' => '',
'alternative' => '',
'alternative_type' => 'url_jump_string'}
candidate['alternative'] << item.elements['DetailPageURL'].text
creators = []
item.elements.each('ItemAttributes/*') do |item_attribute|
case item_attribute.name
when 'Title'; candidate['hyoki'] << item_attribute.text
when 'ListPrice'; candidate['comment'] << item_attribute.elements['FormattedPrice'].text
when 'Creator'; creators << "(#{item_attribute.elements['@Role'].value})#{item_attribute.text}"
end
end
candidate['comment'] << ('\\n' << creators.join('\\n')) unless creators.empty?
candidate
end
{'candidate' => candidates}
rescue TimeoutError => evar
nil
rescue => evar
nil
end
private
def fetch_amazon(keywords)
url = 'http://ecs.amazonaws.jp/onca/xml?Service=AWSECommerceService&Version=2008-10-07' <<
"&AWSAccessKeyId=#{AWS_ACCESS_KEY_ID}" <<
"&Operation=ItemSearch" <<
"&SearchIndex=Blended" <<
"&ResponseGroup=ItemAttributes" <<
"&Keywords=#{URI.encode(keywords)}"
http_response = Net::HTTP.get_response(URI.parse(url))
unless http_response.is_a?(Net::HTTPOK)
raise 'Invalid http response.'
else
http_response.body
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment