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