changeset tagging in dvcs,
[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
17
18 import logging
19 logger = logging.getLogger("fnp.wiki")
20
21
22 RE_TRIM_BEGIN = re.compile("^<!-- TRIM_BEGIN -->$", re.M)
23 RE_TRIM_END = re.compile("^<!-- TRIM_END -->$", re.M)
24
25
26 class Book(models.Model):
27     """ A document edited on the wiki """
28
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)
32
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)
35
36     _list_html = models.TextField(editable=False, null=True)
37
38     class NoTextError(BaseException):
39         pass
40
41     class Meta:
42         ordering = ['parent_number', 'title']
43         verbose_name = _('book')
44         verbose_name_plural = _('books')
45
46     def __unicode__(self):
47         return self.title
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     @staticmethod
83     def trim(text, trim_begin=True, trim_end=True):
84         """ 
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.
87         """
88         if trim_begin:
89             text = RE_TRIM_BEGIN.split(text, maxsplit=1)[-1]
90         if trim_end:
91             text = RE_TRIM_END.split(text, maxsplit=1)[0]
92         return text
93
94     @staticmethod
95     def publish_tag():
96         return dvcs_models.Tag.get('publish')
97
98     def materialize(self, tag=None):
99         """ 
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.
103
104             First non-empty text's beginning isn't trimmed,
105             and last non-empty text's end isn't trimmed.
106         """
107         if tag:
108             changes = [chunk.last_tagged(tag) for chunk in self]
109         else:
110             changes = [chunk.head for chunk in self]
111         if None in changes:
112             raise self.NoTextError('Some chunks have no available text.')
113         texts = []
114         trim_begin = False
115         text = ''
116         for chunk in changes:
117             next_text = chunk.materialize()
118             if not next_text:
119                 continue
120             if text:
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))
124                 trim_begin = True
125             text = next_text
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)
130
131     def publishable(self):
132         if not len(self):
133             return False
134         for chunk in self:
135             if not chunk.publishable():
136                 return False
137         return True
138
139     @staticmethod
140     def listener_create(sender, instance, created, **kwargs):
141         if created:
142             instance.chunk_set.create(number=1, slug='1')
143
144 models.signals.post_save.connect(Book.listener_create, sender=Book)
145
146
147 class Chunk(dvcs_models.Document):
148     """ An editable chunk of text. Every Book text is divided into chunks. """
149
150     book = models.ForeignKey(Book)
151     number = models.IntegerField()
152     slug = models.SlugField()
153     comment = models.CharField(max_length=255)
154
155     class Meta:
156         unique_together = [['book', 'number'], ['book', 'slug']]
157         ordering = ['number']
158
159     def __unicode__(self):
160         return "%d-%d: %s" % (self.book_id, self.number, self.comment)
161
162     def get_absolute_url(self):
163         return reverse("wiki_editor", args=[self.book.slug, self.slug])
164
165     @classmethod
166     def get(cls, slug, chunk=None):
167         if chunk is None:
168             return cls.objects.get(book__slug=slug, number=1)
169         else:
170             return cls.objects.get(book__slug=slug, slug=chunk)
171
172     def pretty_name(self):
173         return "%s, %s (%d/%d)" % (self.book.title, self.comment, 
174                 self.number, len(self.book))
175
176     def publishable(self):
177         return self.last_tagged(Book.publish_tag())
178
179     @staticmethod
180     def listener_saved(sender, instance, created, **kwargs):
181         if instance.book:
182             # save book so that its _list_html is reset
183             instance.book.save()
184
185 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
186
187
188 class Theme(models.Model):
189     name = models.CharField(_('name'), max_length=50, unique=True)
190
191     class Meta:
192         ordering = ('name',)
193         verbose_name = _('theme')
194         verbose_name_plural = _('themes')
195
196     def __unicode__(self):
197         return self.name
198
199     def __repr__(self):
200         return "Theme(name=%r)" % self.name
201