Django 1.7, working version.
[wolnelektury.git] / apps / catalogue / models / book.py
index 64dd498..8f5f107 100644 (file)
@@ -2,25 +2,41 @@
 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
+from collections import OrderedDict
 import re
 from django.conf import settings
-from django.core.cache import get_cache
+from django.core.cache import caches
 from django.db import models
 from django.db.models import permalink
 import django.dispatch
-from django.utils.datastructures import SortedDict
+from django.contrib.contenttypes.fields import GenericRelation
+from django.core.urlresolvers import reverse
 from django.utils.translation import ugettext_lazy as _
 import jsonfield
+from fnpdjango.storage import BofhFileSystemStorage
 from catalogue import constants
 from catalogue.fields import EbookField
 from catalogue.models import Tag, Fragment, BookMedia
-from catalogue.utils import create_zip, split_tags, book_upload_path, related_tag_name
+from catalogue.utils import create_zip, split_tags, related_tag_name
 from catalogue import app_settings
 from catalogue import tasks
 from newtagging import managers
 
+bofh_storage = BofhFileSystemStorage()
 
-permanent_cache = get_cache('permanent')
+permanent_cache = caches['permanent']
+
+
+def _cover_upload_to(i, n):
+    return 'book/cover/%s.jpg' % i.slug
+
+def _cover_thumb_upload_to(i, n):
+    return 'book/cover_thumb/%s.jpg' % i.slug,
+
+def _ebook_upload_to(upload_path):
+    def _upload_to(i, n):
+        return upload_path % i.slug
+    return _upload_to
 
 
 class Book(models.Model):
@@ -43,10 +59,14 @@ class Book(models.Model):
     # files generated during publication
 
     cover = EbookField('cover', _('cover'),
-                upload_to=book_upload_path('jpg'), null=True, blank=True)
+            null=True, blank=True,
+            upload_to=_cover_upload_to,
+            storage=bofh_storage, max_length=255)
     # Cleaner version of cover for thumbs
-    cover_thumb = EbookField('cover_thumb', _('cover thumbnail'),
-                upload_to=book_upload_path('th.jpg'), null=True, blank=True)
+    cover_thumb = EbookField('cover_thumb', _('cover thumbnail'), 
+            null=True, blank=True,
+            upload_to=_cover_thumb_upload_to,
+            max_length=255)
     ebook_formats = constants.EBOOK_FORMATS
     formats = ebook_formats + ['html', 'xml']
 
@@ -58,6 +78,7 @@ class Book(models.Model):
     objects  = models.Manager()
     tagged   = managers.ModelTaggedItemManager(Tag)
     tags     = managers.TagDescriptor(Tag)
+    tag_relations = GenericRelation(Tag.intermediary_table_model)
 
     html_built = django.dispatch.Signal()
     published = django.dispatch.Signal()
@@ -100,6 +121,12 @@ class Book(models.Model):
     def name(self):
         return self.title
 
+    def language_code(self):
+        return constants.LANGUAGES_3TO2.get(self.language, self.language)
+
+    def language_name(self):
+        return dict(settings.LANGUAGES).get(self.language_code(), "")
+
     def book_tag_slug(self):
         return ('l-' + self.slug)[:120]
 
@@ -122,7 +149,7 @@ class Book(models.Model):
         if self.has_media(type_):
             if type_ in Book.formats:
                 return getattr(self, "%s_file" % type_)
-            else:                                             
+            else:
                 return self.media.filter(type=type_)
         else:
             return None
@@ -134,7 +161,7 @@ class Book(models.Model):
     def get_ogg(self):
         return self.get_media("ogg")
     def get_daisy(self):
-        return self.get_media("daisy")                       
+        return self.get_media("daisy")
 
     def reset_short_html(self):
         if self.id is None:
@@ -145,7 +172,7 @@ class Book(models.Model):
         for fragm in self.fragments.all().iterator():
             fragm.reset_short_html()
 
-        try: 
+        try:
             author = self.tags.filter(category='author')[0].sort_key
         except IndexError:
             author = u''
@@ -208,9 +235,9 @@ class Book(models.Model):
         return create_zip(paths, "%s_%s" % (self.slug, format_))
 
     def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
-        import search
         if index is None:
-            index = search.Index()
+            from search.index import Index
+            index = Index()
         try:
             index.index_book(self, book_info)
             if index_tags:
@@ -309,18 +336,16 @@ class Book(models.Model):
             if old_cover:
                 notify_cover_changed.append(child)
 
-        # delete old fragments when overwriting
-        book.fragments.all().delete()
-        # Build HTML, fix the tree tags, build cover.
-        has_own_text = bool(book.html_file.build())
-        tasks.fix_tree_tags.delay(book)
+        # No saves beyond this point.
+
+        # Build cover.
         if 'cover' not in dont_build:
             book.cover.build_delay()
             book.cover_thumb.build_delay()
-        
-        # No saves behind this point.
 
-        if has_own_text:
+        # Build HTML and ebooks.
+        book.html_file.build_delay()
+        if not children:
             for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
                 if format_ not in dont_build:
                     getattr(book, '%s_file' % format_).build_delay()
@@ -406,6 +431,10 @@ class Book(models.Model):
             for child in self.children.all():
                 child.parent_cover_changed()
 
+    def other_versions(self):
+        """Find other versions (i.e. in other languages) of the book."""
+        return type(self).objects.filter(common_slug=self.common_slug).exclude(pk=self.pk)
+
     def related_info(self):
         """Keeps info about related objects (tags, media) in cache field."""
         if self._related_info is not None:
@@ -511,8 +540,6 @@ class Book(models.Model):
         rel_info = book.related_info()
         names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
                     for tag in rel_info['tags'].get('author', ())]
-        import logging
-        logging.info("%s, %s" % (book.slug, unicode(rel_info['tags'].get('author', ()))))
         if 'parents' in rel_info:
             books = [(name, Book.create_url(slug))
                         for name, slug in rel_info['parents']]
@@ -535,7 +562,7 @@ class Book(models.Model):
         """
         # get relevant books and their tags
         objects = cls.tagged.with_all(tags)
-        parents = objects.filter(html_file='').only('slug')
+        parents = objects.exclude(children=None).only('slug')
         # eliminate descendants
         l_tags = Tag.objects.filter(category='book',
             slug__in=[book.book_tag_slug() for book in parents.iterator()])
@@ -558,7 +585,7 @@ class Book(models.Model):
                 'title', 'parent', 'slug')
         if filter:
             books = books.filter(filter).distinct()
-            
+
             book_ids = set(b['pk'] for b in books.values("pk").iterator())
             for book in books.iterator():
                 parent = book.parent_id
@@ -570,11 +597,11 @@ class Book(models.Model):
                 books_by_parent.setdefault(book.parent_id, []).append(book)
 
         orphans = []
-        books_by_author = SortedDict()
+        books_by_author = OrderedDict()
         for tag in Tag.objects.filter(category='author').iterator():
             books_by_author[tag] = []
 
-        for book in books_by_parent.get(None,()):
+        for book in books_by_parent.get(None, ()):
             authors = list(book.tags.filter(category='author'))
             if authors:
                 for author in authors:
@@ -598,6 +625,14 @@ class Book(models.Model):
         audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
         return [a[1] for a in audiences]
 
+    def stage_note(self):
+        stage = self.extra_info.get('stage')
+        if stage and stage < '0.4':
+            return (_('This work needs modernisation'),
+                    reverse('infopage', args=['wymagajace-uwspolczesnienia']))
+        else:
+            return None, None
+
     def choose_fragment(self):
         tag = self.book_tag()
         fragments = Fragment.tagged.with_any([tag])
@@ -608,10 +643,18 @@ class Book(models.Model):
         else:
             return None
 
-
 # add the file fields
 for format_ in Book.formats:
     field_name = "%s_file" % format_
+    # This weird globals() assignment makes Django migrations comfortable.
+    _upload_to = _ebook_upload_to('book/%s/%%s.%s' % (format_, format_))
+    _upload_to.__name__ = '_%s_upload_to' % format_
+    globals()[_upload_to.__name__] = _upload_to
+
     EbookField(format_, _("%s file" % format_.upper()),
-            upload_to=book_upload_path(format_),
-            blank=True, default='').contribute_to_class(Book, field_name)
+        upload_to=_upload_to,
+        storage=bofh_storage,
+        max_length=255,
+        blank=True,
+        default=''
+    ).contribute_to_class(Book, field_name)