Tidying up all the covers craziness and storages.
[wolnelektury.git] / src / catalogue / models / book.py
index 375c79a..cfb3263 100644 (file)
@@ -7,6 +7,7 @@ from datetime import date, timedelta
 from random import randint
 import os.path
 import re
 from random import randint
 import os.path
 import re
+import requests
 from slugify import slugify
 from sortify import sortify
 from urllib.request import urlretrieve
 from slugify import slugify
 from sortify import sortify
 from urllib.request import urlretrieve
@@ -15,10 +16,10 @@ from django.conf import settings
 from django.db import connection, models, transaction
 import django.dispatch
 from django.contrib.contenttypes.fields import GenericRelation
 from django.db import connection, models, transaction
 import django.dispatch
 from django.contrib.contenttypes.fields import GenericRelation
+from django.core.files.storage import storages
 from django.template.loader import render_to_string
 from django.urls import reverse
 from django.utils.translation import gettext_lazy as _, get_language
 from django.template.loader import render_to_string
 from django.urls import reverse
 from django.utils.translation import gettext_lazy as _, get_language
-from fnpdjango.storage import BofhFileSystemStorage
 from lxml import html
 from librarian.cover import WLCover
 from librarian.html import transform_abstrakt
 from lxml import html
 from librarian.cover import WLCover
 from librarian.html import transform_abstrakt
@@ -32,7 +33,9 @@ from catalogue.models.tag import prefetched_relations
 from catalogue import app_settings
 from wolnelektury.utils import makedirs, cached_render, clear_cached_renders
 
 from catalogue import app_settings
 from wolnelektury.utils import makedirs, cached_render, clear_cached_renders
 
-bofh_storage = BofhFileSystemStorage()
+
+def get_storage():
+    return storages['book']
 
 
 class Book(models.Model):
 
 
 class Book(models.Model):
@@ -61,26 +64,20 @@ class Book(models.Model):
     preview_until = models.DateField('prapremiera do', blank=True, null=True)
     preview_key = models.CharField(max_length=32, blank=True, null=True)
     findable = models.BooleanField('wyszukiwalna', default=True, db_index=True)
     preview_until = models.DateField('prapremiera do', blank=True, null=True)
     preview_key = models.CharField(max_length=32, blank=True, null=True)
     findable = models.BooleanField('wyszukiwalna', default=True, db_index=True)
+    can_sell = models.BooleanField('do sprzedaży', default=True)
+    can_sell_mp3 = models.BooleanField('do sprzedaży mp3', default=False)
+    isbn_mp3 = models.CharField('ISBN audiobooka', max_length=32, blank=True)
 
     # files generated during publication
 
     # files generated during publication
-    xml_file = fields.XmlField(storage=bofh_storage, with_etag=False)
-    html_file = fields.HtmlField(storage=bofh_storage)
-    html_nonotes_file = fields.HtmlNonotesField(storage=bofh_storage)
-    fb2_file = fields.Fb2Field(storage=bofh_storage)
-    txt_file = fields.TxtField(storage=bofh_storage)
-    epub_file = fields.EpubField(storage=bofh_storage)
-    mobi_file = fields.MobiField(storage=bofh_storage)
-    pdf_file = fields.PdfField(storage=bofh_storage)
-
-    cover = fields.CoverField('okładka', storage=bofh_storage)
-    # Cleaner version of cover for thumbs
-    cover_clean = fields.CoverCleanField('czysta okładka')
-    cover_thumb = fields.CoverThumbField('miniatura okładki')
-    cover_api_thumb = fields.CoverApiThumbField(
-        'mniaturka okładki dla aplikacji')
-    simple_cover = fields.SimpleCoverField('okładka dla aplikacji')
-    cover_ebookpoint = fields.CoverEbookpointField(
-        'okładka dla Ebookpoint')
+    xml_file = fields.XmlField(storage=get_storage, with_etag=False)
+    html_file = fields.HtmlField(storage=get_storage)
+    html_nonotes_file = fields.HtmlNonotesField(storage=get_storage)
+    fb2_file = fields.Fb2Field(storage=get_storage)
+    txt_file = fields.TxtField(storage=get_storage)
+    epub_file = fields.EpubField(storage=get_storage)
+    mobi_file = fields.MobiField(storage=get_storage)
+    pdf_file = fields.PdfField(storage=get_storage)
+    cover = fields.CoverField('okładka', storage=get_storage)
 
     ebook_formats = constants.EBOOK_FORMATS
     formats = ebook_formats + ['html', 'xml', 'html_nonotes']
 
     ebook_formats = constants.EBOOK_FORMATS
     formats = ebook_formats + ['html', 'xml', 'html_nonotes']
@@ -224,7 +221,8 @@ class Book(models.Model):
         if self.preview and not self.preview_key:
             self.preview_key = get_random_hash(self.slug)[:32]
 
         if self.preview and not self.preview_key:
             self.preview_key = get_random_hash(self.slug)[:32]
 
-        ret = super(Book, self).save(force_insert, force_update, **kwargs)
+        ret = super(Book, self).save(
+            force_insert=force_insert, force_update=force_update, **kwargs)
 
         return ret
 
 
         return ret
 
@@ -634,7 +632,7 @@ class Book(models.Model):
             for filename in os.listdir(gallery_path):
                 file_path = os.path.join(gallery_path, filename)
                 os.unlink(file_path)
             for filename in os.listdir(gallery_path):
                 file_path = os.path.join(gallery_path, filename)
                 os.unlink(file_path)
-        ilustr_elements = list(self.wldocument().edoc.findall('//ilustr'))
+        ilustr_elements = list(self.wldocument().edoc.findall('.//ilustr'))
         if ilustr_elements:
             makedirs(gallery_path)
             for ilustr in ilustr_elements:
         if ilustr_elements:
             makedirs(gallery_path)
             for ilustr in ilustr_elements:
@@ -656,7 +654,7 @@ class Book(models.Model):
         if self.html_file:
             parser = html.HTMLParser(encoding='utf-8')
             tree = html.parse(self.html_file.path, parser=parser)
         if self.html_file:
             parser = html.HTMLParser(encoding='utf-8')
             tree = html.parse(self.html_file.path, parser=parser)
-            toc = tree.find('//div[@id="toc"]/ol')
+            toc = tree.find('.//div[@id="toc"]/ol')
             if toc is None or not len(toc):
                 return
             html_link = reverse('book_text', args=[self.slug])
             if toc is None or not len(toc):
                 return
             html_link = reverse('book_text', args=[self.slug])
@@ -683,7 +681,7 @@ class Book(models.Model):
 
     @classmethod
     def from_text_and_meta(cls, raw_file, book_info, overwrite=False, dont_build=None, search_index=True,
 
     @classmethod
     def from_text_and_meta(cls, raw_file, book_info, overwrite=False, dont_build=None, search_index=True,
-                           remote_gallery_url=None, days=0, findable=True, logo=None, logo_mono=None, logo_alt=None):
+                           remote_gallery_url=None, days=0, findable=True, logo=None, logo_mono=None, logo_alt=None, can_sell=None, isbn_mp3=None):
         from catalogue import tasks
 
         if dont_build is None:
         from catalogue import tasks
 
         if dont_build is None:
@@ -738,6 +736,10 @@ class Book(models.Model):
             extra['logo_mono'] = logo_mono
         if logo_alt:
             extra['logo_alt'] = logo_alt
             extra['logo_mono'] = logo_mono
         if logo_alt:
             extra['logo_alt'] = logo_alt
+        if can_sell is not None:
+            book.can_sell = can_sell
+        if isbn_mp3 is not None:
+            book.isbn_mp3 = isbn_mp3
         book.extra_info = json.dumps(extra)
         book.load_abstract()
         book.load_toc()
         book.extra_info = json.dumps(extra)
         book.load_abstract()
         book.load_toc()
@@ -783,11 +785,6 @@ class Book(models.Model):
         # Build cover.
         if 'cover' not in dont_build:
             book.cover.build_delay()
         # Build cover.
         if 'cover' not in dont_build:
             book.cover.build_delay()
-            book.cover_clean.build_delay()
-            book.cover_thumb.build_delay()
-            book.cover_api_thumb.build_delay()
-            book.simple_cover.build_delay()
-            book.cover_ebookpoint.build_delay()
 
         # Build HTML and ebooks.
         book.html_file.build_delay()
 
         # Build HTML and ebooks.
         book.html_file.build_delay()
@@ -798,7 +795,8 @@ class Book(models.Model):
         for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
             if format_ not in dont_build:
                 getattr(book, '%s_file' % format_).build_delay()
         for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
             if format_ not in dont_build:
                 getattr(book, '%s_file' % format_).build_delay()
-        book.html_nonotes_file.build_delay()
+        if 'html_nonotes' not in dont_build:
+            book.html_nonotes_file.build_delay()
 
         if not settings.NO_SEARCH_INDEX and search_index and findable:
             tasks.index_book.delay(book.id)
 
         if not settings.NO_SEARCH_INDEX and search_index and findable:
             tasks.index_book.delay(book.id)
@@ -807,7 +805,8 @@ class Book(models.Model):
             child.parent_cover_changed()
 
         book.update_popularity()
             child.parent_cover_changed()
 
         book.update_popularity()
-        tasks.update_references.delay(book.id)
+        if 'references' not in dont_build:
+            tasks.update_references.delay(book.id)
 
         cls.published.send(sender=cls, instance=book)
         return book
 
         cls.published.send(sender=cls, instance=book)
         return book
@@ -903,6 +902,19 @@ class Book(models.Model):
             narrators.append(t)
         self.narrators.set(narrators)
 
             narrators.append(t)
         self.narrators.set(narrators)
 
+    def update_can_sell_mp3(self):
+        ret = True
+        for child in self.get_children():
+            child.update_can_sell_mp3()
+            if not child.can_sell_mp3:
+                ret = False
+        if self.has_mp3_file():
+            audio_items = requests.get(f'https://audio.wolnelektury.pl/archive/book/{self.slug}.json').json()['items']
+            if not all(x['project']['can_sell'] for x in audio_items):
+                ret = False
+        self.can_sell_mp3 = ret
+        self.save(update_fields=['can_sell_mp3'])
+
     @classmethod
     @transaction.atomic
     def repopulate_ancestors(cls):
     @classmethod
     @transaction.atomic
     def repopulate_ancestors(cls):
@@ -978,11 +990,6 @@ class Book(models.Model):
         if not self.cover_info(inherit=False):
             if 'cover' not in app_settings.DONT_BUILD:
                 self.cover.build_delay()
         if not self.cover_info(inherit=False):
             if 'cover' not in app_settings.DONT_BUILD:
                 self.cover.build_delay()
-                self.cover_clean.build_delay()
-                self.cover_thumb.build_delay()
-                self.cover_api_thumb.build_delay()
-                self.simple_cover.build_delay()
-                self.cover_ebookpoint.build_delay()
             for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
                 if format_ not in app_settings.DONT_BUILD:
                     getattr(self, '%s_file' % format_).build_delay()
             for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
                 if format_ not in app_settings.DONT_BUILD:
                     getattr(self, '%s_file' % format_).build_delay()