models.py 3.45 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
jean-philippe's avatar
jean-philippe committed
16 17 18 19

from django.template import loader, Context 
from django.conf import settings

20 21
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _
22
from django.core.mail import send_mail
23 24 25

from ckeditor.fields import RichTextField

26 27 28 29 30 31

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.
32 33
    password = models.CharField(max_length=100) # sha1
    
34 35 36 37 38
    def __unicode__(self) :
        return self.email

    def save(self, *args, **kwargs):
        super(Subscriber, self).save(*args, **kwargs)
jean-philippe's avatar
jean-philippe committed
39
        if self.is_validated is None:
fred's avatar
fred committed
40 41 42 43 44 45
            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
46
        context = Context({'token': self.password})
fred's avatar
fred committed
47 48 49
        send_mail(confirm_subject.render(context).strip(), confirm_body.render(context),
                settings.NEWSLETTER_SENDER, [self.email])
        self.is_validated = False
jean-philippe's avatar
jean-philippe committed
50
        self.save()
fred's avatar
fred committed
51 52

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


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
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

    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
        html = self.text.encode('utf-8')
        if settings.NEWSLETTER_STYLE:
            html += '''\n<style type="text/css">\n%s\n</style>''' % settings.NEWSLETTER_STYLE

        part1 = MIMEText(h2t.handle(self.text).encode('utf-8'), 'plain', _charset='utf-8')
        part2 = MIMEText(html, 'html', _charset='utf-8')

        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()
100 101 102

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