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