90a6e02a09402d3563a38d08830180e84c809f19
[redakcja.git] / apps / catalogue / models / image.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from django.conf import settings
7 from django.contrib.sites.models import Site
8 from django.db import models
9 from django.template.loader import render_to_string
10 from django.utils.translation import ugettext_lazy as _
11 from catalogue.helpers import cached_in_field
12 from catalogue.tasks import refresh_instance
13 from dvcs import models as dvcs_models
14
15
16 class Image(dvcs_models.Document):
17     """ An editable chunk of text. Every Book text is divided into chunks. """
18     REPO_PATH = settings.CATALOGUE_IMAGE_REPO_PATH
19
20     image = models.FileField(_('image'), upload_to='catalogue/images')
21     title = models.CharField(_('title'), max_length=255, blank=True)
22     slug = models.SlugField(_('slug'), unique=True)
23     public = models.BooleanField(_('public'), default=True, db_index=True)
24
25     # cache
26     _short_html = models.TextField(null=True, blank=True, editable=False)
27     _new_publishable = models.NullBooleanField(editable=False)
28     _published = models.NullBooleanField(editable=False)
29     _changed = models.NullBooleanField(editable=False)
30
31     class Meta:
32         app_label = 'catalogue'
33         ordering = ['title']
34         verbose_name = _('image')
35         verbose_name_plural = _('images')
36         permissions = [('can_pubmark_image', 'Can mark images for publishing')]
37
38     # Representing
39     # ============
40
41     def __unicode__(self):
42         return self.title
43
44     @models.permalink
45     def get_absolute_url(self):
46         return ("catalogue_image", [self.slug])
47
48     def correct_about(self):
49         return "http://%s%s" % (
50             Site.objects.get_current().domain,
51             self.get_absolute_url()
52         )
53
54     # State & cache
55     # =============
56
57     def last_published(self):
58         try:
59             return self.publish_log.all()[0].timestamp
60         except IndexError:
61             return None
62
63     def assert_publishable(self):
64         from librarian.picture import WLPicture
65         from librarian import NoDublinCore, ParseError, ValidationError
66
67         class SelfImageStore(object):
68             def path(self_, slug, mime_type):
69                 """Returns own file object. Ignores slug ad mime_type."""
70                 return open(self.image.path)
71
72         picture_xml = self.publishable().materialize()
73
74         try:
75             picture = WLPicture.from_string(picture_xml.encode('utf-8'),
76                     image_store=SelfImageStore)
77         except ParseError, e:
78             raise AssertionError(_('Invalid XML') + ': ' + str(e))
79         except NoDublinCore:
80             raise AssertionError(_('No Dublin Core found.'))
81         except ValidationError, e:
82             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
83
84         valid_about = self.correct_about()
85         assert (picture.picture_info.about == valid_about,
86                 _("rdf:about is not") + " " + valid_about)
87
88     def accessible(self, request):
89         return self.public or request.user.is_authenticated()
90
91     def is_new_publishable(self):
92         change = self.publishable()
93         if not change:
94             return False
95         return not change.publish_log.exists()
96     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
97
98     def is_published(self):
99         return self.publish_log.exists()
100     published = cached_in_field('_published')(is_published)
101
102     def is_changed(self):
103         if self.head is None:
104             return False
105         return not self.head.publishable
106     changed = cached_in_field('_changed')(is_changed)
107
108     @cached_in_field('_short_html')
109     def short_html(self):
110         return render_to_string(
111                     'catalogue/image_short.html', {'image': self})
112
113     def refresh(self):
114         """This should be done offline."""
115         self.short_html
116         self.single
117         self.new_publishable
118         self.published
119
120     def touch(self):
121         update = {
122             "_changed": self.is_changed(),
123             "_short_html": None,
124             "_new_publishable": self.is_new_publishable(),
125             "_published": self.is_published(),
126         }
127         Image.objects.filter(pk=self.pk).update(**update)
128         refresh_instance(self)
129
130     def refresh(self):
131         """This should be done offline."""
132         self.changed
133         self.short_html
134
135
136     # Publishing
137     # ==========
138
139     def publish(self, user):
140         """Publishes the picture on behalf of a (local) user."""
141         from base64 import b64encode
142         import apiclient
143         from catalogue.signals import post_publish
144
145         self.assert_publishable()
146         change = self.publishable()
147         picture_xml = change.materialize()
148         picture_data = open(self.image.path).read()
149         apiclient.api_call(user, "pictures/", {
150                 "picture_xml": picture_xml,
151                 "picture_image_data": b64encode(picture_data),
152             })
153         # record the publish
154         log = self.publish_log.create(user=user, change=change)
155         post_publish.send(sender=log)