__author__ = 'Jack Kaliko'
-from datetime import timedelta
-
-from requests import Session, Request, Timeout, ConnectionError
from sima import LFM
from sima.lib.meta import Artist
+from sima.lib.track import Track
-from sima.lib.http import CacheController
-from sima.utils.utils import WSError, WSNotFound, WSTimeout, WSHTTPError
-from sima.utils.utils import getws, Throttle
+from sima.lib.http import HttpClient
+from sima.utils.utils import WSError, WSNotFound
+from sima.utils.utils import getws
if len(LFM.get('apikey')) == 43: # simple hack allowing imp.reload
getws(LFM)
-# Some definitions
-WAIT_BETWEEN_REQUESTS = timedelta(0, 2)
-SOCKET_TIMEOUT = 6
-
class SimaFM:
"""Last.fm http client
"""
root_url = 'http://{host}/{version}/'.format(**LFM)
- ratelimit = None
name = 'Last.fm'
- cache = {}
+ cache = False
+ stats = {'etag':0,
+ 'ccontrol':0,
+ 'total':0}
- def __init__(self, cache=True):
- self.controller = CacheController(self.cache)
+ def __init__(self):
+ self.http = HttpClient(cache=self.cache, stats=self.stats)
self.artist = None
- def _fetch(self, payload):
- """
- Prepare http request
- Use cached elements or proceed http request
- """
- req = Request('GET', SimaFM.root_url, params=payload,
- ).prepare()
- if self.cache:
- cached_response = self.controller.cached_request(req.url, req.headers)
- if cached_response:
- return cached_response.json()
- try:
- return self._fetch_ws(req)
- except Timeout:
- raise WSTimeout('Failed to reach server within {0}s'.format(
- SOCKET_TIMEOUT))
- except ConnectionError as err:
- raise WSError(err)
-
- @Throttle(WAIT_BETWEEN_REQUESTS)
- def _fetch_ws(self, prepreq):
- """fetch from web service"""
- sess = Session()
- resp = sess.send(prepreq, timeout=SOCKET_TIMEOUT)
- #self.__class__.ratelimit = resp.headers.get('x-ratelimit-remaining', None)
- if resp.status_code is not 200:
- raise WSHTTPError('{0.status_code}: {0.reason}'.format(resp))
- ans = resp.json()
- self._controls_answer(ans)
- if self.cache:
- self.controller.cache_response(resp.request, resp)
- return ans
-
def _controls_answer(self, ans):
"""Controls answer.
"""
payload.update(results=100)
if method == 'track':
payload.update(track=track)
- return payload
+ # > hashing the URL into a cache key
+ # return a sorted list of 2-tuple to have consistent cache
+ return sorted(payload.items(), key=lambda param: param[0])
def get_similar(self, artist=None):
"""Fetch similar artists
"""
payload = self._forge_payload(artist)
# Construct URL
- ans = self._fetch(payload)
+ ans = self.http(self.root_url, payload)
+ self._controls_answer(ans.json())
# Artist might be found be return no 'artist' list…
# cf. "Mulatu Astatqe" vs. "Mulatu Astatqé" with autocorrect=0
# json format is broken IMHO, xml is more consistent IIRC
# Here what we got:
# >>> {"similarartists":{"#text":"\n","artist":"Mulatu Astatqe"}}
# autocorrect=1 should fix it, checking anyway.
- simarts = ans.get('similarartists').get('artist')
+ simarts = ans.json().get('similarartists').get('artist')
if not isinstance(simarts, list):
raise WSError('Artist found but no similarities returned')
- for art in ans.get('similarartists').get('artist'):
+ for art in ans.json().get('similarartists').get('artist'):
yield Artist(name=art.get('name'), mbid=art.get('mbid', None))
+ def get_toptrack(self, artist=None):
+ """Fetch artist top tracks
+ """
+ payload = self._forge_payload(artist, method='top')
+ ans = self.http(self.root_url, payload)
+ self._controls_answer(ans.json())
+ tops = ans.json().get('toptracks').get('track')
+ art = {
+ 'artist': artist.name,
+ 'musicbrainz_artistid': artist.mbid,
+ }
+ for song in tops:
+ for key in ['artist', 'streamable', 'listeners',
+ 'url', 'image', '@attr']:
+ if key in song:
+ song.pop(key)
+ song.update(art)
+ song.update(title=song.pop('name'))
+ song.update(time=song.pop('duration'))
+ yield Track(**song)
# VIM MODLINE
# vim: ai ts=4 sw=4 sts=4 expandtab