]> kaliko git repositories - mpd-sima.git/blobdiff - sima/lib/simaecho.py
Integrate dynamic option in echonest plugin
[mpd-sima.git] / sima / lib / simaecho.py
index 03892c0a3a7efd3ce1d41167e1a70ccbcccf3c80..fbb60b07fb973305beec2aa2a5a168ca7db8f0ca 100644 (file)
@@ -30,12 +30,12 @@ import logging
 from datetime import datetime, timedelta
 from time import sleep
 
 from datetime import datetime, timedelta
 from time import sleep
 
-from requests import get, Timeout, ConnectionError
+from requests import get, Request, Timeout, ConnectionError
 
 from sima import ECH
 from sima.lib.meta import Artist
 from sima.utils.utils import getws
 
 from sima import ECH
 from sima.lib.meta import Artist
 from sima.utils.utils import getws
-if len(ECH.get('apikey')) == 23:
+if len(ECH.get('apikey')) == 23:  # simple hack allowing imp.reload
     getws(ECH)
 
 # Some definitions
     getws(ECH)
 
 # Some definitions
@@ -84,19 +84,33 @@ class Cache():
         return self.elem
 
 
         return self.elem
 
 
+def purge_cache(age=4):
+    now = datetime.utcnow()
+    if now.hour == SimaEch.timestamp.hour:
+        return
+    SimaEch.timestamp = datetime.utcnow()
+    cache = SimaEch.cache
+    delta = timedelta(hours=age)
+    for url in list(cache.keys()):
+        timestamp = cache.get(url).created()
+        if now - timestamp > delta:
+            cache.pop(url)
+
+
 class SimaEch():
     """
     """
     root_url = 'http://{host}/api/{version}'.format(**ECH)
     cache = {}
     timestamp = datetime.utcnow()
 class SimaEch():
     """
     """
     root_url = 'http://{host}/api/{version}'.format(**ECH)
     cache = {}
     timestamp = datetime.utcnow()
+    ratelimit = None
 
     def __init__(self, cache=True):
         self.artist = None
         self._ressource = None
         self.current_element = None
         self.caching = cache
 
     def __init__(self, cache=True):
         self.artist = None
         self._ressource = None
         self.current_element = None
         self.caching = cache
-        self.purge_cache()
+        purge_cache()
 
     def _fetch(self, payload):
         """Use cached elements or proceed http request"""
 
     def _fetch(self, payload):
         """Use cached elements or proceed http request"""
@@ -105,7 +119,7 @@ class SimaEch():
             self.current_element = SimaEch.cache.get(url).elem
             return
         try:
             self.current_element = SimaEch.cache.get(url).elem
             return
         try:
-            self._fetch_lfm(payload)
+            self._fetch_ech(payload)
         except Timeout:
             raise EchoTimeout('Failed to reach server within {0}s'.format(
                                SOCKET_TIMEOUT))
         except Timeout:
             raise EchoTimeout('Failed to reach server within {0}s'.format(
                                SOCKET_TIMEOUT))
@@ -113,12 +127,11 @@ class SimaEch():
             raise EchoError(err)
 
     @Throttle(WAIT_BETWEEN_REQUESTS)
             raise EchoError(err)
 
     @Throttle(WAIT_BETWEEN_REQUESTS)
-    def _fetch_lfm(self, payload):
+    def _fetch_ech(self, payload):
         """fetch from web service"""
         req = get(self._ressource, params=payload,
                             timeout=SOCKET_TIMEOUT)
         """fetch from web service"""
         req = get(self._ressource, params=payload,
                             timeout=SOCKET_TIMEOUT)
-        if 'x-ratelimit-remaining' in req.headers:
-            logging.debug('x-ratelimit-remaining {x-ratelimit-remaining}'.format(**req.headers))
+        self.__class__.ratelimit = req.headers.get('x-ratelimit-remaining', None)
         if req.status_code is not 200:
             raise EchoHTTPError(req.status_code)
         self.current_element = req.json()
         if req.status_code is not 200:
             raise EchoHTTPError(req.status_code)
         self.current_element = req.json()
@@ -128,7 +141,7 @@ class SimaEch():
                                  Cache(self.current_element)})
 
     def _controls_answer(self):
                                  Cache(self.current_element)})
 
     def _controls_answer(self):
-        """Controls last.fm answer.
+        """Controls answer.
         """
         status = self.current_element.get('response').get('status')
         code = status.get('code')
         """
         status = self.current_element.get('response').get('status')
         code = status.get('code')
@@ -151,21 +164,9 @@ class SimaEch():
         else:
            payload.update(name=artist.name)
         payload.update(bucket='id:musicbrainz')
         else:
            payload.update(name=artist.name)
         payload.update(bucket='id:musicbrainz')
-        payload.update(results=30)
+        payload.update(results=100)
         return payload
 
         return payload
 
-    def purge_cache(self, age=4):
-        now = datetime.utcnow()
-        if now.hour == SimaEch.timestamp.hour:
-            return
-        SimaEch.timestamp = datetime.utcnow()
-        cache = SimaEch.cache
-        delta = timedelta(hours=age)
-        for url in list(cache.keys()):
-            timestamp = cache.get(url).created()
-            if now - timestamp > delta:
-                cache.pop(url)
-
     def get_similar(self, artist=None):
         """
         """
     def get_similar(self, artist=None):
         """
         """
@@ -177,9 +178,10 @@ class SimaEch():
             artist = {}
             mbid = None
             if 'foreign_ids' in art:
             artist = {}
             mbid = None
             if 'foreign_ids' in art:
-               for frgnid in art.get('foreign_ids'):
-                   if frgnid.get('catalog') == 'musicbrainz':
-                       mbid = frgnid.get('foreign_id').lstrip('musicbrainz:artist:')
+                for frgnid in art.get('foreign_ids'):
+                    if frgnid.get('catalog') == 'musicbrainz':
+                        mbid = frgnid.get('foreign_id'
+                                          ).lstrip('musicbrainz:artist:')
             yield Artist(mbid=mbid, name=art.get('name'))
 
 
             yield Artist(mbid=mbid, name=art.get('name'))