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')) #should be removed
86 self
.emit(QtCore
.SIGNAL('connect_changed'), True)
87 self
.logger
.info('Successfully connected to MPD.')
88 self
._timer
_id
= self
.startTimer(500)
89 self
._db
_timer
_id
= self
.startTimer(10000)
91 def disconnect_mpd(self
):
92 """Disconnect from MPD."""
93 self
.logger
.info('Disconnecting from MPD...')
97 self
._client
.disconnect()
98 except (mpd
.ConnectionError
, socket
.error
):
102 self
.logger
.warning('Attempted to disconnect when not connected.')
105 self
.killTimer(self
._timer
_id
)
106 self
._timer
_id
= None
107 if self
._db
_timer
_id
:
108 self
.killTimer(self
._db
_timer
_id
)
109 self
._db
_timer
_id
= None
110 self
._status
= dict(MPClient
._status
)
111 self
._cur
_song
= None
113 self
._cur
_playlist
= []
115 self
.emit(QtCore
.SIGNAL('disconnected')) #should be removed
116 self
.emit(QtCore
.SIGNAL('connect_changed'), False)
117 self
.logger
.info('Disconnected from MPD.')
118 def password(self
, password
):
119 """Use the password to authenticate with MPD."""
120 self
.logger
.info('Authenticating with MPD.')
121 if not self
._check
_command
_ok
('password'):
124 self
._client
.password(password
)
125 self
.logger
.info('Successfully authenticated')
126 self
._commands
= self
._retrieve
(self
._client
.commands
)
127 except mpd
.CommandError
:
128 self
.logger
.error('Incorrect MPD password.')
129 def is_connected(self
):
130 """Returns True if connected to MPD, False otherwise."""
131 return self
._client
!= None
134 """Get current MPD status."""
137 """Returns the current playlist."""
138 return self
._cur
_playlist
140 """Returns current library."""
142 def current_song(self
):
143 """Returns the current playing song."""
144 return self
._cur
_song
145 def is_playing(self
):
146 """Returns True if MPD is playing, False otherwise."""
147 return self
._status
['state'] == 'play'
149 def update_db(self
, paths
= None):
150 """Starts MPD database update."""
151 self
.logger
.info('Updating database %s'%(paths
if paths
else '.'))
152 if not self
._check
_command
_ok
('update'):
155 return self
._client
.update()
156 self
._client
.command_list_ok_begin()
158 self
._client
.update(path
)
159 self
._client
.command_list_end()
162 """Returns an array of configured MPD audio outputs."""
164 return self
._retrieve
(self
._client
.outputs
)
167 def set_output(self
, output_id
, state
):
168 """Set audio output output_id to state (0/1)."""
169 if not self
._check
_command
_ok
('enableoutput'):
172 self
._client
.enableoutput(output_id
)
174 self
._client
.disableoutput(output_id
)
177 """Get current volume."""
178 return int(self
._status
['volume'])
179 def set_volume(self
, volume
):
180 """Set volume to volume."""
181 self
.logger
.info('Setting volume to %d.'%volume
)
182 if not self
._check
_command
_ok
('setvol'):
184 volume
= min(100, max(0, volume
))
185 self
._client
.setvol(volume
)
187 def urlhandlers(self
):
188 """Returns an array of available url handlers."""
192 return self
._client
.urlhandlers()
194 """Returns a list of supported tags."""
195 if not self
._check
_command
_ok
('tagtypes'):
198 return self
._retrieve
(self
._client
.tagtypes
)
200 """List all currently available MPD commands."""
201 return self
._commands
203 """Get MPD statistics."""
204 return self
._retrieve
(self
._client
.stats
)
206 def repeat(self
, val
):
207 """Set repeat playlist to val (True/False)."""
208 self
.logger
.info('Setting repeat to %d.'%val
)
209 if not self
._check
_command
_ok
('repeat'):
211 if isinstance(val
, bool):
212 val
= 1 if val
else 0
213 self
._client
.repeat(val
)
214 def random(self
, val
):
215 """Set random playback to val (True, False)."""
216 self
.logger
.info('Setting random to %d.'%val
)
217 if not self
._check
_command
_ok
('random'):
219 if isinstance(val
, bool):
220 val
= 1 if val
else 0
221 self
._client
.random(val
)
222 def crossfade(self
, time
):
223 """Set crossfading between songs."""
224 self
.logger
.info('Setting crossfade to %d'%time
)
225 if not self
._check
_command
_ok
('crossfade'):
227 self
._client
.crossfade(time
)
228 def single(self
, val
):
229 """Set single playback to val (True, False)"""
230 self
.logger
.info('Setting single to %d.'%val
)
231 if not self
._check
_command
_ok
('single'):
233 if isinstance(val
, bool):
234 val
= 1 if val
else 0
235 self
._client
.single(val
)
236 def consume(self
, val
):
237 """Set consume mode to val (True, False)"""
238 self
.logger
.info('Setting consume to %d.'%val
)
239 if not self
._check
_command
_ok
('consume'):
241 if isinstance(val
, bool):
242 val
= 1 if val
else 0
243 self
._client
.consume(val
)
245 def play(self
, id = None):
246 """Play song with ID id or next song if id is None."""
247 self
.logger
.info('Starting playback %s.'%('of id %s'%(id) if id else ''))
248 if not self
._check
_command
_ok
('play'):
251 self
._client
.playid(id)
253 self
._client
.playid()
256 self
.logger
.info('Pausing playback.')
257 if not self
._check
_command
_ok
('pause'):
259 self
._client
.pause(1)
261 """Resume playing."""
262 self
.logger
.info('Resuming playback.')
263 if not self
._check
_command
_ok
('pause'):
265 self
._client
.pause(0)
267 """Move on to the next song in the playlist."""
268 self
.logger
.info('Skipping to next song.')
269 if not self
._check
_command
_ok
('next'):
273 """Move back to the previous song in the playlist."""
274 self
.logger
.info('Moving to previous song.')
275 if not self
._check
_command
_ok
('previous'):
277 self
._client
.previous()
280 self
.logger
.info('Stopping playback.')
281 if not self
._check
_command
_ok
('stop'):
284 def seek(self
, time
):
285 """Seek to time (in seconds)."""
286 self
.logger
.info('Seeking to %d.'%time
)
287 if not self
._check
_command
_ok
('seekid'):
289 if self
._status
['songid'] > 0:
290 self
._client
.seekid(self
._status
['songid'], time
)
292 def delete(self
, list):
293 """Remove all song IDs in list from the playlist."""
294 if not self
._check
_command
_ok
('deleteid'):
296 self
._client
.command_list_ok_begin()
298 self
.logger
.info('Deleting id %d from playlist.'%id)
299 self
._client
.deleteid(id)
300 self
._client
.command_list_end()
302 """Clear current playlist."""
303 self
.logger
.info('Clearing playlist.')
304 if not self
._check
_command
_ok
('clear'):
307 def add(self
, paths
):
308 """Add all files in paths to the current playlist."""
309 if not self
._check
_command
_ok
('addid'):
312 self
._client
.command_list_ok_begin()
315 self
.logger
.info('Adding %s to playlist'%path
)
316 self
._client
.addid(path
.encode('utf-8'))
317 ret
= self
._client
.command_list_end()
318 except mpd
.CommandError
, e
:
319 self
.logger
.error('Error adding files: %s.'%e)
320 self
._update
_playlist
()
321 if self
._status
['state'] == 'stop' and ret
:
323 def move(self
, source
, target
):
324 """Move the songs in playlist. Takes a list of source ids and one target position."""
325 self
.logger
.info('Moving %d to %d.'%(source
, target
))
326 if not self
._check
_command
_ok
('moveid'):
328 self
._client
.command_list_ok_begin()
331 self
._client
.moveid(id, target
+ i
)
333 self
._client
.command_list_end()
335 def _retrieve(self
, method
):
336 """Makes sure only one call is made at a time to MPD."""
337 self
._retr
_mutex
.lock()
341 self
.logger
.error('Connection to MPD broken.')
342 self
._retr
_mutex
.unlock()
343 self
.disconnect_mpd()
346 self
._retr
_mutex
.unlock()
348 def _update_lib(self
):
349 """Update the cached library."""
350 self
._cur
_lib
= self
._array
_to
_song
_array
(self
._retrieve
(self
._client
.listallinfo
))
352 for song
in self
._cur
_lib
:
353 song
._data
['id'] = id
355 def _update_playlist(self
):
356 """Update the cached playlist."""
357 self
._cur
_playlist
= self
._array
_to
_song
_array
(self
._retrieve
(self
._client
.playlistinfo
))
358 def _array_to_song_array(self
, array
):
359 """Convert an array to an array of Songs."""
360 return map(lambda entry
: Song(entry
)
361 , filter(lambda entry
: not('directory' in entry
), array
)
363 def _update_current_song(self
):
364 """Update the current song."""
365 song
= self
._retrieve
(self
._client
.currentsong
)
367 self
._cur
_song
= None
369 self
._cur
_song
= Song(song
)
370 def _update_status(self
):
371 """Get current status"""
374 ret
= self
._retrieve
(self
._client
.status
)
378 ret
['repeat'] = int(ret
['repeat'])
379 ret
['random'] = int(ret
['random'])
380 ret
['single'] = int(ret
['single'])
381 ret
['consume'] = int(ret
['consume'])
383 cur
, len = ret
['time'].split(':')
384 ret
['length'] = int(len)
385 ret
['time'] = int(cur
)
390 if not 'songid' in ret
:
394 def _check_command_ok(self
, cmd
):
396 return self
.logger
.error('Not connected.')
397 if not cmd
in self
._commands
:
398 return self
.logger
.error('Command %s not accessible'%cmd
)
401 def timerEvent(self
, event
):
402 """Check for changes since last check."""
403 if event
.timerId
== self
._db
_timer
_id
:
404 #timer for monitoring db changes
405 db_update
= self
.stats()['db_update']
406 if db_update
> self
._db
_update
:
407 self
.logger
.info('Database updated.')
408 self
._db
_update
= db_update
409 self
.emit(QtCore
.SIGNAL('db_updated'))
413 old_status
= self
._status
414 self
._status
= self
._update
_status
()
417 return self
.disconnect_mpd()
419 self
._update
_current
_song
()
421 if self
._status
['songid'] != old_status
['songid']:
422 self
.emit(QtCore
.SIGNAL('song_changed'), self
._status
['songid'])
424 if self
._status
['time'] != old_status
['time']:
425 self
.emit(QtCore
.SIGNAL('time_changed'), self
._status
['time'])
427 if self
._status
['state'] != old_status
['state']:
428 self
.emit(QtCore
.SIGNAL('state_changed'), self
._status
['state'])
430 if self
._status
['volume'] != old_status
['volume']:
431 self
.emit(QtCore
.SIGNAL('volume_changed'), int(self
._status
['volume']))
433 if self
._status
['repeat'] != old_status
['repeat']:
434 self
.emit(QtCore
.SIGNAL('repeat_changed'), bool(self
._status
['repeat']))
436 if self
._status
['random'] != old_status
['random']:
437 self
.emit(QtCore
.SIGNAL('random_changed'), bool(self
._status
['random']))
439 if self
._status
['single'] != old_status
['single']:
440 self
.emit(QtCore
.SIGNAL('single_changed'), bool(self
._status
['single']))
442 if self
._status
['consume'] != old_status
['consume']:
443 self
.emit(QtCore
.SIGNAL('consume_changed'), bool(self
._status
['consume']))
445 if self
._status
['playlist'] != old_status
['playlist']:
446 self
._update
_playlist
()
447 self
.emit(QtCore
.SIGNAL('playlist_changed'))