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,
135 "sticker get": self._fetch_item,
136 "sticker set": self._fetch_nothing,
137 "sticker delete": self._fetch_nothing,
138 "sticker list": self._fetch_list,
139 "sticker find": self._fetch_songs,
140 # Connection Commands
143 "password": self._fetch_nothing,
144 "ping": self._fetch_nothing,
145 # Audio Output Commands
146 "disableoutput": self._fetch_nothing,
147 "enableoutput": self._fetch_nothing,
148 "outputs": self._fetch_outputs,
149 # Reflection Commands
150 "commands": self._fetch_list,
151 "notcommands": self._fetch_list,
152 "tagtypes": self._fetch_list,
153 "urlhandlers": self._fetch_list,
154 "decoders": self._fetch_plugins,
156 "subscribe": self._fetch_nothing,
157 "unsubscribe": self._fetch_nothing,
158 "channels": self._fetch_list,
159 "readmessages": self._fetch_messages,
160 "sendmessage": self._fetch_nothing,
163 def __getattr__(self, attr):
164 if attr.startswith("send_"):
165 command = attr.replace("send_", "", 1)
167 elif attr.startswith("fetch_"):
168 command = attr.replace("fetch_", "", 1)
169 wrapper = self._fetch
172 wrapper = self._execute
173 if command not in self._commands:
174 command = command.replace("_", " ")
175 if command not in self._commands:
176 raise AttributeError("'%s' object has no attribute '%s'" %
177 (self.__class__.__name__, attr))
178 return lambda *args: wrapper(command, args)
180 def _send(self, command, args):
181 if self._command_list is not None:
182 raise CommandListError("Cannot use send_%s in a command list" %
183 command.replace(" ", "_"))
184 self._write_command(command, args)
185 retval = self._commands[command]
186 if retval is not None:
187 self._pending.append(command)
189 def _fetch(self, command, args=None):
190 if self._command_list is not None:
191 raise CommandListError("Cannot use fetch_%s in a command list" %
192 command.replace(" ", "_"))
194 raise IteratingError("Cannot use fetch_%s while iterating" %
195 command.replace(" ", "_"))
196 if not self._pending:
197 raise PendingCommandError("No pending commands to fetch")
198 if self._pending[0] != command:
199 raise PendingCommandError("'%s' is not the currently "
200 "pending command" % command)
202 retval = self._commands[command]
207 def _execute(self, command, args):
209 raise IteratingError("Cannot execute '%s' while iterating" %
212 raise PendingCommandError("Cannot execute '%s' with "
213 "pending commands" % command)
214 retval = self._commands[command]
215 if self._command_list is not None:
216 if not callable(retval):
217 raise CommandListError("'%s' not allowed in command list" %
219 self._write_command(command, args)
220 self._command_list.append(retval)
222 self._write_command(command, args)
227 def _write_line(self, line):
228 self._wfile.write("%s\n" % line)
231 def _write_command(self, command, args=[]):
234 parts.append('"%s"' % escape(str(arg)))
235 self._write_line(" ".join(parts))
237 def _read_line(self):
238 line = self._rfile.readline()
239 if not line.endswith("\n"):
241 raise ConnectionError("Connection lost while reading line")
242 line = line.rstrip("\n")
243 if line.startswith(ERROR_PREFIX):
244 error = line[len(ERROR_PREFIX):].strip()
245 raise CommandError(error)
246 if self._command_list is not None:
250 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
251 elif line == SUCCESS:
255 def _read_pair(self, separator):
256 line = self._read_line()
259 pair = line.split(separator, 1)
261 raise ProtocolError("Could not parse pair: '%s'" % line)
264 def _read_pairs(self, separator=": "):
265 pair = self._read_pair(separator)
268 pair = self._read_pair(separator)
270 def _read_list(self):
272 for key, value in self._read_pairs():
275 raise ProtocolError("Expected key '%s', got '%s'" %
280 def _read_playlist(self):
281 for key, value in self._read_pairs(":"):
284 def _read_objects(self, delimiters=[]):
286 for key, value in self._read_pairs():
289 if key in delimiters:
293 if not isinstance(obj[key], list):
294 obj[key] = [obj[key], value]
296 obj[key].append(value)
302 def _read_command_list(self):
304 for retval in self._command_list:
307 self._command_list = None
308 self._fetch_nothing()
310 def _iterator_wrapper(self, iterator):
312 for item in iterator:
315 self._iterating = False
317 def _wrap_iterator(self, iterator):
319 return list(iterator)
320 self._iterating = True
321 return self._iterator_wrapper(iterator)
323 def _fetch_nothing(self):
324 line = self._read_line()
326 raise ProtocolError("Got unexpected return value: '%s'" % line)
328 def _fetch_item(self):
329 pairs = list(self._read_pairs())
334 def _fetch_list(self):
335 return self._wrap_iterator(self._read_list())
337 def _fetch_playlist(self):
338 return self._wrap_iterator(self._read_playlist())
340 def _fetch_object(self):
341 objs = list(self._read_objects())
346 def _fetch_objects(self, delimiters):
347 return self._wrap_iterator(self._read_objects(delimiters))
349 def _fetch_changes(self):
350 return self._fetch_objects(["cpos"])
352 def _fetch_songs(self):
353 return self._fetch_objects(["file"])
355 def _fetch_playlists(self):
356 return self._fetch_objects(["playlist"])
358 def _fetch_database(self):
359 return self._fetch_objects(["file", "directory", "playlist"])
361 def _fetch_outputs(self):
362 return self._fetch_objects(["outputid"])
364 def _fetch_plugins(self):
365 return self._fetch_objects(["plugin"])
367 def _fetch_messages(self):
368 return self._fetch_objects(["channel"])
370 def _fetch_command_list(self):
371 return self._wrap_iterator(self._read_command_list())
374 line = self._rfile.readline()
375 if not line.endswith("\n"):
376 raise ConnectionError("Connection lost while reading MPD hello")
377 line = line.rstrip("\n")
378 if not line.startswith(HELLO_PREFIX):
379 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
380 self.mpd_version = line[len(HELLO_PREFIX):].strip()
383 self.mpd_version = None
384 self._iterating = False
386 self._command_list = None
388 self._rfile = _NotConnected()
389 self._wfile = _NotConnected()
391 def _connect_unix(self, path):
392 if not hasattr(socket, "AF_UNIX"):
393 raise ConnectionError("Unix domain sockets not supported "
395 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
399 def _connect_tcp(self, host, port):
401 flags = socket.AI_ADDRCONFIG
402 except AttributeError:
405 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
406 socket.SOCK_STREAM, socket.IPPROTO_TCP,
408 af, socktype, proto, canonname, sa = res
411 sock = socket.socket(af, socktype, proto)
414 except socket.error as socket_err:
419 raise ConnectionError(str(err))
421 raise ConnectionError("getaddrinfo returns an empty list")
423 def connect(self, host, port):
424 if self._sock is not None:
425 raise ConnectionError("Already connected")
426 if host.startswith("/"):
427 self._sock = self._connect_unix(host)
429 self._sock = self._connect_tcp(host, port)
430 self._rfile = self._sock.makefile("r", encoding='utf-8')
431 self._wfile = self._sock.makefile("w", encoding='utf-8')
438 def disconnect(self):
439 if hasattr(self._rfile, 'close'):
441 if hasattr(self._wfile, 'close'):
443 if isinstance(self._sock, socket.socket):
448 if self._sock is None:
449 raise ConnectionError("Not connected")
450 return self._sock.fileno()
452 def command_list_ok_begin(self):
453 if self._command_list is not None:
454 raise CommandListError("Already in command list")
456 raise IteratingError("Cannot begin command list while iterating")
458 raise PendingCommandError("Cannot begin command list "
459 "with pending commands")
460 self._write_command("command_list_ok_begin")
461 self._command_list = []
463 def command_list_end(self):
464 if self._command_list is None:
465 raise CommandListError("Not in command list")
467 raise IteratingError("Already iterating over a command list")
468 self._write_command("command_list_end")
469 return self._fetch_command_list()
473 return text.replace("\\", "\\\\").replace('"', '\\"')
476 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: