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 public = models.BooleanField(_('public'), default=True, db_index=True)
28 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
30 #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
31 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children", editable=False)
32 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True, editable=False)
35 _short_html = models.TextField(null=True, blank=True, editable=False)
36 _single = models.NullBooleanField(editable=False, db_index=True)
37 _new_publishable = models.NullBooleanField(editable=False)
38 _published = models.NullBooleanField(editable=False)
40 class NoTextError(BaseException):
44 app_label = 'catalogue'
45 ordering = ['title', 'slug']
46 verbose_name = _('book')
47 verbose_name_plural = _('books')
54 return iter(self.chunk_set.all())
56 def __getitem__(self, chunk):
57 return self.chunk_set.all()[chunk]
60 return self.chunk_set.count()
62 def __nonzero__(self):
64 Necessary so that __len__ isn't used for bool evaluation.
68 def __unicode__(self):
72 def get_absolute_url(self):
73 return ("catalogue_book", [self.slug])
76 # Creating & manipulating
77 # =======================
79 def accessible(self, request):
80 return self.public or request.user.is_authenticated()
83 def create(cls, creator, text, *args, **kwargs):
84 b = cls.objects.create(*args, **kwargs)
85 b.chunk_set.all().update(creator=creator)
86 b[0].commit(text, author=creator)
89 def add(self, *args, **kwargs):
90 """Add a new chunk at the end."""
91 return self.chunk_set.reverse()[0].split(*args, **kwargs)
94 def import_xml_text(cls, text=u'', previous_book=None,
95 commit_args=None, **kwargs):
96 """Imports a book from XML, splitting it into chunks as necessary."""
97 texts = split_xml(text)
99 instance = previous_book
101 instance = cls(**kwargs)
104 # if there are more parts, set the rest to empty strings
105 book_len = len(instance)
106 for i in range(book_len - len(texts)):
107 texts.append((u'pusta część %d' % (i + 1), u''))
110 for i, (title, text) in enumerate(texts):
112 title = u'część %d' % (i + 1)
114 slug = slughifi(title)
118 chunk.slug = slug[:50]
119 chunk.title = title[:255]
122 chunk = instance.add(slug, title)
124 chunk.commit(text, **commit_args)
128 def make_chunk_slug(self, proposed):
130 Finds a chunk slug not yet used in the book.
132 slugs = set(c.slug for c in self)
134 new_slug = proposed[:50]
135 while new_slug in slugs:
136 new_slug = "%s_%d" % (proposed[:45], i)
140 def append(self, other, slugs=None, titles=None):
141 """Add all chunks of another book to self."""
144 number = self[len(self) - 1].number + 1
145 len_other = len(other)
146 single = len_other == 1
148 if slugs is not None:
149 assert len(slugs) == len_other
150 if titles is not None:
151 assert len(titles) == len_other
153 slugs = [slughifi(t) for t in titles]
155 for i, chunk in enumerate(other):
156 # move chunk to new book
158 chunk.number = number
161 # try some title guessing
162 if other.title.startswith(self.title):
163 other_title_part = other.title[len(self.title):].lstrip(' /')
165 other_title_part = other.title
168 # special treatment for appending one-parters:
169 # just use the guessed title and original book slug
170 chunk.title = other_title_part
171 if other.slug.startswith(self.slug):
172 chunk.slug = other.slug[len(self.slug):].lstrip('-_')
174 chunk.slug = other.slug
176 chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
178 chunk.slug = slugs[i]
179 chunk.title = titles[i]
181 chunk.slug = self.make_chunk_slug(chunk.slug)
184 assert not other.chunk_set.exists()
191 def last_published(self):
193 return self.publish_log.all()[0].timestamp
197 def assert_publishable(self):
198 assert self.chunk_set.exists(), _('No chunks in the book.')
200 changes = self.get_current_changes(publishable=True)
201 except self.NoTextError:
202 raise AssertionError(_('Not all chunks have publishable revisions.'))
203 book_xml = self.materialize(changes=changes)
206 bi = BookInfo.from_string(book_xml.encode('utf-8'))
207 except ParseError, e:
208 raise AssertionError(_('Invalid XML') + ': ' + str(e))
210 raise AssertionError(_('No Dublin Core found.'))
211 except ValidationError, e:
212 raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
214 valid_about = "http://%s%s" % (Site.objects.get_current().domain, self.get_absolute_url())
215 assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
218 return self.slug.startswith('.')
220 def is_new_publishable(self):
221 """Checks if book is ready for publishing.
223 Returns True if there is a publishable version newer than the one
227 new_publishable = False
228 if not self.chunk_set.exists():
231 change = chunk.publishable()
234 if not new_publishable and not change.publish_log.exists():
235 new_publishable = True
236 return new_publishable
237 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
239 def is_published(self):
240 return self.publish_log.exists()
241 published = cached_in_field('_published')(is_published)
244 return len(self) == 1
245 single = cached_in_field('_single')(is_single)
247 @cached_in_field('_short_html')
248 def short_html(self):
249 return render_to_string('catalogue/book_list/book.html', {'book': self})
253 "_new_publishable": self.is_new_publishable(),
254 "_published": self.is_published(),
255 "_single": self.is_single(),
258 Book.objects.filter(pk=self.pk).update(**update)
259 refresh_instance(self)
262 """This should be done offline."""
268 # Materializing & publishing
269 # ==========================
271 def get_current_changes(self, publishable=True):
273 Returns a list containing one Change for every Chunk in the Book.
274 Takes the most recent revision (publishable, if set).
275 Throws an error, if a proper revision is unavailable for a Chunk.
278 changes = [chunk.publishable() for chunk in self]
280 changes = [chunk.head for chunk in self if chunk.head is not None]
282 raise self.NoTextError('Some chunks have no available text.')
285 def materialize(self, publishable=False, changes=None):
287 Get full text of the document compiled from chunks.
288 Takes the current versions of all texts
289 or versions most recently tagged for publishing,
290 or a specified iterable changes.
293 changes = self.get_current_changes(publishable)
294 return compile_text(change.materialize() for change in changes)
296 def publish(self, user):
298 Publishes a book on behalf of a (local) user.
300 self.assert_publishable()
301 changes = self.get_current_changes(publishable=True)
302 book_xml = self.materialize(changes=changes)
303 apiclient.api_call(user, "books/", {"book_xml": book_xml})
305 br = BookPublishRecord.objects.create(book=self, user=user)
307 ChunkPublishRecord.objects.create(book_record=br, change=c)
308 post_publish.send(sender=br)