Removed outdated scripts, numerous bugfixes to api
authorKristoffer Grönlund <kristoffer.gronlund@purplescout.se>
Thu, 31 Dec 2009 02:09:24 +0000 (03:09 +0100)
committerKristoffer Grönlund <kristoffer.gronlund@purplescout.se>
Sat, 2 Jan 2010 23:37:44 +0000 (00:37 +0100)
jamaendo/api.py
jamaui/console.py
jamaui/player.py
scripts/query [deleted file]
scripts/refresh_db [deleted file]

index 8bd7d91..9155040 100644 (file)
@@ -97,7 +97,7 @@ class Artist(LazyQuery):
             self.set_from_json(json)
 
     def _needs_load(self):
-        return self._needs_load_impl('name', 'image', 'albums')
+        return self._needs_load_impl('name', 'albums')
 
     def _set_from(self, other):
         return self._set_from_impl(other, 'name', 'image', 'albums')
@@ -139,7 +139,7 @@ class Track(LazyQuery):
        return _OGGURL%(self.ID)
 
     def _needs_load(self):
-        return self._needs_load_impl('name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
+        return self._needs_load_impl('name', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
 
     def _set_from(self, other):
         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
@@ -175,8 +175,8 @@ _CACHED_RADIOS = 10
 # TODO: cache queries?
 
 class Query(object):
-    last_query = time.time()
     rate_limit = 1.0 # max queries per second
+    last_query = time.time() - 1.5
 
     @classmethod
     def _ratelimit(cls):
@@ -189,7 +189,8 @@ class Query(object):
         pass
 
     def _geturl(self, url):
-        print "geturl: %s" % (url)
+        print "*** %s" % (url)
+        Query._ratelimit()
         f = urllib.urlopen(url)
         ret = simplejson.load(f)
         f.close()
@@ -292,7 +293,7 @@ class GetQuery(Query):
             },
         'radio' : {
             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/radio_track_inradioplaylist+track_album+album_artist/?',
-            'params' : 'order=numradio_asc&radio_id=%d',
+            'params' : 'order=random_asc&radio_id=%d',
             'constructor' : [Track]
             },
         'favorite_albums' : {
@@ -382,6 +383,8 @@ def get_artist(artist_id):
         if not a:
             raise JamendoAPIException(str(q))
         _update_cache(_artists, a)
+        if isinstance(a, list):
+            a = a[0]
     return a
 
 def get_albums(artist_id):
@@ -402,6 +405,8 @@ def get_album(album_id):
         if not a:
             raise JamendoAPIException(str(q))
         _update_cache(_albums, a)
+        if isinstance(a, list):
+            a = a[0]
     return a
 
 def get_tracks(album_id):
@@ -422,6 +427,8 @@ def get_track(track_id):
         if not a:
             raise JamendoAPIException(str(q))
         _update_cache(_tracks, a)
+        if isinstance(a, list):
+            a = a[0]
     return a
 
 def get_radio_tracks(radio_id):
@@ -494,9 +501,8 @@ def get_radio(radio_id):
     if not js:
         raise JamendoAPIException(str(q))
     if isinstance(js, list):
-        return [Radio(x['id'], json=x) for x in js]
-    else:
-        return Radio(radio_id, json=js)
+        ks = js[0]
+    return Radio(radio_id, json=js)
 
 def starred_radios():
     """Returns: [Radio]"""
@@ -526,6 +532,7 @@ Artist.load = _artist_loader
 def _album_loader(self):
     if self._needs_load():
         album = get_album(self.ID)
+        album.tracks = get_tracks(self.ID)
         self._set_from(album)
 Album.load = _album_loader
 
index 7aef530..828558d 100644 (file)
@@ -6,97 +6,52 @@ local_module_dir = os.path.join(os.path.dirname(sys.argv[0]), '..')
 if os.path.isdir(local_module_dir):
     sys.path.append(local_module_dir)
 
-from jamaendo.api import LocalDB, Query, Queries, refresh_dump
+import jamaendo
 from jamaui.player import Player, Playlist
 import time
 import gobject
 
 gobject.threads_init()
 
-class Refresher(object):
-    def __init__(self):
-        self.done = False
-        self.last_percent = 0
-        print "Preparing local database..."
-    def complete(self, status):
-        self.done = True
-    def progress(self, percent):
-        if percent - self.last_percent >= 5:
-            print "\r%d%%" % (percent),
-            self.last_percent = percent
-
-    def run(self):
-        refresh_dump(self.complete, self.progress, force=False)
-        while not self.done:
-            time.sleep(1)
+import pprint
 
+pp = pprint.PrettyPrinter(indent=4)
 
-def pprint(x):
-    import simplejson
-    print simplejson.dumps(x, sort_keys=True, indent=4)
+#pp.pprint(stuff)
 
 class Console(object):
     def run(self):
-        Refresher().run()
-
         query = sys.argv[1]
 
-        queries = ['today',
-                   'tracks_this_month',
-                   'artist',
-                   'album',
-                   'play_track',
-                   'play_album']
+        queries = ['albums_of_the_week', 'artists', 'albums']
         if query in queries:
             getattr(self, "query_"+query)()
         else:
             print "Valid queries: " + ", ".join(queries)
 
-    def query_today(self):
-        result = Queries.albums_today()
-        pprint(result)
-
-    def query_tracks_this_month(self):
-        result = Queries.tracks_this_month()
-        pprint(result)
-
-    def query_artist(self):
-        q = sys.argv[2]
-        db = LocalDB()
-        db.connect()
-        for artist in db.search_artists(q):
-            pprint(artist)
-
-    def query_album(self):
-        q = sys.argv[2]
-        db = LocalDB()
-        db.connect()
-        for album in db.search_albums(q):
-            print "%s: %s - %s" % (album['id'], album['artist'], album['name'])
-
-    def query_play_track(self):
-        trackid = int(sys.argv[2])
-        uri = Query.track_mp3(trackid)
-        playlist = Playlist([uri])
-        player = Player()
-        player.play(playlist)
-
-        while player.playing():
-            time.sleep(1)
-
-    def query_play_album(self):
-        albumid = int(sys.argv[2])
-        db = LocalDB()
-        db.connect()
-        album = None
-        for a in db.get_albums([albumid]):
-            album = a
-            break
-        if not album:
-            return
-        print "%s - %s" % (album['artist'], album['name'])
-
-        playlist = Playlist(album['tracks'])
+    def query_albums_of_the_week(self):
+        result = jamaendo.albums_of_the_week()
+        pp.pprint([(a.ID, a.name) for a in result])
+        for a in result:
+            self.play_album(a)
+
+    def query_artists(self):
+        result = jamaendo.search_artists(sys.argv[2])
+        pp.pprint([(a.ID, a.name) for a in result])
+        for a in result:
+            albums = jamaendo.get_albums(a.ID)
+            for album in albums:
+                print "Playing album: %s - %s" % (a.name, album.name)
+                self.play_album(album)
+
+    def query_albums(self):
+        result = jamaendo.search_albums(sys.argv[2])
+        pp.pprint([(a.ID, a.name) for a in result])
+        for a in result:
+            self.play_album(a)
+
+    def play_tracks(self, tracks):
+        playlist = Playlist(tracks)
         player = Player()
         player.play(playlist)
 
@@ -106,5 +61,12 @@ class Console(object):
             except KeyboardInterrupt:
                 player.next()
 
+    def play_album(self, album):
+        if not album.tracks:
+            album.load()
+        print "%s - %s" % (album.artist_name, album.name)
+        if album.tracks:
+            self.play_tracks(album.tracks)
+
 if __name__=="__main__":
     main()
index d67f9fc..f641c32 100644 (file)
@@ -26,6 +26,8 @@ import util
 import dbus
 import dbus.service
 
+import jamaendo
+
 log = logging.getLogger(__name__)
 
 class _Player(object):
@@ -215,12 +217,17 @@ class GStreamer(_Player):
         t = message.type
 
         if t == gst.MESSAGE_EOS:
+            log.info("End of stream")
             self.eos_callback()
-
+        elif t == gst.MESSAGE_STATE_CHANGED:
+            log.info("State changed: %s -> %s -> %s", old, new, pending)
+            old, new, pending = message.parse_state_changed()
         elif t == gst.MESSAGE_ERROR:
-            err, debug = message.parse_error()
             log.critical( 'Error: %s %s', err, debug )
+            err, debug = message.parse_error()
             self.stop()
+        else:
+            log.info("? %s", message.type)
 
     def set_eos_callback(self, cb):
         self.eos_callback = cb
@@ -311,33 +318,21 @@ if util.platform == 'maemo':
 PlayerBackend = GStreamer
 
 class Playlist(object):
-    class Entry(object):
-        def __init__(self, data):
-            if isinstance(data, dict):
-                self.id = data['id']
-                self.name = data['name']
-                self.image = data['image']
-                self.numalbum = int(data['numalbum'])
-                self.url = data['mp3']
-                self.type = 'mp3'
-            elif isinstance(data, basestring): # assume URI
-                self.id = 0
-                self.name = ''
-                self.image = None
-                self.numalbum = 0
-                self.url = data
-                self.type = 'mp3'
-        def __str__(self):
-            return "{%s}" % (", ".join([str(self.name), str(self.numalbum), str(self.url)]))
-
     def __init__(self, items = []):
         if items is None:
             items = []
-        self.items = [Playlist.Entry(item) for item in items]
+        for item in items:
+            assert(isinstance(item, jamaendo.Track))
+        self.items = items
         self._current = -1
 
     def add(self, item):
-        self.items.append(Playlist.Entry(item))
+        if isinstance(item, list):
+            for i in item:
+                assert(isinstance(i, jamaendo.Track))
+            self.items.extend(item)
+        else:
+            self.items.append(item)
 
     def next(self):
         if self.has_next():
@@ -372,7 +367,7 @@ class Player(Playlist):
             if self.playlist.has_next():
                 entry = self.playlist.next()
                 log.debug("playing %s", entry)
-                self.backend.play_url(entry.type, entry.url)
+                self.backend.play_url('mp3', entry.mp3_url())
 
     def pause(self):
         self.backend.pause()
diff --git a/scripts/query b/scripts/query
deleted file mode 100755 (executable)
index e1ef212..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-
-# debugging hack - add . to path
-import os, sys
-local_module_dir = os.path.join(os.path.dirname(sys.argv[0]), '..')
-if os.path.isdir(local_module_dir):
-    sys.path.append(local_module_dir)
-
-from jamaendo.api import LocalDB, Queries, refresh_dump
-import time
-
-class Refresher(object):
-    def __init__(self):
-        self.done = False
-        self.last_percent = 0
-        print "..."
-    def complete(self):
-        print "Done."
-        self.done = True
-    def progress(self, percent):
-        if percent - self.last_percent >= 5:
-            print "\r%d%%" % (percent),
-            self.last_percent = percent
-
-    def run(self):
-        refresh_dump(self.complete, self.progress, force=False)
-        while not self.done:
-            time.sleep(1)
-
-
-def pprint(x):
-    import simplejson
-    print simplejson.dumps(x, sort_keys=True, indent=4)
-
-def main():
-    Refresher().run()
-
-    query = sys.argv[1]
-
-    if query == 'today':
-        result = Queries.albums_today()
-        pprint(result)
-    elif query == 'tracks_this_month':
-        result = Queries.tracks_this_month()
-        pprint(result)
-    elif query == 'artist':
-        q = sys.argv[2]
-        db = LocalDB()
-        db.connect()
-        for artist in db.search_artists(q):
-            pprint(artist)
-    elif query == 'album':
-        q = sys.argv[2]
-        db = LocalDB()
-        db.connect()
-        for album in db.search_albums(q):
-            pprint(album)
-
-if __name__=="__main__":
-    main()
diff --git a/scripts/refresh_db b/scripts/refresh_db
deleted file mode 100755 (executable)
index b7b0412..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/usr/bin/env python
-from jamaendo.api import refresh_dump
-import time
-
-class Monitor(object):
-    def __init__(self):
-        self.done = False
-        self.last_percent = 0
-    def complete(self):
-        print "Done."
-        self.done = True
-    def progress(self, percent):
-        if percent - self.last_percent >= 5:
-            print "%d%%" % (percent)
-            self.last_percent = percent
-
-def main():
-    print "Updating jamendo DB dump..."
-    monitor = Monitor()
-    refresh_dump(monitor.complete, monitor.progress, force=False)
-    while not monitor.done:
-        time.sleep(1)
-
-if __name__ == "__main__":
-    main()