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 SuggestionEntry
, Subscription
, UserProfile
5 from mygpo
.data
.models
import RelatedPodcast
, SuggestionBlacklist
7 class Command(BaseCommand
):
9 option_list
= BaseCommand
.option_list
+ (
10 make_option('--max', action
='store', type='int', dest
='max', default
=15, help="Maximum number of suggested podcasts per user."),
11 make_option('--outdated-only', action
='store_true', dest
='outdated', default
=False, help="Update only users where the suggestions are not up-to-date"),
12 make_option('--user', action
='store', type='string', dest
='username', default
='', help="Update a specific user"),
15 def handle(self
, *args
, **options
):
17 max = options
.get('max')
19 users
= User
.objects
.filter(is_active
=True)
21 if options
.get('outdated'):
22 users
= users
.filter(userprofile__suggestion_up_to_date
=False)
24 if options
.get('username'):
25 users
= users
.filter(username
=options
.get('username'))
28 subscribed_podcasts
= set([s
.podcast
for s
in Subscription
.objects
.filter(user
=user
)])
29 related
= RelatedPodcast
.objects
.filter(ref_podcast__in
=subscribed_podcasts
).exclude(rel_podcast__in
=subscribed_podcasts
)
33 # remove potential suggestions that are in the same group as already subscribed podcasts
34 if r
.rel_podcast
.group
and Subscription
.objects
.filter(podcast__group
=r
.rel_podcast
.group
).exists():
37 # don't suggest blacklisted podcasts
38 if SuggestionBlacklist
.objects
.filter(user
=user
, podcast
=r
.rel_podcast
).exists():
41 related_podcasts
[r
.rel_podcast
] = related_podcasts
.get(r
.rel_podcast
, 0) + r
.priority
44 podcast_list
= [(p
, podcast
) for (p
, podcast
) in related_podcasts
.iteritems()]
45 podcast_list
.sort(key
=lambda (p
, priority
): priority
, reverse
=True)
47 SuggestionEntry
.objects
.filter(user
=user
).delete()
48 for (p
, priority
) in podcast_list
[:max]:
49 SuggestionEntry
.objects
.create(podcast
=p
, priority
=priority
, user
=user
)
51 # flag suggestions up-to-date
52 p
, _created
= UserProfile
.objects
.get_or_create(user
=user
)
53 p
.suggestion_up_to_date
= True