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