]> git.openstreetmap.org Git - osqa.git/blob - forum/management/commands/send_email_alerts.py
ba1d9436d49635c02b10fc22901c51717acd54dc
[osqa.git] / forum / management / commands / send_email_alerts.py
1 from datetime import datetime, timedelta
2 from django.core.management.base import NoArgsCommand
3 from django.utils.translation import ugettext as _
4 from django.template import loader, Context, Template
5 from django.core.mail import EmailMultiAlternatives
6 from django.conf import settings
7 from forum.models import KeyValue, Activity, User, QuestionSubscription
8 from forum.utils.mail import send_email
9 from forum import const
10
11 class QuestionRecord:
12     def __init__(self, question):
13         self.question = question
14         self.records = []
15
16     def log_activity(self, activity):
17         self.records.append(activity)
18
19     def get_activity_since(self, since):
20         activity = [r for r in self.records if r.active_at > since]
21         answers = [a for a in activity if a.activity_type == const.TYPE_ACTIVITY_ANSWER]
22         comments = [a for a in activity if a.activity_type in (const.TYPE_ACTIVITY_COMMENT_QUESTION, const.TYPE_ACTIVITY_COMMENT_ANSWER)]
23
24         accepted = [a for a in activity if a.activity_type == const.TYPE_ACTIVITY_MARK_ANSWER]
25
26         if len(accepted):
27             accepted = accepted[-1:][0]
28         else:
29             accepted = None
30
31         return {
32             'answers': answers,
33             'comments': comments,
34             'accepted': accepted,
35         }
36
37
38 class Command(NoArgsCommand):
39     def handle_noargs(self, **options):
40         digest_control = self.get_digest_control()
41
42         self.send_digest('daily', 'd', digest_control.value['LAST_DAILY'])
43         digest_control.value['LAST_DAILY'] = datetime.now()
44
45         if digest_control.value['LAST_WEEKLY'] + timedelta(days=7) <= datetime.now():
46             self.send_digest('weekly', 'w', digest_control.value['LAST_WEEKLY'])
47             digest_control.value['LAST_WEEKLY'] = datetime.now()
48
49         digest_control.save()
50             
51
52     def send_digest(self, name, char_in_db, control_date):
53         new_questions, question_records = self.prepare_activity(control_date)
54         new_users = User.objects.filter(date_joined__gt=control_date)
55
56         digest_subject = settings.EMAIL_SUBJECT_PREFIX + _('Daily digest')
57
58         users = User.objects.filter(subscription_settings__enable_notifications=True)
59
60         msgs = []
61
62         for u in users:
63             context = {
64                 'user': u,
65                 'digest_type': name,
66             }
67
68             if u.subscription_settings.member_joins == char_in_db:
69                 context['new_users'] = new_users
70             else:
71                 context['new_users'] = False
72
73             if u.subscription_settings.subscribed_questions == char_in_db:
74                 activity_in_subscriptions = []
75
76                 for id, r in question_records.items():
77                     try:
78                         subscription = QuestionSubscription.objects.get(question=r.question, user=u)
79
80                         record = r.get_activity_since(subscription.last_view)
81
82                         if not u.subscription_settings.notify_answers:
83                             del record['answers']
84
85                         if not u.subscription_settings.notify_comments:
86                             if u.subscription_settings.notify_comments_own_post:
87                                 record.comments = [a for a in record.comments if a.content_object.content_object.author == u]
88                                 record['own_comments_only'] = True
89                             else:
90                                 del record['comments']
91
92                         if not u.subscription_settings.notify_accepted:
93                             del record['accepted']
94
95                         if record.get('answers', False) or record.get('comments', False) or record.get('accepted', False):
96                             activity_in_subscriptions.append({'question': r.question, 'activity': record})
97                     except:
98                         pass
99
100                 context['activity_in_subscriptions'] = activity_in_subscriptions
101             else:
102                 context['activity_in_subscriptions'] = False
103
104
105             if u.subscription_settings.new_question == char_in_db:
106                 context['new_questions'] = new_questions
107                 context['watched_tags_only'] = False
108             elif u.subscription_settings.new_question_watched_tags == char_in_db:
109                 context['new_questions'] = [q for q in new_questions if
110                                             q.tags.filter(id__in=u.marked_tags.filter(user_selections__reason='good')).count() > 0]
111                 context['watched_tags_only'] = True
112             else:
113                 context['new_questions'] = False
114
115             if context['new_users'] or context['activity_in_subscriptions'] or context['new_questions']:
116                 send_email(digest_subject, (u.username, u.email), "notifications/digest.html", context, threaded=False)
117
118
119     def get_digest_control(self):
120         try:
121             digest_control = KeyValue.objects.get(key='DIGEST_CONTROL')
122         except:
123             digest_control = KeyValue(key='DIGEST_CONTROL', value={
124                 'LAST_DAILY': datetime.now() - timedelta(days=1),
125                 'LAST_WEEKLY': datetime.now() - timedelta(days=1),
126             })
127
128         return digest_control
129
130     def prepare_activity(self, since):
131         all_activity = Activity.objects.filter(active_at__gt=since, activity_type__in=(
132             const.TYPE_ACTIVITY_ASK_QUESTION, const.TYPE_ACTIVITY_ANSWER,
133             const.TYPE_ACTIVITY_COMMENT_QUESTION, const.TYPE_ACTIVITY_COMMENT_ANSWER,
134             const.TYPE_ACTIVITY_MARK_ANSWER
135         )).order_by('active_at')
136
137         question_records = {}
138         new_questions = []
139
140
141         for activity in all_activity:
142             try:
143                 question = self.get_question_for_activity(activity)
144
145                 if not question.id in question_records:
146                     question_records[question.id] = QuestionRecord(question)
147
148                 question_records[question.id].log_activity(activity)
149
150                 if activity.activity_type == const.TYPE_ACTIVITY_ASK_QUESTION:
151                     new_questions.append(question)
152             except:
153                 pass
154
155         return new_questions, question_records
156
157     def get_question_for_activity(self, activity):
158         if activity.activity_type == const.TYPE_ACTIVITY_ASK_QUESTION:
159             question = activity.content_object
160         elif activity.activity_type == const.TYPE_ACTIVITY_ANSWER:
161             question = activity.content_object.question
162         elif activity.activity_type == const.TYPE_ACTIVITY_COMMENT_QUESTION:
163             question = activity.content_object.content_object
164         elif activity.activity_type == const.TYPE_ACTIVITY_COMMENT_ANSWER:
165             question = activity.content_object.content_object.question
166         elif activity.activity_type == const.TYPE_ACTIVITY_MARK_ANSWER:
167             question = activity.content_object.question
168         else:
169             raise Exception
170
171         return question