Python 3
[redakcja.git] / src / 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.models import Project
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     project = models.ForeignKey(Project, null=True, blank=True)
25
26     # cache
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 __str__(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             "http://%s%s" % (
54                 'obrazy.redakcja.wolnelektury.pl',
55                 self.get_absolute_url()
56             )]
57
58     # State & cache
59     # =============
60
61     def last_published(self):
62         try:
63             return self.publish_log.all()[0].timestamp
64         except IndexError:
65             return None
66
67     def assert_publishable(self):
68         from librarian.picture import WLPicture
69         from librarian import NoDublinCore, ParseError, ValidationError
70
71         class SelfImageStore(object):
72             def path(self_, slug, mime_type):
73                 """Returns own file object. Ignores slug ad mime_type."""
74                 return open(self.image.path)
75
76         publishable = self.publishable()
77         assert publishable, _("There is no publishable revision")
78         picture_xml = publishable.materialize()
79
80         try:
81             picture = WLPicture.from_bytes(
82                     picture_xml.encode('utf-8'),
83                     image_store=SelfImageStore)
84         except ParseError as e:
85             raise AssertionError(_('Invalid XML') + ': ' + str(e))
86         except NoDublinCore:
87             raise AssertionError(_('No Dublin Core found.'))
88         except ValidationError as e:
89             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
90
91         valid_about = self.correct_about()
92         assert picture.picture_info.about in valid_about, \
93                 _("rdf:about is not") + " " + valid_about[0]
94
95     def publishable_error(self):
96         try:
97             return self.assert_publishable()
98         except AssertionError as e:
99             return e
100         else:
101             return None
102
103     def accessible(self, request):
104         return self.public or request.user.is_authenticated()
105
106     def is_new_publishable(self):
107         change = self.publishable()
108         if not change:
109             return False
110         return not change.publish_log.exists()
111     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
112
113     def is_published(self):
114         return self.publish_log.exists()
115     published = cached_in_field('_published')(is_published)
116
117     def is_changed(self):
118         if self.head is None:
119             return False
120         return not self.head.publishable
121     changed = cached_in_field('_changed')(is_changed)
122
123     def touch(self):
124         update = {
125             "_changed": self.is_changed(),
126             "_new_publishable": self.is_new_publishable(),
127             "_published": self.is_published(),
128         }
129         Image.objects.filter(pk=self.pk).update(**update)
130
131     # Publishing
132     # ==========
133
134     def publish(self, user):
135         """Publishes the picture on behalf of a (local) user."""
136         from base64 import b64encode
137         import apiclient
138         from catalogue.signals import post_publish
139
140         self.assert_publishable()
141         change = self.publishable()
142         picture_xml = change.materialize()
143         picture_data = open(self.image.path).read()
144         apiclient.api_call(user, "pictures/", {
145                 "picture_xml": picture_xml,
146                 "picture_image_data": b64encode(picture_data),
147             })
148         # record the publish
149         log = self.publish_log.create(user=user, change=change)
150         post_publish.send(sender=log)