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