1 # -*- coding: utf-8 -*-
 
   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.
 
   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
 
  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
 
  21 class Book(models.Model):
 
  22     """ A document edited on the wiki """
 
  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)
 
  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)
 
  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)
 
  45     class NoTextError(BaseException):
 
  49         app_label = 'catalogue'
 
  50         ordering = ['title', 'slug']
 
  51         verbose_name = u'moduł'
 
  52         verbose_name_plural = u'moduły'
 
  58         return iter(self.chunk_set.all())
 
  60     def __getitem__(self, chunk):
 
  61         return self.chunk_set.all()[chunk]
 
  64         return self.chunk_set.count()
 
  66     def __nonzero__(self):
 
  68             Necessary so that __len__ isn't used for bool evaluation.
 
  72     def __unicode__(self):
 
  76     def get_absolute_url(self):
 
  77         return "catalogue_book", [self.slug]
 
  79     def correct_about(self):
 
  80         return "http://%s%s" % (
 
  81             Site.objects.get_current().domain,
 
  82             self.get_absolute_url()
 
  85     # Creating & manipulating
 
  86     # =======================
 
  88     def accessible(self, request):
 
  89         return self.public or request.user.is_authenticated()
 
  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)
 
  99     def add(self, *args, **kwargs):
 
 100         """Add a new chunk at the end."""
 
 101         return self.chunk_set.reverse()[0].split(*args, **kwargs)
 
 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)
 
 109             instance = previous_book
 
 111             instance = cls(**kwargs)
 
 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''))
 
 119         for i, (title, text) in enumerate(texts):
 
 121                 title = u'część %d' % (i + 1)
 
 123             slug = slughifi(title)
 
 127                 chunk.slug = slug[:50]
 
 128                 chunk.title = title[:255]
 
 131                 chunk = instance.add(slug, title)
 
 133             chunk.commit(text, **commit_args)
 
 137     def make_chunk_slug(self, proposed):
 
 139             Finds a chunk slug not yet used in the book.
 
 141         slugs = set(c.slug for c in self)
 
 143         new_slug = proposed[:50]
 
 144         while new_slug in slugs:
 
 145             new_slug = "%s_%d" % (proposed[:45], i)
 
 149     @transaction.commit_on_success
 
 150     def append(self, other, slugs=None, titles=None):
 
 151         """Add all chunks of another book to self."""
 
 154         number = self[len(self) - 1].number + 1
 
 155         len_other = len(other)
 
 156         single = len_other == 1
 
 158         if slugs is not None:
 
 159             assert len(slugs) == len_other
 
 160         if titles is not None:
 
 161             assert len(titles) == len_other
 
 163                 slugs = [slughifi(t) for t in titles]
 
 165         for i, chunk in enumerate(other):
 
 166             # move chunk to new book
 
 168             chunk.number = number
 
 171                 # try some title guessing
 
 172                 if other.title.startswith(self.title):
 
 173                     other_title_part = other.title[len(self.title):].lstrip(' /')
 
 175                     other_title_part = other.title
 
 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('-_')
 
 184                         chunk.slug = other.slug
 
 186                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
 
 188                 chunk.slug = slugs[i]
 
 189                 chunk.title = titles[i]
 
 191             chunk.slug = self.make_chunk_slug(chunk.slug)
 
 194         assert not other.chunk_set.exists()
 
 196         gm = GalleryMerger(self.gallery, other.gallery)
 
 197         self.gallery = gm.merge()
 
 199         # and move the gallery starts
 
 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
 
 208     @transaction.commit_on_success
 
 209     def prepend_history(self, other):
 
 210         """Prepend history from all the other book's chunks to own."""
 
 213         for i in range(len(self), len(other)):
 
 214             title = u"pusta część %d" % i
 
 215             chunk = self.add(slughifi(title), title)
 
 218         for i in range(len(other)):
 
 219             self[i].prepend_history(other[0])
 
 221         assert not other.chunk_set.exists()
 
 225         """Splits all the chunks into separate books."""
 
 227             book = Book.objects.create(title=chunk.title, slug=chunk.slug, public=self.public, gallery=self.gallery)
 
 232         assert not self.chunk_set.exists()
 
 238     def last_published(self):
 
 240             return self.publish_log.all()[0].timestamp
 
 244     def assert_publishable(self):
 
 245         assert self.chunk_set.exists(), _('No chunks in the book.')
 
 247             changes = self.get_current_changes(publishable=True)
 
 248         except self.NoTextError:
 
 249             raise AssertionError(_('Not all chunks have publishable revisions.'))
 
 251         from librarian import NoDublinCore, ParseError, ValidationError
 
 254             bi = self.wldocument(changes=changes, strict=True).book_info
 
 255         except ParseError, e:
 
 256             raise AssertionError(_('Invalid XML') + ': ' + unicode(e))
 
 258             raise AssertionError(_('No Dublin Core found.'))
 
 259         except ValidationError, e:
 
 260             raise AssertionError(_('Invalid Dublin Core') + ': ' + unicode(e))
 
 262         valid_about = self.correct_about()
 
 263         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
 
 265     def publishable_error(self):
 
 267             return self.assert_publishable()
 
 268         except AssertionError, e:
 
 272         return self.slug.startswith('.')
 
 274     def is_new_publishable(self):
 
 275         """Checks if book is ready for publishing.
 
 277         Returns True if there is a publishable version newer than the one
 
 281         new_publishable = False
 
 282         if not self.chunk_set.exists():
 
 285             change = chunk.publishable()
 
 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)
 
 293     def is_published(self):
 
 294         return self.publish_log.exists()
 
 295     published = cached_in_field('_published')(is_published)
 
 297     def get_on_track(self):
 
 300         stages = [ch.stage.ordering if ch.stage is not None else 0 for ch in self]
 
 304     on_track = cached_in_field('_on_track')(get_on_track)
 
 307         return len(self) == 1
 
 308     single = cached_in_field('_single')(is_single)
 
 310     @cached_in_field('_short_html')
 
 311     def short_html(self):
 
 312         return render_to_string('catalogue/book_list/book.html', {'book': self})
 
 314     def book_info(self, publishable=True):
 
 316             book_xml = self.materialize(publishable=publishable)
 
 317         except self.NoTextError:
 
 320             from librarian.dcparser import BookInfo
 
 321             from librarian import NoDublinCore, ParseError, ValidationError
 
 323                 return BookInfo.from_string(book_xml.encode('utf-8'))
 
 324             except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
 
 327     def refresh_dc_cache(self):
 
 330             'dc_cover_image': None,
 
 333         info = self.book_info()
 
 335             update['dc_slug'] = info.url.slug
 
 336             if info.cover_source:
 
 338                     image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
 
 339                 except Image.DoesNotExist:
 
 342                     if info.cover_source == image.get_full_url():
 
 343                         update['dc_cover_image'] = image
 
 344         Book.objects.filter(pk=self.pk).update(**update)
 
 347         # this should only really be done when text or publishable status changes
 
 348         book_content_updated.delay(self)
 
 351             "_new_publishable": self.is_new_publishable(),
 
 352             "_published": self.is_published(),
 
 353             "_single": self.is_single(),
 
 354             "_on_track": self.get_on_track(),
 
 357         Book.objects.filter(pk=self.pk).update(**update)
 
 358         refresh_instance(self)
 
 361         """This should be done offline."""
 
 367     # Materializing & publishing
 
 368     # ==========================
 
 370     def get_current_changes(self, publishable=True):
 
 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.
 
 377             changes = [chunk.publishable() for chunk in self]
 
 379             changes = [chunk.head for chunk in self if chunk.head is not None]
 
 381             raise self.NoTextError('Some chunks have no available text.')
 
 384     def materialize(self, publishable=False, changes=None):
 
 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.
 
 392             changes = self.get_current_changes(publishable)
 
 393         return compile_text(change.materialize() for change in changes)
 
 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
 
 399         return WLDocument.from_string(
 
 400                 self.materialize(publishable=publishable, changes=changes),
 
 401                 provider=RedakcjaDocProvider(publishable=publishable),
 
 402                 parse_dublincore=parse_dublincore,
 
 405     def publish(self, user):
 
 407             Publishes a book on behalf of a (local) user.
 
 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})
 
 414         br = BookPublishRecord.objects.create(book=self, user=user)
 
 416             ChunkPublishRecord.objects.create(book_record=br, change=c)
 
 417         post_publish.send(sender=br)