2 Access a freedb service from Python.
12 socket
.setdefaulttimeout(30) #don't want things to wait forever now do we?
19 def __init__(self
, cddb_server
= 'http://freedb.freedb.org/~cddb/cddb.cgi',
20 app
= "PyCDDB", version
= __version__
):
21 self
.cddb_server
= cddb_server
22 self
.user
= getpass
.getuser()
23 self
.host
= socket
.gethostname()
25 self
.version
= version
35 elif self
.code
== 200:
36 return "Found exact match"
37 elif self
.code
== 202:
38 return "No match found"
39 elif self
.code
== 210:
41 elif self
.code
== 211:
42 return "Found inexact matches"
43 elif self
.code
== 401:
44 return "Specified CDDB entry not found"
45 elif self
.code
== 402:
47 elif self
.code
== 403:
48 return "Database entry is corrupt"
49 elif self
.code
== 409:
52 def query(self
, discid
):
55 self
.track_offset
= map(string
.atoi
, string
.split(discid
)[2:-1])
56 self
.disc_length
= string
.atoi(string
.split(discid
)[-1:][0]) * 75
57 query
= urllib
.quote_plus(string
.rstrip(discid
))
58 url
= "%s?cmd=cddb+query+%s&hello=%s+%s+%s+%s&proto=%d" % \
59 (self
.cddb_server
, query
, self
.user
, self
.host
, self
.app
,
60 self
.version
, self
.protocol
)
61 response
= urllib
.urlopen(url
)
62 header
= response
.readline()
63 if re
.match("[0-9]+.*", header
):
64 self
.code
= string
.atoi(string
.split(header
, ' ', 1)[0])
65 if self
.code
== 200: # Exact match
66 info
= string
.split(header
, ' ', 3)
67 result
.append( { 'category': info
[1], 'disc_id': info
[2], 'title': info
[3] } )
68 elif self
.code
== 210 or self
.code
== 211: # Multiple exact mattches or inexact match
69 line
= string
.rstrip(response
.readline())
71 info
= string
.split(line
, ' ', 2)
72 result
.append( { 'category': info
[0], 'disc_id': info
[1], 'title': info
[2] } )
73 line
= string
.rstrip(response
.readline())
77 def read(self
, query_item
):
79 url
= "%s?cmd=cddb+read+%s+%s&hello=%s+%s+%s+%s&proto=%d" % \
80 (self
.cddb_server
, query_item
['category'], query_item
['disc_id'],
81 self
.user
, self
.host
, self
.app
, self
.version
, self
.protocol
)
82 response
= urllib
.urlopen(url
)
83 header
= response
.readline()
84 self
.code
= string
.atoi(string
.split(header
, ' ', 1)[0])
86 re_indexed_key
= re
.compile("([^=0123456789]+)([0-9]+)=(.*)")
87 re_key
= re
.compile("([^=]+)=(.*)")
88 for line
in response
.readlines():
89 line
= string
.rstrip(line
)
90 m
= re_indexed_key
.match(line
)
92 (key
, index
, data
) = m
.groups()
93 if result
.has_key(key
):
94 result
[key
].append(data
)
97 result
[key
].append(data
)
99 m
= re_key
.match(line
)
101 (key
, data
) = m
.groups()