ff3d434ea445eb4c2fd90e990794f44c5d13104f
[redakcja.git] / apps / catalogue / 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 from django.core.urlresolvers import reverse
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _
9
10 from dvcs import models as dvcs_models
11 from catalogue.xml_tools import compile_text
12
13 import logging
14 logger = logging.getLogger("fnp.catalogue")
15
16
17 class Book(models.Model):
18     """ A document edited on the wiki """
19
20     title = models.CharField(_('title'), max_length=255, db_index=True)
21     slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
22     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
23
24     parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
25     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
26     last_published = models.DateTimeField(null=True, editable=False, db_index=True)
27
28     class NoTextError(BaseException):
29         pass
30
31     class Meta:
32         ordering = ['parent_number', 'title']
33         verbose_name = _('book')
34         verbose_name_plural = _('books')
35
36     def __unicode__(self):
37         return self.title
38
39     def get_absolute_url(self):
40         return reverse("catalogue_book", args=[self.slug])
41
42     @classmethod
43     def create(cls, creator=None, text=u'', *args, **kwargs):
44         """
45             >>> Book.create(slug='x', text='abc').materialize()
46             'abc'
47         """
48         instance = cls(*args, **kwargs)
49         instance.save()
50         instance[0].commit(author=creator, text=text)
51         return instance
52
53     def __iter__(self):
54         return iter(self.chunk_set.all())
55
56     def __getitem__(self, chunk):
57         return self.chunk_set.all()[chunk]
58
59     def materialize(self, publishable=True):
60         """ 
61             Get full text of the document compiled from chunks.
62             Takes the current versions of all texts
63             or versions most recently tagged for publishing.
64         """
65         if publishable:
66             changes = [chunk.publishable() for chunk in self]
67         else:
68             changes = [chunk.head for chunk in self]
69         if None in changes:
70             raise self.NoTextError('Some chunks have no available text.')
71         return compile_text(change.materialize() for change in changes)
72
73     def publishable(self):
74         if not len(self):
75             return False
76         for chunk in self:
77             if not chunk.publishable():
78                 return False
79         return True
80
81     def make_chunk_slug(self, proposed):
82         """ 
83             Finds a chunk slug not yet used in the book.
84         """
85         slugs = set(c.slug for c in self)
86         i = 1
87         new_slug = proposed
88         while new_slug in slugs:
89             new_slug = "%s-%d" % (proposed, i)
90             i += 1
91         return new_slug
92
93     def append(self, other):
94         number = self[len(self) - 1].number + 1
95         single = len(other) == 1
96         for chunk in other:
97             # move chunk to new book
98             chunk.book = self
99             chunk.number = number
100
101             # try some title guessing
102             if other.title.startswith(self.title):
103                 other_title_part = other.title[len(self.title):].lstrip(' /')
104             else:
105                 other_title_part = other.title
106
107             if single:
108                 # special treatment for appending one-parters:
109                 # just use the guessed title and original book slug
110                 chunk.comment = other_title_part
111                 if other.slug.startswith(self.slug):
112                     chunk_slug = other.slug[len(self.slug):].lstrip('-_')
113                 else:
114                     chunk_slug = other.slug
115                 chunk.slug = self.make_chunk_slug(chunk_slug)
116             else:
117                 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
118                 chunk.slug = self.make_chunk_slug(chunk.slug)
119             chunk.save()
120             number += 1
121         other.delete()
122
123     @staticmethod
124     def listener_create(sender, instance, created, **kwargs):
125         if created:
126             instance.chunk_set.create(number=1, slug='1')
127
128 models.signals.post_save.connect(Book.listener_create, sender=Book)
129
130
131 class Chunk(dvcs_models.Document):
132     """ An editable chunk of text. Every Book text is divided into chunks. """
133
134     book = models.ForeignKey(Book, editable=False)
135     number = models.IntegerField()
136     slug = models.SlugField()
137     comment = models.CharField(max_length=255, blank=True)
138
139     class Meta:
140         unique_together = [['book', 'number'], ['book', 'slug']]
141         ordering = ['number']
142
143     def __unicode__(self):
144         return "%d-%d: %s" % (self.book_id, self.number, self.comment)
145
146     def get_absolute_url(self):
147         return reverse("wiki_editor", args=[self.book.slug, self.slug])
148
149     @classmethod
150     def get(cls, slug, chunk=None):
151         if chunk is None:
152             return cls.objects.get(book__slug=slug, number=1)
153         else:
154             return cls.objects.get(book__slug=slug, slug=chunk)
155
156     def pretty_name(self, book_length=None):
157         title = self.book.title
158         if self.comment:
159             title += ", %s" % self.comment
160         if book_length > 1:
161             title += " (%d/%d)" % (self.number, book_length)
162         return title
163
164     def split(self, slug, comment='', creator=None):
165         """ Create an empty chunk after this one """
166         self.book.chunk_set.filter(number__gt=self.number).update(
167                 number=models.F('number')+1)
168         new_chunk = self.book.chunk_set.create(number=self.number+1,
169                 creator=creator, slug=slug, comment=comment)
170         return new_chunk
171
172     @staticmethod
173     def listener_saved(sender, instance, created, **kwargs):
174         if instance.book:
175             # save book so that its _list_html is reset
176             instance.book.save()
177
178 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)