4dc70173d023cbf6c41ff83d50dc0c3b422b69a3
[redakcja.git] / apps / wiki / models.py
1 # -*- coding: utf-8 -*-
2 #
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.
5 #
6 import itertools
7 import re
8
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
14
15 from dvcs import models as dvcs_models
16 from wiki.xml_tools import compile_text
17
18 import logging
19 logger = logging.getLogger("fnp.wiki")
20
21
22 class Book(models.Model):
23     """ A document edited on the wiki """
24
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)
28
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
32     _list_html = models.TextField(editable=False, null=True)
33
34     class NoTextError(BaseException):
35         pass
36
37     class Meta:
38         ordering = ['parent_number', 'title']
39         verbose_name = _('book')
40         verbose_name_plural = _('books')
41
42     def __unicode__(self):
43         return self.title
44
45     def get_absolute_url(self):
46         return reverse("wiki_book", args=[self.slug])
47
48     def save(self, reset_list_html=True, *args, **kwargs):
49         if reset_list_html:
50             self._list_html = None
51         return super(Book, self).save(*args, **kwargs)
52
53     @classmethod
54     def create(cls, creator=None, text=u'', *args, **kwargs):
55         """
56             >>> Book.create(slug='x', text='abc').materialize()
57             'abc'
58         """
59         instance = cls(*args, **kwargs)
60         instance.save()
61         instance[0].commit(author=creator, text=text)
62         return instance
63
64     def __iter__(self):
65         return iter(self.chunk_set.all())
66
67     def __getitem__(self, chunk):
68         return self.chunk_set.all()[chunk]
69
70     def __len__(self):
71         return self.chunk_set.count()
72
73     def list_html(self):
74         if self._list_html is None:
75             print 'rendering', self.title
76             self._list_html = render_to_string('wiki/document_list_item.html',
77                 {'book': self})
78             self.save(reset_list_html=False)
79         return mark_safe(self._list_html)
80
81     @staticmethod
82     def publish_tag():
83         return dvcs_models.Tag.get('publish')
84
85     def materialize(self, tag=None):
86         """ 
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.
90         """
91         if tag:
92             changes = [chunk.last_tagged(tag) for chunk in self]
93         else:
94             changes = [chunk.head for chunk in self]
95         if None in changes:
96             raise self.NoTextError('Some chunks have no available text.')
97         return compile_text(change.materialize() for change in changes)
98
99     def publishable(self):
100         if not len(self):
101             return False
102         for chunk in self:
103             if not chunk.publishable():
104                 return False
105         return True
106
107     def make_chunk_slug(self, proposed):
108         """ 
109             Finds a chunk slug not yet used in the book.
110         """
111         slugs = set(c.slug for c in self)
112         i = 1
113         new_slug = proposed
114         while new_slug in slugs:
115             new_slug = "%s-%d" % (proposed, i)
116             i += 1
117         return new_slug
118
119     def append(self, other):
120         number = self[len(self) - 1].number + 1
121         single = len(other) == 1
122         for chunk in other:
123             # move chunk to new book
124             chunk.book = self
125             chunk.number = number
126
127             # try some title guessing
128             if other.title.startswith(self.title):
129                 other_title_part = other.title[len(self.title):].lstrip(' /')
130             else:
131                 other_title_part = other.title
132
133             if single:
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('-_')
139                 else:
140                     chunk_slug = other.slug
141                 chunk.slug = self.make_chunk_slug(chunk_slug)
142             else:
143                 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
144                 chunk.slug = self.make_chunk_slug(chunk.slug)
145             chunk.save()
146             number += 1
147         other.delete()
148
149     @staticmethod
150     def listener_create(sender, instance, created, **kwargs):
151         if created:
152             instance.chunk_set.create(number=1, slug='1')
153
154 models.signals.post_save.connect(Book.listener_create, sender=Book)
155
156
157 class Chunk(dvcs_models.Document):
158     """ An editable chunk of text. Every Book text is divided into chunks. """
159
160     book = models.ForeignKey(Book, editable=False)
161     number = models.IntegerField()
162     slug = models.SlugField()
163     comment = models.CharField(max_length=255)
164
165     class Meta:
166         unique_together = [['book', 'number'], ['book', 'slug']]
167         ordering = ['number']
168
169     def __unicode__(self):
170         return "%d-%d: %s" % (self.book_id, self.number, self.comment)
171
172     def get_absolute_url(self):
173         return reverse("wiki_editor", args=[self.book.slug, self.slug])
174
175     @classmethod
176     def get(cls, slug, chunk=None):
177         if chunk is None:
178             return cls.objects.get(book__slug=slug, number=1)
179         else:
180             return cls.objects.get(book__slug=slug, slug=chunk)
181
182     def pretty_name(self):
183         return "%s, %s (%d/%d)" % (self.book.title, self.comment, 
184                 self.number, len(self.book))
185
186     def publishable(self):
187         return self.last_tagged(Book.publish_tag())
188
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)
195         return new_chunk
196
197     @staticmethod
198     def listener_saved(sender, instance, created, **kwargs):
199         if instance.book:
200             # save book so that its _list_html is reset
201             instance.book.save()
202
203 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
204
205
206 class Theme(models.Model):
207     name = models.CharField(_('name'), max_length=50, unique=True)
208
209     class Meta:
210         ordering = ('name',)
211         verbose_name = _('theme')
212         verbose_name_plural = _('themes')
213
214     def __unicode__(self):
215         return self.name
216
217     def __repr__(self):
218         return "Theme(name=%r)" % self.name
219