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.
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
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
24 class Book(models.Model):
25 """ A document edited on the wiki """
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)
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)
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(
47 null=True, blank=True,
48 editable=False, db_index=True,
49 related_name='document_books',
50 related_query_name='document_book',
53 class NoTextError(BaseException):
57 app_label = 'documents'
58 ordering = ['title', 'slug']
59 verbose_name = _('book')
60 verbose_name_plural = _('books')
67 return iter(self.chunk_set.all())
69 def __getitem__(self, chunk):
70 return self.chunk_set.all()[chunk]
73 return self.chunk_set.count()
77 Necessary so that __len__ isn't used for bool evaluation.
84 def get_absolute_url(self):
85 return reverse("documents_book", args=[self.slug])
87 def correct_about(self):
88 return "http://%s%s" % (
89 Site.objects.get_current().domain,
90 self.get_absolute_url()
93 def gallery_path(self):
94 return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
96 def gallery_url(self):
97 return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, self.gallery)
99 # Creating & manipulating
100 # =======================
102 def accessible(self, request):
103 return self.public or request.user.is_authenticated
107 def create(cls, creator, text, *args, **kwargs):
108 b = cls.objects.create(*args, **kwargs)
109 b.chunk_set.all().update(creator=creator)
110 b[0].commit(text, author=creator)
113 def add(self, *args, **kwargs):
114 """Add a new chunk at the end."""
115 return self.chunk_set.reverse()[0].split(*args, **kwargs)
119 def import_xml_text(cls, text=u'', previous_book=None,
120 commit_args=None, **kwargs):
121 """Imports a book from XML, splitting it into chunks as necessary."""
122 texts = split_xml(text)
124 instance = previous_book
126 instance = cls(**kwargs)
129 # if there are more parts, set the rest to empty strings
130 book_len = len(instance)
131 for i in range(book_len - len(texts)):
132 texts.append((u'pusta część %d' % (i + 1), u''))
135 for i, (title, text) in enumerate(texts):
137 title = u'część %d' % (i + 1)
139 slug = slugify(title)
143 chunk.slug = slug[:50]
144 chunk.title = title[:255]
147 chunk = instance.add(slug, title)
149 chunk.commit(text, **commit_args)
153 def make_chunk_slug(self, proposed):
155 Finds a chunk slug not yet used in the book.
157 slugs = set(c.slug for c in self)
159 new_slug = proposed[:50]
160 while new_slug in slugs:
161 new_slug = "%s_%d" % (proposed[:45], i)
166 def append(self, other, slugs=None, titles=None):
167 """Add all chunks of another book to self."""
170 number = self[len(self) - 1].number + 1
171 len_other = len(other)
172 single = len_other == 1
174 if slugs is not None:
175 assert len(slugs) == len_other
176 if titles is not None:
177 assert len(titles) == len_other
179 slugs = [slugify(t) for t in titles]
181 for i, chunk in enumerate(other):
182 # move chunk to new book
184 chunk.number = number
187 # try some title guessing
188 if other.title.startswith(self.title):
189 other_title_part = other.title[len(self.title):].lstrip(' /')
191 other_title_part = other.title
194 # special treatment for appending one-parters:
195 # just use the guessed title and original book slug
196 chunk.title = other_title_part
197 if other.slug.startswith(self.slug):
198 chunk.slug = other.slug[len(self.slug):].lstrip('-_')
200 chunk.slug = other.slug
202 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
204 chunk.slug = slugs[i]
205 chunk.title = titles[i]
207 chunk.slug = self.make_chunk_slug(chunk.slug)
210 assert not other.chunk_set.exists()
212 gm = GalleryMerger(self.gallery, other.gallery)
213 self.gallery = gm.merge()
215 # and move the gallery starts
217 for chunk in self[len(self) - len_other:]:
218 old_start = chunk.gallery_start or 1
219 chunk.gallery_start = old_start + gm.dest_size - gm.num_deleted
226 def prepend_history(self, other):
227 """Prepend history from all the other book's chunks to own."""
230 for i in range(len(self), len(other)):
231 title = u"pusta część %d" % i
232 chunk = self.add(slugify(title), title)
235 for i in range(len(other)):
236 self[i].prepend_history(other[0])
238 assert not other.chunk_set.exists()
242 """Splits all the chunks into separate books."""
245 book = Book.objects.create(title=chunk.title, slug=chunk.slug,
246 public=self.public, gallery=self.gallery)
251 assert not self.chunk_set.exists()
257 def last_published(self):
259 return self.publish_log.all()[0].timestamp
263 def assert_publishable(self):
264 assert self.chunk_set.exists(), _('No chunks in the book.')
266 changes = self.get_current_changes(publishable=True)
267 except self.NoTextError:
268 raise AssertionError(_('Not all chunks have publishable revisions.'))
270 from librarian import NoDublinCore, ParseError, ValidationError
273 bi = self.wldocument(changes=changes, strict=True).book_info
274 except ParseError as e:
275 raise AssertionError(_('Invalid XML') + ': ' + str(e))
277 raise AssertionError(_('No Dublin Core found.'))
278 except ValidationError as e:
279 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
281 valid_about = self.correct_about()
282 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
284 def publishable_error(self):
286 return self.assert_publishable()
287 except AssertionError as e:
293 return self.slug.startswith('.')
295 def is_new_publishable(self):
296 """Checks if book is ready for publishing.
298 Returns True if there is a publishable version newer than the one
302 new_publishable = False
303 if not self.chunk_set.exists():
306 change = chunk.publishable()
309 if not new_publishable and not change.publish_log.exists():
310 new_publishable = True
311 return new_publishable
312 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
314 def is_published(self):
315 return self.publish_log.exists()
316 published = cached_in_field('_published')(is_published)
318 def get_on_track(self):
321 stages = [ch.stage.ordering if ch.stage is not None else 0
326 on_track = cached_in_field('_on_track')(get_on_track)
329 return len(self) == 1
330 single = cached_in_field('_single')(is_single)
332 def book_info(self, publishable=True):
334 book_xml = self.materialize(publishable=publishable)
335 except self.NoTextError:
338 from librarian.dcparser import BookInfo
339 from librarian import NoDublinCore, ParseError, ValidationError
341 return BookInfo.from_bytes(book_xml.encode('utf-8'))
342 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
345 def refresh_dc_cache(self):
347 'catalogue_book_id': None,
348 'dc_cover_image': None,
351 info = self.book_info()
354 update['catalogue_book_id'] = info.url.slug
356 if info.cover_source:
358 image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
362 if info.cover_source == image.get_full_url():
363 update['dc_cover_image'] = image
365 Book.objects.filter(pk=self.pk).update(**update)
369 "_new_publishable": self.is_new_publishable(),
370 "_published": self.is_published(),
371 "_single": self.is_single(),
372 "_on_track": self.get_on_track(),
374 Book.objects.filter(pk=self.pk).update(**update)
375 self.refresh_dc_cache()
377 # Materializing & publishing
378 # ==========================
380 def get_current_changes(self, publishable=True):
382 Returns a list containing one Change for every Chunk in the Book.
383 Takes the most recent revision (publishable, if set).
384 Throws an error, if a proper revision is unavailable for a Chunk.
387 changes = [chunk.publishable() for chunk in self]
389 changes = [chunk.head for chunk in self if chunk.head is not None]
391 raise self.NoTextError('Some chunks have no available text.')
394 def materialize(self, publishable=False, changes=None):
396 Get full text of the document compiled from chunks.
397 Takes the current versions of all texts
398 or versions most recently tagged for publishing,
399 or a specified iterable changes.
402 changes = self.get_current_changes(publishable)
403 return compile_text(change.materialize() for change in changes)
405 def wldocument(self, publishable=True, changes=None,
406 parse_dublincore=True, strict=False):
407 from documents.ebook_utils import RedakcjaDocProvider
408 from librarian.parser import WLDocument
410 return WLDocument.from_bytes(
411 self.materialize(publishable=publishable, changes=changes).encode('utf-8'),
412 provider=RedakcjaDocProvider(publishable=publishable),
413 parse_dublincore=parse_dublincore,
416 def publish(self, user, fake=False, host=None, days=0, beta=False):
418 Publishes a book on behalf of a (local) user.
420 self.assert_publishable()
421 changes = self.get_current_changes(publishable=True)
423 book_xml = self.materialize(changes=changes)
424 data = {"book_xml": book_xml, "days": days}
426 data['gallery_url'] = host + self.gallery_url()
427 apiclient.api_call(user, "books/", data, beta=beta)
430 br = BookPublishRecord.objects.create(book=self, user=user)
432 ChunkPublishRecord.objects.create(book_record=br, change=c)
433 if not self.public and days == 0:
436 if self.public and days > 0:
439 post_publish.send(sender=br)
442 doc = self.wldocument()
443 return doc.latex_dir(cover=True, ilustr_path=self.gallery_path())