]> kaliko git repositories - mpd-sima.git/blob - sima/mpdclient.py
Fixed some code style and comment
[mpd-sima.git] / sima / mpdclient.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2009-2020 kaliko <kaliko@azylum.org>
3 #
4 #  This file is part of sima
5 #
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.
10 #
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.
15 #
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/>.
18
19 # standard library import
20 from difflib import get_close_matches
21 from functools import wraps
22 from itertools import dropwhile
23
24 # external module
25 from musicpd import MPDClient, MPDError
26
27
28 # local import
29 from .lib.meta import Meta, Artist, Album
30 from .lib.track import Track
31 from .lib.simastr import SimaStr
32 from .utils.leven import levenshtein_ratio
33
34
35 class PlayerError(Exception):
36     """Fatal error in the player."""
37
38
39 # Some decorators
40 def bl_artist(func):
41     def wrapper(*args, **kwargs):
42         cls = args[0]
43         if not cls.database:
44             return func(*args, **kwargs)
45         result = func(*args, **kwargs)
46         if not result:
47             return None
48         names = list()
49         for art in result.names:
50             if cls.database.get_bl_artist(art, add_not=True):
51                 cls.log.debug('Blacklisted "%s"', art)
52                 continue
53             names.append(art)
54         if not names:
55             return None
56         resp = Artist(name=names.pop(), mbid=result.mbid)
57         for name in names:
58             resp.add_alias(name)
59         return resp
60     return wrapper
61
62
63 def tracks_wrapper(func):
64     """Convert plain track mapping as returned by MPDClient into :py:obj:Track
65     objects. This decorator accepts single track or list of tracks as input.
66     """
67     @wraps(func)
68     def wrapper(*args, **kwargs):
69         ret = func(*args, **kwargs)
70         if isinstance(ret, dict):
71             return Track(**ret)
72         return [Track(**t) for t in ret]
73     return wrapper
74 # / decorators
75
76
77 def blacklist(artist=False, album=False, track=False):
78     # pylint: disable=C0111,W0212
79     field = (album, track)
80
81     def decorated(func):
82         def wrapper(*args, **kwargs):
83             if not args[0].database:
84                 return func(*args, **kwargs)
85             cls = args[0]
86             boolgen = (bl for bl in field)
87             bl_fun = (cls.database.get_bl_album,
88                       cls.database.get_bl_track,)
89             #bl_getter = next(fn for fn, bl in zip(bl_fun, boolgen) if bl is True)
90             bl_getter = next(dropwhile(lambda _: not next(boolgen), bl_fun))
91             #cls.log.debug('using {0} as bl filter'.format(bl_getter.__name__))
92             results = list()
93             for elem in func(*args, **kwargs):
94                 if bl_getter(elem, add_not=True):
95                     #cls.log.debug('Blacklisted "{0}"'.format(elem))
96                     continue
97                 if track and cls.database.get_bl_album(elem, add_not=True):
98                     # filter album as well in track mode
99                     # (artist have already been)
100                     cls.log.debug('Blacklisted alb. "%s"', elem)
101                     continue
102                 results.append(elem)
103             return results
104         return wrapper
105     return decorated
106
107
108 class MPD(MPDClient):
109     """
110     Player instance inheriting from MPDClient (python-musicpd).
111
112     Some methods are overridden to format objects as sima.lib.Track for
113     instance, other are calling parent class directly through super().
114     cf. MPD.__getattr__
115
116     .. note::
117
118         * find methods are looking for exact match of the object provided
119           attributes in MPD music library
120         * search methods are looking for exact match + fuzzy match.
121     """
122     needed_cmds = ['status', 'stats', 'add', 'find',
123                    'search', 'currentsong', 'ping']
124     needed_tags = {'Artist', 'Album', 'AlbumArtist', 'Title', 'Track'}
125     needed_mbid_tags = {'MUSICBRAINZ_ARTISTID', 'MUSICBRAINZ_ALBUMID',
126                         'MUSICBRAINZ_ALBUMARTISTID', 'MUSICBRAINZ_TRACKID'}
127     MPD_supported_tags = {'Artist', 'ArtistSort', 'Album', 'AlbumSort', 'AlbumArtist',
128                           'AlbumArtistSort', 'Title', 'Track', 'Name', 'Genre',
129                           'Date', 'OriginalDate', 'Composer', 'Performer',
130                           'Conductor', 'Work', 'Grouping', 'Disc', 'Label',
131                           'MUSICBRAINZ_ARTISTID', 'MUSICBRAINZ_ALBUMID',
132                           'MUSICBRAINZ_ALBUMARTISTID', 'MUSICBRAINZ_TRACKID',
133                           'MUSICBRAINZ_RELEASETRACKID', 'MUSICBRAINZ_WORKID'}
134     database = None
135
136     def __init__(self, daemon):
137         super().__init__()
138         self.use_mbid = True
139         self.daemon = daemon
140         self.log = daemon.log
141         self.config = self.daemon.config['MPD']
142         self._cache = None
143
144     # ######### Overriding MPDClient ###########
145     def __getattr__(self, cmd):
146         """Wrapper around MPDClient calls for abstract overriding"""
147         track_wrapped = {'currentsong', 'find', 'playlistinfo', }
148         if cmd in track_wrapped:
149             return tracks_wrapper(super().__getattr__(cmd))
150         return super().__getattr__(cmd)
151
152     def disconnect(self):
153         """Overriding explicitly MPDClient.disconnect()"""
154         if self._sock:
155             super().disconnect()
156
157     def connect(self):
158         """Overriding explicitly MPDClient.connect()"""
159         # host, port, password
160         host = self.config.get('host')
161         port = self.config.get('port')
162         password = self.config.get('password', fallback=None)
163         self.disconnect()
164         try:
165             super().connect(host, port)
166         # Catch socket errors
167         except IOError as err:
168             raise PlayerError('Could not connect to "%s:%s": %s' %
169                               (host, port, err.strerror))
170         # Catch all other possible errors
171         # ConnectionError and ProtocolError are always fatal.  Others may not
172         # be, but we don't know how to handle them here, so treat them as if
173         # they are instead of ignoring them.
174         except MPDError as err:
175             raise PlayerError('Could not connect to "%s:%s": %s' %
176                               (host, port, err))
177         if password:
178             try:
179                 self.password(password)
180             except (MPDError, IOError) as err:
181                 raise PlayerError("Could not connect to '%s': %s" % (host, err))
182         # Controls we have sufficient rights
183         available_cmd = self.commands()
184         for cmd in MPD.needed_cmds:
185             if cmd not in available_cmd:
186                 self.disconnect()
187                 raise PlayerError('Could connect to "%s", '
188                                   'but command "%s" not available' %
189                                   (host, cmd))
190         self.tagtypes('clear')
191         for tag in MPD.needed_tags:
192             self.tagtypes('enable', tag)
193         tt = set(map(str.lower, self.tagtypes()))
194         needed_tags = set(map(str.lower, MPD.needed_tags))
195         if len(needed_tags & tt) != len(MPD.needed_tags):
196             self.log.warning('MPD exposes: %s', tt)
197             self.log.warning('Tags needed: %s', needed_tags)
198             raise PlayerError('Missing mandatory metadata!')
199         for tag in MPD.needed_mbid_tags:
200             self.tagtypes('enable', tag)
201         # Controls use of MusicBrainzIdentifier
202         if self.daemon.config.get('sima', 'musicbrainzid'):
203             tt = set(self.tagtypes())
204             if len(MPD.needed_mbid_tags & tt) != len(MPD.needed_mbid_tags):
205                 self.log.warning('Use of MusicBrainzIdentifier is set but MPD '
206                                  'is not providing related metadata')
207                 self.log.info(tt)
208                 self.log.warning('Disabling MusicBrainzIdentifier')
209                 self.use_mbid = Meta.use_mbid = False
210             else:
211                 self.log.debug('Available metadata: %s', tt)
212                 self.use_mbid = Meta.use_mbid = True
213         else:
214             self.log.warning('Use of MusicBrainzIdentifier disabled!')
215             self.log.info('Consider using MusicBrainzIdentifier for your music library')
216             self.use_mbid = Meta.use_mbid = False
217         self._reset_cache()
218     # ######### / Overriding MPDClient #########
219
220     def _reset_cache(self):
221         """
222         Both flushes and instantiates _cache
223
224         * artists: all artists
225         * nombid_artists: artists with no mbid (set only when self.use_mbid is True)
226         * artist_tracks: caching last artist tracks, used in search_track
227         """
228         if isinstance(self._cache, dict):
229             self.log.info('Player: Flushing cache!')
230         else:
231             self.log.info('Player: Initialising cache!')
232         self._cache = {'artists': frozenset(),
233                        'nombid_artists': frozenset(),
234                        'artist_tracks': {}}
235         self._cache['artists'] = frozenset(filter(None, self.list('artist')))
236         if self.use_mbid:
237             artists = self.list('artist', "(MUSICBRAINZ_ARTISTID == '')")
238             self._cache['nombid_artists'] = frozenset(filter(None, artists))
239
240     def _skipped_track(self, previous):
241         if (self.state == 'stop'
242                 or not hasattr(previous, 'id')
243                 or not hasattr(self.current, 'id')):
244             return False
245         return self.current.id != previous.id  # pylint: disable=no-member
246
247     def monitor(self):
248         """Monitor player for change
249         Returns a list a events among:
250
251             * database  player media library has changed
252             * playlist  playlist modified
253             * options   player options changed: repeat mode, etc…
254             * player    player state changed: paused, stopped, skip track…
255             * skipped   current track skipped
256         """
257         curr = self.current
258         try:
259             ret = self.idle('database', 'playlist', 'player', 'options')
260         except (MPDError, IOError) as err:
261             raise PlayerError("Couldn't init idle: %s" % err)
262         if self._skipped_track(curr):
263             ret.append('skipped')
264         if 'database' in ret:
265             self._reset_cache()
266         return ret
267
268     def clean(self):
269         """Clean blocking event (idle) and pending commands
270         """
271         if 'idle' in self._pending:
272             self.noidle()
273         elif self._pending:
274             self.log.warning('pending commands: %s', self._pending)
275
276     def add(self, payload):
277         """Overriding MPD's add method to accept Track objects
278
279         :param Track,list payload: Either a single :py:obj:`Track` or a list of it
280         """
281         if isinstance(payload, Track):
282             super().__getattr__('add')(payload.file)
283         elif isinstance(payload, list):
284             self.command_list_ok_begin()
285             map(self.add, payload)
286             self.command_list_end()
287         else:
288             self.log.error('Cannot add %s', payload)
289
290     # ######### Properties #####################
291     @property
292     def current(self):
293         return self.currentsong()
294
295     @property
296     def playlist(self):
297         """
298         Override deprecated MPD playlist command
299         """
300         return self.playlistinfo()
301
302     @property
303     def playmode(self):
304         plm = {'repeat': None, 'single': None,
305                'random': None, 'consume': None, }
306         for key, val in self.status().items():
307             if key in plm.keys():
308                 plm.update({key: bool(int(val))})
309         return plm
310
311     @property
312     def queue(self):
313         plst = self.playlist
314         curr_position = int(self.current.pos)
315         plst.reverse()
316         return [trk for trk in plst if int(trk.pos) > curr_position]
317
318     @property
319     def state(self):
320         """Returns (play|stop|pause)"""
321         return str(self.status().get('state'))
322     # ######### / Properties ###################
323
324 # #### find_tracks ####
325     def find_tracks(self, what):
326         """Find tracks for a specific artist or album
327             >>> player.find_tracks(Artist('Nirvana'))
328             >>> player.find_tracks(Album('In Utero', artist=(Artist('Nirvana'))
329
330         :param Artist,Album what: Artist or Album to fetch track from
331
332         Returns a list of :py:obj:Track objects
333         """
334         if isinstance(what, Artist):
335             return self._find_art(what)
336         if isinstance(what, Album):
337             return self._find_alb(what)
338         if isinstance(what, str):
339             return self.find_tracks(Artist(name=what))
340         raise PlayerError('Bad input argument')
341
342     def _find_art(self, artist):
343         tracks = set()
344         if artist.mbid:
345             tracks |= set(self.find('musicbrainz_artistid', artist.mbid))
346         for name in artist.names_sz:
347             tracks |= set(self.find('artist', name))
348         return list(tracks)
349
350     def _find_alb(self, album):
351         if not hasattr(album, 'artist'):
352             raise PlayerError('Album object have no artist attribute')
353         albums = []
354         if self.use_mbid and album.mbid:
355             filt = f"(MUSICBRAINZ_ALBUMID == '{album.mbid}')"
356             albums = self.find(filt)
357         # Now look for album with no MusicBrainzIdentifier
358         if not albums and album.artist.mbid and self.use_mbid:  # Use album artist MBID if possible
359             filt = f"((MUSICBRAINZ_ALBUMARTISTID == '{album.artist.mbid}') AND (album == '{album.name_sz}'))"
360             albums = self.find(filt)
361         if not albums:  # Falls back to (album)?artist/album name
362             for artist in album.artist.names_sz:
363                 filt = f"((albumartist == '{artist}') AND (album == '{album.name_sz}'))"
364                 albums.extend(self.find(filt))
365         return albums
366 # #### / find_tracks ##
367
368 # #### Search Methods #####
369     @bl_artist
370     def search_artist(self, artist):
371         """
372         Search artists based on a fuzzy search in the media library
373             >>> art = Artist(name='the beatles', mbid=<UUID4>) # mbid optional
374             >>> bea = player.search_artist(art)
375             >>> print(bea.names)
376             >>> ['The Beatles', 'Beatles', 'the beatles']
377
378         :param Artist artist: Artist to look for in MPD music library
379
380         Returns an Artist object
381         """
382         found = False
383         if self.use_mbid and artist.mbid:
384             # look for exact search w/ musicbrainz_artistid
385             library = self.list('artist', f"(MUSICBRAINZ_ARTISTID == '{artist.mbid}')")
386             if library:
387                 found = True
388                 self.log.trace('Found mbid "%r" in library', artist)
389                 # library could fetch several artist name for a single MUSICBRAINZ_ARTISTID
390                 if len(library) > 1:
391                     self.log.debug('I got "%s" searching for %r', library, artist)
392                 elif len(library) == 1 and library[0] != artist.name:
393                     self.log.info('Update artist name %s->%s', artist, library[0])
394                     artist = Artist(name=library[0], mbid=artist.mbid)
395             # Fetches remaining artists for potential match
396             artists = self._cache['nombid_artists']
397         else:  # not using MusicBrainzIDs
398             artists = self._cache['artists']
399         match = get_close_matches(artist.name, artists, 50, 0.73)
400         if not match and not found:
401             return None
402         if len(match) > 1:
403             self.log.debug('found close match for "%s": %s',
404                            artist, '/'.join(match))
405         # First lowercased comparison
406         for close_art in match:
407             # Regular lowered string comparison
408             if artist.name.lower() == close_art.lower():
409                 artist.add_alias(close_art)
410                 found = True
411                 if artist.name != close_art:
412                     self.log.debug('"%s" matches "%s".', close_art, artist)
413         # Does not perform fuzzy matching on short and single word strings
414         # Only lowercased comparison
415         if ' ' not in artist.name and len(artist.name) < 8:
416             self.log.trace('no fuzzy matching for %r', artist)
417             if found:
418                 return artist
419             return None
420         # Now perform fuzzy search
421         for fuzz in match:
422             if fuzz in artist.names:  # Already found in lower cased comparison
423                 continue
424             # SimaStr string __eq__ (not regular string comparison here)
425             if SimaStr(artist.name) == fuzz:
426                 found = True
427                 artist.add_alias(fuzz)
428                 self.log.debug('"%s" quite probably matches "%s" (SimaStr)',
429                                fuzz, artist)
430         if found:
431             if artist.aliases:
432                 self.log.info('Found aliases: %s', '/'.join(artist.names))
433             return artist
434         return None
435
436     @blacklist(track=True)
437     def search_track(self, artist, title):
438         """Fuzzy search of title by an artist
439         """
440         cache = self._cache.get('artist_tracks').get(artist)
441         # Retrieve all tracks from artist
442         all_tracks = cache or self.find_tracks(artist)
443         if not cache:
444             self._cache['artist_tracks'] = {}  # clean up
445             self._cache.get('artist_tracks')[artist] = all_tracks
446         # Get all titles (filter missing titles set to 'None')
447         all_artist_titles = frozenset([tr.title for tr in all_tracks
448                                        if tr.title is not None])
449         match = get_close_matches(title, all_artist_titles, 50, 0.78)
450         tracks = []
451         if not match:
452             return []
453         for mtitle in match:
454             leven = levenshtein_ratio(title, mtitle)
455             if leven == 1:
456                 tracks.extend([t for t in all_tracks if t.title == mtitle])
457             elif leven >= 0.77:
458                 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)',
459                                mtitle, title, leven)
460                 tracks.extend([t for t in all_tracks if t.title == mtitle])
461             else:
462                 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)',
463                                mtitle, title, leven)
464         return tracks
465
466     @blacklist(album=True)
467     def search_albums(self, artist):
468         """Find potential albums for "artist"
469
470         * Fetch all albums for "AlbumArtist" == artist
471           → falls back to "Artist" == artist when no "AlbumArtist" tag is set
472         * Tries to filter some mutli-artists album
473           For instance an album by Artist_A may have a track by Artist_B. Then
474           looking for albums for Artist_B returns wrongly this album.
475         """
476         # First, look for all potential albums
477         self.log.debug('Searching album for "%s"', artist)
478         if artist.aliases:
479             self.log.debug('Searching album for %s aliases: "%s"',
480                            artist, artist.aliases)
481         for name_sz in artist.names_sz:
482             raw_albums = self.list('album', f"( albumartist == '{name_sz}')")
483             albums = [Album(a, albumartist=artist.name, artist=artist) for a in raw_albums if a]
484         candidates = []
485         for album in albums:
486             album_trks = self.find_tracks(album)
487             album_artists = {tr.albumartist for tr in album_trks if tr.albumartist}
488             if album.artist.names & album_artists:
489                 candidates.append(album)
490                 continue
491             if 'Various Artists' in album_artists:
492                 self.log.debug('Discarding %s ("Various Artists" set)', album)
493                 continue
494             if album_artists and album.artist.name not in album_artists:
495                 self.log.debug('Discarding "%s", "%s" not set as albumartist', album, album.artist)
496                 continue
497             # Attempt to detect false positive
498             # Avoid selecting albums where artist is credited for a single
499             # track of the album
500             album_trks = self.find(f"(album == '{album.name_sz}')")
501             arts = [trk.artist for trk in album_trks]  # Artists in the album
502             # count artist occurences
503             ratio = arts.count(album.artist.name)/len(arts)
504             if ratio >= 0.8:
505                 candidates.append(album)
506             else:
507                 self.log.debug('"%s" probably not an album of "%s" (ratio=%.2f)',
508                                album, artist, ratio)
509             continue
510         return candidates
511 # #### / Search Methods ###
512
513 # VIM MODLINE
514 # vim: ai ts=4 sw=4 sts=4 expandtab