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
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
)
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
41 def __init__(self
, podcasts
, user
):
42 super(PodcastPercentageListenedSorter
, self
).__init
__(podcasts
)
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
57 podcast
.percent_listened
= 0
58 podcast
.episodes_listened
= 0
60 return sorted(self
.podcasts
, key
=SORT_KEY
, reverse
=True)