]> kaliko git repositories - python-musicpd.git/blob - mpd.py
7f610759d6cb516203511068da869ca2066a1cf0
[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             # 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         }
144
145     def __getattr__(self, attr):
146         if attr.startswith("send_"):
147             command = attr.replace("send_", "", 1)
148             wrapper = self._send
149         elif attr.startswith("fetch_"):
150             command = attr.replace("fetch_", "", 1)
151             wrapper = self._fetch
152         else:
153             command = attr
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)
160
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)
167
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(" ", "_"))
172         if self._iterating:
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)
180         del self._pending[0]
181         retval = self._commands[command]
182         if callable(retval):
183             return retval()
184
185     def _execute(self, command, args):
186         if self._iterating:
187             raise IteratingError("Cannot execute '%s' while iterating" %
188                                  command)
189         if self._pending:
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" %
196                                         command)
197             self._write_command(command, args)
198             self._command_list.append(retval)
199         else:
200             self._write_command(command, args)
201             if callable(retval):
202                 return retval()
203             return retval
204
205     def _write_line(self, line):
206         self._wfile.write("%s\n" % line)
207         self._wfile.flush()
208
209     def _write_command(self, command, args=[]):
210         parts = [command]
211         for arg in args:
212             parts.append('"%s"' % escape(str(arg)))
213         self._write_line(" ".join(parts))
214
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:
224             if line == NEXT:
225                 return
226             if line == SUCCESS:
227                 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
228         elif line == SUCCESS:
229             return
230         return line
231
232     def _read_pair(self, separator):
233         line = self._read_line()
234         if line is None:
235             return
236         pair = line.split(separator, 1)
237         if len(pair) < 2:
238             raise ProtocolError("Could not parse pair: '%s'" % line)
239         return pair
240
241     def _read_pairs(self, separator=": "):
242         pair = self._read_pair(separator)
243         while pair:
244             yield pair
245             pair = self._read_pair(separator)
246
247     def _read_list(self):
248         seen = None
249         for key, value in self._read_pairs():
250             if key != seen:
251                 if seen is not None:
252                     raise ProtocolError("Expected key '%s', got '%s'" %
253                                         (seen, key))
254                 seen = key
255             yield value
256
257     def _read_playlist(self):
258         for key, value in self._read_pairs(":"):
259             yield value
260
261     def _read_objects(self, delimiters=[]):
262         obj = {}
263         for key, value in self._read_pairs():
264             key = key.lower()
265             if obj:
266                 if key in delimiters:
267                     yield obj
268                     obj = {}
269                 elif key in obj:
270                     if not isinstance(obj[key], list):
271                         obj[key] = [obj[key], value]
272                     else:
273                         obj[key].append(value)
274                     continue
275             obj[key] = value
276         if obj:
277             yield obj
278
279     def _read_command_list(self):
280         try:
281             for retval in self._command_list:
282                 yield retval()
283         finally:
284             self._command_list = None
285         self._fetch_nothing()
286
287     def _iterator_wrapper(self, iterator):
288         try:
289             for item in iterator:
290                 yield item
291         finally:
292             self._iterating = False
293
294     def _wrap_iterator(self, iterator):
295         if not self.iterate:
296             return list(iterator)
297         self._iterating = True
298         return self._iterator_wrapper(iterator)
299
300     def _fetch_nothing(self):
301         line = self._read_line()
302         if line is not None:
303             raise ProtocolError("Got unexpected return value: '%s'" % line)
304
305     def _fetch_item(self):
306         pairs = list(self._read_pairs())
307         if len(pairs) != 1:
308             return
309         return pairs[0][1]
310
311     def _fetch_list(self):
312         return self._wrap_iterator(self._read_list())
313
314     def _fetch_playlist(self):
315         return self._wrap_iterator(self._read_playlist())
316
317     def _fetch_object(self):
318         objs = list(self._read_objects())
319         if not objs:
320             return {}
321         return objs[0]
322
323     def _fetch_objects(self, delimiters):
324         return self._wrap_iterator(self._read_objects(delimiters))
325
326     def _fetch_songs(self):
327         return self._fetch_objects(["file"])
328
329     def _fetch_playlists(self):
330         return self._fetch_objects(["playlist"])
331
332     def _fetch_database(self):
333         return self._fetch_objects(["file", "directory", "playlist"])
334
335     def _fetch_outputs(self):
336         return self._fetch_objects(["outputid"])
337
338     def _fetch_changes(self):
339         return self._fetch_objects(["cpos"])
340
341     def _fetch_command_list(self):
342         return self._wrap_iterator(self._read_command_list())
343
344     def _hello(self):
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()
352
353     def _reset(self):
354         self.mpd_version = None
355         self._iterating = False
356         self._pending = []
357         self._command_list = None
358         self._sock = None
359         self._rfile = _NotConnected()
360         self._wfile = _NotConnected()
361
362     def _connect_unix(self, path):
363         if not hasattr(socket, "AF_UNIX"):
364             raise ConnectionError("Unix domain sockets not supported "
365                                   "on this platform")
366         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
367         sock.connect(path)
368         return sock
369
370     def _connect_tcp(self, host, port):
371         try:
372             flags = socket.AI_ADDRCONFIG
373         except AttributeError:
374             flags = 0
375         err = None
376         for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
377                                       socket.SOCK_STREAM, socket.IPPROTO_TCP,
378                                       flags):
379             af, socktype, proto, canonname, sa = res
380             sock = None
381             try:
382                 sock = socket.socket(af, socktype, proto)
383                 sock.connect(sa)
384                 return sock
385             except socket.error, err:
386                 if sock is not None:
387                     sock.close()
388         if err is not None:
389             raise err
390         else:
391             raise ConnectionError("getaddrinfo returns an empty list")
392
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)
398         else:
399             self._sock = self._connect_tcp(host, port)
400         self._rfile = self._sock.makefile("rb")
401         self._wfile = self._sock.makefile("wb")
402         try:
403             self._hello()
404         except:
405             self.disconnect()
406             raise
407
408     def disconnect(self):
409         self._rfile.close()
410         self._wfile.close()
411         self._sock.close()
412         self._reset()
413
414     def fileno(self):
415         if self._sock is None:
416             raise ConnectionError("Not connected")
417         return self._sock.fileno()
418
419     def command_list_ok_begin(self):
420         if self._command_list is not None:
421             raise CommandListError("Already in command list")
422         if self._iterating:
423             raise IteratingError("Cannot begin command list while iterating")
424         if self._pending:
425             raise PendingCommandError("Cannot begin command list "
426                                       "with pending commands")
427         self._write_command("command_list_ok_begin")
428         self._command_list = []
429
430     def command_list_end(self):
431         if self._command_list is None:
432             raise CommandListError("Not in command list")
433         if self._iterating:
434             raise IteratingError("Already iterating over a command list")
435         self._write_command("command_list_end")
436         return self._fetch_command_list()
437
438
439 def escape(text):
440     return text.replace("\\", "\\\\").replace('"', '\\"')
441
442
443 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: