diff --git a/fragdenstaat_de/fds_cms/apps.py b/fragdenstaat_de/fds_cms/apps.py index 6fc798126..069beade1 100644 --- a/fragdenstaat_de/fds_cms/apps.py +++ b/fragdenstaat_de/fds_cms/apps.py @@ -1,18 +1,5 @@ -import logging -from io import BytesIO - from django.apps import AppConfig from django.conf import settings -from django.core.files.base import ContentFile - -from PIL import Image - -try: - import pillow_avif # noqa -except ImportError: - pillow_avif = None - -logger = logging.getLogger(__name__) class FdsCmsConfig(AppConfig): @@ -26,7 +13,7 @@ def ready(self): account_merged.connect(merge_user) - if pillow_avif is not None and settings.FDS_THUMBNAIL_ENABLE_AVIF: + if settings.FDS_THUMBNAIL_ENABLE_AVIF: from easy_thumbnails.signals import thumbnail_created thumbnail_created.connect(store_as_avif) @@ -41,12 +28,7 @@ def merge_user(sender, old_user=None, new_user=None, **kwargs): def store_as_avif(sender, **kwargs): if not sender.name.endswith((".png", ".jpg", ".jpeg")): return - logger.info("Converting %s to avif", sender.name) - avif_name = ".".join([sender.name, "avif"]) - img_file = sender.storage.open(sender.name, "rb") - im = Image.open(img_file) - out_file = BytesIO() - im.save(out_file, format="avif", quality=80) - out_file.seek(0) - sender.storage.save(avif_name, ContentFile(out_file.read())) - logger.info("Done converting %s to avif", sender.name) + + from .tasks import generate_avif_thumbnail + + generate_avif_thumbnail.delay(sender.name, sender.storage) diff --git a/fragdenstaat_de/fds_cms/tasks.py b/fragdenstaat_de/fds_cms/tasks.py index e8f44e162..be803333b 100644 --- a/fragdenstaat_de/fds_cms/tasks.py +++ b/fragdenstaat_de/fds_cms/tasks.py @@ -1,5 +1,18 @@ +import logging +from io import BytesIO + +from django.core.files.base import ContentFile + from celery import shared_task from easy_thumbnails.files import generate_all_aliases +from PIL import Image + +try: + import pillow_avif # noqa +except ImportError: + pillow_avif = None + +logger = logging.getLogger(__name__) @shared_task @@ -7,3 +20,18 @@ def generate_thumbnails(model, pk, field): instance = model._default_manager.get(pk=pk) fieldfile = getattr(instance, field) generate_all_aliases(fieldfile, include_global=True) + + +@shared_task +def generate_avif_thumbnail(filepath: str, storage): + if pillow_avif is None: + return + logger.info("Converting %s to avif", filepath) + avif_path = storage.path(".".join([filepath, "avif"])) + img_file = storage.open(filepath, "rb") + im = Image.open(img_file) + out_file = BytesIO() + im.save(out_file, format="avif", quality=80) + out_file.seek(0) + storage.save(avif_path, ContentFile(out_file.read())) + logger.info("Done converting %s to avif", filepath)