diff options
Diffstat (limited to 'app/lttr/models.py')
-rw-r--r-- | app/lttr/models.py | 311 |
1 files changed, 311 insertions, 0 deletions
diff --git a/app/lttr/models.py b/app/lttr/models.py new file mode 100644 index 0000000..029022c --- /dev/null +++ b/app/lttr/models.py @@ -0,0 +1,311 @@ +import datetime +from django.contrib.gis.db import models +from django.contrib.sites.models import Site +from django.template.loader import select_template +from django.core.mail import EmailMultiAlternatives +from django.utils import timezone +from django.utils.text import slugify +from django.urls import reverse +from django.conf import settings +from django.utils.crypto import get_random_string + +from taggit.managers import TaggableManager + +from taxonomy.models import TaggedItems + + +# Possible actions that user can perform +ACTIONS = ('subscribe', 'unsubscribe', 'update') + + +def make_activation_code(): + """ Generate a unique activation code. """ + + # Use Django's crypto get_random_string() instead of rolling our own. + return get_random_string(length=40) + + +class Newsletter(models.Model): + """ A model for Newletters. Might I one day have two? I might. """ + title = models.CharField(max_length=250) + + def __str__(self): + return self.title + + def get_absolute_url(self): + return reverse("lttr:detail", kwargs={"slug": self.slug}) + + def subscribe_url(self): + return reverse('newsletter_subscribe_request', kwargs={'newsletter_slug': self.slug}) + + def unsubscribe_url(self): + return reverse('newsletter_unsubscribe_request', kwargs={'newsletter_slug': self.slug}) + + def update_url(self): + return reverse('newsletter_update_request', kwargs={'newsletter_slug': self.slug}) + + def archive_url(self): + return reverse('newsletter_archive', kwargs={'newsletter_slug': self.slug}) + + def get_subscriptions(self): + return Subscriber.objects.filter(newsletter=self, subscribed=True) + + @classmethod + def get_default(cls): + try: + return cls.objects.all()[0].pk + except IndexError: + return None + + +class NewsletterMailing(models.Model): + """ A model for Newletter Mailings, the things actually sent out """ + title = models.CharField(max_length=250) + slug = models.SlugField(unique_for_date='pub_date', blank=True) + pub_date = models.DateTimeField() + tags = TaggableManager(through=TaggedItems, blank=True, help_text='Topics Covered') + PUB_STATUS = ( + (0, 'Not Published'), + (1, 'Published'), + ) + status = models.IntegerField(choices=PUB_STATUS, default=0) + date_created = models.DateTimeField(blank=True, auto_now_add=True, editable=False) + + class Meta: + ordering = ('-title', '-date_created') + + def __str__(self): + return self.title + + def get_absolute_url(self): + return reverse("newsletter:mailing-detail", kwargs={"slug": self.slug}) + + def save(self, *args, **kwargs): + if not self.id: + self.date_created = timezone.now() + super(NewsletterMailing, self).save() + + def get_templates(self, action): + """ + Return a subject, text, HTML tuple with e-mail templates for + a particular action. Returns a tuple with subject, text and e-mail + template. + """ + + assert action in ACTIONS + ('message', ), 'Unknown action: %s' % action + + # Common substitutions for filenames + tpl_subst = { + 'action': action, + 'newsletter': self.slug + } + + # Common root path for all the templates + tpl_root = 'newsletter/message/' + + subject_template = select_template([ + tpl_root + '%(newsletter)s/%(action)s_subject.txt' % tpl_subst, + tpl_root + '%(action)s_subject.txt' % tpl_subst, + ]) + + text_template = select_template([ + tpl_root + '%(newsletter)s/%(action)s.txt' % tpl_subst, + tpl_root + '%(action)s.txt' % tpl_subst, + ]) + + if self.send_html: + html_template = select_template([ + tpl_root + '%(newsletter)s/%(action)s.html' % tpl_subst, + tpl_root + '%(action)s.html' % tpl_subst, + ]) + else: + # HTML templates are not required + html_template = None + + return (subject_template, text_template, html_template) + + +class Subscriber(models.Model): + """ A model for Newletter Subscriber """ + email_field = models.EmailField(db_column='email', db_index=True, blank=True, null=True) + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + date_created = models.DateTimeField(blank=True, auto_now_add=True, editable=False) + date_updated = models.DateTimeField(blank=True, auto_now=True, editable=False) + ip = models.GenericIPAddressField(blank=True, null=True) + newsletter = models.ForeignKey(Newsletter, on_delete=models.CASCADE) + create_date = models.DateTimeField(editable=False, default=datetime.datetime.now) + activation_code = models.CharField(max_length=40, default=make_activation_code) + subscribed = models.BooleanField(default=False, db_index=True) + subscribe_date = models.DateTimeField(null=True, blank=True) + unsubscribed = models.BooleanField(default=False, db_index=True) + unsubscribe_date = models.DateTimeField(null=True, blank=True) + + def __str__(self): + return self.user.username + + def get_name(self): + if self.user: + return self.user.get_full_name() + + def get_email(self): + if self.user: + return self.user.email + return self.email_field + + def set_email(self, email): + if not self.user: + self.email_field = email + email = property(get_email, set_email) + + def update(self, action): + """ + Update subscription according to requested action: + subscribe/unsubscribe/update/, then save the changes. + """ + + assert action in ('subscribe', 'update', 'unsubscribe') + + # If a new subscription or update, make sure it is subscribed + # Else, unsubscribe + if action == 'subscribe' or action == 'update': + self.subscribed = True + else: + self.unsubscribed = True + + # This triggers the subscribe() and/or unsubscribe() methods, taking + # care of stuff like maintaining the (un)subscribe date. + self.save() + + def _subscribe(self): + """ + Internal helper method for managing subscription state + during subscription. + """ + + self.subscribe_date = datetime.datetime.now() + self.subscribed = True + self.unsubscribed = False + + def _unsubscribe(self): + """ + Internal helper method for managing subscription state + during unsubscription. + """ + self.subscribed = False + self.unsubscribed = True + self.unsubscribe_date = datetime.datetime.now() + + def save(self, *args, **kwargs): + """ + Perform some basic validation and state maintenance of Subscription. + TODO: Move this code to a more suitable place (i.e. `clean()`) and + cleanup the code. Refer to comment below and + https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean + """ + + # This is a lame way to find out if we have changed but using Django + # API internals is bad practice. This is necessary to discriminate + # from a state where we have never been subscribed but is mostly for + # backward compatibility. It might be very useful to make this just + # one attribute 'subscribe' later. In this case unsubscribed can be + # replaced by a method property. + + if self.pk: + assert(Subscriber.objects.filter(pk=self.pk).count() == 1) + + subscription = Subscriber.objects.get(pk=self.pk) + old_subscribed = subscription.subscribed + old_unsubscribed = subscription.unsubscribed + + # If we are subscribed now and we used not to be so, subscribe. + # If we user to be unsubscribed but are not so anymore, subscribe. + if ((self.subscribed and not old_subscribed) or + (old_unsubscribed and not self.unsubscribed)): + self._subscribe() + + assert not self.unsubscribed + assert self.subscribed + + # If we are unsubcribed now and we used not to be so, unsubscribe. + # If we used to be subscribed but are not subscribed anymore, + # unsubscribe. + elif ((self.unsubscribed and not old_unsubscribed) or + (old_subscribed and not self.subscribed)): + self._unsubscribe() + + assert not self.subscribed + assert self.unsubscribed + else: + if self.subscribed: + self._subscribe() + elif self.unsubscribed: + self._unsubscribe() + + super(Subscriber, self).save(*args, **kwargs) + + def get_recipient(self): + return get_address(self.name, self.email) + + def send_activation_email(self, action): + assert action in ACTIONS, 'Unknown action: %s' % action + + (subject_template, text_template, html_template) = \ + self.newsletter.get_templates(action) + + variable_dict = { + 'subscription': self, + 'site': Site.objects.get_current(), + 'newsletter': self.newsletter, + 'date': self.subscribe_date, + 'STATIC_URL': settings.STATIC_URL, + 'MEDIA_URL': settings.MEDIA_URL + } + + subject = subject_template.render(variable_dict).strip() + text = text_template.render(variable_dict) + + message = EmailMultiAlternatives( + subject, text, + from_email=self.newsletter.get_sender(), + to=[self.email] + ) + + if html_template: + message.attach_alternative( + html_template.render(variable_dict), "text/html" + ) + + message.send() + + def subscribe_activate_url(self): + return reverse('newsletter_update_activate', kwargs={ + 'newsletter_slug': self.newsletter.slug, + 'email': self.email, + 'action': 'subscribe', + 'activation_code': self.activation_code + }) + + def unsubscribe_activate_url(self): + return reverse('newsletter_update_activate', kwargs={ + 'newsletter_slug': self.newsletter.slug, + 'email': self.email, + 'action': 'unsubscribe', + 'activation_code': self.activation_code + }) + + def update_activate_url(self): + return reverse('newsletter_update_activate', kwargs={ + 'newsletter_slug': self.newsletter.slug, + 'email': self.email, + 'action': 'update', + 'activation_code': self.activation_code + }) + + +def get_address(name, email): + # Converting name to ascii for compatibility with django < 1.9. + # Remove this when django 1.8 is no longer supported. + if name: + return u'%s <%s>' % (name, email) + else: + return u'%s' % email |