Commits

Stefan Scherfke committed 3f9067c

complete refactoring. works, but no docstrings yet.

Comments (0)

Files changed (4)

templates/lastfm_widget/_widget.html

-{% for track in tracks %}<div class="lastfm"><a href="{{ track.url }}"><img src="{{ track.img_url }}" alt="{{ track.title }}" title="{{ track.title }}" /></a></div>{% endfor %}
+<div id="lastfm">
+<script type="text/javascript" charset="utf-8">
+    $.getJSON("{% url lastfm %}",
+        function(data) {
+            $.each(data, function(i, item) {
+                img = $("<img />").attr({
+                        'src': item.img_url, 
+                        'alt': item.title, 
+                        'title': item.title
+                })
+                a = $("<a />").attr('href', item.url ).append(img)
+                div = $("<div />").append(a)
+                div.appendTo('#lastfm')
+            });
+        });
+</script>
+</div>

templatetags/lastfm_widget.py

     """Renders the weblog’s sidebar widgets."""
     def __init__(self, var_name):
         self.var_name = var_name
-        self.chart_types = {
-            'recent_tracks': self._get_recent_tracks,
-            'weekly_top_artists': self._get_weekly_top_artists,
-            'top_artists': self._get_top_artists,
-        }
-        self.url = 'http://ws.audioscrobbler.com/2.0/?'
+        # self.chart_types = {
+        #     'recent_tracks': self._get_recent_tracks,
+        #     'weekly_top_artists': self._get_weekly_top_artists,
+        #     'top_artists': self._get_top_artists,
+        # }
+        # self.url = 'http://ws.audioscrobbler.com/2.0/?'
         
     def render(self, context):
         # try:
-        data = self.chart_types[settings.LASTFM_CHART_TYPE]()
+            # data = self.chart_types[settings.LASTFM_CHART_TYPE]()
         # except:
         #     data = []
         
         t = template.loader.get_template('lastfm_widget/_widget.html')
         lastfm_widget = {
             'title': settings.LASTFM_WIDGET_TITLE,
-            'content': t.render(template.Context({'tracks': data},
+            'content': t.render(template.Context({},
                     autoescape=context.autoescape)),
         }
         
         artists = []
         for d in data:
             artist = {
-                'title': d['name'] + ' (' + d['playcount'] + ' plays)',
+                'title': '%s (%s plays)' % (d['name'], d['playcount']),
                 'url': d['url'],
                 'img_url': 'http://cdn.last.fm/flatness/catalogue/' + \
                         'noimage/2/default_artist_large.png',
             if i == int(settings.LASTFM_NUM_IMAGES):
                 break
             artist = {
-                'title': d['name'],
+                'title': '%s (%s plays)' % (d['name'], d['playcount']),
                 'url': d['url'],
                 'img_url':'http://cdn.last.fm/flatness/catalogue/' + \
                         'noimage/2/default_artist_large.png',
 # encoding: utf-8
 """
-Tests for the Django weblog app.
+Tests for the last.fm app.
 """
 
 from django.test import TestCase
 import mock
 
-from highlight_code.templatetags.highlight_code import highlight
-from lastfm_widget.templatetags import lastfm_widget
+from lastfm.templatetags import lastfm_widget
 
 
 class TemplateTagsTestCase(TestCase):
-    """Test the template tags."""
+    """Test the template tag for the last.fm widget."""
     
     def setUp(self):
         self.parser = mock.Mock(spec=['compile_filter'])
+# encoding: utf-8
+
+import urllib
+
+from django.http import HttpResponse
+from django.utils import simplejson as json
+
+from django_site import settings
+
+
+def lastfm_data(request):
+    url = 'http://ws.audioscrobbler.com/2.0/?'
+    chart_types = {
+        'recent_tracks': RecentTracks,
+        'weekly_top_artists': WeeklyTopArtists,
+        'top_artists': TopArtists,
+    }
+    img_size = 'large'
+    if hasattr(settings, 'LASTFM_IMG_SIZE'):
+        img_size = settings.LASTFM_IMG_SIZE
+        
+    chart = chart_types[settings.LASTFM_CHART_TYPE]()
+    
+    params = urllib.urlencode(chart.params)
+    data = json.loads(urllib.urlopen(url + params).read())
+    
+    items = []
+    for i, d in enumerate(chart.get_data(data)):
+        # Not every last.fm method supports the ``limit`` parameter so we have
+        # to take care of this ourselves.
+        if i == int(settings.LASTFM_NUM_IMAGES):
+            break
+        
+        item = {
+            'title': chart.get_item_title(d),
+            'url': d['url'],
+            'img_url': chart.get_default_image(),
+        }
+        
+        if 'image' in d:
+            for img in d['image']:
+                if img['size'] == img_size and img['#text']:
+                    item['img_url'] = img['#text']
+                    break
+        else:
+            item['img_url'] = chart.get_img_url(url, img_size, d)
+        
+        items.append(item)
+        
+    return HttpResponse(json.dumps(items), mimetype='application/json')
+
+        
+class RecentTracks(object):
+    params = {
+        'method': 'user.getRecentTracks',
+        'user': settings.LASTFM_USER,
+        'limit': settings.LASTFM_NUM_IMAGES,
+        'api_key': settings.LASTFM_API_KEY,
+        'format': 'json',
+    }
+    
+    def get_data(self, data):
+        return data['recenttracks']['track']
+        
+    def get_item_title(self, item):
+        return u'%s – %s' % (item['artist']['#text'], item['name'])
+        
+    def get_default_image(self):
+        return 'http://cdn.last.fm/depth/catalogue/noimage/cover_85px.gif'
+
+        
+class WeeklyTopArtists(object):
+    params = {
+        'method': 'user.getWeeklyArtistChart',
+        'user': settings.LASTFM_USER,
+        'limit': settings.LASTFM_NUM_IMAGES,
+        'api_key': settings.LASTFM_API_KEY,
+        'format': 'json',
+    }
+    
+    def get_data(self, data):
+        return data['weeklyartistchart']['artist']
+        
+    def get_item_title(self, item):
+        return '%s (%s plays)' % (item['name'], item['playcount'])
+        
+    def get_default_image(self):
+        return 'http://cdn.last.fm/flatness/catalogue/noimage/2/' + \
+                'default_artist_large.png'
+
+    def get_img_url(self, url, img_size, item):
+        params = urllib.urlencode({
+            'method': 'artist.getimages',
+            'artist': item['name'],
+            'limit': 1,
+            'api_key': settings.LASTFM_API_KEY,
+            'format': 'json',
+        })
+        
+        img_data = json.loads(urllib.urlopen(url + params).read())['images']
+        if 'image' in img_data:
+            img_data = img_data['image']['sizes']['size']
+            for img in img_data:
+                if img['name'] == img_size and img['#text']:
+                    return img['#text']
+    
+    
+class TopArtists(object):
+    params = {
+        'method': 'user.getTopArtists',
+        'user': settings.LASTFM_USER,
+        'api_key': settings.LASTFM_API_KEY,
+        'period': settings.LASTFM_TOP_ARTISTS_PERIOD,
+        'format': 'json'
+    }
+    
+    def get_data(self, data):
+        return data['topartists']['artist']
+        
+    def get_item_title(self, item):
+        return '%s (%s plays)' % (item['name'], item['playcount'])
+        
+    def get_default_image(self):
+        return 'http://cdn.last.fm/flatness/catalogue/noimage/2/' + \
+                'default_artist_large.png'