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()
216 def last_published(self):
218 return self.publish_log.all()[0].timestamp
222 def assert_publishable(self):
223 assert self.chunk_set.exists(), _('No chunks in the book.')
225 changes = self.get_current_changes(publishable=True)
226 except self.NoTextError:
227 raise AssertionError(_('Not all chunks have publishable revisions.'))
228 book_xml = self.materialize(changes=changes)
230 from librarian.dcparser import BookInfo
231 from librarian import NoDublinCore, ParseError, ValidationError
234 bi = BookInfo.from_string(book_xml.encode('utf-8'))
235 except ParseError, e:
236 raise AssertionError(_('Invalid XML') + ': ' + str(e))
238 raise AssertionError(_('No Dublin Core found.'))
239 except ValidationError, e:
240 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
242 valid_about = self.correct_about()
243 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
246 return self.slug.startswith('.')
248 def is_new_publishable(self):
249 """Checks if book is ready for publishing.
251 Returns True if there is a publishable version newer than the one
255 new_publishable = False
256 if not self.chunk_set.exists():
259 change = chunk.publishable()
262 if not new_publishable and not change.publish_log.exists():
263 new_publishable = True
264 return new_publishable
265 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
267 def is_published(self):
268 return self.publish_log.exists()
269 published = cached_in_field('_published')(is_published)
271 def get_on_track(self):
274 stages = [ch.stage.ordering for ch in self if ch.stage is not None]
278 on_track = cached_in_field('_on_track')(get_on_track)
281 return len(self) == 1
282 single = cached_in_field('_single')(is_single)
284 @cached_in_field('_short_html')
285 def short_html(self):
286 return render_to_string('catalogue/book_list/book.html', {'book': self})
288 def book_info(self, publishable=True):
290 book_xml = self.materialize(publishable=publishable)
291 except self.NoTextError:
294 from librarian.dcparser import BookInfo
295 from librarian import NoDublinCore, ParseError, ValidationError
297 return BookInfo.from_string(book_xml.encode('utf-8'))
298 except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
301 def refresh_dc_cache(self):
306 info = self.book_info()
308 update['dc_slug'] = info.slug
309 Book.objects.filter(pk=self.pk).update(**update)
312 # this should only really be done when text or publishable status changes
313 book_content_updated.delay(self)
316 "_new_publishable": self.is_new_publishable(),
317 "_published": self.is_published(),
318 "_single": self.is_single(),
319 "_on_track": self.get_on_track(),
322 Book.objects.filter(pk=self.pk).update(**update)
323 refresh_instance(self)
326 """This should be done offline."""
332 # Materializing & publishing
333 # ==========================
335 def get_current_changes(self, publishable=True):
337 Returns a list containing one Change for every Chunk in the Book.
338 Takes the most recent revision (publishable, if set).
339 Throws an error, if a proper revision is unavailable for a Chunk.
342 changes = [chunk.publishable() for chunk in self]
344 changes = [chunk.head for chunk in self if chunk.head is not None]
346 raise self.NoTextError('Some chunks have no available text.')
349 def materialize(self, publishable=False, changes=None):
351 Get full text of the document compiled from chunks.
352 Takes the current versions of all texts
353 or versions most recently tagged for publishing,
354 or a specified iterable changes.
357 changes = self.get_current_changes(publishable)
358 return compile_text(change.materialize() for change in changes)
360 def publish(self, user):
362 Publishes a book on behalf of a (local) user.
364 self.assert_publishable()
365 changes = self.get_current_changes(publishable=True)
366 book_xml = self.materialize(changes=changes)
367 apiclient.api_call(user, "books/", {"book_xml": book_xml})
369 br = BookPublishRecord.objects.create(book=self, user=user)
371 ChunkPublishRecord.objects.create(book_record=br, change=c)
372 post_publish.send(sender=br)