models.py 3.58 KB
Newer Older
1 2
# -*- coding: utf8 -*-

fred's avatar
fred committed
3
import datetime
fred's avatar
fred committed
4 5
import hashlib
import random
fred's avatar
fred committed
6
import smtplib
7
import subprocess
fred's avatar
fred committed
8

fred's avatar
fred committed
9 10 11 12 13
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import html2text

14
from django.db import models
15
from django.core.urlresolvers import reverse
16

17 18
from django.template import loader, Context
from django.template.loader import render_to_string
19 20
from django.conf import settings

21
from django.utils.safestring import mark_safe
22 23
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _
24
from django.core.mail import send_mail
25 26 27

from ckeditor.fields import RichTextField

28 29 30 31 32 33

class Subscriber(models.Model) :
    email = models.EmailField(unique = True)   # TODO : informer si déjà inscrit ? Que faire dans ce cas.
    inscription_date = models.DateField(auto_now_add=True)
    is_validated = models.NullBooleanField() # Au click sur le lien de confirmation. Null si erreur à l'envoi au souscripteur.
    is_registered = models.NullBooleanField() # À l'inscription après la confirmation Null si erreur à l'envoi à mailman.
34 35
    password = models.CharField(max_length=100) # sha1
    
36 37 38 39 40
    def __unicode__(self) :
        return self.email

    def save(self, *args, **kwargs):
        super(Subscriber, self).save(*args, **kwargs)
41
        if self.is_validated is None:
fred's avatar
fred committed
42 43 44 45 46 47
            self.send_confirmation_email()

    def send_confirmation_email(self):
        self.password = hashlib.sha1(str(random.random())).hexdigest()
        confirm_subject = loader.get_template('newsletter/confirmation_email_subject.txt')
        confirm_body = loader.get_template('newsletter/confirmation_email_body.txt')
fred's avatar
fred committed
48
        context = Context({'token': self.password})
fred's avatar
fred committed
49 50 51
        send_mail(confirm_subject.render(context).strip(), confirm_body.render(context),
                settings.NEWSLETTER_SENDER, [self.email])
        self.is_validated = False
52
        self.save()
fred's avatar
fred committed
53 54

    def subscribe_in_mailman(self):
55 56 57
        t = subprocess.call(['listadmin', '--add-member', self.email, settings.NEWSLETTER_NAME])
        if t != 0:
            return
fred's avatar
fred committed
58
        self.is_registered = True
59
        self.save()
60 61 62 63 64 65 66 67 68 69 70 71 72 73


class Newsletter(models.Model):

    class Meta:
        verbose_name = _('Newsletter')
        verbose_name_plural = _('Newsletters')
        ordering = ['date']

    subject = models.CharField(_('Title'), max_length=50)
    date = models.DateField(_('Date'))
    text = RichTextField(_('Text'), null=True, blank=True)

    expedition_datetime = models.DateTimeField(_('Expedition Date/time'), null=True, blank=True)
fred's avatar
fred committed
74 75 76 77 78 79 80 81 82 83 84 85

    def send(self):
        msg = MIMEMultipart('alternative')
        msg['Subject'] = self.subject
        msg['From'] = settings.NEWSLETTER_SENDER
        if settings.DEBUG:
            msg['To'] = 'fred@localhost'
        else:
            msg['To'] = '%s@%s' % (settings.NEWSLETTER_NAME, settings.NEWSLETTER_DOMAIN)

        h2t = html2text.HTML2Text()
        h2t.unicode_snob = True
86 87 88 89
        context = {
            'text_part': mark_safe(h2t.handle(self.text)),
            'html_part': mark_safe(self.text),
        }
fred's avatar
fred committed
90

91 92
        part1 = MIMEText(render_to_string('newsletter/email_body.txt', context), 'plain', _charset='utf-8')
        part2 = MIMEText(render_to_string('newsletter/email_body.html', context), 'html', _charset='utf-8')
fred's avatar
fred committed
93 94 95 96 97 98 99 100 101 102

        msg.attach(part1)
        msg.attach(part2)

        s = smtplib.SMTP('localhost')
        s.sendmail(msg['From'], msg['To'], msg.as_string())
        s.quit()

        self.expedition_datetime = datetime.datetime.now()
        self.save()
103 104 105

    def get_absolute_url(self):
        return reverse('newsletter-view', kwargs={'pk': self.id})