add published entry manager
[django-migdal.git] / migdal / models.py
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.
4 #
5 import re
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, tQ
18 from migdal import app_settings
19 from migdal.fields import SlugNullField
20
21 class Category(models.Model):
22     taxonomy = models.CharField(_('taxonomy'), max_length=32,
23                     choices=app_settings.TAXONOMIES)
24
25     class Meta:
26         verbose_name = _('category')
27         verbose_name_plural = _('categories')
28
29     def __unicode__(self):
30         return self.title
31
32     @models.permalink
33     def get_absolute_url(self):
34         return ('migdal_category', [self.slug])
35
36
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),
40 })
41
42
43 class PublishedEntryManager(models.Manager):
44     def get_query_set(self):
45         return super(PublishedEntryManager, self).get_query_set().filter(
46                 tQ(published=True)
47             )
48
49 class Entry(models.Model):
50     type = models.CharField(max_length=16,
51             choices=((t.db, t.slug) for t in app_settings.TYPES),
52             db_index=True)
53     date = models.DateTimeField(_('created at'), auto_now_add=True, db_index=True)
54     changed_at = models.DateTimeField(_('changed at'), auto_now=True, db_index=True)
55     author = models.CharField(_('author'), max_length=128)
56     author_email = models.EmailField(_('author email'), max_length=128, null=True, blank=True,
57             help_text=_('Used only to display gravatar and send notifications.'))
58     image = models.ImageField(_('image'), upload_to='entry/image/', null=True, blank=True)
59     promo = models.BooleanField(_('promoted'), default=False)
60     in_stream = models.BooleanField(_('in stream'), default=True)
61     categories = models.ManyToManyField(Category, null=True, blank=True, verbose_name=_('categories'))
62     first_published_at = models.DateTimeField(_('published at'), null=True, blank=True)
63
64     objects = models.Manager()
65     published_objects = PublishedEntryManager()
66
67     class Meta:
68         verbose_name = _('entry')
69         verbose_name_plural = _('entries')
70         ordering = ['-date']
71
72     def __unicode__(self):
73         return self.title
74
75     def save(self, *args, **kwargs):
76         published_now = False
77         for lc, ln in settings.LANGUAGES:
78             if (getattr(self, "published_%s" % lc)
79                     and getattr(self, "published_at_%s" % lc) is None):
80                 now = datetime.now()
81                 setattr(self, "published_at_%s" % lc, now)
82                 if self.first_published_at is None:
83                     self.first_published_at = now
84                     published_now = True
85         super(Entry, self).save(*args, **kwargs)
86         if published_now and self.pk is not None:
87             self.notify_author_published()
88
89     def clean(self):
90         for lc, ln in settings.LANGUAGES:
91             if (getattr(self, "published_%s" % lc) and
92                     not getattr(self, "slug_%s" % lc)):
93                 raise ValidationError(
94                     ugettext("Published entry should have a slug in relevant language (%s).") % lc)
95
96     @models.permalink
97     def get_absolute_url(self):
98         return ('migdal_entry_%s' % self.type, [self.slug])
99
100     def get_type(self):
101         return dict(app_settings.TYPES_DICT)[self.type]
102
103     def notify_author_published(self):
104         if not self.author_email:
105             return
106         site = Site.objects.get_current()
107         mail_text = loader.get_template('migdal/mail/published.txt').render(
108             Context({
109                 'entry': self,
110                 'site': site,
111             }))
112         send_mail(
113             ugettext(u'Your story has been published at %s.') % site.domain,
114             mail_text, settings.SERVER_EMAIL, [self.author_email]
115         )
116
117     def inline_html(self):
118         for att in self.attachment_set.all():
119             if att.file.name.endswith(".html"):
120                 with open(att.file.path) as f:
121                     yield f.read()
122
123
124 add_translatable(Entry, languages=app_settings.OPTIONAL_LANGUAGES, fields={
125     'needed': models.CharField(_('needed'), max_length=1, db_index=True, choices=(
126                 ('n', _('Unneeded')), ('w', _('Needed')), ('y', _('Done'))),
127                 default='n'),
128 })
129
130 add_translatable(Entry, {
131     'slug': SlugNullField(unique=True, db_index=True, null=True, blank=True),
132     'title': models.CharField(_('title'), max_length=255, null=True, blank=True),
133     'lead': MarkupField(_('lead'), markup_type='textile_pl', null=True, blank=True,
134                 help_text=_('Use <a href="http://textile.thresholdstate.com/">Textile</a> syntax.')),
135     'body': MarkupField(_('body'), markup_type='textile_pl', null=True, blank=True,
136                 help_text=_('Use <a href="http://textile.thresholdstate.com/">Textile</a> syntax.')),
137     'published': models.BooleanField(_('published'), default=False),
138     'published_at': models.DateTimeField(_('published at'), null=True, blank=True),
139 })
140
141
142 class Attachment(models.Model):
143     file = models.FileField(_('file'), upload_to='entry/attach/')
144     entry = models.ForeignKey(Entry)
145
146     def url(self):
147         return self.file.url if self.file else ''
148
149
150
151 def notify_new_comment(sender, instance, created, **kwargs):
152     if (created and isinstance(instance.content_object, Entry) and
153                 instance.content_object.author_email):
154         site = Site.objects.get_current()
155         mail_text = loader.get_template('migdal/mail/new_comment.txt').render(
156             Context({
157                 'comment': instance,
158                 'site': site,
159             }))
160         send_mail(
161             ugettext(u'New comment under your story at %s.') % site.domain,
162             mail_text, settings.SERVER_EMAIL, 
163             [instance.content_object.author_email]
164         )
165 models.signals.post_save.connect(notify_new_comment, sender=XtdComment)
166
167
168 def spamfilter(sender, comment, **kwargs):
169     """Very simple spam filter. Just don't let any HTML links go through."""
170     if re.search(r"<a\s+href=", comment.comment):
171         fields = (comment.user, comment.user_name, comment.user_email,
172             comment.user_url, comment.submit_date, comment.ip_address,
173             comment.followup, comment.comment)
174         mail_managers(u"Spam filter report",
175             (u"""This comment was turned down as SPAM: \n""" +
176             """\n%s""" * len(fields) +
177             """\n\nYou don't have to do anything.""") % fields)
178         return False
179     return True
180 comment_will_be_posted.connect(spamfilter)