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