models.py 3.73 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

fred's avatar
fred committed
17
from django.template import loader
fred's avatar
fred committed
18
from django.template.loader import render_to_string
jean-philippe's avatar
jean-philippe committed
19
20
from django.conf import settings

fred's avatar
fred committed
21
from django.utils.encoding import force_bytes
fred's avatar
fred committed
22
from django.utils.safestring import mark_safe
23
24
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _
25
from django.core.mail import send_mail
26
27
28

from ckeditor.fields import RichTextField

29
30

class Subscriber(models.Model) :
31
    email = models.EmailField(unique=True)
32
    inscription_date = models.DateField(auto_now_add=True)
33
34
35
36
    is_validated = models.NullBooleanField()
    is_registered = models.NullBooleanField()
    password = models.CharField(max_length=100)

37
38
39
40
    def __unicode__(self) :
        return self.email

    def save(self, *args, **kwargs):
41
42
43
44
45
46
47
48
49
50
        existing_subscriber = self.objects.filter(email=self.email).first()
        if existing_subscriber and existing_subscriber.id != self.id:
            # reset existing subscriber
            existing_subscriber.is_validated = None
            existing_subscriber.is_registered = None
            existing_subscriber.save()
        else:
            super(Subscriber, self).save(*args, **kwargs)
            if self.is_validated is None:
                self.send_confirmation_email()
fred's avatar
fred committed
51
52

    def send_confirmation_email(self):
fred's avatar
fred committed
53
        self.password = hashlib.sha1(force_bytes(str(random.random()))).hexdigest()
fred's avatar
fred committed
54
55
        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
56
        context = {'token': self.password}
fred's avatar
fred committed
57
58
59
        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
60
        self.save()
fred's avatar
fred committed
61
62

    def subscribe_in_mailman(self):
63
64
65
        t = subprocess.call(['listadmin', '--add-member', self.email, settings.NEWSLETTER_NAME])
        if t != 0:
            return
fred's avatar
fred committed
66
        self.is_registered = True
67
        self.save()
68
69
70
71
72
73
74
75
76
77
78
79
80
81


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
82
83
84
85
86
87
88
89
90
91
92
93

    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
fred's avatar
fred committed
94
95
96
97
        context = {
            'text_part': mark_safe(h2t.handle(self.text)),
            'html_part': mark_safe(self.text),
        }
fred's avatar
fred committed
98

fred's avatar
fred committed
99
100
        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
101
102
103
104
105
106
107
108
109
110

        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()
111
112
113

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