]> kaliko git repositories - mpd-sima.git/blob - sima/lib/webserv.py
Fallback on name only when mbid request is empty
[mpd-sima.git] / sima / lib / webserv.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2009-2014 Jack 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 #
20 """
21 Fetching similar artists from last.fm web services
22 """
23
24 # standard library import
25 import random
26
27 from collections import deque
28 from hashlib import md5
29
30 # third parties components
31
32 # local import
33 from .plugin import Plugin
34 from .track import Track
35 from .meta import Artist
36 from ..utils.utils import WSError, WSNotFound
37
38 def cache(func):
39     """Caching decorator"""
40     def wrapper(*args, **kwargs):
41         #pylint: disable=W0212,C0111
42         cls = args[0]
43         similarities = [art.name for art in args[1]]
44         hashedlst = md5(''.join(similarities).encode('utf-8')).hexdigest()
45         if hashedlst in cls._cache.get('asearch'):
46             cls.log.debug('cached request')
47             results = cls._cache.get('asearch').get(hashedlst)
48         else:
49             results = func(*args, **kwargs)
50             cls.log.debug('caching request')
51             cls._cache.get('asearch').update({hashedlst:list(results)})
52         random.shuffle(results)
53         return results
54     return wrapper
55
56
57 class WebService(Plugin):
58     """similar artists webservice
59     """
60
61     def __init__(self, daemon):
62         Plugin.__init__(self, daemon)
63         self.daemon_conf = daemon.config
64         self.sdb = daemon.sdb
65         self.history = daemon.short_history
66         ##
67         self.to_add = list()
68         self._cache = None
69         self._flush_cache()
70         wrapper = {
71                 'track': self._track,
72                 'top': self._top,
73                 'album': self._album,
74                 }
75         self.queue_mode = wrapper.get(self.plugin_conf.get('queue_mode'))
76         self.ws = None
77
78     def _flush_cache(self):
79         """
80         Both flushes and instanciates _cache
81         """
82         name = self.__class__.__name__
83         if isinstance(self._cache, dict):
84             self.log.info('{0}: Flushing cache!'.format(name))
85         else:
86             self.log.info('{0}: Initialising cache!'.format(name))
87         self._cache = {
88                 'asearch': dict(),
89                 'tsearch': dict(),
90                 }
91
92     def _cleanup_cache(self):
93         """Avoid bloated cache
94         """
95         for _, val in self._cache.items():
96             if isinstance(val, dict):
97                 while len(val) > 150:
98                     val.popitem()
99
100     def get_history(self, artist):
101         """Constructs list of Track for already played titles for an artist.
102         """
103         duration = self.daemon_conf.getint('sima', 'history_duration')
104         tracks_from_db = self.sdb.get_history(duration=duration, artist=artist)
105         # Construct Track() objects list from database history
106         played_tracks = [Track(artist=tr[-1], album=tr[1], title=tr[2],
107                                file=tr[3]) for tr in tracks_from_db]
108         return played_tracks
109
110     def filter_track(self, tracks):
111         """
112         Extract one unplayed track from a Track object list.
113             * not in history
114             * not already in the queue
115             * not blacklisted
116         """
117         artist = tracks[0].artist
118         black_list = self.player.queue + self.to_add
119         not_in_hist = list(set(tracks) - set(self.get_history(artist=artist)))
120         if self.plugin_conf.get('queue_mode') != 'top' and not not_in_hist:
121             self.log.debug('All tracks already played for "{}"'.format(artist))
122         random.shuffle(not_in_hist)
123         candidate = []
124         for trk in [_ for _ in not_in_hist if _ not in black_list]:
125             # Should use albumartist heuristic as well
126             if self.plugin_conf.getboolean('single_album'):
127                 if (trk.album == self.player.current.album or
128                     trk.album in [tr.album for tr in self.to_add]):
129                     self.log.debug('Found unplayed track ' +
130                                'but from an album already queued: %s' % (trk))
131                     continue
132             candidate.append(trk)
133         if not candidate:
134             return False
135         self.to_add.append(random.choice(candidate))
136         return True
137
138     def _get_artists_list_reorg(self, alist):
139         """
140         Move around items in artists_list in order to play first not recently
141         played artists
142         """
143         hist = list()
144         duration = self.daemon_conf.getint('sima', 'history_duration')
145         for art in self.sdb.get_artists_history(alist, duration=duration):
146             if art not in hist:
147                 hist.insert(0, art)
148         reorg = [art for art in alist if art not in hist]
149         reorg.extend(hist)
150         self.log.info('{}'.format(' / '.join([a.name for a in reorg])))
151         return reorg
152
153     @cache
154     def get_artists_from_player(self, similarities):
155         """
156         Look in player library for availability of similar artists in
157         similarities
158         """
159         dynamic = self.plugin_conf.getint('max_art')
160         if dynamic <= 0:
161             dynamic = 100
162         results = list()
163         similarities.reverse()
164         while (len(results) < dynamic
165                and len(similarities) > 0):
166             art_pop = similarities.pop()
167             res = self.player.search_artist(art_pop)
168             if res:
169                 results.append(res)
170         return results
171
172     def ws_similar_artists(self, artist=None):
173         """
174         Retrieve similar artists from WebServive.
175         """
176         # initialize artists deque list to construct from DB
177         as_art = deque()
178         as_artists = self.ws.get_similar(artist=artist)
179         self.log.debug('Requesting {} for {!r}'.format(self.ws.name, artist))
180         try:
181             [as_art.append(art) for art in as_artists]
182         except WSNotFound as err:
183             if artist.mbid:
184                 return self.ws_similar_artists(Artist(name=artist.name))
185             self.log.warning('{}: {}'.format(self.ws.name, err))
186         except WSError as err:
187             self.log.warning('{}: {}'.format(self.ws.name, err))
188         if as_art:
189             self.log.debug('Fetched {} artist(s)'.format(len(as_art)))
190         return as_art
191
192     def get_recursive_similar_artist(self):
193         history = deque(self.history)
194         history.popleft()
195         depth = 0
196         if not self.player.playlist:
197             return
198         last_trk = self.player.playlist[-1]
199         extra_arts = list()
200         while depth < self.plugin_conf.getint('depth'):
201             if len(history) == 0:
202                 break
203             trk = history.popleft()
204             if (trk.Artist in extra_arts
205                 or trk.Artist == last_trk.Artist):
206                 continue
207             extra_arts.append(trk.Artist)
208             depth += 1
209         self.log.info('EXTRA ARTS: {}'.format(
210             '/'.join([art.name for art in extra_arts])))
211         for artist in extra_arts:
212             self.log.debug('Looking for artist similar '
213                            'to "{}" as well'.format(artist))
214             similar = self.ws_similar_artists(artist=artist)
215             if not similar:
216                 return []
217             ret_extra = set(self.get_artists_from_player(similar))
218             if last_trk.Artist in ret_extra:
219                 ret_extra.remove(last_trk.Artist)
220         return ret_extra
221
222     def get_local_similar_artists(self):
223         """Check against local player for similar artists
224         """
225         if not self.player.playlist:
226             return []
227         tolookfor = self.player.playlist[-1].Artist
228         self.log.info('Looking for artist similar to "{}"'.format(tolookfor))
229         similar = self.ws_similar_artists(tolookfor)
230         if not similar:
231             self.log.info('Got nothing from {0}!'.format(self.ws.name))
232             return []
233         self.log.info('First five similar artist(s): {}...'.format(
234                       ' / '.join([a.name for a in list(similar)[0:5]])))
235         self.log.info('Looking availability in music library')
236         ret = set(self.get_artists_from_player(similar))
237         ret_extra = None
238         if len(self.history) >= 2:
239             if self.plugin_conf.getint('depth') > 1:
240                 ret_extra = self.get_recursive_similar_artist()
241         if ret_extra:
242             ret = set(ret) | set(ret_extra)
243         if not ret:
244             self.log.warning('Got nothing from music library.')
245             self.log.warning('Try running in debug mode to guess why...')
246             return []
247         queued_artists = { trk.Artist for trk in self.player.queue }
248         for art in queued_artists:
249             if art in ret:
250                 self.log.debug('Removing already queued artist: {0}'.format(art))
251         ret = ret - queued_artists
252         if ret & queued_artists:
253             self.log.debug('Removing already queued artist: {0}'.format(ret & queued_artists))
254             ret = ret - queued_artists
255         if self.player.current and self.player.current.Artist in ret:
256             self.log.debug('Removing current artist: {0}'.format(self.player.current.Artist))
257             ret = ret - {self.player.current.Artist}
258         # Move around similars items to get in unplayed|not recently played
259         # artist first.
260         self.log.info('Got {} artists in library'.format(len(ret)))
261         return self._get_artists_list_reorg(list(ret))
262
263     def _get_album_history(self, artist=None):
264         """Retrieve album history"""
265         duration = self.daemon_conf.getint('sima', 'history_duration')
266         albums_list = set()
267         for trk in self.sdb.get_history(artist=artist.name, duration=duration):
268             albums_list.add(trk[1])
269         return albums_list
270
271     def find_album(self, artists):
272         """Find albums to queue.
273         """
274         self.to_add = list()
275         nb_album_add = 0
276         target_album_to_add = self.plugin_conf.getint('album_to_add')
277         for artist in artists:
278             self.log.info('Looking for an album to add for "%s"...' % artist)
279             albums = self.player.search_albums(artist)
280             # str conversion while Album type is not propagated
281             albums = [str(album) for album in albums]
282             if albums:
283                 self.log.debug('Albums candidate: {0:s}'.format(
284                                ' / '.join(albums)))
285             else: continue
286             # albums yet in history for this artist
287             albums = set(albums)
288             albums_yet_in_hist = albums & self._get_album_history(artist=artist)
289             albums_not_in_hist = list(albums - albums_yet_in_hist)
290             # Get to next artist if there are no unplayed albums
291             if not albums_not_in_hist:
292                 self.log.info('No album found for "%s"' % artist)
293                 continue
294             album_to_queue = str()
295             random.shuffle(albums_not_in_hist)
296             for album in albums_not_in_hist:
297                 tracks = self.player.find_album(artist, album)
298                 # Look if one track of the album is already queued
299                 # Good heuristic, at least enough to guess if the whole album is
300                 # already queued.
301                 if tracks[0] in self.player.queue:
302                     self.log.debug('"%s" already queued, skipping!' %
303                             tracks[0].album)
304                     continue
305                 album_to_queue = album
306             if not album_to_queue:
307                 self.log.info('No album found for "%s"' % artist)
308                 continue
309             self.log.info('{2} album candidate: {0} - {1}'.format(
310                            artist, album_to_queue, self.ws.name))
311             nb_album_add += 1
312             self.to_add.extend(self.player.find_album(artist, album_to_queue))
313             if nb_album_add == target_album_to_add:
314                 return True
315
316     def find_top(self, artists):
317         """
318         find top tracks for artists in artists list.
319         """
320         self.to_add = list()
321         nbtracks_target = self.plugin_conf.getint('track_to_add')
322         for artist in artists:
323             artist = Artist(name=artist)
324             if len(self.to_add) == nbtracks_target:
325                 return True
326             self.log.info('Looking for a top track for {0}'.format(artist))
327             titles = deque()
328             try:
329                 titles = [t for t in self.ws.get_toptrack(artist)]
330             except WSError as err:
331                 self.log.warning('{0}: {1}'.format(self.ws.name, err))
332             if self.ws.ratelimit:
333                 self.log.info('{0.name} ratelimit: {0.ratelimit}'.format(self.ws))
334             for trk in titles:
335                 found = self.player.fuzzy_find_track(artist.name, trk.title)
336                 random.shuffle(found)
337                 if found:
338                     self.log.debug('{0}'.format(found[0]))
339                     if self.filter_track(found):
340                         break
341
342     def _track(self):
343         """Get some tracks for track queue mode
344         """
345         artists = self.get_local_similar_artists()
346         nbtracks_target = self.plugin_conf.getint('track_to_add')
347         for artist in artists:
348             self.log.debug('Trying to find titles to add for "{}"'.format(
349                            artist))
350             found = self.player.find_track(artist)
351             random.shuffle(found)
352             if not found:
353                 self.log.debug('Found nothing to queue for {0}'.format(artist))
354                 continue
355             # find tracks not in history for artist
356             self.filter_track(found)
357             if len(self.to_add) == nbtracks_target:
358                 break
359         if not self.to_add:
360             self.log.debug('Found no tracks to queue!')
361             return None
362         for track in self.to_add:
363             self.log.info('{1} candidates: {0!s}'.format(track, self.ws.name))
364
365     def _album(self):
366         """Get albums for album queue mode
367         """
368         artists = self.get_local_similar_artists()
369         self.find_album(artists)
370
371     def _top(self):
372         """Get some tracks for top track queue mode
373         """
374         artists = self.get_local_similar_artists()
375         self.find_top(artists)
376         for track in self.to_add:
377             self.log.info('{1} candidates: {0!s}'.format(track, self.ws.name))
378
379     def callback_need_track(self):
380         self._cleanup_cache()
381         if len(self.player.playlist) == 0:
382             self.log.info('No last track, cannot queue')
383             return None
384         if not self.player.playlist[-1].artist:
385             self.log.warning('No artist set for the last track in queue')
386             self.log.debug(repr(self.player.current))
387             return None
388         self.queue_mode()
389         msg = ' '.join(['{0}: {1:>3d}'.format(k, v) for
390                         k, v in sorted(self.ws.stats.items())])
391         self.log.debug(msg)
392         candidates = self.to_add
393         self.to_add = list()
394         if self.plugin_conf.get('queue_mode') != 'album':
395             random.shuffle(candidates)
396         return candidates
397
398     def callback_player_database(self):
399         self._flush_cache()
400
401 # VIM MODLINE
402 # vim: ai ts=4 sw=4 sts=4 expandtab