MPDScrobbler: Add throttling
authorkaliko <kaliko.jack@azylum.org>
Wed, 2 Jan 2013 20:59:14 +0000 (21:59 +0100)
committerkaliko <kaliko.jack@azylum.org>
Wed, 2 Jan 2013 21:11:50 +0000 (22:11 +0100)
misc/MPDScrobbler/mpdscrobbler.py
misc/clientpy2.py

index ec7e3d5..fe7bee7 100755 (executable)
@@ -72,11 +72,12 @@ class QueuManagement(threading.Thread):
             self.queu.appendleft(track)
         else:
             self.queu.remove(track)
+            return True
 
     def run(self):
         for i in xrange(len(self.queu_copy)):
-            #TODO: throttle? should be in scrobble function…
-            self.scrobble_queu()
+            if not self.scrobble_queu():
+                return
 
 
 class MpdScrobbler(Player):
index 666804a..e8ef3e0 100755 (executable)
 import urllib2
 from urllib import urlencode
 
-from time import time
+from time import time, sleep
 from urllib2 import URLError, HTTPError
 
+from datetime import datetime, timedelta
+
+
+WAIT_BETWEEN_REQUESTS = timedelta(0, 0.9)
+
+
+class Throttle(object):
+    def __init__(self, wait):
+        self.wait = wait
+        self.last_called = datetime.now()
+
+    def __call__(self, func):
+        def wrapper(*args, **kwargs):
+            while self.last_called + self.wait > datetime.now():
+                sleep(0.2)
+            result = func(*args, **kwargs)
+            self.last_called = datetime.now()
+            return result
+        return wrapper
+
 
 class Track(object):
     """
@@ -52,6 +72,7 @@ def get_api_options(track):
             options[v] = track.__getattribute__(k)
     return options
 
+@Throttle(WAIT_BETWEEN_REQUESTS)
 def scrobble(trk=None, user=None, pwd=None, srv=None):
     sc_url = u'https://{server}/api/{user}/scrobbles/'
     url = sc_url.format(user=user, server=srv)