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')
45 permissions = [('can_pubmark', 'Can mark for publishing')]
52 return iter(self.chunk_set.all())
54 def __getitem__(self, chunk):
55 return self.chunk_set.all()[chunk]
58 return self.chunk_set.count()
60 def __nonzero__(self):
62 Necessary so that __len__ isn't used for bool evaluation.
66 def __unicode__(self):
70 def get_absolute_url(self):
71 return ("catalogue_book", [self.slug])
74 # Creating & manipulating
75 # =======================
78 def create(cls, creator, text, *args, **kwargs):
79 b = cls.objects.create(*args, **kwargs)
80 b.chunk_set.all().update(creator=creator)
81 b[0].commit(text, author=creator)
84 def add(self, *args, **kwargs):
85 """Add a new chunk at the end."""
86 return self.chunk_set.reverse()[0].split(*args, **kwargs)
89 def import_xml_text(cls, text=u'', previous_book=None,
90 commit_args=None, **kwargs):
91 """Imports a book from XML, splitting it into chunks as necessary."""
92 texts = split_xml(text)
94 instance = previous_book
96 instance = cls(**kwargs)
99 # if there are more parts, set the rest to empty strings
100 book_len = len(instance)
101 for i in range(book_len - len(texts)):
102 texts.append(u'pusta część %d' % (i + 1), u'')
105 for i, (title, text) in enumerate(texts):
107 title = u'część %d' % (i + 1)
109 slug = slughifi(title)
117 chunk = instance.add(slug, title, adjust_slug=True)
119 chunk.commit(text, **commit_args)
123 def make_chunk_slug(self, proposed):
125 Finds a chunk slug not yet used in the book.
127 slugs = set(c.slug for c in self)
130 while new_slug in slugs:
131 new_slug = "%s_%d" % (proposed, i)
135 def append(self, other, slugs=None, titles=None):
136 """Add all chunks of another book to self."""
137 number = self[len(self) - 1].number + 1
138 len_other = len(other)
139 single = len_other == 1
141 if slugs is not None:
142 assert len(slugs) == len_other
143 if titles is not None:
144 assert len(titles) == len_other
146 slugs = [slughifi(t) for t in titles]
148 for i, chunk in enumerate(other):
149 # move chunk to new book
151 chunk.number = number
154 # try some title guessing
155 if other.title.startswith(self.title):
156 other_title_part = other.title[len(self.title):].lstrip(' /')
158 other_title_part = other.title
161 # special treatment for appending one-parters:
162 # just use the guessed title and original book slug
163 chunk.title = other_title_part
164 if other.slug.startswith(self.slug):
165 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
167 chunk_slug = other.slug
168 chunk.slug = self.make_chunk_slug(chunk_slug)
170 chunk.title = "%s, %s" % (other_title_part, chunk.title)
172 chunk.slug = slugs[i]
173 chunk.title = titles[i]
175 chunk.slug = self.make_chunk_slug(chunk.slug)
184 def last_published(self):
186 return self.publish_log.all()[0].timestamp
190 def publishable(self):
191 if not self.chunk_set.exists():
194 if not chunk.publishable():
199 return self.slug.startswith('.')
201 def is_new_publishable(self):
202 """Checks if book is ready for publishing.
204 Returns True if there is a publishable version newer than the one
208 new_publishable = False
209 if not self.chunk_set.exists():
212 change = chunk.publishable()
215 if not new_publishable and not change.publish_log.exists():
216 new_publishable = True
217 return new_publishable
218 new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
220 def is_published(self):
221 return self.publish_log.exists()
222 published = cached_in_field('_published')(is_published)
225 return len(self) == 1
226 single = cached_in_field('_single')(is_single)
228 @cached_in_field('_short_html')
229 def short_html(self):
230 return render_to_string('catalogue/book_list/book.html', {'book': self})
234 "_new_publishable": self.is_new_publishable(),
235 "_published": self.is_published(),
236 "_single": self.is_single(),
239 Book.objects.filter(pk=self.pk).update(**update)
240 refresh_instance(self)
243 """This should be done offline."""
249 # Materializing & publishing
250 # ==========================
252 def get_current_changes(self, publishable=True):
254 Returns a list containing one Change for every Chunk in the Book.
255 Takes the most recent revision (publishable, if set).
256 Throws an error, if a proper revision is unavailable for a Chunk.
259 changes = [chunk.publishable() for chunk in self]
261 changes = [chunk.head for chunk in self if chunk.head is not None]
263 raise self.NoTextError('Some chunks have no available text.')
266 def materialize(self, publishable=False, changes=None):
268 Get full text of the document compiled from chunks.
269 Takes the current versions of all texts
270 or versions most recently tagged for publishing,
271 or a specified iterable changes.
274 changes = self.get_current_changes(publishable)
275 return compile_text(change.materialize() for change in changes)
277 def publish(self, user):
279 Publishes a book on behalf of a (local) user.
281 raise NotImplementedError("Publishing not possible yet.")
283 from apiclient import api_call
285 changes = self.get_current_changes(publishable=True)
286 book_xml = self.materialize(changes=changes)
287 #api_call(user, "books", {"book_xml": book_xml})
289 br = BookPublishRecord.objects.create(book=self, user=user)
291 ChunkPublishRecord.objects.create(book_record=br, change=c)
292 post_publish.send(sender=br)