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