wcag fixes
[redakcja.git] / apps / catalogue / models / book.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.contrib.sites.models import Site
7 from django.db import models, transaction
8 from django.template.loader import render_to_string
9 from django.utils.translation import ugettext_lazy as _
10 from slughifi import slughifi
11
12 from catalogue.helpers import cached_in_field
13 from catalogue.models import BookPublishRecord, ChunkPublishRecord
14 from catalogue.tasks import refresh_instance, book_content_updated
15 from catalogue.xml_tools import compile_text, split_xml
16
17
18 class Book(models.Model):
19     """ A document edited on the wiki """
20
21     title = models.CharField(_('title'), max_length=255, db_index=True)
22     slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
23     public = models.BooleanField(_('public'), default=True, db_index=True)
24     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
25
26     #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
27     parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children", editable=False)
28     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True, editable=False)
29
30     # Cache
31     _short_html = models.TextField(null=True, blank=True, editable=False)
32     _single = models.NullBooleanField(editable=False, db_index=True)
33     _new_publishable = models.NullBooleanField(editable=False)
34     _published = models.NullBooleanField(editable=False)
35     dc_slug = models.CharField(max_length=128, null=True, blank=True,
36             editable=False, db_index=True)
37
38     class NoTextError(BaseException):
39         pass
40
41     class Meta:
42         app_label = 'catalogue'
43         ordering = ['title', 'slug']
44         verbose_name = _('book')
45         verbose_name_plural = _('books')
46
47
48     # Representing
49     # ============
50
51     def __iter__(self):
52         return iter(self.chunk_set.all())
53
54     def __getitem__(self, chunk):
55         return self.chunk_set.all()[chunk]
56
57     def __len__(self):
58         return self.chunk_set.count()
59
60     def __nonzero__(self):
61         """
62             Necessary so that __len__ isn't used for bool evaluation.
63         """
64         return True
65
66     def __unicode__(self):
67         return self.title
68
69     @models.permalink
70     def get_absolute_url(self):
71         return ("catalogue_book", [self.slug])
72
73     def correct_about(self):
74         return "http://%s%s" % (
75             Site.objects.get_current().domain,
76             self.get_absolute_url()
77         )
78
79     # Creating & manipulating
80     # =======================
81
82     def accessible(self, request):
83         return self.public or request.user.is_authenticated()
84
85     @classmethod
86     @transaction.commit_on_success
87     def create(cls, creator, text, *args, **kwargs):
88         b = cls.objects.create(*args, **kwargs)
89         b.chunk_set.all().update(creator=creator)
90         b[0].commit(text, author=creator)
91         return b
92
93     def add(self, *args, **kwargs):
94         """Add a new chunk at the end."""
95         return self.chunk_set.reverse()[0].split(*args, **kwargs)
96
97     @classmethod
98     @transaction.commit_on_success
99     def import_xml_text(cls, text=u'', previous_book=None,
100                 commit_args=None, **kwargs):
101         """Imports a book from XML, splitting it into chunks as necessary."""
102         texts = split_xml(text)
103         if previous_book:
104             instance = previous_book
105         else:
106             instance = cls(**kwargs)
107             instance.save()
108
109         # if there are more parts, set the rest to empty strings
110         book_len = len(instance)
111         for i in range(book_len - len(texts)):
112             texts.append((u'pusta część %d' % (i + 1), u''))
113
114         i = 0
115         for i, (title, text) in enumerate(texts):
116             if not title:
117                 title = u'część %d' % (i + 1)
118
119             slug = slughifi(title)
120
121             if i < book_len:
122                 chunk = instance[i]
123                 chunk.slug = slug[:50]
124                 chunk.title = title[:255]
125                 chunk.save()
126             else:
127                 chunk = instance.add(slug, title)
128
129             chunk.commit(text, **commit_args)
130
131         return instance
132
133     def make_chunk_slug(self, proposed):
134         """ 
135             Finds a chunk slug not yet used in the book.
136         """
137         slugs = set(c.slug for c in self)
138         i = 1
139         new_slug = proposed[:50]
140         while new_slug in slugs:
141             new_slug = "%s_%d" % (proposed[:45], i)
142             i += 1
143         return new_slug
144
145     @transaction.commit_on_success
146     def append(self, other, slugs=None, titles=None):
147         """Add all chunks of another book to self."""
148         assert self != other
149
150         number = self[len(self) - 1].number + 1
151         len_other = len(other)
152         single = len_other == 1
153
154         if slugs is not None:
155             assert len(slugs) == len_other
156         if titles is not None:
157             assert len(titles) == len_other
158             if slugs is None:
159                 slugs = [slughifi(t) for t in titles]
160
161         for i, chunk in enumerate(other):
162             # move chunk to new book
163             chunk.book = self
164             chunk.number = number
165
166             if titles is None:
167                 # try some title guessing
168                 if other.title.startswith(self.title):
169                     other_title_part = other.title[len(self.title):].lstrip(' /')
170                 else:
171                     other_title_part = other.title
172
173                 if single:
174                     # special treatment for appending one-parters:
175                     # just use the guessed title and original book slug
176                     chunk.title = other_title_part
177                     if other.slug.startswith(self.slug):
178                         chunk.slug = other.slug[len(self.slug):].lstrip('-_')
179                     else:
180                         chunk.slug = other.slug
181                 else:
182                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
183             else:
184                 chunk.slug = slugs[i]
185                 chunk.title = titles[i]
186
187             chunk.slug = self.make_chunk_slug(chunk.slug)
188             chunk.save()
189             number += 1
190         assert not other.chunk_set.exists()
191         other.delete()
192
193     @transaction.commit_on_success
194     def prepend_history(self, other):
195         """Prepend history from all the other book's chunks to own."""
196         assert self != other
197
198         for i in range(len(self), len(other)):
199             title = u"pusta część %d" % i
200             chunk = self.add(slughifi(title), title)
201             chunk.commit('')
202
203         for i in range(len(other)):
204             self[i].prepend_history(other[0])
205
206         assert not other.chunk_set.exists()
207         other.delete()
208
209
210     # State & cache
211     # =============
212
213     def last_published(self):
214         try:
215             return self.publish_log.all()[0].timestamp
216         except IndexError:
217             return None
218
219     def assert_publishable(self):
220         assert self.chunk_set.exists(), _('No chunks in the book.')
221         try:
222             changes = self.get_current_changes(publishable=True)
223         except self.NoTextError:
224             raise AssertionError(_('Not all chunks have publishable revisions.'))
225         book_xml = self.materialize(changes=changes)
226
227         from librarian.dcparser import BookInfo
228         from librarian import NoDublinCore, ParseError, ValidationError
229
230         try:
231             bi = BookInfo.from_string(book_xml.encode('utf-8'))
232         except ParseError, e:
233             raise AssertionError(_('Invalid XML') + ': ' + str(e))
234         except NoDublinCore:
235             raise AssertionError(_('No Dublin Core found.'))
236         except ValidationError, e:
237             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
238
239         valid_about = self.correct_about()
240         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
241
242     def hidden(self):
243         return self.slug.startswith('.')
244
245     def is_new_publishable(self):
246         """Checks if book is ready for publishing.
247
248         Returns True if there is a publishable version newer than the one
249         already published.
250
251         """
252         new_publishable = False
253         if not self.chunk_set.exists():
254             return False
255         for chunk in self:
256             change = chunk.publishable()
257             if not change:
258                 return False
259             if not new_publishable and not change.publish_log.exists():
260                 new_publishable = True
261         return new_publishable
262     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
263
264     def is_published(self):
265         return self.publish_log.exists()
266     published = cached_in_field('_published')(is_published)
267
268     def is_single(self):
269         return len(self) == 1
270     single = cached_in_field('_single')(is_single)
271
272     @cached_in_field('_short_html')
273     def short_html(self):
274         return render_to_string('catalogue/book_list/book.html', {'book': self})
275
276     def book_info(self, publishable=True):
277         try:
278             book_xml = self.materialize(publishable=publishable)
279         except self.NoTextError:
280             pass
281         else:
282             from librarian.dcparser import BookInfo
283             from librarian import NoDublinCore, ParseError, ValidationError
284             try:
285                 return BookInfo.from_string(book_xml.encode('utf-8'))
286             except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
287                 return None
288
289     def refresh_dc_cache(self):
290         update = {
291             'dc_slug': None,
292         }
293
294         info = self.book_info()
295         if info is not None:
296             update['dc_slug'] = info.slug
297         Book.objects.filter(pk=self.pk).update(**update)
298
299     def touch(self):
300         # this should only really be done when text or publishable status changes
301         book_content_updated.delay(self)
302
303         update = {
304             "_new_publishable": self.is_new_publishable(),
305             "_published": self.is_published(),
306             "_single": self.is_single(),
307             "_short_html": None,
308         }
309         Book.objects.filter(pk=self.pk).update(**update)
310         refresh_instance(self)
311
312     def refresh(self):
313         """This should be done offline."""
314         self.short_html
315         self.single
316         self.new_publishable
317         self.published
318
319     # Materializing & publishing
320     # ==========================
321
322     def get_current_changes(self, publishable=True):
323         """
324             Returns a list containing one Change for every Chunk in the Book.
325             Takes the most recent revision (publishable, if set).
326             Throws an error, if a proper revision is unavailable for a Chunk.
327         """
328         if publishable:
329             changes = [chunk.publishable() for chunk in self]
330         else:
331             changes = [chunk.head for chunk in self if chunk.head is not None]
332         if None in changes:
333             raise self.NoTextError('Some chunks have no available text.')
334         return changes
335
336     def materialize(self, publishable=False, changes=None):
337         """ 
338             Get full text of the document compiled from chunks.
339             Takes the current versions of all texts
340             or versions most recently tagged for publishing,
341             or a specified iterable changes.
342         """
343         if changes is None:
344             changes = self.get_current_changes(publishable)
345         return compile_text(change.materialize() for change in changes)
346
347     def publish(self, user):
348         """
349             Publishes a book on behalf of a (local) user.
350         """
351         import apiclient
352         from catalogue.signals import post_publish
353
354         self.assert_publishable()
355         changes = self.get_current_changes(publishable=True)
356         book_xml = self.materialize(changes=changes)
357         apiclient.api_call(user, "books/", {"book_xml": book_xml})
358         # record the publish
359         br = BookPublishRecord.objects.create(book=self, user=user)
360         for c in changes:
361             ChunkPublishRecord.objects.create(book_record=br, change=c)
362         post_publish.send(sender=br)