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