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