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