X-Git-Url: https://git.mdrn.pl/wolnelektury.git/blobdiff_plain/f1143b5bcf508dcfe7f72e90faee72cf72a2392a..71d31efcdb70122f705d8136239771747ca3b07d:/src/messaging/models.py?ds=sidebyside diff --git a/src/messaging/models.py b/src/messaging/models.py index 4f394c397..24cf623f1 100644 --- a/src/messaging/models.py +++ b/src/messaging/models.py @@ -1,9 +1,13 @@ +from django.apps import apps from django.conf import settings from django.core.mail import send_mail from django.db import models from django.template import Template, Context +from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from sentry_sdk import capture_exception +from catalogue.utils import get_random_hash +from .recipient import Recipient from .states import states @@ -51,9 +55,25 @@ class EmailTemplate(models.Model): return s raise ValueError('Unknown state', s.state) - def send(self, recipient, verbose=False, dry_run=False): - subject = Template(self.subject).render(Context(recipient.context)) - body = Template(self.body).render(Context(recipient.context)) + def send(self, recipient, verbose=False, dry_run=False, test=False): + ctx = Context(recipient.context) + + if test: + contact = Contact(email=recipient.email, key='test') + else: + # TODO: actually, we should just use Contacts instead of recipients. + contact = Contact.objects.get(email=recipient.email) + + ctx['contact'] = contact + + subject = Template(self.subject).render(ctx) + + if test: + subject = "[test] " + subject + + body_template = '{% extends "messaging/email_body.html" %}{% block body %}' + self.body + '{% endblock %}' + + body = Template(body_template).render(ctx) if verbose: print(recipient.email, subject) if not dry_run: @@ -62,12 +82,18 @@ class EmailTemplate(models.Model): except: capture_exception() else: - self.emailsent_set.create( - hash_value=recipient.hash_value, - email=recipient.email, - subject=subject, - body=body, - ) + if not test: + self.emailsent_set.create( + hash_value=recipient.hash_value, + email=recipient.email, + subject=subject, + body=body, + ) + + def send_test_email(self, email): + state = self.get_state()() + recipient = state.get_example_recipient(email) + self.send(recipient, test=True) class EmailSent(models.Model): @@ -105,6 +131,15 @@ class Contact(models.Model): ]) since = models.DateTimeField() expires_at = models.DateTimeField(null=True, blank=True) + key = models.CharField(max_length=64, blank=True) + + def save(self, *args, **kwargs): + if not self.key: + self.key = get_random_hash(self.email) + super().save(*args, **kwargs) + + def get_optout_url(self): + return reverse('messaging_optout', args=[self.key]) @classmethod def update(cls, email, level, since, expires_at=None):