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 "commands": self._fetch_list,
192 "notcommands": self._fetch_list,
193 "tagtypes": self._fetch_list,
194 "urlhandlers": self._fetch_list,
195 "decoders": self._fetch_plugins,
197 "subscribe": self._fetch_nothing,
198 "unsubscribe": self._fetch_nothing,
199 "channels": self._fetch_list,
200 "readmessages": self._fetch_messages,
201 "sendmessage": self._fetch_nothing,
204 def __getattr__(self, attr):
205 if attr == 'send_noidle': # have send_noidle to cancel idle as well as noidle
207 if attr.startswith("send_"):
208 command = attr.replace("send_", "", 1)
210 elif attr.startswith("fetch_"):
211 command = attr.replace("fetch_", "", 1)
212 wrapper = self._fetch
215 wrapper = self._execute
216 if command not in self._commands:
217 command = command.replace("_", " ")
218 if command not in self._commands:
219 raise AttributeError("'%s' object has no attribute '%s'" %
220 (self.__class__.__name__, attr))
221 return lambda *args: wrapper(command, args)
223 def _send(self, command, args):
224 if self._command_list is not None:
225 raise CommandListError("Cannot use send_%s in a command list" %
226 command.replace(" ", "_"))
227 self._write_command(command, args)
228 retval = self._commands[command]
229 if retval is not None:
230 self._pending.append(command)
232 def _fetch(self, command, args=None):
233 if self._command_list is not None:
234 raise CommandListError("Cannot use fetch_%s in a command list" %
235 command.replace(" ", "_"))
237 raise IteratingError("Cannot use fetch_%s while iterating" %
238 command.replace(" ", "_"))
239 if not self._pending:
240 raise PendingCommandError("No pending commands to fetch")
241 if self._pending[0] != command:
242 raise PendingCommandError("'%s' is not the currently "
243 "pending command" % command)
245 retval = self._commands[command]
250 def _execute(self, command, args):
252 raise IteratingError("Cannot execute '%s' while iterating" %
255 raise PendingCommandError("Cannot execute '%s' with "
256 "pending commands" % command)
257 retval = self._commands[command]
258 if self._command_list is not None:
259 if not callable(retval):
260 raise CommandListError("'%s' not allowed in command list" %
262 self._write_command(command, args)
263 self._command_list.append(retval)
265 self._write_command(command, args)
270 def _write_line(self, line):
271 self._wfile.write("%s\n" % line)
274 def _write_command(self, command, args=None):
279 if isinstance(arg, tuple):
280 parts.append('{0!s}'.format(Range(arg)))
282 parts.append('"%s"' % escape(str(arg)))
283 self._write_line(" ".join(parts))
285 def _read_line(self):
286 line = self._rfile.readline()
287 if not line.endswith("\n"):
289 raise ConnectionError("Connection lost while reading line")
290 line = line.rstrip("\n")
291 if line.startswith(ERROR_PREFIX):
292 error = line[len(ERROR_PREFIX):].strip()
293 raise CommandError(error)
294 if self._command_list is not None:
298 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
299 elif line == SUCCESS:
303 def _read_pair(self, separator):
304 line = self._read_line()
307 pair = line.split(separator, 1)
309 raise ProtocolError("Could not parse pair: '%s'" % line)
312 def _read_pairs(self, separator=": "):
313 pair = self._read_pair(separator)
316 pair = self._read_pair(separator)
318 def _read_list(self):
320 for key, value in self._read_pairs():
323 raise ProtocolError("Expected key '%s', got '%s'" %
328 def _read_playlist(self):
329 for _, value in self._read_pairs(":"):
332 def _read_objects(self, delimiters=None):
334 if delimiters is None:
336 for key, value in self._read_pairs():
339 if key in delimiters:
343 if not isinstance(obj[key], list):
344 obj[key] = [obj[key], value]
346 obj[key].append(value)
352 def _read_command_list(self):
354 for retval in self._command_list:
357 self._command_list = None
358 self._fetch_nothing()
360 def _iterator_wrapper(self, iterator):
362 for item in iterator:
365 self._iterating = False
367 def _wrap_iterator(self, iterator):
369 return list(iterator)
370 self._iterating = True
371 return self._iterator_wrapper(iterator)
373 def _fetch_nothing(self):
374 line = self._read_line()
376 raise ProtocolError("Got unexpected return value: '%s'" % line)
378 def _fetch_item(self):
379 pairs = list(self._read_pairs())
384 def _fetch_list(self):
385 return self._wrap_iterator(self._read_list())
387 def _fetch_playlist(self):
388 return self._wrap_iterator(self._read_playlist())
390 def _fetch_object(self):
391 objs = list(self._read_objects())
396 def _fetch_objects(self, delimiters):
397 return self._wrap_iterator(self._read_objects(delimiters))
399 def _fetch_changes(self):
400 return self._fetch_objects(["cpos"])
402 def _fetch_songs(self):
403 return self._fetch_objects(["file"])
405 def _fetch_playlists(self):
406 return self._fetch_objects(["playlist"])
408 def _fetch_database(self):
409 return self._fetch_objects(["file", "directory", "playlist"])
411 def _fetch_outputs(self):
412 return self._fetch_objects(["outputid"])
414 def _fetch_plugins(self):
415 return self._fetch_objects(["plugin"])
417 def _fetch_messages(self):
418 return self._fetch_objects(["channel"])
420 def _fetch_mounts(self):
421 return self._fetch_objects(["mount"])
423 def _fetch_neighbors(self):
424 return self._fetch_objects(["neighbor"])
426 def _fetch_command_list(self):
427 return self._wrap_iterator(self._read_command_list())
430 line = self._rfile.readline()
431 if not line.endswith("\n"):
432 raise ConnectionError("Connection lost while reading MPD hello")
433 line = line.rstrip("\n")
434 if not line.startswith(HELLO_PREFIX):
435 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
436 self.mpd_version = line[len(HELLO_PREFIX):].strip()
439 # pylint: disable=w0201
440 self.mpd_version = None
441 self._iterating = False
443 self._command_list = None
445 self._rfile = _NotConnected()
446 self._wfile = _NotConnected()
448 def _connect_unix(self, path):
449 if not hasattr(socket, "AF_UNIX"):
450 raise ConnectionError("Unix domain sockets not supported "
452 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
456 def _connect_tcp(self, host, port):
458 flags = socket.AI_ADDRCONFIG
459 except AttributeError:
462 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
463 socket.SOCK_STREAM, socket.IPPROTO_TCP,
465 af, socktype, proto, _, sa = res
468 sock = socket.socket(af, socktype, proto)
471 except socket.error as socket_err:
476 raise ConnectionError(str(err))
478 raise ConnectionError("getaddrinfo returns an empty list")
481 # noidle's special case
482 if not self._pending or self._pending[0] != 'idle':
483 raise CommandError('cannot send noidle if send_idle was not called')
485 self._write_command("noidle")
486 return self._fetch_list()
488 def connect(self, host, port):
489 if self._sock is not None:
490 raise ConnectionError("Already connected")
491 if host.startswith("/"):
492 self._sock = self._connect_unix(host)
494 self._sock = self._connect_tcp(host, port)
495 self._rfile = self._sock.makefile("r", encoding='utf-8')
496 self._wfile = self._sock.makefile("w", encoding='utf-8')
503 def disconnect(self):
504 if hasattr(self._rfile, 'close'):
506 if hasattr(self._wfile, 'close'):
508 if hasattr(self._sock, 'close'):
513 if self._sock is None:
514 raise ConnectionError("Not connected")
515 return self._sock.fileno()
517 def command_list_ok_begin(self):
518 if self._command_list is not None:
519 raise CommandListError("Already in command list")
521 raise IteratingError("Cannot begin command list while iterating")
523 raise PendingCommandError("Cannot begin command list "
524 "with pending commands")
525 self._write_command("command_list_ok_begin")
526 self._command_list = []
528 def command_list_end(self):
529 if self._command_list is None:
530 raise CommandListError("Not in command list")
532 raise IteratingError("Already iterating over a command list")
533 self._write_command("command_list_end")
534 return self._fetch_command_list()
538 return text.replace("\\", "\\\\").replace('"', '\\"')
541 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: