1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2009-2021 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/>.
19 # standard library import
20 from difflib import get_close_matches
21 from functools import wraps
22 from logging import getLogger
23 from select import select
26 from musicpd import MPDClient, MPDError as PlayerError
30 from .lib.meta import Meta, Artist, Album
31 from .lib.track import Track
32 from .lib.simastr import SimaStr
33 from .utils.leven import levenshtein_ratio
38 def wrapper(*args, **kwargs):
41 return func(*args, **kwargs)
42 result = func(*args, **kwargs)
45 for art in result.names:
46 artist = Artist(name=art, mbid=result.mbid)
47 if cls.database.get_bl_artist(artist, add=False):
48 cls.log.debug('Artist in blocklist: %s', artist)
54 def set_artist_mbid(func):
55 def wrapper(*args, **kwargs):
57 result = func(*args, **kwargs)
59 if result and not result.mbid:
60 mbid = cls._find_musicbrainz_artistid(result)
61 artist = Artist(name=result.name, mbid=mbid)
62 artist.add_alias(result)
68 def tracks_wrapper(func):
69 """Convert plain track mapping as returned by MPDClient into :py:obj:`sima.lib.track.Track`
70 objects. This decorator accepts single track or list of tracks as input.
73 def wrapper(*args, **kwargs):
74 ret = func(*args, **kwargs)
75 if isinstance(ret, dict):
77 return [Track(**t) for t in ret]
84 Player instance inheriting from MPDClient (python-musicpd).
86 Some methods are overridden to format objects as :py:obj:`sima.lib.track.Track` for
87 instance, other are calling parent class directly through super().
92 * find methods are looking for exact match of the object provided
93 attributes in MPD music library
94 * search methods are looking for exact match + fuzzy match.
96 needed_cmds = ['status', 'stats', 'add', 'find',
97 'search', 'currentsong', 'ping']
98 needed_tags = {'Artist', 'Album', 'AlbumArtist', 'Title', 'Track'}
99 needed_mbid_tags = {'MUSICBRAINZ_ARTISTID', 'MUSICBRAINZ_ALBUMID',
100 'MUSICBRAINZ_ALBUMARTISTID', 'MUSICBRAINZ_TRACKID'}
101 MPD_supported_tags = {'Artist', 'ArtistSort', 'Album', 'AlbumSort', 'AlbumArtist',
102 'AlbumArtistSort', 'Title', 'Track', 'Name', 'Genre',
103 'Date', 'OriginalDate', 'Composer', 'Performer',
104 'Conductor', 'Work', 'Grouping', 'Disc', 'Label',
105 'MUSICBRAINZ_ARTISTID', 'MUSICBRAINZ_ALBUMID',
106 'MUSICBRAINZ_ALBUMARTISTID', 'MUSICBRAINZ_TRACKID',
107 'MUSICBRAINZ_RELEASETRACKID', 'MUSICBRAINZ_WORKID'}
110 def __init__(self, config):
112 self.socket_timeout = 10
114 self.log = getLogger('sima')
118 # ######### Overriding MPDClient ###########
119 def __getattr__(self, cmd):
120 """Wrapper around MPDClient calls for abstract overriding"""
121 track_wrapped = {'currentsong', 'find', 'playlistinfo', }
123 if cmd in track_wrapped:
124 return tracks_wrapper(super().__getattr__(cmd))
125 return super().__getattr__(cmd)
126 except OSError as err: # socket errors
127 raise PlayerError(err) from err
129 def disconnect(self):
130 """Overriding explicitly MPDClient.disconnect()"""
135 """Overriding explicitly MPDClient.connect()"""
136 mpd_config = self.config['MPD']
137 # host, port, password
138 host = mpd_config.get('host')
139 port = mpd_config.get('port')
140 password = mpd_config.get('password', fallback=None)
143 super().connect(host, port)
144 # Catch socket errors
145 except OSError as err:
146 raise PlayerError(f'Could not connect to "{host}:{port}": {err.strerror}'
148 # Catch all other possible errors
149 # ConnectionError and ProtocolError are always fatal. Others may not
150 # be, but we don't know how to handle them here, so treat them as if
151 # they are instead of ignoring them.
152 except PlayerError as err:
153 raise PlayerError(f'Could not connect to "{host}:{port}": {err}') from err
156 self.password(password)
157 except OSError as err:
158 raise PlayerError(f"Could not connect to '{host}': {err}") from err
159 # Controls we have sufficient rights
160 available_cmd = self.commands()
161 for cmd in MPD.needed_cmds:
162 if cmd not in available_cmd:
164 raise PlayerError(f'Could connect to "{host}", but command "{cmd}" not available')
165 self.tagtypes_clear()
166 for tag in MPD.needed_tags:
167 self.tagtypes_enable(tag)
168 ltt = set(map(str.lower, self.tagtypes()))
169 needed_tags = set(map(str.lower, MPD.needed_tags))
170 if len(needed_tags & ltt) != len(MPD.needed_tags):
171 self.log.warning('MPD exposes: %s', ltt)
172 self.log.warning('Tags needed: %s', needed_tags)
173 raise PlayerError('Missing mandatory metadata!')
174 for tag in MPD.needed_mbid_tags:
175 self.tagtypes_enable(tag)
176 # Controls use of MusicBrainzIdentifier
177 if self.config.getboolean('sima', 'musicbrainzid'):
178 ltt = set(self.tagtypes())
179 if len(MPD.needed_mbid_tags & ltt) != len(MPD.needed_mbid_tags):
180 self.log.warning('Use of MusicBrainzIdentifier is set but MPD '
181 'is not providing related metadata')
183 self.log.warning('Disabling MusicBrainzIdentifier')
184 self.use_mbid = Meta.use_mbid = False
186 self.log.debug('Available metadata: %s', ltt)
187 self.use_mbid = Meta.use_mbid = True
189 self.log.warning('Use of MusicBrainzIdentifier disabled!')
190 self.log.info('Consider using MusicBrainzIdentifier for your music library')
191 self.use_mbid = Meta.use_mbid = False
192 # TODO: Why do I need to intercept OSError here?
193 # why is it not wrapped in PlayerError in __getattr__?
194 # (cf. commit message for more)
197 except OSError as err:
198 raise PlayerError(f'Error during cache init: {err}') from err
199 # ######### / Overriding MPDClient #########
201 def _reset_cache(self):
203 Both flushes and instantiates _cache
205 * artists: all artists
206 * nombid_artists: artists with no mbid (set only when self.use_mbid is True)
207 * artist_tracks: caching last artist tracks, used in search_track
209 if isinstance(self._cache, dict):
210 self.log.info('Player: Flushing cache!')
212 self.log.info('Player: Initialising cache!')
213 self._cache = {'artists': frozenset(),
214 'nombid_artists': frozenset(),
216 self._cache['artists'] = frozenset(filter(None, self.list('artist')))
218 artists = self.list('artist', "(MUSICBRAINZ_ARTISTID == '')")
219 self._cache['nombid_artists'] = frozenset(filter(None, artists))
221 def _skipped_track(self, previous):
222 if (self.state == 'stop'
223 or not hasattr(previous, 'id')
224 or not hasattr(self.current, 'id')):
226 return self.current.id != previous.id # pylint: disable=no-member
229 """Monitor player for change
230 Returns a list a events among:
232 * database player media library has changed
233 * playlist playlist modified
234 * options player options changed: repeat mode, etc…
235 * player player state changed: paused, stopped, skip track…
236 * skipped current track skipped
240 try: # noidle cmd does not go through __getattr__, need to catch OSError then
242 self.send_idle('database', 'playlist', 'player', 'options')
243 _read, _, _ = select([self], [], [], select_timeout)
244 if _read: # tries to read response
245 ret = self.fetch_idle()
246 if self._skipped_track(curr):
247 ret.append('skipped')
248 if 'database' in ret:
251 # Nothing to read, canceling idle
253 except OSError as err:
254 raise PlayerError(err) from err
257 """Clean blocking event (idle) and pending commands
259 if 'idle' in self._pending:
262 self.log.warning('pending commands: %s', self._pending)
264 def add(self, payload):
265 """Overriding MPD's add method to accept Track objects
267 :param Track,list payload: Either a single track or a list of it
269 if isinstance(payload, Track):
270 super().__getattr__('add')(payload.file)
271 elif isinstance(payload, list):
272 self.command_list_ok_begin()
273 map(self.add, payload)
274 self.command_list_end()
276 self.log.error('Cannot add %s', payload)
278 # ######### Properties #####################
281 return self.currentsong()
286 Override deprecated MPD playlist command
288 return self.playlistinfo()
292 plm = {'repeat': None, 'single': None,
293 'random': None, 'consume': None, }
294 for key, val in self.status().items():
296 plm.update({key: bool(int(val))})
302 curr_position = int(self.current.pos)
304 return [trk for trk in plst if int(trk.pos) > curr_position]
308 """Returns (play|stop|pause)"""
309 return str(self.status().get('state'))
310 # ######### / Properties ###################
312 # #### find_tracks ####
313 def find_tracks(self, what):
314 """Find tracks for a specific artist or album
315 >>> player.find_tracks(Artist('Nirvana'))
316 >>> player.find_tracks(Album('In Utero', artist=Artist('Nirvana'))
318 :param Artist,Album what: Artist or Album to fetch track from
319 :return: A list of track objects
322 if isinstance(what, Artist):
323 return self._find_art(what)
324 if isinstance(what, Album):
325 return self._find_alb(what)
326 if isinstance(what, str):
327 return self.find_tracks(Artist(name=what))
328 raise PlayerError('Bad input argument')
330 def _find_art(self, artist):
333 if self.database.get_bl_artist(artist, add=False):
334 self.log.info('Artist in blocklist: %s', artist)
337 tracks |= set(self.find('musicbrainz_artistid', artist.mbid))
338 for name in artist.names:
339 tracks |= set(self.find('artist', name))
341 albums = {Album(trk.Album.name, mbid=trk.musicbrainz_albumid)
343 bl_albums = {Album(a.get('album'), mbid=a.get('musicbrainz_album'))
344 for a in self.database.view_bl() if a.get('album')}
345 if albums & bl_albums:
346 self.log.info('Albums in blocklist for %s: %s', artist, albums & bl_albums)
347 tracks = {trk for trk in tracks if trk.Album not in bl_albums}
349 bl_tracks = {Track(title=t.get('title'), file=t.get('file'))
350 for t in self.database.view_bl() if t.get('title')}
351 if tracks & bl_tracks:
352 self.log.info('Tracks in blocklist for %s: %s',
353 artist, tracks & bl_tracks)
354 tracks = {trk for trk in tracks if trk not in bl_tracks}
357 def _find_alb(self, album):
358 if not hasattr(album, 'artist'):
359 raise PlayerError('Album object have no artist attribute')
360 if self.database.get_bl_album(album, add=False):
361 self.log.info('Album in blocklist: %s', album)
365 filt = f"(MUSICBRAINZ_ALBUMID == '{album.mbid}')"
366 albums = self.find(filt)
367 # Now look for album with no MusicBrainzIdentifier
368 if not albums and album.Artist.mbid: # Use album artist MBID if possible
369 filt = f"((MUSICBRAINZ_ALBUMARTISTID == '{album.Artist.mbid}') AND (album == '{album.name_sz}'))"
370 albums = self.find(filt)
371 if not albums: # Falls back to (album)?artist/album name
372 for artist in album.Artist.names_sz:
373 filt = f"((albumartist == '{artist}') AND (album == '{album.name_sz}'))"
374 albums.extend(self.find(filt))
376 # #### / find_tracks ##
378 # #### Search Methods #####
379 def _find_musicbrainz_artistid(self, artist):
380 """Find MusicBrainzArtistID when possible.
382 if not self.use_mbid:
385 for name in artist.names_sz:
386 filt = f'((artist == "{name}") AND (MUSICBRAINZ_ARTISTID != ""))'
387 mbids = self.list('MUSICBRAINZ_ARTISTID', filt)
393 self.log.debug("Got multiple MBID for artist: %r", artist)
396 if artist.mbid != mbids[0]:
397 self.log('MBID discrepancy, %s found with %s (instead of %s)',
398 artist.name, mbids[0], artist.mbid)
405 def search_artist(self, artist):
407 Search artists based on a fuzzy search in the media library
408 >>> art = Artist(name='the beatles', mbid=<UUID4>) # mbid optional
409 >>> bea = player.search_artist(art)
411 >>> ['The Beatles', 'Beatles', 'the beatles']
413 :param Artist artist: Artist to look for in MPD music library
414 :return: Artist object
419 # look for exact search w/ musicbrainz_artistid
420 library = self.list('artist', f"(MUSICBRAINZ_ARTISTID == '{artist.mbid}')")
423 self.log.trace('Found mbid "%r" in library', artist)
424 # library could fetch several artist name for a single MUSICBRAINZ_ARTISTID
426 self.log.debug('I got "%s" searching for %r', library, artist)
428 if SimaStr(artist.name) == name and name != artist.name:
429 self.log.debug('add alias for %s: %s', artist, name)
430 artist.add_alias(name)
431 # Fetches remaining artists for potential match
432 artists = self._cache['nombid_artists']
433 else: # not using MusicBrainzIDs
434 artists = self._cache['artists']
435 match = get_close_matches(artist.name, artists, 50, 0.73)
436 if not match and not found:
439 self.log.debug('found close match for "%s": %s',
440 artist, '/'.join(match))
441 # First lowercased comparison
442 for close_art in match:
443 # Regular lowered string comparison
444 if artist.name.lower() == close_art.lower():
445 artist.add_alias(close_art)
447 if artist.name != close_art:
448 self.log.debug('"%s" matches "%s".', close_art, artist)
449 # Does not perform fuzzy matching on short and single word strings
450 # Only lowercased comparison
451 if ' ' not in artist.name and len(artist.name) < 8:
452 self.log.trace('no fuzzy matching for %r', artist)
456 # Now perform fuzzy search
458 if fuzz in artist.names: # Already found in lower cased comparison
460 # SimaStr string __eq__ (not regular string comparison here)
461 if SimaStr(artist.name) == fuzz:
463 artist.add_alias(fuzz)
464 self.log.debug('"%s" quite probably matches "%s" (SimaStr)',
468 self.log.info('Found aliases: %s', '/'.join(artist.names))
472 def search_track(self, artist, title):
473 """Fuzzy search of title by an artist
475 cache = self._cache.get('artist_tracks').get(artist)
476 # Retrieve all tracks from artist
477 all_tracks = cache or self.find_tracks(artist)
479 self._cache['artist_tracks'] = {} # clean up
480 self._cache.get('artist_tracks')[artist] = all_tracks
481 # Get all titles (filter missing titles set to 'None')
482 all_artist_titles = frozenset([tr.title for tr in all_tracks
483 if tr.title is not None])
484 match = get_close_matches(title, all_artist_titles, 50, 0.78)
489 leven = levenshtein_ratio(title, mtitle)
491 tracks.extend([t for t in all_tracks if t.title == mtitle])
493 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)',
494 mtitle, title, leven)
495 tracks.extend([t for t in all_tracks if t.title == mtitle])
497 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)',
498 mtitle, title, leven)
501 def search_albums(self, artist):
502 """Find potential albums for "artist"
504 * Fetch all albums for "AlbumArtist" == artist
505 → falls back to "Artist" == artist when no "AlbumArtist" tag is set
506 * Tries to filter some mutli-artists album
507 For instance an album by Artist_A may have a track by Artist_B. Then
508 looking for albums for Artist_B wrongly returns this album.
510 # First, look for all potential albums
511 self.log.debug('Searching album for "%r"', artist)
513 self.log.debug('Searching album for %s aliases: "%s"',
514 artist, artist.aliases)
516 if self.use_mbid and artist.mbid:
517 mpd_filter = f"((musicbrainz_albumartistid == '{artist.mbid}') AND ( album != ''))"
518 raw_album_id = self.list('musicbrainz_albumid', mpd_filter)
519 for albumid in raw_album_id:
520 mpd_filter = f"((musicbrainz_albumid == '{albumid}') AND ( album != ''))"
521 album_name = self.list('album', mpd_filter)
522 if not album_name: # something odd here
524 albums.add(Album(album_name[0], artist=artist.name,
525 Artist=artist, mbid=albumid))
526 for name_sz in artist.names_sz:
527 mpd_filter = f"((albumartist == '{name_sz}') AND ( album != ''))"
528 raw_albums = self.list('album', mpd_filter)
529 for alb in raw_albums:
530 if alb in [a.name for a in albums]:
535 mpd_filter = f"((albumartist == '{artist.name_sz}') AND ( album == '{_.name_sz}'))"
536 mbids = self.list('MUSICBRAINZ_ALBUMID', mpd_filter)
539 albums.add(Album(alb, artist=artist.name,
540 Artist=artist, mbid=mbid))
543 album_trks = self.find_tracks(album)
544 if not album_trks: # find_track result can be empty, blocklist applied
546 album_artists = {tr.albumartist for tr in album_trks if tr.albumartist}
547 if album.Artist.names & album_artists:
548 candidates.append(album)
550 if self.use_mbid and artist.mbid:
551 if artist.mbid == album_trks[0].musicbrainz_albumartistid:
552 candidates.append(album)
554 self.log.debug('Discarding "%s", "%r" not set as musicbrainz_albumartistid',
557 if 'Various Artists' in album_artists:
558 self.log.debug('Discarding %s ("Various Artists" set)', album)
560 if album_artists and album.Artist.name not in album_artists:
561 self.log.debug('Discarding "%s", "%s" not set as albumartist', album, album.Artist)
563 # Attempt to detect false positive (especially when no
564 # AlbumArtist/MBIDs tag ar set)
565 # Avoid selecting albums where artist is credited for a single
567 album_trks = self.find(f"(album == '{album.name_sz}')")
568 arts = [trk.artist for trk in album_trks] # Artists in the album
569 # count artist occurences
570 ratio = arts.count(album.Artist.name)/len(arts)
572 candidates.append(album)
574 self.log.debug('"%s" probably not an album of "%s" (ratio=%.2f)',
575 album, artist, ratio)
578 # #### / Search Methods ###
581 # vim: ai ts=4 sw=4 sts=4 expandtab