Merge master for RC
[laas.git] / src / notifier / tasks.py
1 ##############################################################################
2 # Copyright (c) 2016 Max Breitenfeldt and others.
3 # Copyright (c) 2018 Parker Berberian, Sawyer Bergeron, and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10
11
12 from celery import shared_task
13 from django.utils import timezone
14 from django.conf import settings
15 from booking.models import Booking
16 from notifier.models import Emailed, Email
17 from notifier.manager import NotificationHandler
18 from django.core.mail import send_mail
19
20 import os
21
22
23 @shared_task
24 def notify_expiring():
25     """Notify users if their booking is within 48 hours of expiring."""
26     expire_time = timezone.now() + timezone.timedelta(hours=settings.EXPIRE_HOURS)
27     # Don't email people about bookings that have started recently
28     start_time = timezone.now() - timezone.timedelta(hours=settings.EXPIRE_LIFETIME)
29     bookings = Booking.objects.filter(
30         end__lte=expire_time,
31         end__gte=timezone.now(),
32         start__lte=start_time
33     )
34     for booking in bookings:
35         if Emailed.objects.filter(almost_end_booking=booking).exists():
36             continue
37         NotificationHandler.notify_booking_expiring(booking)
38         Emailed.objects.create(almost_end_booking=booking)
39
40
41 @shared_task
42 def dispatch_emails():
43     for email in Email.objects.filter(sent=False):
44         email.sent = True
45         email.save()
46         send_mail(
47             email.title,
48             email.message,
49             os.environ.get("DEFAULT_FROM_EMAIL", "opnfv@laas-dashboard"),
50             [email.recipient],
51             fail_silently=False)