1 # -*- coding: utf-8 -*-
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.
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
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
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, null=True, blank=True)
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)
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)
47 class NoTextError(BaseException):
51 app_label = 'catalogue'
52 ordering = ['title', 'slug']
53 verbose_name = _('book')
54 verbose_name_plural = _('books')
61 return iter(self.chunk_set.all())
63 def __getitem__(self, chunk):
64 return self.chunk_set.all()[chunk]
67 return self.chunk_set.count()
71 Necessary so that __len__ isn't used for bool evaluation.
79 def get_absolute_url(self):
80 return ("catalogue_book", [self.slug])
82 def correct_about(self):
83 return "http://%s%s" % (
84 Site.objects.get_current().domain,
85 self.get_absolute_url()
88 def gallery_path(self):
89 return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
91 def gallery_url(self):
92 return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, self.gallery)
94 # Creating & manipulating
95 # =======================
97 def accessible(self, request):
98 return self.public or request.user.is_authenticated()
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)
108 def add(self, *args, **kwargs):
109 """Add a new chunk at the end."""
110 return self.chunk_set.reverse()[0].split(*args, **kwargs)
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)
119 instance = previous_book
121 instance = cls(**kwargs)
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''))
130 for i, (title, text) in enumerate(texts):
132 title = u'część %d' % (i + 1)
134 slug = slugify(title)
138 chunk.slug = slug[:50]
139 chunk.title = title[:255]
142 chunk = instance.add(slug, title)
144 chunk.commit(text, **commit_args)
148 def make_chunk_slug(self, proposed):
150 Finds a chunk slug not yet used in the book.
152 slugs = set(c.slug for c in self)
154 new_slug = proposed[:50]
155 while new_slug in slugs:
156 new_slug = "%s_%d" % (proposed[:45], i)
161 def append(self, other, slugs=None, titles=None):
162 """Add all chunks of another book to self."""
165 number = self[len(self) - 1].number + 1
166 len_other = len(other)
167 single = len_other == 1
169 if slugs is not None:
170 assert len(slugs) == len_other
171 if titles is not None:
172 assert len(titles) == len_other
174 slugs = [slugify(t) for t in titles]
176 for i, chunk in enumerate(other):
177 # move chunk to new book
179 chunk.number = number
182 # try some title guessing
183 if other.title.startswith(self.title):
184 other_title_part = other.title[len(self.title):].lstrip(' /')
186 other_title_part = other.title
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('-_')
195 chunk.slug = other.slug
197 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
199 chunk.slug = slugs[i]
200 chunk.title = titles[i]
202 chunk.slug = self.make_chunk_slug(chunk.slug)
205 assert not other.chunk_set.exists()
207 gm = GalleryMerger(self.gallery, other.gallery)
208 self.gallery = gm.merge()
210 # and move the gallery starts
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
221 def prepend_history(self, other):
222 """Prepend history from all the other book's chunks to own."""
225 for i in range(len(self), len(other)):
226 title = u"pusta część %d" % i
227 chunk = self.add(slugify(title), title)
230 for i in range(len(other)):
231 self[i].prepend_history(other[0])
233 assert not other.chunk_set.exists()
237 """Splits all the chunks into separate books."""
240 book = Book.objects.create(title=chunk.title, slug=chunk.slug,
241 public=self.public, gallery=self.gallery)
246 assert not self.chunk_set.exists()
252 def last_published(self):
254 return self.publish_log.all()[0].timestamp
258 def assert_publishable(self):
259 assert self.chunk_set.exists(), _('No chunks in the book.')
261 changes = self.get_current_changes(publishable=True)
262 except self.NoTextError:
263 raise AssertionError(_('Not all chunks have publishable revisions.'))
265 from librarian import NoDublinCore, ParseError, ValidationError
268 bi = self.wldocument(changes=changes, strict=True).book_info
269 except ParseError as e:
270 raise AssertionError(_('Invalid XML') + ': ' + str(e))
272 raise AssertionError(_('No Dublin Core found.'))
273 except ValidationError as e:
274 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
276 valid_about = self.correct_about()
277 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
279 def publishable_error(self):
281 return self.assert_publishable()
282 except AssertionError as e:
288 return self.slug.startswith('.')
290 def is_new_publishable(self):
291 """Checks if book is ready for publishing.
293 Returns True if there is a publishable version newer than the one
297 new_publishable = False
298 if not self.chunk_set.exists():
301 change = chunk.publishable()
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)
309 def is_published(self):
310 return self.publish_log.exists()
311 published = cached_in_field('_published')(is_published)
313 def get_on_track(self):
316 stages = [ch.stage.ordering if ch.stage is not None else 0
321 on_track = cached_in_field('_on_track')(get_on_track)
324 return len(self) == 1
325 single = cached_in_field('_single')(is_single)
327 def book_info(self, publishable=True):
329 book_xml = self.materialize(publishable=publishable)
330 except self.NoTextError:
333 from librarian.dcparser import BookInfo
334 from librarian import NoDublinCore, ParseError, ValidationError
336 return BookInfo.from_bytes(book_xml.encode('utf-8'))
337 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
340 def refresh_dc_cache(self):
343 'dc_cover_image': None,
346 info = self.book_info()
348 update['dc_slug'] = info.url.slug
349 if info.cover_source:
351 image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
355 if info.cover_source == image.get_full_url():
356 update['dc_cover_image'] = image
357 Book.objects.filter(pk=self.pk).update(**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(),
366 Book.objects.filter(pk=self.pk).update(**update)
367 self.refresh_dc_cache()
369 # Materializing & publishing
370 # ==========================
372 def get_current_changes(self, publishable=True):
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.
379 changes = [chunk.publishable() for chunk in self]
381 changes = [chunk.head for chunk in self if chunk.head is not None]
383 raise self.NoTextError('Some chunks have no available text.')
386 def materialize(self, publishable=False, changes=None):
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.
394 changes = self.get_current_changes(publishable)
395 return compile_text(change.materialize() for change in changes)
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
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,
408 def publish(self, user, fake=False, host=None, days=0, beta=False):
410 Publishes a book on behalf of a (local) user.
412 self.assert_publishable()
413 changes = self.get_current_changes(publishable=True)
415 book_xml = self.materialize(changes=changes)
416 data = {"book_xml": book_xml, "days": days}
418 data['gallery_url'] = host + self.gallery_url()
419 apiclient.api_call(user, "books/", data, beta=beta)
422 br = BookPublishRecord.objects.create(book=self, user=user)
424 ChunkPublishRecord.objects.create(book_record=br, change=c)
425 if not self.public and days == 0:
428 if self.public and days > 0:
431 post_publish.send(sender=br)
434 doc = self.wldocument()
435 return doc.latex_dir(cover=True, ilustr_path=self.gallery_path())