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.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
14 from catalogue.helpers import cached_in_field, GalleryMerger
15 from catalogue.models import BookPublishRecord, ChunkPublishRecord, Project
16 from catalogue.signals import post_publish
17 from catalogue.xml_tools import compile_text, split_xml
18 from cover.models import Image
23 class Book(models.Model):
24 """ A document edited on the wiki """
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)
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)
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)
46 class NoTextError(BaseException):
50 app_label = 'catalogue'
51 ordering = ['title', 'slug']
52 verbose_name = _('book')
53 verbose_name_plural = _('books')
60 return iter(self.chunk_set.all())
62 def __getitem__(self, chunk):
63 return self.chunk_set.all()[chunk]
66 return self.chunk_set.count()
70 Necessary so that __len__ isn't used for bool evaluation.
77 def get_absolute_url(self):
78 return reverse("catalogue_book", args=[self.slug])
80 def correct_about(self):
81 return "http://%s%s" % (
82 Site.objects.get_current().domain,
83 self.get_absolute_url()
86 def gallery_path(self):
87 return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
89 def gallery_url(self):
90 return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, self.gallery)
92 # Creating & manipulating
93 # =======================
95 def accessible(self, request):
96 return self.public or request.user.is_authenticated
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)
106 def add(self, *args, **kwargs):
107 """Add a new chunk at the end."""
108 return self.chunk_set.reverse()[0].split(*args, **kwargs)
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)
117 instance = previous_book
119 instance = cls(**kwargs)
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''))
128 for i, (title, text) in enumerate(texts):
130 title = u'część %d' % (i + 1)
132 slug = slugify(title)
136 chunk.slug = slug[:50]
137 chunk.title = title[:255]
140 chunk = instance.add(slug, title)
142 chunk.commit(text, **commit_args)
146 def make_chunk_slug(self, proposed):
148 Finds a chunk slug not yet used in the book.
150 slugs = set(c.slug for c in self)
152 new_slug = proposed[:50]
153 while new_slug in slugs:
154 new_slug = "%s_%d" % (proposed[:45], i)
159 def append(self, other, slugs=None, titles=None):
160 """Add all chunks of another book to self."""
163 number = self[len(self) - 1].number + 1
164 len_other = len(other)
165 single = len_other == 1
167 if slugs is not None:
168 assert len(slugs) == len_other
169 if titles is not None:
170 assert len(titles) == len_other
172 slugs = [slugify(t) for t in titles]
174 for i, chunk in enumerate(other):
175 # move chunk to new book
177 chunk.number = number
180 # try some title guessing
181 if other.title.startswith(self.title):
182 other_title_part = other.title[len(self.title):].lstrip(' /')
184 other_title_part = other.title
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('-_')
193 chunk.slug = other.slug
195 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
197 chunk.slug = slugs[i]
198 chunk.title = titles[i]
200 chunk.slug = self.make_chunk_slug(chunk.slug)
203 assert not other.chunk_set.exists()
205 gm = GalleryMerger(self.gallery, other.gallery)
206 self.gallery = gm.merge()
208 # and move the gallery starts
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
219 def prepend_history(self, other):
220 """Prepend history from all the other book's chunks to own."""
223 for i in range(len(self), len(other)):
224 title = u"pusta część %d" % i
225 chunk = self.add(slugify(title), title)
228 for i in range(len(other)):
229 self[i].prepend_history(other[0])
231 assert not other.chunk_set.exists()
235 """Splits all the chunks into separate books."""
238 book = Book.objects.create(title=chunk.title, slug=chunk.slug,
239 public=self.public, gallery=self.gallery)
244 assert not self.chunk_set.exists()
250 def last_published(self):
252 return self.publish_log.all()[0].timestamp
256 def assert_publishable(self):
257 assert self.chunk_set.exists(), _('No chunks in the book.')
259 changes = self.get_current_changes(publishable=True)
260 except self.NoTextError:
261 raise AssertionError(_('Not all chunks have publishable revisions.'))
263 from librarian import NoDublinCore, ParseError, ValidationError
266 bi = self.wldocument(changes=changes, strict=True).book_info
267 except ParseError as e:
268 raise AssertionError(_('Invalid XML') + ': ' + str(e))
270 raise AssertionError(_('No Dublin Core found.'))
271 except ValidationError as e:
272 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
274 valid_about = self.correct_about()
275 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
277 def publishable_error(self):
279 return self.assert_publishable()
280 except AssertionError as e:
286 return self.slug.startswith('.')
288 def is_new_publishable(self):
289 """Checks if book is ready for publishing.
291 Returns True if there is a publishable version newer than the one
295 new_publishable = False
296 if not self.chunk_set.exists():
299 change = chunk.publishable()
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)
307 def is_published(self):
308 return self.publish_log.exists()
309 published = cached_in_field('_published')(is_published)
311 def get_on_track(self):
314 stages = [ch.stage.ordering if ch.stage is not None else 0
319 on_track = cached_in_field('_on_track')(get_on_track)
322 return len(self) == 1
323 single = cached_in_field('_single')(is_single)
325 def book_info(self, publishable=True):
327 book_xml = self.materialize(publishable=publishable)
328 except self.NoTextError:
331 from librarian.dcparser import BookInfo
332 from librarian import NoDublinCore, ParseError, ValidationError
334 return BookInfo.from_bytes(book_xml.encode('utf-8'))
335 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
338 def refresh_dc_cache(self):
341 'dc_cover_image': None,
344 info = self.book_info()
346 update['dc_slug'] = info.url.slug
347 if info.cover_source:
349 image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
353 if info.cover_source == image.get_full_url():
354 update['dc_cover_image'] = image
355 Book.objects.filter(pk=self.pk).update(**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(),
364 Book.objects.filter(pk=self.pk).update(**update)
365 self.refresh_dc_cache()
367 # Materializing & publishing
368 # ==========================
370 def get_current_changes(self, publishable=True):
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.
377 changes = [chunk.publishable() for chunk in self]
379 changes = [chunk.head for chunk in self if chunk.head is not None]
381 raise self.NoTextError('Some chunks have no available text.')
384 def materialize(self, publishable=False, changes=None):
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.
392 changes = self.get_current_changes(publishable)
393 return compile_text(change.materialize() for change in changes)
395 def wldocument(self, publishable=True, changes=None,
396 parse_dublincore=True, strict=False):
397 from catalogue.ebook_utils import RedakcjaDocProvider
398 from librarian.parser import WLDocument
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,
406 def publish(self, user, fake=False, host=None, days=0, beta=False):
408 Publishes a book on behalf of a (local) user.
410 self.assert_publishable()
411 changes = self.get_current_changes(publishable=True)
413 book_xml = self.materialize(changes=changes)
414 data = {"book_xml": book_xml, "days": days}
416 data['gallery_url'] = host + self.gallery_url()
417 apiclient.api_call(user, "books/", data, beta=beta)
420 br = BookPublishRecord.objects.create(book=self, user=user)
422 ChunkPublishRecord.objects.create(book_record=br, change=c)
423 if not self.public and days == 0:
426 if self.public and days > 0:
429 post_publish.send(sender=br)
432 doc = self.wldocument()
433 return doc.latex_dir(cover=True, ilustr_path=self.gallery_path())