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.db import models
10 from django.utils.translation import ugettext_lazy as _
12 from dvcs import models as dvcs_models
16 logger = logging.getLogger("fnp.wiki")
19 RE_TRIM_BEGIN = re.compile("^<!-- TRIM_BEGIN -->$", re.M)
20 RE_TRIM_END = re.compile("^<!-- TRIM_END -->$", re.M)
23 class Book(models.Model):
24 """ A document edited on the wiki """
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)
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)
34 ordering = ['parent_number', 'title']
35 verbose_name = _('book')
36 verbose_name_plural = _('books')
38 def __unicode__(self):
42 def create(cls, creator=None, text=u'', *args, **kwargs):
44 >>> Book.create(slug='x', text='abc').materialize()
47 instance = cls(*args, **kwargs)
49 instance.chunk_set.all()[0].doc.commit(author=creator, text=text)
53 def trim(text, trim_begin=True, trim_end=True):
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.
59 text = RE_TRIM_BEGIN.split(text, maxsplit=1)[-1]
61 text = RE_TRIM_END.split(text, maxsplit=1)[0]
64 def materialize(self):
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.
70 First non-empty text's beginning isn't trimmed,
71 and last non-empty text's end isn't trimmed.
76 for chunk in self.chunk_set.all():
77 next_text = chunk.doc.materialize()
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))
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))
92 def listener_create(sender, instance, created, **kwargs):
94 instance.chunk_set.create(number=1, slug='1')
96 models.signals.post_save.connect(Book.listener_create, sender=Book)
99 class Chunk(models.Model):
100 """ An editable chunk of text. Every Book text is divided into chunks. """
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)
109 unique_together = [['book', 'number'], ['book', 'slug']]
110 ordering = ['number']
112 def __unicode__(self):
113 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
115 def save(self, *args, **kwargs):
117 self.doc = dvcs_models.Document.objects.create()
118 super(Chunk, self).save(*args, **kwargs)
121 def get(cls, slug, chunk=None):
123 return cls.objects.get(book__slug=slug, number=1)
125 return cls.objects.get(book__slug=slug, slug=chunk)
127 def pretty_name(self):
128 return "%s, %s (%d/%d)" % (self.book.title, self.comment,
129 self.number, self.book.chunk_set.count())
135 from wiki import settings, constants
136 from slughifi import slughifi
138 from django.http import Http404
143 class Document(object):
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)
151 def plain_text(self):
152 return re.sub(self.META_REGEX, '', self.text, 1)
157 m = re.match(self.META_REGEX, self.text)
159 for line in m.group(1).split('\n'):
161 k, v = line.split(':', 1)
162 result[k.strip()] = v.strip()
166 gallery = result.get('gallery', slughifi(self.name.replace(' ', '_')))
168 if gallery.startswith('/'):
169 gallery = os.path.basename(gallery)
171 result['gallery'] = gallery
175 return self.storage.vstorage.page_meta(self.name, self.revision)
180 class Theme(models.Model):
181 name = models.CharField(_('name'), max_length=50, unique=True)
185 verbose_name = _('theme')
186 verbose_name_plural = _('themes')
188 def __unicode__(self):
192 return "Theme(name=%r)" % self.name