1 # -*- coding: utf-8 -*-
 
   2 # This file is part of PrawoKultury, licensed under GNU Affero GPLv3 or later.
 
   3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   6 from datetime import datetime
 
   7 from django.conf import settings
 
   8 from django.contrib.comments.signals import comment_will_be_posted
 
   9 from django.contrib.sites.models import Site
 
  10 from django.core.exceptions import ValidationError
 
  11 from django.core.mail import mail_managers, send_mail
 
  12 from django.db import models
 
  13 from django.template import loader, Context
 
  14 from django.utils.translation import get_language, ugettext_lazy as _, ugettext
 
  15 from django_comments_xtd.models import XtdComment
 
  16 from markupfield.fields import MarkupField
 
  17 from fnpdjango.utils.models.translation import add_translatable
 
  18 from migdal import app_settings
 
  19 from migdal.fields import SlugNullField
 
  21 class Category(models.Model):
 
  22     taxonomy = models.CharField(_('taxonomy'), max_length=32,
 
  23                     choices=app_settings.TAXONOMIES)
 
  26         verbose_name = _('category')
 
  27         verbose_name_plural = _('categories')
 
  29     def __unicode__(self):
 
  33     def get_absolute_url(self):
 
  34         return ('migdal_category', [self.slug])
 
  37 add_translatable(Category, {
 
  38     'title': models.CharField(max_length=64, unique=True, db_index=True),
 
  39     'slug': models.SlugField(unique=True, db_index=True),
 
  43 class Entry(models.Model):
 
  44     type = models.CharField(max_length=16,
 
  45             choices=((t.db, t.slug) for t in app_settings.TYPES),
 
  47     date = models.DateTimeField(_('created at'), auto_now_add=True, db_index=True)
 
  48     changed_at = models.DateTimeField(_('changed at'), auto_now=True, db_index=True)
 
  49     author = models.CharField(_('author'), max_length=128)
 
  50     author_email = models.EmailField(_('author email'), max_length=128, null=True, blank=True,
 
  51             help_text=_('Used only to display gravatar and send notifications.'))
 
  52     image = models.ImageField(_('image'), upload_to='entry/image/', null=True, blank=True)
 
  53     promo = models.BooleanField(_('promoted'), default=False)
 
  54     in_stream = models.BooleanField(_('in stream'), default=True)
 
  55     categories = models.ManyToManyField(Category, null=True, blank=True, verbose_name=_('categories'))
 
  56     first_published_at = models.DateTimeField(_('published at'), null=True, blank=True)
 
  59         verbose_name = _('entry')
 
  60         verbose_name_plural = _('entries')
 
  63     def __unicode__(self):
 
  66     def save(self, *args, **kwargs):
 
  68         for lc, ln in settings.LANGUAGES:
 
  69             if (getattr(self, "published_%s" % lc)
 
  70                     and getattr(self, "published_at_%s" % lc) is None):
 
  72                 setattr(self, "published_at_%s" % lc, now)
 
  73                 if self.first_published_at is None:
 
  74                     self.first_published_at = now
 
  76         super(Entry, self).save(*args, **kwargs)
 
  77         if published_now and self.pk is not None:
 
  78             self.notify_author_published()
 
  81         for lc, ln in settings.LANGUAGES:
 
  82             if (getattr(self, "published_%s" % lc) and
 
  83                     not getattr(self, "slug_%s" % lc)):
 
  84                 raise ValidationError(
 
  85                     ugettext("Published entry should have a slug in relevant language (%s).") % lc)
 
  88     def get_absolute_url(self):
 
  89         return ('migdal_entry_%s' % self.type, [self.slug])
 
  92         return dict(app_settings.TYPES_DICT)[self.type]
 
  94     def notify_author_published(self):
 
  95         if not self.author_email:
 
  97         site = Site.objects.get_current()
 
  98         mail_text = loader.get_template('migdal/mail/published.txt').render(
 
 104             ugettext(u'Your story has been published at %s.') % site.domain,
 
 105             mail_text, settings.SERVER_EMAIL, [self.author_email]
 
 108     def inline_html(self):
 
 109         for att in self.attachment_set.all():
 
 110             if att.file.name.endswith(".html"):
 
 111                 with open(att.file.path) as f:
 
 115 add_translatable(Entry, languages=app_settings.OPTIONAL_LANGUAGES, fields={
 
 116     'needed': models.CharField(_('needed'), max_length=1, db_index=True, choices=(
 
 117                 ('n', _('Unneeded')), ('w', _('Needed')), ('y', _('Done'))),
 
 121 add_translatable(Entry, {
 
 122     'slug': SlugNullField(unique=True, db_index=True, null=True, blank=True),
 
 123     'title': models.CharField(_('title'), max_length=255, null=True, blank=True),
 
 124     'lead': MarkupField(_('lead'), markup_type='textile_pl', null=True, blank=True,
 
 125                 help_text=_('Use <a href="http://textile.thresholdstate.com/">Textile</a> syntax.')),
 
 126     'body': MarkupField(_('body'), markup_type='textile_pl', null=True, blank=True,
 
 127                 help_text=_('Use <a href="http://textile.thresholdstate.com/">Textile</a> syntax.')),
 
 128     'published': models.BooleanField(_('published'), default=False),
 
 129     'published_at': models.DateTimeField(_('published at'), null=True, blank=True),
 
 133 class Attachment(models.Model):
 
 134     file = models.FileField(_('file'), upload_to='entry/attach/')
 
 135     entry = models.ForeignKey(Entry)
 
 138         return self.file.url if self.file else ''
 
 142 def notify_new_comment(sender, instance, created, **kwargs):
 
 143     if (created and isinstance(instance.content_object, Entry) and
 
 144                 instance.content_object.author_email):
 
 145         site = Site.objects.get_current()
 
 146         mail_text = loader.get_template('migdal/mail/new_comment.txt').render(
 
 152             ugettext(u'New comment under your story at %s.') % site.domain,
 
 153             mail_text, settings.SERVER_EMAIL, 
 
 154             [instance.content_object.author_email]
 
 156 models.signals.post_save.connect(notify_new_comment, sender=XtdComment)
 
 159 def spamfilter(sender, comment, **kwargs):
 
 160     """Very simple spam filter. Just don't let any HTML links go through."""
 
 161     if re.search(r"<a\s+href=", comment.comment):
 
 162         fields = (comment.user, comment.user_name, comment.user_email,
 
 163             comment.user_url, comment.submit_date, comment.ip_address,
 
 164             comment.followup, comment.comment)
 
 165         mail_managers(u"Spam filter report",
 
 166             (u"""This comment was turned down as SPAM: \n""" +
 
 167             """\n%s""" * len(fields) +
 
 168             """\n\nYou don't have to do anything.""") % fields)
 
 171 comment_will_be_posted.connect(spamfilter)