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)
31 last_published = models.DateTimeField(null=True, editable=False)
33 _list_html = models.TextField(editable=False, null=True)
35 class NoTextError(BaseException):
39 ordering = ['parent_number', 'title']
40 verbose_name = _('book')
41 verbose_name_plural = _('books')
43 def __unicode__(self):
46 def get_absolute_url(self):
47 return reverse("wiki_book", args=[self.slug])
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)
82 def materialize(self, publishable=True):
84 Get full text of the document compiled from chunks.
85 Takes the current versions of all texts
86 or versions most recently tagged for publishing.
89 changes = [chunk.publishable() for chunk in self]
91 changes = [chunk.head for chunk in self]
93 raise self.NoTextError('Some chunks have no available text.')
94 return compile_text(change.materialize() for change in changes)
96 def publishable(self):
100 if not chunk.publishable():
104 def make_chunk_slug(self, proposed):
106 Finds a chunk slug not yet used in the book.
108 slugs = set(c.slug for c in self)
111 while new_slug in slugs:
112 new_slug = "%s-%d" % (proposed, i)
116 def append(self, other):
117 number = self[len(self) - 1].number + 1
118 single = len(other) == 1
120 # move chunk to new book
122 chunk.number = number
124 # try some title guessing
125 if other.title.startswith(self.title):
126 other_title_part = other.title[len(self.title):].lstrip(' /')
128 other_title_part = other.title
131 # special treatment for appending one-parters:
132 # just use the guessed title and original book slug
133 chunk.comment = other_title_part
134 if other.slug.startswith(self.slug):
135 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
137 chunk_slug = other.slug
138 chunk.slug = self.make_chunk_slug(chunk_slug)
140 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
141 chunk.slug = self.make_chunk_slug(chunk.slug)
147 def listener_create(sender, instance, created, **kwargs):
149 instance.chunk_set.create(number=1, slug='1')
151 models.signals.post_save.connect(Book.listener_create, sender=Book)
154 class Chunk(dvcs_models.Document):
155 """ An editable chunk of text. Every Book text is divided into chunks. """
157 book = models.ForeignKey(Book, editable=False)
158 number = models.IntegerField()
159 slug = models.SlugField()
160 comment = models.CharField(max_length=255, blank=True)
163 unique_together = [['book', 'number'], ['book', 'slug']]
164 ordering = ['number']
166 def __unicode__(self):
167 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
169 def get_absolute_url(self):
170 return reverse("wiki_editor", args=[self.book.slug, self.slug])
173 def get(cls, slug, chunk=None):
175 return cls.objects.get(book__slug=slug, number=1)
177 return cls.objects.get(book__slug=slug, slug=chunk)
179 def pretty_name(self):
180 title = self.book.title
182 title += ", %s" % self.comment
183 count = len(self.book)
185 title += " (%d/%d)" % (self.number, len(self.book))
188 def split(self, slug, comment='', creator=None):
189 """ Create an empty chunk after this one """
190 self.book.chunk_set.filter(number__gt=self.number).update(
191 number=models.F('number')+1)
192 new_chunk = self.book.chunk_set.create(number=self.number+1,
193 creator=creator, slug=slug, comment=comment)
197 _list_html = render_to_string('wiki/chunk_list_item.html',
199 return mark_safe(_list_html)
202 def listener_saved(sender, instance, created, **kwargs):
204 # save book so that its _list_html is reset
207 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
210 class Theme(models.Model):
211 name = models.CharField(_('name'), max_length=50, unique=True)
215 verbose_name = _('theme')
216 verbose_name_plural = _('themes')
218 def __unicode__(self):
222 return "Theme(name=%r)" % self.name