Skip to content

Commit

Permalink
convert ISBN13 to ISBN10 in amazon plugin
Browse files Browse the repository at this point in the history
* PA-API v5 not support ISBN13 (but supported by v4)
* downgrade 13->10 automaticaly when ISBN13 specified
  • Loading branch information
tdtds committed Nov 24, 2019
1 parent df19a2a commit df03d69
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
7 changes: 7 additions & 0 deletions lib/aws/pa_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def initialize(access_key, secret_key, partner_tag)
end

def get_items(asin, locale)
asin = isbn13to10(asin) if asin.length == 13
payload = {
"PartnerTag" => @partner_tag,
"PartnerType" => "Associates",
Expand Down Expand Up @@ -61,5 +62,11 @@ def get_items(asin, locale)
response.value # raise on errors
return response.body
end

private
def isbn13to10(isbn13)
sum, = isbn13[3, 9].split(//).map(&:to_i).reduce([0,10]){|s,d|[s[0] + d * s[1], s[1]-1]}
return isbn13[3, 9] + %w(0 1 2 3 4 5 6 7 8 9 X 0)[11 - sum % 11]
end
end
end
21 changes: 9 additions & 12 deletions misc/plugin/amazon.rb
Original file line number Diff line number Diff line change
Expand Up @@ -138,29 +138,25 @@ def amazon_to_html(item, with_image = true, label = nil, pos = 'amazon')
end

def amazon_get(asin, with_image = true, label = nil, pos = 'amazon')
asin = asin.to_s.strip # delete white spaces
asin.sub!(/\A([a-z]+):/, '')
country = $1 || @conf['amazon.default_country'] || @amazon_default_country
digit = asin.gsub( /[^\d]/, '' )
if digit.length == 13 then # ISBN-13
asin = digit
id_type = /^97[89]/ =~ digit ? 'ISBN' : 'EAN'
else
id_type = 'ASIN'
asin = asin.to_s.strip.gsub(/-/, '')
country, item_id = asin.scan(/\A(..):(.*)/).flatten
unless country
country = @conf['amazon.default_country'] || @amazon_default_country
item_id = asin
end

begin
cache = "#{@cache_path}/amazon"
Dir::mkdir( cache ) unless File::directory?( cache )
begin
json = JSON.parse(File::read("#{cache}/#{country}#{asin}.json"))
json = JSON.parse(File::read("#{cache}/#{country}#{item_id}.json"))
rescue Errno::ENOENT
access_key = @conf['amazon.access_key']
secret_key = @conf['amazon.secret_key']
partner_tag = @conf['amazon.aid']
paapi = AWS::PAAPI.new(access_key, secret_key, partner_tag)
json = paapi.get_items(asin, country.to_sym)
File::open("#{cache}/#{country}#{asin}.json", 'wb'){|f| f.write(json)}
json = paapi.get_items(item_id, country.to_sym)
File::open("#{cache}/#{country}#{item_id}.json", 'wb'){|f| f.write(json)}
end
item = json["ItemsResult"]["Items"][0]
if pos == 'detail' then
Expand All @@ -169,6 +165,7 @@ def amazon_get(asin, with_image = true, label = nil, pos = 'amazon')
amazon_to_html(item, with_image, label, pos)
end
rescue Net::HTTPUnauthorized
p country, item_id
@logger.error "amazon.rb: Amazon API Unauthorized."
message = asin
if @mode == 'preview' then
Expand Down

0 comments on commit df03d69

Please sign in to comment.