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.BooleanField(editable=False, null=True, db_index=True)
38 _new_publishable = models.BooleanField(editable=False, null=True)
39 _published = models.BooleanField(editable=False, null=True)
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,
49 editable=False, db_index=True,
50 related_name='document_books',
51 related_query_name='document_book',
54 class NoTextError(BaseException):
58 app_label = 'documents'
59 ordering = ['title', 'slug']
60 verbose_name = _('book')
61 verbose_name_plural = _('books')
68 return iter(self.chunk_set.all())
70 def __getitem__(self, chunk):
71 return self.chunk_set.all()[chunk]
74 return self.chunk_set.count()
78 Necessary so that __len__ isn't used for bool evaluation.
85 def get_absolute_url(self):
86 return reverse("documents_book", args=[self.slug])
88 def correct_about(self):
89 return "http://%s%s" % (
90 Site.objects.get_current().domain,
91 self.get_absolute_url()
94 def gallery_path(self):
95 return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
97 def gallery_url(self):
98 return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, self.gallery)
100 # Creating & manipulating
101 # =======================
103 def accessible(self, request):
104 return self.public or request.user.is_authenticated
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)
114 def add(self, *args, **kwargs):
115 """Add a new chunk at the end."""
116 return self.chunk_set.reverse()[0].split(*args, **kwargs)
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)
125 instance = previous_book
127 instance = cls(**kwargs)
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''))
136 for i, (title, text) in enumerate(texts):
138 title = u'część %d' % (i + 1)
140 slug = slugify(title)
144 chunk.slug = slug[:50]
145 chunk.title = title[:255]
148 chunk = instance.add(slug, title)
150 chunk.commit(text, **commit_args)
154 def make_chunk_slug(self, proposed):
156 Finds a chunk slug not yet used in the book.
158 slugs = set(c.slug for c in self)
160 new_slug = proposed[:50]
161 while new_slug in slugs:
162 new_slug = "%s_%d" % (proposed[:45], i)
167 def append(self, other, slugs=None, titles=None):
168 """Add all chunks of another book to self."""
171 number = self[len(self) - 1].number + 1
172 len_other = len(other)
173 single = len_other == 1
175 if slugs is not None:
176 assert len(slugs) == len_other
177 if titles is not None:
178 assert len(titles) == len_other
180 slugs = [slugify(t) for t in titles]
182 for i, chunk in enumerate(other):
183 # move chunk to new book
185 chunk.number = number
188 # try some title guessing
189 if other.title.startswith(self.title):
190 other_title_part = other.title[len(self.title):].lstrip(' /')
192 other_title_part = other.title
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('-_')
201 chunk.slug = other.slug
203 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
205 chunk.slug = slugs[i]
206 chunk.title = titles[i]
208 chunk.slug = self.make_chunk_slug(chunk.slug)
211 assert not other.chunk_set.exists()
213 gm = GalleryMerger(self.gallery, other.gallery)
214 self.gallery = gm.merge()
216 # and move the gallery starts
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
227 def prepend_history(self, other):
228 """Prepend history from all the other book's chunks to own."""
231 for i in range(len(self), len(other)):
232 title = u"pusta część %d" % i
233 chunk = self.add(slugify(title), title)
236 for i in range(len(other)):
237 self[i].prepend_history(other[0])
239 assert not other.chunk_set.exists()
243 """Splits all the chunks into separate books."""
246 book = Book.objects.create(title=chunk.title, slug=chunk.slug,
247 public=self.public, gallery=self.gallery)
252 assert not self.chunk_set.exists()
258 def last_published(self):
260 return self.publish_log.all()[0].timestamp
264 def assert_publishable(self):
265 assert self.chunk_set.exists(), _('No chunks in the book.')
267 changes = self.get_current_changes(publishable=True)
268 except self.NoTextError:
269 raise AssertionError(_('Not all chunks have publishable revisions.'))
271 from librarian import NoDublinCore, ParseError, ValidationError
274 bi = self.wldocument(changes=changes, strict=True).book_info
275 except ParseError as e:
276 raise AssertionError(_('Invalid XML') + ': ' + str(e))
278 raise AssertionError(_('No Dublin Core found.'))
279 except ValidationError as e:
280 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
282 valid_about = self.correct_about()
283 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
285 def publishable_error(self):
287 return self.assert_publishable()
288 except AssertionError as e:
294 return self.slug.startswith('.')
296 def is_new_publishable(self):
297 """Checks if book is ready for publishing.
299 Returns True if there is a publishable version newer than the one
303 new_publishable = False
304 if not self.chunk_set.exists():
307 change = chunk.publishable()
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)
315 def is_published(self):
316 return self.publish_log.exists()
317 published = cached_in_field('_published')(is_published)
319 def get_on_track(self):
322 stages = [ch.stage.ordering if ch.stage is not None else 0
327 on_track = cached_in_field('_on_track')(get_on_track)
330 return len(self) == 1
331 single = cached_in_field('_single')(is_single)
333 def book_info(self, publishable=True):
335 book_xml = self.materialize(publishable=publishable)
336 except self.NoTextError:
339 from librarian.dcparser import BookInfo
340 from librarian import NoDublinCore, ParseError, ValidationError
342 return BookInfo.from_bytes(book_xml.encode('utf-8'))
343 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
346 def refresh_dc_cache(self):
348 'catalogue_book_id': None,
349 'dc_cover_image': None,
352 info = self.book_info()
354 update['catalogue_book_id'] = info.url.slug
355 if info.cover_source:
357 image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
361 if info.cover_source == image.get_full_url():
362 update['dc_cover_image'] = image
363 Book.objects.filter(pk=self.pk).update(**update)
367 "_new_publishable": self.is_new_publishable(),
368 "_published": self.is_published(),
369 "_single": self.is_single(),
370 "_on_track": self.get_on_track(),
372 Book.objects.filter(pk=self.pk).update(**update)
373 self.refresh_dc_cache()
375 # Materializing & publishing
376 # ==========================
378 def get_current_changes(self, publishable=True):
380 Returns a list containing one Change for every Chunk in the Book.
381 Takes the most recent revision (publishable, if set).
382 Throws an error, if a proper revision is unavailable for a Chunk.
385 changes = [chunk.publishable() for chunk in self]
387 changes = [chunk.head for chunk in self if chunk.head is not None]
389 raise self.NoTextError('Some chunks have no available text.')
392 def materialize(self, publishable=False, changes=None):
394 Get full text of the document compiled from chunks.
395 Takes the current versions of all texts
396 or versions most recently tagged for publishing,
397 or a specified iterable changes.
400 changes = self.get_current_changes(publishable)
401 return compile_text(change.materialize() for change in changes)
403 def wldocument(self, publishable=True, changes=None,
404 parse_dublincore=True, strict=False):
405 from documents.ebook_utils import RedakcjaDocProvider
406 from librarian.parser import WLDocument
408 return WLDocument.from_bytes(
409 self.materialize(publishable=publishable, changes=changes).encode('utf-8'),
410 provider=RedakcjaDocProvider(publishable=publishable),
411 parse_dublincore=parse_dublincore,
414 def publish(self, user, fake=False, host=None, days=0, beta=False):
416 Publishes a book on behalf of a (local) user.
418 self.assert_publishable()
419 changes = self.get_current_changes(publishable=True)
421 book_xml = self.materialize(changes=changes)
422 data = {"book_xml": book_xml, "days": days}
424 data['gallery_url'] = host + self.gallery_url()
425 apiclient.api_call(user, "books/", data, beta=beta)
428 br = BookPublishRecord.objects.create(book=self, user=user)
430 ChunkPublishRecord.objects.create(book_record=br, change=c)
431 if not self.public and days == 0:
434 if self.public and days > 0:
437 post_publish.send(sender=br)
440 doc = self.wldocument()
441 return doc.latex_dir(cover=True, ilustr_path=self.gallery_path())