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