refactor mgmt cmd update-toplist to use just CouchDB
[mygpo.git] / mygpo / directory / management / commands / update-toplist.py
blob280441e35898a3258feb1514b0148ef85297a097
1 from datetime import datetime
3 from django.core.management.base import BaseCommand
5 from mygpo.core.models import Podcast, SubscriberData
6 from mygpo.users.models import PodcastUserState
7 from mygpo.utils import progress
8 from mygpo.decorators import repeat_on_conflict
11 class Command(BaseCommand):
13 def handle(self, *args, **options):
15 # couchdbkit doesn't preserve microseconds
16 started = datetime.utcnow().replace(microsecond=0)
18 podcasts = Podcast.all_podcasts()
19 total = Podcast.view('core/podcasts_by_oldid', limit=0).total_rows
21 for n, podcast in enumerate(podcasts):
22 subscriber_count = self.get_subscriber_count(podcast.get_id())
23 self.update(podcast=podcast, started=started, subscriber_count=subscriber_count)
24 progress(n, total)
27 @repeat_on_conflict(['podcast'])
28 def update(self, podcast, started, subscriber_count):
30 # We've already updated this podcast
31 if started in [e.timestamp for e in podcast.subscribers]:
32 return
34 data = SubscriberData(
35 timestamp = started,
36 subscriber_count = max(0, subscriber_count),
39 podcast.subscribers = sorted(podcast.subscribers + [data], key=lambda e: e.timestamp)
40 podcast.save()
43 @staticmethod
44 def get_subscriber_count(podcast_id):
45 db = PodcastUserState.get_db()
46 x = db.view('users/subscriptions_by_podcast',
47 startkey = [podcast_id, None],
48 endkey = [podcast_id, {}],
49 reduce = True,
50 group = True,
51 group_level = 2,
53 return x.count()