Project

General

Profile

Download (5.07 KB) Statistics
| Branch: | Tag: | Revision:
from datetime import datetime
import logging
import urlparse
from html2text import HTML2Text
from emails.django import Message
from lxml.etree import HTML as HTMLTree

from django.utils import timezone
from django.conf import settings
from django.db import models
from django.core.files.storage import DefaultStorage
from django.utils.translation import ugettext_lazy as _
from django.core import signing
from django.template import loader, Context
from django.core.urlresolvers import reverse

from ckeditor.fields import RichTextField

channel_choices = (
('mailto', _('Email')),
('homepage', _('Homepage'))
)

logger = logging.getLogger(__name__)

class Category(models.Model):
name = models.CharField(max_length=64, blank=False, null=False)
ctime = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
return self.name


class Announce(models.Model):
category = models.ForeignKey('Category', verbose_name=_('category'))
title = models.CharField(_('title'), max_length=256,
help_text=_('maximum 256 characters'))
text = RichTextField(_('Content'))
publication_time = models.DateTimeField(_('publication time'), blank=True,
null=True)
expiration_time = models.DateTimeField(_('Expires on'), blank=True,
null=True)
ctime = models.DateTimeField(_('creation time'), auto_now_add=True)
mtime = models.DateTimeField(_('modification time'), auto_now=True)

def __unicode__(self):
return u'{title} ({id}) at {mtime}'.format(title=self.title,
id=self.id, mtime=self.mtime)

def is_expired(self):
if self.expiration_time:
return self.expiration_time < timezone.now()
return False

def is_published(self):
if self.is_expired():
return False
if self.publication_time:
return self.publication_time <= timezone.now()
return False

class Meta:
verbose_name = _('announce')
ordering = ('-mtime',)


class Broadcast(models.Model):
announce = models.ForeignKey(Announce, verbose_name=_('announce'))
deliver_time = models.DateTimeField(_('Deliver time'), null=True)
result = models.TextField(_('result'), blank=True)

def __unicode__(self):
if self.deliver_time:
return u'announce {id} delivered via at {time}'.format(
id=self.announce.id, time=self.deliver_time)
return u'announce {id} to deliver'.format(id=self.announce.id)

def send(self):
subscriptions = self.announce.category.subscription_set.all()
total_sent = 0
handler = HTML2Text()
template = loader.get_template('corbo/announce.html')
m = Message(subject=self.announce.title, mail_from=settings.CORBO_DEFAULT_FROM_EMAIL)
html_tree = HTMLTree(self.announce.text)
storage = DefaultStorage()
for img in html_tree.xpath('//img/@src'):
img_path = img.lstrip(storage.base_url)
m.attach(filename=img, data=storage.open(img_path))
m.attachments[img].is_inline = True
for s in subscriptions:
if not s.identifier:
continue
unsubscribe_token = signing.dumps({'category': self.announce.category.pk,
'identifier': s.identifier})
unsubscribe_link = urlparse.urljoin(settings.SITE_BASE_URL, reverse('unsubscribe',
kwargs={'unsubscription_token': unsubscribe_token}))
message = template.render(Context({'unsubscribe_link': unsubscribe_link,
'content': self.announce.text}))
m.html = message
m.transformer.load_and_transform()
m.transformer.synchronize_inline_images()
m.transformer.save()
handler.body_width = 0
m.text = handler.handle(message)
sent = m.send(to=s.identifier)
if sent:
total_sent += 1
logger.info('Announce "%s" sent to %s', self.announce.title, s.identifier)
else:
logger.warning('Error occured while sending announce "%s" to %s.',
self.announce.title, s.identifier)
self.result = total_sent
self.deliver_time = timezone.now()
self.save()

class Meta:
verbose_name = _('sent')
ordering = ('-deliver_time',)


class Subscription(models.Model):
category = models.ForeignKey('Category', verbose_name=_('Category'))
uuid = models.CharField(_('User identifier'), max_length=128, blank=True)
identifier = models.CharField(_('identifier'), max_length=128, blank=True,
help_text=_('ex.: mailto, homepage, ...'))

def get_identifier_display(self):
try:
scheme, identifier = self.identifier.split(':')
return identifier
except ValueError:
return self.identifier

class Meta:
unique_together = ('category', 'identifier', 'uuid')
(6-6/11)