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