Ejemplo n.º 1
0
    def get_json(self):
        end = datetime.now()
        start = end - timedelta(days=7)
        qs = PlayCountSnapshot.all().filter("established >=", start).filter("established <=", end)

        # Collect the play counts.
        weekly = {}
        for count in qs.run():
            id = count.track_id
            weekly.setdefault(id, {"play_count": []})
            weekly[id].update(
                {"artist": count.artist_name, "release": count.album_title, "label": count.label, "id": id}
            )
            weekly[id]["play_count"].append(count.play_count)

        for key, stat in weekly.iteritems():
            pc = stat["play_count"]
            weekly[key].update(
                {
                    # Average the play counts per release.
                    "play_count": int(round(sum(pc) / len(pc), 1)),
                    # Make this ID shorter so it's easier for clients.
                    "id": hashlib.sha1(stat["id"]).hexdigest(),
                }
            )

        # Sort the releases in descending order of play count.
        rel = sorted(weekly.values(), key=lambda c: (c["play_count"], c["release"]), reverse=True)
        # Limit to top 40.
        rel = rel[0:40]

        return {"this_week": {"start": start.strftime("%Y-%m-%d"), "end": end.strftime("%Y-%m-%d"), "releases": rel}}
Ejemplo n.º 2
0
def play_count_snapshot(request):
    """Cron view to create a play count snapshot (top 40)."""
    qs = PlayCount.all().order('-play_count')
    results = []
    for count in qs.fetch(40):
        results.append(PlayCountSnapshot.create_from_count(count))
    for res in results:
        res.get_result()  # wait for result
    log.info('Created play count snapshot')
Ejemplo n.º 3
0
def play_count_snapshot(request):
    """Cron view to create a play count snapshot (top 40)."""
    qs = PlayCount.all().order('-play_count')
    results = []
    for count in qs.fetch(40):
        results.append(PlayCountSnapshot.create_from_count(count))
    for res in results:
        res.get_result()  # wait for result
    log.info('Created play count snapshot')
Ejemplo n.º 4
0
def clear_data():
    for pl in Playlist.all():
        for track in PlaylistTrack.all().filter('playlist =', pl):
            track.delete()
        pl.delete()
    for u in User.all():
        u.delete()
    for ob in PlayCountSnapshot.all():
        ob.delete()
Ejemplo n.º 5
0
def clear_data():
    for pl in Playlist.all():
        for track in PlaylistTrack.all().filter('playlist =', pl):
            track.delete()
        pl.delete()
    for u in User.all():
        u.delete()
    for ob in PlayCountSnapshot.all():
        ob.delete()
Ejemplo n.º 6
0
 def setUp(self):
     super(TestPlayStats, self).setUp()
     dbconfig['lastfm.api_key'] = 'SEKRET_LASTFM_KEY'
     PlayCountSnapshot(track_id='1',
                       play_count=5,
                       artist_name='Tame Impala',
                       album_title='Lonerism',
                       label='label1').put()
     PlayCountSnapshot(track_id='1',
                       play_count=5,
                       artist_name='Tame Impala',
                       album_title='Lonerism',
                       label='label1').put()
     PlayCountSnapshot(track_id='2',
                       play_count=20,
                       artist_name='Taken By Trees',
                       album_title='Dreams',
                       label='label2').put()
Ejemplo n.º 7
0
 def test_snapshot_count_track_ids(self):
     self.count()
     self.count()
     res = self.snapshot()
     res = self.snapshot()  # second run
     track_ids = [w.track_id for w in PlayCountSnapshot.all()]
     # For the same track name and album, the IDs should be the same.
     eq_(track_ids[0], track_ids[1])
     assert track_ids[0] is not None
     assert track_ids[1] is not None
Ejemplo n.º 8
0
 def test_snapshot_count_track_ids(self):
     self.count()
     self.count()
     res = self.snapshot()
     res = self.snapshot()  # second run
     track_ids = [w.track_id for w in PlayCountSnapshot.all()]
     # For the same track name and album, the IDs should be the same.
     eq_(track_ids[0], track_ids[1])
     assert track_ids[0] is not None
     assert track_ids[1] is not None
Ejemplo n.º 9
0
 def test_snapshot_count(self):
     self.count()
     self.count()
     res = self.snapshot()
     eq_(res.status_code, 200)
     snap = PlayCountSnapshot.all()[0]
     eq_(snap.established.strftime('%Y-%m-%d'),
         datetime.datetime.now().strftime('%Y-%m-%d'))
     eq_(snap.play_count, 2)
     eq_(snap.artist_name, self.track.artist_name)
     eq_(snap.album_title, self.track.album_title)
     eq_(snap.label, self.track.label)
Ejemplo n.º 10
0
 def test_snapshot_count(self):
     self.count()
     self.count()
     res = self.snapshot()
     eq_(res.status_code, 200)
     snap = PlayCountSnapshot.all()[0]
     eq_(snap.established.strftime('%Y-%m-%d'),
         datetime.datetime.now().strftime('%Y-%m-%d'))
     eq_(snap.play_count, 2)
     eq_(snap.artist_name, self.track.artist_name)
     eq_(snap.album_title, self.track.album_title)
     eq_(snap.label, self.track.label)
Ejemplo n.º 11
0
 def test_this_week(self):
     p = PlayCountSnapshot(
         track_id='3',
         play_count=1,
         artist_name='Ignore Me',
         album_title='Inore This',
         label='...',
         # This was entered older than a week.
         established=datetime.now() - timedelta(days=8))
     p.put()
     res = self.request('/api/stats')
     weekly = res['this_week']['releases']
     eq_(weekly[0]['artist'], 'Taken By Trees')
     eq_(weekly[0]['release'], 'Dreams')
     eq_(weekly[0]['label'], 'label2')
     eq_(weekly[0]['play_count'], 20)
     assert 'id' in weekly[0]
     eq_(weekly[1]['artist'], 'Tame Impala')
     eq_(weekly[1]['release'], 'Lonerism')
     eq_(weekly[1]['label'], 'label1')
     eq_(weekly[1]['play_count'], 5)
     eq_(len(weekly), 2, weekly)
Ejemplo n.º 12
0
 def test_this_week(self):
     p = PlayCountSnapshot(
         track_id='3',
         play_count=1,
         artist_name='Ignore Me',
         album_title='Inore This',
         label='...',
         # This was entered older than a week.
         established=datetime.now() - timedelta(days=8)
     )
     p.put()
     res = self.request('/api/stats')
     weekly = res['this_week']['releases']
     eq_(weekly[0]['artist'], 'Taken By Trees')
     eq_(weekly[0]['release'], 'Dreams')
     eq_(weekly[0]['label'], 'label2')
     eq_(weekly[0]['play_count'], 20)
     assert 'id' in weekly[0]
     eq_(weekly[1]['artist'], 'Tame Impala')
     eq_(weekly[1]['release'], 'Lonerism')
     eq_(weekly[1]['label'], 'label1')
     eq_(weekly[1]['play_count'], 5)
     eq_(len(weekly), 2, weekly)
Ejemplo n.º 13
0
    def get_json(self):
        end = datetime.now()
        start = end - timedelta(days=7)
        qs = (PlayCountSnapshot.all().filter('established >=', start).filter(
            'established <=', end))

        # Collect the play counts.
        weekly = {}
        for count in qs.run():
            id = count.track_id
            weekly.setdefault(id, {'play_count': []})
            weekly[id].update({
                'artist': count.artist_name,
                'release': count.album_title,
                'label': count.label,
                'id': id
            })
            weekly[id]['play_count'].append(count.play_count)

        for key, stat in weekly.iteritems():
            pc = stat['play_count']
            weekly[key].update({
                # Average the play counts per release.
                'play_count': int(round(sum(pc) / len(pc), 1)),
                # Make this ID shorter so it's easier for clients.
                'id': hashlib.sha1(stat['id']).hexdigest()
            })

        # Sort the releases in descending order of play count.
        rel = sorted(weekly.values(),
                     key=lambda c: (c['play_count'], c['release']),
                     reverse=True)
        # Limit to top 40.
        rel = rel[0:40]

        return {
            'this_week': {
                'start': start.strftime('%Y-%m-%d'),
                'end': end.strftime('%Y-%m-%d'),
                'releases': rel
            }
        }
Ejemplo n.º 14
0
    def get_json(self):
        end = datetime.now()
        start = end - timedelta(days=7)
        qs = (PlayCountSnapshot.all()
              .filter('established >=', start)
              .filter('established <=', end))

        # Collect the play counts.
        weekly = {}
        for count in qs.run():
            id = count.track_id
            weekly.setdefault(id, {'play_count': []})
            weekly[id].update({'artist': count.artist_name,
                               'release': count.album_title,
                               'label': count.label,
                               'id': id})
            weekly[id]['play_count'].append(count.play_count)

        for key, stat in weekly.iteritems():
            pc = stat['play_count']
            weekly[key].update({
                # Average the play counts per release.
                'play_count': int(round(sum(pc) / len(pc), 1)),
                # Make this ID shorter so it's easier for clients.
                'id': hashlib.sha1(stat['id']).hexdigest()
            })

        # Sort the releases in descending order of play count.
        rel = sorted(weekly.values(),
                     key=lambda c: (c['play_count'], c['release']),
                     reverse=True)
        # Limit to top 40.
        rel = rel[0:40]

        return {
            'this_week': {
                'start': start.strftime('%Y-%m-%d'),
                'end': end.strftime('%Y-%m-%d'),
                'releases': rel
            }
        }
Ejemplo n.º 15
0
 def test_freeform_compilation(self):
     stevie, talking_book, tracks = create_stevie_wonder_album_data()
     talking_book.is_compilation = True
     talking_book.put()
     for artist, track in (('Stevie Wonder', 'Superstition'),
                           ('Stevie Wonder', 'Big Brother')):
         new_trk = PlaylistTrack(
             playlist=self.track.playlist,
             selector=self.track.selector,
             freeform_album_title='Talking Book',
             freeform_artist_name=artist,
             freeform_track_title=track,
             freeform_label='...')
         new_trk.put()
         self.count(track_key=new_trk.key())
     res = self.snapshot()
     eq_(res.status_code, 200)
     snap = PlayCountSnapshot.all()[0]
     eq_(snap.play_count, 2)
     eq_(snap.artist_name, 'Various')
     eq_(snap.album_title, 'Talking Book')
Ejemplo n.º 16
0
 def test_freeform_compilation(self):
     stevie, talking_book, tracks = create_stevie_wonder_album_data()
     talking_book.is_compilation = True
     talking_book.put()
     for artist, track in (('Stevie Wonder', 'Superstition'),
                           ('Stevie Wonder', 'Big Brother')):
         new_trk = PlaylistTrack(
             playlist=self.track.playlist,
             selector=self.track.selector,
             freeform_album_title='Talking Book',
             freeform_artist_name=artist,
             freeform_track_title=track,
             freeform_label='...')
         new_trk.put()
         self.count(track_key=new_trk.key())
     res = self.snapshot()
     eq_(res.status_code, 200)
     snap = PlayCountSnapshot.all()[0]
     eq_(snap.play_count, 2)
     eq_(snap.artist_name, 'Various')
     eq_(snap.album_title, 'Talking Book')