1 # python-musicpd: Python MPD client library
2 # Copyright (C) 2008-2010 J. Alexander Treuman <jat@spatialrift.net>
3 # Copyright (C) 2012-2018 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=missing-docstring
23 from functools import wraps
26 HELLO_PREFIX = "OK MPD "
33 def iterator_wrapper(func):
34 """Decorator handling iterate option"""
36 def decorated_function(instance, *args, **kwargs):
37 generator = func(instance, *args, **kwargs)
38 if not instance.iterate:
39 return list(generator)
40 instance._iterating = True
46 instance._iterating = False
47 return iterator(generator)
48 return decorated_function
51 class MPDError(Exception):
54 class ConnectionError(MPDError):
57 class ProtocolError(MPDError):
60 class CommandError(MPDError):
63 class CommandListError(MPDError):
66 class PendingCommandError(MPDError):
69 class IteratingError(MPDError):
74 def __init__(self, tpl):
79 if len(self.tpl) == 0:
81 if len(self.tpl) == 1:
82 return '{0}:'.format(self.tpl[0])
83 return '{0[0]}:{0[1]}'.format(self.tpl)
86 return 'Range({0})'.format(self.tpl)
89 if not isinstance(self.tpl, tuple):
90 raise CommandError('Wrong type, provide a tuple')
91 if len(self.tpl) not in [0, 1, 2]:
92 raise CommandError('length not in [0, 1, 2]')
93 for index in self.tpl:
96 except (TypeError, ValueError):
97 raise CommandError('Not a tuple of int')
100 def __getattr__(self, attr):
104 raise ConnectionError("Not connected")
107 """MPDClient instance will look for ``MPD_HOST``/``MPD_PORT`` environment
108 variables and set instance attribute ``host``, ``port`` and ``password``
117 "clearerror": self._fetch_nothing,
118 "currentsong": self._fetch_object,
119 "idle": self._fetch_list,
121 "status": self._fetch_object,
122 "stats": self._fetch_object,
123 # Playback Option Commands
124 "consume": self._fetch_nothing,
125 "crossfade": self._fetch_nothing,
126 "mixrampdb": self._fetch_nothing,
127 "mixrampdelay": self._fetch_nothing,
128 "random": self._fetch_nothing,
129 "repeat": self._fetch_nothing,
130 "setvol": self._fetch_nothing,
131 "single": self._fetch_nothing,
132 "replay_gain_mode": self._fetch_nothing,
133 "replay_gain_status": self._fetch_item,
134 "volume": self._fetch_nothing,
135 # Playback Control Commands
136 "next": self._fetch_nothing,
137 "pause": self._fetch_nothing,
138 "play": self._fetch_nothing,
139 "playid": self._fetch_nothing,
140 "previous": self._fetch_nothing,
141 "seek": self._fetch_nothing,
142 "seekid": self._fetch_nothing,
143 "seekcur": self._fetch_nothing,
144 "stop": self._fetch_nothing,
146 "add": self._fetch_nothing,
147 "addid": self._fetch_item,
148 "clear": self._fetch_nothing,
149 "delete": self._fetch_nothing,
150 "deleteid": self._fetch_nothing,
151 "move": self._fetch_nothing,
152 "moveid": self._fetch_nothing,
153 "playlist": self._fetch_playlist,
154 "playlistfind": self._fetch_songs,
155 "playlistid": self._fetch_songs,
156 "playlistinfo": self._fetch_songs,
157 "playlistsearch": self._fetch_songs,
158 "plchanges": self._fetch_songs,
159 "plchangesposid": self._fetch_changes,
160 "prio": self._fetch_nothing,
161 "prioid": self._fetch_nothing,
162 "rangeid": self._fetch_nothing,
163 "shuffle": self._fetch_nothing,
164 "swap": self._fetch_nothing,
165 "swapid": self._fetch_nothing,
166 "addtagid": self._fetch_nothing,
167 "cleartagid": self._fetch_nothing,
168 # Stored Playlist Commands
169 "listplaylist": self._fetch_list,
170 "listplaylistinfo": self._fetch_songs,
171 "listplaylists": self._fetch_playlists,
172 "load": self._fetch_nothing,
173 "playlistadd": self._fetch_nothing,
174 "playlistclear": self._fetch_nothing,
175 "playlistdelete": self._fetch_nothing,
176 "playlistmove": self._fetch_nothing,
177 "rename": self._fetch_nothing,
178 "rm": self._fetch_nothing,
179 "save": self._fetch_nothing,
181 "count": self._fetch_object,
182 "find": self._fetch_songs,
183 "findadd": self._fetch_nothing,
184 "list": self._fetch_list,
185 "listall": self._fetch_database,
186 "listallinfo": self._fetch_database,
187 "lsinfo": self._fetch_database,
188 "search": self._fetch_songs,
189 "searchadd": self._fetch_nothing,
190 "searchaddpl": self._fetch_nothing,
191 "update": self._fetch_item,
192 "rescan": self._fetch_item,
193 "readcomments": self._fetch_object,
194 # Mounts and neighbors
195 "mount": self._fetch_nothing,
196 "unmount": self._fetch_nothing,
197 "listmounts": self._fetch_mounts,
198 "listneighbors": self._fetch_neighbors,
200 "sticker get": self._fetch_item,
201 "sticker set": self._fetch_nothing,
202 "sticker delete": self._fetch_nothing,
203 "sticker list": self._fetch_list,
204 "sticker find": self._fetch_songs,
205 # Connection Commands
208 "password": self._fetch_nothing,
209 "ping": self._fetch_nothing,
210 # Audio Output Commands
211 "disableoutput": self._fetch_nothing,
212 "enableoutput": self._fetch_nothing,
213 "toggleoutput": self._fetch_nothing,
214 "outputs": self._fetch_outputs,
215 # Reflection Commands
216 "config": self._fetch_object,
217 "commands": self._fetch_list,
218 "notcommands": self._fetch_list,
219 "tagtypes": self._fetch_list,
220 "urlhandlers": self._fetch_list,
221 "decoders": self._fetch_plugins,
223 "subscribe": self._fetch_nothing,
224 "unsubscribe": self._fetch_nothing,
225 "channels": self._fetch_list,
226 "readmessages": self._fetch_messages,
227 "sendmessage": self._fetch_nothing,
231 def _get_envvars(self):
233 Retrieve MPD env. var. to overrides "localhost:6600"
234 Use MPD_HOST/MPD_PORT if set
235 else use MPD_HOST=${XDG_RUNTIME_DIR:-/run/}/mpd/socket if file exists
237 self.host = 'localhost'
239 self.port = os.environ.get('MPD_PORT', '6600')
240 mpd_host_env = os.environ.get('MPD_HOST')
242 # If password is set:
243 # mpd_host_env = ['pass', 'host'] because MPD_HOST=pass@host
244 mpd_host_env = mpd_host_env.split('@')
245 mpd_host_env.reverse()
246 self.host = mpd_host_env[0]
247 if len(mpd_host_env) > 1 and mpd_host_env[1]:
248 self.password = mpd_host_env[1]
251 xdg_runtime_dir = os.environ.get('XDG_RUNTIME_DIR', '/run')
252 rundir = os.path.join(xdg_runtime_dir, 'mpd/socket')
253 if os.path.exists(rundir):
256 def __getattr__(self, attr):
257 if attr == 'send_noidle': # have send_noidle to cancel idle as well as noidle
259 if attr.startswith("send_"):
260 command = attr.replace("send_", "", 1)
262 elif attr.startswith("fetch_"):
263 command = attr.replace("fetch_", "", 1)
264 wrapper = self._fetch
267 wrapper = self._execute
268 if command not in self._commands:
269 command = command.replace("_", " ")
270 if command not in self._commands:
271 raise AttributeError("'%s' object has no attribute '%s'" %
272 (self.__class__.__name__, attr))
273 return lambda *args: wrapper(command, args)
275 def _send(self, command, args):
276 if self._command_list is not None:
277 raise CommandListError("Cannot use send_%s in a command list" %
278 command.replace(" ", "_"))
279 self._write_command(command, args)
280 retval = self._commands[command]
281 if retval is not None:
282 self._pending.append(command)
284 def _fetch(self, command, args=None):
285 if self._command_list is not None:
286 raise CommandListError("Cannot use fetch_%s in a command list" %
287 command.replace(" ", "_"))
289 raise IteratingError("Cannot use fetch_%s while iterating" %
290 command.replace(" ", "_"))
291 if not self._pending:
292 raise PendingCommandError("No pending commands to fetch")
293 if self._pending[0] != command:
294 raise PendingCommandError("'%s' is not the currently "
295 "pending command" % command)
297 retval = self._commands[command]
302 def _execute(self, command, args):
304 raise IteratingError("Cannot execute '%s' while iterating" %
307 raise PendingCommandError("Cannot execute '%s' with "
308 "pending commands" % command)
309 retval = self._commands[command]
310 if self._command_list is not None:
311 if not callable(retval):
312 raise CommandListError("'%s' not allowed in command list" %
314 self._write_command(command, args)
315 self._command_list.append(retval)
317 self._write_command(command, args)
322 def _write_line(self, line):
323 self._wfile.write("%s\n" % line)
326 def _write_command(self, command, args=None):
331 if isinstance(arg, tuple):
332 parts.append('{0!s}'.format(Range(arg)))
334 parts.append('"%s"' % escape(str(arg)))
335 self._write_line(" ".join(parts))
337 def _read_line(self):
338 line = self._rfile.readline()
339 if not line.endswith("\n"):
341 raise ConnectionError("Connection lost while reading line")
342 line = line.rstrip("\n")
343 if line.startswith(ERROR_PREFIX):
344 error = line[len(ERROR_PREFIX):].strip()
345 raise CommandError(error)
346 if self._command_list is not None:
350 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
351 elif line == SUCCESS:
355 def _read_pair(self, separator):
356 line = self._read_line()
359 pair = line.split(separator, 1)
361 raise ProtocolError("Could not parse pair: '%s'" % line)
364 def _read_pairs(self, separator=": "):
365 pair = self._read_pair(separator)
368 pair = self._read_pair(separator)
370 def _read_list(self):
372 for key, value in self._read_pairs():
375 raise ProtocolError("Expected key '%s', got '%s'" %
380 def _read_playlist(self):
381 for _, value in self._read_pairs(":"):
384 def _read_objects(self, delimiters=None):
386 if delimiters is None:
388 for key, value in self._read_pairs():
391 if key in delimiters:
395 if not isinstance(obj[key], list):
396 obj[key] = [obj[key], value]
398 obj[key].append(value)
404 def _read_command_list(self):
406 for retval in self._command_list:
409 self._command_list = None
410 self._fetch_nothing()
412 def _fetch_nothing(self):
413 line = self._read_line()
415 raise ProtocolError("Got unexpected return value: '%s'" % line)
417 def _fetch_item(self):
418 pairs = list(self._read_pairs())
424 def _fetch_list(self):
425 return self._read_list()
428 def _fetch_playlist(self):
429 return self._read_playlist()
431 def _fetch_object(self):
432 objs = list(self._read_objects())
438 def _fetch_objects(self, delimiters):
439 return self._read_objects(delimiters)
441 def _fetch_changes(self):
442 return self._fetch_objects(["cpos"])
444 def _fetch_songs(self):
445 return self._fetch_objects(["file"])
447 def _fetch_playlists(self):
448 return self._fetch_objects(["playlist"])
450 def _fetch_database(self):
451 return self._fetch_objects(["file", "directory", "playlist"])
453 def _fetch_outputs(self):
454 return self._fetch_objects(["outputid"])
456 def _fetch_plugins(self):
457 return self._fetch_objects(["plugin"])
459 def _fetch_messages(self):
460 return self._fetch_objects(["channel"])
462 def _fetch_mounts(self):
463 return self._fetch_objects(["mount"])
465 def _fetch_neighbors(self):
466 return self._fetch_objects(["neighbor"])
469 def _fetch_command_list(self):
470 return self._read_command_list()
473 line = self._rfile.readline()
474 if not line.endswith("\n"):
475 raise ConnectionError("Connection lost while reading MPD hello")
476 line = line.rstrip("\n")
477 if not line.startswith(HELLO_PREFIX):
478 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
479 self.mpd_version = line[len(HELLO_PREFIX):].strip()
482 self.mpd_version = None
483 self._iterating = False
485 self._command_list = None
487 self._rfile = _NotConnected()
488 self._wfile = _NotConnected()
490 def _connect_unix(self, path):
491 if not hasattr(socket, "AF_UNIX"):
492 raise ConnectionError("Unix domain sockets not supported "
494 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
498 def _connect_tcp(self, host, port):
500 flags = socket.AI_ADDRCONFIG
501 except AttributeError:
504 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
505 socket.SOCK_STREAM, socket.IPPROTO_TCP,
507 af, socktype, proto, _, sa = res
510 sock = socket.socket(af, socktype, proto)
513 except socket.error as socket_err:
518 raise ConnectionError(str(err))
520 raise ConnectionError("getaddrinfo returns an empty list")
523 # noidle's special case
524 if not self._pending or self._pending[0] != 'idle':
525 raise CommandError('cannot send noidle if send_idle was not called')
527 self._write_command("noidle")
528 return self._fetch_list()
530 def connect(self, host=None, port=None):
531 """Connects the MPD server
533 :param str host: hostname, IP or FQDN (defaults to `localhost` or socket, see below for details)
534 :param str port: port number (defaults to 6600)
536 The connect method honors MPD_HOST/MPD_PORT environment variables.
538 .. note:: Default host/port
540 If host evaluate to :py:obj:`False`
541 * if ``MPD_HOST`` env. var. is set, use it for host
542 * else looks for a existing file in ``${XDG_RUNTIME_DIR:-/run/}/mpd/socket``
543 * finally set host to ``localhost``
545 If port evaluate to :py:obj:`False`
546 * if ``MPD_PORT`` env. var. is set, use it for port
553 if self._sock is not None:
554 raise ConnectionError("Already connected")
555 if host.startswith("/"):
556 self._sock = self._connect_unix(host)
558 self._sock = self._connect_tcp(host, port)
559 self._rfile = self._sock.makefile("r", encoding='utf-8')
560 self._wfile = self._sock.makefile("w", encoding='utf-8')
567 def disconnect(self):
568 """Closes the MPD connection.
569 The client closes the actual socket and not using the
570 'close' request from MPD protocol as suggested in documentation.
572 if hasattr(self._rfile, 'close'):
574 if hasattr(self._wfile, 'close'):
576 if hasattr(self._sock, 'close'):
581 if self._sock is None:
582 raise ConnectionError("Not connected")
583 return self._sock.fileno()
585 def command_list_ok_begin(self):
586 if self._command_list is not None:
587 raise CommandListError("Already in command list")
589 raise IteratingError("Cannot begin command list while iterating")
591 raise PendingCommandError("Cannot begin command list "
592 "with pending commands")
593 self._write_command("command_list_ok_begin")
594 self._command_list = []
596 def command_list_end(self):
597 if self._command_list is None:
598 raise CommandListError("Not in command list")
600 raise IteratingError("Already iterating over a command list")
601 self._write_command("command_list_end")
602 return self._fetch_command_list()
606 return text.replace("\\", "\\\\").replace('"', '\\"')
608 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: