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