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.core.urlresolvers import reverse
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _
10 from dvcs import models as dvcs_models
11 from catalogue.xml_tools import compile_text
14 logger = logging.getLogger("fnp.catalogue")
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 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
25 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
26 last_published = models.DateTimeField(null=True, editable=False, db_index=True)
28 class NoTextError(BaseException):
32 ordering = ['parent_number', 'title']
33 verbose_name = _('book')
34 verbose_name_plural = _('books')
36 def __unicode__(self):
39 def get_absolute_url(self):
40 return reverse("catalogue_book", args=[self.slug])
43 def create(cls, creator=None, text=u'', *args, **kwargs):
45 >>> Book.create(slug='x', text='abc').materialize()
48 instance = cls(*args, **kwargs)
50 instance[0].commit(author=creator, text=text)
54 return iter(self.chunk_set.all())
56 def __getitem__(self, chunk):
57 return self.chunk_set.all()[chunk]
59 def materialize(self, publishable=True):
61 Get full text of the document compiled from chunks.
62 Takes the current versions of all texts
63 or versions most recently tagged for publishing.
66 changes = [chunk.publishable() for chunk in self]
68 changes = [chunk.head for chunk in self]
70 raise self.NoTextError('Some chunks have no available text.')
71 return compile_text(change.materialize() for change in changes)
73 def publishable(self):
77 if not chunk.publishable():
81 def make_chunk_slug(self, proposed):
83 Finds a chunk slug not yet used in the book.
85 slugs = set(c.slug for c in self)
88 while new_slug in slugs:
89 new_slug = "%s-%d" % (proposed, i)
93 def append(self, other):
94 number = self[len(self) - 1].number + 1
95 single = len(other) == 1
97 # move chunk to new book
101 # try some title guessing
102 if other.title.startswith(self.title):
103 other_title_part = other.title[len(self.title):].lstrip(' /')
105 other_title_part = other.title
108 # special treatment for appending one-parters:
109 # just use the guessed title and original book slug
110 chunk.comment = other_title_part
111 if other.slug.startswith(self.slug):
112 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
114 chunk_slug = other.slug
115 chunk.slug = self.make_chunk_slug(chunk_slug)
117 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
118 chunk.slug = self.make_chunk_slug(chunk.slug)
124 def listener_create(sender, instance, created, **kwargs):
126 instance.chunk_set.create(number=1, slug='1')
128 models.signals.post_save.connect(Book.listener_create, sender=Book)
131 class Chunk(dvcs_models.Document):
132 """ An editable chunk of text. Every Book text is divided into chunks. """
134 book = models.ForeignKey(Book, editable=False)
135 number = models.IntegerField()
136 slug = models.SlugField()
137 comment = models.CharField(max_length=255, blank=True)
140 unique_together = [['book', 'number'], ['book', 'slug']]
141 ordering = ['number']
143 def __unicode__(self):
144 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
146 def get_absolute_url(self):
147 return reverse("wiki_editor", args=[self.book.slug, self.slug])
150 def get(cls, slug, chunk=None):
152 return cls.objects.get(book__slug=slug, number=1)
154 return cls.objects.get(book__slug=slug, slug=chunk)
156 def pretty_name(self, book_length=None):
157 title = self.book.title
159 title += ", %s" % self.comment
161 title += " (%d/%d)" % (self.number, book_length)
164 def split(self, slug, comment='', creator=None):
165 """ Create an empty chunk after this one """
166 self.book.chunk_set.filter(number__gt=self.number).update(
167 number=models.F('number')+1)
168 new_chunk = self.book.chunk_set.create(number=self.number+1,
169 creator=creator, slug=slug, comment=comment)
173 def listener_saved(sender, instance, created, **kwargs):
175 # save book so that its _list_html is reset
178 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)