librarian update
[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         publishable = self.publishable()
73         assert publishable, _("There is no publishable revision")
74         picture_xml = publishable.materialize()
75
76         try:
77             picture = WLPicture.from_string(picture_xml.encode('utf-8'),
78                     image_store=SelfImageStore)
79         except ParseError, e:
80             raise AssertionError(_('Invalid XML') + ': ' + str(e))
81         except NoDublinCore:
82             raise AssertionError(_('No Dublin Core found.'))
83         except ValidationError, e:
84             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
85
86         valid_about = self.correct_about()
87         assert picture.picture_info.about == valid_about, \
88                 _("rdf:about is not") + " " + valid_about
89
90     def accessible(self, request):
91         return self.public or request.user.is_authenticated()
92
93     def is_new_publishable(self):
94         change = self.publishable()
95         if not change:
96             return False
97         return not change.publish_log.exists()
98     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
99
100     def is_published(self):
101         return self.publish_log.exists()
102     published = cached_in_field('_published')(is_published)
103
104     def is_changed(self):
105         if self.head is None:
106             return False
107         return not self.head.publishable
108     changed = cached_in_field('_changed')(is_changed)
109
110     @cached_in_field('_short_html')
111     def short_html(self):
112         return render_to_string(
113                     'catalogue/image_short.html', {'image': self})
114
115     def refresh(self):
116         """This should be done offline."""
117         self.short_html
118         self.single
119         self.new_publishable
120         self.published
121
122     def touch(self):
123         update = {
124             "_changed": self.is_changed(),
125             "_short_html": None,
126             "_new_publishable": self.is_new_publishable(),
127             "_published": self.is_published(),
128         }
129         Image.objects.filter(pk=self.pk).update(**update)
130         refresh_instance(self)
131
132     def refresh(self):
133         """This should be done offline."""
134         self.changed
135         self.short_html
136
137
138     # Publishing
139     # ==========
140
141     def publish(self, user):
142         """Publishes the picture on behalf of a (local) user."""
143         from base64 import b64encode
144         import apiclient
145         from catalogue.signals import post_publish
146
147         self.assert_publishable()
148         change = self.publishable()
149         picture_xml = change.materialize()
150         picture_data = open(self.image.path).read()
151         apiclient.api_call(user, "pictures/", {
152                 "picture_xml": picture_xml,
153                 "picture_image_data": b64encode(picture_data),
154             })
155         # record the publish
156         log = self.publish_log.create(user=user, change=change)
157         post_publish.send(sender=log)