Bump babel from 2.9.1 to 2.10.3
[mygpo.git] / mygpo / users / subscriptions.py
blob9c9382e6e70b1482bc0ed2791c670302bc1d2c9f
1 from mygpo.podcasts.models import Podcast
2 from mygpo.history.stats import played_episode_counts
5 class PodcastSorter(object):
6 """Sorts a list of podcast"""
8 def __init__(self, podcasts):
9 self.podcasts = podcasts
10 self.sorted_podcasts = None
12 def _sort(self):
13 return self.podcasts
15 def __len__(self):
16 return len(self.podcasts)
18 def __getitem__(self, val):
19 if self.sorted_podcasts is None:
20 self.sorted_podcasts = self._sort()
22 return self.sorted_podcasts.__getitem__(val)
24 def __iter__(self):
25 if self.sorted_podcasts is None:
26 self.sorted_podcasts = self._sort()
28 return iter(self.sorted_podcasts)
31 class PodcastPercentageListenedSorter(PodcastSorter):
32 """Sorts podcasts by the percentage of listened episodes
34 Adds the attributes percent_listened and episodes_listened to the podcasts
36 Cost: 1 DB query"""
38 def __init__(self, podcasts, user):
39 super(PodcastPercentageListenedSorter, self).__init__(podcasts)
40 self.user = user
42 def _sort(self):
44 SORT_KEY = lambda podcast: podcast.percent_listened
46 counts = played_episode_counts(self.user)
47 for podcast in self.podcasts:
48 c = counts.get(podcast.id, 0)
49 if podcast.episode_count:
50 podcast.percent_listened = c / float(podcast.episode_count)
51 podcast.episodes_listened = c
52 else:
53 podcast.percent_listened = 0
54 podcast.episodes_listened = 0
56 return sorted(self.podcasts, key=SORT_KEY, reverse=True)
59 def subscription_changes(device_id, podcast_states, since, until):
60 """returns subscription changes for the device and podcast states"""
62 add, rem = [], []
63 for p_state in podcast_states:
64 change = p_state.get_change_between(device_id, since, until)
65 if change == "subscribe":
66 add.append(p_state.ref_url)
67 elif change == "unsubscribe":
68 rem.append(p_state.ref_url)
70 return add, rem
73 def podcasts_for_states(podcast_states):
74 """returns the podcasts corresponding to the podcast states"""
76 podcast_ids = [state.podcast for state in podcast_states]
77 podcasts = Podcast.objects.filter(id__in=podcast_ids)
78 podcasts = {podcast.id.hex: podcast for podcast in podcasts}
79 return podcasts.values()