diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py index b2bbb0bd7..9a72c17a0 100644 --- a/wger/exercises/api/serializers.py +++ b/wger/exercises/api/serializers.py @@ -13,16 +13,20 @@ # You should have received a copy of the GNU Affero General Public License # Standard Library +import re import uuid +from difflib import SequenceMatcher # Django from django.conf import settings +from django.contrib.postgres.search import TrigramSimilarity from django.core.cache import cache from django.db import ( models, transaction, ) from django.db.models import Q +from django.db.models.functions import Length # Third Party from actstream import action as actstream_action @@ -48,9 +52,14 @@ from wger.exercises.models import ( from wger.exercises.views.helper import StreamVerbs from wger.utils.cache import CacheKeyMapper from wger.utils.constants import CC_BY_SA_4_LICENSE_ID +from wger.utils.db import is_postgres_db from wger.utils.url import make_absolute_url +# Configuration threshold +SIMILARITY_THRESHOLD = 0.85 + + def _log_action_creation(serializer, instance): """ Emit an actstream ``created`` event for a freshly-created instance. @@ -68,6 +77,48 @@ def _log_action_creation(serializer, instance): ) +def _normalise_name(name: str) -> str: + """ + Regex: matches space, hyphen and underscore, and replaces with an empty string. + """ + return re.sub(r'[\s\-_]+', '', name.strip().lower()) + + +def _check_duplicates(name, language, exclude_pk=None): + base_qs = Translation.objects.filter(language=language) + if exclude_pk: + base_qs = base_qs.exclude(pk=exclude_pk) + + # Trigram Similarity + if is_postgres_db(): + return ( + base_qs.annotate(similarity=TrigramSimilarity('name', name)) + .filter(similarity__gte=SIMILARITY_THRESHOLD) + .order_by('-similarity') + .values_list('name', flat=True) + .first() + ) + + norm_new = _normalise_name(name) + input_len = len(name) + + # Filter by length for exact match + candidates = base_qs.annotate(n_len=Length('name')).filter( + n_len__gte=input_len - 4, n_len__lte=input_len + 4 + ) + + # SequenceMatcher + for candidate in candidates: + if _normalise_name(candidate.name) == norm_new: + return candidate.name + + if ( + SequenceMatcher(None, norm_new, _normalise_name(candidate.name)).ratio() + >= SIMILARITY_THRESHOLD + ): + return candidate.name + + class ExerciseSerializer(serializers.ModelSerializer): """ Exercise serializer @@ -457,6 +508,24 @@ class ExerciseTranslationSerializer(serializers.ModelSerializer): if description and language: validate_language_matches(description, language, 'description') + # Check for duplicates, but only when the name is actually being + # changed since there are possibly near-duplicates in the existing db + name = value.get('name') + name_changed = not self.instance or _normalise_name(name or '') != _normalise_name( + self.instance.name + ) + if name and language and name_changed: + exclude_pk = self.instance.pk if self.instance else None + duplicate_hit = _check_duplicates(name, language, exclude_pk=exclude_pk) + if duplicate_hit: + raise serializers.ValidationError( + { + 'name': f'The name "{name}" is too similar to the existing exercise ' + f'"{duplicate_hit}". Please choose a more distinct name or submit ' + f'a variation instead.' + } + ) + return super().validate(value) diff --git a/wger/exercises/tests/api/test_create_throttle.py b/wger/exercises/tests/api/test_create_throttle.py index b4edac8cb..c771d59e7 100644 --- a/wger/exercises/tests/api/test_create_throttle.py +++ b/wger/exercises/tests/api/test_create_throttle.py @@ -41,14 +41,14 @@ class ExerciseCreateThrottleTestCase(BaseTestCase, ApiBaseTestCase): """ @staticmethod - def get_payload(): + def get_payload(name='Throttle Test Exercise'): return { 'category': 3, 'license': 5, 'license_author': 'tester', 'translations': [ { - 'name': 'Throttle Test Exercise', + 'name': name, 'description_source': ( 'A sufficiently long English description so the language ' 'detector recognises it and the minimum length passes.' @@ -97,7 +97,9 @@ class ExerciseCreateThrottleTestCase(BaseTestCase, ApiBaseTestCase): with mock.patch.dict(api_settings.DEFAULT_THROTTLE_RATES, {'exercise_create': '1/min'}): first = self.client.post(url, data=self.get_payload()) - second = self.client.post(url, data=self.get_payload()) + # A distinct name, otherwise the duplicate-name check would reject + # the second submission before the throttle exemption is exercised. + second = self.client.post(url, data=self.get_payload('Completely Different Movement')) self.assertEqual(first.status_code, status.HTTP_201_CREATED) self.assertEqual(second.status_code, status.HTTP_201_CREATED) diff --git a/wger/exercises/tests/test_exercise_translation.py b/wger/exercises/tests/test_exercise_translation.py index 65794c64e..ec7d3779c 100644 --- a/wger/exercises/tests/test_exercise_translation.py +++ b/wger/exercises/tests/test_exercise_translation.py @@ -21,6 +21,7 @@ from wger.core.tests.api_base_test import ExerciseCrudApiTestCase from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( Exercise, + ExerciseCategory, Muscle, Translation, ) @@ -398,3 +399,168 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes response = self.client.patch(self.url_detail, data={'language': 3}) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue(response.data['non_field_errors']) + + def test_post_rejects_structural_duplicate_name(self): + """ + Test that submitting a name structurally identical (ignoring spaces/hyphens) + to an existing exercise in the same language is rejected. + """ + category = ExerciseCategory.objects.first() + + exercise_a = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=exercise_a, + language_id=2, + name='Pull ups', + description_source='A base description for the duplicate name seed translation.', + ) + + exercise_b = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + + payload = { + 'name': 'Pull-ups', + 'description_source': 'A new description for the pullups duplicate test.', + 'exercise': exercise_b.pk, + 'language': 2, + } + + self.authenticate('trainer1') + response = self.client.post(self.url, data=payload) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn('name', response.json()) + self.assertIn('too similar', response.json()['name'][0]) + + def test_post_rejects_fuzzy_duplicate_name(self): + """ + Test that submitting a name that is only fuzzily similar to an existing + one in the same language is rejected. The names differ even after + normalisation (stripping spaces/hyphens leaves the trailing "s"), so + this exercises the similarity fallback rather than exact matching. + """ + category = ExerciseCategory.objects.first() + + exercise_a = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=exercise_a, + language_id=2, + name='Deadlift', + description_source='A base description for the deadlift seed translation.', + ) + + exercise_b = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + + payload = { + 'name': 'Deadlifts', # fuzzy duplicate (plural variant) + 'description_source': 'A new description for the deadlifts duplicate test.', + 'exercise': exercise_b.pk, + 'language': 2, + } + + self.authenticate('trainer1') + response = self.client.post(self.url, data=payload) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn('name', response.json()) + self.assertIn('too similar', response.json()['name'][0]) + + def test_patch_allows_self_edit_with_same_name(self): + """ + Test that editing an existing translation without changing its name + (or submitting the exact same name) does not trigger a duplicate error, + validating the `exclude_pk` logic. + """ + translation = Translation.objects.get(pk=self.pk) + original_name = translation.name + + self.authenticate('trainer1') + # passing the same name back + response = self.client.patch( + self.url_detail, + data={ + 'description_source': ( + 'A sufficiently long English description so the language ' + 'detector can reliably recognise it as English.' + ), + 'name': original_name, + }, + ) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_patch_rejects_conflict_with_other_name(self): + """ + Test that editing an existing translation's name to collide with + a DIFFERENT existing translation's name is rejected. + """ + other_exercise = Exercise.objects.create( + category=ExerciseCategory.objects.first(), + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=other_exercise, + language_id=2, + name='Barbell Squat', + description_source='Base description for barbell squat test.', + ) + + self.authenticate('trainer1') + response = self.client.patch( + self.url_detail, + data={'name': 'Barbell-Squat'}, # Structural duplicate + ) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn('name', response.json()) + + def test_patch_allows_edit_when_unchanged_name_collides_with_existing(self): + """ + Test that editing a translation without changing its name succeeds even + when another, pre-existing near-duplicate already lives in the database + """ + translation = Translation.objects.get(pk=self.pk) + + # Seed a near-duplicate of the edited translation in the same language + twin_exercise = Exercise.objects.create( + category=ExerciseCategory.objects.first(), + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=twin_exercise, + language_id=translation.language_id, + name=translation.name.replace(' ', '-'), + description_source='Base description for the pre-existing near-duplicate.', + ) + + self.authenticate('trainer1') + # Resubmit the unchanged name together with a new description + response = self.client.patch( + self.url_detail, + data={ + 'name': translation.name, + 'description_source': ( + 'A sufficiently long English description so the language ' + 'detector can reliably recognise it as English.' + ), + }, + ) + + self.assertEqual(response.status_code, status.HTTP_200_OK)