tests fixes
[redakcja.git] / apps / catalogue / models / book.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.db import models
7 from django.template.loader import render_to_string
8 from django.utils.translation import ugettext_lazy as _
9 from slughifi import slughifi
10 from catalogue.helpers import cached_in_field
11 from catalogue.models import BookPublishRecord, ChunkPublishRecord
12 from catalogue.signals import post_publish
13 from catalogue.tasks import refresh_instance
14 from catalogue.xml_tools import compile_text, split_xml
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     #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
25     parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
26     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
27
28     # Cache
29     _short_html = models.TextField(null=True, blank=True, editable=False)
30     _single = models.NullBooleanField(editable=False, db_index=True)
31     _new_publishable = models.NullBooleanField(editable=False)
32     _published = models.NullBooleanField(editable=False)
33
34     # Managers
35     objects = models.Manager()
36
37     class NoTextError(BaseException):
38         pass
39
40     class Meta:
41         app_label = 'catalogue'
42         ordering = ['parent_number', 'title']
43         verbose_name = _('book')
44         verbose_name_plural = _('books')
45
46
47     # Representing
48     # ============
49
50     def __iter__(self):
51         return iter(self.chunk_set.all())
52
53     def __getitem__(self, chunk):
54         return self.chunk_set.all()[chunk]
55
56     def __len__(self):
57         return self.chunk_set.count()
58
59     def __nonzero__(self):
60         """
61             Necessary so that __len__ isn't used for bool evaluation.
62         """
63         return True
64
65     def __unicode__(self):
66         return self.title
67
68     @models.permalink
69     def get_absolute_url(self):
70         return ("catalogue_book", [self.slug])
71
72
73     # Creating & manipulating
74     # =======================
75
76     @classmethod
77     def create(cls, creator, text, *args, **kwargs):
78         b = cls.objects.create(*args, **kwargs)
79         b.chunk_set.all().update(creator=creator)
80         b[0].commit(text, author=creator)
81         return b
82
83     def add(self, *args, **kwargs):
84         """Add a new chunk at the end."""
85         return self.chunk_set.reverse()[0].split(*args, **kwargs)
86
87     @classmethod
88     def import_xml_text(cls, text=u'', previous_book=None,
89                 commit_args=None, **kwargs):
90         """Imports a book from XML, splitting it into chunks as necessary."""
91         texts = split_xml(text)
92         if previous_book:
93             instance = previous_book
94         else:
95             instance = cls(**kwargs)
96             instance.save()
97
98         # if there are more parts, set the rest to empty strings
99         book_len = len(instance)
100         for i in range(book_len - len(texts)):
101             texts.append((u'pusta część %d' % (i + 1), u''))
102
103         i = 0
104         for i, (title, text) in enumerate(texts):
105             if not title:
106                 title = u'część %d' % (i + 1)
107
108             slug = slughifi(title)
109
110             if i < book_len:
111                 chunk = instance[i]
112                 chunk.slug = slug[:50]
113                 chunk.title = title[:255]
114                 chunk.save()
115             else:
116                 chunk = instance.add(slug, title, adjust_slug=True)
117
118             chunk.commit(text, **commit_args)
119
120         return instance
121
122     def make_chunk_slug(self, proposed):
123         """ 
124             Finds a chunk slug not yet used in the book.
125         """
126         slugs = set(c.slug for c in self)
127         i = 1
128         new_slug = proposed
129         while new_slug in slugs:
130             new_slug = "%s_%d" % (proposed, i)
131             i += 1
132         return new_slug
133
134     def append(self, other, slugs=None, titles=None):
135         """Add all chunks of another book to self."""
136         number = self[len(self) - 1].number + 1
137         len_other = len(other)
138         single = len_other == 1
139
140         if slugs is not None:
141             assert len(slugs) == len_other
142         if titles is not None:
143             assert len(titles) == len_other
144             if slugs is None:
145                 slugs = [slughifi(t) for t in titles]
146
147         for i, chunk in enumerate(other):
148             # move chunk to new book
149             chunk.book = self
150             chunk.number = number
151
152             if titles is None:
153                 # try some title guessing
154                 if other.title.startswith(self.title):
155                     other_title_part = other.title[len(self.title):].lstrip(' /')
156                 else:
157                     other_title_part = other.title
158
159                 if single:
160                     # special treatment for appending one-parters:
161                     # just use the guessed title and original book slug
162                     chunk.title = other_title_part
163                     if other.slug.startswith(self.slug):
164                         chunk_slug = other.slug[len(self.slug):].lstrip('-_')
165                     else:
166                         chunk_slug = other.slug
167                     chunk.slug = self.make_chunk_slug(chunk_slug)
168                 else:
169                     chunk.title = "%s, %s" % (other_title_part, chunk.title)
170             else:
171                 chunk.slug = slugs[i]
172                 chunk.title = titles[i]
173
174             chunk.slug = self.make_chunk_slug(chunk.slug)
175             chunk.save()
176             number += 1
177         other.delete()
178
179
180     # State & cache
181     # =============
182
183     def last_published(self):
184         try:
185             return self.publish_log.all()[0].timestamp
186         except IndexError:
187             return None
188
189     def publishable(self):
190         if not self.chunk_set.exists():
191             return False
192         for chunk in self:
193             if not chunk.publishable():
194                 return False
195         return True
196
197     def hidden(self):
198         return self.slug.startswith('.')
199
200     def is_new_publishable(self):
201         """Checks if book is ready for publishing.
202
203         Returns True if there is a publishable version newer than the one
204         already published.
205
206         """
207         new_publishable = False
208         if not self.chunk_set.exists():
209             return False
210         for chunk in self:
211             change = chunk.publishable()
212             if not change:
213                 return False
214             if not new_publishable and not change.publish_log.exists():
215                 new_publishable = True
216         return new_publishable
217     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
218
219     def is_published(self):
220         return self.publish_log.exists()
221     published = cached_in_field('_published')(is_published)
222
223     def is_single(self):
224         return len(self) == 1
225     single = cached_in_field('_single')(is_single)
226
227     @cached_in_field('_short_html')
228     def short_html(self):
229         return render_to_string('catalogue/book_list/book.html', {'book': self})
230
231     def touch(self):
232         update = {
233             "_new_publishable": self.is_new_publishable(),
234             "_published": self.is_published(),
235             "_single": self.is_single(),
236             "_short_html": None,
237         }
238         Book.objects.filter(pk=self.pk).update(**update)
239         refresh_instance(self)
240
241     def refresh(self):
242         """This should be done offline."""
243         self.short_html
244         self.single
245         self.new_publishable
246         self.published
247
248     # Materializing & publishing
249     # ==========================
250
251     def get_current_changes(self, publishable=True):
252         """
253             Returns a list containing one Change for every Chunk in the Book.
254             Takes the most recent revision (publishable, if set).
255             Throws an error, if a proper revision is unavailable for a Chunk.
256         """
257         if publishable:
258             changes = [chunk.publishable() for chunk in self]
259         else:
260             changes = [chunk.head for chunk in self if chunk.head is not None]
261         if None in changes:
262             raise self.NoTextError('Some chunks have no available text.')
263         return changes
264
265     def materialize(self, publishable=False, changes=None):
266         """ 
267             Get full text of the document compiled from chunks.
268             Takes the current versions of all texts
269             or versions most recently tagged for publishing,
270             or a specified iterable changes.
271         """
272         if changes is None:
273             changes = self.get_current_changes(publishable)
274         return compile_text(change.materialize() for change in changes)
275
276     def publish(self, user):
277         """
278             Publishes a book on behalf of a (local) user.
279         """
280         raise NotImplementedError("Publishing not possible yet.")
281
282         from apiclient import api_call
283
284         changes = self.get_current_changes(publishable=True)
285         book_xml = self.materialize(changes=changes)
286         #api_call(user, "books", {"book_xml": book_xml})
287         # record the publish
288         br = BookPublishRecord.objects.create(book=self, user=user)
289         for c in changes:
290             ChunkPublishRecord.objects.create(book_record=br, change=c)
291         post_publish.send(sender=br)