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