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.
9 from django.core.urlresolvers import reverse
10 from django.db import models
11 from django.utils.safestring import mark_safe
12 from django.utils.translation import ugettext_lazy as _
13 from django.template.loader import render_to_string
15 from dvcs import models as dvcs_models
16 from wiki.xml_tools import compile_text
19 logger = logging.getLogger("fnp.wiki")
22 class Book(models.Model):
23 """ A document edited on the wiki """
25 title = models.CharField(_('title'), max_length=255)
26 slug = models.SlugField(_('slug'), max_length=128, unique=True)
27 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
29 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
30 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
32 _list_html = models.TextField(editable=False, null=True)
34 class NoTextError(BaseException):
38 ordering = ['parent_number', 'title']
39 verbose_name = _('book')
40 verbose_name_plural = _('books')
42 def __unicode__(self):
45 def get_absolute_url(self):
46 return reverse("wiki_book", args=[self.slug])
48 def save(self, reset_list_html=True, *args, **kwargs):
50 self._list_html = None
51 return super(Book, self).save(*args, **kwargs)
54 def create(cls, creator=None, text=u'', *args, **kwargs):
56 >>> Book.create(slug='x', text='abc').materialize()
59 instance = cls(*args, **kwargs)
61 instance[0].commit(author=creator, text=text)
65 return iter(self.chunk_set.all())
67 def __getitem__(self, chunk):
68 return self.chunk_set.all()[chunk]
71 return self.chunk_set.count()
74 if self._list_html is None:
75 print 'rendering', self.title
76 self._list_html = render_to_string('wiki/document_list_item.html',
78 self.save(reset_list_html=False)
79 return mark_safe(self._list_html)
83 return dvcs_models.Tag.get('publish')
85 def materialize(self, tag=None):
87 Get full text of the document compiled from chunks.
88 Takes the current versions of all texts
89 or versions most recently tagged by a given tag.
92 changes = [chunk.last_tagged(tag) for chunk in self]
94 changes = [chunk.head for chunk in self]
96 raise self.NoTextError('Some chunks have no available text.')
97 return compile_text(change.materialize() for change in changes)
99 def publishable(self):
103 if not chunk.publishable():
107 def make_chunk_slug(self, proposed):
109 Finds a chunk slug not yet used in the book.
111 slugs = set(c.slug for c in self)
114 while new_slug in slugs:
115 new_slug = "%s-%d" % (proposed, i)
119 def append(self, other):
120 number = self[len(self) - 1].number + 1
121 single = len(other) == 1
123 # move chunk to new book
125 chunk.number = number
127 # try some title guessing
128 if other.title.startswith(self.title):
129 other_title_part = other.title[len(self.title):].lstrip(' /')
131 other_title_part = other.title
134 # special treatment for appending one-parters:
135 # just use the guessed title and original book slug
136 chunk.comment = other_title_part
137 if other.slug.startswith(self.slug):
138 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
140 chunk_slug = other.slug
141 chunk.slug = self.make_chunk_slug(chunk_slug)
143 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
144 chunk.slug = self.make_chunk_slug(chunk.slug)
150 def listener_create(sender, instance, created, **kwargs):
152 instance.chunk_set.create(number=1, slug='1')
154 models.signals.post_save.connect(Book.listener_create, sender=Book)
157 class Chunk(dvcs_models.Document):
158 """ An editable chunk of text. Every Book text is divided into chunks. """
160 book = models.ForeignKey(Book, editable=False)
161 number = models.IntegerField()
162 slug = models.SlugField()
163 comment = models.CharField(max_length=255)
166 unique_together = [['book', 'number'], ['book', 'slug']]
167 ordering = ['number']
169 def __unicode__(self):
170 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
172 def get_absolute_url(self):
173 return reverse("wiki_editor", args=[self.book.slug, self.slug])
176 def get(cls, slug, chunk=None):
178 return cls.objects.get(book__slug=slug, number=1)
180 return cls.objects.get(book__slug=slug, slug=chunk)
182 def pretty_name(self):
183 return "%s, %s (%d/%d)" % (self.book.title, self.comment,
184 self.number, len(self.book))
186 def publishable(self):
187 return self.last_tagged(Book.publish_tag())
189 def split(self, slug, comment='', creator=None):
190 """ Create an empty chunk after this one """
191 self.book.chunk_set.filter(number__gt=self.number).update(
192 number=models.F('number')+1)
193 new_chunk = self.book.chunk_set.create(number=self.number+1,
194 creator=creator, slug=slug, comment=comment)
198 def listener_saved(sender, instance, created, **kwargs):
200 # save book so that its _list_html is reset
203 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
206 class Theme(models.Model):
207 name = models.CharField(_('name'), max_length=50, unique=True)
211 verbose_name = _('theme')
212 verbose_name_plural = _('themes')
214 def __unicode__(self):
218 return "Theme(name=%r)" % self.name