plugin: really remove dock widgets
[nephilim.git] / nephilim / mpclient.py
blob0b7c1c626e0d00e8304d98462c82321a531dafca
2 # Copyright (C) 2008 jerous <jerous@gmail.com>
3 # Copyright (C) 2009 Anton Khirnov <wyskas@gmail.com>
5 # Nephilim is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU 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.
10 # Nephilim 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 General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Nephilim. If not, see <http://www.gnu.org/licenses/>.
19 from PyQt4 import QtCore
20 import mpd
21 import socket
22 import logging
24 from song import Song, SongRef, PlaylistEntryRef
26 class MPClient(QtCore.QObject):
27 """This class offers another layer above pympd, with usefull events."""
28 # public, read-only
29 logger = None
31 # these don't change while mpd is running
32 outputs = None
33 tagtypes = None
34 urlhandlers = None
35 commands = None
37 # private
38 __password = None
39 _client = None
40 _cur_song = None
41 _status = {'volume' : 0, 'repeat' : 0, 'random' : 0,
42 'songid' : 0, 'playlist' : 0, 'playlistlength' : 0,
43 'time' : 0, 'length' : 0, 'xfade' : 0,
44 'state' : 'stop', 'single' : 0,
45 'consume' : 0}
47 _timer_id = None #for querying status changes
48 _db_timer_id = None #for querying db updates
49 _db_update = None #time of last db update
51 __stats = {'artists': '0', 'albums' : '0', 'songs' : '0', 'uptime' : '0',
52 'playtime' : '0', 'db_playtime' : '0', 'db_update' : '0'}
54 # SIGNALS
55 connect_changed = QtCore.pyqtSignal(bool)
56 db_updated = QtCore.pyqtSignal()
57 song_changed = QtCore.pyqtSignal(object)
58 time_changed = QtCore.pyqtSignal(int)
59 state_changed = QtCore.pyqtSignal(str)
60 volume_changed = QtCore.pyqtSignal(int)
61 repeat_changed = QtCore.pyqtSignal(bool)
62 random_changed = QtCore.pyqtSignal(bool)
63 single_changed = QtCore.pyqtSignal(bool)
64 consume_changed = QtCore.pyqtSignal(bool)
65 playlist_changed = QtCore.pyqtSignal()
68 def __init__(self):
69 QtCore.QObject.__init__(self)
70 self.logger = logging.getLogger('mpclient')
71 self.__update_static()
72 self._status = dict(MPClient._status)
74 def connect_mpd(self, host, port, password = None):
75 """Connect to MPD@host:port, optionally using password."""
76 self.logger.info('Connecting to MPD...')
77 if self._client:
78 self.logger.warning('Attempted to connect when already connected.')
79 return
81 self._client = mpd.MPDClient()
82 self._client.connect_changed.connect(lambda val:self.__finish_connect() if val else self.__finish_disconnect())
83 self._client.connect_mpd(host, port)
84 self.__password = password
86 def disconnect_mpd(self):
87 """Disconnect from MPD."""
88 self.logger.info('Disconnecting from MPD...')
89 if self._client:
90 self._client.disconnect_mpd()
92 def password(self, password):
93 """Use the password to authenticate with MPD."""
94 self.logger.info('Authenticating with MPD.')
95 if not self.__check_command_ok('password'):
96 return
97 try:
98 self._client.password(password)
99 self.logger.info('Successfully authenticated')
100 self.__update_static()
101 except mpd.CommandError:
102 self.logger.error('Incorrect MPD password.')
103 def is_connected(self):
104 """Returns True if connected to MPD, False otherwise."""
105 return self._client != None
107 def status(self):
108 """Get current MPD status."""
109 return self._status
110 def playlistinfo(self):
111 """Returns a list of songs in current playlist."""
112 self.logger.info('Listing current playlist.')
113 if not self.__check_command_ok('playlistinfo'):
114 raise StopIteration
115 for song in self._client.playlistinfo():
116 yield Song(song)
117 raise StopIteration
118 def library(self):
119 """Returns a list of all songs in library."""
120 self.logger.info('Listing library.')
121 if not self.__check_command_ok('listallinfo'):
122 raise StopIteration
123 for song in self._client.listallinfo():
124 if 'file' in song:
125 yield Song(song)
127 raise StopIteration
128 def current_song(self):
129 """Returns the current playing song."""
130 return self._cur_song
131 def is_playing(self):
132 """Returns True if MPD is playing, False otherwise."""
133 return self._status['state'] == 'play'
134 def find(self, *args):
135 if not self.__check_command_ok('find'):
136 raise StopIteration
137 for song in self._client.find(*args):
138 yield Song(song)
139 raise StopIteration
140 def findadd(self, *args):
141 if not self.__check_command_ok('findadd'):
142 return
143 return self._client.findadd(*args)
145 def update_db(self, paths = None):
146 """Starts MPD database update."""
147 self.logger.info('Updating database %s'%(paths if paths else '.'))
148 if not self.__check_command_ok('update'):
149 return
150 if not paths:
151 return self._client.update()
152 self._client.command_list_ok_begin()
153 for path in paths:
154 self._client.update(path)
155 list(self._client.command_list_end())
157 def volume(self):
158 """Get current volume."""
159 return int(self._status['volume'])
160 def set_volume(self, volume):
161 """Set volume to volume."""
162 self.logger.info('Setting volume to %d.'%volume)
163 if not self.__check_command_ok('setvol'):
164 return
165 volume = min(100, max(0, volume))
166 try:
167 self._client.setvol(volume)
168 except mpd.CommandError, e:
169 self.logger.warning('Error setting volume (probably no outputs enabled): %s.'%e)
171 def stats(self):
172 """Get MPD statistics."""
173 if not self.__check_command_ok('stats'):
174 return self.__stats
175 return self._client.stats()
177 def repeat(self, val):
178 """Set repeat playlist to val (True/False)."""
179 self.logger.info('Setting repeat to %d.'%val)
180 if not self.__check_command_ok('repeat'):
181 return
182 if isinstance(val, bool):
183 val = 1 if val else 0
184 self._client.repeat(val)
185 def random(self, val):
186 """Set random playback to val (True, False)."""
187 self.logger.info('Setting random to %d.'%val)
188 if not self.__check_command_ok('random'):
189 return
190 if isinstance(val, bool):
191 val = 1 if val else 0
192 self._client.random(val)
193 def crossfade(self, time):
194 """Set crossfading between songs."""
195 self.logger.info('Setting crossfade to %d'%time)
196 if not self.__check_command_ok('crossfade'):
197 return
198 self._client.crossfade(time)
199 def single(self, val):
200 """Set single playback to val (True, False)"""
201 self.logger.info('Setting single to %d.'%val)
202 if not self.__check_command_ok('single'):
203 return
204 if isinstance(val, bool):
205 val = 1 if val else 0
206 self._client.single(val)
207 def consume(self, val):
208 """Set consume mode to val (True, False)"""
209 self.logger.info('Setting consume to %d.'%val)
210 if not self.__check_command_ok('consume'):
211 return
212 if isinstance(val, bool):
213 val = 1 if val else 0
214 self._client.consume(val)
216 def play(self, id = None):
217 """Play song with ID id or next song if id is None."""
218 self.logger.info('Starting playback %s.'%('of id %s'%(id) if id else ''))
219 if not self.__check_command_ok('play'):
220 return
221 if id:
222 self._client.playid(id)
223 else:
224 self._client.playid()
225 def pause(self):
226 """Pause playing."""
227 self.logger.info('Pausing playback.')
228 if not self.__check_command_ok('pause'):
229 return
230 self._client.pause(1)
231 def resume(self):
232 """Resume playing."""
233 self.logger.info('Resuming playback.')
234 if not self.__check_command_ok('pause'):
235 return
236 self._client.pause(0)
237 def next(self):
238 """Move on to the next song in the playlist."""
239 self.logger.info('Skipping to next song.')
240 if not self.__check_command_ok('next'):
241 return
242 self._client.next()
243 def previous(self):
244 """Move back to the previous song in the playlist."""
245 self.logger.info('Moving to previous song.')
246 if not self.__check_command_ok('previous'):
247 return
248 self._client.previous()
249 def stop(self):
250 """Stop playing."""
251 self.logger.info('Stopping playback.')
252 if not self.__check_command_ok('stop'):
253 return
254 self._client.stop()
255 def seek(self, time):
256 """Seek to time (in seconds)."""
257 self.logger.info('Seeking to %d.'%time)
258 if not self.__check_command_ok('seekid'):
259 return
260 if self._status['songid'] > 0:
261 self._client.seekid(self._status['songid'], time)
263 def delete(self, ids):
264 """Remove all song IDs in list from the playlist."""
265 if not self.__check_command_ok('deleteid'):
266 return
267 self._client.command_list_ok_begin()
268 try:
269 for id in ids:
270 self.logger.info('Deleting id %s from playlist.'%id)
271 self._client.deleteid(id)
272 list(self._client.command_list_end())
273 except mpd.CommandError, e:
274 self.logger.error('Error deleting files: %s.'%e)
275 def clear(self):
276 """Clear current playlist."""
277 self.logger.info('Clearing playlist.')
278 if not self.__check_command_ok('clear'):
279 return
280 self._client.clear()
281 def add(self, paths, pos = -1):
282 """Add all files in paths to the current playlist."""
283 if not self.__check_command_ok('addid'):
284 return
285 ret = None
286 self._client.command_list_ok_begin()
287 for path in paths:
288 self.logger.info('Adding %s to playlist'%path)
289 if pos < 0:
290 self._client.addid(path)
291 else:
292 self._client.addid(path, pos)
293 pos += 1
294 try:
295 ret = list(self._client.command_list_end())
296 except mpd.CommandError, e:
297 self.logger.error('Error adding files: %s.'%e)
298 if self._status['state'] == 'stop' and ret:
299 self.play(ret[0])
300 def move(self, source, target):
301 """Move the songs in playlist. Takes one source id and one target position."""
302 self.logger.info('Moving %s to %s.'%(source, target))
303 if not self.__check_command_ok('moveid'):
304 return
305 self._client.moveid(source, target)
307 #### private ####
308 def __finish_connect(self):
309 if self.__password:
310 self.password(self.__password)
311 else:
312 self.__update_static()
314 if not self.__check_command_ok('listallinfo'):
315 self.logger.error('Don\'t have MPD read permission, diconnecting.')
316 return self.disconnect_mpd()
318 self.__update_current_song()
319 self._db_update = self.stats()['db_update']
321 self.connect_changed.emit(True)
322 self.logger.info('Successfully connected to MPD.')
323 self._timer_id = self.startTimer(500)
324 self._db_timer_id = self.startTimer(1000)
325 def __finish_disconnect(self):
326 self._client = None
328 if self._timer_id:
329 self.killTimer(self._timer_id)
330 self._timer_id = None
331 if self._db_timer_id:
332 self.killTimer(self._db_timer_id)
333 self._db_timer_id = None
334 self._status = dict(MPClient._status)
335 self._cur_song = None
336 self.__update_static()
337 self.connect_changed.emit(False)
338 self.logger.info('Disconnected from MPD.')
339 def __update_current_song(self):
340 """Update the current song."""
341 song = self._client.currentsong()
342 if not song:
343 self._cur_song = None
344 else:
345 self._cur_song = Song(song)
346 def _update_status(self):
347 """Get current status"""
348 if not self._client:
349 return None
350 ret = self._client.status()
351 if not ret:
352 return None
354 ret['repeat'] = int(ret['repeat'])
355 ret['random'] = int(ret['random'])
356 ret['single'] = int(ret['single'])
357 ret['consume'] = int(ret['consume'])
358 ret['volume'] = int(ret['volume'])
359 if 'time' in ret:
360 cur, len = ret['time'].split(':')
361 ret['length'] = int(len)
362 ret['time'] = int(cur)
363 else:
364 ret['length'] = 0
365 ret['time'] = 0
367 if not 'songid' in ret:
368 ret['songid'] = '-1'
370 return ret
371 def __check_command_ok(self, cmd):
372 if not self._client:
373 return self.logger.info('Not connected.')
374 if not cmd in self.commands:
375 return self.logger.error('Command %s not accessible'%cmd)
376 return True
378 def __update_static(self):
379 """Update static values, called on connect/disconnect."""
380 if self._client:
381 self.commands = list(self._client.commands())
382 else:
383 self.commands = []
385 if self.__check_command_ok('outputs'):
386 outputs = []
387 for output in self._client.outputs():
388 outputs.append(AudioOutput(self, output['outputname'], output['outputid'],
389 bool(output['outputenabled'])))
390 self.outputs = outputs
391 else:
392 self.outputs = []
394 if self.__check_command_ok('tagtypes'):
395 self.tagtypes = map(unicode.lower, self._client.tagtypes()) + ['file']
396 else:
397 self.tagtypes = []
399 if self.__check_command_ok('urlhandlers'):
400 self.urlhandlers = list(self._client.urlhandlers())
401 else:
402 self.urlhandlers = []
404 def set_output(self, output_id, state):
405 """Set audio output output_id to state (0/1). Called only by AudioOutput."""
406 if not self.__check_command_ok('enableoutput'):
407 return
408 if state:
409 self._client.enableoutput(output_id)
410 else:
411 self._client.disableoutput(output_id)
413 def timerEvent(self, event):
414 """Check for changes since last check."""
415 if event.timerId() == self._db_timer_id:
416 #timer for monitoring db changes
417 db_update = self.stats()['db_update']
418 if db_update > self._db_update:
419 self.logger.info('Database updated.')
420 self._db_update = db_update
421 self.db_updated.emit()
422 return
425 old_status = self._status
426 self._status = self._update_status()
428 if not self._status:
429 return self.disconnect_mpd()
431 if self._status['songid'] != old_status['songid']:
432 self.__update_current_song()
433 self.song_changed.emit(PlaylistEntryRef(self, self._status['songid']))
435 if self._status['time'] != old_status['time']:
436 self.time_changed.emit(self._status['time'])
438 if self._status['state'] != old_status['state']:
439 self.state_changed.emit(self._status['state'])
441 if self._status['volume'] != old_status['volume']:
442 self.volume_changed.emit( int(self._status['volume']))
444 if self._status['repeat'] != old_status['repeat']:
445 self.repeat_changed.emit(bool(self._status['repeat']))
447 if self._status['random'] != old_status['random']:
448 self.random_changed.emit(bool(self._status['random']))
450 if self._status['single'] != old_status['single']:
451 self.single_changed.emit(bool(self._status['single']))
453 if self._status['consume'] != old_status['consume']:
454 self.consume_changed.emit(bool(self._status['consume']))
456 if self._status['playlist'] != old_status['playlist']:
457 self.playlist_changed.emit()
459 outputs = list(self._client.outputs())
460 for i in range(len(outputs)):
461 if int(outputs[i]['outputenabled']) != int(self.outputs[i].state):
462 self.outputs[i].mpd_toggle_state()
465 class AudioOutput(QtCore.QObject):
466 """This class represents an MPD audio output."""
467 # public, const
468 mpclient = None
469 name = None
470 id = None
471 state = None
473 # SIGNALS
474 state_changed = QtCore.pyqtSignal(bool)
476 #### public ####
477 def __init__(self, mpclient, name, id, state):
478 QtCore.QObject.__init__(self)
480 self.mpclient = mpclient
481 self.name = name
482 self.id = id
483 self.state = state
485 @QtCore.pyqtSlot(bool)
486 def set_state(self, state):
487 self.mpclient.set_output(self.id, state)
489 #### private ####
490 def mpd_toggle_state(self):
491 """This is called by mpclient to inform about output state change."""
492 self.state = not self.state
493 self.state_changed.emit(self.state)