local_periodic_tasks.py 3.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

import logging
from django.conf import settings
from django.core.mail import send_mail
Kohl Krisztofer committed
21
from django.urls import reverse
22 23 24 25 26 27 28 29 30
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ungettext, override

from manager.mancelery import celery
from ..models import Notification
from ..views import UnsubscribeFormView

Szeberényi Imre committed
31 32 33 34 35 36 37

try:
    # Python 2: "unicode" is built-in
    unicode
except NameError:
    unicode = str

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
logger = logging.getLogger(__name__)


@celery.task(ignore_result=True)
def send_email_notifications():
    q = Q(status=Notification.STATUS.new) & (
        Q(valid_until__lt=timezone.now()) | Q(valid_until=None))
    from_email = settings.DEFAULT_FROM_EMAIL

    recipients = {}
    for i in Notification.objects.filter(q):
        recipients.setdefault(i.to, [])
        recipients[i.to].append(i)
    logger.info("Delivering notifications to %d users", len(recipients))

Kohl Krisztofer committed
53
    for user, msgs in list(recipients.items()):
54 55
        if (not user.profile or not user.email or not
                user.profile.email_notifications):
Szeberényi Imre committed
56
            logger.debug("%s gets no notifications", unicode(user))
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
            continue
        with override(user.profile.preferred_language):
            context = {'user': user.profile, 'messages': msgs,
                       'url': (settings.DJANGO_URL.rstrip("/") +
                               reverse("dashboard.views.notifications")),
                       'unsub': (settings.DJANGO_URL.rstrip("/") + reverse(
                           "dashboard.views.unsubscribe",
                           args=[UnsubscribeFormView.get_token(user)])),
                       'site': settings.COMPANY_NAME}
            subject = settings.EMAIL_SUBJECT_PREFIX + ungettext(
                "%d new notification",
                "%d new notifications", len(msgs)) % len(msgs)
            body = render_to_string('dashboard/notifications/email.txt',
                                    context)
        try:
            send_mail(subject, body, from_email, (user.email, ))
        except:
            logger.error("Failed to send mail to %s", user, exc_info=True)
        else:
            logger.info("Delivered notifications %s",
Szeberényi Imre committed
77
                        " ".join(unicode(i.pk) for i in msgs))
78 79 80
            for i in msgs:
                i.status = i.STATUS.delivered
                i.save()