teh legendary `Publish' button, oh yeah!
[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     last_published = models.DateTimeField(null=True, editable=False)
32
33     _list_html = models.TextField(editable=False, null=True)
34
35     class NoTextError(BaseException):
36         pass
37
38     class Meta:
39         ordering = ['parent_number', 'title']
40         verbose_name = _('book')
41         verbose_name_plural = _('books')
42
43     def __unicode__(self):
44         return self.title
45
46     def get_absolute_url(self):
47         return reverse("wiki_book", args=[self.slug])
48
49     def save(self, reset_list_html=True, *args, **kwargs):
50         if reset_list_html:
51             self._list_html = None
52         return super(Book, self).save(*args, **kwargs)
53
54     @classmethod
55     def create(cls, creator=None, text=u'', *args, **kwargs):
56         """
57             >>> Book.create(slug='x', text='abc').materialize()
58             'abc'
59         """
60         instance = cls(*args, **kwargs)
61         instance.save()
62         instance[0].commit(author=creator, text=text)
63         return instance
64
65     def __iter__(self):
66         return iter(self.chunk_set.all())
67
68     def __getitem__(self, chunk):
69         return self.chunk_set.all()[chunk]
70
71     def __len__(self):
72         return self.chunk_set.count()
73
74     def list_html(self):
75         if self._list_html is None:
76             print 'rendering', self.title
77             self._list_html = render_to_string('wiki/document_list_item.html',
78                 {'book': self})
79             self.save(reset_list_html=False)
80         return mark_safe(self._list_html)
81
82     def materialize(self, publishable=True):
83         """ 
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.
87         """
88         if publishable:
89             changes = [chunk.publishable() for chunk in self]
90         else:
91             changes = [chunk.head for chunk in self]
92         if None in changes:
93             raise self.NoTextError('Some chunks have no available text.')
94         return compile_text(change.materialize() for change in changes)
95
96     def publishable(self):
97         if not len(self):
98             return False
99         for chunk in self:
100             if not chunk.publishable():
101                 return False
102         return True
103
104     def make_chunk_slug(self, proposed):
105         """ 
106             Finds a chunk slug not yet used in the book.
107         """
108         slugs = set(c.slug for c in self)
109         i = 1
110         new_slug = proposed
111         while new_slug in slugs:
112             new_slug = "%s-%d" % (proposed, i)
113             i += 1
114         return new_slug
115
116     def append(self, other):
117         number = self[len(self) - 1].number + 1
118         single = len(other) == 1
119         for chunk in other:
120             # move chunk to new book
121             chunk.book = self
122             chunk.number = number
123
124             # try some title guessing
125             if other.title.startswith(self.title):
126                 other_title_part = other.title[len(self.title):].lstrip(' /')
127             else:
128                 other_title_part = other.title
129
130             if single:
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('-_')
136                 else:
137                     chunk_slug = other.slug
138                 chunk.slug = self.make_chunk_slug(chunk_slug)
139             else:
140                 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
141                 chunk.slug = self.make_chunk_slug(chunk.slug)
142             chunk.save()
143             number += 1
144         other.delete()
145
146     @staticmethod
147     def listener_create(sender, instance, created, **kwargs):
148         if created:
149             instance.chunk_set.create(number=1, slug='1')
150
151 models.signals.post_save.connect(Book.listener_create, sender=Book)
152
153
154 class Chunk(dvcs_models.Document):
155     """ An editable chunk of text. Every Book text is divided into chunks. """
156
157     book = models.ForeignKey(Book, editable=False)
158     number = models.IntegerField()
159     slug = models.SlugField()
160     comment = models.CharField(max_length=255)
161
162     class Meta:
163         unique_together = [['book', 'number'], ['book', 'slug']]
164         ordering = ['number']
165
166     def __unicode__(self):
167         return "%d-%d: %s" % (self.book_id, self.number, self.comment)
168
169     def get_absolute_url(self):
170         return reverse("wiki_editor", args=[self.book.slug, self.slug])
171
172     @classmethod
173     def get(cls, slug, chunk=None):
174         if chunk is None:
175             return cls.objects.get(book__slug=slug, number=1)
176         else:
177             return cls.objects.get(book__slug=slug, slug=chunk)
178
179     def pretty_name(self):
180         return "%s, %s (%d/%d)" % (self.book.title, self.comment, 
181                 self.number, len(self.book))
182
183     def split(self, slug, comment='', creator=None):
184         """ Create an empty chunk after this one """
185         self.book.chunk_set.filter(number__gt=self.number).update(
186                 number=models.F('number')+1)
187         new_chunk = self.book.chunk_set.create(number=self.number+1,
188                 creator=creator, slug=slug, comment=comment)
189         return new_chunk
190
191     @staticmethod
192     def listener_saved(sender, instance, created, **kwargs):
193         if instance.book:
194             # save book so that its _list_html is reset
195             instance.book.save()
196
197 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
198
199
200 class Theme(models.Model):
201     name = models.CharField(_('name'), max_length=50, unique=True)
202
203     class Meta:
204         ordering = ('name',)
205         verbose_name = _('theme')
206         verbose_name_plural = _('themes')
207
208     def __unicode__(self):
209         return self.name
210
211     def __repr__(self):
212         return "Theme(name=%r)" % self.name
213