]> kaliko git repositories - python-musicpd.git/blob - mpd.py
adding decoders command
[python-musicpd.git] / mpd.py
1 # python-mpd: Python MPD client library
2 # Copyright (C) 2008-2010  J. Alexander Treuman <jat@spatialrift.net>
3 #
4 # python-mpd is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Lesser 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 # python-mpd 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 Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with python-mpd.  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             # Sticker Commands
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
130             "close":            None,
131             "kill":             None,
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,
143             "decoders":         self._fetch_plugins,
144         }
145
146     def __getattr__(self, attr):
147         if attr.startswith("send_"):
148             command = attr.replace("send_", "", 1)
149             wrapper = self._send
150         elif attr.startswith("fetch_"):
151             command = attr.replace("fetch_", "", 1)
152             wrapper = self._fetch
153         else:
154             command = attr
155             wrapper = self._execute
156         command = command.replace("_", " ")
157         if command not in self._commands:
158             raise AttributeError("'%s' object has no attribute '%s'" %
159                                  (self.__class__.__name__, attr))
160         return lambda *args: wrapper(command, args)
161
162     def _send(self, command, args):
163         if self._command_list is not None:
164             raise CommandListError("Cannot use send_%s in a command list" %
165                                    command.replace(" ", "_"))
166         self._write_command(command, args)
167         self._pending.append(command)
168
169     def _fetch(self, command, args=None):
170         if self._command_list is not None:
171             raise CommandListError("Cannot use fetch_%s in a command list" %
172                                    command.replace(" ", "_"))
173         if self._iterating:
174             raise IteratingError("Cannot use fetch_%s while iterating" %
175                                  command.replace(" ", "_"))
176         if not self._pending:
177             raise PendingCommandError("No pending commands to fetch")
178         if self._pending[0] != command:
179             raise PendingCommandError("'%s' is not the currently "
180                                       "pending command" % command)
181         del self._pending[0]
182         retval = self._commands[command]
183         if callable(retval):
184             return retval()
185
186     def _execute(self, command, args):
187         if self._iterating:
188             raise IteratingError("Cannot execute '%s' while iterating" %
189                                  command)
190         if self._pending:
191             raise PendingCommandError("Cannot execute '%s' with "
192                                       "pending commands" % command)
193         retval = self._commands[command]
194         if self._command_list is not None:
195             if not callable(retval):
196                 raise CommandListError("'%s' not allowed in command list" %
197                                         command)
198             self._write_command(command, args)
199             self._command_list.append(retval)
200         else:
201             self._write_command(command, args)
202             if callable(retval):
203                 return retval()
204             return retval
205
206     def _write_line(self, line):
207         self._wfile.write("%s\n" % line)
208         self._wfile.flush()
209
210     def _write_command(self, command, args=[]):
211         parts = [command]
212         for arg in args:
213             parts.append('"%s"' % escape(str(arg)))
214         self._write_line(" ".join(parts))
215
216     def _read_line(self):
217         line = self._rfile.readline()
218         if not line.endswith("\n"):
219             raise ConnectionError("Connection lost while reading line")
220         line = line.rstrip("\n")
221         if line.startswith(ERROR_PREFIX):
222             error = line[len(ERROR_PREFIX):].strip()
223             raise CommandError(error)
224         if self._command_list is not None:
225             if line == NEXT:
226                 return
227             if line == SUCCESS:
228                 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
229         elif line == SUCCESS:
230             return
231         return line
232
233     def _read_pair(self, separator):
234         line = self._read_line()
235         if line is None:
236             return
237         pair = line.split(separator, 1)
238         if len(pair) < 2:
239             raise ProtocolError("Could not parse pair: '%s'" % line)
240         return pair
241
242     def _read_pairs(self, separator=": "):
243         pair = self._read_pair(separator)
244         while pair:
245             yield pair
246             pair = self._read_pair(separator)
247
248     def _read_list(self):
249         seen = None
250         for key, value in self._read_pairs():
251             if key != seen:
252                 if seen is not None:
253                     raise ProtocolError("Expected key '%s', got '%s'" %
254                                         (seen, key))
255                 seen = key
256             yield value
257
258     def _read_playlist(self):
259         for key, value in self._read_pairs(":"):
260             yield value
261
262     def _read_objects(self, delimiters=[]):
263         obj = {}
264         for key, value in self._read_pairs():
265             key = key.lower()
266             if obj:
267                 if key in delimiters:
268                     yield obj
269                     obj = {}
270                 elif key in obj:
271                     if not isinstance(obj[key], list):
272                         obj[key] = [obj[key], value]
273                     else:
274                         obj[key].append(value)
275                     continue
276             obj[key] = value
277         if obj:
278             yield obj
279
280     def _read_command_list(self):
281         try:
282             for retval in self._command_list:
283                 yield retval()
284         finally:
285             self._command_list = None
286         self._fetch_nothing()
287
288     def _iterator_wrapper(self, iterator):
289         try:
290             for item in iterator:
291                 yield item
292         finally:
293             self._iterating = False
294
295     def _wrap_iterator(self, iterator):
296         if not self.iterate:
297             return list(iterator)
298         self._iterating = True
299         return self._iterator_wrapper(iterator)
300
301     def _fetch_nothing(self):
302         line = self._read_line()
303         if line is not None:
304             raise ProtocolError("Got unexpected return value: '%s'" % line)
305
306     def _fetch_item(self):
307         pairs = list(self._read_pairs())
308         if len(pairs) != 1:
309             return
310         return pairs[0][1]
311
312     def _fetch_list(self):
313         return self._wrap_iterator(self._read_list())
314
315     def _fetch_playlist(self):
316         return self._wrap_iterator(self._read_playlist())
317
318     def _fetch_object(self):
319         objs = list(self._read_objects())
320         if not objs:
321             return {}
322         return objs[0]
323
324     def _fetch_objects(self, delimiters):
325         return self._wrap_iterator(self._read_objects(delimiters))
326
327     def _fetch_changes(self):
328         return self._fetch_objects(["cpos"])
329
330     def _fetch_songs(self):
331         return self._fetch_objects(["file"])
332
333     def _fetch_playlists(self):
334         return self._fetch_objects(["playlist"])
335
336     def _fetch_database(self):
337         return self._fetch_objects(["file", "directory", "playlist"])
338
339     def _fetch_outputs(self):
340         return self._fetch_objects(["outputid"])
341
342     def _fetch_plugins(self):
343         return self._fetch_objects(["plugin"])
344
345     def _fetch_command_list(self):
346         return self._wrap_iterator(self._read_command_list())
347
348     def _hello(self):
349         line = self._rfile.readline()
350         if not line.endswith("\n"):
351             raise ConnectionError("Connection lost while reading MPD hello")
352         line = line.rstrip("\n")
353         if not line.startswith(HELLO_PREFIX):
354             raise ProtocolError("Got invalid MPD hello: '%s'" % line)
355         self.mpd_version = line[len(HELLO_PREFIX):].strip()
356
357     def _reset(self):
358         self.mpd_version = None
359         self._iterating = False
360         self._pending = []
361         self._command_list = None
362         self._sock = None
363         self._rfile = _NotConnected()
364         self._wfile = _NotConnected()
365
366     def _connect_unix(self, path):
367         if not hasattr(socket, "AF_UNIX"):
368             raise ConnectionError("Unix domain sockets not supported "
369                                   "on this platform")
370         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
371         sock.connect(path)
372         return sock
373
374     def _connect_tcp(self, host, port):
375         try:
376             flags = socket.AI_ADDRCONFIG
377         except AttributeError:
378             flags = 0
379         err = None
380         for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
381                                       socket.SOCK_STREAM, socket.IPPROTO_TCP,
382                                       flags):
383             af, socktype, proto, canonname, sa = res
384             sock = None
385             try:
386                 sock = socket.socket(af, socktype, proto)
387                 sock.connect(sa)
388                 return sock
389             except socket.error, err:
390                 if sock is not None:
391                     sock.close()
392         if err is not None:
393             raise err
394         else:
395             raise ConnectionError("getaddrinfo returns an empty list")
396
397     def connect(self, host, port):
398         if self._sock is not None:
399             raise ConnectionError("Already connected")
400         if host.startswith("/"):
401             self._sock = self._connect_unix(host)
402         else:
403             self._sock = self._connect_tcp(host, port)
404         self._rfile = self._sock.makefile("rb")
405         self._wfile = self._sock.makefile("wb")
406         try:
407             self._hello()
408         except:
409             self.disconnect()
410             raise
411
412     def disconnect(self):
413         self._rfile.close()
414         self._wfile.close()
415         self._sock.close()
416         self._reset()
417
418     def fileno(self):
419         if self._sock is None:
420             raise ConnectionError("Not connected")
421         return self._sock.fileno()
422
423     def command_list_ok_begin(self):
424         if self._command_list is not None:
425             raise CommandListError("Already in command list")
426         if self._iterating:
427             raise IteratingError("Cannot begin command list while iterating")
428         if self._pending:
429             raise PendingCommandError("Cannot begin command list "
430                                       "with pending commands")
431         self._write_command("command_list_ok_begin")
432         self._command_list = []
433
434     def command_list_end(self):
435         if self._command_list is None:
436             raise CommandListError("Not in command list")
437         if self._iterating:
438             raise IteratingError("Already iterating over a command list")
439         self._write_command("command_list_end")
440         return self._fetch_command_list()
441
442
443 def escape(text):
444     return text.replace("\\", "\\\\").replace('"', '\\"')
445
446
447 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: