1 # python-musicpd: Python MPD client library
2 # Copyright (C) 2008-2010 J. Alexander Treuman <jat@spatialrift.net>
3 # Copyright (C) 2012-2014 Kaliko Jack <kaliko@azylum.org>
5 # python-musicpd 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-musicpd 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-musicpd. If not, see <http://www.gnu.org/licenses/>.
18 # pylint: disable=C0111
23 HELLO_PREFIX = "OK MPD "
30 class MPDError(Exception):
33 class ConnectionError(MPDError):
36 class ProtocolError(MPDError):
39 class CommandError(MPDError):
42 class CommandListError(MPDError):
45 class PendingCommandError(MPDError):
48 class IteratingError(MPDError):
53 def __init__(self, tpl):
58 if len(self.tpl) == 1:
59 return '{0}:'.format(self.tpl[0])
60 return '{0[0]}:{0[1]}'.format(self.tpl)
63 return 'Range({0})'.format(self.tpl)
66 if not isinstance(self.tpl, tuple):
67 raise CommandError('Wrong type, provide a tuple')
68 if len(self.tpl) not in [1, 2]:
69 raise CommandError('length not in [1, 2]')
70 for index in self.tpl:
73 except (TypeError, ValueError):
74 raise CommandError('Not a tuple of int')
78 def __getattr__(self, attr):
82 raise ConnectionError("Not connected")
90 "clearerror": self._fetch_nothing,
91 "currentsong": self._fetch_object,
92 "idle": self._fetch_list,
94 "status": self._fetch_object,
95 "stats": self._fetch_object,
96 # Playback Option Commands
97 "consume": self._fetch_nothing,
98 "crossfade": self._fetch_nothing,
99 "mixrampdb": self._fetch_nothing,
100 "mixrampdelay": self._fetch_nothing,
101 "random": self._fetch_nothing,
102 "repeat": self._fetch_nothing,
103 "setvol": self._fetch_nothing,
104 "single": self._fetch_nothing,
105 "replay_gain_mode": self._fetch_nothing,
106 "replay_gain_status": self._fetch_item,
107 "volume": self._fetch_nothing,
108 # Playback Control Commands
109 "next": self._fetch_nothing,
110 "pause": self._fetch_nothing,
111 "play": self._fetch_nothing,
112 "playid": self._fetch_nothing,
113 "previous": self._fetch_nothing,
114 "seek": self._fetch_nothing,
115 "seekid": self._fetch_nothing,
116 "seekcur": self._fetch_nothing,
117 "stop": self._fetch_nothing,
119 "add": self._fetch_nothing,
120 "addid": self._fetch_item,
121 "clear": self._fetch_nothing,
122 "delete": self._fetch_nothing,
123 "deleteid": self._fetch_nothing,
124 "move": self._fetch_nothing,
125 "moveid": self._fetch_nothing,
126 "playlist": self._fetch_playlist,
127 "playlistfind": self._fetch_songs,
128 "playlistid": self._fetch_songs,
129 "playlistinfo": self._fetch_songs,
130 "playlistsearch": self._fetch_songs,
131 "plchanges": self._fetch_songs,
132 "plchangesposid": self._fetch_changes,
133 "prio": self._fetch_nothing,
134 "prioid": self._fetch_nothing,
135 "shuffle": self._fetch_nothing,
136 "swap": self._fetch_nothing,
137 "swapid": self._fetch_nothing,
138 "addtagid": self._fetch_nothing,
139 "cleartagid": self._fetch_nothing,
140 # Stored Playlist Commands
141 "listplaylist": self._fetch_list,
142 "listplaylistinfo": self._fetch_songs,
143 "listplaylists": self._fetch_playlists,
144 "load": self._fetch_nothing,
145 "playlistadd": self._fetch_nothing,
146 "playlistclear": self._fetch_nothing,
147 "playlistdelete": self._fetch_nothing,
148 "playlistmove": self._fetch_nothing,
149 "rename": self._fetch_nothing,
150 "rm": self._fetch_nothing,
151 "save": self._fetch_nothing,
153 "count": self._fetch_object,
154 "find": self._fetch_songs,
155 "findadd": self._fetch_nothing,
156 "list": self._fetch_list,
157 "listall": self._fetch_database,
158 "listallinfo": self._fetch_database,
159 "lsinfo": self._fetch_database,
160 "search": self._fetch_songs,
161 "searchadd": self._fetch_nothing,
162 "searchaddpl": self._fetch_nothing,
163 "update": self._fetch_item,
164 "rescan": self._fetch_item,
165 "readcomments": self._fetch_object,
166 # Mounts and neighbors
167 "mount": self._fetch_nothing,
168 "unmount": self._fetch_nothing,
169 "listmounts": self._fetch_mounts,
170 "listneighbors": self._fetch_neighbors,
172 "sticker get": self._fetch_item,
173 "sticker set": self._fetch_nothing,
174 "sticker delete": self._fetch_nothing,
175 "sticker list": self._fetch_list,
176 "sticker find": self._fetch_songs,
177 # Connection Commands
180 "password": self._fetch_nothing,
181 "ping": self._fetch_nothing,
182 # Audio Output Commands
183 "disableoutput": self._fetch_nothing,
184 "enableoutput": self._fetch_nothing,
185 "toggleoutput": self._fetch_nothing,
186 "outputs": self._fetch_outputs,
187 # Reflection Commands
188 "commands": self._fetch_list,
189 "notcommands": self._fetch_list,
190 "tagtypes": self._fetch_list,
191 "urlhandlers": self._fetch_list,
192 "decoders": self._fetch_plugins,
194 "subscribe": self._fetch_nothing,
195 "unsubscribe": self._fetch_nothing,
196 "channels": self._fetch_list,
197 "readmessages": self._fetch_messages,
198 "sendmessage": self._fetch_nothing,
201 def __getattr__(self, attr):
202 if attr == 'send_noidle': # have send_noidle to cancel idle as well as noidle
204 if attr.startswith("send_"):
205 command = attr.replace("send_", "", 1)
207 elif attr.startswith("fetch_"):
208 command = attr.replace("fetch_", "", 1)
209 wrapper = self._fetch
212 wrapper = self._execute
213 if command not in self._commands:
214 command = command.replace("_", " ")
215 if command not in self._commands:
216 raise AttributeError("'%s' object has no attribute '%s'" %
217 (self.__class__.__name__, attr))
218 return lambda *args: wrapper(command, args)
220 def _send(self, command, args):
221 if self._command_list is not None:
222 raise CommandListError("Cannot use send_%s in a command list" %
223 command.replace(" ", "_"))
224 self._write_command(command, args)
225 retval = self._commands[command]
226 if retval is not None:
227 self._pending.append(command)
229 def _fetch(self, command, args=None):
230 if self._command_list is not None:
231 raise CommandListError("Cannot use fetch_%s in a command list" %
232 command.replace(" ", "_"))
234 raise IteratingError("Cannot use fetch_%s while iterating" %
235 command.replace(" ", "_"))
236 if not self._pending:
237 raise PendingCommandError("No pending commands to fetch")
238 if self._pending[0] != command:
239 raise PendingCommandError("'%s' is not the currently "
240 "pending command" % command)
242 retval = self._commands[command]
247 def _execute(self, command, args):
249 raise IteratingError("Cannot execute '%s' while iterating" %
252 raise PendingCommandError("Cannot execute '%s' with "
253 "pending commands" % command)
254 retval = self._commands[command]
255 if self._command_list is not None:
256 if not callable(retval):
257 raise CommandListError("'%s' not allowed in command list" %
259 self._write_command(command, args)
260 self._command_list.append(retval)
262 self._write_command(command, args)
267 def _write_line(self, line):
268 self._wfile.write("%s\n" % line)
271 def _write_command(self, command, args=None):
276 if isinstance(arg, tuple):
277 parts.append('{0!s}'.format(Range(arg)))
279 parts.append('"%s"' % escape(str(arg)))
280 self._write_line(" ".join(parts))
282 def _read_line(self):
283 line = self._rfile.readline()
284 if not line.endswith("\n"):
286 raise ConnectionError("Connection lost while reading line")
287 line = line.rstrip("\n")
288 if line.startswith(ERROR_PREFIX):
289 error = line[len(ERROR_PREFIX):].strip()
290 raise CommandError(error)
291 if self._command_list is not None:
295 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
296 elif line == SUCCESS:
300 def _read_pair(self, separator):
301 line = self._read_line()
304 pair = line.split(separator, 1)
306 raise ProtocolError("Could not parse pair: '%s'" % line)
309 def _read_pairs(self, separator=": "):
310 pair = self._read_pair(separator)
313 pair = self._read_pair(separator)
315 def _read_list(self):
317 for key, value in self._read_pairs():
320 raise ProtocolError("Expected key '%s', got '%s'" %
325 def _read_playlist(self):
326 for _, value in self._read_pairs(":"):
329 def _read_objects(self, delimiters=None):
331 if delimiters is None:
333 for key, value in self._read_pairs():
336 if key in delimiters:
340 if not isinstance(obj[key], list):
341 obj[key] = [obj[key], value]
343 obj[key].append(value)
349 def _read_command_list(self):
351 for retval in self._command_list:
354 self._command_list = None
355 self._fetch_nothing()
357 def _iterator_wrapper(self, iterator):
359 for item in iterator:
362 self._iterating = False
364 def _wrap_iterator(self, iterator):
366 return list(iterator)
367 self._iterating = True
368 return self._iterator_wrapper(iterator)
370 def _fetch_nothing(self):
371 line = self._read_line()
373 raise ProtocolError("Got unexpected return value: '%s'" % line)
375 def _fetch_item(self):
376 pairs = list(self._read_pairs())
381 def _fetch_list(self):
382 return self._wrap_iterator(self._read_list())
384 def _fetch_playlist(self):
385 return self._wrap_iterator(self._read_playlist())
387 def _fetch_object(self):
388 objs = list(self._read_objects())
393 def _fetch_objects(self, delimiters):
394 return self._wrap_iterator(self._read_objects(delimiters))
396 def _fetch_changes(self):
397 return self._fetch_objects(["cpos"])
399 def _fetch_songs(self):
400 return self._fetch_objects(["file"])
402 def _fetch_playlists(self):
403 return self._fetch_objects(["playlist"])
405 def _fetch_database(self):
406 return self._fetch_objects(["file", "directory", "playlist"])
408 def _fetch_outputs(self):
409 return self._fetch_objects(["outputid"])
411 def _fetch_plugins(self):
412 return self._fetch_objects(["plugin"])
414 def _fetch_messages(self):
415 return self._fetch_objects(["channel"])
417 def _fetch_mounts(self):
418 return self._fetch_objects(["mount"])
420 def _fetch_neighbors(self):
421 return self._fetch_objects(["neighbor"])
423 def _fetch_command_list(self):
424 return self._wrap_iterator(self._read_command_list())
427 line = self._rfile.readline()
428 if not line.endswith("\n"):
429 raise ConnectionError("Connection lost while reading MPD hello")
430 line = line.rstrip("\n")
431 if not line.startswith(HELLO_PREFIX):
432 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
433 self.mpd_version = line[len(HELLO_PREFIX):].strip()
436 # pylint: disable=w0201
437 self.mpd_version = None
438 self._iterating = False
440 self._command_list = None
442 self._rfile = _NotConnected()
443 self._wfile = _NotConnected()
445 def _connect_unix(self, path):
446 if not hasattr(socket, "AF_UNIX"):
447 raise ConnectionError("Unix domain sockets not supported "
449 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
453 def _connect_tcp(self, host, port):
455 flags = socket.AI_ADDRCONFIG
456 except AttributeError:
459 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
460 socket.SOCK_STREAM, socket.IPPROTO_TCP,
462 af, socktype, proto, _, sa = res
465 sock = socket.socket(af, socktype, proto)
468 except socket.error as socket_err:
473 raise ConnectionError(str(err))
475 raise ConnectionError("getaddrinfo returns an empty list")
478 # noidle's special case
479 if not self._pending or self._pending[0] != 'idle':
480 raise CommandError('cannot send noidle if send_idle was not called')
482 self._write_command("noidle")
483 return self._fetch_list()
485 def connect(self, host, port):
486 if self._sock is not None:
487 raise ConnectionError("Already connected")
488 if host.startswith("/"):
489 self._sock = self._connect_unix(host)
491 self._sock = self._connect_tcp(host, port)
492 self._rfile = self._sock.makefile("r", encoding='utf-8')
493 self._wfile = self._sock.makefile("w", encoding='utf-8')
500 def disconnect(self):
501 if hasattr(self._rfile, 'close'):
503 if hasattr(self._wfile, 'close'):
505 if hasattr(self._sock, 'close'):
510 if self._sock is None:
511 raise ConnectionError("Not connected")
512 return self._sock.fileno()
514 def command_list_ok_begin(self):
515 if self._command_list is not None:
516 raise CommandListError("Already in command list")
518 raise IteratingError("Cannot begin command list while iterating")
520 raise PendingCommandError("Cannot begin command list "
521 "with pending commands")
522 self._write_command("command_list_ok_begin")
523 self._command_list = []
525 def command_list_end(self):
526 if self._command_list is None:
527 raise CommandListError("Not in command list")
529 raise IteratingError("Already iterating over a command list")
530 self._write_command("command_list_end")
531 return self._fetch_command_list()
535 return text.replace("\\", "\\\\").replace('"', '\\"')
538 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: