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
8 from django.template.loader import render_to_string
9 from django.utils.translation import ugettext_lazy as _
10 from slughifi import slughifi
11 from librarian import NoDublinCore, ParseError, ValidationError
12 from librarian.dcparser import BookInfo
15 from catalogue.helpers import cached_in_field
16 from catalogue.models import BookPublishRecord, ChunkPublishRecord
17 from catalogue.signals import post_publish
18 from catalogue.tasks import refresh_instance
19 from catalogue.xml_tools import compile_text, split_xml
22 class Book(models.Model):
23 """ A document edited on the wiki """
25 title = models.CharField(_('title'), max_length=255, db_index=True)
26 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
27 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
29 #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
30 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children", editable=False)
31 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True, editable=False)
34 _short_html = models.TextField(null=True, blank=True, editable=False)
35 _single = models.NullBooleanField(editable=False, db_index=True)
36 _new_publishable = models.NullBooleanField(editable=False)
37 _published = models.NullBooleanField(editable=False)
40 objects = models.Manager()
42 class NoTextError(BaseException):
46 app_label = 'catalogue'
47 ordering = ['title', 'slug']
48 verbose_name = _('book')
49 verbose_name_plural = _('books')
56 return iter(self.chunk_set.all())
58 def __getitem__(self, chunk):
59 return self.chunk_set.all()[chunk]
62 return self.chunk_set.count()
64 def __nonzero__(self):
66 Necessary so that __len__ isn't used for bool evaluation.
70 def __unicode__(self):
74 def get_absolute_url(self):
75 return ("catalogue_book", [self.slug])
78 # Creating & manipulating
79 # =======================
82 def create(cls, creator, text, *args, **kwargs):
83 b = cls.objects.create(*args, **kwargs)
84 b.chunk_set.all().update(creator=creator)
85 b[0].commit(text, author=creator)
88 def add(self, *args, **kwargs):
89 """Add a new chunk at the end."""
90 return self.chunk_set.reverse()[0].split(*args, **kwargs)
93 def import_xml_text(cls, text=u'', previous_book=None,
94 commit_args=None, **kwargs):
95 """Imports a book from XML, splitting it into chunks as necessary."""
96 texts = split_xml(text)
98 instance = previous_book
100 instance = cls(**kwargs)
103 # if there are more parts, set the rest to empty strings
104 book_len = len(instance)
105 for i in range(book_len - len(texts)):
106 texts.append((u'pusta część %d' % (i + 1), u''))
109 for i, (title, text) in enumerate(texts):
111 title = u'część %d' % (i + 1)
113 slug = slughifi(title)
117 chunk.slug = slug[:50]
118 chunk.title = title[:255]
121 chunk = instance.add(slug, title)
123 chunk.commit(text, **commit_args)
127 def make_chunk_slug(self, proposed):
129 Finds a chunk slug not yet used in the book.
131 slugs = set(c.slug for c in self)
133 new_slug = proposed[:50]
134 while new_slug in slugs:
135 new_slug = "%s_%d" % (proposed[:45], i)
139 def append(self, other, slugs=None, titles=None):
140 """Add all chunks of another book to self."""
143 number = self[len(self) - 1].number + 1
144 len_other = len(other)
145 single = len_other == 1
147 if slugs is not None:
148 assert len(slugs) == len_other
149 if titles is not None:
150 assert len(titles) == len_other
152 slugs = [slughifi(t) for t in titles]
154 for i, chunk in enumerate(other):
155 # move chunk to new book
157 chunk.number = number
160 # try some title guessing
161 if other.title.startswith(self.title):
162 other_title_part = other.title[len(self.title):].lstrip(' /')
164 other_title_part = other.title
167 # special treatment for appending one-parters:
168 # just use the guessed title and original book slug
169 chunk.title = other_title_part
170 if other.slug.startswith(self.slug):
171 chunk.slug = other.slug[len(self.slug):].lstrip('-_')
173 chunk.slug = other.slug
175 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
177 chunk.slug = slugs[i]
178 chunk.title = titles[i]
180 chunk.slug = self.make_chunk_slug(chunk.slug)
183 assert not other.chunk_set.exists()
190 def last_published(self):
192 return self.publish_log.all()[0].timestamp
196 def assert_publishable(self):
197 assert self.chunk_set.exists(), _('No chunks in the book.')
199 changes = self.get_current_changes(publishable=True)
200 except self.NoTextError:
201 raise AssertionError(_('Not all chunks have publishable revisions.'))
202 book_xml = self.materialize(changes=changes)
205 bi = BookInfo.from_string(book_xml.encode('utf-8'))
206 except ParseError, e:
207 raise AssertionError(_('Invalid XML') + ': ' + str(e))
209 raise AssertionError(_('No Dublin Core found.'))
210 except ValidationError, e:
211 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
213 valid_about = "http://%s%s" % (Site.objects.get_current().domain, self.get_absolute_url())
214 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
217 return self.slug.startswith('.')
219 def is_new_publishable(self):
220 """Checks if book is ready for publishing.
222 Returns True if there is a publishable version newer than the one
226 new_publishable = False
227 if not self.chunk_set.exists():
230 change = chunk.publishable()
233 if not new_publishable and not change.publish_log.exists():
234 new_publishable = True
235 return new_publishable
236 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
238 def is_published(self):
239 return self.publish_log.exists()
240 published = cached_in_field('_published')(is_published)
243 return len(self) == 1
244 single = cached_in_field('_single')(is_single)
246 @cached_in_field('_short_html')
247 def short_html(self):
248 return render_to_string('catalogue/book_list/book.html', {'book': self})
252 "_new_publishable": self.is_new_publishable(),
253 "_published": self.is_published(),
254 "_single": self.is_single(),
257 Book.objects.filter(pk=self.pk).update(**update)
258 refresh_instance(self)
261 """This should be done offline."""
267 # Materializing & publishing
268 # ==========================
270 def get_current_changes(self, publishable=True):
272 Returns a list containing one Change for every Chunk in the Book.
273 Takes the most recent revision (publishable, if set).
274 Throws an error, if a proper revision is unavailable for a Chunk.
277 changes = [chunk.publishable() for chunk in self]
279 changes = [chunk.head for chunk in self if chunk.head is not None]
281 raise self.NoTextError('Some chunks have no available text.')
284 def materialize(self, publishable=False, changes=None):
286 Get full text of the document compiled from chunks.
287 Takes the current versions of all texts
288 or versions most recently tagged for publishing,
289 or a specified iterable changes.
292 changes = self.get_current_changes(publishable)
293 return compile_text(change.materialize() for change in changes)
295 def publish(self, user):
297 Publishes a book on behalf of a (local) user.
299 self.assert_publishable()
300 changes = self.get_current_changes(publishable=True)
301 book_xml = self.materialize(changes=changes)
302 apiclient.api_call(user, "books/", {"book_xml": book_xml})
304 br = BookPublishRecord.objects.create(book=self, user=user)
306 ChunkPublishRecord.objects.create(book_record=br, change=c)
307 post_publish.send(sender=br)