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