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
21 from functools import wraps
24 HELLO_PREFIX = "OK MPD "
31 def iterator_wrapper(func):
32 """Decorator handling iterate option"""
34 def decorated_function(instance, *args, **kwargs):
35 generator = func(instance, *args, **kwargs)
36 if not instance.iterate:
37 return list(generator)
38 instance._iterating = True
44 instance._iterating = False
45 return iterator(generator)
46 return decorated_function
49 class MPDError(Exception):
52 class ConnectionError(MPDError):
55 class ProtocolError(MPDError):
58 class CommandError(MPDError):
61 class CommandListError(MPDError):
64 class PendingCommandError(MPDError):
67 class IteratingError(MPDError):
72 def __init__(self, tpl):
77 if len(self.tpl) == 0:
79 if len(self.tpl) == 1:
80 return '{0}:'.format(self.tpl[0])
81 return '{0[0]}:{0[1]}'.format(self.tpl)
84 return 'Range({0})'.format(self.tpl)
87 if not isinstance(self.tpl, tuple):
88 raise CommandError('Wrong type, provide a tuple')
89 if len(self.tpl) not in [0, 1, 2]:
90 raise CommandError('length not in [0, 1, 2]')
91 for index in self.tpl:
94 except (TypeError, ValueError):
95 raise CommandError('Not a tuple of int')
98 def __getattr__(self, attr):
102 raise ConnectionError("Not connected")
110 "clearerror": self._fetch_nothing,
111 "currentsong": self._fetch_object,
112 "idle": self._fetch_list,
114 "status": self._fetch_object,
115 "stats": self._fetch_object,
116 # Playback Option Commands
117 "consume": self._fetch_nothing,
118 "crossfade": self._fetch_nothing,
119 "mixrampdb": self._fetch_nothing,
120 "mixrampdelay": self._fetch_nothing,
121 "random": self._fetch_nothing,
122 "repeat": self._fetch_nothing,
123 "setvol": self._fetch_nothing,
124 "single": self._fetch_nothing,
125 "replay_gain_mode": self._fetch_nothing,
126 "replay_gain_status": self._fetch_item,
127 "volume": self._fetch_nothing,
128 # Playback Control Commands
129 "next": self._fetch_nothing,
130 "pause": self._fetch_nothing,
131 "play": self._fetch_nothing,
132 "playid": self._fetch_nothing,
133 "previous": self._fetch_nothing,
134 "seek": self._fetch_nothing,
135 "seekid": self._fetch_nothing,
136 "seekcur": self._fetch_nothing,
137 "stop": self._fetch_nothing,
139 "add": self._fetch_nothing,
140 "addid": self._fetch_item,
141 "clear": self._fetch_nothing,
142 "delete": self._fetch_nothing,
143 "deleteid": self._fetch_nothing,
144 "move": self._fetch_nothing,
145 "moveid": self._fetch_nothing,
146 "playlist": self._fetch_playlist,
147 "playlistfind": self._fetch_songs,
148 "playlistid": self._fetch_songs,
149 "playlistinfo": self._fetch_songs,
150 "playlistsearch": self._fetch_songs,
151 "plchanges": self._fetch_songs,
152 "plchangesposid": self._fetch_changes,
153 "prio": self._fetch_nothing,
154 "prioid": self._fetch_nothing,
155 "rangeid": self._fetch_nothing,
156 "shuffle": self._fetch_nothing,
157 "swap": self._fetch_nothing,
158 "swapid": self._fetch_nothing,
159 "addtagid": self._fetch_nothing,
160 "cleartagid": self._fetch_nothing,
161 # Stored Playlist Commands
162 "listplaylist": self._fetch_list,
163 "listplaylistinfo": self._fetch_songs,
164 "listplaylists": self._fetch_playlists,
165 "load": self._fetch_nothing,
166 "playlistadd": self._fetch_nothing,
167 "playlistclear": self._fetch_nothing,
168 "playlistdelete": self._fetch_nothing,
169 "playlistmove": self._fetch_nothing,
170 "rename": self._fetch_nothing,
171 "rm": self._fetch_nothing,
172 "save": self._fetch_nothing,
174 "count": self._fetch_object,
175 "find": self._fetch_songs,
176 "findadd": self._fetch_nothing,
177 "list": self._fetch_list,
178 "listall": self._fetch_database,
179 "listallinfo": self._fetch_database,
180 "lsinfo": self._fetch_database,
181 "search": self._fetch_songs,
182 "searchadd": self._fetch_nothing,
183 "searchaddpl": self._fetch_nothing,
184 "update": self._fetch_item,
185 "rescan": self._fetch_item,
186 "readcomments": self._fetch_object,
187 # Mounts and neighbors
188 "mount": self._fetch_nothing,
189 "unmount": self._fetch_nothing,
190 "listmounts": self._fetch_mounts,
191 "listneighbors": self._fetch_neighbors,
193 "sticker get": self._fetch_item,
194 "sticker set": self._fetch_nothing,
195 "sticker delete": self._fetch_nothing,
196 "sticker list": self._fetch_list,
197 "sticker find": self._fetch_songs,
198 # Connection Commands
201 "password": self._fetch_nothing,
202 "ping": self._fetch_nothing,
203 # Audio Output Commands
204 "disableoutput": self._fetch_nothing,
205 "enableoutput": self._fetch_nothing,
206 "toggleoutput": self._fetch_nothing,
207 "outputs": self._fetch_outputs,
208 # Reflection Commands
209 "config": self._fetch_object,
210 "commands": self._fetch_list,
211 "notcommands": self._fetch_list,
212 "tagtypes": self._fetch_list,
213 "urlhandlers": self._fetch_list,
214 "decoders": self._fetch_plugins,
216 "subscribe": self._fetch_nothing,
217 "unsubscribe": self._fetch_nothing,
218 "channels": self._fetch_list,
219 "readmessages": self._fetch_messages,
220 "sendmessage": self._fetch_nothing,
223 def __getattr__(self, attr):
224 if attr == 'send_noidle': # have send_noidle to cancel idle as well as noidle
226 if attr.startswith("send_"):
227 command = attr.replace("send_", "", 1)
229 elif attr.startswith("fetch_"):
230 command = attr.replace("fetch_", "", 1)
231 wrapper = self._fetch
234 wrapper = self._execute
235 if command not in self._commands:
236 command = command.replace("_", " ")
237 if command not in self._commands:
238 raise AttributeError("'%s' object has no attribute '%s'" %
239 (self.__class__.__name__, attr))
240 return lambda *args: wrapper(command, args)
242 def _send(self, command, args):
243 if self._command_list is not None:
244 raise CommandListError("Cannot use send_%s in a command list" %
245 command.replace(" ", "_"))
246 self._write_command(command, args)
247 retval = self._commands[command]
248 if retval is not None:
249 self._pending.append(command)
251 def _fetch(self, command, args=None):
252 if self._command_list is not None:
253 raise CommandListError("Cannot use fetch_%s in a command list" %
254 command.replace(" ", "_"))
256 raise IteratingError("Cannot use fetch_%s while iterating" %
257 command.replace(" ", "_"))
258 if not self._pending:
259 raise PendingCommandError("No pending commands to fetch")
260 if self._pending[0] != command:
261 raise PendingCommandError("'%s' is not the currently "
262 "pending command" % command)
264 retval = self._commands[command]
269 def _execute(self, command, args):
271 raise IteratingError("Cannot execute '%s' while iterating" %
274 raise PendingCommandError("Cannot execute '%s' with "
275 "pending commands" % command)
276 retval = self._commands[command]
277 if self._command_list is not None:
278 if not callable(retval):
279 raise CommandListError("'%s' not allowed in command list" %
281 self._write_command(command, args)
282 self._command_list.append(retval)
284 self._write_command(command, args)
289 def _write_line(self, line):
290 self._wfile.write("%s\n" % line)
293 def _write_command(self, command, args=None):
298 if isinstance(arg, tuple):
299 parts.append('{0!s}'.format(Range(arg)))
301 parts.append('"%s"' % escape(str(arg)))
302 self._write_line(" ".join(parts))
304 def _read_line(self):
305 line = self._rfile.readline()
306 if not line.endswith("\n"):
308 raise ConnectionError("Connection lost while reading line")
309 line = line.rstrip("\n")
310 if line.startswith(ERROR_PREFIX):
311 error = line[len(ERROR_PREFIX):].strip()
312 raise CommandError(error)
313 if self._command_list is not None:
317 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
318 elif line == SUCCESS:
322 def _read_pair(self, separator):
323 line = self._read_line()
326 pair = line.split(separator, 1)
328 raise ProtocolError("Could not parse pair: '%s'" % line)
331 def _read_pairs(self, separator=": "):
332 pair = self._read_pair(separator)
335 pair = self._read_pair(separator)
337 def _read_list(self):
339 for key, value in self._read_pairs():
342 raise ProtocolError("Expected key '%s', got '%s'" %
347 def _read_playlist(self):
348 for _, value in self._read_pairs(":"):
351 def _read_objects(self, delimiters=None):
353 if delimiters is None:
355 for key, value in self._read_pairs():
358 if key in delimiters:
362 if not isinstance(obj[key], list):
363 obj[key] = [obj[key], value]
365 obj[key].append(value)
371 def _read_command_list(self):
373 for retval in self._command_list:
376 self._command_list = None
377 self._fetch_nothing()
379 def _fetch_nothing(self):
380 line = self._read_line()
382 raise ProtocolError("Got unexpected return value: '%s'" % line)
384 def _fetch_item(self):
385 pairs = list(self._read_pairs())
391 def _fetch_list(self):
392 return self._read_list()
395 def _fetch_playlist(self):
396 return self._read_playlist()
398 def _fetch_object(self):
399 objs = list(self._read_objects())
405 def _fetch_objects(self, delimiters):
406 return self._read_objects(delimiters)
408 def _fetch_changes(self):
409 return self._fetch_objects(["cpos"])
411 def _fetch_songs(self):
412 return self._fetch_objects(["file"])
414 def _fetch_playlists(self):
415 return self._fetch_objects(["playlist"])
417 def _fetch_database(self):
418 return self._fetch_objects(["file", "directory", "playlist"])
420 def _fetch_outputs(self):
421 return self._fetch_objects(["outputid"])
423 def _fetch_plugins(self):
424 return self._fetch_objects(["plugin"])
426 def _fetch_messages(self):
427 return self._fetch_objects(["channel"])
429 def _fetch_mounts(self):
430 return self._fetch_objects(["mount"])
432 def _fetch_neighbors(self):
433 return self._fetch_objects(["neighbor"])
436 def _fetch_command_list(self):
437 return self._read_command_list()
440 line = self._rfile.readline()
441 if not line.endswith("\n"):
442 raise ConnectionError("Connection lost while reading MPD hello")
443 line = line.rstrip("\n")
444 if not line.startswith(HELLO_PREFIX):
445 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
446 self.mpd_version = line[len(HELLO_PREFIX):].strip()
449 # pylint: disable=w0201
450 self.mpd_version = None
451 self._iterating = False
453 self._command_list = None
455 self._rfile = _NotConnected()
456 self._wfile = _NotConnected()
458 def _connect_unix(self, path):
459 if not hasattr(socket, "AF_UNIX"):
460 raise ConnectionError("Unix domain sockets not supported "
462 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
466 def _connect_tcp(self, host, port):
468 flags = socket.AI_ADDRCONFIG
469 except AttributeError:
472 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
473 socket.SOCK_STREAM, socket.IPPROTO_TCP,
475 af, socktype, proto, _, sa = res
478 sock = socket.socket(af, socktype, proto)
481 except socket.error as socket_err:
486 raise ConnectionError(str(err))
488 raise ConnectionError("getaddrinfo returns an empty list")
491 # noidle's special case
492 if not self._pending or self._pending[0] != 'idle':
493 raise CommandError('cannot send noidle if send_idle was not called')
495 self._write_command("noidle")
496 return self._fetch_list()
498 def connect(self, host, port):
499 if self._sock is not None:
500 raise ConnectionError("Already connected")
501 if host.startswith("/"):
502 self._sock = self._connect_unix(host)
504 self._sock = self._connect_tcp(host, port)
505 self._rfile = self._sock.makefile("r", encoding='utf-8')
506 self._wfile = self._sock.makefile("w", encoding='utf-8')
513 def disconnect(self):
514 if hasattr(self._rfile, 'close'):
516 if hasattr(self._wfile, 'close'):
518 if hasattr(self._sock, 'close'):
523 if self._sock is None:
524 raise ConnectionError("Not connected")
525 return self._sock.fileno()
527 def command_list_ok_begin(self):
528 if self._command_list is not None:
529 raise CommandListError("Already in command list")
531 raise IteratingError("Cannot begin command list while iterating")
533 raise PendingCommandError("Cannot begin command list "
534 "with pending commands")
535 self._write_command("command_list_ok_begin")
536 self._command_list = []
538 def command_list_end(self):
539 if self._command_list is None:
540 raise CommandListError("Not in command list")
542 raise IteratingError("Already iterating over a command list")
543 self._write_command("command_list_end")
544 return self._fetch_command_list()
548 return text.replace("\\", "\\\\").replace('"', '\\"')
550 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: