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
24 from song
import Song
, SongRef
, PlaylistEntryRef
26 class MPClient(QtCore
.QObject
):
27 """This class offers another layer above pympd, with usefull events."""
31 # these don't change while mpd is running
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,
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'}
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()
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...')
78 self
.logger
.warning('Attempted to connect when already connected.')
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...')
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'):
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
108 """Get current MPD 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'):
115 for song
in self
._client
.playlistinfo():
119 """Returns a list of all songs in library."""
120 self
.logger
.info('Listing library.')
121 if not self
.__check
_command
_ok
('listallinfo'):
123 for song
in self
._client
.listallinfo():
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'):
137 for song
in self
._client
.find(*args
):
140 def findadd(self
, *args
):
141 if not self
.__check
_command
_ok
('findadd'):
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'):
151 return self
._client
.update()
152 self
._client
.command_list_ok_begin()
154 self
._client
.update(path
)
155 list(self
._client
.command_list_end())
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'):
165 volume
= min(100, max(0, volume
))
167 self
._client
.setvol(volume
)
168 except mpd
.CommandError
, e
:
169 self
.logger
.warning('Error setting volume (probably no outputs enabled): %s.'%e)
172 """Get MPD statistics."""
173 if not self
.__check
_command
_ok
('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'):
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'):
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'):
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'):
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'):
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'):
222 self
._client
.playid(id)
224 self
._client
.playid()
227 self
.logger
.info('Pausing playback.')
228 if not self
.__check
_command
_ok
('pause'):
230 self
._client
.pause(1)
232 """Resume playing."""
233 self
.logger
.info('Resuming playback.')
234 if not self
.__check
_command
_ok
('pause'):
236 self
._client
.pause(0)
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'):
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'):
248 self
._client
.previous()
251 self
.logger
.info('Stopping playback.')
252 if not self
.__check
_command
_ok
('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'):
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'):
267 self
._client
.command_list_ok_begin()
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)
276 """Clear current playlist."""
277 self
.logger
.info('Clearing playlist.')
278 if not self
.__check
_command
_ok
('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'):
286 self
._client
.command_list_ok_begin()
288 self
.logger
.info('Adding %s to playlist'%path
)
290 self
._client
.addid(path
)
292 self
._client
.addid(path
, pos
)
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
:
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'):
305 self
._client
.moveid(source
, target
)
308 def __finish_connect(self
):
310 self
.password(self
.__password
)
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
):
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()
343 self
._cur
_song
= None
345 self
._cur
_song
= Song(song
)
346 def _update_status(self
):
347 """Get current status"""
350 ret
= self
._client
.status()
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'])
360 cur
, len = ret
['time'].split(':')
361 ret
['length'] = int(len)
362 ret
['time'] = int(cur
)
367 if not 'songid' in ret
:
371 def __check_command_ok(self
, cmd
):
373 return self
.logger
.info('Not connected.')
374 if not cmd
in self
.commands
:
375 return self
.logger
.error('Command %s not accessible'%cmd
)
378 def __update_static(self
):
379 """Update static values, called on connect/disconnect."""
381 self
.commands
= list(self
._client
.commands())
385 if self
.__check
_command
_ok
('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
394 if self
.__check
_command
_ok
('tagtypes'):
395 self
.tagtypes
= map(unicode.lower
, self
._client
.tagtypes()) + ['file']
399 if self
.__check
_command
_ok
('urlhandlers'):
400 self
.urlhandlers
= list(self
._client
.urlhandlers())
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'):
409 self
._client
.enableoutput(output_id
)
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()
425 old_status
= self
._status
426 self
._status
= self
._update
_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."""
474 state_changed
= QtCore
.pyqtSignal(bool)
477 def __init__(self
, mpclient
, name
, id, state
):
478 QtCore
.QObject
.__init
__(self
)
480 self
.mpclient
= mpclient
485 @QtCore.pyqtSlot(bool)
486 def set_state(self
, state
):
487 self
.mpclient
.set_output(self
.id, state
)
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
)