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