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