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