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