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