c3c1369be45ff0464677a746f5a89827c6a072c2
[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.contrib.sites.models import Site
7 from django.db import models, transaction
8 from django.template.loader import render_to_string
9 from django.utils.translation import ugettext_lazy as _
10 from slughifi import slughifi
11
12 import apiclient
13 from catalogue.helpers import cached_in_field
14 from catalogue.models import BookPublishRecord, ChunkPublishRecord
15 from catalogue.signals import post_publish
16 from catalogue.tasks import refresh_instance, book_content_updated
17 from catalogue.xml_tools import compile_text, split_xml
18
19
20 class Book(models.Model):
21     """ A document edited on the wiki """
22
23     title = models.CharField(_('title'), max_length=255, db_index=True)
24     slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
25     public = models.BooleanField(_('public'), default=True, db_index=True)
26     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
27
28     #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
29     parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children", editable=False)
30     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True, editable=False)
31
32     # Cache
33     _short_html = models.TextField(null=True, blank=True, editable=False)
34     _single = models.NullBooleanField(editable=False, db_index=True)
35     _new_publishable = models.NullBooleanField(editable=False)
36     _published = models.NullBooleanField(editable=False)
37     dc_slug = models.CharField(max_length=128, null=True, blank=True, editable=False)
38
39     class NoTextError(BaseException):
40         pass
41
42     class Meta:
43         app_label = 'catalogue'
44         ordering = ['title', 'slug']
45         verbose_name = _('book')
46         verbose_name_plural = _('books')
47
48
49     # Representing
50     # ============
51
52     def __iter__(self):
53         return iter(self.chunk_set.all())
54
55     def __getitem__(self, chunk):
56         return self.chunk_set.all()[chunk]
57
58     def __len__(self):
59         return self.chunk_set.count()
60
61     def __nonzero__(self):
62         """
63             Necessary so that __len__ isn't used for bool evaluation.
64         """
65         return True
66
67     def __unicode__(self):
68         return self.title
69
70     @models.permalink
71     def get_absolute_url(self):
72         return ("catalogue_book", [self.slug])
73
74     def correct_about(self):
75         return "http://%s%s" % (
76             Site.objects.get_current().domain,
77             self.get_absolute_url()
78         )
79
80     # Creating & manipulating
81     # =======================
82
83     def accessible(self, request):
84         return self.public or request.user.is_authenticated()
85
86     @classmethod
87     @transaction.commit_on_success
88     def create(cls, creator, text, *args, **kwargs):
89         b = cls.objects.create(*args, **kwargs)
90         b.chunk_set.all().update(creator=creator)
91         b[0].commit(text, author=creator)
92         return b
93
94     def add(self, *args, **kwargs):
95         """Add a new chunk at the end."""
96         return self.chunk_set.reverse()[0].split(*args, **kwargs)
97
98     @classmethod
99     @transaction.commit_on_success
100     def import_xml_text(cls, text=u'', previous_book=None,
101                 commit_args=None, **kwargs):
102         """Imports a book from XML, splitting it into chunks as necessary."""
103         texts = split_xml(text)
104         if previous_book:
105             instance = previous_book
106         else:
107             instance = cls(**kwargs)
108             instance.save()
109
110         # if there are more parts, set the rest to empty strings
111         book_len = len(instance)
112         for i in range(book_len - len(texts)):
113             texts.append((u'pusta część %d' % (i + 1), u''))
114
115         i = 0
116         for i, (title, text) in enumerate(texts):
117             if not title:
118                 title = u'część %d' % (i + 1)
119
120             slug = slughifi(title)
121
122             if i < book_len:
123                 chunk = instance[i]
124                 chunk.slug = slug[:50]
125                 chunk.title = title[:255]
126                 chunk.save()
127             else:
128                 chunk = instance.add(slug, title)
129
130             chunk.commit(text, **commit_args)
131
132         return instance
133
134     def make_chunk_slug(self, proposed):
135         """ 
136             Finds a chunk slug not yet used in the book.
137         """
138         slugs = set(c.slug for c in self)
139         i = 1
140         new_slug = proposed[:50]
141         while new_slug in slugs:
142             new_slug = "%s_%d" % (proposed[:45], i)
143             i += 1
144         return new_slug
145
146     @transaction.commit_on_success
147     def append(self, other, slugs=None, titles=None):
148         """Add all chunks of another book to self."""
149         assert self != other
150
151         number = self[len(self) - 1].number + 1
152         len_other = len(other)
153         single = len_other == 1
154
155         if slugs is not None:
156             assert len(slugs) == len_other
157         if titles is not None:
158             assert len(titles) == len_other
159             if slugs is None:
160                 slugs = [slughifi(t) for t in titles]
161
162         for i, chunk in enumerate(other):
163             # move chunk to new book
164             chunk.book = self
165             chunk.number = number
166
167             if titles is None:
168                 # try some title guessing
169                 if other.title.startswith(self.title):
170                     other_title_part = other.title[len(self.title):].lstrip(' /')
171                 else:
172                     other_title_part = other.title
173
174                 if single:
175                     # special treatment for appending one-parters:
176                     # just use the guessed title and original book slug
177                     chunk.title = other_title_part
178                     if other.slug.startswith(self.slug):
179                         chunk.slug = other.slug[len(self.slug):].lstrip('-_')
180                     else:
181                         chunk.slug = other.slug
182                 else:
183                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
184             else:
185                 chunk.slug = slugs[i]
186                 chunk.title = titles[i]
187
188             chunk.slug = self.make_chunk_slug(chunk.slug)
189             chunk.save()
190             number += 1
191         assert not other.chunk_set.exists()
192         other.delete()
193
194     @transaction.commit_on_success
195     def prepend_history(self, other):
196         """Prepend history from all the other book's chunks to own."""
197         assert self != other
198
199         for i in range(len(self), len(other)):
200             title = u"pusta część %d" % i
201             chunk = self.add(slughifi(title), title)
202             chunk.commit('')
203
204         for i in range(len(other)):
205             self[i].prepend_history(other[0])
206
207         assert not other.chunk_set.exists()
208         other.delete()
209
210
211     # State & cache
212     # =============
213
214     def last_published(self):
215         try:
216             return self.publish_log.all()[0].timestamp
217         except IndexError:
218             return None
219
220     def assert_publishable(self):
221         assert self.chunk_set.exists(), _('No chunks in the book.')
222         try:
223             changes = self.get_current_changes(publishable=True)
224         except self.NoTextError:
225             raise AssertionError(_('Not all chunks have publishable revisions.'))
226         book_xml = self.materialize(changes=changes)
227
228         from librarian.dcparser import BookInfo
229         from librarian import NoDublinCore, ParseError, ValidationError
230
231         try:
232             bi = BookInfo.from_string(book_xml.encode('utf-8'))
233         except ParseError, e:
234             raise AssertionError(_('Invalid XML') + ': ' + str(e))
235         except NoDublinCore:
236             raise AssertionError(_('No Dublin Core found.'))
237         except ValidationError, e:
238             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
239
240         valid_about = self.correct_about()
241         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
242
243     def hidden(self):
244         return self.slug.startswith('.')
245
246     def is_new_publishable(self):
247         """Checks if book is ready for publishing.
248
249         Returns True if there is a publishable version newer than the one
250         already published.
251
252         """
253         new_publishable = False
254         if not self.chunk_set.exists():
255             return False
256         for chunk in self:
257             change = chunk.publishable()
258             if not change:
259                 return False
260             if not new_publishable and not change.publish_log.exists():
261                 new_publishable = True
262         return new_publishable
263     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
264
265     def is_published(self):
266         return self.publish_log.exists()
267     published = cached_in_field('_published')(is_published)
268
269     def is_single(self):
270         return len(self) == 1
271     single = cached_in_field('_single')(is_single)
272
273     @cached_in_field('_short_html')
274     def short_html(self):
275         return render_to_string('catalogue/book_list/book.html', {'book': self})
276
277     def book_info(self, publishable=True):
278         try:
279             book_xml = self.materialize(publishable=publishable)
280         except self.NoTextError:
281             pass
282         else:
283             from librarian.dcparser import BookInfo
284             from librarian import NoDublinCore, ParseError, ValidationError
285             try:
286                 return BookInfo.from_string(book_xml.encode('utf-8'))
287             except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
288                 return None
289
290     def refresh_dc_cache(self):
291         update = {
292             'dc_slug': None,
293         }
294
295         info = self.book_info()
296         if info is not None:
297             update['dc_slug'] = info.slug
298         Book.objects.filter(pk=self.pk).update(**update)
299
300     def touch(self):
301         # this should only really be done when text or publishable status changes
302         book_content_updated.delay(self)
303
304         update = {
305             "_new_publishable": self.is_new_publishable(),
306             "_published": self.is_published(),
307             "_single": self.is_single(),
308             "_short_html": None,
309         }
310         Book.objects.filter(pk=self.pk).update(**update)
311         refresh_instance(self)
312
313     def refresh(self):
314         """This should be done offline."""
315         self.short_html
316         self.single
317         self.new_publishable
318         self.published
319
320     # Materializing & publishing
321     # ==========================
322
323     def get_current_changes(self, publishable=True):
324         """
325             Returns a list containing one Change for every Chunk in the Book.
326             Takes the most recent revision (publishable, if set).
327             Throws an error, if a proper revision is unavailable for a Chunk.
328         """
329         if publishable:
330             changes = [chunk.publishable() for chunk in self]
331         else:
332             changes = [chunk.head for chunk in self if chunk.head is not None]
333         if None in changes:
334             raise self.NoTextError('Some chunks have no available text.')
335         return changes
336
337     def materialize(self, publishable=False, changes=None):
338         """ 
339             Get full text of the document compiled from chunks.
340             Takes the current versions of all texts
341             or versions most recently tagged for publishing,
342             or a specified iterable changes.
343         """
344         if changes is None:
345             changes = self.get_current_changes(publishable)
346         return compile_text(change.materialize() for change in changes)
347
348     def publish(self, user):
349         """
350             Publishes a book on behalf of a (local) user.
351         """
352         self.assert_publishable()
353         changes = self.get_current_changes(publishable=True)
354         book_xml = self.materialize(changes=changes)
355         apiclient.api_call(user, "books/", {"book_xml": book_xml})
356         # record the publish
357         br = BookPublishRecord.objects.create(book=self, user=user)
358         for c in changes:
359             ChunkPublishRecord.objects.create(book_record=br, change=c)
360         post_publish.send(sender=br)