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