1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
 
   2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   4 from django.apps import apps
 
   5 from django.contrib.sites.models import Site
 
   6 from django.db import models, transaction
 
   7 from django.template.loader import render_to_string
 
   8 from django.urls import reverse
 
   9 from django.utils.translation import ugettext_lazy as _
 
  10 from django.conf import settings
 
  11 from slugify import slugify
 
  15 from documents.helpers import cached_in_field, GalleryMerger
 
  16 from documents.models import BookPublishRecord, ChunkPublishRecord, Project
 
  17 from documents.signals import post_publish
 
  18 from documents.xml_tools import compile_text, split_xml
 
  19 from cover.models import Image
 
  24 class Book(models.Model):
 
  25     """ A document edited on the wiki """
 
  27     title = models.CharField(_('title'), max_length=255, db_index=True)
 
  28     slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
 
  29     public = models.BooleanField(_('public'), default=True, db_index=True)
 
  30     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
 
  31     project = models.ForeignKey(Project, models.SET_NULL, null=True, blank=True)
 
  33     #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
 
  34     parent = models.ForeignKey('self', models.SET_NULL, 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)
 
  38     _single = models.NullBooleanField(editable=False, db_index=True)
 
  39     _new_publishable = models.NullBooleanField(editable=False)
 
  40     _published = models.NullBooleanField(editable=False)
 
  41     _on_track = models.IntegerField(null=True, blank=True, db_index=True, editable=False)
 
  42     dc_cover_image = models.ForeignKey(Image, blank=True, null=True,
 
  43         db_index=True, on_delete=models.SET_NULL, editable=False)
 
  44     dc_slug = models.CharField(max_length=128, null=True, blank=True,
 
  45             editable=False, db_index=True)
 
  47     class NoTextError(BaseException):
 
  51         app_label = 'documents'
 
  52         ordering = ['title', 'slug']
 
  53         verbose_name = _('book')
 
  54         verbose_name_plural = _('books')
 
  61         return iter(self.chunk_set.all())
 
  63     def __getitem__(self, chunk):
 
  64         return self.chunk_set.all()[chunk]
 
  67         return self.chunk_set.count()
 
  71             Necessary so that __len__ isn't used for bool evaluation.
 
  78     def get_absolute_url(self):
 
  79         return reverse("documents_book", args=[self.slug])
 
  81     def correct_about(self):
 
  82         return "http://%s%s" % (
 
  83             Site.objects.get_current().domain,
 
  84             self.get_absolute_url()
 
  87     def gallery_path(self):
 
  88         return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
 
  90     def gallery_url(self):
 
  91         return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, self.gallery)
 
  94     def catalogue_book(self):
 
  95         CBook = apps.get_model('catalogue', 'Book')
 
  96         return CBook.objects.filter(slug=self.dc_slug).first()
 
  98     # Creating & manipulating
 
  99     # =======================
 
 101     def accessible(self, request):
 
 102         return self.public or request.user.is_authenticated
 
 106     def create(cls, creator, text, *args, **kwargs):
 
 107         b = cls.objects.create(*args, **kwargs)
 
 108         b.chunk_set.all().update(creator=creator)
 
 109         b[0].commit(text, author=creator)
 
 112     def add(self, *args, **kwargs):
 
 113         """Add a new chunk at the end."""
 
 114         return self.chunk_set.reverse()[0].split(*args, **kwargs)
 
 118     def import_xml_text(cls, text=u'', previous_book=None,
 
 119                 commit_args=None, **kwargs):
 
 120         """Imports a book from XML, splitting it into chunks as necessary."""
 
 121         texts = split_xml(text)
 
 123             instance = previous_book
 
 125             instance = cls(**kwargs)
 
 128         # if there are more parts, set the rest to empty strings
 
 129         book_len = len(instance)
 
 130         for i in range(book_len - len(texts)):
 
 131             texts.append((u'pusta część %d' % (i + 1), u''))
 
 134         for i, (title, text) in enumerate(texts):
 
 136                 title = u'część %d' % (i + 1)
 
 138             slug = slugify(title)
 
 142                 chunk.slug = slug[:50]
 
 143                 chunk.title = title[:255]
 
 146                 chunk = instance.add(slug, title)
 
 148             chunk.commit(text, **commit_args)
 
 152     def make_chunk_slug(self, proposed):
 
 154             Finds a chunk slug not yet used in the book.
 
 156         slugs = set(c.slug for c in self)
 
 158         new_slug = proposed[:50]
 
 159         while new_slug in slugs:
 
 160             new_slug = "%s_%d" % (proposed[:45], i)
 
 165     def append(self, other, slugs=None, titles=None):
 
 166         """Add all chunks of another book to self."""
 
 169         number = self[len(self) - 1].number + 1
 
 170         len_other = len(other)
 
 171         single = len_other == 1
 
 173         if slugs is not None:
 
 174             assert len(slugs) == len_other
 
 175         if titles is not None:
 
 176             assert len(titles) == len_other
 
 178                 slugs = [slugify(t) for t in titles]
 
 180         for i, chunk in enumerate(other):
 
 181             # move chunk to new book
 
 183             chunk.number = number
 
 186                 # try some title guessing
 
 187                 if other.title.startswith(self.title):
 
 188                     other_title_part = other.title[len(self.title):].lstrip(' /')
 
 190                     other_title_part = other.title
 
 193                     # special treatment for appending one-parters:
 
 194                     # just use the guessed title and original book slug
 
 195                     chunk.title = other_title_part
 
 196                     if other.slug.startswith(self.slug):
 
 197                         chunk.slug = other.slug[len(self.slug):].lstrip('-_')
 
 199                         chunk.slug = other.slug
 
 201                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
 
 203                 chunk.slug = slugs[i]
 
 204                 chunk.title = titles[i]
 
 206             chunk.slug = self.make_chunk_slug(chunk.slug)
 
 209         assert not other.chunk_set.exists()
 
 211         gm = GalleryMerger(self.gallery, other.gallery)
 
 212         self.gallery = gm.merge()
 
 214         # and move the gallery starts
 
 216                 for chunk in self[len(self) - len_other:]:
 
 217                         old_start = chunk.gallery_start or 1
 
 218                         chunk.gallery_start = old_start + gm.dest_size - gm.num_deleted
 
 225     def prepend_history(self, other):
 
 226         """Prepend history from all the other book's chunks to own."""
 
 229         for i in range(len(self), len(other)):
 
 230             title = u"pusta część %d" % i
 
 231             chunk = self.add(slugify(title), title)
 
 234         for i in range(len(other)):
 
 235             self[i].prepend_history(other[0])
 
 237         assert not other.chunk_set.exists()
 
 241         """Splits all the chunks into separate books."""
 
 244             book = Book.objects.create(title=chunk.title, slug=chunk.slug,
 
 245                     public=self.public, gallery=self.gallery)
 
 250         assert not self.chunk_set.exists()
 
 256     def last_published(self):
 
 258             return self.publish_log.all()[0].timestamp
 
 262     def assert_publishable(self):
 
 263         assert self.chunk_set.exists(), _('No chunks in the book.')
 
 265             changes = self.get_current_changes(publishable=True)
 
 266         except self.NoTextError:
 
 267             raise AssertionError(_('Not all chunks have publishable revisions.'))
 
 269         from librarian import NoDublinCore, ParseError, ValidationError
 
 272             bi = self.wldocument(changes=changes, strict=True).book_info
 
 273         except ParseError as e:
 
 274             raise AssertionError(_('Invalid XML') + ': ' + str(e))
 
 276             raise AssertionError(_('No Dublin Core found.'))
 
 277         except ValidationError as e:
 
 278             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
 
 280         valid_about = self.correct_about()
 
 281         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
 
 283     def publishable_error(self):
 
 285             return self.assert_publishable()
 
 286         except AssertionError as e:
 
 292         return self.slug.startswith('.')
 
 294     def is_new_publishable(self):
 
 295         """Checks if book is ready for publishing.
 
 297         Returns True if there is a publishable version newer than the one
 
 301         new_publishable = False
 
 302         if not self.chunk_set.exists():
 
 305             change = chunk.publishable()
 
 308             if not new_publishable and not change.publish_log.exists():
 
 309                 new_publishable = True
 
 310         return new_publishable
 
 311     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
 
 313     def is_published(self):
 
 314         return self.publish_log.exists()
 
 315     published = cached_in_field('_published')(is_published)
 
 317     def get_on_track(self):
 
 320         stages = [ch.stage.ordering if ch.stage is not None else 0
 
 325     on_track = cached_in_field('_on_track')(get_on_track)
 
 328         return len(self) == 1
 
 329     single = cached_in_field('_single')(is_single)
 
 331     def book_info(self, publishable=True):
 
 333             book_xml = self.materialize(publishable=publishable)
 
 334         except self.NoTextError:
 
 337             from librarian.dcparser import BookInfo
 
 338             from librarian import NoDublinCore, ParseError, ValidationError
 
 340                 return BookInfo.from_bytes(book_xml.encode('utf-8'))
 
 341             except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
 
 344     def refresh_dc_cache(self):
 
 347             'dc_cover_image': None,
 
 350         info = self.book_info()
 
 352             update['dc_slug'] = info.url.slug
 
 353             if info.cover_source:
 
 355                     image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
 
 359                     if info.cover_source == image.get_full_url():
 
 360                         update['dc_cover_image'] = image
 
 361         Book.objects.filter(pk=self.pk).update(**update)
 
 365             "_new_publishable": self.is_new_publishable(),
 
 366             "_published": self.is_published(),
 
 367             "_single": self.is_single(),
 
 368             "_on_track": self.get_on_track(),
 
 370         Book.objects.filter(pk=self.pk).update(**update)
 
 371         self.refresh_dc_cache()
 
 373     # Materializing & publishing
 
 374     # ==========================
 
 376     def get_current_changes(self, publishable=True):
 
 378             Returns a list containing one Change for every Chunk in the Book.
 
 379             Takes the most recent revision (publishable, if set).
 
 380             Throws an error, if a proper revision is unavailable for a Chunk.
 
 383             changes = [chunk.publishable() for chunk in self]
 
 385             changes = [chunk.head for chunk in self if chunk.head is not None]
 
 387             raise self.NoTextError('Some chunks have no available text.')
 
 390     def materialize(self, publishable=False, changes=None):
 
 392             Get full text of the document compiled from chunks.
 
 393             Takes the current versions of all texts
 
 394             or versions most recently tagged for publishing,
 
 395             or a specified iterable changes.
 
 398             changes = self.get_current_changes(publishable)
 
 399         return compile_text(change.materialize() for change in changes)
 
 401     def wldocument(self, publishable=True, changes=None, 
 
 402             parse_dublincore=True, strict=False):
 
 403         from documents.ebook_utils import RedakcjaDocProvider
 
 404         from librarian.parser import WLDocument
 
 406         return WLDocument.from_bytes(
 
 407                 self.materialize(publishable=publishable, changes=changes).encode('utf-8'),
 
 408                 provider=RedakcjaDocProvider(publishable=publishable),
 
 409                 parse_dublincore=parse_dublincore,
 
 412     def publish(self, user, fake=False, host=None, days=0, beta=False):
 
 414             Publishes a book on behalf of a (local) user.
 
 416         self.assert_publishable()
 
 417         changes = self.get_current_changes(publishable=True)
 
 419             book_xml = self.materialize(changes=changes)
 
 420             data = {"book_xml": book_xml, "days": days}
 
 422                 data['gallery_url'] = host + self.gallery_url()
 
 423             apiclient.api_call(user, "books/", data, beta=beta)
 
 426             br = BookPublishRecord.objects.create(book=self, user=user)
 
 428                 ChunkPublishRecord.objects.create(book_record=br, change=c)
 
 429             if not self.public and days == 0:
 
 432             if self.public and days > 0:
 
 435             post_publish.send(sender=br)
 
 438         doc = self.wldocument()
 
 439         return doc.latex_dir(cover=True, ilustr_path=self.gallery_path())