1 # Python MPD client library
2 # Copyright (C) 2008 J. Alexander Treuman <jat@spatialrift.net>
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 HELLO_PREFIX = "OK MPD "
26 class MPDError(Exception):
29 class ProtocolError(MPDError):
32 class CommandError(MPDError):
35 class CommandListError(MPDError):
39 class MPDClient(object):
45 "disableoutput": self._getnone,
46 "enableoutput": self._getnone,
48 "update": self._getitem,
49 # Informational Commands
50 "status": self._getobject,
51 "stats": self._getobject,
52 "outputs": self._getoutputs,
53 "commands": self._getlist,
54 "notcommands": self._getlist,
55 "tagtypes": self._getlist,
56 "urlhandlers": self._getlist,
58 "find": self._getsongs,
59 "list": self._getlist,
60 "listall": self._getdatabase,
61 "listallinfo": self._getdatabase,
62 "lsinfo": self._getdatabase,
63 "search": self._getsongs,
64 "count": self._getobject,
67 "addid": self._getitem,
68 "clear": self._getnone,
69 "currentsong": self._getobject,
70 "delete": self._getnone,
71 "deleteid": self._getnone,
72 "load": self._getnone,
73 "rename": self._getnone,
74 "move": self._getnone,
75 "moveid": self._getnone,
76 "playlist": self._getplaylist,
77 "playlistinfo": self._getsongs,
78 "playlistid": self._getsongs,
79 "plchanges": self._getsongs,
80 "plchangesposid": self._getchanges,
82 "save": self._getnone,
83 "shuffle": self._getnone,
84 "swap": self._getnone,
85 "swapid": self._getnone,
86 "listplaylist": self._getlist,
87 "listplaylistinfo": self._getsongs,
88 "playlistadd": self._getnone,
89 "playlistclear": self._getnone,
90 "playlistdelete": self._getnone,
91 "playlistmove": self._getnone,
92 "playlistfind": self._getsongs,
93 "playlistsearch": self._getsongs,
95 "crossfade": self._getnone,
96 "next": self._getnone,
97 "pause": self._getnone,
98 "play": self._getnone,
99 "playid": self._getnone,
100 "previous": self._getnone,
101 "random": self._getnone,
102 "repeat": self._getnone,
103 "seek": self._getnone,
104 "seekid": self._getnone,
105 "setvol": self._getnone,
106 "stop": self._getnone,
107 "volume": self._getnone,
108 # Miscellaneous Commands
109 "clearerror": self._getnone,
111 "password": self._getnone,
112 "ping": self._getnone,
115 def __getattr__(self, attr):
117 retval = self._commands[attr]
119 raise AttributeError, "'%s' object has no attribute '%s'" % \
120 (self.__class__.__name__, attr)
121 return lambda *args: self._docommand(attr, args, retval)
123 def _docommand(self, command, args, retval):
124 if self._commandlist is not None and not callable(retval):
125 raise CommandListError, "%s not allowed in command list" % command
126 self._writecommand(command, args)
127 if self._commandlist is None:
131 self._commandlist.append(retval)
133 def _writeline(self, line):
134 self._sockfile.write("%s\n" % line)
135 self._sockfile.flush()
137 def _writecommand(self, command, args=[]):
140 parts.append('"%s"' % escape(str(arg)))
141 self._writeline(" ".join(parts))
144 line = self._sockfile.readline().rstrip("\n")
145 if line.startswith(ERROR_PREFIX):
146 error = line[len(ERROR_PREFIX):].strip()
147 raise CommandError, error
148 if self._commandlist is not None:
152 raise ProtocolError, "Got unexpected '%s'" % SUCCESS
153 elif line == SUCCESS:
157 def _readitem(self, separator):
158 line = self._readline()
161 item = line.split(separator, 1)
163 raise ProtocolError, "Could not parse item: '%s'" % line
166 def _readitems(self, separator=": "):
167 item = self._readitem(separator)
170 item = self._readitem(separator)
175 for key, value in self._readitems():
178 raise ProtocolError, "Expected key '%s', got '%s'" % \
184 def _readplaylist(self):
185 for key, value in self._readitems(":"):
189 def _readobjects(self, delimiters=[]):
191 for key, value in self._readitems():
194 if key in delimiters:
197 elif obj.has_key(key):
198 if not isinstance(obj[key], list):
199 obj[key] = [obj[key], value]
201 obj[key].append(value)
208 def _readcommandlist(self):
209 for retval in self._commandlist:
211 self._commandlist = None
215 def _wrapiterator(self, iterator):
217 return list(iterator)
221 line = self._readline()
223 raise ProtocolError, "Got unexpected return value: '%s'" % line
226 items = list(self._readitems())
228 raise ProtocolError, "Expected 1 item, got %i" % len(items)
232 return self._wrapiterator(self._readlist())
234 def _getplaylist(self):
235 return self._wrapiterator(self._readplaylist())
237 def _getobject(self):
238 objs = list(self._readobjects())
243 def _getobjects(self, delimiters):
244 return self._wrapiterator(self._readobjects(delimiters))
247 return self._getobjects(["file"])
249 def _getdatabase(self):
250 return self._getobjects(["file", "directory", "playlist"])
252 def _getoutputs(self):
253 return self._getobjects(["outputid"])
255 def _getchanges(self):
256 return self._getobjects(["cpos"])
258 def _getcommandlist(self):
259 return self._wrapiterator(self._readcommandlist())
262 line = self._sockfile.readline().rstrip("\n")
263 if not line.startswith(HELLO_PREFIX):
264 raise ProtocolError, "Got invalid MPD hello: '%s'" % line
265 self.mpd_version = line[len(HELLO_PREFIX):].strip()
268 self.mpd_version = None
269 self._commandlist = None
270 self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
271 self._sockfile = self._sock.makefile("rb+")
273 def connect(self, host, port):
275 self._sock.connect((host, port))
278 def disconnect(self):
279 self._sockfile.close()
283 def command_list_ok_begin(self):
284 if self._commandlist is not None:
285 raise CommandListError, "Already in command list"
286 self._writecommand("command_list_ok_begin")
287 self._commandlist = []
289 def command_list_end(self):
290 if self._commandlist is None:
291 raise CommandListError, "Not in command list"
292 self._writecommand("command_list_end")
293 return self._getcommandlist()
297 return text.replace("\\", "\\\\").replace('"', '\\"')
300 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: