simplify gallery
[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 fnpdjango.utils.fields import TextileField
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_queryset(self):
44         return super(PublishedEntryManager, self).get_queryset().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 TEXTILE_HELP = _('Use <a href="https://txstyle.org/article/44/an-overview-of-the-textile-syntax">Textile</a> syntax.')
134
135 add_translatable(Entry, {
136     'slug': SlugNullField(unique=True, db_index=True, null=True, blank=True),
137     'title': models.CharField(_('title'), max_length=255, null=True, blank=True),
138     'lead': TextileField(
139         _('lead'), markup_type='textile_pl', null=True, blank=True, help_text=TEXTILE_HELP),
140     'body': TextileField(
141         _('body'), markup_type='textile_pl', null=True, blank=True, help_text=TEXTILE_HELP),
142     'place': models.CharField(_('place'), null=True, blank=True, max_length=256),
143     'time': models.CharField(_('time'), null=True, blank=True, max_length=256),
144     'published': models.BooleanField(_('published'), default=False),
145     'published_at': models.DateTimeField(_('published at'), null=True, blank=True),
146 })
147
148
149 class Attachment(models.Model):
150     file = models.FileField(_('file'), upload_to='entry/attach/')
151     entry = models.ForeignKey(Entry)
152
153     def url(self):
154         return self.file.url if self.file else ''
155
156
157 class Photo(models.Model):
158     image = models.ImageField(_('image'), upload_to='entry/photo/')
159     entry = models.ForeignKey(Entry)
160
161     def url(self):
162         return self.image.url if self.image else ''
163
164
165 def notify_new_comment(sender, instance, created, **kwargs):
166     if created and isinstance(instance.content_object, Entry) and instance.content_object.author_email:
167         site = Site.objects.get_current()
168         mail_text = loader.get_template('migdal/mail/new_comment.txt').render(
169             Context({
170                 'comment': instance,
171                 'site': site,
172             }))
173         send_mail(
174             ugettext(u'New comment under your story at %s.') % site.domain,
175             mail_text, settings.SERVER_EMAIL, 
176             [instance.content_object.author_email]
177         )
178 models.signals.post_save.connect(notify_new_comment, sender=XtdComment)
179
180
181 def spamfilter(sender, comment, **kwargs):
182     """Very simple spam filter. Just don't let any HTML links go through."""
183     if re.search(r"<a\s+href=", comment.comment):
184         fields = (
185             comment.user, comment.user_name, comment.user_email,
186             comment.user_url, comment.submit_date, comment.ip_address,
187             comment.followup, comment.comment)
188         mail_managers(
189             u"Spam filter report",
190             (u"""This comment was turned down as SPAM: \n""" +
191              """\n%s""" * len(fields) +
192              """\n\nYou don't have to do anything.""") % fields)
193         return False
194     return True
195 # comment_will_be_posted.connect(spamfilter)