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