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