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 django.conf import settings
 
  11 from slugify import slugify
 
  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
 
  25 class Book(models.Model):
 
  26     """ A document edited on the wiki """
 
  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)
 
  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)
 
  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)
 
  49     class NoTextError(BaseException):
 
  53         app_label = 'catalogue'
 
  54         ordering = ['title', 'slug']
 
  55         verbose_name = _('book')
 
  56         verbose_name_plural = _('books')
 
  63         return iter(self.chunk_set.all())
 
  65     def __getitem__(self, chunk):
 
  66         return self.chunk_set.all()[chunk]
 
  69         return self.chunk_set.count()
 
  71     def __nonzero__(self):
 
  73             Necessary so that __len__ isn't used for bool evaluation.
 
  77     def __unicode__(self):
 
  81     def get_absolute_url(self):
 
  82         return ("catalogue_book", [self.slug])
 
  84     def correct_about(self):
 
  85         return "http://%s%s" % (
 
  86             Site.objects.get_current().domain,
 
  87             self.get_absolute_url()
 
  90     def gallery_path(self):
 
  91         return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
 
  93     def gallery_url(self):
 
  94         return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, self.gallery)
 
  96     # Creating & manipulating
 
  97     # =======================
 
  99     def accessible(self, request):
 
 100         return self.public or request.user.is_authenticated()
 
 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)
 
 110     def add(self, *args, **kwargs):
 
 111         """Add a new chunk at the end."""
 
 112         return self.chunk_set.reverse()[0].split(*args, **kwargs)
 
 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)
 
 121             instance = previous_book
 
 123             instance = cls(**kwargs)
 
 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''))
 
 132         for i, (title, text) in enumerate(texts):
 
 134                 title = u'część %d' % (i + 1)
 
 136             slug = slugify(title)
 
 140                 chunk.slug = slug[:50]
 
 141                 chunk.title = title[:255]
 
 144                 chunk = instance.add(slug, title)
 
 146             chunk.commit(text, **commit_args)
 
 150     def make_chunk_slug(self, proposed):
 
 152             Finds a chunk slug not yet used in the book.
 
 154         slugs = set(c.slug for c in self)
 
 156         new_slug = proposed[:50]
 
 157         while new_slug in slugs:
 
 158             new_slug = "%s_%d" % (proposed[:45], i)
 
 163     def append(self, other, slugs=None, titles=None):
 
 164         """Add all chunks of another book to self."""
 
 167         number = self[len(self) - 1].number + 1
 
 168         len_other = len(other)
 
 169         single = len_other == 1
 
 171         if slugs is not None:
 
 172             assert len(slugs) == len_other
 
 173         if titles is not None:
 
 174             assert len(titles) == len_other
 
 176                 slugs = [slugify(t) for t in titles]
 
 178         for i, chunk in enumerate(other):
 
 179             # move chunk to new book
 
 181             chunk.number = number
 
 184                 # try some title guessing
 
 185                 if other.title.startswith(self.title):
 
 186                     other_title_part = other.title[len(self.title):].lstrip(' /')
 
 188                     other_title_part = other.title
 
 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('-_')
 
 197                         chunk.slug = other.slug
 
 199                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
 
 201                 chunk.slug = slugs[i]
 
 202                 chunk.title = titles[i]
 
 204             chunk.slug = self.make_chunk_slug(chunk.slug)
 
 207         assert not other.chunk_set.exists()
 
 209         gm = GalleryMerger(self.gallery, other.gallery)
 
 210         self.gallery = gm.merge()
 
 212         # and move the gallery starts
 
 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
 
 223     def prepend_history(self, other):
 
 224         """Prepend history from all the other book's chunks to own."""
 
 227         for i in range(len(self), len(other)):
 
 228             title = u"pusta część %d" % i
 
 229             chunk = self.add(slugify(title), title)
 
 232         for i in range(len(other)):
 
 233             self[i].prepend_history(other[0])
 
 235         assert not other.chunk_set.exists()
 
 239         """Splits all the chunks into separate books."""
 
 242             book = Book.objects.create(title=chunk.title, slug=chunk.slug,
 
 243                     public=self.public, gallery=self.gallery)
 
 248         assert not self.chunk_set.exists()
 
 254     def last_published(self):
 
 256             return self.publish_log.all()[0].timestamp
 
 260     def assert_publishable(self):
 
 261         assert self.chunk_set.exists(), _('No chunks in the book.')
 
 263             changes = self.get_current_changes(publishable=True)
 
 264         except self.NoTextError:
 
 265             raise AssertionError(_('Not all chunks have publishable revisions.'))
 
 267         from librarian import NoDublinCore, ParseError, ValidationError
 
 270             bi = self.wldocument(changes=changes, strict=True).book_info
 
 271         except ParseError, e:
 
 272             raise AssertionError(_('Invalid XML') + ': ' + unicode(e))
 
 274             raise AssertionError(_('No Dublin Core found.'))
 
 275         except ValidationError, e:
 
 276             raise AssertionError(_('Invalid Dublin Core') + ': ' + unicode(e))
 
 278         valid_about = self.correct_about()
 
 279         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
 
 281     def publishable_error(self):
 
 283             return self.assert_publishable()
 
 284         except AssertionError, e:
 
 290         return self.slug.startswith('.')
 
 292     def is_new_publishable(self):
 
 293         """Checks if book is ready for publishing.
 
 295         Returns True if there is a publishable version newer than the one
 
 299         new_publishable = False
 
 300         if not self.chunk_set.exists():
 
 303             change = chunk.publishable()
 
 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)
 
 311     def is_published(self):
 
 312         return self.publish_log.exists()
 
 313     published = cached_in_field('_published')(is_published)
 
 315     def get_on_track(self):
 
 318         stages = [ch.stage.ordering if ch.stage is not None else 0
 
 323     on_track = cached_in_field('_on_track')(get_on_track)
 
 326         return len(self) == 1
 
 327     single = cached_in_field('_single')(is_single)
 
 329     @cached_in_field('_short_html')
 
 330     def short_html(self):
 
 331         return render_to_string('catalogue/book_list/book.html', {'book': self})
 
 333     def book_info(self, publishable=True):
 
 335             book_xml = self.materialize(publishable=publishable)
 
 336         except self.NoTextError:
 
 339             from librarian.dcparser import BookInfo
 
 340             from librarian import NoDublinCore, ParseError, ValidationError
 
 342                 return BookInfo.from_string(book_xml.encode('utf-8'))
 
 343             except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
 
 346     def refresh_dc_cache(self):
 
 349             'dc_cover_image': None,
 
 352         info = self.book_info()
 
 354             update['dc_slug'] = info.url.slug
 
 355             if info.cover_source:
 
 357                     image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
 
 361                     if info.cover_source == image.get_full_url():
 
 362                         update['dc_cover_image'] = image
 
 363         Book.objects.filter(pk=self.pk).update(**update)
 
 366         # this should only really be done when text or publishable status changes
 
 367         book_content_updated.delay(self)
 
 370             "_new_publishable": self.is_new_publishable(),
 
 371             "_published": self.is_published(),
 
 372             "_single": self.is_single(),
 
 373             "_on_track": self.get_on_track(),
 
 376         Book.objects.filter(pk=self.pk).update(**update)
 
 377         refresh_instance(self)
 
 380         """This should be done offline."""
 
 386     # Materializing & publishing
 
 387     # ==========================
 
 389     def get_current_changes(self, publishable=True):
 
 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.
 
 396             changes = [chunk.publishable() for chunk in self]
 
 398             changes = [chunk.head for chunk in self if chunk.head is not None]
 
 400             raise self.NoTextError('Some chunks have no available text.')
 
 403     def materialize(self, publishable=False, changes=None):
 
 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.
 
 411             changes = self.get_current_changes(publishable)
 
 412         return compile_text(change.materialize() for change in changes)
 
 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
 
 419         return WLDocument.from_string(
 
 420                 self.materialize(publishable=publishable, changes=changes),
 
 421                 provider=RedakcjaDocProvider(publishable=publishable),
 
 422                 parse_dublincore=parse_dublincore,
 
 425     def publish(self, user, fake=False, host=None):
 
 427             Publishes a book on behalf of a (local) user.
 
 429         self.assert_publishable()
 
 430         changes = self.get_current_changes(publishable=True)
 
 431         book_xml = self.materialize(changes=changes)
 
 433             data = {"book_xml": book_xml}
 
 435                 data['gallery_url'] = host + self.gallery_url()
 
 436             apiclient.api_call(user, "books/", data)
 
 438         br = BookPublishRecord.objects.create(book=self, user=user)
 
 440             ChunkPublishRecord.objects.create(book_record=br, change=c)
 
 441         post_publish.send(sender=br)