1 # python-musicpd: Python MPD client library
2 # Copyright (C) 2008-2010 J. Alexander Treuman <jat@spatialrift.net>
3 # Copyright (C) 2012-2013 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/>.
21 HELLO_PREFIX = "OK MPD "
28 class MPDError(Exception):
31 class ConnectionError(MPDError):
34 class ProtocolError(MPDError):
37 class CommandError(MPDError):
40 class CommandListError(MPDError):
43 class PendingCommandError(MPDError):
46 class IteratingError(MPDError):
50 class _NotConnected(object):
51 def __getattr__(self, attr):
55 raise ConnectionError("Not connected")
57 class MPDClient(object):
63 "clearerror": self._fetch_nothing,
64 "currentsong": self._fetch_object,
65 "idle": self._fetch_list,
67 "status": self._fetch_object,
68 "stats": self._fetch_object,
69 # Playback Option Commands
70 "consume": self._fetch_nothing,
71 "crossfade": self._fetch_nothing,
72 "mixrampdb": self._fetch_nothing,
73 "mixrampdelay": self._fetch_nothing,
74 "random": self._fetch_nothing,
75 "repeat": self._fetch_nothing,
76 "setvol": self._fetch_nothing,
77 "single": self._fetch_nothing,
78 "replay_gain_mode": self._fetch_nothing,
79 "replay_gain_status": self._fetch_item,
80 "volume": self._fetch_nothing,
81 # Playback Control Commands
82 "next": self._fetch_nothing,
83 "pause": self._fetch_nothing,
84 "play": self._fetch_nothing,
85 "playid": self._fetch_nothing,
86 "previous": self._fetch_nothing,
87 "seek": self._fetch_nothing,
88 "seekid": self._fetch_nothing,
89 "seekcur": self._fetch_nothing,
90 "stop": self._fetch_nothing,
92 "add": self._fetch_nothing,
93 "addid": self._fetch_item,
94 "clear": self._fetch_nothing,
95 "delete": self._fetch_nothing,
96 "deleteid": self._fetch_nothing,
97 "move": self._fetch_nothing,
98 "moveid": self._fetch_nothing,
99 "playlist": self._fetch_playlist,
100 "playlistfind": self._fetch_songs,
101 "playlistid": self._fetch_songs,
102 "playlistinfo": self._fetch_songs,
103 "playlistsearch": self._fetch_songs,
104 "plchanges": self._fetch_songs,
105 "plchangesposid": self._fetch_changes,
106 "shuffle": self._fetch_nothing,
107 "swap": self._fetch_nothing,
108 "swapid": self._fetch_nothing,
109 # Stored Playlist Commands
110 "listplaylist": self._fetch_list,
111 "listplaylistinfo": self._fetch_songs,
112 "listplaylists": self._fetch_playlists,
113 "load": self._fetch_nothing,
114 "playlistadd": self._fetch_nothing,
115 "playlistclear": self._fetch_nothing,
116 "playlistdelete": self._fetch_nothing,
117 "playlistmove": self._fetch_nothing,
118 "rename": self._fetch_nothing,
119 "rm": self._fetch_nothing,
120 "save": self._fetch_nothing,
122 "count": self._fetch_object,
123 "find": self._fetch_songs,
124 "findadd": self._fetch_nothing,
125 "list": self._fetch_list,
126 "listall": self._fetch_database,
127 "listallinfo": self._fetch_database,
128 "lsinfo": self._fetch_database,
129 "search": self._fetch_songs,
130 "searchadd": self._fetch_nothing,
131 "searchaddpl": self._fetch_nothing,
132 "update": self._fetch_item,
133 "rescan": self._fetch_item,
134 "readcomments": self._fetch_object,
136 "sticker get": self._fetch_item,
137 "sticker set": self._fetch_nothing,
138 "sticker delete": self._fetch_nothing,
139 "sticker list": self._fetch_list,
140 "sticker find": self._fetch_songs,
141 # Connection Commands
144 "password": self._fetch_nothing,
145 "ping": self._fetch_nothing,
146 # Audio Output Commands
147 "disableoutput": self._fetch_nothing,
148 "enableoutput": self._fetch_nothing,
149 "toggleoutput": self._fetch_nothing,
150 "outputs": self._fetch_outputs,
151 # Reflection Commands
152 "commands": self._fetch_list,
153 "notcommands": self._fetch_list,
154 "tagtypes": self._fetch_list,
155 "urlhandlers": self._fetch_list,
156 "decoders": self._fetch_plugins,
158 "subscribe": self._fetch_nothing,
159 "unsubscribe": self._fetch_nothing,
160 "channels": self._fetch_list,
161 "readmessages": self._fetch_messages,
162 "sendmessage": self._fetch_nothing,
165 def __getattr__(self, attr):
166 if attr.startswith("send_"):
167 command = attr.replace("send_", "", 1)
169 elif attr.startswith("fetch_"):
170 command = attr.replace("fetch_", "", 1)
171 wrapper = self._fetch
174 wrapper = self._execute
175 if command not in self._commands:
176 command = command.replace("_", " ")
177 if command not in self._commands:
178 raise AttributeError("'%s' object has no attribute '%s'" %
179 (self.__class__.__name__, attr))
180 return lambda *args: wrapper(command, args)
182 def _send(self, command, args):
183 if self._command_list is not None:
184 raise CommandListError("Cannot use send_%s in a command list" %
185 command.replace(" ", "_"))
186 self._write_command(command, args)
187 retval = self._commands[command]
188 if retval is not None:
189 self._pending.append(command)
191 def _fetch(self, command, args=None):
192 if self._command_list is not None:
193 raise CommandListError("Cannot use fetch_%s in a command list" %
194 command.replace(" ", "_"))
196 raise IteratingError("Cannot use fetch_%s while iterating" %
197 command.replace(" ", "_"))
198 if not self._pending:
199 raise PendingCommandError("No pending commands to fetch")
200 if self._pending[0] != command:
201 raise PendingCommandError("'%s' is not the currently "
202 "pending command" % command)
204 retval = self._commands[command]
209 def _execute(self, command, args):
211 raise IteratingError("Cannot execute '%s' while iterating" %
214 raise PendingCommandError("Cannot execute '%s' with "
215 "pending commands" % command)
216 retval = self._commands[command]
217 if self._command_list is not None:
218 if not callable(retval):
219 raise CommandListError("'%s' not allowed in command list" %
221 self._write_command(command, args)
222 self._command_list.append(retval)
224 self._write_command(command, args)
229 def _write_line(self, line):
230 self._wfile.write("%s\n" % line)
233 def _write_command(self, command, args=[]):
236 parts.append('"%s"' % escape(str(arg)))
237 self._write_line(" ".join(parts))
239 def _read_line(self):
240 line = self._rfile.readline()
241 if not line.endswith("\n"):
243 raise ConnectionError("Connection lost while reading line")
244 line = line.rstrip("\n")
245 if line.startswith(ERROR_PREFIX):
246 error = line[len(ERROR_PREFIX):].strip()
247 raise CommandError(error)
248 if self._command_list is not None:
252 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
253 elif line == SUCCESS:
257 def _read_pair(self, separator):
258 line = self._read_line()
261 pair = line.split(separator, 1)
263 raise ProtocolError("Could not parse pair: '%s'" % line)
266 def _read_pairs(self, separator=": "):
267 pair = self._read_pair(separator)
270 pair = self._read_pair(separator)
272 def _read_list(self):
274 for key, value in self._read_pairs():
277 raise ProtocolError("Expected key '%s', got '%s'" %
282 def _read_playlist(self):
283 for key, value in self._read_pairs(":"):
286 def _read_objects(self, delimiters=[]):
288 for key, value in self._read_pairs():
291 if key in delimiters:
295 if not isinstance(obj[key], list):
296 obj[key] = [obj[key], value]
298 obj[key].append(value)
304 def _read_command_list(self):
306 for retval in self._command_list:
309 self._command_list = None
310 self._fetch_nothing()
312 def _iterator_wrapper(self, iterator):
314 for item in iterator:
317 self._iterating = False
319 def _wrap_iterator(self, iterator):
321 return list(iterator)
322 self._iterating = True
323 return self._iterator_wrapper(iterator)
325 def _fetch_nothing(self):
326 line = self._read_line()
328 raise ProtocolError("Got unexpected return value: '%s'" % line)
330 def _fetch_item(self):
331 pairs = list(self._read_pairs())
336 def _fetch_list(self):
337 return self._wrap_iterator(self._read_list())
339 def _fetch_playlist(self):
340 return self._wrap_iterator(self._read_playlist())
342 def _fetch_object(self):
343 objs = list(self._read_objects())
348 def _fetch_objects(self, delimiters):
349 return self._wrap_iterator(self._read_objects(delimiters))
351 def _fetch_changes(self):
352 return self._fetch_objects(["cpos"])
354 def _fetch_songs(self):
355 return self._fetch_objects(["file"])
357 def _fetch_playlists(self):
358 return self._fetch_objects(["playlist"])
360 def _fetch_database(self):
361 return self._fetch_objects(["file", "directory", "playlist"])
363 def _fetch_outputs(self):
364 return self._fetch_objects(["outputid"])
366 def _fetch_plugins(self):
367 return self._fetch_objects(["plugin"])
369 def _fetch_messages(self):
370 return self._fetch_objects(["channel"])
372 def _fetch_command_list(self):
373 return self._wrap_iterator(self._read_command_list())
376 line = self._rfile.readline()
377 if not line.endswith("\n"):
378 raise ConnectionError("Connection lost while reading MPD hello")
379 line = line.rstrip("\n")
380 if not line.startswith(HELLO_PREFIX):
381 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
382 self.mpd_version = line[len(HELLO_PREFIX):].strip()
385 self.mpd_version = None
386 self._iterating = False
388 self._command_list = None
390 self._rfile = _NotConnected()
391 self._wfile = _NotConnected()
393 def _connect_unix(self, path):
394 if not hasattr(socket, "AF_UNIX"):
395 raise ConnectionError("Unix domain sockets not supported "
397 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
401 def _connect_tcp(self, host, port):
403 flags = socket.AI_ADDRCONFIG
404 except AttributeError:
407 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
408 socket.SOCK_STREAM, socket.IPPROTO_TCP,
410 af, socktype, proto, canonname, sa = res
413 sock = socket.socket(af, socktype, proto)
416 except socket.error as socket_err:
421 raise ConnectionError(str(err))
423 raise ConnectionError("getaddrinfo returns an empty list")
425 def connect(self, host, port):
426 if self._sock is not None:
427 raise ConnectionError("Already connected")
428 if host.startswith("/"):
429 self._sock = self._connect_unix(host)
431 self._sock = self._connect_tcp(host, port)
432 self._rfile = self._sock.makefile("r", encoding='utf-8')
433 self._wfile = self._sock.makefile("w", encoding='utf-8')
440 def disconnect(self):
441 if hasattr(self._rfile, 'close'):
443 if hasattr(self._wfile, 'close'):
445 if hasattr(self._sock, 'close'):
450 if self._sock is None:
451 raise ConnectionError("Not connected")
452 return self._sock.fileno()
454 def command_list_ok_begin(self):
455 if self._command_list is not None:
456 raise CommandListError("Already in command list")
458 raise IteratingError("Cannot begin command list while iterating")
460 raise PendingCommandError("Cannot begin command list "
461 "with pending commands")
462 self._write_command("command_list_ok_begin")
463 self._command_list = []
465 def command_list_end(self):
466 if self._command_list is None:
467 raise CommandListError("Not in command list")
469 raise IteratingError("Already iterating over a command list")
470 self._write_command("command_list_end")
471 return self._fetch_command_list()
475 return text.replace("\\", "\\\\").replace('"', '\\"')
478 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: