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