1 # Python MPD client library
2 # Copyright (C) 2008-2010 J. Alexander Treuman <jat@spatialrift.net>
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 HELLO_PREFIX = "OK MPD "
26 class MPDError(Exception):
29 class ConnectionError(MPDError):
32 class ProtocolError(MPDError):
35 class CommandError(MPDError):
38 class CommandListError(MPDError):
41 class PendingCommandError(MPDError):
44 class IteratingError(MPDError):
48 class _NotConnected(object):
49 def __getattr__(self, attr):
53 raise ConnectionError("Not connected")
55 class MPDClient(object):
61 "clearerror": self._fetch_nothing,
62 "currentsong": self._fetch_object,
63 "idle": self._fetch_list,
65 "status": self._fetch_object,
66 "stats": self._fetch_object,
67 # Playback Option Commands
68 "consume": self._fetch_nothing,
69 "crossfade": self._fetch_nothing,
70 "random": self._fetch_nothing,
71 "repeat": self._fetch_nothing,
72 "setvol": self._fetch_nothing,
73 "single": self._fetch_nothing,
74 "volume": self._fetch_nothing,
75 # Playback Control Commands
76 "next": self._fetch_nothing,
77 "pause": self._fetch_nothing,
78 "play": self._fetch_nothing,
79 "playid": self._fetch_nothing,
80 "previous": self._fetch_nothing,
81 "seek": self._fetch_nothing,
82 "seekid": self._fetch_nothing,
83 "stop": self._fetch_nothing,
85 "add": self._fetch_nothing,
86 "addid": self._fetch_item,
87 "clear": self._fetch_nothing,
88 "delete": self._fetch_nothing,
89 "deleteid": self._fetch_nothing,
90 "move": self._fetch_nothing,
91 "moveid": self._fetch_nothing,
92 "playlist": self._fetch_playlist,
93 "playlistfind": self._fetch_songs,
94 "playlistid": self._fetch_songs,
95 "playlistinfo": self._fetch_songs,
96 "playlistsearch": self._fetch_songs,
97 "plchanges": self._fetch_songs,
98 "plchangesposid": self._fetch_changes,
99 "shuffle": self._fetch_nothing,
100 "swap": self._fetch_nothing,
101 "swapid": self._fetch_nothing,
102 # Stored Playlist Commands
103 "listplaylist": self._fetch_list,
104 "listplaylistinfo": self._fetch_songs,
105 "listplaylists": self._fetch_playlists,
106 "load": self._fetch_nothing,
107 "playlistadd": self._fetch_nothing,
108 "playlistclear": self._fetch_nothing,
109 "playlistdelete": self._fetch_nothing,
110 "playlistmove": self._fetch_nothing,
111 "rename": self._fetch_nothing,
112 "rm": self._fetch_nothing,
113 "save": self._fetch_nothing,
115 "count": self._fetch_object,
116 "find": self._fetch_songs,
117 "list": self._fetch_list,
118 "listall": self._fetch_database,
119 "listallinfo": self._fetch_database,
120 "lsinfo": self._fetch_database,
121 "search": self._fetch_songs,
122 "update": self._fetch_item,
124 "sticker get": self._fetch_item,
125 "sticker set": self._fetch_nothing,
126 "sticker delete": self._fetch_nothing,
127 "sticker list": self._fetch_list,
128 "sticker find": self._fetch_songs,
129 # Connection Commands
132 "password": self._fetch_nothing,
133 "ping": self._fetch_nothing,
134 # Audio Output Commands
135 "disableoutput": self._fetch_nothing,
136 "enableoutput": self._fetch_nothing,
137 "outputs": self._fetch_outputs,
138 # Reflection Commands
139 "commands": self._fetch_list,
140 "notcommands": self._fetch_list,
141 "tagtypes": self._fetch_list,
142 "urlhandlers": self._fetch_list,
145 def __getattr__(self, attr):
146 if attr.startswith("send_"):
147 command = attr.replace("send_", "", 1)
149 elif attr.startswith("fetch_"):
150 command = attr.replace("fetch_", "", 1)
151 wrapper = self._fetch
154 wrapper = self._execute
155 command = command.replace("_", " ")
156 if command not in self._commands:
157 raise AttributeError("'%s' object has no attribute '%s'" %
158 (self.__class__.__name__, attr))
159 return lambda *args: wrapper(command, args)
161 def _send(self, command, args):
162 if self._command_list is not None:
163 raise CommandListError("Cannot use send_%s in a command list" %
164 command.replace(" ", "_"))
165 self._write_command(command, args)
166 self._pending.append(command)
168 def _fetch(self, command, args=None):
169 if self._command_list is not None:
170 raise CommandListError("Cannot use fetch_%s in a command list" %
171 command.replace(" ", "_"))
173 raise IteratingError("Cannot use fetch_%s while iterating" %
174 command.replace(" ", "_"))
175 if not self._pending:
176 raise PendingCommandError("No pending commands to fetch")
177 if self._pending[0] != command:
178 raise PendingCommandError("'%s' is not the currently "
179 "pending command" % command)
181 retval = self._commands[command]
185 def _execute(self, command, args):
187 raise IteratingError("Cannot execute '%s' while iterating" %
190 raise PendingCommandError("Cannot execute '%s' with "
191 "pending commands" % command)
192 retval = self._commands[command]
193 if self._command_list is not None:
194 if not callable(retval):
195 raise CommandListError("'%s' not allowed in command list" %
197 self._write_command(command, args)
198 self._command_list.append(retval)
200 self._write_command(command, args)
205 def _write_line(self, line):
206 self._wfile.write("%s\n" % line)
209 def _write_command(self, command, args=[]):
212 parts.append('"%s"' % escape(str(arg)))
213 self._write_line(" ".join(parts))
215 def _read_line(self):
216 line = self._rfile.readline()
217 if not line.endswith("\n"):
218 raise ConnectionError("Connection lost while reading line")
219 line = line.rstrip("\n")
220 if line.startswith(ERROR_PREFIX):
221 error = line[len(ERROR_PREFIX):].strip()
222 raise CommandError(error)
223 if self._command_list is not None:
227 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
228 elif line == SUCCESS:
232 def _read_pair(self, separator):
233 line = self._read_line()
236 pair = line.split(separator, 1)
238 raise ProtocolError("Could not parse pair: '%s'" % line)
241 def _read_pairs(self, separator=": "):
242 pair = self._read_pair(separator)
245 pair = self._read_pair(separator)
247 def _read_list(self):
249 for key, value in self._read_pairs():
252 raise ProtocolError("Expected key '%s', got '%s'" %
257 def _read_playlist(self):
258 for key, value in self._read_pairs(":"):
261 def _read_objects(self, delimiters=[]):
263 for key, value in self._read_pairs():
266 if key in delimiters:
270 if not isinstance(obj[key], list):
271 obj[key] = [obj[key], value]
273 obj[key].append(value)
279 def _read_command_list(self):
281 for retval in self._command_list:
284 self._command_list = None
285 self._fetch_nothing()
287 def _iterator_wrapper(self, iterator):
289 for item in iterator:
292 self._iterating = False
294 def _wrap_iterator(self, iterator):
296 return list(iterator)
297 self._iterating = True
298 return self._iterator_wrapper(iterator)
300 def _fetch_nothing(self):
301 line = self._read_line()
303 raise ProtocolError("Got unexpected return value: '%s'" % line)
305 def _fetch_item(self):
306 pairs = list(self._read_pairs())
311 def _fetch_list(self):
312 return self._wrap_iterator(self._read_list())
314 def _fetch_playlist(self):
315 return self._wrap_iterator(self._read_playlist())
317 def _fetch_object(self):
318 objs = list(self._read_objects())
323 def _fetch_objects(self, delimiters):
324 return self._wrap_iterator(self._read_objects(delimiters))
326 def _fetch_songs(self):
327 return self._fetch_objects(["file"])
329 def _fetch_playlists(self):
330 return self._fetch_objects(["playlist"])
332 def _fetch_database(self):
333 return self._fetch_objects(["file", "directory", "playlist"])
335 def _fetch_outputs(self):
336 return self._fetch_objects(["outputid"])
338 def _fetch_changes(self):
339 return self._fetch_objects(["cpos"])
341 def _fetch_command_list(self):
342 return self._wrap_iterator(self._read_command_list())
345 line = self._rfile.readline()
346 if not line.endswith("\n"):
347 raise ConnectionError("Connection lost while reading MPD hello")
348 line = line.rstrip("\n")
349 if not line.startswith(HELLO_PREFIX):
350 raise ProtocolError("Got invalid MPD hello: '%s'" % line)
351 self.mpd_version = line[len(HELLO_PREFIX):].strip()
354 self.mpd_version = None
355 self._iterating = False
357 self._command_list = None
359 self._rfile = _NotConnected()
360 self._wfile = _NotConnected()
362 def _connect_unix(self, path):
363 if not hasattr(socket, "AF_UNIX"):
364 raise ConnectionError("Unix domain sockets not supported "
366 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
370 def _connect_tcp(self, host, port):
372 flags = socket.AI_ADDRCONFIG
373 except AttributeError:
376 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
377 socket.SOCK_STREAM, socket.IPPROTO_TCP,
379 af, socktype, proto, canonname, sa = res
382 sock = socket.socket(af, socktype, proto)
385 except socket.error, err:
391 raise ConnectionError("getaddrinfo returns an empty list")
393 def connect(self, host, port):
394 if self._sock is not None:
395 raise ConnectionError("Already connected")
396 if host.startswith("/"):
397 self._sock = self._connect_unix(host)
399 self._sock = self._connect_tcp(host, port)
400 self._rfile = self._sock.makefile("rb")
401 self._wfile = self._sock.makefile("wb")
408 def disconnect(self):
415 if self._sock is None:
416 raise ConnectionError("Not connected")
417 return self._sock.fileno()
419 def command_list_ok_begin(self):
420 if self._command_list is not None:
421 raise CommandListError("Already in command list")
423 raise IteratingError("Cannot begin command list while iterating")
425 raise PendingCommandError("Cannot begin command list "
426 "with pending commands")
427 self._write_command("command_list_ok_begin")
428 self._command_list = []
430 def command_list_end(self):
431 if self._command_list is None:
432 raise CommandListError("Not in command list")
434 raise IteratingError("Already iterating over a command list")
435 self._write_command("command_list_end")
436 return self._fetch_command_list()
440 return text.replace("\\", "\\\\").replace('"', '\\"')
443 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: