Skip to content

Instantly share code, notes, and snippets.

@Floppy
Created August 5, 2009 21:13
Show Gist options
  • Save Floppy/162965 to your computer and use it in GitHub Desktop.
Save Floppy/162965 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "rubygems"
require "mp3info"
require "net/http"
require 'cgi'
require 'zlib'
require 'stringio'
require 'rexml/document'
API_KEY = "xxxxxxxxxx"
def get_year(artist, album)
@@cache ||= {}
unless @@cache.has_key?([artist, album])
# Search discogs.com
search = "\"#{artist}\" \"#{album}\""
res = Net::HTTP.start("www.discogs.com") do |http|
http.get("/search?type=all&q=#{CGI::escape(search)}&f=xml&api_key=#{API_KEY}", "Accept-Encoding" => "gzip")
end
body = Zlib::GzipReader.new(StringIO.new(res.body)).read rescue res.body
# Parse XML to get release ID
doc = REXML::Document.new(body)
result = REXML::XPath.first(doc, "//result[@type='release']/uri").text rescue ""
match = result.match /.*release\/(.*)/
if match
release = match[1]
# Get release and find year
res = Net::HTTP.start("www.discogs.com") do |http|
http.get("/release/#{release}?f=xml&api_key=#{API_KEY}", "Accept-Encoding" => "gzip")
end
body = Zlib::GzipReader.new(StringIO.new(res.body)).read
doc = REXML::Document.new(body)
year = REXML::XPath.first(doc, "//released").text.to_i
# Store in file
@@cache[[artist, album]] = year
else
@@cache[[artist, album]] = nil
end
end
@@cache[[artist, album]]
end
# read and display infos & tags
ARGV.each do |file|
Mp3Info.open(file) do |mp3info|
unless mp3info.tag.year
year = get_year(mp3info.tag.artist, mp3info.tag.album)
if year
puts "Setting #{mp3info.tag.album} (#{mp3info.tag.artist}) to #{year}"
mp3info.tag.year = year
else
puts "Couldn't find #{mp3info.tag.album} (#{mp3info.tag.artist})"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment