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 slughifi import slughifi
15 from catalogue.helpers import cached_in_field, GalleryMerger
16 from catalogue.models import BookPublishRecord, ChunkPublishRecord
17 from catalogue.signals import post_publish
18 from catalogue.tasks import refresh_instance, book_content_updated
19 from catalogue.xml_tools import compile_text, split_xml
20 from cover.models import Image
25 class Book(models.Model):
26 """ A document edited on the wiki """
28 title = models.CharField(_('title'), max_length=255, db_index=True)
29 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
30 public = models.BooleanField(_('public'), default=True, db_index=True)
31 gallery = models.CharField(_('scan gallery name'), max_length=255, 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 _short_html = models.TextField(null=True, blank=True, editable=False)
39 _single = models.NullBooleanField(editable=False, db_index=True)
40 _new_publishable = models.NullBooleanField(editable=False)
41 _published = models.NullBooleanField(editable=False)
42 _on_track = models.IntegerField(null=True, blank=True, db_index=True, editable=False)
43 dc_cover_image = models.ForeignKey(Image, blank=True, null=True, db_index=True, on_delete=models.SET_NULL)
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()
69 def __nonzero__(self):
71 Necessary so that __len__ isn't used for bool evaluation.
75 def __unicode__(self):
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 # Creating & manipulating
89 # =======================
91 def accessible(self, request):
92 return self.public or request.user.is_authenticated()
95 @transaction.commit_on_success
96 def create(cls, creator, text, *args, **kwargs):
97 b = cls.objects.create(*args, **kwargs)
98 b.chunk_set.all().update(creator=creator)
99 b[0].commit(text, author=creator)
102 def add(self, *args, **kwargs):
103 """Add a new chunk at the end."""
104 return self.chunk_set.reverse()[0].split(*args, **kwargs)
107 @transaction.commit_on_success
108 def import_xml_text(cls, text=u'', previous_book=None,
109 commit_args=None, **kwargs):
110 """Imports a book from XML, splitting it into chunks as necessary."""
111 texts = split_xml(text)
113 instance = previous_book
115 instance = cls(**kwargs)
118 # if there are more parts, set the rest to empty strings
119 book_len = len(instance)
120 for i in range(book_len - len(texts)):
121 texts.append((u'pusta część %d' % (i + 1), u''))
124 for i, (title, text) in enumerate(texts):
126 title = u'część %d' % (i + 1)
128 slug = slughifi(title)
132 chunk.slug = slug[:50]
133 chunk.title = title[:255]
136 chunk = instance.add(slug, title)
138 chunk.commit(text, **commit_args)
142 def make_chunk_slug(self, proposed):
144 Finds a chunk slug not yet used in the book.
146 slugs = set(c.slug for c in self)
148 new_slug = proposed[:50]
149 while new_slug in slugs:
150 new_slug = "%s_%d" % (proposed[:45], i)
154 @transaction.commit_on_success
155 def append(self, other, slugs=None, titles=None):
156 """Add all chunks of another book to self."""
159 number = self[len(self) - 1].number + 1
160 len_other = len(other)
161 single = len_other == 1
163 if slugs is not None:
164 assert len(slugs) == len_other
165 if titles is not None:
166 assert len(titles) == len_other
168 slugs = [slughifi(t) for t in titles]
170 for i, chunk in enumerate(other):
171 # move chunk to new book
173 chunk.number = number
176 # try some title guessing
177 if other.title.startswith(self.title):
178 other_title_part = other.title[len(self.title):].lstrip(' /')
180 other_title_part = other.title
183 # special treatment for appending one-parters:
184 # just use the guessed title and original book slug
185 chunk.title = other_title_part
186 if other.slug.startswith(self.slug):
187 chunk.slug = other.slug[len(self.slug):].lstrip('-_')
189 chunk.slug = other.slug
191 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
193 chunk.slug = slugs[i]
194 chunk.title = titles[i]
196 chunk.slug = self.make_chunk_slug(chunk.slug)
199 assert not other.chunk_set.exists()
201 gm = GalleryMerger(self.gallery, other.gallery)
202 self.gallery = gm.merge()
204 # and move the gallery starts
206 for chunk in self[len(self) - len_other:]:
207 chunk.gallery_start += gm.dest_size - gm.num_deleted
213 @transaction.commit_on_success
214 def prepend_history(self, other):
215 """Prepend history from all the other book's chunks to own."""
218 for i in range(len(self), len(other)):
219 title = u"pusta część %d" % i
220 chunk = self.add(slughifi(title), title)
223 for i in range(len(other)):
224 self[i].prepend_history(other[0])
226 assert not other.chunk_set.exists()
230 """Splits all the chunks into separate books."""
233 book = Book.objects.create(title=chunk.title, slug=chunk.slug,
234 public=self.public, gallery=self.gallery)
239 assert not self.chunk_set.exists()
245 def last_published(self):
247 return self.publish_log.all()[0].timestamp
251 def assert_publishable(self):
252 assert self.chunk_set.exists(), _('No chunks in the book.')
254 changes = self.get_current_changes(publishable=True)
255 except self.NoTextError:
256 raise AssertionError(_('Not all chunks have publishable revisions.'))
257 book_xml = self.materialize(changes=changes)
259 from librarian.dcparser import BookInfo
260 from librarian import NoDublinCore, ParseError, ValidationError
263 bi = BookInfo.from_string(book_xml.encode('utf-8'), strict=True)
264 except ParseError, e:
265 raise AssertionError(_('Invalid XML') + ': ' + unicode(e))
267 raise AssertionError(_('No Dublin Core found.'))
268 except ValidationError, e:
269 raise AssertionError(_('Invalid Dublin Core') + ': ' + unicode(e))
271 valid_about = self.correct_about()
272 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
275 return self.slug.startswith('.')
277 def is_new_publishable(self):
278 """Checks if book is ready for publishing.
280 Returns True if there is a publishable version newer than the one
284 new_publishable = False
285 if not self.chunk_set.exists():
288 change = chunk.publishable()
291 if not new_publishable and not change.publish_log.exists():
292 new_publishable = True
293 return new_publishable
294 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
296 def is_published(self):
297 return self.publish_log.exists()
298 published = cached_in_field('_published')(is_published)
300 def get_on_track(self):
303 stages = [ch.stage.ordering if ch.stage is not None else 0
308 on_track = cached_in_field('_on_track')(get_on_track)
311 return len(self) == 1
312 single = cached_in_field('_single')(is_single)
314 @cached_in_field('_short_html')
315 def short_html(self):
316 return render_to_string('catalogue/book_list/book.html', {'book': self})
318 def book_info(self, publishable=True):
320 book_xml = self.materialize(publishable=publishable)
321 except self.NoTextError:
324 from librarian.dcparser import BookInfo
325 from librarian import NoDublinCore, ParseError, ValidationError
327 return BookInfo.from_string(book_xml.encode('utf-8'))
328 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
331 def refresh_dc_cache(self):
334 'dc_cover_image': None,
337 info = self.book_info()
339 update['dc_slug'] = info.url.slug
340 if info.cover_source:
342 image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
346 if info.cover_source == image.get_absolute_url():
347 update['dc_cover_image'] = image
348 Book.objects.filter(pk=self.pk).update(**update)
351 # this should only really be done when text or publishable status changes
352 book_content_updated.delay(self)
355 "_new_publishable": self.is_new_publishable(),
356 "_published": self.is_published(),
357 "_single": self.is_single(),
358 "_on_track": self.get_on_track(),
361 Book.objects.filter(pk=self.pk).update(**update)
362 refresh_instance(self)
365 """This should be done offline."""
371 # Materializing & publishing
372 # ==========================
374 def get_current_changes(self, publishable=True):
376 Returns a list containing one Change for every Chunk in the Book.
377 Takes the most recent revision (publishable, if set).
378 Throws an error, if a proper revision is unavailable for a Chunk.
381 changes = [chunk.publishable() for chunk in self]
383 changes = [chunk.head for chunk in self if chunk.head is not None]
385 raise self.NoTextError('Some chunks have no available text.')
388 def materialize(self, publishable=False, changes=None):
390 Get full text of the document compiled from chunks.
391 Takes the current versions of all texts
392 or versions most recently tagged for publishing,
393 or a specified iterable changes.
396 changes = self.get_current_changes(publishable)
397 return compile_text(change.materialize() for change in changes)
399 def wldocument(self, publishable=True, changes=None, parse_dublincore=True):
400 from catalogue.ebook_utils import RedakcjaDocProvider
401 from librarian.parser import WLDocument
403 return WLDocument.from_string(
404 self.materialize(publishable=publishable, changes=changes),
405 provider=RedakcjaDocProvider(publishable=publishable),
406 parse_dublincore=parse_dublincore)
408 def publish(self, user):
410 Publishes a book on behalf of a (local) user.
412 self.assert_publishable()
413 changes = self.get_current_changes(publishable=True)
414 book_xml = self.materialize(changes=changes)
415 apiclient.api_call(user, "books/", {"book_xml": book_xml})
417 br = BookPublishRecord.objects.create(book=self, user=user)
419 ChunkPublishRecord.objects.create(book_record=br, change=c)
420 post_publish.send(sender=br)