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