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