Class: AmazonAlbumArt::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/amazon-album-art/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(access_key, secret_key, associate_tag, locale) ⇒ Client

Returns a new instance of Client.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
# File 'lib/amazon-album-art/client.rb', line 12

def initialize(access_key, secret_key, associate_tag, locale)
  raise ArgumentError.new("Access, secret key and associate tag are required") if access_key.empty? || secret_key.empty? || associate_tag.empty?
  
  @worker = Sucker.new(
    :locale => "us",
    :key    => access_key, 
    :secret => secret_key,
    :associate_tag => associate_tag
  )
end

Instance Method Details

#search(artist, album, sizes = [:swatch, :small, :thumbnail, :tiny, :medium, :large]) ⇒ Object

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/amazon-album-art/client.rb', line 23

def search(artist, album, sizes = [:swatch, :small, :thumbnail, :tiny, :medium, :large])
  raise ArgumentError.new("An artist and album are required to search") if artist.empty? || album.empty?

  # clean up params, this client may be used repeatedly
  @worker.parameters.reset

  # Prepare a request.
  @worker << {
    "Operation"     => "ItemSearch",
    "SearchIndex"   => "Music",
    "Title"         => album,
    "Artist"        => artist
  }

  # Get a response.
  results = @worker.get

  # Make sure nothing went awry.
  return nil if !check_response?(results, "Error finding album")

  # Now parse it.
  results.map("Item") do |match|
    begin
      attribs = match['ItemAttributes']
      # grab values that were returned
      found_artist, found_album = load_artist(attribs), load_album(attribs)
    rescue StandardError => bang
      # handled error from Sucker in some cases
      next
    end
    # check to see if we have a reasonable match
    next unless !found_album.empty? && !found_artist.empty? && matches?(album, found_album) && matches?(artist, found_artist)

    # remove params not used for image search
    @worker.parameters.reset

    # fetch images
    @worker << {
      "Operation"     => "ItemLookup",
      "IdType"        => "ASIN",
      "ResponseGroup" => "Images",
      "ItemId"        => match["ASIN"]
    }

    # Get a response.
    images = @worker.get

    # Make sure nothing went awry.
    return nil if !check_response?(results, "Error finding images")

    # parse response
    doc = Nokogiri::XML.parse(images.body)

    return { :artist => found_artist, :album => found_album, :images => load_images(doc, sizes) }
  end
  
  return nil # nothing found
end