1 # python-mpd: Python MPD client library
2 # Copyright (C) 2008-2010 J. Alexander Treuman <jat@spatialrift.net>
3 # Copyright (C) 2012 Kaliko Jack <kaliko@azylum.org>
5 # python-mpd is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # python-mpd is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with python-mpd. If not, see <http://www.gnu.org/licenses/>.
21 HELLO_PREFIX = "OK MPD "
27 class MPDError(Exception):
30 class ConnectionError(MPDError):
33 class ProtocolError(MPDError):
36 class CommandError(MPDError):
39 class CommandListError(MPDError):
42 class PendingCommandError(MPDError):
45 class IteratingError(MPDError):
49 class _NotConnected(object):
50 def __getattr__(self, attr):
54 raise ConnectionError("Not connected")
56 class MPDClient(object):
62 "clearerror": self._fetch_nothing,
63 "currentsong": self._fetch_object,
64 "idle": self._fetch_list,
66 "status": self._fetch_object,
67 "stats": self._fetch_object,
68 # Playback Option Commands
69 "consume": self._fetch_nothing,
70 "crossfade": self._fetch_nothing,
71 "mixrampdb": self._fetch_nothing,
72 "mixrampdelay": self._fetch_nothing,
73 "random": self._fetch_nothing,
74 "repeat": self._fetch_nothing,
75 "setvol": self._fetch_nothing,
76 "single": self._fetch_nothing,
77 "replay_gain_mode": self._fetch_nothing,
78 "replay_gain_status": self._fetch_item,
79 "volume": self._fetch_nothing,
80 # Playback Control Commands
81 "next": self._fetch_nothing,
82 "pause": self._fetch_nothing,
83 "play": self._fetch_nothing,
84 "playid": self._fetch_nothing,
85 "previous": self._fetch_nothing,
86 "seek": self._fetch_nothing,
87 "seekid": self._fetch_nothing,
88 "seekcur": self._fetch_nothing,
89 "stop": self._fetch_nothing,
91 "add": self._fetch_nothing,
92 "addid": self._fetch_item,
93 "clear": self._fetch_nothing,
94 "delete": self._fetch_nothing,
95 "deleteid": self._fetch_nothing,
96 "move": self._fetch_nothing,
97 "moveid": self._fetch_nothing,
98 "playlist": self._fetch_playlist,
99 "playlistfind": self._fetch_songs,
100 "playlistid": self._fetch_songs,
101 "playlistinfo": self._fetch_songs,
102 "playlistsearch": self._fetch_songs,
103 "plchanges": self._fetch_songs,
104 "plchangesposid": self._fetch_changes,
105 "shuffle": self._fetch_nothing,
106 "swap": self._fetch_nothing,
107 "swapid": self._fetch_nothing,
108 # Stored Playlist Commands
109 "listplaylist": self._fetch_list,
110 "listplaylistinfo": self._fetch_songs,
111 "listplaylists": self._fetch_playlists,
112 "load": self._fetch_nothing,
113 "playlistadd": self._fetch_nothing,
114 "playlistclear": self._fetch_nothing,
115 "playlistdelete": self._fetch_nothing,
116 "playlistmove": self._fetch_nothing,
117 "rename": self._fetch_nothing,
118 "rm": self._fetch_nothing,
119 "save": self._fetch_nothing,
121 "count": self._fetch_object,
122 "find": self._fetch_songs,
123 "findadd": self._fetch_nothing,
124 "list": self._fetch_list,
125 "listall": self._fetch_database,
126 "listallinfo": self._fetch_database,
127 "lsinfo": self._fetch_database,
128 "search": self._fetch_songs,
129 "searchadd": self._fetch_nothing,
130 "searchaddpl": self._fetch_nothing,
131 "update": self._fetch_item,
132 "rescan": self._fetch_item,
134 "sticker get": self._fetch_item,
135 "sticker set": self._fetch_nothing,
136 "sticker delete": self._fetch_nothing,
137 "sticker list": self._fetch_list,
138 "sticker find": self._fetch_songs,
139 # Connection Commands
142 "password": self._fetch_nothing,
143 "ping": self._fetch_nothing,
144 # Audio Output Commands
145 "disableoutput": self._fetch_nothing,
146 "enableoutput": self._fetch_nothing,
147 "outputs": self._fetch_outputs,
148 # Reflection Commands
149 "commands": self._fetch_list,
150 "notcommands": self._fetch_list,
151 "tagtypes": self._fetch_list,
152 "urlhandlers": self._fetch_list,
153 "decoders": self._fetch_plugins,
155 "subscribe": self._fetch_nothing,
156 "unsubscribe": self._fetch_nothing,
157 "channels": self._fetch_list,
158 "readmessages": self._fetch_messages,
159 "sendmessage": self._fetch_nothing,
162 def __getattr__(self, attr):
163 if attr.startswith("send_"):
164 command = attr.replace("send_", "", 1)
166 elif attr.startswith("fetch_"):
167 command = attr.replace("fetch_", "", 1)
168 wrapper = self._fetch
171 wrapper = self._execute
172 if command not in self._commands:
173 command = command.replace("_", " ")
174 if command not in self._commands:
175 raise AttributeError("'%s' object has no attribute '%s'" %
176 (self.__class__.__name__, attr))
177 return lambda *args: wrapper(command, args)
179 def _send(self, command, args):
180 if self._command_list is not None:
181 raise CommandListError("Cannot use send_%s in a command list" %
182 command.replace(" ", "_"))
183 self._write_command(command, args)
184 retval = self._commands[command]
185 if retval is not None:
186 self._pending.append(command)
188 def _fetch(self, command, args=None):
189 if self._command_list is not None:
190 raise CommandListError("Cannot use fetch_%s in a command list" %
191 command.replace(" ", "_"))
193 raise IteratingError("Cannot use fetch_%s while iterating" %
194 command.replace(" ", "_"))
195 if not self._pending:
196 raise PendingCommandError("No pending commands to fetch")
197 if self._pending[0] != command:
198 raise PendingCommandError("'%s' is not the currently "
199 "pending command" % command)
201 retval = self._commands[command]
206 def _execute(self, command, args):
208 raise IteratingError("Cannot execute '%s' while iterating" %
211 raise PendingCommandError("Cannot execute '%s' with "
212 "pending commands" % command)
213 retval = self._commands[command]
214 if self._command_list is not None:
215 if not callable(retval):
216 raise CommandListError("'%s' not allowed in command list" %
218 self._write_command(command, args)
219 self._command_list.append(retval)
221 self._write_command(command, args)
226 def _write_line(self, line):
227 self._wfile.write("%s\n" % line)
230 def _write_command(self, command, args=[]):
233 parts.append('"%s"' % escape(str(arg)))
234 self._write_line(" ".join(parts))
236 def _read_line(self):
237 line = self._rfile.readline()
238 if not line.endswith("\n"):
239 raise ConnectionError("Connection lost while reading line")
240 line = line.rstrip("\n")
241 if line.startswith(ERROR_PREFIX):
242 error = line[len(ERROR_PREFIX):].strip()
243 raise CommandError(error)
244 if self._command_list is not None:
248 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
249 elif line == SUCCESS:
253 def _read_pair(self, separator):
254 line = self._read_line()
257 pair = line.split(separator, 1)
259 raise ProtocolError("Could not parse pair: '%s'" % line)
262 def _read_pairs(self, separator=": "):
263 pair = self._read_pair(separator)
266 pair = self._read_pair(separator)
268 def _read_list(self):
270 for key, value in self._read_pairs():
273 raise ProtocolError("Expected key '%s', got '%s'" %
278 def _read_playlist(self):
279 for key, value in self._read_pairs(":"):
282 def _read_objects(self, delimiters=[]):
284 for key, value in self._read_pairs():
287 if key in delimiters:
291 if not isinstance(obj[key], list):
292 obj[key] = [obj[key], value]
294 obj[key].append(value)
300 def _read_command_list(self):
302 for retval in self._command_list:
305 self._command_list = None
306 self._fetch_nothing()
308 def _iterator_wrapper(self, iterator):
310 for item in iterator:
313 self._iterating = False
315 def _wrap_iterator(self, iterator):
317 return list(iterator)
318 self._iterating = True
319 return self._iterator_wrapper(iterator)
321 def _fetch_nothing(self):
322 line = self._read_line()
324 raise ProtocolError("Got unexpected return value: '%s'" % line)
326 def _fetch_item(self):
327 pairs = list(self._read_pairs())
332 def _fetch_list(self):
333 return self._wrap_iterator(self._read_list())
335 def _fetch_playlist(self):
336 return self._wrap_iterator(self._read_playlist())
338 def _fetch_object(self):
339 objs = list(self._read_objects())
344 def _fetch_objects(self, delimiters):
345 return self._wrap_iterator(self._read_objects(delimiters))
347 def _fetch_changes(self):
348 return self._fetch_objects(["cpos"])
350 def _fetch_songs(self):
351 return self._fetch_objects(["file"])
353 def _fetch_playlists(self):
354 return self._fetch_objects(["playlist"])
356 def _fetch_database(self):
357 return self._fetch_objects(["file", "directory", "playlist"])
359 def _fetch_outputs(self):
360 return self._fetch_objects(["outputid"])
362 def _fetch_plugins(self):
363 return self._fetch_objects(["plugin"])
365 def _fetch_messages(self):
366 return self._fetch_objects(["channel"])
368 def _fetch_command_list(self):
369 return self._wrap_iterator(self._read_command_list())
372 line = self._rfile.readline()
373 if not line.endswith("\n"):
374 raise ConnectionError("Connection lost while reading MPD hello")
375 line = line.rstrip("\n")
376 if not line.startswith(HELLO_PREFIX):
377 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
378 self.mpd_version = line[len(HELLO_PREFIX):].strip()
381 self.mpd_version = None
382 self._iterating = False
384 self._command_list = None
386 self._rfile = _NotConnected()
387 self._wfile = _NotConnected()
389 def _connect_unix(self, path):
390 if not hasattr(socket, "AF_UNIX"):
391 raise ConnectionError("Unix domain sockets not supported "
393 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
397 def _connect_tcp(self, host, port):
399 flags = socket.AI_ADDRCONFIG
400 except AttributeError:
403 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
404 socket.SOCK_STREAM, socket.IPPROTO_TCP,
406 af, socktype, proto, canonname, sa = res
409 sock = socket.socket(af, socktype, proto)
412 except socket.error as socket_err:
419 raise ConnectionError("getaddrinfo returns an empty list")
421 def connect(self, host, port):
422 if self._sock is not None:
423 raise ConnectionError("Already connected")
424 if host.startswith("/"):
425 self._sock = self._connect_unix(host)
427 self._sock = self._connect_tcp(host, port)
428 self._rfile = self._sock.makefile("r")
429 self._wfile = self._sock.makefile("w")
436 def disconnect(self):
443 if self._sock is None:
444 raise ConnectionError("Not connected")
445 return self._sock.fileno()
447 def command_list_ok_begin(self):
448 if self._command_list is not None:
449 raise CommandListError("Already in command list")
451 raise IteratingError("Cannot begin command list while iterating")
453 raise PendingCommandError("Cannot begin command list "
454 "with pending commands")
455 self._write_command("command_list_ok_begin")
456 self._command_list = []
458 def command_list_end(self):
459 if self._command_list is None:
460 raise CommandListError("Not in command list")
462 raise IteratingError("Already iterating over a command list")
463 self._write_command("command_list_end")
464 return self._fetch_command_list()
468 return text.replace("\\", "\\\\").replace('"', '\\"')
471 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: