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 a list of source ids and one target position."""
299 self
.logger
.info('Moving %d to %d.'%(source
, target
))
300 if not self
.__check
_command
_ok
('moveid'):
302 self
._client
.command_list_ok_begin()
305 self
._client
.moveid(id, target
+ i
)
307 list(self
._client
.command_list_end())
310 def __finish_connect(self
):
312 self
.password(self
.__password
)
314 self
.__update
_static
()
316 if not self
.__check
_command
_ok
('listallinfo'):
317 self
.logger
.error('Don\'t have MPD read permission, diconnecting.')
318 return self
.disconnect_mpd()
320 self
.__update
_current
_song
()
321 self
._db
_update
= self
.stats()['db_update']
323 self
.connect_changed
.emit(True)
324 self
.logger
.info('Successfully connected to MPD.')
325 self
._timer
_id
= self
.startTimer(500)
326 self
._db
_timer
_id
= self
.startTimer(1000)
327 def __finish_disconnect(self
):
331 self
.killTimer(self
._timer
_id
)
332 self
._timer
_id
= None
333 if self
._db
_timer
_id
:
334 self
.killTimer(self
._db
_timer
_id
)
335 self
._db
_timer
_id
= None
336 self
._status
= dict(MPClient
._status
)
337 self
._cur
_song
= None
338 self
.__update
_static
()
339 self
.connect_changed
.emit(False)
340 self
.logger
.info('Disconnected from MPD.')
341 def __update_current_song(self
):
342 """Update the current song."""
343 song
= self
._client
.currentsong()
345 self
._cur
_song
= None
347 self
._cur
_song
= Song(song
)
348 def _update_status(self
):
349 """Get current status"""
352 ret
= self
._client
.status()
356 ret
['repeat'] = int(ret
['repeat'])
357 ret
['random'] = int(ret
['random'])
358 ret
['single'] = int(ret
['single'])
359 ret
['consume'] = int(ret
['consume'])
361 cur
, len = ret
['time'].split(':')
362 ret
['length'] = int(len)
363 ret
['time'] = int(cur
)
368 if not 'songid' in ret
:
372 def __check_command_ok(self
, cmd
):
374 return self
.logger
.info('Not connected.')
375 if not cmd
in self
.commands
:
376 return self
.logger
.error('Command %s not accessible'%cmd
)
379 def __update_static(self
):
380 """Update static values, called on connect/disconnect."""
382 self
.commands
= list(self
._client
.commands())
386 if self
.__check
_command
_ok
('outputs'):
388 for output
in self
._client
.outputs():
389 outputs
.append(AudioOutput(self
, output
['outputname'], output
['outputid'],
390 bool(output
['outputenabled'])))
391 self
.outputs
= outputs
395 if self
.__check
_command
_ok
('tagtypes'):
396 self
.tagtypes
= map(str.lower
, self
._client
.tagtypes()) + ['file']
400 if self
.__check
_command
_ok
('urlhandlers'):
401 self
.urlhandlers
= list(self
._client
.urlhandlers())
403 self
.urlhandlers
= []
405 def set_output(self
, output_id
, state
):
406 """Set audio output output_id to state (0/1). Called only by AudioOutput."""
407 if not self
.__check
_command
_ok
('enableoutput'):
410 self
._client
.enableoutput(output_id
)
412 self
._client
.disableoutput(output_id
)
414 def timerEvent(self
, event
):
415 """Check for changes since last check."""
416 if event
.timerId() == self
._db
_timer
_id
:
417 #timer for monitoring db changes
418 db_update
= self
.stats()['db_update']
419 if db_update
> self
._db
_update
:
420 self
.logger
.info('Database updated.')
421 self
._db
_update
= db_update
422 self
.db_updated
.emit()
426 old_status
= self
._status
427 self
._status
= self
._update
_status
()
430 return self
.disconnect_mpd()
432 if self
._status
['songid'] != old_status
['songid']:
433 self
.__update
_current
_song
()
434 self
.song_changed
.emit(PlaylistEntryRef(self
, self
._status
['songid']))
436 if self
._status
['time'] != old_status
['time']:
437 self
.time_changed
.emit(self
._status
['time'])
439 if self
._status
['state'] != old_status
['state']:
440 self
.state_changed
.emit(self
._status
['state'])
442 if self
._status
['volume'] != old_status
['volume']:
443 self
.volume_changed
.emit( int(self
._status
['volume']))
445 if self
._status
['repeat'] != old_status
['repeat']:
446 self
.repeat_changed
.emit(bool(self
._status
['repeat']))
448 if self
._status
['random'] != old_status
['random']:
449 self
.random_changed
.emit(bool(self
._status
['random']))
451 if self
._status
['single'] != old_status
['single']:
452 self
.single_changed
.emit(bool(self
._status
['single']))
454 if self
._status
['consume'] != old_status
['consume']:
455 self
.consume_changed
.emit(bool(self
._status
['consume']))
457 if self
._status
['playlist'] != old_status
['playlist']:
458 self
.playlist_changed
.emit()
460 outputs
= list(self
._client
.outputs())
461 for i
in range(len(outputs
)):
462 if int(outputs
[i
]['outputenabled']) != int(self
.outputs
[i
].state
):
463 self
.outputs
[i
].mpd_toggle_state()
466 class AudioOutput(QtCore
.QObject
):
467 """This class represents an MPD audio output."""
475 state_changed
= QtCore
.pyqtSignal(bool)
478 def __init__(self
, mpclient
, name
, id, state
):
479 QtCore
.QObject
.__init
__(self
)
481 self
.mpclient
= mpclient
486 @QtCore.pyqtSlot(bool)
487 def set_state(self
, state
):
488 self
.mpclient
.set_output(self
.id, state
)
491 def mpd_toggle_state(self
):
492 """This is called by mpclient to inform about output state change."""
493 self
.state
= not self
.state
494 self
.state_changed
.emit(self
.state
)