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.auth.models import User
7 from django.core.urlresolvers import reverse
8 from django.db import models
9 from django.utils.translation import ugettext_lazy as _
10 from django.db.utils import IntegrityError
12 from slughifi import slughifi
14 from dvcs import models as dvcs_models
15 from catalogue.xml_tools import compile_text, split_xml
18 logger = logging.getLogger("fnp.catalogue")
21 class Book(models.Model):
22 """ A document edited on the wiki """
24 title = models.CharField(_('title'), max_length=255, db_index=True)
25 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
26 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
28 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
29 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
31 class NoTextError(BaseException):
35 ordering = ['parent_number', 'title']
36 verbose_name = _('book')
37 verbose_name_plural = _('books')
38 permissions = [('can_pubmark', 'Can mark for publishing')]
40 def __unicode__(self):
43 def get_absolute_url(self):
44 return reverse("catalogue_book", args=[self.slug])
47 def import_xml_text(cls, text=u'', creator=None, previous_book=None,
50 texts = split_xml(text)
52 instance = previous_book
54 instance = cls(*args, **kwargs)
57 # if there are more parts, set the rest to empty strings
58 book_len = len(instance)
59 for i in range(book_len - len(texts)):
60 texts.append(u'pusta część %d' % (i + 1), u'')
63 for i, (title, text) in enumerate(texts):
65 title = u'część %d' % (i + 1)
67 slug = slughifi(title)
75 chunk = instance.add(slug, title, creator, adjust_slug=True)
77 chunk.commit(text, author=creator)
82 def create(cls, creator=None, text=u'', *args, **kwargs):
84 >>> Book.create(slug='x', text='abc').materialize()
87 instance = cls(*args, **kwargs)
89 instance[0].commit(text, author=creator)
93 return iter(self.chunk_set.all())
95 def __getitem__(self, chunk):
96 return self.chunk_set.all()[chunk]
99 return self.chunk_set.count()
101 def __nonzero__(self):
103 Necessary so that __len__ isn't used for bool evaluation.
107 def get_current_changes(self, publishable=True):
109 Returns a list containing one Change for every Chunk in the Book.
110 Takes the most recent revision (publishable, if set).
111 Throws an error, if a proper revision is unavailable for a Chunk.
114 changes = [chunk.publishable() for chunk in self]
116 changes = [chunk.head for chunk in self if chunk.head is not None]
118 raise self.NoTextError('Some chunks have no available text.')
121 def materialize(self, publishable=False, changes=None):
123 Get full text of the document compiled from chunks.
124 Takes the current versions of all texts
125 or versions most recently tagged for publishing,
126 or a specified iterable changes.
129 changes = self.get_current_changes(publishable)
130 return compile_text(change.materialize() for change in changes)
132 def publishable(self):
133 if not self.chunk_set.exists():
136 if not chunk.publishable():
140 def publish(self, user):
142 Publishes a book on behalf of a (local) user.
144 from apiclient import api_call
146 changes = self.get_current_changes(publishable=True)
147 book_xml = book.materialize(changes=changes)
148 #api_call(user, "books", {"book_xml": book_xml})
150 br = BookPublishRecord.objects.create(book=self, user=user)
152 ChunkPublishRecord.objects.create(book_record=br, change=c)
154 def make_chunk_slug(self, proposed):
156 Finds a chunk slug not yet used in the book.
158 slugs = set(c.slug for c in self)
161 while new_slug in slugs:
162 new_slug = "%s_%d" % (proposed, i)
166 def append(self, other, slugs=None, titles=None):
167 """Add all chunks of another book to self."""
168 number = self[len(self) - 1].number + 1
169 len_other = len(other)
170 single = len_other == 1
172 if slugs is not None:
173 assert len(slugs) == len_other
174 if titles is not None:
175 assert len(titles) == len_other
177 slugs = [slughifi(t) for t in titles]
179 for i, chunk in enumerate(other):
180 # move chunk to new book
182 chunk.number = number
185 # try some title guessing
186 if other.title.startswith(self.title):
187 other_title_part = other.title[len(self.title):].lstrip(' /')
189 other_title_part = other.title
192 # special treatment for appending one-parters:
193 # just use the guessed title and original book slug
194 chunk.title = other_title_part
195 if other.slug.startswith(self.slug):
196 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
198 chunk_slug = other.slug
199 chunk.slug = self.make_chunk_slug(chunk_slug)
201 chunk.title = "%s, %s" % (other_title_part, chunk.title)
203 chunk.slug = slugs[i]
204 chunk.title = titles[i]
206 chunk.slug = self.make_chunk_slug(chunk.slug)
211 def add(self, *args, **kwargs):
212 """Add a new chunk at the end."""
213 return self.chunk_set.reverse()[0].split(*args, **kwargs)
216 def listener_create(sender, instance, created, **kwargs):
218 instance.chunk_set.create(number=1, slug='1')
220 models.signals.post_save.connect(Book.listener_create, sender=Book)
223 class Chunk(dvcs_models.Document):
224 """ An editable chunk of text. Every Book text is divided into chunks. """
226 book = models.ForeignKey(Book, editable=False)
227 number = models.IntegerField()
228 slug = models.SlugField()
229 title = models.CharField(max_length=255, blank=True)
232 unique_together = [['book', 'number'], ['book', 'slug']]
233 ordering = ['number']
235 def __unicode__(self):
236 return "%d:%d: %s" % (self.book_id, self.number, self.title)
238 def get_absolute_url(self):
239 return reverse("wiki_editor", args=[self.book.slug, self.slug])
242 def get(cls, slug, chunk=None):
244 return cls.objects.get(book__slug=slug, number=1)
246 return cls.objects.get(book__slug=slug, slug=chunk)
248 def pretty_name(self, book_length=None):
249 title = self.book.title
251 title += ", %s" % self.title
253 title += " (%d/%d)" % (self.number, book_length)
256 def split(self, slug, title='', creator=None, adjust_slug=False):
257 """ Create an empty chunk after this one """
258 self.book.chunk_set.filter(number__gt=self.number).update(
259 number=models.F('number')+1)
262 new_slug = self.book.make_chunk_slug(slug)
264 new_chunk = self.book.chunk_set.create(number=self.number+1,
265 creator=creator, slug=new_slug, title=title)
266 except IntegrityError:
271 def listener_saved(sender, instance, created, **kwargs):
273 # save book so that its _list_html is reset
276 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
279 class BookPublishRecord(models.Model):
281 A record left after publishing a Book.
284 book = models.ForeignKey(Book)
285 timestamp = models.DateTimeField(auto_now_add=True)
286 user = models.ForeignKey(User)
289 ordering = ['-timestamp']
292 class ChunkPublishRecord(models.Model):
294 BookPublishRecord details for each Chunk.
297 book_record = models.ForeignKey(BookPublishRecord)
298 change = models.ForeignKey(Chunk.change_model)