move all PodcastUserState db queries into separate module
[mygpo.git] / mygpo / directory / management / commands / update-toplist.py
blob5d7f537f8907731afdfbfe29fbb289a666005526
1 from datetime import datetime
2 from optparse import make_option
4 from django.core.management.base import BaseCommand
6 from mygpo.core.models import Podcast, SubscriberData
7 from mygpo.couch import get_main_database
8 from mygpo.utils import progress
9 from mygpo.decorators import repeat_on_conflict
10 from mygpo.db.couchdb.podcast import podcast_count, all_podcasts
11 from mygpo.db.couchdb.podcast_state import podcast_subscriber_count
14 class Command(BaseCommand):
16 option_list = BaseCommand.option_list + (
17 make_option('--silent', action='store_true', dest='silent',
18 default=False, help="Don't show any output"),
21 def handle(self, *args, **options):
23 silent = options.get('silent')
25 # couchdbkit doesn't preserve microseconds
26 started = datetime.utcnow().replace(microsecond=0)
28 podcasts = all_podcasts()
29 total = podcast_count()
31 for n, podcast in enumerate(podcasts):
32 subscriber_count = podcast_subscriber_count(podcast)
33 self.update(podcast=podcast, started=started, subscriber_count=subscriber_count)
35 if not silent:
36 progress(n, total)
39 @repeat_on_conflict(['podcast'])
40 def update(self, podcast, started, subscriber_count):
42 # We've already updated this podcast
43 if started in [e.timestamp for e in podcast.subscribers]:
44 return
46 data = SubscriberData(
47 timestamp = started,
48 subscriber_count = max(0, subscriber_count),
51 podcast.subscribers = sorted(podcast.subscribers + [data], key=lambda e: e.timestamp)
52 podcast.save()