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
 
  12 from catalogue.helpers import cached_in_field
 
  13 from catalogue.models import BookPublishRecord, ChunkPublishRecord
 
  14 from catalogue.tasks import refresh_instance, book_content_updated
 
  15 from catalogue.xml_tools import compile_text, split_xml
 
  18 class Book(models.Model):
 
  19     """ A document edited on the wiki """
 
  21     title = models.CharField(_('title'), max_length=255, db_index=True)
 
  22     slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
 
  23     public = models.BooleanField(_('public'), default=True, db_index=True)
 
  24     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
 
  26     #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
 
  27     parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children", editable=False)
 
  28     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True, editable=False)
 
  31     _short_html = models.TextField(null=True, blank=True, editable=False)
 
  32     _single = models.NullBooleanField(editable=False, db_index=True)
 
  33     _new_publishable = models.NullBooleanField(editable=False)
 
  34     _published = models.NullBooleanField(editable=False)
 
  35     dc_slug = models.CharField(max_length=128, null=True, blank=True,
 
  36             editable=False, db_index=True)
 
  38     class NoTextError(BaseException):
 
  42         app_label = 'catalogue'
 
  43         ordering = ['title', 'slug']
 
  44         verbose_name = _('book')
 
  45         verbose_name_plural = _('books')
 
  52         return iter(self.chunk_set.all())
 
  54     def __getitem__(self, chunk):
 
  55         return self.chunk_set.all()[chunk]
 
  58         return self.chunk_set.count()
 
  60     def __nonzero__(self):
 
  62             Necessary so that __len__ isn't used for bool evaluation.
 
  66     def __unicode__(self):
 
  70     def get_absolute_url(self):
 
  71         return ("catalogue_book", [self.slug])
 
  73     def correct_about(self):
 
  74         return "http://%s%s" % (
 
  75             Site.objects.get_current().domain,
 
  76             self.get_absolute_url()
 
  79     # Creating & manipulating
 
  80     # =======================
 
  82     def accessible(self, request):
 
  83         return self.public or request.user.is_authenticated()
 
  86     @transaction.commit_on_success
 
  87     def create(cls, creator, text, *args, **kwargs):
 
  88         b = cls.objects.create(*args, **kwargs)
 
  89         b.chunk_set.all().update(creator=creator)
 
  90         b[0].commit(text, author=creator)
 
  93     def add(self, *args, **kwargs):
 
  94         """Add a new chunk at the end."""
 
  95         return self.chunk_set.reverse()[0].split(*args, **kwargs)
 
  98     @transaction.commit_on_success
 
  99     def import_xml_text(cls, text=u'', previous_book=None,
 
 100                 commit_args=None, **kwargs):
 
 101         """Imports a book from XML, splitting it into chunks as necessary."""
 
 102         texts = split_xml(text)
 
 104             instance = previous_book
 
 106             instance = cls(**kwargs)
 
 109         # if there are more parts, set the rest to empty strings
 
 110         book_len = len(instance)
 
 111         for i in range(book_len - len(texts)):
 
 112             texts.append((u'pusta część %d' % (i + 1), u''))
 
 115         for i, (title, text) in enumerate(texts):
 
 117                 title = u'część %d' % (i + 1)
 
 119             slug = slughifi(title)
 
 123                 chunk.slug = slug[:50]
 
 124                 chunk.title = title[:255]
 
 127                 chunk = instance.add(slug, title)
 
 129             chunk.commit(text, **commit_args)
 
 133     def make_chunk_slug(self, proposed):
 
 135             Finds a chunk slug not yet used in the book.
 
 137         slugs = set(c.slug for c in self)
 
 139         new_slug = proposed[:50]
 
 140         while new_slug in slugs:
 
 141             new_slug = "%s_%d" % (proposed[:45], i)
 
 145     @transaction.commit_on_success
 
 146     def append(self, other, slugs=None, titles=None):
 
 147         """Add all chunks of another book to self."""
 
 150         number = self[len(self) - 1].number + 1
 
 151         len_other = len(other)
 
 152         single = len_other == 1
 
 154         if slugs is not None:
 
 155             assert len(slugs) == len_other
 
 156         if titles is not None:
 
 157             assert len(titles) == len_other
 
 159                 slugs = [slughifi(t) for t in titles]
 
 161         for i, chunk in enumerate(other):
 
 162             # move chunk to new book
 
 164             chunk.number = number
 
 167                 # try some title guessing
 
 168                 if other.title.startswith(self.title):
 
 169                     other_title_part = other.title[len(self.title):].lstrip(' /')
 
 171                     other_title_part = other.title
 
 174                     # special treatment for appending one-parters:
 
 175                     # just use the guessed title and original book slug
 
 176                     chunk.title = other_title_part
 
 177                     if other.slug.startswith(self.slug):
 
 178                         chunk.slug = other.slug[len(self.slug):].lstrip('-_')
 
 180                         chunk.slug = other.slug
 
 182                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
 
 184                 chunk.slug = slugs[i]
 
 185                 chunk.title = titles[i]
 
 187             chunk.slug = self.make_chunk_slug(chunk.slug)
 
 190         assert not other.chunk_set.exists()
 
 193     @transaction.commit_on_success
 
 194     def prepend_history(self, other):
 
 195         """Prepend history from all the other book's chunks to own."""
 
 198         for i in range(len(self), len(other)):
 
 199             title = u"pusta część %d" % i
 
 200             chunk = self.add(slughifi(title), title)
 
 203         for i in range(len(other)):
 
 204             self[i].prepend_history(other[0])
 
 206         assert not other.chunk_set.exists()
 
 213     def last_published(self):
 
 215             return self.publish_log.all()[0].timestamp
 
 219     def assert_publishable(self):
 
 220         assert self.chunk_set.exists(), _('No chunks in the book.')
 
 222             changes = self.get_current_changes(publishable=True)
 
 223         except self.NoTextError:
 
 224             raise AssertionError(_('Not all chunks have publishable revisions.'))
 
 225         book_xml = self.materialize(changes=changes)
 
 227         from librarian.dcparser import BookInfo
 
 228         from librarian import NoDublinCore, ParseError, ValidationError
 
 231             bi = BookInfo.from_string(book_xml.encode('utf-8'))
 
 232         except ParseError, e:
 
 233             raise AssertionError(_('Invalid XML') + ': ' + str(e))
 
 235             raise AssertionError(_('No Dublin Core found.'))
 
 236         except ValidationError, e:
 
 237             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
 
 239         valid_about = self.correct_about()
 
 240         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
 
 243         return self.slug.startswith('.')
 
 245     def is_new_publishable(self):
 
 246         """Checks if book is ready for publishing.
 
 248         Returns True if there is a publishable version newer than the one
 
 252         new_publishable = False
 
 253         if not self.chunk_set.exists():
 
 256             change = chunk.publishable()
 
 259             if not new_publishable and not change.publish_log.exists():
 
 260                 new_publishable = True
 
 261         return new_publishable
 
 262     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
 
 264     def is_published(self):
 
 265         return self.publish_log.exists()
 
 266     published = cached_in_field('_published')(is_published)
 
 269         return len(self) == 1
 
 270     single = cached_in_field('_single')(is_single)
 
 272     @cached_in_field('_short_html')
 
 273     def short_html(self):
 
 274         return render_to_string('catalogue/book_list/book.html', {'book': self})
 
 276     def book_info(self, publishable=True):
 
 278             book_xml = self.materialize(publishable=publishable)
 
 279         except self.NoTextError:
 
 282             from librarian.dcparser import BookInfo
 
 283             from librarian import NoDublinCore, ParseError, ValidationError
 
 285                 return BookInfo.from_string(book_xml.encode('utf-8'))
 
 286             except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
 
 289     def refresh_dc_cache(self):
 
 294         info = self.book_info()
 
 296             update['dc_slug'] = info.slug
 
 297         Book.objects.filter(pk=self.pk).update(**update)
 
 300         # this should only really be done when text or publishable status changes
 
 301         book_content_updated.delay(self)
 
 304             "_new_publishable": self.is_new_publishable(),
 
 305             "_published": self.is_published(),
 
 306             "_single": self.is_single(),
 
 309         Book.objects.filter(pk=self.pk).update(**update)
 
 310         refresh_instance(self)
 
 313         """This should be done offline."""
 
 319     # Materializing & publishing
 
 320     # ==========================
 
 322     def get_current_changes(self, publishable=True):
 
 324             Returns a list containing one Change for every Chunk in the Book.
 
 325             Takes the most recent revision (publishable, if set).
 
 326             Throws an error, if a proper revision is unavailable for a Chunk.
 
 329             changes = [chunk.publishable() for chunk in self]
 
 331             changes = [chunk.head for chunk in self if chunk.head is not None]
 
 333             raise self.NoTextError('Some chunks have no available text.')
 
 336     def materialize(self, publishable=False, changes=None):
 
 338             Get full text of the document compiled from chunks.
 
 339             Takes the current versions of all texts
 
 340             or versions most recently tagged for publishing,
 
 341             or a specified iterable changes.
 
 344             changes = self.get_current_changes(publishable)
 
 345         return compile_text(change.materialize() for change in changes)
 
 347     def publish(self, user):
 
 349             Publishes a book on behalf of a (local) user.
 
 352         from catalogue.signals import post_publish
 
 354         self.assert_publishable()
 
 355         changes = self.get_current_changes(publishable=True)
 
 356         book_xml = self.materialize(changes=changes)
 
 357         apiclient.api_call(user, "books/", {"book_xml": book_xml})
 
 359         br = BookPublishRecord.objects.create(book=self, user=user)
 
 361             ChunkPublishRecord.objects.create(book_record=br, change=c)
 
 362         post_publish.send(sender=br)