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) == 0:
60 if len(self.tpl) == 1:
61 return '{0}:'.format(self.tpl[0])
62 return '{0[0]}:{0[1]}'.format(self.tpl)
65 return 'Range({0})'.format(self.tpl)
68 if not isinstance(self.tpl, tuple):
69 raise CommandError('Wrong type, provide a tuple')
70 if len(self.tpl) not in [0, 1, 2]:
71 raise CommandError('length not in [0, 1, 2]')
72 for index in self.tpl:
75 except (TypeError, ValueError):
76 raise CommandError('Not a tuple of int')
80 def __getattr__(self, attr):
84 raise ConnectionError("Not connected")
92 "clearerror": self._fetch_nothing,
93 "currentsong": self._fetch_object,
94 "idle": self._fetch_list,
96 "status": self._fetch_object,
97 "stats": self._fetch_object,
98 # Playback Option Commands
99 "consume": self._fetch_nothing,
100 "crossfade": self._fetch_nothing,
101 "mixrampdb": self._fetch_nothing,
102 "mixrampdelay": self._fetch_nothing,
103 "random": self._fetch_nothing,
104 "repeat": self._fetch_nothing,
105 "setvol": self._fetch_nothing,
106 "single": self._fetch_nothing,
107 "replay_gain_mode": self._fetch_nothing,
108 "replay_gain_status": self._fetch_item,
109 "volume": self._fetch_nothing,
110 # Playback Control Commands
111 "next": self._fetch_nothing,
112 "pause": self._fetch_nothing,
113 "play": self._fetch_nothing,
114 "playid": self._fetch_nothing,
115 "previous": self._fetch_nothing,
116 "seek": self._fetch_nothing,
117 "seekid": self._fetch_nothing,
118 "seekcur": self._fetch_nothing,
119 "stop": self._fetch_nothing,
121 "add": self._fetch_nothing,
122 "addid": self._fetch_item,
123 "clear": self._fetch_nothing,
124 "delete": self._fetch_nothing,
125 "deleteid": self._fetch_nothing,
126 "move": self._fetch_nothing,
127 "moveid": self._fetch_nothing,
128 "playlist": self._fetch_playlist,
129 "playlistfind": self._fetch_songs,
130 "playlistid": self._fetch_songs,
131 "playlistinfo": self._fetch_songs,
132 "playlistsearch": self._fetch_songs,
133 "plchanges": self._fetch_songs,
134 "plchangesposid": self._fetch_changes,
135 "prio": self._fetch_nothing,
136 "prioid": self._fetch_nothing,
137 "rangeid": self._fetch_nothing,
138 "shuffle": self._fetch_nothing,
139 "swap": self._fetch_nothing,
140 "swapid": self._fetch_nothing,
141 "addtagid": self._fetch_nothing,
142 "cleartagid": self._fetch_nothing,
143 # Stored Playlist Commands
144 "listplaylist": self._fetch_list,
145 "listplaylistinfo": self._fetch_songs,
146 "listplaylists": self._fetch_playlists,
147 "load": self._fetch_nothing,
148 "playlistadd": self._fetch_nothing,
149 "playlistclear": self._fetch_nothing,
150 "playlistdelete": self._fetch_nothing,
151 "playlistmove": self._fetch_nothing,
152 "rename": self._fetch_nothing,
153 "rm": self._fetch_nothing,
154 "save": self._fetch_nothing,
156 "count": self._fetch_object,
157 "find": self._fetch_songs,
158 "findadd": self._fetch_nothing,
159 "list": self._fetch_list,
160 "listall": self._fetch_database,
161 "listallinfo": self._fetch_database,
162 "lsinfo": self._fetch_database,
163 "search": self._fetch_songs,
164 "searchadd": self._fetch_nothing,
165 "searchaddpl": self._fetch_nothing,
166 "update": self._fetch_item,
167 "rescan": self._fetch_item,
168 "readcomments": self._fetch_object,
169 # Mounts and neighbors
170 "mount": self._fetch_nothing,
171 "unmount": self._fetch_nothing,
172 "listmounts": self._fetch_mounts,
173 "listneighbors": self._fetch_neighbors,
175 "sticker get": self._fetch_item,
176 "sticker set": self._fetch_nothing,
177 "sticker delete": self._fetch_nothing,
178 "sticker list": self._fetch_list,
179 "sticker find": self._fetch_songs,
180 # Connection Commands
183 "password": self._fetch_nothing,
184 "ping": self._fetch_nothing,
185 # Audio Output Commands
186 "disableoutput": self._fetch_nothing,
187 "enableoutput": self._fetch_nothing,
188 "toggleoutput": self._fetch_nothing,
189 "outputs": self._fetch_outputs,
190 # Reflection Commands
191 "config": self._fetch_object,
192 "commands": self._fetch_list,
193 "notcommands": self._fetch_list,
194 "tagtypes": self._fetch_list,
195 "urlhandlers": self._fetch_list,
196 "decoders": self._fetch_plugins,
198 "subscribe": self._fetch_nothing,
199 "unsubscribe": self._fetch_nothing,
200 "channels": self._fetch_list,
201 "readmessages": self._fetch_messages,
202 "sendmessage": self._fetch_nothing,
205 def __getattr__(self, attr):
206 if attr == 'send_noidle': # have send_noidle to cancel idle as well as noidle
208 if attr.startswith("send_"):
209 command = attr.replace("send_", "", 1)
211 elif attr.startswith("fetch_"):
212 command = attr.replace("fetch_", "", 1)
213 wrapper = self._fetch
216 wrapper = self._execute
217 if command not in self._commands:
218 command = command.replace("_", " ")
219 if command not in self._commands:
220 raise AttributeError("'%s' object has no attribute '%s'" %
221 (self.__class__.__name__, attr))
222 return lambda *args: wrapper(command, args)
224 def _send(self, command, args):
225 if self._command_list is not None:
226 raise CommandListError("Cannot use send_%s in a command list" %
227 command.replace(" ", "_"))
228 self._write_command(command, args)
229 retval = self._commands[command]
230 if retval is not None:
231 self._pending.append(command)
233 def _fetch(self, command, args=None):
234 if self._command_list is not None:
235 raise CommandListError("Cannot use fetch_%s in a command list" %
236 command.replace(" ", "_"))
238 raise IteratingError("Cannot use fetch_%s while iterating" %
239 command.replace(" ", "_"))
240 if not self._pending:
241 raise PendingCommandError("No pending commands to fetch")
242 if self._pending[0] != command:
243 raise PendingCommandError("'%s' is not the currently "
244 "pending command" % command)
246 retval = self._commands[command]
251 def _execute(self, command, args):
253 raise IteratingError("Cannot execute '%s' while iterating" %
256 raise PendingCommandError("Cannot execute '%s' with "
257 "pending commands" % command)
258 retval = self._commands[command]
259 if self._command_list is not None:
260 if not callable(retval):
261 raise CommandListError("'%s' not allowed in command list" %
263 self._write_command(command, args)
264 self._command_list.append(retval)
266 self._write_command(command, args)
271 def _write_line(self, line):
272 self._wfile.write("%s\n" % line)
275 def _write_command(self, command, args=None):
280 if isinstance(arg, tuple):
281 parts.append('{0!s}'.format(Range(arg)))
283 parts.append('"%s"' % escape(str(arg)))
284 self._write_line(" ".join(parts))
286 def _read_line(self):
287 line = self._rfile.readline()
288 if not line.endswith("\n"):
290 raise ConnectionError("Connection lost while reading line")
291 line = line.rstrip("\n")
292 if line.startswith(ERROR_PREFIX):
293 error = line[len(ERROR_PREFIX):].strip()
294 raise CommandError(error)
295 if self._command_list is not None:
299 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
300 elif line == SUCCESS:
304 def _read_pair(self, separator):
305 line = self._read_line()
308 pair = line.split(separator, 1)
310 raise ProtocolError("Could not parse pair: '%s'" % line)
313 def _read_pairs(self, separator=": "):
314 pair = self._read_pair(separator)
317 pair = self._read_pair(separator)
319 def _read_list(self):
321 for key, value in self._read_pairs():
324 raise ProtocolError("Expected key '%s', got '%s'" %
329 def _read_playlist(self):
330 for _, value in self._read_pairs(":"):
333 def _read_objects(self, delimiters=None):
335 if delimiters is None:
337 for key, value in self._read_pairs():
340 if key in delimiters:
344 if not isinstance(obj[key], list):
345 obj[key] = [obj[key], value]
347 obj[key].append(value)
353 def _read_command_list(self):
355 for retval in self._command_list:
358 self._command_list = None
359 self._fetch_nothing()
361 def _iterator_wrapper(self, iterator):
363 for item in iterator:
366 self._iterating = False
368 def _wrap_iterator(self, iterator):
370 return list(iterator)
371 self._iterating = True
372 return self._iterator_wrapper(iterator)
374 def _fetch_nothing(self):
375 line = self._read_line()
377 raise ProtocolError("Got unexpected return value: '%s'" % line)
379 def _fetch_item(self):
380 pairs = list(self._read_pairs())
385 def _fetch_list(self):
386 return self._wrap_iterator(self._read_list())
388 def _fetch_playlist(self):
389 return self._wrap_iterator(self._read_playlist())
391 def _fetch_object(self):
392 objs = list(self._read_objects())
397 def _fetch_objects(self, delimiters):
398 return self._wrap_iterator(self._read_objects(delimiters))
400 def _fetch_changes(self):
401 return self._fetch_objects(["cpos"])
403 def _fetch_songs(self):
404 return self._fetch_objects(["file"])
406 def _fetch_playlists(self):
407 return self._fetch_objects(["playlist"])
409 def _fetch_database(self):
410 return self._fetch_objects(["file", "directory", "playlist"])
412 def _fetch_outputs(self):
413 return self._fetch_objects(["outputid"])
415 def _fetch_plugins(self):
416 return self._fetch_objects(["plugin"])
418 def _fetch_messages(self):
419 return self._fetch_objects(["channel"])
421 def _fetch_mounts(self):
422 return self._fetch_objects(["mount"])
424 def _fetch_neighbors(self):
425 return self._fetch_objects(["neighbor"])
427 def _fetch_command_list(self):
428 return self._wrap_iterator(self._read_command_list())
431 line = self._rfile.readline()
432 if not line.endswith("\n"):
433 raise ConnectionError("Connection lost while reading MPD hello")
434 line = line.rstrip("\n")
435 if not line.startswith(HELLO_PREFIX):
436 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
437 self.mpd_version = line[len(HELLO_PREFIX):].strip()
440 # pylint: disable=w0201
441 self.mpd_version = None
442 self._iterating = False
444 self._command_list = None
446 self._rfile = _NotConnected()
447 self._wfile = _NotConnected()
449 def _connect_unix(self, path):
450 if not hasattr(socket, "AF_UNIX"):
451 raise ConnectionError("Unix domain sockets not supported "
453 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
457 def _connect_tcp(self, host, port):
459 flags = socket.AI_ADDRCONFIG
460 except AttributeError:
463 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
464 socket.SOCK_STREAM, socket.IPPROTO_TCP,
466 af, socktype, proto, _, sa = res
469 sock = socket.socket(af, socktype, proto)
472 except socket.error as socket_err:
477 raise ConnectionError(str(err))
479 raise ConnectionError("getaddrinfo returns an empty list")
482 # noidle's special case
483 if not self._pending or self._pending[0] != 'idle':
484 raise CommandError('cannot send noidle if send_idle was not called')
486 self._write_command("noidle")
487 return self._fetch_list()
489 def connect(self, host, port):
490 if self._sock is not None:
491 raise ConnectionError("Already connected")
492 if host.startswith("/"):
493 self._sock = self._connect_unix(host)
495 self._sock = self._connect_tcp(host, port)
496 self._rfile = self._sock.makefile("r", encoding='utf-8')
497 self._wfile = self._sock.makefile("w", encoding='utf-8')
504 def disconnect(self):
505 if hasattr(self._rfile, 'close'):
507 if hasattr(self._wfile, 'close'):
509 if hasattr(self._sock, 'close'):
514 if self._sock is None:
515 raise ConnectionError("Not connected")
516 return self._sock.fileno()
518 def command_list_ok_begin(self):
519 if self._command_list is not None:
520 raise CommandListError("Already in command list")
522 raise IteratingError("Cannot begin command list while iterating")
524 raise PendingCommandError("Cannot begin command list "
525 "with pending commands")
526 self._write_command("command_list_ok_begin")
527 self._command_list = []
529 def command_list_end(self):
530 if self._command_list is None:
531 raise CommandListError("Not in command list")
533 raise IteratingError("Already iterating over a command list")
534 self._write_command("command_list_end")
535 return self._fetch_command_list()
539 return text.replace("\\", "\\\\").replace('"', '\\"')
542 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: