mpd/mpclient: catch socket errors when sending commands
[nephilim.git] / nephilim / mpd.py
blobbcdf3ac0e24080cb6591871e49d2983559d6c16f
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/>.
17 import socket
18 import logging
19 from PyQt4 import QtCore
22 HELLO_PREFIX = "OK MPD "
23 ERROR_PREFIX = "ACK "
24 SUCCESS = "OK"
25 NEXT = "list_OK"
28 class MPDError(Exception):
29 pass
31 class ConnectionError(MPDError):
32 pass
34 class ProtocolError(MPDError):
35 pass
37 class CommandError(MPDError):
38 pass
40 class CommandListError(MPDError):
41 pass
44 class _NotConnected(object):
45 def __getattr__(self, attr):
46 return self._dummy
48 def _dummy(*args):
49 raise ConnectionError("Not connected")
51 class MPDClient(QtCore.QObject):
52 # public
53 logger = None
55 # SIGNALS
56 connect_changed = QtCore.pyqtSignal(bool)
57 def __init__(self):
58 QtCore.QObject.__init__(self)
59 self.logger = logging.getLogger('mpclient.mpdsocket')
60 self._reset()
61 self._commands = {
62 # Admin Commands
63 "disableoutput": self._getnone,
64 "enableoutput": self._getnone,
65 "kill": None,
66 "update": self._getitem,
67 # Informational Commands
68 "status": self._getobject,
69 "stats": self._getobject,
70 "outputs": self._getoutputs,
71 "commands": self._getlist,
72 "notcommands": self._getlist,
73 "tagtypes": self._getlist,
74 "urlhandlers": self._getlist,
75 # Database Commands
76 "find": self._getsongs,
77 "findadd": self._getnone,
78 "list": self._getlist,
79 "listall": self._getdatabase,
80 "listallinfo": self._getdatabase,
81 "lsinfo": self._getdatabase,
82 "search": self._getsongs,
83 "count": self._getobject,
84 # Playlist Commands
85 "add": self._getnone,
86 "addid": self._getitem,
87 "clear": self._getnone,
88 "currentsong": self._getobject,
89 "delete": self._getnone,
90 "deleteid": self._getnone,
91 "load": self._getnone,
92 "rename": self._getnone,
93 "move": self._getnone,
94 "moveid": self._getnone,
95 "playlist": self._getplaylist,
96 "playlistinfo": self._getsongs,
97 "playlistid": self._getsongs,
98 "plchanges": self._getsongs,
99 "plchangesposid": self._getchanges,
100 "rm": self._getnone,
101 "save": self._getnone,
102 "shuffle": self._getnone,
103 "swap": self._getnone,
104 "swapid": self._getnone,
105 "listplaylist": self._getlist,
106 "listplaylistinfo": self._getsongs,
107 "playlistadd": self._getnone,
108 "playlistclear": self._getnone,
109 "playlistdelete": self._getnone,
110 "playlistmove": self._getnone,
111 "playlistfind": self._getsongs,
112 "playlistsearch": self._getsongs,
113 # Playback Commands
114 "consume": self._getnone,
115 "crossfade": self._getnone,
116 "next": self._getnone,
117 "pause": self._getnone,
118 "play": self._getnone,
119 "playid": self._getnone,
120 "previous": self._getnone,
121 "random": self._getnone,
122 "repeat": self._getnone,
123 "seek": self._getnone,
124 "seekid": self._getnone,
125 "setvol": self._getnone,
126 "single": self._getnone,
127 "stop": self._getnone,
128 "volume": self._getnone,
129 # Miscellaneous Commands
130 "clearerror": self._getnone,
131 "close": None,
132 "password": self._getnone,
133 "ping": self._getnone,
136 def __getattr__(self, attr):
137 try:
138 retval = self._commands[attr]
139 except KeyError:
140 raise AttributeError("'%s' object has no attribute '%s'" %
141 (self.__class__.__name__, attr))
142 return lambda *args: self._docommand(attr, args, retval)
144 def _docommand(self, command, args, retval):
145 if self._commandlist is not None and not callable(retval):
146 raise CommandListError("%s not allowed in command list" % command)
147 try:
148 self._writecommand(command, args)
149 except socket.error, e:
150 self.logger.error('Error sending command: %s.'%e)
151 self.disconnect_mpd()
152 return None
154 if self._commandlist is None:
155 if callable(retval):
156 return retval()
157 return retval
158 self._commandlist.append(retval)
160 def _writeline(self, line):
161 self._wfile.write("%s\n" % line)
162 self._wfile.flush()
164 def _writecommand(self, command, args=[]):
165 parts = [command]
166 for arg in args:
167 parts.append('"%s"' % escape(str(arg)))
168 self._writeline(" ".join(parts))
170 def _readline(self):
171 line = self._rfile.readline()
172 if not line.endswith("\n"):
173 raise ConnectionError("Connection lost while reading line")
174 line = line.rstrip("\n")
175 if line.startswith(ERROR_PREFIX):
176 error = line[len(ERROR_PREFIX):].strip()
177 raise CommandError(error)
178 if self._commandlist is not None:
179 if line == NEXT:
180 return
181 if line == SUCCESS:
182 raise ProtocolError("Got unexpected '%s'" % SUCCESS)
183 elif line == SUCCESS:
184 return
185 return line
187 def _readitem(self, separator):
188 line = self._readline()
189 if line is None:
190 return
191 item = line.split(separator, 1)
192 if len(item) < 2:
193 raise ProtocolError("Could not parse item: '%s'" % line)
194 return item
196 def _readitems(self, separator=": "):
197 item = self._readitem(separator)
198 while item:
199 yield item
200 item = self._readitem(separator)
201 raise StopIteration
203 def _readlist(self):
204 seen = None
205 for key, value in self._readitems():
206 if key != seen:
207 if seen is not None:
208 raise ProtocolError("Expected key '%s', got '%s'" %
209 (seen, key))
210 seen = key
211 yield value
212 raise StopIteration
214 def _readplaylist(self):
215 for key, value in self._readitems(":"):
216 yield value
217 raise StopIteration
219 def _readobjects(self, delimiters=[]):
220 obj = {}
221 for key, value in self._readitems():
222 key = key.lower()
223 if obj:
224 if key in delimiters:
225 yield obj
226 obj = {}
227 elif obj.has_key(key):
228 if not isinstance(obj[key], list):
229 obj[key] = [obj[key], value]
230 else:
231 obj[key].append(value)
232 continue
233 obj[key] = value
234 if obj:
235 yield obj
236 raise StopIteration
238 def _readcommandlist(self):
239 for retval in self._commandlist:
240 yield retval()
241 self._commandlist = None
242 self._getnone()
243 raise StopIteration
245 def _getnone(self):
246 line = self._readline()
247 if line is not None:
248 raise ProtocolError("Got unexpected return value: '%s'" % line)
250 def _getitem(self):
251 items = list(self._readitems())
252 if len(items) != 1:
253 return
254 return items[0][1]
256 def _getlist(self):
257 return self._readlist()
259 def _getplaylist(self):
260 return self._readplaylist()
262 def _getobject(self):
263 objs = list(self._readobjects())
264 if not objs:
265 return {}
266 return objs[0]
268 def _getobjects(self, delimiters):
269 return self._readobjects(delimiters)
271 def _getsongs(self):
272 return self._getobjects(["file"])
274 def _getdatabase(self):
275 return self._getobjects(["file", "directory", "playlist"])
277 def _getoutputs(self):
278 return self._getobjects(["outputid"])
280 def _getchanges(self):
281 return self._getobjects(["cpos"])
283 def _getcommandlist(self):
284 try:
285 return self._readcommandlist()
286 except CommandError:
287 self._commandlist = None
288 raise
290 def _reset(self):
291 self.mpd_version = None
292 self._commandlist = None
293 self._sock = None
294 self._rfile = _NotConnected()
295 self._wfile = _NotConnected()
297 def connect_mpd(self, host, port):
298 if self._sock:
299 self.logger.error('Already connected.')
300 msg = "getaddrinfo returns an empty list"
301 try:
302 flags = socket.AI_ADDRCONFIG
303 except AttributeError:
304 flags = 0
305 if port == None: #assume Unix domain socket
306 try:
307 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
308 self._sock.connect(host)
309 except socket.error, e:
310 if self._sock:
311 self._sock.close()
312 self._sock = None
313 self.logger.error('Error connecting to MPD: %s.'%e)
314 else:
315 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
316 socket.SOCK_STREAM, socket.IPPROTO_TCP,
317 flags):
318 af, socktype, proto, canonname, sa = res
319 try:
320 self._sock = socket.socket(af, socktype, proto)
321 self._sock.connect(sa)
322 except socket.error, e:
323 if self._sock:
324 self._sock.close()
325 self._sock = None
326 self.logger.error('Error connecting to MPD: %s.'%e)
327 continue
328 break
329 if not self._sock:
330 return
331 self._rfile = self._sock.makefile('rb')
332 self._wfile = self._sock.makefile('wb')
334 # read MPD hello
335 line = self._rfile.readline()
336 if not line.endswith("\n"):
337 self.logger.error('Connnection lost while reading MPD hello')
338 self.disconnect_mpd()
339 return False
340 line = line.rstrip("\n")
341 if not line.startswith(HELLO_PREFIX):
342 self.logger.error('Got invalid MPD hello: %s' % line)
343 self.disconnect_mpd()
344 return
345 self.mpd_version = line[len(HELLO_PREFIX):].strip()
347 self.connect_changed.emit(True)
349 def disconnect_mpd(self):
350 self._rfile.close()
351 self._wfile.close()
352 self._sock.close()
353 self._reset()
354 self.connect_changed.emit(False)
356 def command_list_ok_begin(self):
357 if self._commandlist is not None:
358 raise CommandListError("Already in command list")
359 self._writecommand("command_list_ok_begin")
360 self._commandlist = []
362 def command_list_end(self):
363 if self._commandlist is None:
364 raise CommandListError("Not in command list")
365 self._writecommand("command_list_end")
366 return self._getcommandlist()
369 def escape(text):
370 return text.replace("\\", "\\\\").replace('"', '\\"')
373 # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: