text splitted into chunks,
[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.db import models
10 from django.utils.translation import ugettext_lazy as _
11
12 from dvcs import models as dvcs_models
13
14
15 import logging
16 logger = logging.getLogger("fnp.wiki")
17
18
19 RE_TRIM_BEGIN = re.compile("^<!-- TRIM_BEGIN -->$", re.M)
20 RE_TRIM_END = re.compile("^<!-- TRIM_END -->$", re.M)
21
22
23 class Book(models.Model):
24     """ A document edited on the wiki """
25
26     title = models.CharField(_('title'), max_length=255)
27     slug = models.SlugField(_('slug'), max_length=128, unique=True)
28     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
29
30     parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
31     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
32
33     class Meta:
34         ordering = ['parent_number', 'title']
35         verbose_name = _('book')
36         verbose_name_plural = _('books')
37
38     def __unicode__(self):
39         return self.title
40
41     @classmethod
42     def create(cls, creator=None, text=u'', *args, **kwargs):
43         """
44             >>> Book.create(slug='x', text='abc').materialize()
45             'abc'
46         """
47         instance = cls(*args, **kwargs)
48         instance.save()
49         instance.chunk_set.all()[0].doc.commit(author=creator, text=text)
50         return instance
51
52     @staticmethod
53     def trim(text, trim_begin=True, trim_end=True):
54         """ 
55             Cut off everything before RE_TRIM_BEGIN and after RE_TRIM_END, so
56             that eg. one big XML file can be compiled from many small XML files.
57         """
58         if trim_begin:
59             text = RE_TRIM_BEGIN.split(text, maxsplit=1)[-1]
60         if trim_end:
61             text = RE_TRIM_END.split(text, maxsplit=1)[0]
62         return text
63
64     def materialize(self):
65         """ 
66             Get full text of the document compiled from chunks.
67             Takes the current versions of all texts for now, but it should
68             be possible to specify a tag or a point in time for compiling.
69
70             First non-empty text's beginning isn't trimmed,
71             and last non-empty text's end isn't trimmed.
72         """
73         texts = []
74         trim_begin = False
75         text = ''
76         for chunk in self.chunk_set.all():
77             next_text = chunk.doc.materialize()
78             if not next_text:
79                 continue
80             if text:
81                 # trim the end, because there's more non-empty text
82                 # don't trim beginning, if `text' is the first non-empty part
83                 texts.append(self.trim(text, trim_begin=trim_begin))
84                 trim_begin = True
85             text = next_text
86         # don't trim the end, because there's no more text coming after `text'
87         # only trim beginning if it's not still the first non-empty
88         texts.append(self.trim(text, trim_begin=trim_begin, trim_end=False))
89         return "".join(texts)
90
91     @staticmethod
92     def listener_create(sender, instance, created, **kwargs):
93         if created:
94             instance.chunk_set.create(number=1, slug='1')
95
96 models.signals.post_save.connect(Book.listener_create, sender=Book)
97
98
99 class Chunk(models.Model):
100     """ An editable chunk of text. Every Book text is divided into chunks. """
101
102     book = models.ForeignKey(Book)
103     number = models.IntegerField()
104     slug = models.SlugField()
105     comment = models.CharField(max_length=255)
106     doc = models.ForeignKey(dvcs_models.Document, editable=False, unique=True, null=True)
107
108     class Meta:
109         unique_together = [['book', 'number'], ['book', 'slug']]
110         ordering = ['number']
111
112     def __unicode__(self):
113         return "%d-%d: %s" % (self.book_id, self.number, self.comment)
114
115     def save(self, *args, **kwargs):
116         if self.doc is None:
117             self.doc = dvcs_models.Document.objects.create()
118         super(Chunk, self).save(*args, **kwargs)
119
120     @classmethod
121     def get(cls, slug, chunk=None):
122         if chunk is None:
123             return cls.objects.get(book__slug=slug, number=1)
124         else:
125             return cls.objects.get(book__slug=slug, slug=chunk)
126
127     def pretty_name(self):
128         return "%s, %s (%d/%d)" % (self.book.title, self.comment, 
129                 self.number, self.book.chunk_set.count())
130
131
132
133
134 '''
135 from wiki import settings, constants
136 from slughifi import slughifi
137
138 from django.http import Http404
139
140
141
142
143 class Document(object):
144
145     def add_tag(self, tag, revision, author):
146         """ Add document specific tag """
147         logger.debug("Adding tag %s to doc %s version %d", tag, self.name, revision)
148         self.storage.vstorage.add_page_tag(self.name, revision, tag, user=author)
149
150     @property
151     def plain_text(self):
152         return re.sub(self.META_REGEX, '', self.text, 1)
153
154     def meta(self):
155         result = {}
156
157         m = re.match(self.META_REGEX, self.text)
158         if m:
159             for line in m.group(1).split('\n'):
160                 try:
161                     k, v = line.split(':', 1)
162                     result[k.strip()] = v.strip()
163                 except ValueError:
164                     continue
165
166         gallery = result.get('gallery', slughifi(self.name.replace(' ', '_')))
167
168         if gallery.startswith('/'):
169             gallery = os.path.basename(gallery)
170
171         result['gallery'] = gallery
172         return result
173
174     def info(self):
175         return self.storage.vstorage.page_meta(self.name, self.revision)
176
177
178
179 '''
180 class Theme(models.Model):
181     name = models.CharField(_('name'), max_length=50, unique=True)
182
183     class Meta:
184         ordering = ('name',)
185         verbose_name = _('theme')
186         verbose_name_plural = _('themes')
187
188     def __unicode__(self):
189         return self.name
190
191     def __repr__(self):
192         return "Theme(name=%r)" % self.name
193