#!/usr/bin/env ruby require "amazon/search" require "rubygems" require "id3lib" require "tmpdir" require "find" require "net/http" @covercache = Hash.new def get_cover(artist, title) if @covercache.has_key?(title + artist) then return @covercache[title + artist] end puts "searching #{artist} - #{title}" dir = Dir::tmpdir + "/" begin req = Amazon::Search::Request.new "" res = req.keyword_search(artist + " " + title, 'music') if !res.products[0].image_url_medium.nil? url = res.products[0].image_url_medium elsif !res.products[0].image_url_small.nil? url = res.products[0].image_url_small end if url.nil? then return nil end urlparts = url.split("/") if !File.exist?(dir + urlparts[5]) Net::HTTP.start(urlparts[2]) do |http| resp = http.get("/"+urlparts[3..5].join("/")) open(dir + urlparts[5], "wb") do |file| file.write(resp.body) end end end rescue STDERR.puts "no match found for query" return nil end @covercache[title + artist] = dir + urlparts[5] return dir + urlparts[5] end def insert_cover(tag, file) puts "inserting #{file}" cover = { :id => :APIC, :mimetype => 'image/jpeg', :picturetype => 3, :description => "Album cover for #{tag.artist} - #{tag.title}", :textenc => 0, :data => File.read(file) } tag << cover tag.update! end def traverse_music(root) Find.find(root) do |path| filetype = File.basename(path.downcase).split(".").last if ['mp3'].include?(filetype) then yield path end end end covertmps = [] traverse_music(ARGV[0]) do |file| tag = ID3Lib::Tag.new(file) if tag.artist.nil? or tag.album.nil? then next end if tag.frame(:APIC).nil? coverfile = get_cover(tag.artist, tag.album) if !coverfile.nil? covertmps.push(coverfile) insert_cover(tag, coverfile) end else puts "#{file} already has a cover attached!" end end #covertmps.collect{|file| File.unlink(file)}