Merge pull request #793 from gpodder/remove-advertise
[mygpo.git] / mygpo / suggestions / tasks.py
blob7fc6631f0e40cd1b9c5fa3d23d2610ff9f4939fd
1 from itertools import chain
2 from collections import Counter
4 from django.contrib.auth import get_user_model
6 from django_db_geventpool.utils import close_connection
8 from celery import shared_task
10 from mygpo.celery import celery
11 from mygpo.subscriptions import get_subscribed_podcasts
12 from mygpo.suggestions.models import PodcastSuggestion
14 from celery.utils.log import get_task_logger
16 logger = get_task_logger(__name__)
19 @shared_task
20 @close_connection
21 def update_suggestions(user_pk, max_suggestions=15):
22 """updates the suggestions of a user"""
24 User = get_user_model()
25 user = User.objects.get(pk=user_pk)
27 logger.info("Updating suggestions of user {user.username}".format(user=user))
29 # calculate possible suggestions
30 subscribed_podcasts = [sp.podcast for sp in get_subscribed_podcasts(user)]
31 logger.debug(
32 "Found {num_podcasts} subscribed podcasts".format(
33 num_podcasts=len(subscribed_podcasts)
37 # TODO: update related_podcasts of the subscribed_podcasts?
39 related = list(
40 chain.from_iterable([p.related_podcasts.all() for p in subscribed_podcasts])
43 # get most relevant
44 counter = Counter(related)
45 logger.debug(
46 "Found {num_related} related podcasts".format(num_related=len(counter))
49 suggested = [p for p, count in counter.most_common(max_suggestions)]
51 for suggested_podcast in suggested:
52 ps, created = PodcastSuggestion.objects.get_or_create(
53 suggested_to=user, podcast=suggested_podcast
55 if created:
56 logger.info(
57 "Created suggestion for {podcast}".format(podcast=suggested_podcast)
60 user.profile.suggestions_up_to_date = True
61 user.profile.save()