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