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