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