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 slughifi import slughifi
 
  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)
 
  34     # wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
 
  35     parent = models.ForeignKey(
 
  36         'self', null=True, blank=True, verbose_name=_('parent'), related_name="children", editable=False)
 
  37     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True, editable=False)
 
  40     _short_html = models.TextField(null=True, blank=True, editable=False)
 
  41     _single = models.NullBooleanField(editable=False, db_index=True)
 
  42     _new_publishable = models.NullBooleanField(editable=False)
 
  43     _published = models.NullBooleanField(editable=False)
 
  44     _on_track = models.IntegerField(null=True, blank=True, db_index=True, editable=False)
 
  45     dc_cover_image = models.ForeignKey(Image, blank=True, null=True,
 
  46         db_index=True, on_delete=models.SET_NULL, editable=False)
 
  47     dc_slug = models.CharField(max_length=128, null=True, blank=True,
 
  48             editable=False, db_index=True)
 
  50     class NoTextError(BaseException):
 
  54         app_label = 'catalogue'
 
  55         ordering = ['title', 'slug']
 
  56         verbose_name = _('book')
 
  57         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 gallery_path(self):
 
  85         return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, self.gallery)
 
  87     def correct_about(self):
 
  88         return "http://%s%s" % (
 
  89             Site.objects.get_current().domain,
 
  90             self.get_absolute_url()
 
  93     # Creating & manipulating
 
  94     # =======================
 
  96     def accessible(self, request):
 
  97         return self.public or request.user.is_authenticated()
 
 100     @transaction.commit_on_success
 
 101     def create(cls, creator, text, *args, **kwargs):
 
 102         b = cls.objects.create(*args, **kwargs)
 
 103         b.chunk_set.all().update(creator=creator)
 
 104         b[0].commit(text, author=creator)
 
 107     def add(self, *args, **kwargs):
 
 108         """Add a new chunk at the end."""
 
 109         return self.chunk_set.reverse()[0].split(*args, **kwargs)
 
 112     @transaction.commit_on_success
 
 113     def import_xml_text(cls, text=u'', previous_book=None,
 
 114                 commit_args=None, **kwargs):
 
 115         """Imports a book from XML, splitting it into chunks as necessary."""
 
 116         texts = split_xml(text)
 
 118             instance = previous_book
 
 120             instance = cls(**kwargs)
 
 123         # if there are more parts, set the rest to empty strings
 
 124         book_len = len(instance)
 
 125         for i in range(book_len - len(texts)):
 
 126             texts.append((u'pusta część %d' % (i + 1), u''))
 
 129         for i, (title, text) in enumerate(texts):
 
 131                 title = u'część %d' % (i + 1)
 
 133             slug = slughifi(title)
 
 137                 chunk.slug = slug[:50]
 
 138                 chunk.title = title[:255]
 
 141                 chunk = instance.add(slug, title)
 
 143             chunk.commit(text, **commit_args)
 
 147     def make_chunk_slug(self, proposed):
 
 149             Finds a chunk slug not yet used in the book.
 
 151         slugs = set(c.slug for c in self)
 
 153         new_slug = proposed[:50]
 
 154         while new_slug in slugs:
 
 155             new_slug = "%s_%d" % (proposed[:45], i)
 
 159     @transaction.commit_on_success
 
 160     def append(self, other, slugs=None, titles=None):
 
 161         """Add all chunks of another book to self."""
 
 164         number = self[len(self) - 1].number + 1
 
 165         len_other = len(other)
 
 166         single = len_other == 1
 
 168         if slugs is not None:
 
 169             assert len(slugs) == len_other
 
 170         if titles is not None:
 
 171             assert len(titles) == len_other
 
 173                 slugs = [slughifi(t) for t in titles]
 
 175         for i, chunk in enumerate(other):
 
 176             # move chunk to new book
 
 178             chunk.number = number
 
 181                 # try some title guessing
 
 182                 if other.title.startswith(self.title):
 
 183                     other_title_part = other.title[len(self.title):].lstrip(' /')
 
 185                     other_title_part = other.title
 
 188                     # special treatment for appending one-parters:
 
 189                     # just use the guessed title and original book slug
 
 190                     chunk.title = other_title_part
 
 191                     if other.slug.startswith(self.slug):
 
 192                         chunk.slug = other.slug[len(self.slug):].lstrip('-_')
 
 194                         chunk.slug = other.slug
 
 196                     chunk.title = ("%s, %s" % (other_title_part, chunk.title))[:255]
 
 198                 chunk.slug = slugs[i]
 
 199                 chunk.title = titles[i]
 
 201             chunk.slug = self.make_chunk_slug(chunk.slug)
 
 204         assert not other.chunk_set.exists()
 
 206         gm = GalleryMerger(self.gallery, other.gallery)
 
 207         self.gallery = gm.merge()
 
 209         # and move the gallery starts
 
 211                 for chunk in self[len(self) - len_other:]:
 
 212                         old_start = chunk.gallery_start or 1
 
 213                         chunk.gallery_start = old_start + gm.dest_size - gm.num_deleted
 
 219     @transaction.commit_on_success
 
 220     def prepend_history(self, other):
 
 221         """Prepend history from all the other book's chunks to own."""
 
 224         for i in range(len(self), len(other)):
 
 225             title = u"pusta część %d" % i
 
 226             chunk = self.add(slughifi(title), title)
 
 229         for i in range(len(other)):
 
 230             self[i].prepend_history(other[0])
 
 232         assert not other.chunk_set.exists()
 
 236         """Splits all the chunks into separate books."""
 
 239             book = Book.objects.create(title=chunk.title, slug=chunk.slug,
 
 240                     public=self.public, gallery=self.gallery)
 
 245         assert not self.chunk_set.exists()
 
 251     def last_published(self):
 
 253             return self.publish_log.all()[0].timestamp
 
 257     def assert_publishable(self):
 
 258         assert self.chunk_set.exists(), _('No chunks in the book.')
 
 260             changes = self.get_current_changes(publishable=True)
 
 261         except self.NoTextError:
 
 262             raise AssertionError(_('Not all chunks have publishable revisions.'))
 
 264         from librarian import NoDublinCore, ParseError, ValidationError
 
 267             bi = self.wldocument(changes=changes, strict=True).book_info
 
 268         except ParseError, e:
 
 269             raise AssertionError(_('Invalid XML') + ': ' + unicode(e))
 
 271             raise AssertionError(_('No Dublin Core found.'))
 
 272         except ValidationError, e:
 
 273             raise AssertionError(_('Invalid Dublin Core') + ': ' + unicode(e))
 
 275         valid_about = self.correct_about()
 
 276         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
 
 278     def publishable_error(self):
 
 280             return self.assert_publishable()
 
 281         except AssertionError, e:
 
 287         return self.slug.startswith('.')
 
 289     def is_new_publishable(self):
 
 290         """Checks if book is ready for publishing.
 
 292         Returns True if there is a publishable version newer than the one
 
 296         new_publishable = False
 
 297         if not self.chunk_set.exists():
 
 300             change = chunk.publishable()
 
 303             if not new_publishable and not change.publish_log.exists():
 
 304                 new_publishable = True
 
 305         return new_publishable
 
 306     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
 
 308     def is_published(self):
 
 309         return self.publish_log.exists()
 
 310     published = cached_in_field('_published')(is_published)
 
 312     def get_on_track(self):
 
 315         stages = [ch.stage.ordering if ch.stage is not None else 0
 
 320     on_track = cached_in_field('_on_track')(get_on_track)
 
 323         return len(self) == 1
 
 324     single = cached_in_field('_single')(is_single)
 
 326     @cached_in_field('_short_html')
 
 327     def short_html(self):
 
 328         return render_to_string('catalogue/book_list/book.html', {'book': self})
 
 330     def book_info(self, publishable=True):
 
 332             book_xml = self.materialize(publishable=publishable)
 
 333         except self.NoTextError:
 
 336             from librarian.dcparser import BookInfo
 
 337             from librarian import NoDublinCore, ParseError, ValidationError
 
 339                 return BookInfo.from_string(book_xml.encode('utf-8'))
 
 340             except (self.NoTextError, ParseError, NoDublinCore, ValidationError):
 
 343     def refresh_dc_cache(self):
 
 346             'dc_cover_image': None,
 
 349         info = self.book_info()
 
 351             update['dc_slug'] = info.url.slug
 
 352             if info.cover_source:
 
 354                     image = Image.objects.get(pk=int(info.cover_source.rstrip('/').rsplit('/', 1)[-1]))
 
 358                     if info.cover_source == image.get_full_url():
 
 359                         update['dc_cover_image'] = image
 
 360         Book.objects.filter(pk=self.pk).update(**update)
 
 363         # this should only really be done when text or publishable status changes
 
 364         book_content_updated.delay(self)
 
 367             "_new_publishable": self.is_new_publishable(),
 
 368             "_published": self.is_published(),
 
 369             "_single": self.is_single(),
 
 370             "_on_track": self.get_on_track(),
 
 373         Book.objects.filter(pk=self.pk).update(**update)
 
 374         refresh_instance(self)
 
 377         """This should be done offline."""
 
 383     # Materializing & publishing
 
 384     # ==========================
 
 386     def get_current_changes(self, publishable=True):
 
 388             Returns a list containing one Change for every Chunk in the Book.
 
 389             Takes the most recent revision (publishable, if set).
 
 390             Throws an error, if a proper revision is unavailable for a Chunk.
 
 393             changes = [chunk.publishable() for chunk in self]
 
 395             changes = [chunk.head for chunk in self if chunk.head is not None]
 
 397             raise self.NoTextError('Some chunks have no available text.')
 
 400     def materialize(self, publishable=False, changes=None):
 
 402             Get full text of the document compiled from chunks.
 
 403             Takes the current versions of all texts
 
 404             or versions most recently tagged for publishing,
 
 405             or a specified iterable changes.
 
 408             changes = self.get_current_changes(publishable)
 
 409         return compile_text(change.materialize() for change in changes)
 
 411     def wldocument(self, publishable=True, changes=None, 
 
 412             parse_dublincore=True, strict=False):
 
 413         from catalogue.ebook_utils import RedakcjaDocProvider
 
 414         from librarian.parser import WLDocument
 
 416         return WLDocument.from_string(
 
 417                 self.materialize(publishable=publishable, changes=changes),
 
 418                 provider=RedakcjaDocProvider(publishable=publishable),
 
 419                 parse_dublincore=parse_dublincore,
 
 422     def publish(self, user):
 
 424             Publishes a book on behalf of a (local) user.
 
 426         self.assert_publishable()
 
 427         changes = self.get_current_changes(publishable=True)
 
 428         book_xml = self.materialize(changes=changes)
 
 429         apiclient.api_call(user, "books/", {"book_xml": book_xml})
 
 431         br = BookPublishRecord.objects.create(book=self, user=user)
 
 433             ChunkPublishRecord.objects.create(book_record=br, change=c)
 
 434         post_publish.send(sender=br)