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