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
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()
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...')
76 self
.logger
.warning('Attempted to connect when already connected.')
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...')
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'):
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
107 """Get current MPD 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'):
114 for song
in self
._client
.playlistinfo():
118 """Returns a list of all songs in library."""
119 self
.logger
.info('Listing library.')
120 if not self
.__check
_command
_ok
('listallinfo'):
122 for song
in self
._client
.listallinfo():
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'):
136 for song
in self
._client
.find(*args
):
139 def findadd(self
, *args
):
140 if not self
.__check
_command
_ok
('findadd'):
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'):
150 return self
._client
.update()
151 self
._client
.command_list_ok_begin()
153 self
._client
.update(path
)
154 list(self
._client
.command_list_end())
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'):
164 volume
= min(100, max(0, volume
))
166 self
._client
.setvol(volume
)
167 except mpd
.CommandError
, e
:
168 self
.logger
.warning('Error setting volume (probably no outputs enabled): %s.'%e)
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'):
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'):
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'):
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'):
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'):
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'):
219 self
._client
.playid(id)
221 self
._client
.playid()
224 self
.logger
.info('Pausing playback.')
225 if not self
.__check
_command
_ok
('pause'):
227 self
._client
.pause(1)
229 """Resume playing."""
230 self
.logger
.info('Resuming playback.')
231 if not self
.__check
_command
_ok
('pause'):
233 self
._client
.pause(0)
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'):
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'):
245 self
._client
.previous()
248 self
.logger
.info('Stopping playback.')
249 if not self
.__check
_command
_ok
('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'):
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'):
264 self
._client
.command_list_ok_begin()
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)
273 """Clear current playlist."""
274 self
.logger
.info('Clearing playlist.')
275 if not self
.__check
_command
_ok
('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'):
283 self
._client
.command_list_ok_begin()
286 self
.logger
.info('Adding %s to playlist'%path
)
288 self
._client
.addid(path
.encode('utf-8'))
290 self
._client
.addid(path
.encode('utf-8'), pos
)
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
:
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'):
302 self
._client
.moveid(source
, target
)
305 def __finish_connect(self
):
307 self
.password(self
.__password
)
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
):
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()
340 self
._cur
_song
= None
342 self
._cur
_song
= Song(song
)
343 def _update_status(self
):
344 """Get current status"""
347 ret
= self
._client
.status()
351 ret
['repeat'] = int(ret
['repeat'])
352 ret
['random'] = int(ret
['random'])
353 ret
['single'] = int(ret
['single'])
354 ret
['consume'] = int(ret
['consume'])
356 cur
, len = ret
['time'].split(':')
357 ret
['length'] = int(len)
358 ret
['time'] = int(cur
)
363 if not 'songid' in ret
:
367 def __check_command_ok(self
, cmd
):
369 return self
.logger
.info('Not connected.')
370 if not cmd
in self
.commands
:
371 return self
.logger
.error('Command %s not accessible'%cmd
)
374 def __update_static(self
):
375 """Update static values, called on connect/disconnect."""
377 self
.commands
= list(self
._client
.commands())
381 if self
.__check
_command
_ok
('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
390 if self
.__check
_command
_ok
('tagtypes'):
391 self
.tagtypes
= map(str.lower
, self
._client
.tagtypes()) + ['file']
395 if self
.__check
_command
_ok
('urlhandlers'):
396 self
.urlhandlers
= list(self
._client
.urlhandlers())
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'):
405 self
._client
.enableoutput(output_id
)
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()
421 old_status
= self
._status
422 self
._status
= self
._update
_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."""
470 state_changed
= QtCore
.pyqtSignal(bool)
473 def __init__(self
, mpclient
, name
, id, state
):
474 QtCore
.QObject
.__init
__(self
)
476 self
.mpclient
= mpclient
481 @QtCore.pyqtSlot(bool)
482 def set_state(self
, state
):
483 self
.mpclient
.set_output(self
.id, state
)
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
)