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.db import models
7 from django.template.loader import render_to_string
8 from django.utils.translation import ugettext_lazy as _
9 from slughifi import slughifi
10 from catalogue.helpers import cached_in_field
11 from catalogue.models import BookPublishRecord, ChunkPublishRecord
12 from catalogue.signals import post_publish
13 from catalogue.tasks import refresh_instance
14 from catalogue.xml_tools import compile_text, split_xml
17 class Book(models.Model):
18 """ A document edited on the wiki """
20 title = models.CharField(_('title'), max_length=255, db_index=True)
21 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
22 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
24 #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
25 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
26 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
29 _short_html = models.TextField(null=True, blank=True, editable=False)
30 _single = models.NullBooleanField(editable=False, db_index=True)
31 _new_publishable = models.NullBooleanField(editable=False)
32 _published = models.NullBooleanField(editable=False)
35 objects = models.Manager()
37 class NoTextError(BaseException):
41 app_label = 'catalogue'
42 ordering = ['parent_number', 'title']
43 verbose_name = _('book')
44 verbose_name_plural = _('books')
51 return iter(self.chunk_set.all())
53 def __getitem__(self, chunk):
54 return self.chunk_set.all()[chunk]
57 return self.chunk_set.count()
59 def __nonzero__(self):
61 Necessary so that __len__ isn't used for bool evaluation.
65 def __unicode__(self):
69 def get_absolute_url(self):
70 return ("catalogue_book", [self.slug])
73 # Creating & manipulating
74 # =======================
77 def create(cls, creator, text, *args, **kwargs):
78 b = cls.objects.create(*args, **kwargs)
79 b.chunk_set.all().update(creator=creator)
80 b[0].commit(text, author=creator)
83 def add(self, *args, **kwargs):
84 """Add a new chunk at the end."""
85 return self.chunk_set.reverse()[0].split(*args, **kwargs)
88 def import_xml_text(cls, text=u'', previous_book=None,
89 commit_args=None, **kwargs):
90 """Imports a book from XML, splitting it into chunks as necessary."""
91 texts = split_xml(text)
93 instance = previous_book
95 instance = cls(**kwargs)
98 # if there are more parts, set the rest to empty strings
99 book_len = len(instance)
100 for i in range(book_len - len(texts)):
101 texts.append((u'pusta część %d' % (i + 1), u''))
104 for i, (title, text) in enumerate(texts):
106 title = u'część %d' % (i + 1)
108 slug = slughifi(title)
112 chunk.slug = slug[:50]
113 chunk.title = title[:255]
116 chunk = instance.add(slug, title, adjust_slug=True)
118 chunk.commit(text, **commit_args)
122 def make_chunk_slug(self, proposed):
124 Finds a chunk slug not yet used in the book.
126 slugs = set(c.slug for c in self)
129 while new_slug in slugs:
130 new_slug = "%s_%d" % (proposed, i)
134 def append(self, other, slugs=None, titles=None):
135 """Add all chunks of another book to self."""
136 number = self[len(self) - 1].number + 1
137 len_other = len(other)
138 single = len_other == 1
140 if slugs is not None:
141 assert len(slugs) == len_other
142 if titles is not None:
143 assert len(titles) == len_other
145 slugs = [slughifi(t) for t in titles]
147 for i, chunk in enumerate(other):
148 # move chunk to new book
150 chunk.number = number
153 # try some title guessing
154 if other.title.startswith(self.title):
155 other_title_part = other.title[len(self.title):].lstrip(' /')
157 other_title_part = other.title
160 # special treatment for appending one-parters:
161 # just use the guessed title and original book slug
162 chunk.title = other_title_part
163 if other.slug.startswith(self.slug):
164 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
166 chunk_slug = other.slug
167 chunk.slug = self.make_chunk_slug(chunk_slug)
169 chunk.title = "%s, %s" % (other_title_part, chunk.title)
171 chunk.slug = slugs[i]
172 chunk.title = titles[i]
174 chunk.slug = self.make_chunk_slug(chunk.slug)
183 def last_published(self):
185 return self.publish_log.all()[0].timestamp
189 def publishable(self):
190 if not self.chunk_set.exists():
193 if not chunk.publishable():
198 return self.slug.startswith('.')
200 def is_new_publishable(self):
201 """Checks if book is ready for publishing.
203 Returns True if there is a publishable version newer than the one
207 new_publishable = False
208 if not self.chunk_set.exists():
211 change = chunk.publishable()
214 if not new_publishable and not change.publish_log.exists():
215 new_publishable = True
216 return new_publishable
217 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
219 def is_published(self):
220 return self.publish_log.exists()
221 published = cached_in_field('_published')(is_published)
224 return len(self) == 1
225 single = cached_in_field('_single')(is_single)
227 @cached_in_field('_short_html')
228 def short_html(self):
229 return render_to_string('catalogue/book_list/book.html', {'book': self})
233 "_new_publishable": self.is_new_publishable(),
234 "_published": self.is_published(),
235 "_single": self.is_single(),
238 Book.objects.filter(pk=self.pk).update(**update)
239 refresh_instance(self)
242 """This should be done offline."""
248 # Materializing & publishing
249 # ==========================
251 def get_current_changes(self, publishable=True):
253 Returns a list containing one Change for every Chunk in the Book.
254 Takes the most recent revision (publishable, if set).
255 Throws an error, if a proper revision is unavailable for a Chunk.
258 changes = [chunk.publishable() for chunk in self]
260 changes = [chunk.head for chunk in self if chunk.head is not None]
262 raise self.NoTextError('Some chunks have no available text.')
265 def materialize(self, publishable=False, changes=None):
267 Get full text of the document compiled from chunks.
268 Takes the current versions of all texts
269 or versions most recently tagged for publishing,
270 or a specified iterable changes.
273 changes = self.get_current_changes(publishable)
274 return compile_text(change.materialize() for change in changes)
276 def publish(self, user):
278 Publishes a book on behalf of a (local) user.
280 raise NotImplementedError("Publishing not possible yet.")
282 from apiclient import api_call
284 changes = self.get_current_changes(publishable=True)
285 book_xml = self.materialize(changes=changes)
286 #api_call(user, "books", {"book_xml": book_xml})
288 br = BookPublishRecord.objects.create(book=self, user=user)
290 ChunkPublishRecord.objects.create(book_record=br, change=c)
291 post_publish.send(sender=br)