]> kaliko git repositories - python-musicpd.git/blob - mpd.py
mpd.py: adding support for spaces in command names
[python-musicpd.git] / mpd.py
1 # Python MPD client library
2 # Copyright (C) 2008-2010  J. Alexander Treuman <jat@spatialrift.net>
3 #
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.
8 #
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.
13 #
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/>.
16
17 import socket
18
19
20 HELLO_PREFIX = "OK MPD "
21 ERROR_PREFIX = "ACK "
22 SUCCESS = "OK"
23 NEXT = "list_OK"
24
25
26 class MPDError(Exception):
27     pass
28
29 class ConnectionError(MPDError):
30     pass
31
32 class ProtocolError(MPDError):
33     pass
34
35 class CommandError(MPDError):
36     pass
37
38 class CommandListError(MPDError):
39     pass
40
41 class PendingCommandError(MPDError):
42     pass
43
44 class IteratingError(MPDError):
45     pass
46
47
48 class _NotConnected(object):
49     def __getattr__(self, attr):
50         return self._dummy
51
52     def _dummy(*args):
53         raise ConnectionError("Not connected")
54
55 class MPDClient(object):
56     def __init__(self):
57         self.iterate = False
58         self._reset()
59         self._commands = {
60             # Status Commands
61             "clearerror":       self._fetch_nothing,
62             "currentsong":      self._fetch_object,
63             "idle":             self._fetch_list,
64             "noidle":           None,
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,
84             # Playlist Commands
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,
114             # Database Commands
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,
123             # Connection Commands
124             "close":            None,
125             "kill":             None,
126             "password":         self._fetch_nothing,
127             "ping":             self._fetch_nothing,
128             # Audio Output Commands
129             "disableoutput":    self._fetch_nothing,
130             "enableoutput":     self._fetch_nothing,
131             "outputs":          self._fetch_outputs,
132             # Reflection Commands
133             "commands":         self._fetch_list,
134             "notcommands":      self._fetch_list,
135             "tagtypes":         self._fetch_list,
136             "urlhandlers":      self._fetch_list,
137         }
138
139     def __getattr__(self, attr):
140         if attr.startswith("send_"):
141             command = attr.replace("send_", "", 1)
142             wrapper = self._send
143         elif attr.startswith("fetch_"):
144             command = attr.replace("fetch_", "", 1)
145             wrapper = self._fetch
146         else:
147             command = attr
148             wrapper = self._execute
149         command = command.replace("_", " ")
150         if command not in self._commands:
151             raise AttributeError("'%s' object has no attribute '%s'" %
152                                  (self.__class__.__name__, attr))
153         return lambda *args: wrapper(command, args)
154
155     def _send(self, command, args):
156         if self._command_list is not None:
157             raise CommandListError("Cannot use send_%s in a command list" %
158                                    command.replace(" ", "_"))
159         self._write_command(command, args)
160         self._pending.append(command)
161
162     def _fetch(self, command, args=None):
163         if self._command_list is not None:
164             raise CommandListError("Cannot use fetch_%s in a command list" %
165                                    command.replace(" ", "_"))
166         if self._iterating:
167             raise IteratingError("Cannot use fetch_%s while iterating" %
168                                  command.replace(" ", "_"))
169         if not self._pending:
170             raise PendingCommandError("No pending commands to fetch")
171         if self._pending[0] != command:
172             raise PendingCommandError("'%s' is not the currently "
173                                       "pending command" % command)
174         del self._pending[0]
175         retval = self._commands[command]
176         if callable(retval):
177             return retval()
178
179     def _execute(self, command, args):
180         if self._iterating:
181             raise IteratingError("Cannot execute '%s' while iterating" %
182                                  command)
183         if self._pending:
184             raise PendingCommandError("Cannot execute '%s' with "
185                                       "pending commands" % command)
186         retval = self._commands[command]
187         if self._command_list is not None:
188             if not callable(retval):
189                 raise CommandListError("'%s' not allowed in command list" %
190                                         command)
191             self._write_command(command, args)
192             self._command_list.append(retval)
193         else:
194             self._write_command(command, args)
195             if callable(retval):
196                 return retval()
197             return retval
198
199     def _write_line(self, line):
200         self._wfile.write("%s\n" % line)
201         self._wfile.flush()
202
203     def _write_command(self, command, args=[]):
204         parts = [command]
205         for arg in args:
206             parts.append('"%s"' % escape(str(arg)))
207         self._write_line(" ".join(parts))
208
209     def _read_line(self):
210         line = self._rfile.readline()
211         if not line.endswith("\n"):
212             raise ConnectionError("Connection lost while reading line")
213         line = line.rstrip("\n")
214         if line.startswith(ERROR_PREFIX):
215             error = line[len(ERROR_PREFIX):].strip()
216             raise CommandError(error)
217         if self._command_list is not None:
218             if line == NEXT:
219                 return
220             if line == SUCCESS:
221                 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
222         elif line == SUCCESS:
223             return
224         return line
225
226     def _read_pair(self, separator):
227         line = self._read_line()
228         if line is None:
229             return
230         pair = line.split(separator, 1)
231         if len(pair) < 2:
232             raise ProtocolError("Could not parse pair: '%s'" % line)
233         return pair
234
235     def _read_pairs(self, separator=": "):
236         pair = self._read_pair(separator)
237         while pair:
238             yield pair
239             pair = self._read_pair(separator)
240
241     def _read_list(self):
242         seen = None
243         for key, value in self._read_pairs():
244             if key != seen:
245                 if seen is not None:
246                     raise ProtocolError("Expected key '%s', got '%s'" %
247                                         (seen, key))
248                 seen = key
249             yield value
250
251     def _read_playlist(self):
252         for key, value in self._read_pairs(":"):
253             yield value
254
255     def _read_objects(self, delimiters=[]):
256         obj = {}
257         for key, value in self._read_pairs():
258             key = key.lower()
259             if obj:
260                 if key in delimiters:
261                     yield obj
262                     obj = {}
263                 elif key in obj:
264                     if not isinstance(obj[key], list):
265                         obj[key] = [obj[key], value]
266                     else:
267                         obj[key].append(value)
268                     continue
269             obj[key] = value
270         if obj:
271             yield obj
272
273     def _read_command_list(self):
274         try:
275             for retval in self._command_list:
276                 yield retval()
277         finally:
278             self._command_list = None
279         self._fetch_nothing()
280
281     def _iterator_wrapper(self, iterator):
282         try:
283             for item in iterator:
284                 yield item
285         finally:
286             self._iterating = False
287
288     def _wrap_iterator(self, iterator):
289         if not self.iterate:
290             return list(iterator)
291         self._iterating = True
292         return self._iterator_wrapper(iterator)
293
294     def _fetch_nothing(self):
295         line = self._read_line()
296         if line is not None:
297             raise ProtocolError("Got unexpected return value: '%s'" % line)
298
299     def _fetch_item(self):
300         pairs = list(self._read_pairs())
301         if len(pairs) != 1:
302             return
303         return pairs[0][1]
304
305     def _fetch_list(self):
306         return self._wrap_iterator(self._read_list())
307
308     def _fetch_playlist(self):
309         return self._wrap_iterator(self._read_playlist())
310
311     def _fetch_object(self):
312         objs = list(self._read_objects())
313         if not objs:
314             return {}
315         return objs[0]
316
317     def _fetch_objects(self, delimiters):
318         return self._wrap_iterator(self._read_objects(delimiters))
319
320     def _fetch_songs(self):
321         return self._fetch_objects(["file"])
322
323     def _fetch_playlists(self):
324         return self._fetch_objects(["playlist"])
325
326     def _fetch_database(self):
327         return self._fetch_objects(["file", "directory", "playlist"])
328
329     def _fetch_outputs(self):
330         return self._fetch_objects(["outputid"])
331
332     def _fetch_changes(self):
333         return self._fetch_objects(["cpos"])
334
335     def _fetch_command_list(self):
336         return self._wrap_iterator(self._read_command_list())
337
338     def _hello(self):
339         line = self._rfile.readline()
340         if not line.endswith("\n"):
341             raise ConnectionError("Connection lost while reading MPD hello")
342         line = line.rstrip("\n")
343         if not line.startswith(HELLO_PREFIX):
344             raise ProtocolError("Got invalid MPD hello: '%s'" % line)
345         self.mpd_version = line[len(HELLO_PREFIX):].strip()
346
347     def _reset(self):
348         self.mpd_version = None
349         self._iterating = False
350         self._pending = []
351         self._command_list = None
352         self._sock = None
353         self._rfile = _NotConnected()
354         self._wfile = _NotConnected()
355
356     def _connect_unix(self, path):
357         if not hasattr(socket, "AF_UNIX"):
358             raise ConnectionError("Unix domain sockets not supported "
359                                   "on this platform")
360         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
361         sock.connect(path)
362         return sock
363
364     def _connect_tcp(self, host, port):
365         try:
366             flags = socket.AI_ADDRCONFIG
367         except AttributeError:
368             flags = 0
369         err = None
370         for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
371                                       socket.SOCK_STREAM, socket.IPPROTO_TCP,
372                                       flags):
373             af, socktype, proto, canonname, sa = res
374             sock = None
375             try:
376                 sock = socket.socket(af, socktype, proto)
377                 sock.connect(sa)
378                 return sock
379             except socket.error, err:
380                 if sock is not None:
381                     sock.close()
382         if err is not None:
383             raise err
384         else:
385             raise ConnectionError("getaddrinfo returns an empty list")
386
387     def connect(self, host, port):
388         if self._sock is not None:
389             raise ConnectionError("Already connected")
390         if host.startswith("/"):
391             self._sock = self._connect_unix(host)
392         else:
393             self._sock = self._connect_tcp(host, port)
394         self._rfile = self._sock.makefile("rb")
395         self._wfile = self._sock.makefile("wb")
396         try:
397             self._hello()
398         except:
399             self.disconnect()
400             raise
401
402     def disconnect(self):
403         self._rfile.close()
404         self._wfile.close()
405         self._sock.close()
406         self._reset()
407
408     def fileno(self):
409         if self._sock is None:
410             raise ConnectionError("Not connected")
411         return self._sock.fileno()
412
413     def command_list_ok_begin(self):
414         if self._command_list is not None:
415             raise CommandListError("Already in command list")
416         if self._iterating:
417             raise IteratingError("Cannot begin command list while iterating")
418         if self._pending:
419             raise PendingCommandError("Cannot begin command list "
420                                       "with pending commands")
421         self._write_command("command_list_ok_begin")
422         self._command_list = []
423
424     def command_list_end(self):
425         if self._command_list is None:
426             raise CommandListError("Not in command list")
427         if self._iterating:
428             raise IteratingError("Already iterating over a command list")
429         self._write_command("command_list_end")
430         return self._fetch_command_list()
431
432
433 def escape(text):
434     return text.replace("\\", "\\\\").replace('"', '\\"')
435
436
437 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: