Cache media file size. Reorganize uploading. Remove some unused code.
authorRadek Czajka <radekczajka@wolnelektury.pl>
Fri, 27 Nov 2026 19:28:31 +0000 (20:28 +0100)
committerRadek Czajka <radekczajka@wolnelektury.pl>
Fri, 27 Nov 2026 19:28:31 +0000 (20:28 +0100)
22 files changed:
src/api/tests/res/responses/books.json
src/api/tests/res/responses/books.xml
src/api/tests/res/responses/filter-books.json
src/catalogue/__init__.py
src/catalogue/api/serializers.py
src/catalogue/api/views.py
src/catalogue/feeds.py
src/catalogue/fixtures/test-books.yaml
src/catalogue/management/commands/checkcovers.py [deleted file]
src/catalogue/migrations/0060_bookmedia_file_size.py [new file with mode: 0644]
src/catalogue/models/book.py
src/catalogue/models/bookmedia.py
src/catalogue/templatetags/catalogue_tags.py
src/catalogue/test_utils.py
src/catalogue/tests/test_bookmedia.py
src/catalogue/urls.py
src/catalogue/utils.py
src/catalogue/views.py
src/opds/views.py
src/reporting/views.py
src/wolnelektury/settings/test.py
src/wolnelektury/static/js/current.js [deleted file]

index 3700ac8..9a564a9 100644 (file)
@@ -46,7 +46,7 @@
         "epoch": "Barok", 
         "href": "http://testserver/api/books/parent/",
         "genre": "Sonet", 
         "epoch": "Barok", 
         "href": "http://testserver/api/books/parent/",
         "genre": "Sonet", 
-        "simple_thumb": "http://testserver/media/cover/parent.jpg-139x193",
+        "simple_thumb": "cover/parent.jpg",
         "slug": "parent", 
         "cover_thumb": "cover/parent.jpg"
     }
         "slug": "parent", 
         "cover_thumb": "cover/parent.jpg"
     }
index 3d47fe9..2727725 100644 (file)
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="utf-8"?>
 <?xml version="1.0" encoding="utf-8"?>
-<response><resource><kind></kind><full_sort_key>$child$2</full_sort_key><title>Child</title><url>http://testserver/katalog/lektura/child/</url><cover_color>#000000</cover_color><author></author><cover></cover><epoch></epoch><href>http://testserver/api/books/child/?format=xml</href><has_audio>False</has_audio><genre>Wiersz</genre><simple_thumb></simple_thumb><slug>child</slug><cover_thumb></cover_thumb><liked></liked></resource><resource><kind></kind><full_sort_key>$grandchild$3</full_sort_key><title>Grandchild</title><url>http://testserver/katalog/lektura/grandchild/</url><cover_color>#000000</cover_color><author></author><cover></cover><epoch></epoch><href>http://testserver/api/books/grandchild/?format=xml</href><has_audio>False</has_audio><genre>Sonet</genre><simple_thumb></simple_thumb><slug>grandchild</slug><cover_thumb></cover_thumb><liked></liked></resource><resource><kind>Liryka</kind><full_sort_key>john doe$parent$1</full_sort_key><title>Parent</title><url>http://testserver/katalog/lektura/parent/</url><cover_color>#a6820a</cover_color><author>John Doe</author><cover>cover/parent.jpg</cover><epoch>Barok</epoch><href>http://testserver/api/books/parent/?format=xml</href><has_audio>True</has_audio><genre>Sonet</genre><simple_thumb>http://testserver/media/cover/parent.jpg</simple_thumb><slug>parent</slug><cover_thumb>cover/parent.jpg</cover_thumb><liked></liked></resource></response>
+<response><resource><kind></kind><full_sort_key>$child$2</full_sort_key><title>Child</title><url>http://testserver/katalog/lektura/child/</url><cover_color>#000000</cover_color><author></author><cover></cover><epoch></epoch><href>http://testserver/api/books/child/?format=xml</href><has_audio>False</has_audio><genre>Wiersz</genre><simple_thumb></simple_thumb><slug>child</slug><cover_thumb></cover_thumb><liked></liked></resource><resource><kind></kind><full_sort_key>$grandchild$3</full_sort_key><title>Grandchild</title><url>http://testserver/katalog/lektura/grandchild/</url><cover_color>#000000</cover_color><author></author><cover></cover><epoch></epoch><href>http://testserver/api/books/grandchild/?format=xml</href><has_audio>False</has_audio><genre>Sonet</genre><simple_thumb></simple_thumb><slug>grandchild</slug><cover_thumb></cover_thumb><liked></liked></resource><resource><kind>Liryka</kind><full_sort_key>john doe$parent$1</full_sort_key><title>Parent</title><url>http://testserver/katalog/lektura/parent/</url><cover_color>#a6820a</cover_color><author>John Doe</author><cover>cover/parent.jpg</cover><epoch>Barok</epoch><href>http://testserver/api/books/parent/?format=xml</href><has_audio>True</has_audio><genre>Sonet</genre><simple_thumb>cover/parent.jpg</simple_thumb><slug>parent</slug><cover_thumb>cover/parent.jpg</cover_thumb><liked></liked></resource></response>
index 3e4c72b..b1eb5af 100644 (file)
@@ -49,7 +49,7 @@
         "href": "http://testserver/api/books/parent/",
         "key": "book$parent", 
         "genre": "Sonet", 
         "href": "http://testserver/api/books/parent/",
         "key": "book$parent", 
         "genre": "Sonet", 
-        "simple_thumb": "http://testserver/media/cover/parent.jpg-139x193",
+        "simple_thumb": "cover/parent.jpg",
         "slug": "parent", 
         "cover_thumb": "cover/parent.jpg"
     }
         "slug": "parent", 
         "cover_thumb": "cover/parent.jpg"
     }
index 534211a..b5a7319 100644 (file)
@@ -2,8 +2,6 @@
 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
 import logging
 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
 import logging
-from django.conf import settings
-from django.utils.module_loading import import_string
 from catalogue.utils import AppSettings
 
 
 from catalogue.utils import AppSettings
 
 
@@ -13,13 +11,5 @@ class Settings(AppSettings):
     # PDF needs TeXML + XeLaTeX, MOBI needs Calibre.
     DONT_BUILD = {'pdf', 'mobi'}
 
     # PDF needs TeXML + XeLaTeX, MOBI needs Calibre.
     DONT_BUILD = {'pdf', 'mobi'}
 
-    REDAKCJA_URL = "http://redakcja.wolnelektury.pl"
-    GOOD_LICENSES = {r'CC BY \d\.\d', r'CC BY-SA \d\.\d'}
-    RELATED_RANDOM_PICTURE_CHANCE = .5
-    GET_MP3_LENGTH = 'catalogue.utils.get_mp3_length'
-
-    def _more_GET_MP3_LENGTH(self, value):
-        return import_string(value)
-
 
 app_settings = Settings('CATALOGUE')
 
 app_settings = Settings('CATALOGUE')
index ee34532..cad9d62 100644 (file)
@@ -238,6 +238,7 @@ class BookSerializer(LegacyMixin, serializers.ModelSerializer):
 class BookListSerializer(BookSerializer):
     cover = serializers.CharField()
     cover_thumb = serializers.CharField(source='cover')
 class BookListSerializer(BookSerializer):
     cover = serializers.CharField()
     cover_thumb = serializers.CharField(source='cover')
+    simple_thumb = serializers.CharField(source='cover')
 
     Meta = BookSerializer.Meta
 
 
     Meta = BookSerializer.Meta
 
@@ -268,7 +269,7 @@ class MediaSerializer2(MediaSerializer):
         fields = ['url', 'director', 'type', 'name', 'part_name', 'artist', 'duration', 'size']
 
     def get_size(self, obj):
         fields = ['url', 'director', 'type', 'name', 'part_name', 'artist', 'duration', 'size']
 
     def get_size(self, obj):
-        return obj.file.size
+        return obj.file_size
 
 
 class BookDetailSerializer(LegacyMixin, serializers.ModelSerializer):
 
 
 class BookDetailSerializer(LegacyMixin, serializers.ModelSerializer):
index 2d7fe7d..a04cc6d 100644 (file)
@@ -180,8 +180,7 @@ class BookList(LegacyListAPIView):
         bm.index = index
         bm.project_description = project_description
         bm.project_icon = project_icon
         bm.index = index
         bm.project_description = project_description
         bm.project_icon = project_icon
-        bm.file.save(None, request.data['file'], save=False)
-        bm.save(parts_count=parts_count)
+        bm.set_file(request.data['file'], parts_count=parts_count)
 
         return Response({}, status=status.HTTP_201_CREATED)
 
 
         return Response({}, status=status.HTTP_201_CREATED)
 
index ee4b37f..90973c4 100644 (file)
@@ -75,7 +75,7 @@ class AudiobookFeed(Feed):
         return absolute_url(item.file.url)
 
     def item_enclosure_length(self, item):
         return absolute_url(item.file.url)
 
     def item_enclosure_length(self, item):
-        return item.file.size
+        return item.file_size
 
     def item_enclosure_mime_type(self, item):
         return self.mime_types[item.type]
 
     def item_enclosure_mime_type(self, item):
         return self.mime_types[item.type]
index a2ecdb2..e05b255 100644 (file)
     type: mp3
     name: Parent Audiobook
     file: mp3/parent.mp3
     type: mp3
     name: Parent Audiobook
     file: mp3/parent.mp3
+    duration: 60
     uploaded_at: "1970-01-03 0:0Z"
     extra_info: '{"director_name": "Director", "artist_name": "Artist"}'
 - model: catalogue.bookmedia
     uploaded_at: "1970-01-03 0:0Z"
     extra_info: '{"director_name": "Director", "artist_name": "Artist"}'
 - model: catalogue.bookmedia
diff --git a/src/catalogue/management/commands/checkcovers.py b/src/catalogue/management/commands/checkcovers.py
deleted file mode 100644 (file)
index 6b94fec..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-# This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
-# Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
-#
-from django.contrib.sites.models import Site
-from django.core.management.base import BaseCommand
-from django.utils.functional import lazy
-from catalogue import app_settings
-
-
-def ancestor_has_cover(book):
-    while book.parent:
-        book = book.parent
-        if book.get_extra_info_json().get('cover_url'):
-            return True
-    return False
-
-
-current_domain = lazy(lambda: Site.objects.get_current().domain, str)()
-
-
-def full_url(obj):
-    return 'http://%s%s' % (
-                current_domain,
-                obj.get_absolute_url())
-
-
-class Command(BaseCommand):
-    help = 'Checks cover sources and licenses.'
-
-    def add_arguments(self, parser):
-        parser.add_argument(
-                '-q', '--quiet', action='store_false', dest='verbose',
-                default=True, help='Suppress output')
-
-    def handle(self, **options):
-        from collections import defaultdict
-        import re
-        from django.db import transaction
-        from catalogue.models import Book
-
-        verbose = options['verbose']
-
-        without_cover = []
-        with_ancestral_cover = []
-        not_redakcja = []
-        bad_license = defaultdict(list)
-        no_license = []
-
-        re_license = re.compile(r'.*,\s*(CC.*)')
-
-        redakcja_url = app_settings.REDAKCJA_URL
-        good_license = re.compile("(%s)" % ")|(".join(
-                            app_settings.GOOD_LICENSES))
-
-        with transaction.atomic():
-            for book in Book.objects.all().order_by('slug').iterator():
-                extra_info = book.get_extra_info_json()
-                if not extra_info.get('cover_url'):
-                    if ancestor_has_cover(book):
-                        with_ancestral_cover.append(book)
-                    else:
-                        without_cover.append(book)
-                else:
-                    if not extra_info.get('cover_source', '').startswith(redakcja_url):
-                        not_redakcja.append(book)
-                    match = re_license.match(extra_info.get('cover_by', ''))
-                    if match:
-                        if not good_license.match(match.group(1)):
-                            bad_license[match.group(1)].append(book)
-                    else:
-                        no_license.append(book)
-
-        print("""%d books with no covers, %d with inherited covers.
-Bad licenses used: %s (%d covers without license).
-%d covers not from %s.
-""" % (
-            len(without_cover),
-            len(with_ancestral_cover),
-            ", ".join(sorted(bad_license.keys())) or "none",
-            len(no_license),
-            len(not_redakcja),
-            redakcja_url,
-            ))
-
-        if verbose:
-            if bad_license:
-                print()
-                print("Bad license:")
-                print("============")
-                for lic, books in bad_license.items():
-                    print()
-                    print(lic)
-                    for book in books:
-                        print(full_url(book))
-
-            if no_license:
-                print()
-                print("No license:")
-                print("===========")
-                for book in no_license:
-                    print()
-                    print(full_url(book))
-                    extra_info = book.get_extra_info_json()
-                    print(extra_info.get('cover_by'))
-                    print(extra_info.get('cover_source'))
-                    print(extra_info.get('cover_url'))
-
-            if not_redakcja:
-                print()
-                print("Not from Redakcja or source missing:")
-                print("====================================")
-                for book in not_redakcja:
-                    print()
-                    print(full_url(book))
-                    extra_info = book.get_extra_info_json()
-                    print(extra_info.get('cover_by'))
-                    print(extra_info.get('cover_source'))
-                    print(extra_info.get('cover_url'))
-
-            if without_cover:
-                print()
-                print("No cover:")
-                print("=========")
-                for book in without_cover:
-                    print(full_url(book))
-
-            if with_ancestral_cover:
-                print()
-                print("With ancestral cover:")
-                print("=====================")
-                for book in with_ancestral_cover:
-                    print(full_url(book))
diff --git a/src/catalogue/migrations/0060_bookmedia_file_size.py b/src/catalogue/migrations/0060_bookmedia_file_size.py
new file mode 100644 (file)
index 0000000..53b83ab
--- /dev/null
@@ -0,0 +1,18 @@
+# Generated by Django 5.2.19 on 2026-11-27 19:18
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('catalogue', '0059_remove_book_cover_api_thumb_and_more'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='bookmedia',
+            name='file_size',
+            field=models.IntegerField(blank=True, null=True),
+        ),
+    ]
index cfb3263..a62cac6 100644 (file)
@@ -17,7 +17,6 @@ from django.db import connection, models, transaction
 import django.dispatch
 from django.contrib.contenttypes.fields import GenericRelation
 from django.core.files.storage import storages
 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 lxml import html
 from django.urls import reverse
 from django.utils.translation import gettext_lazy as _, get_language
 from lxml import html
@@ -320,10 +319,9 @@ class Book(models.Model):
             return '%d:%02d:%02d' % (hours, minutes, seconds)
 
     def get_audio_length(self):
             return '%d:%02d:%02d' % (hours, minutes, seconds)
 
     def get_audio_length(self):
-        total = 0
-        for media in self.get_mp3() or ():
-            total += app_settings.GET_MP3_LENGTH(media.file.path)
-        return int(total)
+        total = self.media.filter(type='mp3').aggregate(
+            models.Sum('duration'))['duration__sum']
+        return int(total or 0)
 
     def get_time(self):
         return round(self.xml_file.size / 1000 * 40)
 
     def get_time(self):
         return round(self.xml_file.size / 1000 * 40)
@@ -601,22 +599,6 @@ class Book(models.Model):
         paths = [(pretty_file_name(b), getattr(b, field_name).path) for b in books.iterator()]
         return create_zip(paths, field.ZIP)
 
         paths = [(pretty_file_name(b), getattr(b, field_name).path) for b in books.iterator()]
         return create_zip(paths, field.ZIP)
 
-    def zip_audiobooks(self, format_):
-        bm = BookMedia.objects.filter(book=self, type=format_)
-        paths = map(lambda bm: (bm.get_nice_filename(), bm.file.path), bm)
-        licenses = set()
-        for m in bm:
-            license = constants.LICENSES.get(
-                m.get_extra_info_json().get('license'), {}
-            ).get('locative')
-            if license:
-                licenses.add(license)
-        readme = render_to_string('catalogue/audiobook_zip_readme.txt', {
-            'licenses': licenses,
-            'meta': self.wldocument2().meta,
-        })
-        return create_zip(paths, "%s_%s" % (self.slug, format_), {'informacje.txt': readme})
-
     def search_index(self, index=None):
         if not self.findable:
             return
     def search_index(self, index=None):
         if not self.findable:
             return
@@ -879,9 +861,11 @@ class Book(models.Model):
     def update_narrators(self):
         narrator_names = set()
         for bm in self.media.filter(type='mp3'):
     def update_narrators(self):
         narrator_names = set()
         for bm in self.media.filter(type='mp3'):
-            narrator_names.update(set(
-                a.strip() for a in re.split(r',|\si\s', bm.artist)
-            ))
+            artist = bm.artist
+            if artist:
+                narrator_names.update(set(
+                    a.strip() for a in re.split(r',|\si\s', artist)
+                ))
         narrators = []
 
         for name in narrator_names:
         narrators = []
 
         for name in narrator_names:
index c1b0c5f..38cb233 100644 (file)
@@ -8,7 +8,6 @@ from django.core.files.storage import storages
 from django.db import models
 from slugify import slugify
 import mutagen
 from django.db import models
 from slugify import slugify
 import mutagen
-from mutagen import id3
 
 
 def _file_upload_to(i, _n):
 
 
 def _file_upload_to(i, _n):
@@ -42,6 +41,7 @@ class BookMedia(models.Model):
     part_name = models.CharField('nazwa części', default='', blank=True, max_length=512)
     index = models.IntegerField('indeks', default=0)
     file = models.FileField('plik', max_length=600, upload_to=_file_upload_to, storage=get_storage)
     part_name = models.CharField('nazwa części', default='', blank=True, max_length=512)
     index = models.IntegerField('indeks', default=0)
     file = models.FileField('plik', max_length=600, upload_to=_file_upload_to, storage=get_storage)
+    file_size = models.IntegerField(null=True, blank=True)
     duration = models.FloatField(null=True, blank=True)
     uploaded_at = models.DateTimeField('data utworzenia', auto_now_add=True, editable=False, db_index=True)
     project_description = models.CharField(max_length=2048, blank=True)
     duration = models.FloatField(null=True, blank=True)
     uploaded_at = models.DateTimeField('data utworzenia', auto_now_add=True, editable=False, db_index=True)
     project_description = models.CharField(max_length=2048, blank=True)
@@ -73,13 +73,9 @@ class BookMedia(models.Model):
         ext = self.ext()
         return f'{name}.{ext}'
 
         ext = self.ext()
         return f'{name}.{ext}'
 
-    def save(self, parts_count=None, *args, **kwargs):
-        if self.type in ('daisy', 'audio.epub'):
-            return super().save(*args, **kwargs)
-        from catalogue.utils import ExistingFile, remove_zip
-
+    def set_file(self, content, parts_count=None):
         if not parts_count:
         if not parts_count:
-            parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
+            parts_count = 1 + type(self).objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
         if parts_count == 1:
             self.name = self.book.pretty_title()
         else:
         if parts_count == 1:
             self.name = self.book.pretty_title()
         else:
@@ -88,62 +84,48 @@ class BookMedia(models.Model):
             if self.part_name:
                 self.name += ', ' + self.part_name
 
             if self.part_name:
                 self.name += ', ' + self.part_name
 
-        try:
-            old = BookMedia.objects.get(pk=self.pk)
-        except BookMedia.DoesNotExist:
-            old = None
-
-        #super(BookMedia, self).save(*args, **kwargs)
-        
-        # remove the zip package for book with modified media
-        if old:
-            remove_zip("%s_%s" % (old.book.slug, old.type))
-        remove_zip("%s_%s" % (self.book.slug, self.type))
-
-        extra_info = self.get_extra_info_json()
-        extra_info.update(self.read_meta())
-        self.extra_info = json.dumps(extra_info)
-        self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
-        self.duration = self.read_duration()
-        super(BookMedia, self).save(*args, **kwargs)
+        if self.type in ('mp3', 'ogg'):
+            try:
+                audio = mutagen.File(content)
+                self.duration = audio.info.length
+            except (mutagen.MutagenError, AttributeError):
+                self.extra_info = '{}'
+                self.duration = None
+                self.source_sha1 = None
+            else:
+                self.extra_info = json.dumps(
+                    self.read_meta(audio, self.type))
+                self.source_sha1 = self.read_source_sha1(audio, self.type)
+        self.file_size = content.size
+        self.file.save(None, content)
         self.book.update_narrators()
         self.book.update_has_audio()
 
         self.book.update_narrators()
         self.book.update_has_audio()
 
-    def read_duration(self):
-        try:
-            return mutagen.File(self.file.path).info.length
-        except:
-            return None
-
-    def read_meta(self):
+    @staticmethod
+    def read_meta(audio, file_type):
         """
             Reads some metadata from the audiobook.
         """
         """
             Reads some metadata from the audiobook.
         """
+        tags = audio.tags
+        if not tags:
+            return {}
         artist_name = director_name = project = funded_by = license = ''
         artist_name = director_name = project = funded_by = license = ''
-        if self.type == 'mp3':
-            try:
-                audio = id3.ID3(self.file.path)
-                artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
-                director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
-                license = ', '.join(tag.url for tag in audio.getall('WCOP'))
-                project = ", ".join([
-                    t.data.decode('utf-8') for t in audio.getall('PRIV')
-                    if t.owner == 'wolnelektury.pl?project'])
-                funded_by = ", ".join([
-                    t.data.decode('utf-8') for t in audio.getall('PRIV')
-                    if t.owner == 'wolnelektury.pl?funded_by'])
-            except mutagen.MutagenError:
-                pass
-        elif self.type == 'ogg':
-            try:
-                audio = mutagen.File(self.file.path)
-                artist_name = ', '.join(audio.get('artist', []))
-                director_name = ', '.join(audio.get('conductor', []))
-                license = ', '.join(audio.get('license', []))
-                project = ", ".join(audio.get('project', []))
-                funded_by = ", ".join(audio.get('funded_by', []))
-            except (mutagen.MutagenError, AttributeError):
-                pass
+        if file_type == 'mp3':
+            artist_name = ', '.join(', '.join(tag.text) for tag in tags.getall('TPE1'))
+            director_name = ', '.join(', '.join(tag.text) for tag in tags.getall('TPE3'))
+            license = ', '.join(tag.url for tag in tags.getall('WCOP'))
+            project = ", ".join([
+                t.data.decode('utf-8') for t in tags.getall('PRIV')
+                if t.owner == 'wolnelektury.pl?project'])
+            funded_by = ", ".join([
+                t.data.decode('utf-8') for t in tags.getall('PRIV')
+                if t.owner == 'wolnelektury.pl?funded_by'])
+        elif file_type == 'ogg':
+            artist_name = ', '.join(tags.get('artist', []))
+            director_name = ', '.join(tags.get('conductor', []))
+            license = ', '.join(tags.get('license', []))
+            project = ", ".join(tags.get('project', []))
+            funded_by = ", ".join(tags.get('funded_by', []))
         else:
             return {}
         return {'artist_name': artist_name, 'director_name': director_name,
         else:
             return {}
         return {'artist_name': artist_name, 'director_name': director_name,
@@ -153,22 +135,22 @@ class BookMedia(models.Model):
         return self.formats[self.type].ext
 
     @staticmethod
         return self.formats[self.type].ext
 
     @staticmethod
-    def read_source_sha1(filepath, filetype):
+    def read_source_sha1(audio, filetype):
         """
             Reads source file SHA1 from audiobok metadata.
         """
         """
             Reads source file SHA1 from audiobok metadata.
         """
+        if not audio.tags:
+            return None
         if filetype == 'mp3':
             try:
         if filetype == 'mp3':
             try:
-                audio = id3.ID3(filepath)
-                return [t.data.decode('utf-8') for t in audio.getall('PRIV')
+                return [t.data.decode('utf-8') for t in audio.tags.getall('PRIV')
                         if t.owner == 'wolnelektury.pl?flac_sha1'][0]
                         if t.owner == 'wolnelektury.pl?flac_sha1'][0]
-            except (mutagen.MutagenError, IndexError):
+            except IndexError:
                 return None
         elif filetype == 'ogg':
             try:
                 return None
         elif filetype == 'ogg':
             try:
-                audio = mutagen.File(filepath)
-                return audio.get('flac_sha1', [None])[0]
-            except (mutagen.MutagenError, AttributeError, IndexError):
+                return audio.tags.get('flac_sha1', [None])[0]
+            except IndexError:
                 return None
         else:
             return None
                 return None
         else:
             return None
index 2901975..a71feb5 100644 (file)
@@ -1,8 +1,7 @@
 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
-from random import randint, random
-from urllib.parse import urlparse
+from random import randint
 from django.contrib.contenttypes.models import ContentType
 
 from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 
 from django.conf import settings
@@ -14,7 +13,7 @@ from django.utils.safestring import mark_safe
 from django.utils.translation import gettext as _
 
 from catalogue.helpers import get_audiobook_tags
 from django.utils.translation import gettext as _
 
 from catalogue.helpers import get_audiobook_tags
-from catalogue.models import Book, BookMedia, Fragment, Tag, Source
+from catalogue.models import Book, BookMedia, Fragment, Tag
 from catalogue.constants import LICENSES
 from club.models import Membership
 from social.models import UserList
 from catalogue.constants import LICENSES
 from club.models import Membership
 from social.models import UserList
@@ -357,31 +356,6 @@ def license_locative(license_url, default):
     return LICENSES.get(license_url, {}).get('locative', default)
 
 
     return LICENSES.get(license_url, {}).get('locative', default)
 
 
-@register.simple_tag
-def source_name(url):
-    url = url.lstrip()
-    netloc = urlparse(url).netloc
-    if not netloc:
-        netloc = urlparse('http://' + url).netloc
-    if not netloc:
-        return ''
-    source, created = Source.objects.get_or_create(netloc=netloc)
-    return source.name or netloc
-
-
-@register.simple_tag
-def catalogue_random_book(exclude_ids):
-    from .. import app_settings
-    if random() < app_settings.RELATED_RANDOM_PICTURE_CHANCE:
-        return None
-    queryset = Book.objects.filter(findable=True).exclude(pk__in=exclude_ids)
-    count = queryset.count()
-    if count:
-        return queryset[randint(0, count - 1)]
-    else:
-        return None
-
-
 @register.simple_tag
 def choose_fragment(book=None, tag_ids=None):
     if book is not None:
 @register.simple_tag
 def choose_fragment(book=None, tag_ids=None):
     if book is not None:
index af3659f..9ea0c1c 100644 (file)
@@ -90,7 +90,3 @@ def get_fixture(path, app=None):
         mod_path = extract_stack(limit=2)[0][0]
         f_path = join(dirname(abspath(mod_path)), 'files', path)
     return f_path
         mod_path = extract_stack(limit=2)[0][0]
         f_path = join(dirname(abspath(mod_path)), 'files', path)
     return f_path
-
-
-def get_mp3_length(path):
-    return 60
index c2a5e0a..c2961d7 100644 (file)
@@ -49,21 +49,3 @@ class BookMediaTests(WLTestCase):
 
         utils.remove_zip('test-zip-slug')
         self.assertFalse(exists(join(settings.MEDIA_ROOT, url)))
 
         utils.remove_zip('test-zip-slug')
         self.assertFalse(exists(join(settings.MEDIA_ROOT, url)))
-
-    def test_remove_zip_on_media_change(self):
-        bm = models.BookMedia(book=self.book, type='ogg', name="Title")
-        self.set_title(bm.name)
-        bm.file.save(None, self.file)
-        bm.save()
-
-        zip_url = self.book.zip_audiobooks('ogg')
-        self.assertEqual('zip/'+self.book.slug+'_ogg.zip', zip_url)
-        self.assertTrue(exists(join(settings.MEDIA_ROOT, zip_url)))
-
-        bm2 = models.BookMedia(book=self.book, type='ogg', name="Other title")
-        self.set_title(bm2.name)
-        bm2.file.save(None, self.file2)
-        self.set_title("Title")
-        bm2.save()
-        # was the audiobook zip deleted?
-        self.assertFalse(exists(join(settings.MEDIA_ROOT, zip_url)))
index 37b298d..59331e9 100644 (file)
@@ -47,9 +47,9 @@ urlpatterns = [
     path('pobierz/<key>/<slug:slug>.<slug:format_>', views.embargo_link, name='embargo_link'),
 
     # zip
     path('pobierz/<key>/<slug:slug>.<slug:format_>', views.embargo_link, name='embargo_link'),
 
     # zip
-    path('zip/pdf.zip', views.download_zip, {'file_format': 'pdf', 'slug': None}, 'download_zip_pdf'),
-    path('zip/epub.zip', views.download_zip, {'file_format': 'epub', 'slug': None}, 'download_zip_epub'),
-    path('zip/mobi.zip', views.download_zip, {'file_format': 'mobi', 'slug': None}, 'download_zip_mobi'),
+    path('zip/pdf.zip', views.download_zip, {'file_format': 'pdf'}, 'download_zip_pdf'),
+    path('zip/epub.zip', views.download_zip, {'file_format': 'epub'}, 'download_zip_epub'),
+    path('zip/mobi.zip', views.download_zip, {'file_format': 'mobi'}, 'download_zip_mobi'),
     path('zip/<slug:slug>_mp3.zip', views.stream_zip, {'media_format': 'mp3'}, 'download_zip_mp3'),
     path('zip/<slug:slug>_ogg.zip', views.stream_zip, {'media_format': 'ogg'}, 'download_zip_ogg'),
 
     path('zip/<slug:slug>_mp3.zip', views.stream_zip, {'media_format': 'mp3'}, 'download_zip_mp3'),
     path('zip/<slug:slug>_ogg.zip', views.stream_zip, {'media_format': 'ogg'}, 'download_zip_ogg'),
 
index e6e567b..2469d6c 100644 (file)
@@ -17,7 +17,6 @@ from zipfile import ZipFile
 from django.apps import apps
 from django.conf import settings
 from django.core.files.storage import DefaultStorage
 from django.apps import apps
 from django.conf import settings
 from django.core.files.storage import DefaultStorage
-from django.core.files.uploadedfile import UploadedFile
 from django.http import HttpResponse
 from django.utils.encoding import force_str
 
 from django.http import HttpResponse
 from django.utils.encoding import force_str
 
@@ -61,19 +60,6 @@ def split_tags(*tag_lists):
     return result
 
 
     return result
 
 
-class ExistingFile(UploadedFile):
-
-    def __init__(self, path, *args, **kwargs):
-        self.path = path
-        super(ExistingFile, self).__init__(*args, **kwargs)
-
-    def temporary_file_path(self):
-        return self.path
-
-    def close(self):
-        pass
-
-
 class LockFile(object):
     """
     A file lock monitor class; createas an ${objname}.lock
 class LockFile(object):
     """
     A file lock monitor class; createas an ${objname}.lock
@@ -325,11 +311,6 @@ def absolute_url(url):
     return urljoin(base_url, url)
 
 
     return urljoin(base_url, url)
 
 
-def get_mp3_length(path):
-    from mutagen.mp3 import MP3
-    return int(MP3(path).info.length)
-
-
 def set_file_permissions(self, fieldfile):
     if fieldfile.instance.preview:
         fieldfile.set_readable(False)
 def set_file_permissions(self, fieldfile):
     if fieldfile.instance.preview:
         fieldfile.set_readable(False)
index 45c2485..ebe9921 100644 (file)
@@ -32,7 +32,7 @@ from catalogue import forms
 from catalogue.helpers import get_top_level_related_tags
 from catalogue.models import Book, Collection, Tag, Fragment
 from catalogue.models.tag import TagRelation
 from catalogue.helpers import get_top_level_related_tags
 from catalogue.models import Book, Collection, Tag, Fragment
 from catalogue.models.tag import TagRelation
-from catalogue.utils import split_tags
+from catalogue.utils import split_tags, iter_file
 from catalogue.models.tag import prefetch_relations
 
 staff_required = user_passes_test(lambda user: user.is_staff)
 from catalogue.models.tag import prefetch_relations
 
 staff_required = user_passes_test(lambda user: user.is_staff)
@@ -507,14 +507,8 @@ def embargo_link(request, key, format_, slug):
     return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
 
 
     return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
 
 
-def download_zip(request, file_format=None, media_format=None, slug=None):
-    if file_format:
-        url = Book.zip_format(file_format)
-    elif media_format and slug is not None:
-        book = get_object_or_404(Book, slug=slug)
-        url = book.zip_audiobooks(media_format)
-    else:
-        raise Http404('No format specified for zip package')
+def download_zip(request, file_format):
+    url = Book.zip_format(file_format)
     return HttpResponseRedirect(quote_plus(settings.MEDIA_URL + url, safe='/?='))
 
 
     return HttpResponseRedirect(quote_plus(settings.MEDIA_URL + url, safe='/?='))
 
 
@@ -523,7 +517,7 @@ def stream_zip(request, media_format=None, slug=None):
     def iterate_audiobooks(book, names):
         for bm in book.media.filter(type=media_format).order_by('index'):
             yield (
     def iterate_audiobooks(book, names):
         for bm in book.media.filter(type=media_format).order_by('index'):
             yield (
-                bm.file,
+                bm,
                 bm.get_extra_info_json().get('license'),
                 names + (slugify(bm.part_name),) if bm.part_name else names
             )
                 bm.get_extra_info_json().get('license'),
                 names + (slugify(bm.part_name),) if bm.part_name else names
             )
@@ -535,17 +529,17 @@ def stream_zip(request, media_format=None, slug=None):
     audiobook_list = list(iterate_audiobooks(book, ()))
     
     licenses = set()
     audiobook_list = list(iterate_audiobooks(book, ()))
     
     licenses = set()
-    for i, (bmfile, lic, names) in enumerate(audiobook_list):
+    for i, (bm, lic, names) in enumerate(audiobook_list):
         index = i + 1
         part_name = '_'.join(names)
         if part_name:
             part_name = '_' + part_name
         index = i + 1
         part_name = '_'.join(names)
         if part_name:
             part_name = '_' + part_name
-        ext = bmfile.name.rsplit('.', 1)[-1]
+        ext = bm.file.name.rsplit('.', 1)[-1]
         if len(audiobook_list) > 1:
             zip_name = f'{book.slug}_{index:03d}{part_name}'[:240] + '.' + ext
         else:
             zip_name = book.slug[:240] + '.' + ext
         if len(audiobook_list) > 1:
             zip_name = f'{book.slug}_{index:03d}{part_name}'[:240] + '.' + ext
         else:
             zip_name = book.slug[:240] + '.' + ext
-        zs.add(iter_file(bmfile), zip_name)
+        zs.add(iter_file(bm.file), zip_name, size=bm.file_size)
 
         lic_name = constants.LICENSES.get(lic, {}).get('locative')
         if lic_name:
 
         lic_name = constants.LICENSES.get(lic, {}).get('locative')
         if lic_name:
index 3862c5c..023ee41 100644 (file)
@@ -220,7 +220,7 @@ class AcquisitionFeed(Feed):
         if book.has_mp3_file():
             e = Enclosure(
                 url=full_url(reverse('download_zip_mp3', args=[book.slug])),
         if book.has_mp3_file():
             e = Enclosure(
                 url=full_url(reverse('download_zip_mp3', args=[book.slug])),
-                length=sum(bm.file.size for bm in book.get_media('mp3')),
+                length=sum(bm.file_size for bm in book.get_media('mp3')),
                 mime_type="application/zip"
             )
             e.indirect = 'audio/mpeg'
                 mime_type="application/zip"
             )
             e.indirect = 'audio/mpeg'
index 22c0e52..5dae96b 100644 (file)
@@ -16,7 +16,7 @@ from reporting.utils import render_to_pdf, render_to_csv, generated_file_view
 def stats_page(request):
     media_types = BookMedia.objects.values('type').annotate(count=Count('type')).order_by('type')
     for mt in media_types:
 def stats_page(request):
     media_types = BookMedia.objects.values('type').annotate(count=Count('type')).order_by('type')
     for mt in media_types:
-        mt['size'] = sum(b.file.size for b in BookMedia.objects.filter(type=mt['type']).iterator())
+        mt['size'] = sum(b.file_size for b in BookMedia.objects.filter(type=mt['type']).iterator())
         if mt['type'] in ('mp3', 'ogg'):
             deprecated = BookMedia.objects.filter(type=mt['type'], source_sha1=None)
             mt['deprecated'] = deprecated.count()
         if mt['type'] in ('mp3', 'ogg'):
             deprecated = BookMedia.objects.filter(type=mt['type'], source_sha1=None)
             mt['deprecated'] = deprecated.count()
index 21a1ba5..7845674 100644 (file)
@@ -4,7 +4,6 @@
 from wolnelektury.settings import *
 
 THUMBNAIL_BACKEND = 'wolnelektury.test_utils.DummyThumbnailBackend'
 from wolnelektury.settings import *
 
 THUMBNAIL_BACKEND = 'wolnelektury.test_utils.DummyThumbnailBackend'
-CATALOGUE_GET_MP3_LENGTH = 'catalogue.test_utils.get_mp3_length'
 MEDIA_URL = '/media/'
 
 CACHES = {
 MEDIA_URL = '/media/'
 
 CACHES = {
diff --git a/src/wolnelektury/static/js/current.js b/src/wolnelektury/static/js/current.js
deleted file mode 100644 (file)
index e963dd2..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-(function($){
-    $(function() {
-
-
-        if (Modernizr.localstorage) {
-            try {
-                audiobooks = JSON.parse(localStorage["audiobook-history"]);
-            } catch {
-                audiobooks = {};
-            }
-
-            latest = [];
-            Object.keys(audiobooks).forEach(function(slug) {
-                [ts, media_id, time] = audiobooks[slug];
-                latest.push([ts, slug]);
-            });
-            latest.sort().reverse().forEach(function(item) {
-                [ts, slug] = item;
-                $newitem = $('<div style="display:inline-block;"></div>');  // remove from history
-                $("#last-audiobooks").append($newitem);
-                (function($box) {
-                    $.get(
-                        "/katalog/lektura/" + slug + "/mini_box.html",
-                        function(data) {
-                            console.log(data);
-                            $box.html(data);
-                            $("#personal-history").slideDown("slow");
-                        }).fail(function() {
-                            $box.remove();
-                        });
-                })($newitem);
-            });
-        }
-    });
-})(jQuery);