chrono/chrono/agendas/management/commands/utils.py

76 lines
2.6 KiB
Python

from smtplib import SMTPException
from django.conf import settings
from django.core.mail import send_mail
from django.db.transaction import atomic
from django.template import Context, Template, TemplateSyntaxError, VariableDoesNotExist
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from requests import RequestException
from chrono.utils import timezone
from chrono.utils.requests_wrapper import requests
def send_reminder(booking, msg_type):
agenda = booking.event.agenda
kind = agenda.kind
days = getattr(agenda.reminder_settings, f'days_before_{msg_type}')
ctx = {
'booking': booking,
'in_x_days': _('tomorrow') if days == 1 else _('in %s days') % days,
'date': booking.event.start_datetime,
}
ctx.update(settings.TEMPLATE_VARS)
for extra_info in ('email_extra_info', 'sms_extra_info'):
try:
ctx[extra_info] = Template(getattr(agenda.reminder_settings, extra_info)).render(
Context({'booking': booking}, autoescape=False)
)
except (VariableDoesNotExist, TemplateSyntaxError):
pass
if msg_type == 'email' and booking.emails:
for email in booking.emails:
send_email_reminder(email, booking, kind, ctx)
elif msg_type == 'sms' and booking.phone_numbers:
send_sms_reminder(booking.phone_numbers, booking, kind, ctx)
def send_email_reminder(email, booking, kind, ctx):
subject = render_to_string('agendas/%s_reminder_subject.txt' % kind, ctx).strip()
body = render_to_string('agendas/%s_reminder_body.txt' % kind, ctx)
html_body = render_to_string('agendas/%s_reminder_body.html' % kind, ctx)
try:
with atomic():
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [email], html_message=html_body)
booking.email_reminder_datetime = timezone.now()
booking.save()
except SMTPException:
pass
def send_sms_reminder(phone_numbers, booking, kind, ctx):
if not settings.SMS_URL:
return
message = render_to_string('agendas/%s_reminder_message.txt' % kind, ctx).strip()
payload = {
'message': message,
'from': settings.SMS_SENDER,
'to': phone_numbers,
}
try:
with atomic():
request = requests.post(
settings.SMS_URL, json=payload, remote_service='auto', timeout=10, without_user=True
)
request.raise_for_status()
booking.sms_reminder_datetime = timezone.now()
booking.save()
except RequestException:
pass