[Migration] remove remaining CouchDB related code
[mygpo.git] / mygpo / users / subscriptions.py
blobe8460a50b75369e5aac9cf07a49b81827dd1c049
1 import collections
2 from operator import itemgetter
4 from mygpo.utils import linearize
5 from mygpo.podcasts.models import Podcast
6 from mygpo.history.stats import played_episode_counts
9 class PodcastSorter(object):
10 """ Sorts a list of podcast """
12 def __init__(self, podcasts):
13 self.podcasts = podcasts
14 self.sorted_podcasts = None
17 def _sort(self):
18 return self.podcasts
21 def __len__(self):
22 return len(self.podcasts)
25 def __getitem__(self, val):
26 if self.sorted_podcasts is None:
27 self.sorted_podcasts = self._sort()
29 return self.sorted_podcasts.__getitem__(val)
31 def __iter__(self):
32 if self.sorted_podcasts is None:
33 self.sorted_podcasts = self._sort()
35 return iter(self.sorted_podcasts)
39 class PodcastPercentageListenedSorter(PodcastSorter):
40 """ Sorts podcasts by the percentage of listened episodes
42 Adds the attributes percent_listened and episodes_listened to the podcasts
44 Cost: 1 DB query """
46 def __init__(self, podcasts, user):
47 super(PodcastPercentageListenedSorter, self).__init__(podcasts)
48 self.user = user
51 def _sort(self):
53 SORT_KEY = lambda podcast: podcast.percent_listened
55 counts = played_episode_counts(self.user)
56 for podcast in self.podcasts:
57 c = counts.get(podcast.id, 0)
58 if podcast.episode_count:
59 podcast.percent_listened = c / float(podcast.episode_count)
60 podcast.episodes_listened = c
61 else:
62 podcast.percent_listened = 0
63 podcast.episodes_listened = 0
65 return sorted(self.podcasts, key=SORT_KEY, reverse=True)
68 def subscription_changes(device_id, podcast_states, since, until):
69 """ returns subscription changes for the device and podcast states """
71 add, rem = [], []
72 for p_state in podcast_states:
73 change = p_state.get_change_between(device_id, since, until)
74 if change == 'subscribe':
75 add.append( p_state.ref_url )
76 elif change == 'unsubscribe':
77 rem.append( p_state.ref_url )
79 return add, rem
82 def podcasts_for_states(podcast_states):
83 """ returns the podcasts corresponding to the podcast states """
85 podcast_ids = [state.podcast for state in podcast_states]
86 podcasts = Podcast.objects.filter(id__in=podcast_ids)
87 podcasts = {podcast.id.hex: podcast for podcast in podcasts}
88 return podcasts.values()