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")
112 "clearerror": self._fetch_nothing,
113 "currentsong": self._fetch_object,
114 "idle": self._fetch_list,
116 "status": self._fetch_object,
117 "stats": self._fetch_object,
118 # Playback Option Commands
119 "consume": self._fetch_nothing,
120 "crossfade": self._fetch_nothing,
121 "mixrampdb": self._fetch_nothing,
122 "mixrampdelay": self._fetch_nothing,
123 "random": self._fetch_nothing,
124 "repeat": self._fetch_nothing,
125 "setvol": self._fetch_nothing,
126 "single": self._fetch_nothing,
127 "replay_gain_mode": self._fetch_nothing,
128 "replay_gain_status": self._fetch_item,
129 "volume": self._fetch_nothing,
130 # Playback Control Commands
131 "next": self._fetch_nothing,
132 "pause": self._fetch_nothing,
133 "play": self._fetch_nothing,
134 "playid": self._fetch_nothing,
135 "previous": self._fetch_nothing,
136 "seek": self._fetch_nothing,
137 "seekid": self._fetch_nothing,
138 "seekcur": self._fetch_nothing,
139 "stop": self._fetch_nothing,
141 "add": self._fetch_nothing,
142 "addid": self._fetch_item,
143 "clear": self._fetch_nothing,
144 "delete": self._fetch_nothing,
145 "deleteid": self._fetch_nothing,
146 "move": self._fetch_nothing,
147 "moveid": self._fetch_nothing,
148 "playlist": self._fetch_playlist,
149 "playlistfind": self._fetch_songs,
150 "playlistid": self._fetch_songs,
151 "playlistinfo": self._fetch_songs,
152 "playlistsearch": self._fetch_songs,
153 "plchanges": self._fetch_songs,
154 "plchangesposid": self._fetch_changes,
155 "prio": self._fetch_nothing,
156 "prioid": self._fetch_nothing,
157 "rangeid": self._fetch_nothing,
158 "shuffle": self._fetch_nothing,
159 "swap": self._fetch_nothing,
160 "swapid": self._fetch_nothing,
161 "addtagid": self._fetch_nothing,
162 "cleartagid": self._fetch_nothing,
163 # Stored Playlist Commands
164 "listplaylist": self._fetch_list,
165 "listplaylistinfo": self._fetch_songs,
166 "listplaylists": self._fetch_playlists,
167 "load": self._fetch_nothing,
168 "playlistadd": self._fetch_nothing,
169 "playlistclear": self._fetch_nothing,
170 "playlistdelete": self._fetch_nothing,
171 "playlistmove": self._fetch_nothing,
172 "rename": self._fetch_nothing,
173 "rm": self._fetch_nothing,
174 "save": self._fetch_nothing,
176 "count": self._fetch_object,
177 "find": self._fetch_songs,
178 "findadd": self._fetch_nothing,
179 "list": self._fetch_list,
180 "listall": self._fetch_database,
181 "listallinfo": self._fetch_database,
182 "lsinfo": self._fetch_database,
183 "search": self._fetch_songs,
184 "searchadd": self._fetch_nothing,
185 "searchaddpl": self._fetch_nothing,
186 "update": self._fetch_item,
187 "rescan": self._fetch_item,
188 "readcomments": self._fetch_object,
189 # Mounts and neighbors
190 "mount": self._fetch_nothing,
191 "unmount": self._fetch_nothing,
192 "listmounts": self._fetch_mounts,
193 "listneighbors": self._fetch_neighbors,
195 "sticker get": self._fetch_item,
196 "sticker set": self._fetch_nothing,
197 "sticker delete": self._fetch_nothing,
198 "sticker list": self._fetch_list,
199 "sticker find": self._fetch_songs,
200 # Connection Commands
203 "password": self._fetch_nothing,
204 "ping": self._fetch_nothing,
205 # Audio Output Commands
206 "disableoutput": self._fetch_nothing,
207 "enableoutput": self._fetch_nothing,
208 "toggleoutput": self._fetch_nothing,
209 "outputs": self._fetch_outputs,
210 # Reflection Commands
211 "config": self._fetch_object,
212 "commands": self._fetch_list,
213 "notcommands": self._fetch_list,
214 "tagtypes": self._fetch_list,
215 "urlhandlers": self._fetch_list,
216 "decoders": self._fetch_plugins,
218 "subscribe": self._fetch_nothing,
219 "unsubscribe": self._fetch_nothing,
220 "channels": self._fetch_list,
221 "readmessages": self._fetch_messages,
222 "sendmessage": self._fetch_nothing,
226 def _get_envvars(self):
228 Retrieve MPD env. var. to overrides "localhost:6600"
229 Use MPD_HOST/MPD_PORT if set
230 else use MPD_HOST=${XDG_RUNTIME_DIR:-/run/}/mpd/socket if file exists
232 self.host = 'localhost'
234 self.port = os.environ.get('MPD_PORT', '6600')
235 mpd_host_env = os.environ.get('MPD_HOST')
237 # If password is set:
238 # mpd_host_env = ['pass', 'host'] because MPD_HOST=pass@host
239 mpd_host_env = mpd_host_env.split('@')
240 mpd_host_env.reverse()
241 self.host = mpd_host_env[0]
242 if len(mpd_host_env) > 1 and mpd_host_env[1]:
243 self.password = mpd_host_env[1]
246 xdg_runtime_dir = os.environ.get('XDG_RUNTIME_DIR', '/run')
247 rundir = os.path.join(xdg_runtime_dir, 'mpd/socket')
248 if os.path.exists(rundir):
251 def __getattr__(self, attr):
252 if attr == 'send_noidle': # have send_noidle to cancel idle as well as noidle
254 if attr.startswith("send_"):
255 command = attr.replace("send_", "", 1)
257 elif attr.startswith("fetch_"):
258 command = attr.replace("fetch_", "", 1)
259 wrapper = self._fetch
262 wrapper = self._execute
263 if command not in self._commands:
264 command = command.replace("_", " ")
265 if command not in self._commands:
266 raise AttributeError("'%s' object has no attribute '%s'" %
267 (self.__class__.__name__, attr))
268 return lambda *args: wrapper(command, args)
270 def _send(self, command, args):
271 if self._command_list is not None:
272 raise CommandListError("Cannot use send_%s in a command list" %
273 command.replace(" ", "_"))
274 self._write_command(command, args)
275 retval = self._commands[command]
276 if retval is not None:
277 self._pending.append(command)
279 def _fetch(self, command, args=None):
280 if self._command_list is not None:
281 raise CommandListError("Cannot use fetch_%s in a command list" %
282 command.replace(" ", "_"))
284 raise IteratingError("Cannot use fetch_%s while iterating" %
285 command.replace(" ", "_"))
286 if not self._pending:
287 raise PendingCommandError("No pending commands to fetch")
288 if self._pending[0] != command:
289 raise PendingCommandError("'%s' is not the currently "
290 "pending command" % command)
292 retval = self._commands[command]
297 def _execute(self, command, args):
299 raise IteratingError("Cannot execute '%s' while iterating" %
302 raise PendingCommandError("Cannot execute '%s' with "
303 "pending commands" % command)
304 retval = self._commands[command]
305 if self._command_list is not None:
306 if not callable(retval):
307 raise CommandListError("'%s' not allowed in command list" %
309 self._write_command(command, args)
310 self._command_list.append(retval)
312 self._write_command(command, args)
317 def _write_line(self, line):
318 self._wfile.write("%s\n" % line)
321 def _write_command(self, command, args=None):
326 if isinstance(arg, tuple):
327 parts.append('{0!s}'.format(Range(arg)))
329 parts.append('"%s"' % escape(str(arg)))
330 self._write_line(" ".join(parts))
332 def _read_line(self):
333 line = self._rfile.readline()
334 if not line.endswith("\n"):
336 raise ConnectionError("Connection lost while reading line")
337 line = line.rstrip("\n")
338 if line.startswith(ERROR_PREFIX):
339 error = line[len(ERROR_PREFIX):].strip()
340 raise CommandError(error)
341 if self._command_list is not None:
345 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
346 elif line == SUCCESS:
350 def _read_pair(self, separator):
351 line = self._read_line()
354 pair = line.split(separator, 1)
356 raise ProtocolError("Could not parse pair: '%s'" % line)
359 def _read_pairs(self, separator=": "):
360 pair = self._read_pair(separator)
363 pair = self._read_pair(separator)
365 def _read_list(self):
367 for key, value in self._read_pairs():
370 raise ProtocolError("Expected key '%s', got '%s'" %
375 def _read_playlist(self):
376 for _, value in self._read_pairs(":"):
379 def _read_objects(self, delimiters=None):
381 if delimiters is None:
383 for key, value in self._read_pairs():
386 if key in delimiters:
390 if not isinstance(obj[key], list):
391 obj[key] = [obj[key], value]
393 obj[key].append(value)
399 def _read_command_list(self):
401 for retval in self._command_list:
404 self._command_list = None
405 self._fetch_nothing()
407 def _fetch_nothing(self):
408 line = self._read_line()
410 raise ProtocolError("Got unexpected return value: '%s'" % line)
412 def _fetch_item(self):
413 pairs = list(self._read_pairs())
419 def _fetch_list(self):
420 return self._read_list()
423 def _fetch_playlist(self):
424 return self._read_playlist()
426 def _fetch_object(self):
427 objs = list(self._read_objects())
433 def _fetch_objects(self, delimiters):
434 return self._read_objects(delimiters)
436 def _fetch_changes(self):
437 return self._fetch_objects(["cpos"])
439 def _fetch_songs(self):
440 return self._fetch_objects(["file"])
442 def _fetch_playlists(self):
443 return self._fetch_objects(["playlist"])
445 def _fetch_database(self):
446 return self._fetch_objects(["file", "directory", "playlist"])
448 def _fetch_outputs(self):
449 return self._fetch_objects(["outputid"])
451 def _fetch_plugins(self):
452 return self._fetch_objects(["plugin"])
454 def _fetch_messages(self):
455 return self._fetch_objects(["channel"])
457 def _fetch_mounts(self):
458 return self._fetch_objects(["mount"])
460 def _fetch_neighbors(self):
461 return self._fetch_objects(["neighbor"])
464 def _fetch_command_list(self):
465 return self._read_command_list()
468 line = self._rfile.readline()
469 if not line.endswith("\n"):
470 raise ConnectionError("Connection lost while reading MPD hello")
471 line = line.rstrip("\n")
472 if not line.startswith(HELLO_PREFIX):
473 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
474 self.mpd_version = line[len(HELLO_PREFIX):].strip()
477 self.mpd_version = None
478 self._iterating = False
480 self._command_list = None
482 self._rfile = _NotConnected()
483 self._wfile = _NotConnected()
485 def _connect_unix(self, path):
486 if not hasattr(socket, "AF_UNIX"):
487 raise ConnectionError("Unix domain sockets not supported "
489 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
493 def _connect_tcp(self, host, port):
495 flags = socket.AI_ADDRCONFIG
496 except AttributeError:
499 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
500 socket.SOCK_STREAM, socket.IPPROTO_TCP,
502 af, socktype, proto, _, sa = res
505 sock = socket.socket(af, socktype, proto)
508 except socket.error as socket_err:
513 raise ConnectionError(str(err))
515 raise ConnectionError("getaddrinfo returns an empty list")
518 # noidle's special case
519 if not self._pending or self._pending[0] != 'idle':
520 raise CommandError('cannot send noidle if send_idle was not called')
522 self._write_command("noidle")
523 return self._fetch_list()
525 def connect(self, host=None, port=None):
530 if self._sock is not None:
531 raise ConnectionError("Already connected")
532 if host.startswith("/"):
533 self._sock = self._connect_unix(host)
535 self._sock = self._connect_tcp(host, port)
536 self._rfile = self._sock.makefile("r", encoding='utf-8')
537 self._wfile = self._sock.makefile("w", encoding='utf-8')
544 def disconnect(self):
545 if hasattr(self._rfile, 'close'):
547 if hasattr(self._wfile, 'close'):
549 if hasattr(self._sock, 'close'):
554 if self._sock is None:
555 raise ConnectionError("Not connected")
556 return self._sock.fileno()
558 def command_list_ok_begin(self):
559 if self._command_list is not None:
560 raise CommandListError("Already in command list")
562 raise IteratingError("Cannot begin command list while iterating")
564 raise PendingCommandError("Cannot begin command list "
565 "with pending commands")
566 self._write_command("command_list_ok_begin")
567 self._command_list = []
569 def command_list_end(self):
570 if self._command_list is None:
571 raise CommandListError("Not in command list")
573 raise IteratingError("Already iterating over a command list")
574 self._write_command("command_list_end")
575 return self._fetch_command_list()
579 return text.replace("\\", "\\\\").replace('"', '\\"')
581 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: