Created
January 5, 2009 10:56
-
-
Save mrkn/43354 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/ruby -Ku | |
# To rewrite URL, the following may be written in .htaccess: | |
# | |
# RewriteEngine On | |
# RewriteBase ^/path/to | |
# RewriteRule ^([\dX]+) /path/to/?$1 [L,R] | |
def isbn10_check_digit(common) | |
d = common.split(//) | |
c = (11 - (2..10).inject(0) {|a, x| a + x*d[10-x].to_i} % 11) % 11 | |
return c == 10 ? 'X' : c.to_s | |
end | |
def isbn13_check_digit(common) | |
d = [9, 7, 8] + common.split(//) | |
c = (10 - d.zip([1,3]*6).inject(0) {|a, x| a + x[0].to_i*x[1]} % 10) % 10 | |
return c.to_s | |
end | |
def check_isbn10(isbn10) | |
d = isbn10.split(//) | |
c = isbn10_check_digit(d[0,9].join) | |
return c == d[-1] | |
end | |
def check_isbn13(isbn13) | |
d = isbn13.split(//) | |
c = isbn13_check_digit(d[3,9].join) | |
return c == d[-1] | |
end | |
def isbn10_to_13(isbn10) | |
if isbn10 =~ /\A(\d{9})[\dX]\Z/ | |
common = $1 | |
if check_isbn10(isbn10) | |
return '978' + common + isbn13_check_digit(common) | |
end | |
end | |
return nil | |
end | |
def isbn13_to_10(isbn13) | |
if isbn13 =~ /\A978(\d{9})\d\Z/ | |
common = $1 | |
if check_isbn13(isbn13) | |
return common + isbn10_check_digit(common) | |
end | |
end | |
return nil | |
end | |
isbn = ENV['QUERY_STRING'] | |
if isbn.nil? | |
print "Location: http://www.amazon.co.jp/\r\n" | |
print "\r\n" | |
exit | |
end | |
isbn10 = nil | |
isbn13 = nil | |
if isbn =~ /\A(\d{9})([\dX])\Z/ | |
if check_isbn10(isbn) | |
isbn10 = isbn | |
isbn13 = isbn10_to_13(isbn10) | |
end | |
elsif isbn =~ /\A978(\d{9})(\d)\Z/ | |
if check_isbn13(isbn) | |
isbn13 = isbn | |
isbn10 = isbn13_to_10(isbn13) | |
end | |
end | |
#$stderr.puts "#{isbn.inspect}, #{isbn10.inspect}, #{isbn13.inspect}" | |
if isbn10 | |
location = "http://www.amazon.co.jp/dp/#{isbn10}/mrkn-22" | |
else | |
location = "http://www.amazon.co.jp/" | |
end | |
print "Location: #{location}\r\n" | |
print "X-ISBN10: #{isbn10}\r\n" | |
print "X-ISBN13: #{isbn13}\r\n" | |
print "\r\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment