]> git.openstreetmap.org Git - osqa.git/blob - forum/management/commands/send_email_alerts.py
4cdb2e1d35636fa27a5061539d83095db69a067c
[osqa.git] / forum / management / commands / send_email_alerts.py
1 import datetime
2 from forum.models import *
3 from django.db import models
4 from forum.utils.mail import send_template_email
5 from django.core.management.base import NoArgsCommand
6 from forum.settings.email import EMAIL_DIGEST_CONTROL
7 from django.utils import translation
8 import logging
9
10 SHOW_N_MORE_ACTIVE_NEW_MEMBERS = 5
11 SUB_QUESTION_LIST_LENGTH = 5
12 TRY_N_USER_TAGS = 5
13
14
15
16 class DigestQuestionsIndex(object):
17     def __init__(self, from_date):
18         self.from_date = from_date
19
20         new_questions = Question.objects.filter_state(deleted=False).\
21             filter(added_at__gt=from_date).\
22             annotate(n_actions=models.Count('actions')).\
23             annotate(child_count=models.Count('all_children'))
24
25         hotness = lambda q: 3*q.child_count + q.n_actions
26
27         for q in new_questions:
28             q.hotness=hotness(q)
29
30         self.questions = sorted(new_questions, lambda q1, q2: q2.hotness - q1.hotness)
31         self.count = len(self.questions)
32
33     def unseen_question(self, user, question):
34         try:
35             subscription = QuestionSubscription.objects.get(question=q, user=user)
36         except:
37             subscription = None
38
39         return (not subscription) or subscription.last_view < q.last_activity_at
40
41     def get_for_user(self, user):
42         user_tags = list(user.marked_tags.filter(user_selections__reason='good'))
43
44         if len(user_tags) < TRY_N_USER_TAGS:
45             user_tags += list(Tag.objects.filter(models.Q(nodes__author=user) | models.Q(nodes__children__author=user)) \
46                 .annotate(user_tag_usage_count=models.Count('name')).order_by('-user_tag_usage_count')[:TRY_N_USER_TAGS - len(user_tags)])
47
48         user_tag_names = set([t.name for t in user_tags])
49
50
51         subscriptions = user.subscriptions.filter(added_at__lt=self.from_date, last_activity_at__gt=models.F('questionsubscription__last_view')
52                                                   ).order_by('-questionsubscription__last_view')[:SUB_QUESTION_LIST_LENGTH]
53
54         unseen_questions = [q for q in self.questions if self.unseen_question(user, q)]
55
56         interesting = []
57
58         for q in unseen_questions:
59             if len(set(q.tagname_list()) & user_tag_names): interesting.append(q)
60
61
62         may_help = []
63         if len(interesting):
64             if len(interesting) > SUB_QUESTION_LIST_LENGTH:
65                 may_help = interesting[SUB_QUESTION_LIST_LENGTH:][-SUB_QUESTION_LIST_LENGTH:]
66                 interesting = interesting[:SUB_QUESTION_LIST_LENGTH]
67         else:
68             interesting = unseen_questions[:SUB_QUESTION_LIST_LENGTH]
69
70         return {'interesting': interesting, 'may_help': may_help, 'subscriptions': subscriptions}
71
72
73
74
75 class Command(NoArgsCommand):
76     def handle_noargs(self, **options):
77         try:
78             translation.activate(settings.LANGUAGE_CODE)
79         except:
80             logging.error("Unable to set the locale in the send emails cron job")
81
82         digest_control = EMAIL_DIGEST_CONTROL.value
83
84         if digest_control is None:
85             digest_control = KeyValue(key='DIGEST_CONTROL', value={
86             'LAST_DAILY': datetime.datetime.now() - datetime.timedelta(days=1),
87             'LAST_WEEKLY': datetime.datetime.now() - datetime.timedelta(days=1),
88             })
89
90         from_date = digest_control.value['LAST_DAILY']
91         digest_control.value['LAST_DAILY'] = datetime.datetime.now()
92
93         EMAIL_DIGEST_CONTROL.set_value(digest_control)
94
95         users = User.objects.filter(subscription_settings__enable_notifications=True)
96         new_members = User.objects.filter(is_active=True, date_joined__gt=from_date).annotate(n_actions=models.Count('actions')).order_by('-n_actions')
97
98         new_member_count = new_members.count()
99
100         if new_member_count >= SHOW_N_MORE_ACTIVE_NEW_MEMBERS:
101             new_members = new_members[:SHOW_N_MORE_ACTIVE_NEW_MEMBERS]
102             show_all_users = True
103         else:
104             show_all_users = False
105
106         digest = DigestQuestionsIndex(from_date)
107
108         send_template_email(users, "notifications/digest.html", locals())
109
110