Self hosted FLOSS fitness/workout, nutrition and weight tracker
Move exercise media when they are transferred during the deletion process
Roland Geiderec8b03de27ae
diff --git a/wger/exercises/models/base.py b/wger/exercises/models/base.pyindex 03f21773e..346db35c9 100644--- a/wger/exercises/models/base.py+++ b/wger/exercises/models/base.py@@ -18,8 +18,10 @@import datetimeimport uuidfrom typing import (+ Callable,List,Optional,+ Type,)# Django@@ -57,6 +59,34 @@ from .equipment import Equipmentfrom .muscle import Muscle+def _relocate_media_files(+ model: Type[models.Model],+ pks: List[int],+ field_name: str,+ upload_to: Callable,+) -> None:+ """+ Move each media file to the path that ``upload_to`` computes for its (already+ reassigned) exercise, then update the stored name+ """++ for obj in model.objects.filter(pk__in=pks):+ field = getattr(obj, field_name)+ old_name = field.name+ if not old_name:+ continue++ target = upload_to(obj, old_name)+ storage = field.storage+ if target == old_name or not storage.exists(old_name):+ continue++ with storage.open(old_name) as media_file:+ new_name = storage.save(target, media_file)+ storage.delete(old_name)+ model.objects.filter(pk=obj.pk).update(**{field_name: new_name})++class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):"""Model for an exercise base@@ -269,9 +299,15 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):"""# wgerfrom wger.exercises.models import DeletionLog- from wger.exercises.models.image import ExerciseImage+ from wger.exercises.models.image import (+ ExerciseImage,+ exercise_image_upload_dir,+ )from wger.exercises.models.translation import Translation- from wger.exercises.models.video import ExerciseVideo+ from wger.exercises.models.video import (+ ExerciseVideo,+ exercise_video_upload_dir,+ )from wger.manager.helpers import reset_routine_cachefrom wger.manager.models import (Routine,@@ -329,8 +365,29 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):reset_routine_cache(routine)if transfer_media:- ExerciseImage.objects.filter(exercise=self).update(exercise=replacement)- ExerciseVideo.objects.filter(exercise=self).update(exercise=replacement)+ image_pks = list(+ ExerciseImage.objects.filter(exercise=self).values_list('pk', flat=True)+ )+ video_pks = list(+ ExerciseVideo.objects.filter(exercise=self).values_list('pk', flat=True)+ )+ ExerciseImage.objects.filter(pk__in=image_pks).update(exercise=replacement)+ ExerciseVideo.objects.filter(pk__in=video_pks).update(exercise=replacement)++ # Move the underlying files so their path (keyed on the exercise+ # id) matches the new owner. Deferred to on_commit because the+ # file operations are not part of this transaction so if the delete+ # rolls back, no file is touched.+ transaction.on_commit(+ lambda: _relocate_media_files(+ ExerciseImage, image_pks, 'image', exercise_image_upload_dir+ )+ )+ transaction.on_commit(+ lambda: _relocate_media_files(+ ExerciseVideo, video_pks, 'video', exercise_video_upload_dir+ )+ )if transfer_translations:existing_languages = Translation.objects.filter(diff --git a/wger/exercises/tests/test_deletion_log.py b/wger/exercises/tests/test_deletion_log.pyindex 6a541f390..cce26a52a 100644--- a/wger/exercises/tests/test_deletion_log.py+++ b/wger/exercises/tests/test_deletion_log.py@@ -18,6 +18,7 @@ from uuid import UUID# Djangofrom django.core.cache import cache+from django.core.files import File# wgerfrom wger.core.tests.base_testcase import WgerTestCase@@ -198,6 +199,35 @@ class DeletionLogTestCase(WgerTestCase):self.assertEqual(ExerciseImage.objects.filter(exercise=replacement).count(), 1)self.assertEqual(ExerciseVideo.objects.filter(exercise=replacement).count(), 1)+ def test_exercise_replace_by_transfers_media_moves_the_file(self):+ """+ When media is transferred, the underlying file is physically moved so its+ stored path reflects the new owner, not just the database reference.+ """+ exercise_to_delete = Exercise.objects.get(pk=1)+ replacement = Exercise.objects.get(pk=2)++ image = ExerciseImage(exercise=exercise_to_delete)+ with open('wger/exercises/tests/protestschwein.jpg', 'rb') as raw:+ image.image.save('protestschwein.jpg', File(raw))+ image.save()+ storage = image.image.storage+ old_name = image.image.name+ self.addCleanup(storage.delete, old_name)+ self.assertIn(f'exercise-images/{exercise_to_delete.id}/', old_name)+ self.assertTrue(storage.exists(old_name))++ with self.captureOnCommitCallbacks(execute=True):+ exercise_to_delete.delete(replace_by=str(replacement.uuid), transfer_media=True)++ image.refresh_from_db()+ new_name = image.image.name+ self.addCleanup(storage.delete, new_name)+ self.assertIn(f'exercise-images/{replacement.id}/', new_name)+ self.assertNotEqual(new_name, old_name)+ self.assertTrue(storage.exists(new_name))+ self.assertFalse(storage.exists(old_name))+def test_exercise_replace_by_transfers_translations_in_missing_languages(self):"""Test that translations of the deleted exercise whose language is not