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