#!/usr/bin/python import mad, sys, os, urllib, re class cddbsearch: """ Simple front-end to the web-interface of CDDB Create an object by passing it a path to a directory of mp3's. Then call the search function to see if theres a result. If there is a result, an array of dictionaries will be returned. The dictionary holds the genre, cddbid, and title of the results. You may return the tracks of a specific result using the getResult function. """ error = '' discid = '' frames = '' total_time = 0 numfiles = 0 tracknames = [] def __init__(self, dir): if not os.path.isdir(dir): self.error = 'Path does not exist' return 0 else: files = [] for file in os.listdir(dir): (name, ext) = os.path.splitext(file) if ext.lower() == '.mp3': files.append(os.path.join(dir, file)) files.sort() for file in files: totalframes = self.total_time * 75 self.frames = self.frames + str(totalframes) + " " ff = mad.MadFile(file) milli = ff.total_time() track_time = milli / 1000 n = self.cddb_sum(self.total_time) self.total_time += track_time self.numfiles = self.numfiles + 1 tmp = ((long(n) % 0xFF) << 24 | self.total_time << 8 | self.numfiles) self.discid = '%08lx' % tmp def search(self): searchstring = self.discid + " " + str(self.numfiles) + " " + self.frames + str(self.total_time) searchstring = searchstring.replace(' ', '+') results = urllib.urlopen('http://freedb.freedb.org/~cddb/cddb.cgi?cmd=cddb+query+' + searchstring + '&hello=cddbsearch+localhost+xmcd+2.1&proto=6') result = results.readlines()[1:-1] f = [] for i in result: genre = i.split(' ')[0] cddbid = i.split(' ')[1] title = ' '.join(i.split(' ')[2:]).rstrip("\r\n") f.append({'genre':genre,'cddbid':cddbid,'title':title}) return f def getResult(self, genre, cddbid): searchstring = genre + " " + cddbid searchstring = searchstring.replace(' ', '+') results = urllib.urlopen('http://freedb.freedb.org/~cddb/cddb.cgi?cmd=cddb+read+' + searchstring + '&hello=cddbsearch+localhost+xmcd+2.1&proto=6') if results: for line in results: if re.compile(r'^TTITLE').match(line): trackname = re.compile(r'^TTITLE\d+=').sub('',line) self.tracknames.append(trackname.rstrip("\n")) def cddb_sum(self, n): ret = 0 while n > 0: ret = ret + (n % 10) n = n / 10 return ret