]> kaliko git repositories - python-musicpd.git/blob - mpd.py
4ad4804a23a17c1a384af068d8a287601d913ca7
[python-musicpd.git] / mpd.py
1 # python-mpd: Python MPD client library
2 # Copyright (C) 2008-2010  J. Alexander Treuman <jat@spatialrift.net>
3 # Copyright (C)      2012  Kaliko Jack <kaliko@azylum.org>
4 #
5 # python-mpd is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # python-mpd is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with python-mpd.  If not, see <http://www.gnu.org/licenses/>.
17
18 import socket
19
20
21 HELLO_PREFIX = "OK MPD "
22 ERROR_PREFIX = "ACK "
23 SUCCESS = "OK"
24 NEXT = "list_OK"
25
26
27 class MPDError(Exception):
28     pass
29
30 class ConnectionError(MPDError):
31     pass
32
33 class ProtocolError(MPDError):
34     pass
35
36 class CommandError(MPDError):
37     pass
38
39 class CommandListError(MPDError):
40     pass
41
42 class PendingCommandError(MPDError):
43     pass
44
45 class IteratingError(MPDError):
46     pass
47
48
49 class _NotConnected(object):
50     def __getattr__(self, attr):
51         return self._dummy
52
53     def _dummy(*args):
54         raise ConnectionError("Not connected")
55
56 class MPDClient(object):
57     def __init__(self):
58         self.iterate = False
59         self._reset()
60         self._commands = {
61             # Status Commands
62             "clearerror":         self._fetch_nothing,
63             "currentsong":        self._fetch_object,
64             "idle":               self._fetch_list,
65             "noidle":             None,
66             "status":             self._fetch_object,
67             "stats":              self._fetch_object,
68             # Playback Option Commands
69             "consume":            self._fetch_nothing,
70             "crossfade":          self._fetch_nothing,
71             "mixrampdb":          self._fetch_nothing,
72             "mixrampdelay":       self._fetch_nothing,
73             "random":             self._fetch_nothing,
74             "repeat":             self._fetch_nothing,
75             "setvol":             self._fetch_nothing,
76             "single":             self._fetch_nothing,
77             "replay_gain_mode":   self._fetch_nothing,
78             "replay_gain_status": self._fetch_item,
79             "volume":             self._fetch_nothing,
80             # Playback Control Commands
81             "next":               self._fetch_nothing,
82             "pause":              self._fetch_nothing,
83             "play":               self._fetch_nothing,
84             "playid":             self._fetch_nothing,
85             "previous":           self._fetch_nothing,
86             "seek":               self._fetch_nothing,
87             "seekid":             self._fetch_nothing,
88             "seekcur":            self._fetch_nothing,
89             "stop":               self._fetch_nothing,
90             # Playlist Commands
91             "add":                self._fetch_nothing,
92             "addid":              self._fetch_item,
93             "clear":              self._fetch_nothing,
94             "delete":             self._fetch_nothing,
95             "deleteid":           self._fetch_nothing,
96             "move":               self._fetch_nothing,
97             "moveid":             self._fetch_nothing,
98             "playlist":           self._fetch_playlist,
99             "playlistfind":       self._fetch_songs,
100             "playlistid":         self._fetch_songs,
101             "playlistinfo":       self._fetch_songs,
102             "playlistsearch":     self._fetch_songs,
103             "plchanges":          self._fetch_songs,
104             "plchangesposid":     self._fetch_changes,
105             "shuffle":            self._fetch_nothing,
106             "swap":               self._fetch_nothing,
107             "swapid":             self._fetch_nothing,
108             # Stored Playlist Commands
109             "listplaylist":       self._fetch_list,
110             "listplaylistinfo":   self._fetch_songs,
111             "listplaylists":      self._fetch_playlists,
112             "load":               self._fetch_nothing,
113             "playlistadd":        self._fetch_nothing,
114             "playlistclear":      self._fetch_nothing,
115             "playlistdelete":     self._fetch_nothing,
116             "playlistmove":       self._fetch_nothing,
117             "rename":             self._fetch_nothing,
118             "rm":                 self._fetch_nothing,
119             "save":               self._fetch_nothing,
120             # Database Commands
121             "count":              self._fetch_object,
122             "find":               self._fetch_songs,
123             "findadd":            self._fetch_nothing,
124             "list":               self._fetch_list,
125             "listall":            self._fetch_database,
126             "listallinfo":        self._fetch_database,
127             "lsinfo":             self._fetch_database,
128             "search":             self._fetch_songs,
129             "searchadd":          self._fetch_nothing,
130             "searchaddpl":        self._fetch_nothing,
131             "update":             self._fetch_item,
132             "rescan":             self._fetch_item,
133             # Sticker Commands
134             "sticker get":        self._fetch_item,
135             "sticker set":        self._fetch_nothing,
136             "sticker delete":     self._fetch_nothing,
137             "sticker list":       self._fetch_list,
138             "sticker find":       self._fetch_songs,
139             # Connection Commands
140             "close":              None,
141             "kill":               None,
142             "password":           self._fetch_nothing,
143             "ping":               self._fetch_nothing,
144             # Audio Output Commands
145             "disableoutput":      self._fetch_nothing,
146             "enableoutput":       self._fetch_nothing,
147             "outputs":            self._fetch_outputs,
148             # Reflection Commands
149             "commands":           self._fetch_list,
150             "notcommands":        self._fetch_list,
151             "tagtypes":           self._fetch_list,
152             "urlhandlers":        self._fetch_list,
153             "decoders":           self._fetch_plugins,
154             # Client to Client
155             "subscribe":          self._fetch_nothing,
156             "unsubscribe":        self._fetch_nothing,
157             "channels":           self._fetch_list,
158             "readmessages":       self._fetch_messages,
159             "sendmessage":        self._fetch_nothing,
160         }
161
162     def __getattr__(self, attr):
163         if attr.startswith("send_"):
164             command = attr.replace("send_", "", 1)
165             wrapper = self._send
166         elif attr.startswith("fetch_"):
167             command = attr.replace("fetch_", "", 1)
168             wrapper = self._fetch
169         else:
170             command = attr
171             wrapper = self._execute
172         if command not in self._commands:
173             command = command.replace("_", " ")
174             if command not in self._commands:
175                 raise AttributeError("'%s' object has no attribute '%s'" %
176                                      (self.__class__.__name__, attr))
177         return lambda *args: wrapper(command, args)
178
179     def _send(self, command, args):
180         if self._command_list is not None:
181             raise CommandListError("Cannot use send_%s in a command list" %
182                                    command.replace(" ", "_"))
183         self._write_command(command, args)
184         retval = self._commands[command]
185         if retval is not None:
186             self._pending.append(command)
187
188     def _fetch(self, command, args=None):
189         if self._command_list is not None:
190             raise CommandListError("Cannot use fetch_%s in a command list" %
191                                    command.replace(" ", "_"))
192         if self._iterating:
193             raise IteratingError("Cannot use fetch_%s while iterating" %
194                                  command.replace(" ", "_"))
195         if not self._pending:
196             raise PendingCommandError("No pending commands to fetch")
197         if self._pending[0] != command:
198             raise PendingCommandError("'%s' is not the currently "
199                                       "pending command" % command)
200         del self._pending[0]
201         retval = self._commands[command]
202         if callable(retval):
203             return retval()
204         return retval
205
206     def _execute(self, command, args):
207         if self._iterating:
208             raise IteratingError("Cannot execute '%s' while iterating" %
209                                  command)
210         if self._pending:
211             raise PendingCommandError("Cannot execute '%s' with "
212                                       "pending commands" % command)
213         retval = self._commands[command]
214         if self._command_list is not None:
215             if not callable(retval):
216                 raise CommandListError("'%s' not allowed in command list" %
217                                         command)
218             self._write_command(command, args)
219             self._command_list.append(retval)
220         else:
221             self._write_command(command, args)
222             if callable(retval):
223                 return retval()
224             return retval
225
226     def _write_line(self, line):
227         self._wfile.write("%s\n" % line)
228         self._wfile.flush()
229
230     def _write_command(self, command, args=[]):
231         parts = [command]
232         for arg in args:
233             parts.append('"%s"' % escape(str(arg)))
234         self._write_line(" ".join(parts))
235
236     def _read_line(self):
237         line = self._rfile.readline()
238         if not line.endswith("\n"):
239             raise ConnectionError("Connection lost while reading line")
240         line = line.rstrip("\n")
241         if line.startswith(ERROR_PREFIX):
242             error = line[len(ERROR_PREFIX):].strip()
243             raise CommandError(error)
244         if self._command_list is not None:
245             if line == NEXT:
246                 return
247             if line == SUCCESS:
248                 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
249         elif line == SUCCESS:
250             return
251         return line
252
253     def _read_pair(self, separator):
254         line = self._read_line()
255         if line is None:
256             return
257         pair = line.split(separator, 1)
258         if len(pair) < 2:
259             raise ProtocolError("Could not parse pair: '%s'" % line)
260         return pair
261
262     def _read_pairs(self, separator=": "):
263         pair = self._read_pair(separator)
264         while pair:
265             yield pair
266             pair = self._read_pair(separator)
267
268     def _read_list(self):
269         seen = None
270         for key, value in self._read_pairs():
271             if key != seen:
272                 if seen is not None:
273                     raise ProtocolError("Expected key '%s', got '%s'" %
274                                         (seen, key))
275                 seen = key
276             yield value
277
278     def _read_playlist(self):
279         for key, value in self._read_pairs(":"):
280             yield value
281
282     def _read_objects(self, delimiters=[]):
283         obj = {}
284         for key, value in self._read_pairs():
285             key = key.lower()
286             if obj:
287                 if key in delimiters:
288                     yield obj
289                     obj = {}
290                 elif key in obj:
291                     if not isinstance(obj[key], list):
292                         obj[key] = [obj[key], value]
293                     else:
294                         obj[key].append(value)
295                     continue
296             obj[key] = value
297         if obj:
298             yield obj
299
300     def _read_command_list(self):
301         try:
302             for retval in self._command_list:
303                 yield retval()
304         finally:
305             self._command_list = None
306         self._fetch_nothing()
307
308     def _iterator_wrapper(self, iterator):
309         try:
310             for item in iterator:
311                 yield item
312         finally:
313             self._iterating = False
314
315     def _wrap_iterator(self, iterator):
316         if not self.iterate:
317             return list(iterator)
318         self._iterating = True
319         return self._iterator_wrapper(iterator)
320
321     def _fetch_nothing(self):
322         line = self._read_line()
323         if line is not None:
324             raise ProtocolError("Got unexpected return value: '%s'" % line)
325
326     def _fetch_item(self):
327         pairs = list(self._read_pairs())
328         if len(pairs) != 1:
329             return
330         return pairs[0][1]
331
332     def _fetch_list(self):
333         return self._wrap_iterator(self._read_list())
334
335     def _fetch_playlist(self):
336         return self._wrap_iterator(self._read_playlist())
337
338     def _fetch_object(self):
339         objs = list(self._read_objects())
340         if not objs:
341             return {}
342         return objs[0]
343
344     def _fetch_objects(self, delimiters):
345         return self._wrap_iterator(self._read_objects(delimiters))
346
347     def _fetch_changes(self):
348         return self._fetch_objects(["cpos"])
349
350     def _fetch_songs(self):
351         return self._fetch_objects(["file"])
352
353     def _fetch_playlists(self):
354         return self._fetch_objects(["playlist"])
355
356     def _fetch_database(self):
357         return self._fetch_objects(["file", "directory", "playlist"])
358
359     def _fetch_outputs(self):
360         return self._fetch_objects(["outputid"])
361
362     def _fetch_plugins(self):
363         return self._fetch_objects(["plugin"])
364
365     def _fetch_messages(self):
366         return self._fetch_objects(["channel"])
367
368     def _fetch_command_list(self):
369         return self._wrap_iterator(self._read_command_list())
370
371     def _hello(self):
372         line = self._rfile.readline()
373         if not line.endswith("\n"):
374             raise ConnectionError("Connection lost while reading MPD hello")
375         line = line.rstrip("\n")
376         if not line.startswith(HELLO_PREFIX):
377             raise ProtocolError("Got invalid MPD hello: '%s'" % line)
378         self.mpd_version = line[len(HELLO_PREFIX):].strip()
379
380     def _reset(self):
381         self.mpd_version = None
382         self._iterating = False
383         self._pending = []
384         self._command_list = None
385         self._sock = None
386         self._rfile = _NotConnected()
387         self._wfile = _NotConnected()
388
389     def _connect_unix(self, path):
390         if not hasattr(socket, "AF_UNIX"):
391             raise ConnectionError("Unix domain sockets not supported "
392                                   "on this platform")
393         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
394         sock.connect(path)
395         return sock
396
397     def _connect_tcp(self, host, port):
398         try:
399             flags = socket.AI_ADDRCONFIG
400         except AttributeError:
401             flags = 0
402         err = None
403         for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
404                                       socket.SOCK_STREAM, socket.IPPROTO_TCP,
405                                       flags):
406             af, socktype, proto, canonname, sa = res
407             sock = None
408             try:
409                 sock = socket.socket(af, socktype, proto)
410                 sock.connect(sa)
411                 return sock
412             except socket.error as socket_err:
413                 err = socket_err
414                 if sock is not None:
415                     sock.close()
416         if err is not None:
417             raise err
418         else:
419             raise ConnectionError("getaddrinfo returns an empty list")
420
421     def connect(self, host, port):
422         if self._sock is not None:
423             raise ConnectionError("Already connected")
424         if host.startswith("/"):
425             self._sock = self._connect_unix(host)
426         else:
427             self._sock = self._connect_tcp(host, port)
428         self._rfile = self._sock.makefile("r")
429         self._wfile = self._sock.makefile("w")
430         try:
431             self._hello()
432         except:
433             self.disconnect()
434             raise
435
436     def disconnect(self):
437         self._rfile.close()
438         self._wfile.close()
439         self._sock.close()
440         self._reset()
441
442     def fileno(self):
443         if self._sock is None:
444             raise ConnectionError("Not connected")
445         return self._sock.fileno()
446
447     def command_list_ok_begin(self):
448         if self._command_list is not None:
449             raise CommandListError("Already in command list")
450         if self._iterating:
451             raise IteratingError("Cannot begin command list while iterating")
452         if self._pending:
453             raise PendingCommandError("Cannot begin command list "
454                                       "with pending commands")
455         self._write_command("command_list_ok_begin")
456         self._command_list = []
457
458     def command_list_end(self):
459         if self._command_list is None:
460             raise CommandListError("Not in command list")
461         if self._iterating:
462             raise IteratingError("Already iterating over a command list")
463         self._write_command("command_list_end")
464         return self._fetch_command_list()
465
466
467 def escape(text):
468     return text.replace("\\", "\\\\").replace('"', '\\"')
469
470
471 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: