Amarok: Album Release Dates from MusicBrainz

·
This code should* select all the albums in a MySQL Amarok database for which the release year is unknown, look them up from MusicBrainz and update the database as appropriate. The found year isn't written to the tracks' ID3 tags, unfortunately, as there doesn't seem to be a DCOP call to update the year.

Then you can make a smart playlist like this:

* NOTE: backup your database first


#! /usr/bin/env python
import sys, time, MySQLdb
from musicbrainz2.webservice import Query, ReleaseFilter
db = MySQLdb.connect(db="DB_NAME", user="DB_USER", passwd="DB_PASS", use_unicode=True, charset="utf8")
c = db.cursor()
c.execute("""SELECT a.name as 'artist', a.id as 'artist_id', b.name as 'album', b.id as 'album_id' FROM `artist` a INNER JOIN `tags` t ON a.id = t.artist INNER JOIN `album` b ON t.album = b.id WHERE t.year = 1 AND t.sampler = 0 GROUP BY a.id, b.id ORDER BY a.name ASC""")
print "%d rows" % c.rowcount
albums = c.fetchall()
for (artist, artist_id, album, album_id) in albums:  
  if (artist and album):
    time.sleep(1)
    
    q = Query()
    print "Looking up: %s - %s" % (artist, album)
    f = ReleaseFilter(artistName=artist, title=album, limit=1)
    results = q.getReleases(f)
    
    if results:
      result = results[0]
      release = result.release
      
      print "Found: %s - %s" % (release.artist.name, release.title)
      
      if (release.releaseEvents and release.releaseEvents[0].date):
        ymd = release.releaseEvents[0].date.split('-');
        print ymd[0];
        c.execute ("""SELECT `id` FROM `year` WHERE `name` = %s""", (ymd[0]))
        year_id = c.fetchone()
        if year_id:
          c.execute ("""UPDATE tags SET year = %s WHERE artist = %s AND album = %s""", (year_id[0], artist_id, album_id))
        
    else:
      print "No results"
  print
c.close()
db.close()