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, db_index=True)
26 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=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, db_index=True)
33 class NoTextError(BaseException):
37 ordering = ['parent_number', 'title']
38 verbose_name = _('book')
39 verbose_name_plural = _('books')
41 def __unicode__(self):
44 def get_absolute_url(self):
45 return reverse("wiki_book", args=[self.slug])
48 def create(cls, creator=None, text=u'', *args, **kwargs):
50 >>> Book.create(slug='x', text='abc').materialize()
53 instance = cls(*args, **kwargs)
55 instance[0].commit(author=creator, text=text)
59 return iter(self.chunk_set.all())
61 def __getitem__(self, chunk):
62 return self.chunk_set.all()[chunk]
64 def materialize(self, publishable=True):
66 Get full text of the document compiled from chunks.
67 Takes the current versions of all texts
68 or versions most recently tagged for publishing.
71 changes = [chunk.publishable() for chunk in self]
73 changes = [chunk.head for chunk in self]
75 raise self.NoTextError('Some chunks have no available text.')
76 return compile_text(change.materialize() for change in changes)
78 def publishable(self):
82 if not chunk.publishable():
86 def make_chunk_slug(self, proposed):
88 Finds a chunk slug not yet used in the book.
90 slugs = set(c.slug for c in self)
93 while new_slug in slugs:
94 new_slug = "%s-%d" % (proposed, i)
98 def append(self, other):
99 number = self[len(self) - 1].number + 1
100 single = len(other) == 1
102 # move chunk to new book
104 chunk.number = number
106 # try some title guessing
107 if other.title.startswith(self.title):
108 other_title_part = other.title[len(self.title):].lstrip(' /')
110 other_title_part = other.title
113 # special treatment for appending one-parters:
114 # just use the guessed title and original book slug
115 chunk.comment = other_title_part
116 if other.slug.startswith(self.slug):
117 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
119 chunk_slug = other.slug
120 chunk.slug = self.make_chunk_slug(chunk_slug)
122 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
123 chunk.slug = self.make_chunk_slug(chunk.slug)
129 def listener_create(sender, instance, created, **kwargs):
131 instance.chunk_set.create(number=1, slug='1')
133 models.signals.post_save.connect(Book.listener_create, sender=Book)
136 class Chunk(dvcs_models.Document):
137 """ An editable chunk of text. Every Book text is divided into chunks. """
139 book = models.ForeignKey(Book, editable=False)
140 number = models.IntegerField()
141 slug = models.SlugField()
142 comment = models.CharField(max_length=255, blank=True)
145 unique_together = [['book', 'number'], ['book', 'slug']]
146 ordering = ['number']
148 def __unicode__(self):
149 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
151 def get_absolute_url(self):
152 return reverse("wiki_editor", args=[self.book.slug, self.slug])
155 def get(cls, slug, chunk=None):
157 return cls.objects.get(book__slug=slug, number=1)
159 return cls.objects.get(book__slug=slug, slug=chunk)
161 def pretty_name(self, book_length=None):
162 title = self.book.title
164 title += ", %s" % self.comment
166 title += " (%d/%d)" % (self.number, book_length)
169 def split(self, slug, comment='', creator=None):
170 """ Create an empty chunk after this one """
171 self.book.chunk_set.filter(number__gt=self.number).update(
172 number=models.F('number')+1)
173 new_chunk = self.book.chunk_set.create(number=self.number+1,
174 creator=creator, slug=slug, comment=comment)
178 _list_html = render_to_string('wiki/chunk_list_item.html',
180 return mark_safe(_list_html)
183 def listener_saved(sender, instance, created, **kwargs):
185 # save book so that its _list_html is reset
188 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
191 class Theme(models.Model):
192 name = models.CharField(_('name'), max_length=50, unique=True)
196 verbose_name = _('theme')
197 verbose_name_plural = _('themes')
199 def __unicode__(self):
203 return "Theme(name=%r)" % self.name