1 from django
.core
.management
.base
import BaseCommand
2 from django
.contrib
.auth
.models
import User
3 from optparse
import make_option
4 from mygpo
.api
.models
import Podcast
, SuggestionEntry
, Subscription
, UserProfile
5 from mygpo
.data
.models
import RelatedPodcast
, SuggestionBlacklist
6 from mygpo
.data
.podcast
import calc_similar_podcasts
8 class Command(BaseCommand
):
10 option_list
= BaseCommand
.option_list
+ (
11 make_option('--max', action
='store', type='int', dest
='max', default
=15, help="Maximum number of suggested podcasts per user."),
12 make_option('--outdated-only', action
='store_true', dest
='outdated', default
=False, help="Update only users where the suggestions are not up-to-date"),
13 make_option('--user', action
='store', type='string', dest
='username', default
='', help="Update a specific user"),
16 def handle(self
, *args
, **options
):
18 max = options
.get('max')
20 users
= User
.objects
.filter(is_active
=True)
22 if options
.get('outdated'):
23 users
= users
.filter(userprofile__suggestion_up_to_date
=False)
25 if options
.get('username'):
26 users
= users
.filter(username
=options
.get('username'))
29 subscribed_podcasts
= set([s
.podcast
for s
in Subscription
.objects
.filter(user
=user
)])
30 related
= RelatedPodcast
.objects
.filter(ref_podcast__in
=subscribed_podcasts
).exclude(rel_podcast__in
=subscribed_podcasts
)
34 # remove potential suggestions that are in the same group as already subscribed podcasts
35 if r
.rel_podcast
.group
and Subscription
.objects
.filter(podcast__group
=r
.rel_podcast
.group
).exists():
38 # don't suggest blacklisted podcasts
39 if SuggestionBlacklist
.objects
.filter(user
=user
, podcast
=r
.rel_podcast
).exists():
42 related_podcasts
[r
.rel_podcast
] = related_podcasts
.get(r
.rel_podcast
, 0) + r
.priority
45 podcast_list
= [(p
, podcast
) for (p
, podcast
) in related_podcasts
.iteritems()]
46 podcast_list
.sort(key
=lambda (p
, priority
): priority
, reverse
=True)
48 SuggestionEntry
.objects
.filter(user
=user
).delete()
49 for (p
, priority
) in podcast_list
[:max]:
50 SuggestionEntry
.objects
.create(podcast
=p
, priority
=priority
, user
=user
)
52 # flag suggestions up-to-date
53 p
, _created
= UserProfile
.objects
.get_or_create(user
=user
)
54 p
.suggestion_up_to_date
= True