diff --git a/boards/management/commands/cleanfiles.py b/boards/management/commands/cleanfiles.py deleted file mode 100644 --- a/boards/management/commands/cleanfiles.py +++ /dev/null @@ -1,36 +0,0 @@ -import os -from boards.abstracts.constants import FILE_DIRECTORY - -from django.core.management import BaseCommand -from django.db import transaction -from boards.models import Attachment - -from neboard.settings import MEDIA_ROOT - - -__author__ = 'neko259' - -THUMB_SIZE = (200, 150) - - -class Command(BaseCommand): - help = 'Remove files whose models were deleted' - - @transaction.atomic - def handle(self, *args, **options): - thumb_prefix = '.{}x{}'.format(*THUMB_SIZE) - - count = 0 - model_files = os.listdir(MEDIA_ROOT + FILE_DIRECTORY) - for file in model_files: - model_filename = file if thumb_prefix not in file else file.replace( - thumb_prefix, '') - found = Attachment.objects.filter(file=FILE_DIRECTORY + model_filename)\ - .exists() - - if not found: - print('Missing {}'.format(file)) - os.remove(MEDIA_ROOT + FILE_DIRECTORY + file) - count += 1 - - print('Deleted {} attachment files.'.format(count)) diff --git a/boards/signals.py b/boards/signals.py --- a/boards/signals.py +++ b/boards/signals.py @@ -1,4 +1,11 @@ import re +import os + +from django.db.models.signals import post_save, pre_save, pre_delete, \ + post_delete +from django.dispatch import receiver +from django.utils import timezone + from boards import thumbs from boards.mdx_neboard import get_parser @@ -8,10 +15,7 @@ from boards.models.post import REGEX_NOT REGEX_GLOBAL_REPLY from boards.models.post.manager import post_import_deps from boards.models.user import Notification -from django.db.models.signals import post_save, pre_save, pre_delete, \ - post_delete -from django.dispatch import receiver -from django.utils import timezone +from neboard.settings import MEDIA_ROOT THUMB_SIZES = ((200, 150),) @@ -113,3 +117,16 @@ def rebuild_refmap(instance, **kwargs): for referenced_post in instance.refposts.all(): referenced_post.build_refmap(excluded_ids=[instance.id]) referenced_post.save(update_fields=['refmap']) + + +@receiver(post_delete, sender=Attachment) +def delete_file(instance, **kwargs): + if instance.is_internal(): + file = MEDIA_ROOT + instance.file.name + os.remove(file) + if instance.mimetype in FILE_TYPES_IMAGE: + for size in THUMB_SIZES: + file_name_parts = instance.file.name.split('.') + thumb_file = MEDIA_ROOT + '{}.{}x{}.{}'.format(file_name_parts[0], *size, file_name_parts[1]) + os.remove(thumb_file) +