1 # Python MPD client library
2 # Copyright (C) 2008 J. Alexander Treuman <jat@spatialrift.net>
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 HELLO_PREFIX = "OK MPD "
26 class MPDError(Exception):
29 class ConnectionError(MPDError):
32 class ProtocolError(MPDError):
35 class CommandError(MPDError):
38 class CommandListError(MPDError):
42 class _NotConnected(object):
43 def __getattr__(self, attr):
47 raise ConnectionError("Not connected")
49 class MPDClient(object):
55 "clearerror": self._getnone,
56 "currentsong": self._getobject,
57 "status": self._getobject,
58 "stats": self._getobject,
59 # Playback Option Commands
60 "crossfade": self._getnone,
61 "random": self._getnone,
62 "repeat": self._getnone,
63 "setvol": self._getnone,
64 "volume": self._getnone,
65 # Playback Control Commands
66 "next": self._getnone,
67 "pause": self._getnone,
68 "play": self._getnone,
69 "playid": self._getnone,
70 "previous": self._getnone,
71 "seek": self._getnone,
72 "seekid": self._getnone,
73 "stop": self._getnone,
76 "addid": self._getitem,
77 "clear": self._getnone,
78 "delete": self._getnone,
79 "deleteid": self._getnone,
80 "move": self._getnone,
81 "moveid": self._getnone,
82 "playlist": self._getplaylist,
83 "playlistfind": self._getsongs,
84 "playlistid": self._getsongs,
85 "playlistinfo": self._getsongs,
86 "playlistsearch": self._getsongs,
87 "plchanges": self._getsongs,
88 "plchangesposid": self._getchanges,
89 "shuffle": self._getnone,
90 "swap": self._getnone,
91 "swapid": self._getnone,
92 # Stored Playlist Commands
93 "listplaylist": self._getlist,
94 "listplaylistinfo": self._getsongs,
95 "listplaylists": self._getplaylists,
96 "load": self._getnone,
97 "playlistadd": self._getnone,
98 "playlistclear": self._getnone,
99 "playlistdelete": self._getnone,
100 "playlistmove": self._getnone,
101 "rename": self._getnone,
103 "save": self._getnone,
105 "count": self._getobject,
106 "find": self._getsongs,
107 "list": self._getlist,
108 "listall": self._getdatabase,
109 "listallinfo": self._getdatabase,
110 "lsinfo": self._getdatabase,
111 "search": self._getsongs,
112 "update": self._getitem,
113 # Connection Commands
116 "password": self._getnone,
117 "ping": self._getnone,
118 # Audio Output Commands
119 "disableoutput": self._getnone,
120 "enableoutput": self._getnone,
121 "outputs": self._getoutputs,
122 # Reflection Commands
123 "commands": self._getlist,
124 "notcommands": self._getlist,
125 "tagtypes": self._getlist,
126 "urlhandlers": self._getlist,
129 def __getattr__(self, attr):
131 retval = self._commands[attr]
133 raise AttributeError("'%s' object has no attribute '%s'" %
134 (self.__class__.__name__, attr))
135 return lambda *args: self._docommand(attr, args, retval)
137 def _docommand(self, command, args, retval):
138 if self._commandlist is not None and not callable(retval):
139 raise CommandListError("%s not allowed in command list" % command)
140 self._writecommand(command, args)
141 if self._commandlist is None:
145 self._commandlist.append(retval)
147 def _writeline(self, line):
148 self._wfile.write("%s\n" % line)
151 def _writecommand(self, command, args=[]):
154 parts.append('"%s"' % escape(str(arg)))
155 self._writeline(" ".join(parts))
158 line = self._rfile.readline()
159 if not line.endswith("\n"):
160 raise ConnectionError("Connection lost while reading line")
161 line = line.rstrip("\n")
162 if line.startswith(ERROR_PREFIX):
163 error = line[len(ERROR_PREFIX):].strip()
164 raise CommandError(error)
165 if self._commandlist is not None:
169 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
170 elif line == SUCCESS:
174 def _readitem(self, separator):
175 line = self._readline()
178 item = line.split(separator, 1)
180 raise ProtocolError("Could not parse item: '%s'" % line)
183 def _readitems(self, separator=": "):
184 item = self._readitem(separator)
187 item = self._readitem(separator)
192 for key, value in self._readitems():
195 raise ProtocolError("Expected key '%s', got '%s'" %
201 def _readplaylist(self):
202 for key, value in self._readitems(":"):
206 def _readobjects(self, delimiters=[]):
208 for key, value in self._readitems():
211 if key in delimiters:
214 elif obj.has_key(key):
215 if not isinstance(obj[key], list):
216 obj[key] = [obj[key], value]
218 obj[key].append(value)
225 def _readcommandlist(self):
226 for retval in self._commandlist:
228 self._commandlist = None
232 def _wrapiterator(self, iterator):
234 return list(iterator)
238 line = self._readline()
240 raise ProtocolError("Got unexpected return value: '%s'" % line)
243 items = list(self._readitems())
249 return self._wrapiterator(self._readlist())
251 def _getplaylist(self):
252 return self._wrapiterator(self._readplaylist())
254 def _getobject(self):
255 objs = list(self._readobjects())
260 def _getobjects(self, delimiters):
261 return self._wrapiterator(self._readobjects(delimiters))
264 return self._getobjects(["file"])
266 def _getplaylists(self):
267 return self._getobjects(["playlist"])
269 def _getdatabase(self):
270 return self._getobjects(["file", "directory", "playlist"])
272 def _getoutputs(self):
273 return self._getobjects(["outputid"])
275 def _getchanges(self):
276 return self._getobjects(["cpos"])
278 def _getcommandlist(self):
279 return self._wrapiterator(self._readcommandlist())
282 line = self._rfile.readline()
283 if not line.endswith("\n"):
284 raise ConnectionError("Connection lost while reading MPD hello")
285 line = line.rstrip("\n")
286 if not line.startswith(HELLO_PREFIX):
287 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
288 self.mpd_version = line[len(HELLO_PREFIX):].strip()
291 self.mpd_version = None
292 self._commandlist = None
294 self._rfile = _NotConnected()
295 self._wfile = _NotConnected()
297 def connect(self, host, port):
299 raise ConnectionError("Already connected")
300 msg = "getaddrinfo returns an empty list"
302 flags = socket.AI_ADDRCONFIG
303 except AttributeError:
305 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
306 socket.SOCK_STREAM, socket.IPPROTO_TCP,
308 af, socktype, proto, canonname, sa = res
310 self._sock = socket.socket(af, socktype, proto)
311 self._sock.connect(sa)
312 except socket.error, msg:
319 raise socket.error(msg)
320 self._rfile = self._sock.makefile("rb")
321 self._wfile = self._sock.makefile("wb")
328 def disconnect(self):
334 def command_list_ok_begin(self):
335 if self._commandlist is not None:
336 raise CommandListError("Already in command list")
337 self._writecommand("command_list_ok_begin")
338 self._commandlist = []
340 def command_list_end(self):
341 if self._commandlist is None:
342 raise CommandListError("Not in command list")
343 self._writecommand("command_list_end")
344 return self._getcommandlist()
348 return text.replace("\\", "\\\\").replace('"', '\\"')
351 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: