Playlist: support for moving songs with drag&drop
[nephilim.git] / nephilim / mpclient.py
blob9e287d7eab364596dee2be86fcf7610f91c4342f
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
52 # SIGNALS
53 connect_changed = QtCore.pyqtSignal(bool)
54 db_updated = QtCore.pyqtSignal()
55 song_changed = QtCore.pyqtSignal(object)
56 time_changed = QtCore.pyqtSignal(int)
57 state_changed = QtCore.pyqtSignal(str)
58 volume_changed = QtCore.pyqtSignal(int)
59 repeat_changed = QtCore.pyqtSignal(bool)
60 random_changed = QtCore.pyqtSignal(bool)
61 single_changed = QtCore.pyqtSignal(bool)
62 consume_changed = QtCore.pyqtSignal(bool)
63 playlist_changed = QtCore.pyqtSignal()
66 def __init__(self):
67 QtCore.QObject.__init__(self)
68 self.logger = logging.getLogger('mpclient')
69 self.__update_static()
70 self._status = dict(MPClient._status)
72 def connect_mpd(self, host, port, password = None):
73 """Connect to MPD@host:port, optionally using password."""
74 self.logger.info('Connecting to MPD...')
75 if self._client:
76 self.logger.warning('Attempted to connect when already connected.')
77 return
79 self._client = mpd.MPDClient()
80 self._client.connect_changed.connect(lambda val:self.__finish_connect() if val else self.__finish_disconnect())
81 self._client.connect_mpd(host, port)
82 self.__password = password
84 def disconnect_mpd(self):
85 """Disconnect from MPD."""
86 self.logger.info('Disconnecting from MPD...')
87 if not self._client:
88 self.logger.warning('Attempted to disconnect when not connected.')
89 self._client.disconnect_mpd()
91 def password(self, password):
92 """Use the password to authenticate with MPD."""
93 self.logger.info('Authenticating with MPD.')
94 if not self.__check_command_ok('password'):
95 return
96 try:
97 self._client.password(password)
98 self.logger.info('Successfully authenticated')
99 self.__update_static()
100 except mpd.CommandError:
101 self.logger.error('Incorrect MPD password.')
102 def is_connected(self):
103 """Returns True if connected to MPD, False otherwise."""
104 return self._client != None
106 def status(self):
107 """Get current MPD status."""
108 return self._status
109 def playlistinfo(self):
110 """Returns a list of songs in current playlist."""
111 self.logger.info('Listing current playlist.')
112 if not self.__check_command_ok('playlistinfo'):
113 raise StopIteration
114 for song in self._client.playlistinfo():
115 yield Song(song)
116 raise StopIteration
117 def library(self):
118 """Returns a list of all songs in library."""
119 self.logger.info('Listing library.')
120 if not self.__check_command_ok('listallinfo'):
121 raise StopIteration
122 for song in self._client.listallinfo():
123 if 'file' in song:
124 yield Song(song)
126 raise StopIteration
127 def current_song(self):
128 """Returns the current playing song."""
129 return self._cur_song
130 def is_playing(self):
131 """Returns True if MPD is playing, False otherwise."""
132 return self._status['state'] == 'play'
133 def find(self, *args):
134 if not self.__check_command_ok('find'):
135 raise StopIteration
136 for song in self._client.find(*args):
137 yield Song(song)
138 raise StopIteration
139 def findadd(self, *args):
140 if not self.__check_command_ok('findadd'):
141 return
142 return self._client.findadd(*args)
144 def update_db(self, paths = None):
145 """Starts MPD database update."""
146 self.logger.info('Updating database %s'%(paths if paths else '.'))
147 if not self.__check_command_ok('update'):
148 return
149 if not paths:
150 return self._client.update()
151 self._client.command_list_ok_begin()
152 for path in paths:
153 self._client.update(path)
154 list(self._client.command_list_end())
156 def volume(self):
157 """Get current volume."""
158 return int(self._status['volume'])
159 def set_volume(self, volume):
160 """Set volume to volume."""
161 self.logger.info('Setting volume to %d.'%volume)
162 if not self.__check_command_ok('setvol'):
163 return
164 volume = min(100, max(0, volume))
165 try:
166 self._client.setvol(volume)
167 except mpd.CommandError, e:
168 self.logger.warning('Error setting volume (probably no outputs enabled): %s.'%e)
170 def stats(self):
171 """Get MPD statistics."""
172 return self._client.stats()
174 def repeat(self, val):
175 """Set repeat playlist to val (True/False)."""
176 self.logger.info('Setting repeat to %d.'%val)
177 if not self.__check_command_ok('repeat'):
178 return
179 if isinstance(val, bool):
180 val = 1 if val else 0
181 self._client.repeat(val)
182 def random(self, val):
183 """Set random playback to val (True, False)."""
184 self.logger.info('Setting random to %d.'%val)
185 if not self.__check_command_ok('random'):
186 return
187 if isinstance(val, bool):
188 val = 1 if val else 0
189 self._client.random(val)
190 def crossfade(self, time):
191 """Set crossfading between songs."""
192 self.logger.info('Setting crossfade to %d'%time)
193 if not self.__check_command_ok('crossfade'):
194 return
195 self._client.crossfade(time)
196 def single(self, val):
197 """Set single playback to val (True, False)"""
198 self.logger.info('Setting single to %d.'%val)
199 if not self.__check_command_ok('single'):
200 return
201 if isinstance(val, bool):
202 val = 1 if val else 0
203 self._client.single(val)
204 def consume(self, val):
205 """Set consume mode to val (True, False)"""
206 self.logger.info('Setting consume to %d.'%val)
207 if not self.__check_command_ok('consume'):
208 return
209 if isinstance(val, bool):
210 val = 1 if val else 0
211 self._client.consume(val)
213 def play(self, id = None):
214 """Play song with ID id or next song if id is None."""
215 self.logger.info('Starting playback %s.'%('of id %s'%(id) if id else ''))
216 if not self.__check_command_ok('play'):
217 return
218 if id:
219 self._client.playid(id)
220 else:
221 self._client.playid()
222 def pause(self):
223 """Pause playing."""
224 self.logger.info('Pausing playback.')
225 if not self.__check_command_ok('pause'):
226 return
227 self._client.pause(1)
228 def resume(self):
229 """Resume playing."""
230 self.logger.info('Resuming playback.')
231 if not self.__check_command_ok('pause'):
232 return
233 self._client.pause(0)
234 def next(self):
235 """Move on to the next song in the playlist."""
236 self.logger.info('Skipping to next song.')
237 if not self.__check_command_ok('next'):
238 return
239 self._client.next()
240 def previous(self):
241 """Move back to the previous song in the playlist."""
242 self.logger.info('Moving to previous song.')
243 if not self.__check_command_ok('previous'):
244 return
245 self._client.previous()
246 def stop(self):
247 """Stop playing."""
248 self.logger.info('Stopping playback.')
249 if not self.__check_command_ok('stop'):
250 return
251 self._client.stop()
252 def seek(self, time):
253 """Seek to time (in seconds)."""
254 self.logger.info('Seeking to %d.'%time)
255 if not self.__check_command_ok('seekid'):
256 return
257 if self._status['songid'] > 0:
258 self._client.seekid(self._status['songid'], time)
260 def delete(self, ids):
261 """Remove all song IDs in list from the playlist."""
262 if not self.__check_command_ok('deleteid'):
263 return
264 self._client.command_list_ok_begin()
265 try:
266 for id in ids:
267 self.logger.info('Deleting id %s from playlist.'%id)
268 self._client.deleteid(id)
269 list(self._client.command_list_end())
270 except mpd.CommandError, e:
271 self.logger.error('Error deleting files: %s.'%e)
272 def clear(self):
273 """Clear current playlist."""
274 self.logger.info('Clearing playlist.')
275 if not self.__check_command_ok('clear'):
276 return
277 self._client.clear()
278 def add(self, paths, pos = -1):
279 """Add all files in paths to the current playlist."""
280 if not self.__check_command_ok('addid'):
281 return
282 ret = None
283 self._client.command_list_ok_begin()
284 try:
285 for path in paths:
286 self.logger.info('Adding %s to playlist'%path)
287 if pos < 0:
288 self._client.addid(path.encode('utf-8'))
289 else:
290 self._client.addid(path.encode('utf-8'), pos)
291 pos += 1
292 ret = list(self._client.command_list_end())
293 except mpd.CommandError, e:
294 self.logger.error('Error adding files: %s.'%e)
295 if self._status['state'] == 'stop' and ret:
296 self.play(ret[0])
297 def move(self, source, target):
298 """Move the songs in playlist. Takes one source id and one target position."""
299 self.logger.info('Moving %s to %s.'%(source, target))
300 if not self.__check_command_ok('moveid'):
301 return
302 self._client.moveid(source, target)
304 #### private ####
305 def __finish_connect(self):
306 if self.__password:
307 self.password(self.__password)
308 else:
309 self.__update_static()
311 if not self.__check_command_ok('listallinfo'):
312 self.logger.error('Don\'t have MPD read permission, diconnecting.')
313 return self.disconnect_mpd()
315 self.__update_current_song()
316 self._db_update = self.stats()['db_update']
318 self.connect_changed.emit(True)
319 self.logger.info('Successfully connected to MPD.')
320 self._timer_id = self.startTimer(500)
321 self._db_timer_id = self.startTimer(1000)
322 def __finish_disconnect(self):
323 self._client = None
325 if self._timer_id:
326 self.killTimer(self._timer_id)
327 self._timer_id = None
328 if self._db_timer_id:
329 self.killTimer(self._db_timer_id)
330 self._db_timer_id = None
331 self._status = dict(MPClient._status)
332 self._cur_song = None
333 self.__update_static()
334 self.connect_changed.emit(False)
335 self.logger.info('Disconnected from MPD.')
336 def __update_current_song(self):
337 """Update the current song."""
338 song = self._client.currentsong()
339 if not song:
340 self._cur_song = None
341 else:
342 self._cur_song = Song(song)
343 def _update_status(self):
344 """Get current status"""
345 if not self._client:
346 return None
347 ret = self._client.status()
348 if not ret:
349 return None
351 ret['repeat'] = int(ret['repeat'])
352 ret['random'] = int(ret['random'])
353 ret['single'] = int(ret['single'])
354 ret['consume'] = int(ret['consume'])
355 if 'time' in ret:
356 cur, len = ret['time'].split(':')
357 ret['length'] = int(len)
358 ret['time'] = int(cur)
359 else:
360 ret['length'] = 0
361 ret['time'] = 0
363 if not 'songid' in ret:
364 ret['songid'] = '-1'
366 return ret
367 def __check_command_ok(self, cmd):
368 if not self._client:
369 return self.logger.info('Not connected.')
370 if not cmd in self.commands:
371 return self.logger.error('Command %s not accessible'%cmd)
372 return True
374 def __update_static(self):
375 """Update static values, called on connect/disconnect."""
376 if self._client:
377 self.commands = list(self._client.commands())
378 else:
379 self.commands = []
381 if self.__check_command_ok('outputs'):
382 outputs = []
383 for output in self._client.outputs():
384 outputs.append(AudioOutput(self, output['outputname'], output['outputid'],
385 bool(output['outputenabled'])))
386 self.outputs = outputs
387 else:
388 self.outputs = []
390 if self.__check_command_ok('tagtypes'):
391 self.tagtypes = map(str.lower, self._client.tagtypes()) + ['file']
392 else:
393 self.tagtypes = []
395 if self.__check_command_ok('urlhandlers'):
396 self.urlhandlers = list(self._client.urlhandlers())
397 else:
398 self.urlhandlers = []
400 def set_output(self, output_id, state):
401 """Set audio output output_id to state (0/1). Called only by AudioOutput."""
402 if not self.__check_command_ok('enableoutput'):
403 return
404 if state:
405 self._client.enableoutput(output_id)
406 else:
407 self._client.disableoutput(output_id)
409 def timerEvent(self, event):
410 """Check for changes since last check."""
411 if event.timerId() == self._db_timer_id:
412 #timer for monitoring db changes
413 db_update = self.stats()['db_update']
414 if db_update > self._db_update:
415 self.logger.info('Database updated.')
416 self._db_update = db_update
417 self.db_updated.emit()
418 return
421 old_status = self._status
422 self._status = self._update_status()
424 if not self._status:
425 return self.disconnect_mpd()
427 if self._status['songid'] != old_status['songid']:
428 self.__update_current_song()
429 self.song_changed.emit(PlaylistEntryRef(self, self._status['songid']))
431 if self._status['time'] != old_status['time']:
432 self.time_changed.emit(self._status['time'])
434 if self._status['state'] != old_status['state']:
435 self.state_changed.emit(self._status['state'])
437 if self._status['volume'] != old_status['volume']:
438 self.volume_changed.emit( int(self._status['volume']))
440 if self._status['repeat'] != old_status['repeat']:
441 self.repeat_changed.emit(bool(self._status['repeat']))
443 if self._status['random'] != old_status['random']:
444 self.random_changed.emit(bool(self._status['random']))
446 if self._status['single'] != old_status['single']:
447 self.single_changed.emit(bool(self._status['single']))
449 if self._status['consume'] != old_status['consume']:
450 self.consume_changed.emit(bool(self._status['consume']))
452 if self._status['playlist'] != old_status['playlist']:
453 self.playlist_changed.emit()
455 outputs = list(self._client.outputs())
456 for i in range(len(outputs)):
457 if int(outputs[i]['outputenabled']) != int(self.outputs[i].state):
458 self.outputs[i].mpd_toggle_state()
461 class AudioOutput(QtCore.QObject):
462 """This class represents an MPD audio output."""
463 # public, const
464 mpclient = None
465 name = None
466 id = None
467 state = None
469 # SIGNALS
470 state_changed = QtCore.pyqtSignal(bool)
472 #### public ####
473 def __init__(self, mpclient, name, id, state):
474 QtCore.QObject.__init__(self)
476 self.mpclient = mpclient
477 self.name = name
478 self.id = id
479 self.state = state
481 @QtCore.pyqtSlot(bool)
482 def set_state(self, state):
483 self.mpclient.set_output(self.id, state)
485 #### private ####
486 def mpd_toggle_state(self):
487 """This is called by mpclient to inform about output state change."""
488 self.state = not self.state
489 self.state_changed.emit(self.state)