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