36e5037a31413c69d14448392cb824dc0f1d4883
[mygpo.git] / mygpo / users / subscriptions.py
blob36e5037a31413c69d14448392cb824dc0f1d4883
1 from mygpo.db.couchdb.user import get_num_listened_episodes
4 class PodcastSorter(object):
5 """ Sorts a list of podcast """
7 def __init__(self, podcasts):
8 self.podcasts = podcasts
9 self.sorted_podcasts = None
12 def _sort(self):
13 return self.podcasts
16 def __len__(self):
17 return len(self.podcasts)
20 def __getitem__(self, val):
21 if self.sorted_podcasts is None:
22 self.sorted_podcasts = self._sort()
24 return self.sorted_podcasts.__getitem__(val)
26 def __iter__(self):
27 if self.sorted_podcasts is None:
28 self.sorted_podcasts = self._sort()
30 return iter(self.sorted_podcasts)
34 class PodcastPercentageListenedSorter(PodcastSorter):
35 """ Sorts podcasts by the percentage of listened episodes
37 Adds the attributes percent_listened and episodes_listened to the podcasts
39 Cost: 1 DB query """
41 def __init__(self, podcasts, user):
42 super(PodcastPercentageListenedSorter, self).__init__(podcasts)
43 self.user = user
46 def _sort(self):
48 SORT_KEY = lambda podcast: podcast.percent_listened
50 counts = dict(get_num_listened_episodes(self.user))
51 for podcast in self.podcasts:
52 c = counts.get(podcast.get_id(), 0)
53 if podcast.episode_count:
54 podcast.percent_listened = c / float(podcast.episode_count)
55 podcast.episodes_listened = c
56 else:
57 podcast.percent_listened = 0
58 podcast.episodes_listened = 0
60 return sorted(self.podcasts, key=SORT_KEY, reverse=True)