#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import sqlite3
import mutagen.id3
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
from subprocess import call
def getStuff(database):
conn = sqlite3.connect(database)
c = conn.cursor()
result = c.execute("SELECT LocalCopyPath, Title, Album, Artist, Composer, Genre, Year FROM MUSIC WHERE Id IN (SELECT MusicId FROM SHOULDKEEPON)")
stuff = []
for track in result:
stuff.append(track)
# Let's be good programmers and close the connection to database, even though there were only read operations
conn.close()
return stuff
def parseStuff(musicdir, stuff):
for item in stuff:
records = []
for record in item:
if type(record) == "list":
records.append(record[0])
else:
records.append(record)
# Have to do it this way since Mutagen's methods often change string to lists
title = records[1]
album = records[2]
artist = records[3]
composer = records[4]
genre = records[5]
date = str(records[6])
audiofile = musicdir + "/" + records[0]
audio = MP3(audiofile, ID3=EasyID3)
try:
audio.add_tags(ID3=EasyID3)
except mutagen.id3.error:
pass
audio['title'] = title
audio['album'] = album
audio['artist'] = artist
audio['composer'] = composer
audio['genre'] = genre
audio['date'] = date
audio.save()
if artist == "":
artist = "Unknown Artist"
newFileName = "%s/%s - %s.mp3" % (musicdir, artist.replace('/', '|'), title.replace('/', '|'))
call(["mv", audiofile, newFileName])
if __name__ == "__main__":
from optparse import OptionParser
from sys import exit
parser = OptionParser()
parser.add_option('-d', '--database', dest="database", help="Google Music database file", metavar="DB")
parser.add_option('-i', '--musicdir', dest="musicdir", help="Directory with Google Music cache of MP3s", metavar="MP3")
(options, args) = parser.parse_args()
if not options.database or not options.database:
parser.error("You must specify both database and musicdir! See --help.")
musicdir = options.musicdir
db = options.database
try:
parseStuff(musicdir, getStuff(db))
except KeyboardInterrupt:
print "Canceled by user."
exit(2)
exit(0)