1 from mygpo
.podcasts
.models
import Podcast
2 from mygpo
.db
.couchdb
.user
import get_num_listened_episodes
5 class PodcastSorter(object):
6 """ Sorts a list of podcast """
8 def __init__(self
, podcasts
):
9 self
.podcasts
= podcasts
10 self
.sorted_podcasts
= None
18 return len(self
.podcasts
)
21 def __getitem__(self
, val
):
22 if self
.sorted_podcasts
is None:
23 self
.sorted_podcasts
= self
._sort
()
25 return self
.sorted_podcasts
.__getitem
__(val
)
28 if self
.sorted_podcasts
is None:
29 self
.sorted_podcasts
= self
._sort
()
31 return iter(self
.sorted_podcasts
)
35 class PodcastPercentageListenedSorter(PodcastSorter
):
36 """ Sorts podcasts by the percentage of listened episodes
38 Adds the attributes percent_listened and episodes_listened to the podcasts
42 def __init__(self
, podcasts
, user
):
43 super(PodcastPercentageListenedSorter
, self
).__init
__(podcasts
)
49 SORT_KEY
= lambda podcast
: podcast
.percent_listened
51 counts
= dict(get_num_listened_episodes(self
.user
))
52 for podcast
in self
.podcasts
:
53 c
= counts
.get(podcast
.get_id(), 0)
54 if podcast
.episode_count
:
55 podcast
.percent_listened
= c
/ float(podcast
.episode_count
)
56 podcast
.episodes_listened
= c
58 podcast
.percent_listened
= 0
59 podcast
.episodes_listened
= 0
61 return sorted(self
.podcasts
, key
=SORT_KEY
, reverse
=True)
64 def subscription_changes(device_id
, podcast_states
, since
, until
):
65 """ returns subscription changes for the device and podcast states """
68 for p_state
in podcast_states
:
69 change
= p_state
.get_change_between(device_id
, since
, until
)
70 if change
== 'subscribe':
71 add
.append( p_state
.ref_url
)
72 elif change
== 'unsubscribe':
73 rem
.append( p_state
.ref_url
)
78 def podcasts_for_states(podcast_states
):
79 """ returns the podcasts corresponding to the podcast states """
81 podcast_ids
= [state
.podcast
for state
in podcast_states
]
82 podcasts
= Podcast
.objects
.filter(id__in
=podcast_ids
)
83 podcasts
= {podcast
.id.hex: podcast
for podcast
in podcasts
}
84 return podcasts
.values()
88 def get_subscribed_podcasts(user
, public
=None):
89 """ Returns all subscribed podcasts for the user
91 The attribute "url" contains the URL that was used when subscribing to
94 from mygpo
.db
.couchdb
.podcast_state
import get_subscribed_podcast_states_by_user
95 states
= get_subscribed_podcast_states_by_user(user
.profile
.uuid
.hex, public
)
96 podcast_ids
= [state
.podcast
for state
in states
]
97 podcasts
= Podcast
.objects
.filter(id__in
=podcast_ids
)
98 podcasts
= {podcast
.id: podcast
for podcast
in podcasts
}
101 podcast
= podcasts
.get(state
.podcast
, None)
105 podcast
= proxy_object(podcast
, url
=state
.ref_url
)
106 podcasts
[state
.podcast
] = podcast
108 return set(podcasts
.values())