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
19 logger = logging.getLogger("fnp.wiki")
22 RE_TRIM_BEGIN = re.compile("^<!-- TRIM_BEGIN -->$", re.M)
23 RE_TRIM_END = re.compile("^<!-- TRIM_END -->$", re.M)
26 class Book(models.Model):
27 """ A document edited on the wiki """
29 title = models.CharField(_('title'), max_length=255)
30 slug = models.SlugField(_('slug'), max_length=128, unique=True)
31 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
33 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
34 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
36 _list_html = models.TextField(editable=False, null=True)
38 class NoTextError(BaseException):
42 ordering = ['parent_number', 'title']
43 verbose_name = _('book')
44 verbose_name_plural = _('books')
46 def __unicode__(self):
49 def save(self, reset_list_html=True, *args, **kwargs):
51 self._list_html = None
52 return super(Book, self).save(*args, **kwargs)
55 def create(cls, creator=None, text=u'', *args, **kwargs):
57 >>> Book.create(slug='x', text='abc').materialize()
60 instance = cls(*args, **kwargs)
62 instance[0].commit(author=creator, text=text)
66 return iter(self.chunk_set.all())
68 def __getitem__(self, chunk):
69 return self.chunk_set.all()[chunk]
72 return self.chunk_set.count()
75 if self._list_html is None:
76 print 'rendering', self.title
77 self._list_html = render_to_string('wiki/document_list_item.html',
79 self.save(reset_list_html=False)
80 return mark_safe(self._list_html)
83 def trim(text, trim_begin=True, trim_end=True):
85 Cut off everything before RE_TRIM_BEGIN and after RE_TRIM_END, so
86 that eg. one big XML file can be compiled from many small XML files.
89 text = RE_TRIM_BEGIN.split(text, maxsplit=1)[-1]
91 text = RE_TRIM_END.split(text, maxsplit=1)[0]
96 return dvcs_models.Tag.get('publish')
98 def materialize(self, tag=None):
100 Get full text of the document compiled from chunks.
101 Takes the current versions of all texts for now, but it should
102 be possible to specify a tag or a point in time for compiling.
104 First non-empty text's beginning isn't trimmed,
105 and last non-empty text's end isn't trimmed.
108 changes = [chunk.last_tagged(tag) for chunk in self]
110 changes = [chunk.head for chunk in self]
112 raise self.NoTextError('Some chunks have no available text.')
116 for chunk in changes:
117 next_text = chunk.materialize()
121 # trim the end, because there's more non-empty text
122 # don't trim beginning, if `text' is the first non-empty part
123 texts.append(self.trim(text, trim_begin=trim_begin))
126 # don't trim the end, because there's no more text coming after `text'
127 # only trim beginning if it's not still the first non-empty
128 texts.append(self.trim(text, trim_begin=trim_begin, trim_end=False))
129 return "".join(texts)
131 def publishable(self):
135 if not chunk.publishable():
140 def listener_create(sender, instance, created, **kwargs):
142 instance.chunk_set.create(number=1, slug='1')
144 models.signals.post_save.connect(Book.listener_create, sender=Book)
147 class Chunk(dvcs_models.Document):
148 """ An editable chunk of text. Every Book text is divided into chunks. """
150 book = models.ForeignKey(Book)
151 number = models.IntegerField()
152 slug = models.SlugField()
153 comment = models.CharField(max_length=255)
156 unique_together = [['book', 'number'], ['book', 'slug']]
157 ordering = ['number']
159 def __unicode__(self):
160 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
162 def get_absolute_url(self):
163 return reverse("wiki_editor", args=[self.book.slug, self.slug])
166 def get(cls, slug, chunk=None):
168 return cls.objects.get(book__slug=slug, number=1)
170 return cls.objects.get(book__slug=slug, slug=chunk)
172 def pretty_name(self):
173 return "%s, %s (%d/%d)" % (self.book.title, self.comment,
174 self.number, len(self.book))
176 def publishable(self):
177 return self.last_tagged(Book.publish_tag())
180 def listener_saved(sender, instance, created, **kwargs):
182 # save book so that its _list_html is reset
185 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
188 class Theme(models.Model):
189 name = models.CharField(_('name'), max_length=50, unique=True)
193 verbose_name = _('theme')
194 verbose_name_plural = _('themes')
196 def __unicode__(self):
200 return "Theme(name=%r)" % self.name