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
26 class MPClient(QtCore
.QObject
):
27 """This class offers another layer above pympd, with usefull events."""
32 _status
= {'volume' : 0, 'repeat' : 0, 'random' : 0,
33 'songid' : 0, 'playlist' : 0, 'playlistlength' : 0,
34 'time' : 0, 'length' : 0, 'xfade' : 0,
35 'state' : 'stop', 'single' : 0,
39 _timer_id
= None #for querying status changes
40 _db_timer_id
= None #for querying db updates
41 _db_update
= None #time of last db update
43 _retr_mutex
= QtCore
.QMutex()
48 QtCore
.QObject
.__init
__(self
)
50 self
._cur
_playlist
= []
52 self
._status
= dict(MPClient
._status
)
53 self
.logger
= logging
.getLogger('mpclient')
55 def connect_mpd(self
, host
, port
, password
= None):
56 """Connect to MPD@host:port, optionally using password.
57 Returns True at success, False otherwise."""
59 self
.logger
.info('Connecting to MPD...')
61 self
.logger
.warning('Attempted to connect when already connected.')
65 self
._client
= mpd
.MPDClient()
66 self
._client
.connect(host
, port
)
67 except socket
.error
, e
:
68 self
.logger
.error('Socket error: %s.'%e)
73 self
.password(password
)
75 self
._commands
= self
._retrieve
(self
._client
.commands
)
77 if not self
._check
_command
_ok
('listallinfo'):
78 self
.logger
.error('Don\'t have MPD read permission, diconnecting.')
79 return self
.disconnect_mpd()
82 self
._update
_playlist
()
83 self
._update
_current
_song
()
85 self
.emit(QtCore
.SIGNAL('connected'))
86 self
.logger
.info('Successfully connected to MPD.')
87 self
._timer
_id
= self
.startTimer(500)
88 self
._db
_timer
_id
= self
.startTimer(10000)
90 def disconnect_mpd(self
):
91 """Disconnect from MPD."""
92 self
.logger
.info('Disconnecting from MPD...')
96 self
._client
.disconnect()
97 except (mpd
.ConnectionError
, socket
.error
):
101 self
.logger
.warning('Attempted to disconnect when not connected.')
104 self
.killTimer(self
._timer
_id
)
105 self
._timer
_id
= None
106 if self
._db
_timer
_id
:
107 self
.killTimer(self
._db
_timer
_id
)
108 self
._db
_timer
_id
= None
109 self
._status
= dict(MPClient
._status
)
110 self
._cur
_song
= None
112 self
._cur
_playlist
= []
114 self
.emit(QtCore
.SIGNAL('disconnected'))
115 self
.logger
.info('Disconnected from MPD.')
116 def password(self
, password
):
117 """Use the password to authenticate with MPD."""
118 self
.logger
.info('Authenticating with MPD.')
119 if not self
._check
_command
_ok
('password'):
122 self
._client
.password(password
)
123 self
.logger
.info('Successfully authenticated')
124 self
._commands
= self
._retrieve
(self
._client
.commands
)
125 except mpd
.CommandError
:
126 self
.logger
.error('Incorrect MPD password.')
127 def is_connected(self
):
128 """Returns True if connected to MPD, False otherwise."""
129 return self
._client
!= None
132 """Get current MPD status."""
135 """Returns the current playlist."""
136 return self
._cur
_playlist
138 """Returns current library."""
140 def current_song(self
):
141 """Returns the current playing song."""
142 return self
._cur
_song
143 def is_playing(self
):
144 """Returns True if MPD is playing, False otherwise."""
145 return self
._status
['state'] == 'play'
147 def update_db(self
, paths
= None):
148 """Starts MPD database update."""
149 self
.logger
.info('Updating database %s'%(paths
if paths
else '.'))
150 if not self
._check
_command
_ok
('update'):
153 return self
._client
.update()
154 self
._client
.command_list_ok_begin()
156 self
._client
.update(path
)
157 self
._client
.command_list_end()
160 """Returns an array of configured MPD audio outputs."""
162 return self
._retrieve
(self
._client
.outputs
)
165 def set_output(self
, output_id
, state
):
166 """Set audio output output_id to state (0/1)."""
167 if not self
._check
_command
_ok
('enableoutput'):
170 self
._client
.enableoutput(output_id
)
172 self
._client
.disableoutput(output_id
)
175 """Get current volume."""
176 return int(self
._status
['volume'])
177 def set_volume(self
, volume
):
178 """Set volume to volume."""
179 self
.logger
.info('Setting volume to %d.'%volume
)
180 if not self
._check
_command
_ok
('setvol'):
182 volume
= min(100, max(0, volume
))
183 self
._client
.setvol(volume
)
185 def urlhandlers(self
):
186 """Returns an array of available url handlers."""
190 return self
._client
.urlhandlers()
192 """Returns a list of supported tags."""
193 if not self
._check
_command
_ok
('tagtypes'):
196 return self
._retrieve
(self
._client
.tagtypes
)
198 """List all currently available MPD commands."""
199 return self
._commands
201 """Get MPD statistics."""
202 return self
._retrieve
(self
._client
.stats
)
204 def repeat(self
, val
):
205 """Set repeat playlist to val (True/False)."""
206 self
.logger
.info('Setting repeat to %d.'%val
)
207 if not self
._check
_command
_ok
('repeat'):
209 if isinstance(val
, bool):
210 val
= 1 if val
else 0
211 self
._client
.repeat(val
)
212 def random(self
, val
):
213 """Set random playback to val (True, False)."""
214 self
.logger
.info('Setting random to %d.'%val
)
215 if not self
._check
_command
_ok
('random'):
217 if isinstance(val
, bool):
218 val
= 1 if val
else 0
219 self
._client
.random(val
)
220 def crossfade(self
, time
):
221 """Set crossfading between songs."""
222 self
.logger
.info('Setting crossfade to %d'%time
)
223 if not self
._check
_command
_ok
('crossfade'):
225 self
._client
.crossfade(time
)
226 def single(self
, val
):
227 """Set single playback to val (True, False)"""
228 self
.logger
.info('Setting single to %d.'%val
)
229 if not self
._check
_command
_ok
('single'):
231 if isinstance(val
, bool):
232 val
= 1 if val
else 0
233 self
._client
.single(val
)
234 def consume(self
, val
):
235 """Set consume mode to val (True, False)"""
236 self
.logger
.info('Setting consume to %d.'%val
)
237 if not self
._check
_command
_ok
('consume'):
239 if isinstance(val
, bool):
240 val
= 1 if val
else 0
241 self
._client
.consume(val
)
243 def play(self
, id = None):
244 """Play song with ID id or next song if id is None."""
245 self
.logger
.info('Starting playback %s.'%('of id %s'%(id) if id else ''))
246 if not self
._check
_command
_ok
('play'):
249 self
._client
.playid(id)
251 self
._client
.playid()
254 self
.logger
.info('Pausing playback.')
255 if not self
._check
_command
_ok
('pause'):
257 self
._client
.pause(1)
259 """Resume playing."""
260 self
.logger
.info('Resuming playback.')
261 if not self
._check
_command
_ok
('pause'):
263 self
._client
.pause(0)
265 """Move on to the next song in the playlist."""
266 self
.logger
.info('Skipping to next song.')
267 if not self
._check
_command
_ok
('next'):
271 """Move back to the previous song in the playlist."""
272 self
.logger
.info('Moving to previous song.')
273 if not self
._check
_command
_ok
('previous'):
275 self
._client
.previous()
278 self
.logger
.info('Stopping playback.')
279 if not self
._check
_command
_ok
('stop'):
282 def seek(self
, time
):
283 """Seek to time (in seconds)."""
284 self
.logger
.info('Seeking to %d.'%time
)
285 if not self
._check
_command
_ok
('seekid'):
287 if self
._status
['songid'] > 0:
288 self
._client
.seekid(self
._status
['songid'], time
)
290 def delete(self
, list):
291 """Remove all song IDs in list from the playlist."""
292 if not self
._check
_command
_ok
('deleteid'):
294 self
._client
.command_list_ok_begin()
296 self
.logger
.info('Deleting id %d from playlist.'%id)
297 self
._client
.deleteid(id)
298 self
._client
.command_list_end()
300 """Clear current playlist."""
301 self
.logger
.info('Clearing playlist.')
302 if not self
._check
_command
_ok
('clear'):
305 def add(self
, paths
):
306 """Add all files in paths to the current playlist."""
307 if not self
._check
_command
_ok
('addid'):
310 self
._client
.command_list_ok_begin()
313 self
.logger
.info('Adding %s to playlist'%path
)
314 self
._client
.addid(path
.encode('utf-8'))
315 ret
= self
._client
.command_list_end()
316 except mpd
.CommandError
, e
:
317 self
.logger
.error('Error adding files: %s.'%e)
318 self
._update
_playlist
()
319 if self
._status
['state'] == 'stop' and ret
:
321 def move(self
, source
, target
):
322 """Move the songs in playlist. Takes a list of source ids and one target position."""
323 self
.logger
.info('Moving %d to %d.'%(source
, target
))
324 if not self
._check
_command
_ok
('moveid'):
326 self
._client
.command_list_ok_begin()
329 self
._client
.moveid(id, target
+ i
)
331 self
._client
.command_list_end()
333 def _retrieve(self
, method
):
334 """Makes sure only one call is made at a time to MPD."""
335 self
._retr
_mutex
.lock()
339 self
.logger
.error('Connection to MPD broken.')
340 self
._retr
_mutex
.unlock()
341 self
.disconnect_mpd()
344 self
._retr
_mutex
.unlock()
346 def _update_lib(self
):
347 """Update the cached library."""
348 self
._cur
_lib
= self
._array
_to
_song
_array
(self
._retrieve
(self
._client
.listallinfo
))
350 for song
in self
._cur
_lib
:
351 song
._data
['id'] = id
353 def _update_playlist(self
):
354 """Update the cached playlist."""
355 self
._cur
_playlist
= self
._array
_to
_song
_array
(self
._retrieve
(self
._client
.playlistinfo
))
356 def _array_to_song_array(self
, array
):
357 """Convert an array to an array of Songs."""
358 return map(lambda entry
: Song(entry
)
359 , filter(lambda entry
: not('directory' in entry
), array
)
361 def _update_current_song(self
):
362 """Update the current song."""
363 song
= self
._retrieve
(self
._client
.currentsong
)
365 self
._cur
_song
= None
367 self
._cur
_song
= Song(song
)
368 def _update_status(self
):
369 """Get current status"""
372 ret
= self
._retrieve
(self
._client
.status
)
376 ret
['repeat'] = int(ret
['repeat'])
377 ret
['random'] = int(ret
['random'])
378 ret
['single'] = int(ret
['single'])
379 ret
['consume'] = int(ret
['consume'])
381 cur
, len = ret
['time'].split(':')
382 ret
['length'] = int(len)
383 ret
['time'] = int(cur
)
388 if not 'songid' in ret
:
392 def _check_command_ok(self
, cmd
):
394 return self
.logger
.error('Not connected.')
395 if not cmd
in self
._commands
:
396 return self
.logger
.error('Command %s not accessible'%cmd
)
399 def timerEvent(self
, event
):
400 """Check for changes since last check."""
401 if event
.timerId
== self
._db
_timer
_id
:
402 #timer for monitoring db changes
403 db_update
= self
.stats()['db_update']
404 if db_update
> self
._db
_update
:
405 self
.logger
.info('Database updated.')
406 self
._db
_update
= db_update
407 self
.emit(QtCore
.SIGNAL('db_updated'))
411 old_status
= self
._status
412 self
._status
= self
._update
_status
()
415 return self
.disconnect_mpd()
417 self
._update
_current
_song
()
419 if self
._status
['songid'] != old_status
['songid']:
420 self
.emit(QtCore
.SIGNAL('song_changed'), self
._status
['songid'])
422 if self
._status
['time'] != old_status
['time']:
423 self
.emit(QtCore
.SIGNAL('time_changed'), self
._status
['time'])
425 if self
._status
['state'] != old_status
['state']:
426 self
.emit(QtCore
.SIGNAL('state_changed'), self
._status
['state'])
428 if self
._status
['volume'] != old_status
['volume']:
429 self
.emit(QtCore
.SIGNAL('volume_changed'), int(self
._status
['volume']))
431 if self
._status
['repeat'] != old_status
['repeat']:
432 self
.emit(QtCore
.SIGNAL('repeat_changed'), bool(self
._status
['repeat']))
434 if self
._status
['random'] != old_status
['random']:
435 self
.emit(QtCore
.SIGNAL('random_changed'), bool(self
._status
['random']))
437 if self
._status
['single'] != old_status
['single']:
438 self
.emit(QtCore
.SIGNAL('single_changed'), bool(self
._status
['single']))
440 if self
._status
['consume'] != old_status
['consume']:
441 self
.emit(QtCore
.SIGNAL('consume_changed'), bool(self
._status
['consume']))
443 if self
._status
['playlist'] != old_status
['playlist']:
444 self
._update
_playlist
()
445 self
.emit(QtCore
.SIGNAL('playlist_changed'))