]> kaliko git repositories - python-musicpd.git/blob - musicpd.py
Avoid potential dangerous default value [] as argument
[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 # 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.0'
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             # Sticker Commands
163             "sticker get":        self._fetch_item,
164             "sticker set":        self._fetch_nothing,
165             "sticker delete":     self._fetch_nothing,
166             "sticker list":       self._fetch_list,
167             "sticker find":       self._fetch_songs,
168             # Connection Commands
169             "close":              None,
170             "kill":               None,
171             "password":           self._fetch_nothing,
172             "ping":               self._fetch_nothing,
173             # Audio Output Commands
174             "disableoutput":      self._fetch_nothing,
175             "enableoutput":       self._fetch_nothing,
176             "toggleoutput":       self._fetch_nothing,
177             "outputs":            self._fetch_outputs,
178             # Reflection Commands
179             "commands":           self._fetch_list,
180             "notcommands":        self._fetch_list,
181             "tagtypes":           self._fetch_list,
182             "urlhandlers":        self._fetch_list,
183             "decoders":           self._fetch_plugins,
184             # Client to Client
185             "subscribe":          self._fetch_nothing,
186             "unsubscribe":        self._fetch_nothing,
187             "channels":           self._fetch_list,
188             "readmessages":       self._fetch_messages,
189             "sendmessage":        self._fetch_nothing,
190         }
191
192     def __getattr__(self, attr):
193         if attr.startswith("send_"):
194             command = attr.replace("send_", "", 1)
195             wrapper = self._send
196         elif attr.startswith("fetch_"):
197             command = attr.replace("fetch_", "", 1)
198             wrapper = self._fetch
199         else:
200             command = attr
201             wrapper = self._execute
202         if command not in self._commands:
203             command = command.replace("_", " ")
204             if command not in self._commands:
205                 raise AttributeError("'%s' object has no attribute '%s'" %
206                                      (self.__class__.__name__, attr))
207         return lambda *args: wrapper(command, args)
208
209     def _send(self, command, args):
210         if self._command_list is not None:
211             raise CommandListError("Cannot use send_%s in a command list" %
212                                    command.replace(" ", "_"))
213         self._write_command(command, args)
214         retval = self._commands[command]
215         if retval is not None:
216             self._pending.append(command)
217
218     def _fetch(self, command, args=None):
219         if self._command_list is not None:
220             raise CommandListError("Cannot use fetch_%s in a command list" %
221                                    command.replace(" ", "_"))
222         if self._iterating:
223             raise IteratingError("Cannot use fetch_%s while iterating" %
224                                  command.replace(" ", "_"))
225         if not self._pending:
226             raise PendingCommandError("No pending commands to fetch")
227         if self._pending[0] != command:
228             raise PendingCommandError("'%s' is not the currently "
229                                       "pending command" % command)
230         del self._pending[0]
231         retval = self._commands[command]
232         if callable(retval):
233             return retval()
234         return retval
235
236     def _execute(self, command, args):
237         if self._iterating:
238             raise IteratingError("Cannot execute '%s' while iterating" %
239                                  command)
240         if self._pending:
241             raise PendingCommandError("Cannot execute '%s' with "
242                                       "pending commands" % command)
243         retval = self._commands[command]
244         if self._command_list is not None:
245             if not callable(retval):
246                 raise CommandListError("'%s' not allowed in command list" %
247                                         command)
248             self._write_command(command, args)
249             self._command_list.append(retval)
250         else:
251             self._write_command(command, args)
252             if callable(retval):
253                 return retval()
254             return retval
255
256     def _write_line(self, line):
257         self._wfile.write("%s\n" % line)
258         self._wfile.flush()
259
260     def _write_command(self, command, args=None):
261         if args is None:
262             args = []
263         parts = [command]
264         for arg in args:
265             if isinstance(arg, tuple):
266                 parts.append('{0!s}'.format(Range(arg)))
267             else:
268                 parts.append('"%s"' % escape(str(arg)))
269         self._write_line(" ".join(parts))
270
271     def _read_line(self):
272         line = self._rfile.readline()
273         if not line.endswith("\n"):
274             self.disconnect()
275             raise ConnectionError("Connection lost while reading line")
276         line = line.rstrip("\n")
277         if line.startswith(ERROR_PREFIX):
278             error = line[len(ERROR_PREFIX):].strip()
279             raise CommandError(error)
280         if self._command_list is not None:
281             if line == NEXT:
282                 return
283             if line == SUCCESS:
284                 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
285         elif line == SUCCESS:
286             return
287         return line
288
289     def _read_pair(self, separator):
290         line = self._read_line()
291         if line is None:
292             return
293         pair = line.split(separator, 1)
294         if len(pair) < 2:
295             raise ProtocolError("Could not parse pair: '%s'" % line)
296         return pair
297
298     def _read_pairs(self, separator=": "):
299         pair = self._read_pair(separator)
300         while pair:
301             yield pair
302             pair = self._read_pair(separator)
303
304     def _read_list(self):
305         seen = None
306         for key, value in self._read_pairs():
307             if key != seen:
308                 if seen is not None:
309                     raise ProtocolError("Expected key '%s', got '%s'" %
310                                         (seen, key))
311                 seen = key
312             yield value
313
314     def _read_playlist(self):
315         for _, value in self._read_pairs(":"):
316             yield value
317
318     def _read_objects(self, delimiters=None):
319         obj = {}
320         if delimiters is None:
321             delimiters = []
322         for key, value in self._read_pairs():
323             key = key.lower()
324             if obj:
325                 if key in delimiters:
326                     yield obj
327                     obj = {}
328                 elif key in obj:
329                     if not isinstance(obj[key], list):
330                         obj[key] = [obj[key], value]
331                     else:
332                         obj[key].append(value)
333                     continue
334             obj[key] = value
335         if obj:
336             yield obj
337
338     def _read_command_list(self):
339         try:
340             for retval in self._command_list:
341                 yield retval()
342         finally:
343             self._command_list = None
344         self._fetch_nothing()
345
346     def _iterator_wrapper(self, iterator):
347         try:
348             for item in iterator:
349                 yield item
350         finally:
351             self._iterating = False
352
353     def _wrap_iterator(self, iterator):
354         if not self.iterate:
355             return list(iterator)
356         self._iterating = True
357         return self._iterator_wrapper(iterator)
358
359     def _fetch_nothing(self):
360         line = self._read_line()
361         if line is not None:
362             raise ProtocolError("Got unexpected return value: '%s'" % line)
363
364     def _fetch_item(self):
365         pairs = list(self._read_pairs())
366         if len(pairs) != 1:
367             return
368         return pairs[0][1]
369
370     def _fetch_list(self):
371         return self._wrap_iterator(self._read_list())
372
373     def _fetch_playlist(self):
374         return self._wrap_iterator(self._read_playlist())
375
376     def _fetch_object(self):
377         objs = list(self._read_objects())
378         if not objs:
379             return {}
380         return objs[0]
381
382     def _fetch_objects(self, delimiters):
383         return self._wrap_iterator(self._read_objects(delimiters))
384
385     def _fetch_changes(self):
386         return self._fetch_objects(["cpos"])
387
388     def _fetch_songs(self):
389         return self._fetch_objects(["file"])
390
391     def _fetch_playlists(self):
392         return self._fetch_objects(["playlist"])
393
394     def _fetch_database(self):
395         return self._fetch_objects(["file", "directory", "playlist"])
396
397     def _fetch_outputs(self):
398         return self._fetch_objects(["outputid"])
399
400     def _fetch_plugins(self):
401         return self._fetch_objects(["plugin"])
402
403     def _fetch_messages(self):
404         return self._fetch_objects(["channel"])
405
406     def _fetch_command_list(self):
407         return self._wrap_iterator(self._read_command_list())
408
409     def _hello(self):
410         line = self._rfile.readline()
411         if not line.endswith("\n"):
412             raise ConnectionError("Connection lost while reading MPD hello")
413         line = line.rstrip("\n")
414         if not line.startswith(HELLO_PREFIX):
415             raise ProtocolError("Got invalid MPD hello: '%s'" % line)
416         self.mpd_version = line[len(HELLO_PREFIX):].strip()
417
418     def _reset(self):
419         # pylint: disable=w0201
420         self.mpd_version = None
421         self._iterating = False
422         self._pending = []
423         self._command_list = None
424         self._sock = None
425         self._rfile = _NotConnected()
426         self._wfile = _NotConnected()
427
428     def _connect_unix(self, path):
429         if not hasattr(socket, "AF_UNIX"):
430             raise ConnectionError("Unix domain sockets not supported "
431                                   "on this platform")
432         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
433         sock.connect(path)
434         return sock
435
436     def _connect_tcp(self, host, port):
437         try:
438             flags = socket.AI_ADDRCONFIG
439         except AttributeError:
440             flags = 0
441         err = None
442         for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
443                                       socket.SOCK_STREAM, socket.IPPROTO_TCP,
444                                       flags):
445             af, socktype, proto, _, sa = res
446             sock = None
447             try:
448                 sock = socket.socket(af, socktype, proto)
449                 sock.connect(sa)
450                 return sock
451             except socket.error as socket_err:
452                 err = socket_err
453                 if sock is not None:
454                     sock.close()
455         if err is not None:
456             raise ConnectionError(str(err))
457         else:
458             raise ConnectionError("getaddrinfo returns an empty list")
459
460     def connect(self, host, port):
461         if self._sock is not None:
462             raise ConnectionError("Already connected")
463         if host.startswith("/"):
464             self._sock = self._connect_unix(host)
465         else:
466             self._sock = self._connect_tcp(host, port)
467         self._rfile = self._sock.makefile("r", encoding='utf-8')
468         self._wfile = self._sock.makefile("w", encoding='utf-8')
469         try:
470             self._hello()
471         except:
472             self.disconnect()
473             raise
474
475     def disconnect(self):
476         if hasattr(self._rfile, 'close'):
477             self._rfile.close()
478         if hasattr(self._wfile, 'close'):
479             self._wfile.close()
480         if hasattr(self._sock, 'close'):
481             self._sock.close()
482         self._reset()
483
484     def fileno(self):
485         if self._sock is None:
486             raise ConnectionError("Not connected")
487         return self._sock.fileno()
488
489     def command_list_ok_begin(self):
490         if self._command_list is not None:
491             raise CommandListError("Already in command list")
492         if self._iterating:
493             raise IteratingError("Cannot begin command list while iterating")
494         if self._pending:
495             raise PendingCommandError("Cannot begin command list "
496                                       "with pending commands")
497         self._write_command("command_list_ok_begin")
498         self._command_list = []
499
500     def command_list_end(self):
501         if self._command_list is None:
502             raise CommandListError("Not in command list")
503         if self._iterating:
504             raise IteratingError("Already iterating over a command list")
505         self._write_command("command_list_end")
506         return self._fetch_command_list()
507
508
509 def escape(text):
510     return text.replace("\\", "\\\\").replace('"', '\\"')
511
512
513 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: