Skip to content

Instantly share code, notes, and snippets.

@benmcredmond
Created July 22, 2009 12:35
Show Gist options
  • Save benmcredmond/151989 to your computer and use it in GitHub Desktop.
Save benmcredmond/151989 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'hpricot'
require 'net/http'
class AlbumArt
@api_key = "yourapikey"
# get_artwork_url_for_size :size => "small" (|| medium || large)
# :artist => "Artist name", :album => "Album Name"
def self.get_url(params)
sizes = {"small" => "SmallImage", "medium" => "MediumImage", "large" => "LargeImage"}
asin = get_asin_for(params[:album], params[:artist])
unless asin == nil
url = build_url_for_lookup(asin)
xml_data = Net::HTTP.get_response(URI.parse(url)).body
doc = Hpricot.XML(xml_data)
return doc.search("Item").at(sizes[params[:size]]).at("URL").innerHTML
else
return nil
end
end
private
def self.build_url_for_search(album, artist)
# Remove any brackets, eg. (single version)
album = album.gsub /\([^)]*\)/, ''
keywords = CGI::escape("#{album}, #{artist}")
url = "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=#{@api_key}&Operation=ItemSearch&SearchIndex=Music&Keywords=#{keywords}&Count=1"
end
def self.build_url_for_lookup(asin)
url = "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=#{@api_key}&Operation=ItemLookup&ItemId=#{asin}&ResponseGroup=Images"
end
def self.get_asin_for(album, artist)
url = build_url_for_search(album, artist)
xml_data = Net::HTTP.get_response(URI.parse(url)).body
if(xml_data != nil)
doc = Hpricot.XML(xml_data)
unless(doc.search("TotalResults").inner_html.to_i == 0)
return doc.search("Item").at("ASIN").inner_html
else
return nil
end
else
return nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment