Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Fill exercise license author with the username

Roland Geider80b6ae16857d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9469d787d..3b99d890e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,9 @@ Progression requirements can now reference the top of the prescribed range via t
writing, and can be filtered by `metric_type` and `external_id`. Integrations
such as scale apps no longer have to look up their category first or keep
track of the ids of the entries they wrote.
+* Exercise contributions always have an author: if none is given, the username
+ is used. Everyone who edits an exercise or translation is credited as an
+ author, images and videos keep the author of the file.
### Bug fixes
diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py
index c20900b5b..e2649acc0 100644
--- a/wger/exercises/api/serializers.py
+++ b/wger/exercises/api/serializers.py
@@ -80,6 +80,34 @@ def _log_action_creation(serializer, instance):
)
+class LicenseAuthorDefaultMixin:
+ """
+ Stores the username as license author when none is given.
+
+ On create a missing or empty author is replaced. On update this depends on
+ ``credit_editor``: if set, every edit stores the editor unless a non-empty
+ author is sent, so the editor ends up in ``author_history``. If not set
+ (media, where the author is the creator of the file), only an explicitly
+ empty author is replaced and omitting it keeps the stored one.
+ """
+
+ credit_editor = False
+
+ def to_internal_value(self, data):
+ attrs = super().to_internal_value(data)
+
+ request = self.context.get('request')
+ user = getattr(request, 'user', None)
+ if user is None or not user.is_authenticated:
+ return attrs
+
+ replace_missing = self.instance is None or self.credit_editor
+ author = attrs.get('license_author', '')
+ if (replace_missing or 'license_author' in attrs) and not author.strip():
+ attrs['license_author'] = user.username
+ return attrs
+
+
def _normalise_name(name: str) -> str:
"""
Regex: matches space, hyphen and underscore, and replaces with an empty string.
@@ -122,11 +150,13 @@ def _check_duplicates(name, language, exclude_pk=None):
return candidate.name
-class ExerciseSerializer(serializers.ModelSerializer):
+class ExerciseSerializer(LicenseAuthorDefaultMixin, serializers.ModelSerializer):
"""
Exercise serializer
"""
+ credit_editor = True
+
class Meta:
model = Exercise
fields = (
@@ -193,7 +223,7 @@ class AbsoluteUrlFileField(serializers.FileField):
return make_absolute_url(value.url, self.context.get('request'))
-class ExerciseImageSerializer(serializers.ModelSerializer):
+class ExerciseImageSerializer(LicenseAuthorDefaultMixin, serializers.ModelSerializer):
"""
ExerciseImage serializer
"""
@@ -247,7 +277,7 @@ class ExerciseImageSerializer(serializers.ModelSerializer):
return result
-class ExerciseVideoSerializer(serializers.ModelSerializer):
+class ExerciseVideoSerializer(LicenseAuthorDefaultMixin, serializers.ModelSerializer):
"""
ExerciseVideo serializer
"""
@@ -445,11 +475,13 @@ class ExerciseTranslationInfoSerializer(serializers.ModelSerializer):
)
-class ExerciseTranslationSerializer(serializers.ModelSerializer):
+class ExerciseTranslationSerializer(LicenseAuthorDefaultMixin, serializers.ModelSerializer):
"""
Exercise translation serializer
"""
+ credit_editor = True
+
id = serializers.IntegerField(required=False, read_only=True)
uuid = serializers.UUIDField(required=False, read_only=True)
exercise = serializers.PrimaryKeyRelatedField(
@@ -687,7 +719,7 @@ def get_default_license() -> License:
return License.objects.get(pk=CC_BY_SA_4_LICENSE_ID)
-class ExerciseSubmissionSerializer(serializers.ModelSerializer):
+class ExerciseSubmissionSerializer(LicenseAuthorDefaultMixin, serializers.ModelSerializer):
"""
Exercise submission serializer
"""
diff --git a/wger/exercises/tests/api/test_exercise_submission_api.py b/wger/exercises/tests/api/test_exercise_submission_api.py
index 1a0c6ec6b..02b9de9e3 100644
--- a/wger/exercises/tests/api/test_exercise_submission_api.py
+++ b/wger/exercises/tests/api/test_exercise_submission_api.py
@@ -298,3 +298,46 @@ class ExerciseSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
# Nothing was created (the create runs in a transaction)
self.assertEqual(before, after)
+
+ def _submit_with_authors(self, **author):
+ """Submit with the given license author on the exercise and every translation"""
+ self.authenticate('admin')
+
+ payload = self.get_payload()
+ for obj in (payload, *payload['translations']):
+ obj.pop('license_author')
+ obj.update(author)
+
+ response = self.client.post(self.url, data=payload)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ return Exercise.objects.get(pk=response.json()['id'])
+
+ def test_submission_without_license_author_uses_username(self):
+ """Exercise and translations get the username when no author is sent"""
+ exercise = self._submit_with_authors()
+
+ self.assertEqual(exercise.license_author, 'admin')
+ self.assertEqual(
+ set(exercise.translations.values_list('license_author', flat=True)),
+ {'admin'},
+ )
+
+ def test_submission_with_empty_license_author_uses_username(self):
+ """Exercise and translations get the username when the author is empty"""
+ exercise = self._submit_with_authors(license_author='')
+
+ self.assertEqual(exercise.license_author, 'admin')
+ self.assertEqual(
+ set(exercise.translations.values_list('license_author', flat=True)),
+ {'admin'},
+ )
+
+ def test_submission_keeps_license_author(self):
+ """An author that is sent is stored as is"""
+ exercise = self._submit_with_authors(license_author='Jane Doe')
+
+ self.assertEqual(exercise.license_author, 'Jane Doe')
+ self.assertEqual(
+ set(exercise.translations.values_list('license_author', flat=True)),
+ {'Jane Doe'},
+ )
diff --git a/wger/exercises/tests/api_mixins.py b/wger/exercises/tests/api_mixins.py
index 9b6c53ae3..ac907b982 100644
--- a/wger/exercises/tests/api_mixins.py
+++ b/wger/exercises/tests/api_mixins.py
@@ -72,3 +72,70 @@ class ActstreamUpdateMixin(_ActstreamMixinBase):
class ActstreamApiMixin(ActstreamCreateMixin, ActstreamUpdateMixin):
"""Covers both create and update — for endpoints supporting POST + PATCH."""
+
+
+class LicenseAuthorCreateMixin:
+ """POSTing ``self.data`` without an author stores the username as license author."""
+
+ def _post_with_author(self, **author):
+ self.authenticate('admin')
+ response = self.client.post(self.url, data={**self.data, **author})
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ return self.resource.objects.get(pk=response.json()['id'])
+
+ def test_license_author_defaults_to_username_on_create(self):
+ self.assertEqual(self._post_with_author().license_author, 'admin')
+
+ def test_empty_license_author_becomes_username_on_create(self):
+ self.assertEqual(self._post_with_author(license_author='').license_author, 'admin')
+
+ def test_license_author_is_kept_on_create(self):
+ obj = self._post_with_author(license_author='Jane Doe')
+ self.assertEqual(obj.license_author, 'Jane Doe')
+
+
+class LicenseAuthorUpdateMixin:
+ """PATCHing an empty author stores the username, omitting it keeps the stored one."""
+
+ patch_format = 'json'
+
+ def test_empty_license_author_becomes_username_on_update(self):
+ self.authenticate('admin')
+ response = self.client.patch(
+ self.url_detail,
+ data={'license_author': ''},
+ format=self.patch_format,
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(self.resource.objects.get(pk=self.pk).license_author, 'admin')
+
+ def test_license_author_unchanged_on_update_without_it(self):
+ self.resource.objects.filter(pk=self.pk).update(license_author='Jane Doe')
+ self.authenticate('admin')
+ response = self.client.patch(self.url_detail, data=self.data, format=self.patch_format)
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(self.resource.objects.get(pk=self.pk).license_author, 'Jane Doe')
+
+
+class LicenseAuthorEditorMixin:
+ """PATCHing without a non-empty author stores the editor, a sent author is kept."""
+
+ def _patch_author(self, data):
+ self.resource.objects.filter(pk=self.pk).update(license_author='Jane Doe')
+ self.authenticate('admin')
+ response = self.client.patch(self.url_detail, data=data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ return self.resource.objects.get(pk=self.pk).license_author
+
+ def test_editor_becomes_license_author_on_update(self):
+ self.assertEqual(self._patch_author(self.data), 'admin')
+
+ def test_empty_license_author_becomes_editor_on_update(self):
+ self.assertEqual(self._patch_author({**self.data, 'license_author': ''}), 'admin')
+
+ def test_license_author_is_kept_on_update(self):
+ self.assertEqual(self._patch_author({**self.data, 'license_author': 'Max'}), 'Max')
+
+
+class LicenseAuthorApiMixin(LicenseAuthorCreateMixin, LicenseAuthorEditorMixin):
+ """Create and editor credit, for exercises and translations (POST + PATCH)."""
diff --git a/wger/exercises/tests/test_exercise.py b/wger/exercises/tests/test_exercise.py
index e46ddc413..27add79f4 100644
--- a/wger/exercises/tests/test_exercise.py
+++ b/wger/exercises/tests/test_exercise.py
@@ -26,7 +26,10 @@ from wger.exercises.models import (
Exercise,
Translation,
)
-from wger.exercises.tests.api_mixins import ActstreamApiMixin
+from wger.exercises.tests.api_mixins import (
+ ActstreamApiMixin,
+ LicenseAuthorApiMixin,
+)
from wger.utils.constants import CC_BY_SA_4_LICENSE_ID
@@ -98,7 +101,11 @@ class ExerciseTestCase(WgerTestCase):
)
-class ExerciseCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTestCase):
+class ExerciseCustomApiTestCase(
+ ActstreamApiMixin,
+ LicenseAuthorApiMixin,
+ ExerciseCrudApiTestCase,
+):
pk = 1
resource = Exercise
diff --git a/wger/exercises/tests/test_exercise_images.py b/wger/exercises/tests/test_exercise_images.py
index 10b0375fe..8b03ef27d 100644
--- a/wger/exercises/tests/test_exercise_images.py
+++ b/wger/exercises/tests/test_exercise_images.py
@@ -17,6 +17,9 @@ from django.core.files import File
from django.test import SimpleTestCase
from django.urls import reverse
+# Third Party
+from rest_framework import status
+
# wger
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import WgerTestCase
@@ -25,7 +28,10 @@ from wger.exercises.models import (
ExerciseImage,
Translation,
)
-from wger.exercises.tests.api_mixins import ActstreamUpdateMixin
+from wger.exercises.tests.api_mixins import (
+ ActstreamUpdateMixin,
+ LicenseAuthorUpdateMixin,
+)
class MainImageTestCase(WgerTestCase):
@@ -253,6 +259,7 @@ class ExerciseImageThumbnailsApiTestCase(WgerTestCase):
# TODO: add POST and DELETE tests
class ExerciseImagesApiTestCase(
ActstreamUpdateMixin,
+ LicenseAuthorUpdateMixin,
api_base_test.BaseTestCase,
api_base_test.ApiBaseTestCase,
api_base_test.ApiGetTestCase,
@@ -267,3 +274,18 @@ class ExerciseImagesApiTestCase(
overview_cached = True
data = {'is_main': True}
patch_format = 'multipart'
+
+ def test_upload_without_license_author_uses_username(self):
+ """An image uploaded without author gets the username"""
+ self.authenticate('admin')
+ with open('wger/exercises/tests/protestschwein.jpg', 'rb') as image:
+ response = self.client.post(
+ self.url,
+ data={'exercise': 1, 'image': image, 'license_author': ''},
+ format='multipart',
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(
+ ExerciseImage.objects.get(pk=response.json()['id']).license_author, 'admin'
+ )
diff --git a/wger/exercises/tests/test_exercise_translation.py b/wger/exercises/tests/test_exercise_translation.py
index e9f70f8bb..8419456a7 100644
--- a/wger/exercises/tests/test_exercise_translation.py
+++ b/wger/exercises/tests/test_exercise_translation.py
@@ -25,7 +25,10 @@ from wger.exercises.models import (
Muscle,
Translation,
)
-from wger.exercises.tests.api_mixins import ActstreamApiMixin
+from wger.exercises.tests.api_mixins import (
+ ActstreamApiMixin,
+ LicenseAuthorApiMixin,
+)
from wger.utils.constants import (
CC_0_LICENSE_ID,
CC_BY_SA_4_LICENSE_ID,
@@ -129,7 +132,11 @@ class ExerciseInfoApiTestCase(
return 'exerciseinfo'
-class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTestCase):
+class ExerciseTranslationCustomApiTestCase(
+ ActstreamApiMixin,
+ LicenseAuthorApiMixin,
+ ExerciseCrudApiTestCase,
+):
pk = 1
resource = Translation
diff --git a/wger/exercises/tests/test_exercise_videos.py b/wger/exercises/tests/test_exercise_videos.py
index 29c3bada6..4b11b33cc 100644
--- a/wger/exercises/tests/test_exercise_videos.py
+++ b/wger/exercises/tests/test_exercise_videos.py
@@ -28,7 +28,10 @@ from django.urls import reverse
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import WgerTestCase
from wger.exercises.models import ExerciseVideo
-from wger.exercises.tests.api_mixins import ActstreamUpdateMixin
+from wger.exercises.tests.api_mixins import (
+ ActstreamUpdateMixin,
+ LicenseAuthorUpdateMixin,
+)
HTML_PAYLOAD = b'<!DOCTYPE html><script>document.title = "xss"</script>'
@@ -112,6 +115,7 @@ class ExerciseVideoUploadTestCase(WgerTestCase):
# TODO: add POST and DELETE tests
class ExerciseVideosApiTestCase(
ActstreamUpdateMixin,
+ LicenseAuthorUpdateMixin,
api_base_test.BaseTestCase,
api_base_test.ApiBaseTestCase,
api_base_test.ApiGetTestCase,
diff --git a/wger/version.py b/wger/version.py
index 6bc604c51..fae52e9dd 100644
--- a/wger/version.py
+++ b/wger/version.py
@@ -35,7 +35,7 @@ Always use versions in the x.y.z format, without any suffixes like "beta1" or su
MIN_SERVER_VERSION = Version('2.5.0')
"""Minimum version of the server required to run sync commands on this server"""
-VERSION_STRING = '2.8.0-dev.2'
+VERSION_STRING = '2.8.0-dev.3'
"""
Current version of the app.