locale
[prawokultury.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 from datetime import datetime
6 from django.conf import settings
7 from django.contrib.sites.models import Site
8 from django.core.exceptions import ValidationError
9 from django.core.mail import send_mail
10 from django.db import models
11 from django.template import loader, Context
12 from django.utils.translation import get_language, ugettext_lazy as _, ugettext
13 from django_comments_xtd.models import XtdComment
14 from markupfield.fields import MarkupField
15 from migdal import app_settings
16 from migdal.helpers import add_translatable
17 from migdal.fields import SlugNullField
18
19 class Category(models.Model):
20     taxonomy = models.CharField(_('taxonomy'), max_length=32,
21                     choices=app_settings.TAXONOMIES)
22
23     class Meta:
24         verbose_name = _('category')
25         verbose_name_plural = _('categories')
26
27     def __unicode__(self):
28         return self.title
29
30     @models.permalink
31     def get_absolute_url(self):
32         return ('migdal_category', [self.slug])
33
34
35 add_translatable(Category, {
36     'title': models.CharField(max_length=64, unique=True, db_index=True),
37     'slug': models.SlugField(unique=True, db_index=True),
38 })
39
40
41 class Entry(models.Model):
42     type = models.CharField(max_length=16,
43             choices=((t.db, t.slug) for t in app_settings.TYPES),
44             db_index=True)
45     date = models.DateTimeField(_('created at'), auto_now_add=True, db_index=True)
46     changed_at = models.DateTimeField(_('changed at'), auto_now=True, db_index=True)
47     author = models.CharField(_('author'), max_length=128)
48     author_email = models.EmailField(_('author email'), max_length=128, null=True, blank=True,
49             help_text=_('Used only to display gravatar and send notifications.'))
50     image = models.ImageField(_('image'), upload_to='entry/image/', null=True, blank=True)
51     promo = models.BooleanField(_('promoted'), default=False)
52     categories = models.ManyToManyField(Category, null=True, blank=True, verbose_name=_('categories'))
53
54     class Meta:
55         verbose_name = _('entry')
56         verbose_name_plural = _('entries')
57         ordering = ['-date']
58
59     def __unicode__(self):
60         return self.title
61
62     def save(self, *args, **kwargs):
63         if self.pk is not None:
64             orig = type(self).objects.get(pk=self.pk)
65             published_now = False
66             for lc, ln in settings.LANGUAGES:
67                 if (getattr(self, "published_%s" % lc)
68                         and getattr(self, "published_at_%s" % lc) is None):
69                     setattr(self, "published_at_%s" % lc, datetime.now())
70                     published_now = True
71             if published_now:
72                 self.notify_author_published()
73         super(Entry, self).save(*args, **kwargs)
74
75     def clean(self):
76         for lc, ln in settings.LANGUAGES:
77             if (getattr(self, "published_%s" % lc) and
78                     not getattr(self, "slug_%s" % lc)):
79                 raise ValidationError(
80                     ugettext("Published entry should have a slug in relevant language (%s).") % lc)
81
82     @models.permalink
83     def get_absolute_url(self):
84         return ('migdal_entry_%s' % self.type, [self.slug])
85
86     def get_type(self):
87         return dict(app_settings.TYPES_DICT)[self.type]
88
89     def notify_author_published(self):
90         if not self.author_email:
91             return
92         site = Site.objects.get_current()
93         mail_text = loader.get_template('migdal/mail/published.txt').render(
94             Context({
95                 'entry': self,
96                 'site': site,
97             }))
98         send_mail(
99             ugettext(u'Your story has been published at %s.') % site.domain,
100             mail_text, settings.SERVER_EMAIL, [self.author_email]
101         )
102
103
104 add_translatable(Entry, languages=app_settings.OPTIONAL_LANGUAGES, fields={
105     'needed': models.CharField(_('needed'), max_length=1, db_index=True, choices=(
106                 ('n', _('Unneeded')), ('w', _('Needed')), ('y', _('Done'))),
107                 default='n'),
108 })
109
110 add_translatable(Entry, {
111     'slug': SlugNullField(unique=True, db_index=True, null=True, blank=True),
112     'title': models.CharField(_('title'), max_length=255, null=True, blank=True),
113     'lead': MarkupField(_('lead'), markup_type='textile_pl', null=True, blank=True,
114                 help_text=_('Use <a href="http://textile.thresholdstate.com/">Textile</a> syntax.')),
115     'body': MarkupField(_('body'), markup_type='textile_pl', null=True, blank=True,
116                 help_text=_('Use <a href="http://textile.thresholdstate.com/">Textile</a> syntax.')),
117     'published': models.BooleanField(_('published'), default=False),
118     'published_at': models.DateTimeField(_('published at'), null=True, blank=True),
119 })
120
121
122 class Attachment(models.Model):
123     file = models.FileField(_('file'), upload_to='entry/attach/')
124     entry = models.ForeignKey(Entry)
125
126     def url(self):
127         return self.file.url if self.file else ''
128
129
130
131 def notify_new_comment(sender, instance, created, **kwargs):
132     if (created and isinstance(instance.content_object, Entry) and
133                 instance.content_object.author_email):
134         site = Site.objects.get_current()
135         mail_text = loader.get_template('migdal/mail/new_comment.txt').render(
136             Context({
137                 'comment': instance,
138                 'site': site,
139             }))
140         send_mail(
141             ugettext(u'New comment under your story at %s.') % site.domain,
142             mail_text, settings.SERVER_EMAIL, 
143             [instance.content_object.author_email]
144         )
145 models.signals.post_save.connect(notify_new_comment, sender=XtdComment)