From 53b5c6261e5a0b6a10fe237a0b7bd269fa1bbc0b Mon Sep 17 00:00:00 2001 From: Agate Date: Sun, 23 Aug 2020 16:39:31 +0200 Subject: [PATCH] Delete existing thumbnails automatically when running --- api/funkwhale_api/cli/media.py | 13 ++++++++++++- api/funkwhale_api/common/storage.py | 12 ++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/api/funkwhale_api/cli/media.py b/api/funkwhale_api/cli/media.py index c50df6b77..2c23f8a75 100644 --- a/api/funkwhale_api/cli/media.py +++ b/api/funkwhale_api/cli/media.py @@ -2,6 +2,7 @@ import click from django.core.cache import cache from django.conf import settings +from django.core.files.storage import default_storage from versatileimagefield.image_warmer import VersatileImageFieldWarmer from versatileimagefield import settings as vif_settings @@ -19,13 +20,23 @@ def media(): @media.command("generate-thumbnails") -def generate_thumbnails(): +@click.option("-d", "--delete", is_flag=True) +def generate_thumbnails(delete): """ Generate thumbnails for all images (avatars, covers, etc.). This can take a long time and generate a lot of I/O depending of the size of your library. """ + click.echo("Deleting existing thumbnails…") + if delete: + try: + # FileSystemStorage doesn't support deleting a non-empty directory + # so we reimplemented a method to do so + default_storage.force_delete("__sized__") + except AttributeError: + # backends doesn't support directory deletion + pass MODELS = [ (Attachment, "file", "attachment_square"), ] diff --git a/api/funkwhale_api/common/storage.py b/api/funkwhale_api/common/storage.py index 07d6a7cc3..8959c6532 100644 --- a/api/funkwhale_api/common/storage.py +++ b/api/funkwhale_api/common/storage.py @@ -1,3 +1,5 @@ +import os +import shutil import slugify from django.core.files.storage import FileSystemStorage @@ -15,6 +17,16 @@ class ASCIIFileSystemStorage(FileSystemStorage): def get_valid_name(self, name): return super().get_valid_name(asciionly(name)) + def force_delete(self, name): + path = self.path(name) + try: + if os.path.isdir(path): + shutil.rmtree(path) + else: + return super().delete(name) + except FileNotFoundError: + pass + class ASCIIS3Boto3Storage(S3Boto3Storage): def get_valid_name(self, name):