Filter by places.
[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 connection, models, transaction
7 from django.template.loader import render_to_string
8 from django.urls import reverse
9 from django.utils.translation import gettext_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 from io import BytesIO
21 import os
22 import shutil
23 import re
24
25 class Book(models.Model):
26     """ A document edited on the wiki """
27
28     title = models.CharField(_('title'), max_length=255, db_index=True)
29     slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
30     public = models.BooleanField(_('public'), default=True, db_index=True)
31     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
32     project = models.ForeignKey(Project, models.SET_NULL, null=True, blank=True)
33
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.BooleanField(editable=False, null=True, db_index=True)
39     _new_publishable = models.BooleanField(editable=False, null=True)
40     _published = models.BooleanField(editable=False, null=True)
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 = models.JSONField(null=True, editable=False)
45     catalogue_book = models.ForeignKey(
46         'catalogue.Book',
47         models.DO_NOTHING,
48         to_field='slug',
49         null=True, blank=True,
50         db_constraint=False,
51         editable=False, db_index=True,
52         related_name='document_books',
53         related_query_name='document_book',
54     )
55     legimi_id = models.CharField(max_length=255, blank=True)
56
57     class NoTextError(BaseException):
58         pass
59
60     class Meta:
61         app_label = 'documents'
62         ordering = ['title', 'slug']
63         verbose_name = _('book')
64         verbose_name_plural = _('books')
65
66     @classmethod
67     def get_visible_for(cls, user):
68         qs = cls.objects.all()
69         if not user.is_authenticated:
70             qs = qs.filter(public=True)
71         return qs
72
73     @staticmethod
74     def q_dc(field, field_plural, value, prefix=''):
75         if connection.features.supports_json_field_contains:
76             return models.Q(**{f'{prefix}dc__{field_plural}__contains': value})
77         else:
78             return models.Q(**{f'{prefix}dc__{field}': value})
79             
80     
81     # Representing
82     # ============
83
84     def __iter__(self):
85         return iter(self.chunk_set.all())
86
87     def __getitem__(self, chunk):
88         return self.chunk_set.all()[chunk]
89
90     def __len__(self):
91         return self.chunk_set.count()
92
93     def __bool__(self):
94         """
95             Necessary so that __len__ isn't used for bool evaluation.
96         """
97         return True
98
99     def __str__(self):
100         return self.title
101
102     def get_absolute_url(self):
103         return reverse("documents_book", args=[self.slug])
104
105     def correct_about(self):
106         return "http://%s%s" % (
107             Site.objects.get_current().domain,
108             self.get_absolute_url()
109         )
110
111     def gallery_path(self):
112         return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
113
114     def gallery_url(self):
115         return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, self.gallery)
116
117     # Creating & manipulating
118     # =======================
119
120     def accessible(self, request):
121         return self.public or request.user.is_authenticated
122
123     @classmethod
124     @transaction.atomic
125     def create(cls, creator, text, *args, **kwargs):
126         b = cls.objects.create(*args, **kwargs)
127         b.chunk_set.all().update(creator=creator)
128         b[0].commit(text, author=creator)
129         return b
130
131     def add(self, *args, **kwargs):
132         """Add a new chunk at the end."""
133         return self.chunk_set.reverse()[0].split(*args, **kwargs)
134
135     @classmethod
136     @transaction.atomic
137     def import_xml_text(cls, text=u'', previous_book=None,
138                 commit_args=None, **kwargs):
139         """Imports a book from XML, splitting it into chunks as necessary."""
140         texts = split_xml(text)
141         if previous_book:
142             instance = previous_book
143         else:
144             instance = cls(**kwargs)
145             instance.save()
146
147         # if there are more parts, set the rest to empty strings
148         book_len = len(instance)
149         for i in range(book_len - len(texts)):
150             texts.append((u'pusta część %d' % (i + 1), u''))
151
152         i = 0
153         for i, (title, text) in enumerate(texts):
154             if not title:
155                 title = u'część %d' % (i + 1)
156
157             slug = slugify(title)
158
159             if i < book_len:
160                 chunk = instance[i]
161                 chunk.slug = slug[:50]
162                 chunk.title = title[:255]
163                 chunk.save()
164             else:
165                 chunk = instance.add(slug, title)
166
167             chunk.commit(text, **commit_args)
168
169         return instance
170
171     def make_chunk_slug(self, proposed):
172         """ 
173             Finds a chunk slug not yet used in the book.
174         """
175         slugs = set(c.slug for c in self)
176         i = 1
177         new_slug = proposed[:50]
178         while new_slug in slugs:
179             new_slug = "%s_%d" % (proposed[:45], i)
180             i += 1
181         return new_slug
182
183     @transaction.atomic
184     def append(self, other, slugs=None, titles=None):
185         """Add all chunks of another book to self."""
186         assert self != other
187
188         number = self[len(self) - 1].number + 1
189         len_other = len(other)
190         single = len_other == 1
191
192         if slugs is not None:
193             assert len(slugs) == len_other
194         if titles is not None:
195             assert len(titles) == len_other
196             if slugs is None:
197                 slugs = [slugify(t) for t in titles]
198
199         for i, chunk in enumerate(other):
200             # move chunk to new book
201             chunk.book = self
202             chunk.number = number
203
204             if titles is None:
205                 # try some title guessing
206                 if other.title.startswith(self.title):
207                     other_title_part = other.title[len(self.title):].lstrip(' /')
208                 else:
209                     other_title_part = other.title
210
211                 if single:
212                     # special treatment for appending one-parters:
213                     # just use the guessed title and original book slug
214                     chunk.title = other_title_part
215                     if other.slug.startswith(self.slug):
216                         chunk.slug = other.slug[len(self.slug):].lstrip('-_')
217                     else:
218                         chunk.slug = other.slug
219                 else:
220                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
221             else:
222                 chunk.slug = slugs[i]
223                 chunk.title = titles[i]
224
225             chunk.slug = self.make_chunk_slug(chunk.slug)
226             chunk.save()
227             number += 1
228         assert not other.chunk_set.exists()
229
230         gm = GalleryMerger(self.gallery, other.gallery)
231         self.gallery = gm.merge()
232
233         # and move the gallery starts
234         if gm.was_merged:
235                 for chunk in self[len(self) - len_other:]:
236                         old_start = chunk.gallery_start or 1
237                         chunk.gallery_start = old_start + gm.dest_size - gm.num_deleted
238                         chunk.save()
239
240         other.delete()
241
242
243     @transaction.atomic
244     def prepend_history(self, other):
245         """Prepend history from all the other book's chunks to own."""
246         assert self != other
247
248         for i in range(len(self), len(other)):
249             title = u"pusta część %d" % i
250             chunk = self.add(slugify(title), title)
251             chunk.commit('')
252
253         for i in range(len(other)):
254             self[i].prepend_history(other[0])
255
256         assert not other.chunk_set.exists()
257         other.delete()
258
259     def split(self):
260         """Splits all the chunks into separate books."""
261         self.title
262         for chunk in self:
263             book = Book.objects.create(title=chunk.title, slug=chunk.slug,
264                     public=self.public, gallery=self.gallery)
265             book[0].delete()
266             chunk.book = book
267             chunk.number = 1
268             chunk.save()
269         assert not self.chunk_set.exists()
270         self.delete()
271
272     # State & cache
273     # =============
274
275     def last_published(self):
276         try:
277             return self.publish_log.all()[0].timestamp
278         except IndexError:
279             return None
280
281     def last_legimi_publish(self):
282         return self.legimibookpublish_set.order_by('-created_at').first()
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
396     # Materializing & publishing
397     # ==========================
398
399     def get_current_changes(self, publishable=True):
400         """
401             Returns a list containing one Change for every Chunk in the Book.
402             Takes the most recent revision (publishable, if set).
403             Throws an error, if a proper revision is unavailable for a Chunk.
404         """
405         if publishable:
406             changes = [chunk.publishable() for chunk in self]
407         else:
408             changes = [chunk.head for chunk in self if chunk.head is not None]
409         if None in changes:
410             raise self.NoTextError('Some chunks have no available text.')
411         return changes
412
413     def materialize(self, publishable=False, changes=None):
414         """ 
415             Get full text of the document compiled from chunks.
416             Takes the current versions of all texts
417             or versions most recently tagged for publishing,
418             or a specified iterable changes.
419         """
420         if changes is None:
421             changes = self.get_current_changes(publishable)
422         return compile_text(change.materialize() for change in changes)
423
424     def wldocument(self, publishable=True, changes=None, 
425                    parse_dublincore=True, strict=False, librarian2=False):
426         from documents.ebook_utils import RedakcjaDocProvider
427         from librarian.parser import WLDocument
428         from librarian.document import WLDocument as WLDocument2
429
430         provider = RedakcjaDocProvider(publishable=publishable)
431         xml = self.materialize(publishable=publishable, changes=changes).encode('utf-8')
432         
433         if librarian2:
434             return WLDocument2(
435                 BytesIO(xml),
436                 provider=provider)
437         return WLDocument.from_bytes(
438                 xml,
439                 provider=provider,
440                 parse_dublincore=parse_dublincore,
441                 strict=strict)
442
443     def publish(self, user, fake=False, host=None, days=0, beta=False, hidden=False):
444         """
445             Publishes a book on behalf of a (local) user.
446         """
447         self.assert_publishable()
448         changes = self.get_current_changes(publishable=True)
449         if not fake:
450             book_xml = self.materialize(changes=changes)
451             data = {"book_xml": book_xml, "days": days, "hidden": hidden}
452             if host:
453                 data['gallery_url'] = host + self.gallery_url()
454             apiclient.api_call(user, "books/", data, beta=beta)
455         if not beta:
456             # record the publish
457             br = BookPublishRecord.objects.create(book=self, user=user)
458             for c in changes:
459                 ChunkPublishRecord.objects.create(book_record=br, change=c)
460             if not self.public and days == 0:
461                 self.public = True
462                 self.save()
463             if self.public and days > 0:
464                 self.public = False
465                 self.save()
466             post_publish.send(sender=br)
467
468     def latex_dir(self):
469         doc = self.wldocument()
470         return doc.latex_dir(cover=True, ilustr_path=self.gallery_path())