1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014 Jack Kaliko <kaliko@azylum.org>
4 # This file is part of sima
6 # sima is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # sima is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with sima. If not, see <http://www.gnu.org/licenses/>.
20 """MPD client for Sima
22 This client is built above python-musicpd a fork of python-mpd
24 # pylint: disable=C0111
26 # standard library import
27 from difflib import get_close_matches
28 from select import select
30 # third parties components
32 from musicpd import (MPDClient, MPDError, CommandError)
33 except ImportError as err:
34 from sys import exit as sexit
35 print('ERROR: missing python-musicpd?\n{0}'.format(err))
39 from .lib.simastr import SimaStr
40 from .lib.player import Player, blacklist
41 from .lib.track import Track
42 from .lib.meta import Album, Artist
43 from .utils.leven import levenshtein_ratio
46 class PlayerError(Exception):
47 """Fatal error in poller."""
49 class PlayerCommandError(PlayerError):
52 PlayerUnHandledError = MPDError # pylint: disable=C0103
55 def wrapper(*args, **kwargs):
57 if not args[0].database:
58 return func(*args, **kwargs)
59 result = func(*args, **kwargs)
63 for art in result.names:
64 if cls.database.get_bl_artist(art, add_not=True):
65 cls.log.debug('Blacklisted "{0}"'.format(art))
70 resp = Artist(name=names.pop(), mbid=result.mbid)
77 class PlayerClient(Player):
81 _fetch_item single str
82 _fetch_object single dict
83 _fetch_list list of str
84 _fetch_playlist list of str
85 _fetch_changes list of dict
86 _fetch_database list of dict
87 _fetch_songs list of dict, especially tracks
89 TODO: handle exception in command not going through _client_wrapper() (ie.
92 database = None # sima database (history, blacklist)
94 def __init__(self, host="localhost", port="6600", password=None):
96 self._comm = self._args = None
97 self._mpd = host, port, password
98 self._client = MPDClient()
99 self._client.iterate = True
102 def __getattr__(self, attr):
104 wrapper = self._execute
105 return lambda *args: wrapper(command, args)
107 def _execute(self, command, args):
108 self._write_command(command, args)
109 return self._client_wrapper()
111 def _write_command(self, command, args=None):
115 self._args.append(arg)
117 def _client_wrapper(self):
118 func = self._client.__getattr__(self._comm)
120 ans = func(*self._args)
121 # WARNING: MPDError is an ancestor class of # CommandError
122 except CommandError as err:
123 raise PlayerCommandError('MPD command error: %s' % err)
124 except (MPDError, IOError) as err:
125 raise PlayerError(err)
126 return self._track_format(ans)
128 def _track_format(self, ans):
130 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
131 "commands", "notcommands", "tagtypes", "urlhandlers",]
133 # TODO: ain't working for "sticker find" and "sticker list"
134 tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
135 "playlistsearch", "plchanges", "listplaylistinfo", "find",
136 "search", "sticker find",]
137 track_obj = ['currentsong']
138 if self._comm in tracks_listing + track_obj:
139 # pylint: disable=w0142
140 if isinstance(ans, list):
141 return [Track(**track) for track in ans]
142 elif isinstance(ans, dict):
146 def __skipped_track(self, old_curr):
147 if (self.state == 'stop'
148 or not hasattr(old_curr, 'id')
149 or not hasattr(self.current, 'id')):
151 return self.current.id != old_curr.id # pylint: disable=no-member
153 def _flush_cache(self):
155 Both flushes and instantiates _cache
157 if isinstance(self._cache, dict):
158 self.log.info('Player: Flushing cache!')
160 self.log.info('Player: Initialising cache!')
162 'artists': frozenset(),
163 'nombid_artists': frozenset(),
165 self._cache['artists'] = frozenset(self._execute('list', ['artist']))
167 self._cache['nombid_artists'] = frozenset(self._execute('list', ['artist', 'musicbrainz_artistid', '']))
169 @blacklist(track=True)
170 def find_track(self, artist, title=None):
174 tracks |= set(self.find('musicbrainz_artistid', artist.mbid,
177 tracks |= set(self.find('musicbrainz_artistid', artist.mbid))
179 for name in artist.names:
181 tracks |= set(self.find('artist', name, 'title', title))
183 tracks |= set(self.find('artist', name))
187 def search_artist(self, artist):
189 Search artists based on a fuzzy search in the media library
190 >>> art = Artist(name='the beatles', mbid=<UUID4>) # mbid optional
191 >>> bea = player.search_artist(art)
193 >>> ['The Beatles', 'Beatles', 'the beatles']
195 Returns an Artist object
199 # look for exact search w/ musicbrainz_artistid
200 exact_m = self._execute('list', ['artist', 'musicbrainz_artistid', artist.mbid])
202 [artist.add_alias(name) for name in exact_m]
205 artist = Artist(name=artist.name)
206 # then complete with fuzzy search on artist with no musicbrainz_artistid
208 # we already performed a lookup on artists with mbid set
209 # search through remaining artists
210 artists = self._cache.get('nombid_artists')
212 artists = self._cache.get('artists')
213 match = get_close_matches(artist.name, artists, 50, 0.73)
214 if not match and not found:
217 self.log.debug('found close match for "%s": %s' %
218 (artist, '/'.join(match)))
219 # Does not perform fuzzy matching on short and single word strings
220 # Only lowercased comparison
221 if ' ' not in artist.name and len(artist.name) < 8:
222 for fuzz_art in match:
223 # Regular lowered string comparison
224 if artist.name.lower() == fuzz_art.lower():
225 artist.add_alias(fuzz_art)
227 fzartist = SimaStr(artist.name)
228 for fuzz_art in match:
229 # Regular lowered string comparison
230 if artist.name.lower() == fuzz_art.lower():
232 artist.add_alias(fuzz_art)
233 if artist.name != fuzz_art:
234 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
236 # SimaStr string __eq__ (not regular string comparison here)
237 if fzartist == fuzz_art:
239 artist.add_alias(fuzz_art)
240 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
244 self.log.debug('Found: {}'.format('/'.join(list(artist.names)[:4])))
247 def fuzzy_find_track(self, artist, title):
248 # Retrieve all tracks from artist
249 all_tracks = self.find_track(artist, title)
250 # Get all titles (filter missing titles set to 'None')
251 all_artist_titles = frozenset([tr.title for tr in all_tracks
252 if tr.title is not None])
253 match = get_close_matches(title, all_artist_titles, 50, 0.78)
257 leven = levenshtein_ratio(title.lower(), title_.lower())
260 elif leven >= 0.79: # PARAM
261 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
262 (title_, title, leven))
264 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
265 (title_, title, leven))
267 return self.find('artist', artist, 'title', title_)
269 def find_album(self, artist, album):
271 Special wrapper around album search:
272 Album lookup is made through AlbumArtist/Album instead of Artist/Album
274 alb_art_search = self.find('albumartist', artist, 'album', album)
276 return alb_art_search
277 return self.find('artist', artist, 'album', album)
279 @blacklist(album=True)
280 def search_albums(self, artist):
282 Fetch all albums for "AlbumArtist" == artist
283 Filter albums returned for "artist" == artist since MPD returns any
284 album containing at least a single track for artist
287 for name in artist.names:
288 if len(artist.names) > 1:
289 self.log.debug('Searching album for aliase: "{}"'.format(name))
290 kwalbart = {'albumartist':name, 'artist':name}
291 for album in self.list('album', 'albumartist', artist):
292 if album and album not in albums:
293 albums.append(Album(name=album, **kwalbart))
294 for album in self.list('album', 'artist', artist):
295 album_trks = [trk for trk in self.find('album', album)]
296 if 'Various Artists' in [tr.albumartist for tr in album_trks]:
297 self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
299 arts = set([trk.artist for trk in album_trks])
300 if len(set(arts)) < 2: # TODO: better heuristic, use a ratio instead
301 if album not in albums:
302 albums.append(Album(name=album, **kwalbart))
303 elif album and album not in albums:
304 self.log.debug('"{0}" probably not an album of "{1}"'.format(
305 album, artist) + '({0})'.format('/'.join(arts)))
311 self.send_idle('database', 'playlist', 'player', 'options')
312 select([self._client], [], [], 60)
313 ret = self.fetch_idle()
314 if self.__skipped_track(curr):
315 ret.append('skipped')
316 if 'database' in ret:
319 except (MPDError, IOError) as err:
320 raise PlayerError("Couldn't init idle: %s" % err)
323 """Clean blocking event (idle) and pending commands
325 if 'idle' in self._client._pending:
326 self._client.noidle()
327 elif self._client._pending:
328 self.log.warning('pending commands: {}'.format(self._client._pending))
330 def remove(self, position=0):
331 self.delete(position)
333 def add(self, track):
334 """Overriding MPD's add method to accept add signature with a Track
336 self._execute('add', [track.file])
340 return self._cache.get('artists')
344 return str(self.status().get('state'))
348 return self.currentsong()
354 return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
359 Override deprecated MPD playlist command
361 return self.playlistinfo()
364 host, port, password = self._mpd
367 self._client.connect(host, port)
369 # Catch socket errors
370 except IOError as err:
371 raise PlayerError('Could not connect to "%s:%s": %s' %
372 (host, port, err.strerror))
374 # Catch all other possible errors
375 # ConnectionError and ProtocolError are always fatal. Others may not
376 # be, but we don't know how to handle them here, so treat them as if
377 # they are instead of ignoring them.
378 except MPDError as err:
379 raise PlayerError('Could not connect to "%s:%s": %s' %
384 self._client.password(password)
386 # Catch errors with the password command (e.g., wrong password)
387 except CommandError as err:
388 raise PlayerError("Could not connect to '%s': "
389 "password command failed: %s" %
392 # Catch all other possible errors
393 except (MPDError, IOError) as err:
394 raise PlayerError("Could not connect to '%s': "
395 "error with password command: %s" %
397 # Controls we have sufficient rights
398 needed_cmds = ['status', 'stats', 'add', 'find', \
399 'search', 'currentsong', 'ping']
401 available_cmd = self._client.commands()
402 for nddcmd in needed_cmds:
403 if nddcmd not in available_cmd:
405 raise PlayerError('Could connect to "%s", '
406 'but command "%s" not available' %
409 # Controls use of MusicBrainzIdentifier
411 if 'MUSICBRAINZ_ARTISTID' not in self._client.tagtypes():
412 self.log.warning('Use of MusicBrainzIdentifier is set but MPD is '
413 'not providing related metadata')
414 self.log.info(self._client.tagtypes())
415 self.log.warning('Disabling MusicBrainzIdentifier')
416 Artist.use_mbid = False
418 self.log.warning('Use of MusicBrainzIdentifier disabled!')
419 self.log.info('Consider using MusicBrainzIdentifier for your music library')
422 def disconnect(self):
423 # Try to tell MPD we're closing the connection first
425 self._client.noidle()
427 # If that fails, don't worry, just ignore it and disconnect
428 except (MPDError, IOError):
431 self._client.disconnect()
432 # Disconnecting failed, so use a new client object instead
433 # This should never happen. If it does, something is seriously broken,
434 # and the client object shouldn't be trusted to be re-used.
435 except (MPDError, IOError):
436 self._client = MPDClient()
439 # vim: ai ts=4 sw=4 sts=4 expandtab