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