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
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
)
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
38 def __init__(self
, podcasts
, user
):
39 super(PodcastPercentageListenedSorter
, self
).__init
__(podcasts
)
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
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"""
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
)
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()