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 slughifi import slughifi
13 from catalogue.helpers import cached_in_field
14 from catalogue.models import BookPublishRecord, ChunkPublishRecord
15 from catalogue.signals import post_publish
16 from catalogue.tasks import refresh_instance, book_content_updated
17 from catalogue.xml_tools import compile_text, split_xml
20 class Book(models.Model):
21 """ A document edited on the wiki """
23 title = models.CharField(_('title'), max_length=255, db_index=True)
24 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
25 public = models.BooleanField(_('public'), default=True, db_index=True)
26 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
28 #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
29 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children", editable=False)
30 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True, editable=False)
33 _short_html = models.TextField(null=True, blank=True, editable=False)
34 _single = models.NullBooleanField(editable=False, db_index=True)
35 _new_publishable = models.NullBooleanField(editable=False)
36 _published = models.NullBooleanField(editable=False)
37 _on_track = models.IntegerField(null=True, blank=True, db_index=True, editable=False)
38 dc_slug = models.CharField(max_length=128, null=True, blank=True,
39 editable=False, db_index=True)
41 class NoTextError(BaseException):
45 app_label = 'catalogue'
46 ordering = ['title', 'slug']
47 verbose_name = _('book')
48 verbose_name_plural = _('books')
55 return iter(self.chunk_set.all())
57 def __getitem__(self, chunk):
58 return self.chunk_set.all()[chunk]
61 return self.chunk_set.count()
63 def __nonzero__(self):
65 Necessary so that __len__ isn't used for bool evaluation.
69 def __unicode__(self):
73 def get_absolute_url(self):
74 return ("catalogue_book", [self.slug])
76 def correct_about(self):
77 return "http://%s%s" % (
78 Site.objects.get_current().domain,
79 self.get_absolute_url()
82 # Creating & manipulating
83 # =======================
85 def accessible(self, request):
86 return self.public or request.user.is_authenticated()
89 @transaction.commit_on_success
90 def create(cls, creator, text, *args, **kwargs):
91 b = cls.objects.create(*args, **kwargs)
92 b.chunk_set.all().update(creator=creator)
93 b[0].commit(text, author=creator)
96 def add(self, *args, **kwargs):
97 """Add a new chunk at the end."""
98 return self.chunk_set.reverse()[0].split(*args, **kwargs)
101 @transaction.commit_on_success
102 def import_xml_text(cls, text=u'', previous_book=None,
103 commit_args=None, **kwargs):
104 """Imports a book from XML, splitting it into chunks as necessary."""
105 texts = split_xml(text)
107 instance = previous_book
109 instance = cls(**kwargs)
112 # if there are more parts, set the rest to empty strings
113 book_len = len(instance)
114 for i in range(book_len - len(texts)):
115 texts.append((u'pusta część %d' % (i + 1), u''))
118 for i, (title, text) in enumerate(texts):
120 title = u'część %d' % (i + 1)
122 slug = slughifi(title)
126 chunk.slug = slug[:50]
127 chunk.title = title[:255]
130 chunk = instance.add(slug, title)
132 chunk.commit(text, **commit_args)
136 def make_chunk_slug(self, proposed):
138 Finds a chunk slug not yet used in the book.
140 slugs = set(c.slug for c in self)
142 new_slug = proposed[:50]
143 while new_slug in slugs:
144 new_slug = "%s_%d" % (proposed[:45], i)
148 @transaction.commit_on_success
149 def append(self, other, slugs=None, titles=None):
150 """Add all chunks of another book to self."""
153 number = self[len(self) - 1].number + 1
154 len_other = len(other)
155 single = len_other == 1
157 if slugs is not None:
158 assert len(slugs) == len_other
159 if titles is not None:
160 assert len(titles) == len_other
162 slugs = [slughifi(t) for t in titles]
164 for i, chunk in enumerate(other):
165 # move chunk to new book
167 chunk.number = number
170 # try some title guessing
171 if other.title.startswith(self.title):
172 other_title_part = other.title[len(self.title):].lstrip(' /')
174 other_title_part = other.title
177 # special treatment for appending one-parters:
178 # just use the guessed title and original book slug
179 chunk.title = other_title_part
180 if other.slug.startswith(self.slug):
181 chunk.slug = other.slug[len(self.slug):].lstrip('-_')
183 chunk.slug = other.slug
185 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
187 chunk.slug = slugs[i]
188 chunk.title = titles[i]
190 chunk.slug = self.make_chunk_slug(chunk.slug)
193 assert not other.chunk_set.exists()
196 @transaction.commit_on_success
197 def prepend_history(self, other):
198 """Prepend history from all the other book's chunks to own."""
201 for i in range(len(self), len(other)):
202 title = u"pusta część %d" % i
203 chunk = self.add(slughifi(title), title)
206 for i in range(len(other)):
207 self[i].prepend_history(other[0])
209 assert not other.chunk_set.exists()
213 """Splits all the chunks into separate books."""
216 book = Book.objects.create(title=chunk.title, slug=chunk.slug,
217 public=self.public, gallery=self.gallery)
222 assert not self.chunk_set.exists()
228 def last_published(self):
230 return self.publish_log.all()[0].timestamp
234 def assert_publishable(self):
235 assert self.chunk_set.exists(), _('No chunks in the book.')
237 changes = self.get_current_changes(publishable=True)
238 except self.NoTextError:
239 raise AssertionError(_('Not all chunks have publishable revisions.'))
240 book_xml = self.materialize(changes=changes)
242 from librarian.dcparser import BookInfo
243 from librarian import NoDublinCore, ParseError, ValidationError
246 bi = BookInfo.from_string(book_xml.encode('utf-8'))
247 except ParseError, e:
248 raise AssertionError(_('Invalid XML') + ': ' + str(e))
250 raise AssertionError(_('No Dublin Core found.'))
251 except ValidationError, e:
252 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
254 valid_about = self.correct_about()
255 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
258 return self.slug.startswith('.')
260 def is_new_publishable(self):
261 """Checks if book is ready for publishing.
263 Returns True if there is a publishable version newer than the one
267 new_publishable = False
268 if not self.chunk_set.exists():
271 change = chunk.publishable()
274 if not new_publishable and not change.publish_log.exists():
275 new_publishable = True
276 return new_publishable
277 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
279 def is_published(self):
280 return self.publish_log.exists()
281 published = cached_in_field('_published')(is_published)
283 def get_on_track(self):
286 stages = [ch.stage.ordering if ch.stage is not None else 0
291 on_track = cached_in_field('_on_track')(get_on_track)
294 return len(self) == 1
295 single = cached_in_field('_single')(is_single)
297 @cached_in_field('_short_html')
298 def short_html(self):
299 return render_to_string('catalogue/book_list/book.html', {'book': self})
301 def book_info(self, publishable=True):
303 book_xml = self.materialize(publishable=publishable)
304 except self.NoTextError:
307 from librarian.dcparser import BookInfo
308 from librarian import NoDublinCore, ParseError, ValidationError
310 return BookInfo.from_string(book_xml.encode('utf-8'))
311 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
314 def refresh_dc_cache(self):
319 info = self.book_info()
321 update['dc_slug'] = info.slug
322 Book.objects.filter(pk=self.pk).update(**update)
325 # this should only really be done when text or publishable status changes
326 book_content_updated.delay(self)
329 "_new_publishable": self.is_new_publishable(),
330 "_published": self.is_published(),
331 "_single": self.is_single(),
332 "_on_track": self.get_on_track(),
335 Book.objects.filter(pk=self.pk).update(**update)
336 refresh_instance(self)
339 """This should be done offline."""
345 # Materializing & publishing
346 # ==========================
348 def get_current_changes(self, publishable=True):
350 Returns a list containing one Change for every Chunk in the Book.
351 Takes the most recent revision (publishable, if set).
352 Throws an error, if a proper revision is unavailable for a Chunk.
355 changes = [chunk.publishable() for chunk in self]
357 changes = [chunk.head for chunk in self if chunk.head is not None]
359 raise self.NoTextError('Some chunks have no available text.')
362 def materialize(self, publishable=False, changes=None):
364 Get full text of the document compiled from chunks.
365 Takes the current versions of all texts
366 or versions most recently tagged for publishing,
367 or a specified iterable changes.
370 changes = self.get_current_changes(publishable)
371 return compile_text(change.materialize() for change in changes)
373 def publish(self, user):
375 Publishes a book on behalf of a (local) user.
377 self.assert_publishable()
378 changes = self.get_current_changes(publishable=True)
379 book_xml = self.materialize(changes=changes)
380 apiclient.api_call(user, "books/", {"book_xml": book_xml})
382 br = BookPublishRecord.objects.create(book=self, user=user)
384 ChunkPublishRecord.objects.create(book_record=br, change=c)
385 post_publish.send(sender=br)