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,
44 db_index=True, on_delete=models.SET_NULL, editable=False)
45 dc_slug = models.CharField(max_length=128, null=True, blank=True,
46 editable=False, db_index=True)
48 class NoTextError(BaseException):
52 app_label = 'catalogue'
53 ordering = ['title', 'slug']
54 verbose_name = _('book')
55 verbose_name_plural = _('books')
62 return iter(self.chunk_set.all())
64 def __getitem__(self, chunk):
65 return self.chunk_set.all()[chunk]
68 return self.chunk_set.count()
70 def __nonzero__(self):
72 Necessary so that __len__ isn't used for bool evaluation.
76 def __unicode__(self):
80 def get_absolute_url(self):
81 return ("catalogue_book", [self.slug])
83 def correct_about(self):
84 return "http://%s%s" % (
85 Site.objects.get_current().domain,
86 self.get_absolute_url()
89 # Creating & manipulating
90 # =======================
92 def accessible(self, request):
93 return self.public or request.user.is_authenticated()
96 @transaction.commit_on_success
97 def create(cls, creator, text, *args, **kwargs):
98 b = cls.objects.create(*args, **kwargs)
99 b.chunk_set.all().update(creator=creator)
100 b[0].commit(text, author=creator)
103 def add(self, *args, **kwargs):
104 """Add a new chunk at the end."""
105 return self.chunk_set.reverse()[0].split(*args, **kwargs)
108 @transaction.commit_on_success
109 def import_xml_text(cls, text=u'', previous_book=None,
110 commit_args=None, **kwargs):
111 """Imports a book from XML, splitting it into chunks as necessary."""
112 texts = split_xml(text)
114 instance = previous_book
116 instance = cls(**kwargs)
119 # if there are more parts, set the rest to empty strings
120 book_len = len(instance)
121 for i in range(book_len - len(texts)):
122 texts.append((u'pusta część %d' % (i + 1), u''))
125 for i, (title, text) in enumerate(texts):
127 title = u'część %d' % (i + 1)
129 slug = slughifi(title)
133 chunk.slug = slug[:50]
134 chunk.title = title[:255]
137 chunk = instance.add(slug, title)
139 chunk.commit(text, **commit_args)
143 def make_chunk_slug(self, proposed):
145 Finds a chunk slug not yet used in the book.
147 slugs = set(c.slug for c in self)
149 new_slug = proposed[:50]
150 while new_slug in slugs:
151 new_slug = "%s_%d" % (proposed[:45], i)
155 @transaction.commit_on_success
156 def append(self, other, slugs=None, titles=None):
157 """Add all chunks of another book to self."""
160 number = self[len(self) - 1].number + 1
161 len_other = len(other)
162 single = len_other == 1
164 if slugs is not None:
165 assert len(slugs) == len_other
166 if titles is not None:
167 assert len(titles) == len_other
169 slugs = [slughifi(t) for t in titles]
171 for i, chunk in enumerate(other):
172 # move chunk to new book
174 chunk.number = number
177 # try some title guessing
178 if other.title.startswith(self.title):
179 other_title_part = other.title[len(self.title):].lstrip(' /')
181 other_title_part = other.title
184 # special treatment for appending one-parters:
185 # just use the guessed title and original book slug
186 chunk.title = other_title_part
187 if other.slug.startswith(self.slug):
188 chunk.slug = other.slug[len(self.slug):].lstrip('-_')
190 chunk.slug = other.slug
192 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
194 chunk.slug = slugs[i]
195 chunk.title = titles[i]
197 chunk.slug = self.make_chunk_slug(chunk.slug)
200 assert not other.chunk_set.exists()
202 gm = GalleryMerger(self.gallery, other.gallery)
203 self.gallery = gm.merge()
205 # and move the gallery starts
207 for chunk in self[len(self) - len_other:]:
208 old_start = chunk.gallery_start or 1
209 chunk.gallery_start = old_start + gm.dest_size - gm.num_deleted
215 @transaction.commit_on_success
216 def prepend_history(self, other):
217 """Prepend history from all the other book's chunks to own."""
220 for i in range(len(self), len(other)):
221 title = u"pusta część %d" % i
222 chunk = self.add(slughifi(title), title)
225 for i in range(len(other)):
226 self[i].prepend_history(other[0])
228 assert not other.chunk_set.exists()
232 """Splits all the chunks into separate books."""
235 book = Book.objects.create(title=chunk.title, slug=chunk.slug,
236 public=self.public, gallery=self.gallery)
241 assert not self.chunk_set.exists()
247 def last_published(self):
249 return self.publish_log.all()[0].timestamp
253 def assert_publishable(self):
254 assert self.chunk_set.exists(), _('No chunks in the book.')
256 changes = self.get_current_changes(publishable=True)
257 except self.NoTextError:
258 raise AssertionError(_('Not all chunks have publishable revisions.'))
260 from librarian import NoDublinCore, ParseError, ValidationError
263 bi = self.wldocument(changes=changes, strict=True).book_info
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
274 def publishable_error(self):
276 return self.assert_publishable()
277 except AssertionError, e:
283 return self.slug.startswith('.')
285 def is_new_publishable(self):
286 """Checks if book is ready for publishing.
288 Returns True if there is a publishable version newer than the one
292 new_publishable = False
293 if not self.chunk_set.exists():
296 change = chunk.publishable()
299 if not new_publishable and not change.publish_log.exists():
300 new_publishable = True
301 return new_publishable
302 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
304 def is_published(self):
305 return self.publish_log.exists()
306 published = cached_in_field('_published')(is_published)
308 def get_on_track(self):
311 stages = [ch.stage.ordering if ch.stage is not None else 0
316 on_track = cached_in_field('_on_track')(get_on_track)
319 return len(self) == 1
320 single = cached_in_field('_single')(is_single)
322 @cached_in_field('_short_html')
323 def short_html(self):
324 return render_to_string('catalogue/book_list/book.html', {'book': self})
326 def book_info(self, publishable=True):
328 book_xml = self.materialize(publishable=publishable)
329 except self.NoTextError:
332 from librarian.dcparser import BookInfo
333 from librarian import NoDublinCore, ParseError, ValidationError
335 return BookInfo.from_string(book_xml.encode('utf-8'))
336 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
339 def refresh_dc_cache(self):
342 'dc_cover_image': None,
345 info = self.book_info()
347 update['dc_slug'] = info.url.slug
348 if info.cover_source:
350 image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
354 if info.cover_source == image.get_full_url():
355 update['dc_cover_image'] = image
356 Book.objects.filter(pk=self.pk).update(**update)
359 # this should only really be done when text or publishable status changes
360 book_content_updated.delay(self)
363 "_new_publishable": self.is_new_publishable(),
364 "_published": self.is_published(),
365 "_single": self.is_single(),
366 "_on_track": self.get_on_track(),
369 Book.objects.filter(pk=self.pk).update(**update)
370 refresh_instance(self)
373 """This should be done offline."""
379 # Materializing & publishing
380 # ==========================
382 def get_current_changes(self, publishable=True):
384 Returns a list containing one Change for every Chunk in the Book.
385 Takes the most recent revision (publishable, if set).
386 Throws an error, if a proper revision is unavailable for a Chunk.
389 changes = [chunk.publishable() for chunk in self]
391 changes = [chunk.head for chunk in self if chunk.head is not None]
393 raise self.NoTextError('Some chunks have no available text.')
396 def materialize(self, publishable=False, changes=None):
398 Get full text of the document compiled from chunks.
399 Takes the current versions of all texts
400 or versions most recently tagged for publishing,
401 or a specified iterable changes.
404 changes = self.get_current_changes(publishable)
405 return compile_text(change.materialize() for change in changes)
407 def wldocument(self, publishable=True, changes=None,
408 parse_dublincore=True, strict=False):
409 from catalogue.ebook_utils import RedakcjaDocProvider
410 from librarian.parser import WLDocument
412 return WLDocument.from_string(
413 self.materialize(publishable=publishable, changes=changes),
414 provider=RedakcjaDocProvider(publishable=publishable),
415 parse_dublincore=parse_dublincore,
418 def publish(self, user):
420 Publishes a book on behalf of a (local) user.
422 self.assert_publishable()
423 changes = self.get_current_changes(publishable=True)
424 book_xml = self.materialize(changes=changes)
425 apiclient.api_call(user, "books/", {"book_xml": book_xml})
427 br = BookPublishRecord.objects.create(book=self, user=user)
429 ChunkPublishRecord.objects.create(book_record=br, change=c)
430 post_publish.send(sender=br)