本文整理汇总了Python中CDDB类的典型用法代码示例。如果您正苦于以下问题:Python CDDB类的具体用法?Python CDDB怎么用?Python CDDB使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CDDB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cddbRequest
def cddbRequest(self, discInfo):
""" Return disc information from online CDDB, None if request fails """
import CDDB, socket
# Make sure to not be blocked by the request
socket.setdefaulttimeout(consts.socketTimeout)
try:
(status, info) = CDDB.query(discInfo)
if status == 200:
disc = info # Success
elif status == 210:
disc = info[0] # Exact multiple matches
elif status == 211:
disc = info[0] # Inexact multiple matches
else:
raise Exception, "Unknown disc (phase 1 returned %u)" % status
(status, info) = CDDB.read(disc["category"], disc["disc_id"])
if status == 210:
return info
else:
raise Exception, "Unknown disc (phase 2 returned %u)" % status
except:
logger.error("[%s] CDDB request failed\n\n%s" % (MOD_INFO[modules.MODINFO_NAME], traceback.format_exc()))
return None
示例2: get_cddb
def get_cddb(self):
try:
import CDDB, DiscID
except ImportError:
fatal('You need python-cddb (http://cddb-py.sf.net) to convert cds. Please install it.')
disc_id = DiscID.disc_id(DiscID.open(self.dev))
query_info = CDDB.query(disc_id)[1]
if not query_info:
fatal('The disk is not listed in FreeDB, dir2ogg only supports disk listed in MusicBrainz or FreeDB')
if isinstance(query_info, list):
query_info = query_info[0]
read_info = CDDB.read(query_info['category'], query_info['disc_id'])[1]
for track in range(disc_id[1]):
title = {}
title['discid'] = query_info['disc_id']
title['artist'], title['album'] = (track.strip() for track in query_info['title'].split("/"))
title['genre'] = read_info['DGENRE']
title['date'] = read_info['DYEAR']
title['title'] = read_info['TTITLE' + str(track)]
title['tracktotal'] = str(len(range(disc_id[1])) + 1)
title['ntracknumber'] = '0' * (len(title['tracktotal'] ) - len(str(track+1)) ) + str(track+1)
title['tracknumber'] = str(track+1)
for key, val in title.items():
title[key] = unicode(str(val), "ISO-8859-1")
ConvertTrack(self.dev, self.conf, track+1, title)
示例3: get_cddb_info
def get_cddb_info(self):
try:
disc = DiscID.open(self.device)
self.info = DiscID.disc_id(disc)
status, info = CDDB.query(self.info)
except IOError:
return
if status in (210, 211):
info = info[0]
status = 200
if status != 200:
return
(status, info) = CDDB.read(info['category'], info['disc_id'])
title = info['DTITLE'].split(" / ")
for i in range(self.info[1]):
tr = self[i]
tr.set_tag_raw('title',
info['TTITLE' + `i`].decode('iso-8859-15', 'replace'))
tr.set_tag_raw('album',
title[1].decode('iso-8859-15', 'replace'))
tr.set_tag_raw('artist',
title[0].decode('iso-8859-15', 'replace'))
tr.set_tag_raw('year',
info['EXTD'].replace("YEAR: ", ""))
tr.set_tag_raw('genre',
info['DGENRE'])
self.name = title[1].decode('iso-8859-15', 'replace')
event.log_event('cddb_info_retrieved', self, True)
示例4: get_cddb_info
def get_cddb_info(self):
try:
disc = DiscID.open(self.device)
self.info = DiscID.disc_id(disc)
status, info = CDDB.query(self.info)
except IOError:
return
if status in (210, 211):
info = info[0]
status = 200
if status != 200:
return
(status, info) = CDDB.read(info["category"], info["disc_id"])
title = info["DTITLE"].split(" / ")
for i in range(self.info[1]):
tr = self[i]
tr.set_tag_raw("title", info["TTITLE" + str(i)].decode("iso-8859-15", "replace"))
tr.set_tag_raw("album", title[1].decode("iso-8859-15", "replace"))
tr.set_tag_raw("artist", title[0].decode("iso-8859-15", "replace"))
tr.set_tag_raw("year", info["EXTD"].replace("YEAR: ", ""))
tr.set_tag_raw("genre", info["DGENRE"])
self.name = title[1].decode("iso-8859-15", "replace")
event.log_event("cddb_info_retrieved", self, True)
示例5: read
def read(self):
try:
device = DiscID.open()
disc_info = DiscID.disc_id(device)
(query_status, self.query_info) = CDDB.query(disc_info)
except cdrom.error, e:
raise cdrom.error, e
示例6: __init__
def __init__(self):
cdaudio = DiscID.open()
print "CD: ", cdaudio
try:
self.disc_id = DiscID.disc_id(cdaudio)
print "disc_id: ", self.disc_id
self.is_audio_cd = True
except:
print "No CD"
disc_id = None
self.is_audio_cd = False
self.song_list = []
cdaudio.close()
raise
if self.is_audio_cd:
try:
self.query_status, self.query_info = CDDB.query(self.disc_id)
print "query_status: ", self.query_status
print "query_info: ", self.query_info
except:
print 'IOError'
self.song_list = []
cdaudio.close()
self.query_status = 409
self.query_info = {"disc_id": "", "category": "", "title":""}
pass
示例7: query
def query(category, discid, xcode='utf8:utf8'):
#from quodlibet's cddb plugin by Michael Urman
discinfo = {}
tracktitles = {}
read, info = CDDB.read(category, discid, **CLIENTINFO)
if read != 210: return None
xf, xt = xcode.split(':')
for key, value in info.iteritems():
try: value = value.decode('utf-8', 'replace').strip().encode(
xf, 'replace').decode(xt, 'replace')
except AttributeError: pass
if key.startswith('TTITLE'):
try: tracktitles[int(key[6:])] = value
except ValueError: pass
elif key == 'DGENRE': discinfo['genre'] = value
elif key == 'DTITLE':
dtitle = value.strip().split(' / ', 1)
if len(dtitle) == 2:
discinfo['artist'], discinfo['title'] = dtitle
else: discinfo['title'] = dtitle[0].strip()
elif key == 'DYEAR': discinfo['year'] = value
return discinfo, tracktitles
示例8: __init__
def __init__(self, disc_id):
# Assume that no results will be found.
self.artist = _("Unknown artist")
self.length = 0
self.title = _("Unknown title")
self.tracks = []
try:
(query_status, query_info) = CDDB.query(disc_id)
except IOError:
# Set query_status to 0 to act like an unknown CD.
query_status = 0
# See CDDB documentation for more information.
# http://cddb-py.sourceforge.net/CDDB/README
# query_info variable's type depends on query_status
if query_status == 200:
# On 200, a dictionary containing three items is returned
self._get_information_from_result_element(query_info, disc_id)
elif query_status == 210 or query_status == 211:
# On 211 or 210, a list will be returned as the second item.
# Each element of the list will be a dictionary containing
# three items, exactly the same as a single 200 success return.
self._get_information_from_result_element(query_info[0], disc_id)
else:
# No metadata found for this disc
for i in range(disc_id[1]):
self.tracks.append(CompactDiscTrack(i + 1,
_("Unknown track %(num)s.") % {'num': str(i + 1)}, 0))
示例9: run
def run(self):
(status, info) = CDDB.query(self._disc_id,
client_name="dmusic",
client_version="1.0")
if status in [200, 210, 211]:
if status in [210, 211]:
info = sorted(info, key=lambda w: w["category"])
info = info[0]
else:
self.logdebug('Unable to fetch CDDB info, status=%d', status)
(status, info) = CDDB.read(info['category'], info['disc_id'])
if status != 210:
self.logdebug('Unable to fetch CDDB info, status=%d', status)
return
gobject.idle_add(self._cb, self._disc_id, info)
示例10: get_CDDB_tag
def get_CDDB_tag(self, query_status, query_info):
if self.is_audio_cd:
read_status, read_info = CDDB.read(query_info['category'], query_info['disc_id'])
print "read status: ", read_status
print "read info: ", read_info
else:
return
self.song_list = []
if query_status in [200, 210]:
self.is_audio_cd = True
self.cddb_disc_id_b10 = self.disc_id[0]
self.cddb_disc_id_b16 = query_info['disc_id']
self.total_tracks = self.disc_id[1]
if read_status == 210:
for i in range(self.disc_id[1]):
n = "%.02d" %(i + 1)
title = "%s" %(read_info['TTITLE' + `i`])
frame = self.disc_id[i+2]
self.song_list.append({"track_number":int(n), "title":title, "num_frame":frame})
print "Song_list: ", self.song_list
if read_info['DTITLE']:
disc_title = read_info['DTITLE']
else:
disc_title = query_info[0]['title']
self.artist, self.album = re.split(" / ", disc_title)
if "," in self.artist:
a, b = re.split(", ", self.artist)
self.artist = b.title() + " " + a.title()
try:
self.disc_len = read_info['disc_len']
except:
self.disc_len = self.disc_id[2+self.disc_id[1]]
self.year = read_info['DYEAR']
if read_info['DGENRE']:
self.cddb_genre = read_info['DGENRE']
else:
self.cddb_genre = query_info[0]['category']
elif read_status in [401, 402, 403, 409, 417]:
self.error = read_status
else:
return
elif query_status in [211, 202, 403, 409]:
self.error = query_status
try:
cdaudio.close()
except:
pass
return self.error
else:
cdaudio.close()
return
示例11: query
def query(category, discid, xcode='utf8:utf8'):
discinfo = {}
tracktitles = {}
dump = path.join(path.expanduser("~"), '.cddb', category, discid)
try:
for line in file(dump):
if line.startswith("TTITLE"):
track, title = line.split("=", 1)
try: track = int(track[6:])
except (ValueError): pass
else: tracktitles[track] = \
title.decode('utf-8', 'replace').strip()
elif line.startswith("DGENRE"):
discinfo['genre'] = line.split('=', 1)[1].strip()
elif line.startswith("DTITLE"):
dtitle = line.split('=', 1)[1].strip().split(' / ', 1)
if len(dtitle) == 2:
discinfo['artist'], discinfo['title'] = dtitle
else:
discinfo['title'] = dtitle[0].strip()
elif line.startswith("DYEAR"):
discinfo['year'] = line.split('=', 1)[1].strip()
except EnvironmentError: pass
else: return discinfo, tracktitles
read, info = CDDB.read(category, discid, **CLIENTINFO)
if read != 210: return None
try: os.makedirs(path.join(path.expanduser("~"), '.cddb'))
except EnvironmentError: pass
try:
save = file(dump, 'w')
keys = info.keys()
keys.sort()
for key in keys:
print>>save, "%s=%s" % (key, info[key])
save.close()
except EnvironmentError: pass
xf, xt = xcode.split(':')
for key, value in info.iteritems():
try: value = value.decode('utf-8', 'replace').strip().encode(
xf, 'replace').decode(xt, 'replace')
except AttributeError: pass
if key.startswith('TTITLE'):
try: tracktitles[int(key[6:])] = value
except ValueError: pass
elif key == 'DGENRE': discinfo['genre'] = value
elif key == 'DTITLE':
dtitle = value.strip().split(' / ', 1)
if len(dtitle) == 2:
discinfo['artist'], discinfo['title'] = dtitle
else: discinfo['title'] = dtitle[0].strip()
elif key == 'DYEAR': discinfo['year'] = value
return discinfo, tracktitles
示例12: query
def query(self, device):
cdromfd = cdrom.audiocd_open(device)
disc_id = cdrom.audiocd_id(cdromfd)
if kaa.metadata.USE_NETWORK:
try:
(query_stat, query_info) = CDDB.query(disc_id)
except Exception, e:
# Oops no connection
query_stat = 404
示例13: set_category
def set_category(self, cat):
self._clear_md()
cache_path = os.path.join(self.cache_dir, '{0}-{1}'.format(self.fingerprint, cat))
for k,v in cached(lambda:CDDB.read(cat, self.fingerprint)[1])(cache_path).items():
if not v or k[0] not in 'DTE':
continue
elif k == 'DTITLE':
self.metadata[0]['artist'],_,self.metadata[0]['title'] = v.partition(' / ')
elif k == 'DGENRE': self.metadata[0]['genre'] = v
elif k == 'DYEAR': self.metadata[0]['year'] = v
elif k.startswith('TTITLE'): self.metadata[int(k[6:])+1]['title'] = v
示例14: extractAudioCdInfo
def extractAudioCdInfo (self):
""" extract the CD info (album art + artist + tracks), and construct the UPnP items"""
self.cdrom = DiscID.open(self.device_name)
disc_id = DiscID.disc_id(self.cdrom)
(query_status, query_info) = CDDB.query(disc_id)
if query_status in (210, 211):
query_info = query_info[0]
(read_status, read_info) = CDDB.read(query_info['category'], query_info['disc_id'])
# print query_info['title']
# print disc_id[1]
# for i in range(disc_id[1]):
# print "Track %.02d: %s" % (i, read_info['TTITLE' + `i`])
track_count = disc_id[1]
disc_id = query_info['disc_id']
self.disc_title = query_info['title'].encode('utf-8')
tracks = {}
for i in range(track_count):
tracks[i + 1] = read_info['TTITLE' + `i`].decode('ISO-8859-1').encode('utf-8')
self.name = self.disc_title
root_item = Container(None, self.disc_title)
# we will sort the item by "track_number"
def childs_sort(x, y):
return cmp(x.track_number, y.track_number)
root_item.sorting_method = childs_sort
self.set_root_item(root_item)
for number, title in tracks.items():
item = TrackItem(self.device_name, number, "Unknown", title)
external_id = "%s_%d" % (disc_id, number)
root_item.add_child(item, external_id=external_id)
self.info('Sharing audio CD %s', self.disc_title)
reactor.callLater(2, self.checkIfAudioCdStillPresent)
self.init_completed()
示例15: cddb_query
def cddb_query(discid, cache_dir=os.path.expanduser('~/.cache/cddb')):
cache_path = os.path.join(cache_dir, '%08x' % discid[0])
query = cached(lambda:CDDB.query(discid)[1])(cache_path, discid)
categories = {}
if query is None:
raise Exception('Server has no data for this disc')
if isinstance(query, dict):
query = [query]
if isinstance(query, list):
for q in query:
categories[q['category']] = q['title']
return categories