Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Always generate the absolute urls for exercise images and videos

Roland Geider48a9aa18dd49
diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py
index b9b421f8e..9971e3deb 100644
--- a/wger/exercises/api/serializers.py
+++ b/wger/exercises/api/serializers.py
@@ -13,13 +13,15 @@
# You should have received a copy of the GNU Affero General Public License
# Standard Library
-import logging
import uuid
# Django
from django.conf import settings
from django.core.cache import cache
-from django.db import transaction
+from django.db import (
+ models,
+ transaction,
+)
from django.db.models import Q
# Third Party
@@ -44,9 +46,7 @@ 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
-
-
-logger = logging.getLogger(__name__)
+from wger.utils.url import make_absolute_url
def _log_action_creation(serializer, instance):
@@ -113,11 +113,40 @@ class DeletionLogSerializer(serializers.ModelSerializer):
)
+class AbsoluteUrlImageField(serializers.ImageField):
+ """
+ ImageField whose representation is always an absolute URL.
+
+ DRF returns a host-less media path when the serializer has no request in
+ its context, which happens when the exercise cache is warmed by a celery
+ task. The SITE_URL fallback keeps the cached representation usable.
+ """
+
+ def to_representation(self, value):
+ if not value:
+ return None
+ return make_absolute_url(value.url, self.context.get('request'))
+
+
+class AbsoluteUrlFileField(serializers.FileField):
+ """FileField variant of AbsoluteUrlImageField, see there for details."""
+
+ def to_representation(self, value):
+ if not value:
+ return None
+ return make_absolute_url(value.url, self.context.get('request'))
+
+
class ExerciseImageSerializer(serializers.ModelSerializer):
"""
ExerciseImage serializer
"""
+ serializer_field_mapping = {
+ **serializers.ModelSerializer.serializer_field_mapping,
+ models.ImageField: AbsoluteUrlImageField,
+ }
+
author_history = serializers.ListSerializer(child=serializers.CharField(), read_only=True)
exercise_uuid = serializers.ReadOnlyField(source='exercise.uuid')
@@ -180,6 +209,11 @@ class ExerciseVideoInfoSerializer(serializers.ModelSerializer):
ExerciseVideo serializer for the info endpoint
"""
+ serializer_field_mapping = {
+ **serializers.ModelSerializer.serializer_field_mapping,
+ models.FileField: AbsoluteUrlFileField,
+ }
+
author_history = serializers.ListSerializer(child=serializers.CharField(), read_only=True)
class Meta:
@@ -289,26 +323,12 @@ class MuscleSerializer(serializers.ModelSerializer):
)
def get_image_url_main(self, obj: Muscle):
- """Build absolute URL to muscle image"""
-
- request = self.context.get('request')
- if request is not None:
- return request.build_absolute_uri(obj.image_url_main)
-
- # no host available
- logger.info('Cannot build absolute URL for main muscle image without request context')
- return None
+ """Absolute URL to the main muscle image"""
+ return make_absolute_url(obj.image_url_main, self.context.get('request'))
def get_image_url_secondary(self, obj: Muscle):
- """Build absolute URL to muscle image"""
-
- request = self.context.get('request')
- if request is not None:
- return request.build_absolute_uri(obj.image_url_secondary)
-
- # no host available
- logger.info('Cannot build absolute URL for secondary muscle image without request context')
- return None
+ """Absolute URL to the secondary muscle image"""
+ return make_absolute_url(obj.image_url_secondary, self.context.get('request'))
class ExerciseTranslationInfoSerializer(serializers.ModelSerializer):
diff --git a/wger/exercises/tests/test_cache.py b/wger/exercises/tests/test_cache.py
index 7903a6ae9..f9f16a96b 100644
--- a/wger/exercises/tests/test_cache.py
+++ b/wger/exercises/tests/test_cache.py
@@ -4,13 +4,20 @@ from unittest.mock import (
patch,
)
+# Django
+from django.test import override_settings
+
# wger
from wger.core.tests.base_testcase import WgerTestCase
+from wger.exercises.api.serializers import ExerciseInfoSerializer
from wger.exercises.cache import (
cache_api_exercises,
cache_exercise,
)
-from wger.exercises.models import Exercise
+from wger.exercises.models import (
+ Exercise,
+ ExerciseImage,
+)
class TestCacheExercise(WgerTestCase):
@@ -58,3 +65,35 @@ class TestCacheExercise(WgerTestCase):
cache_api_exercises(print_fn=output.append, force=True)
self.assertTrue(len(called_exercises) > 0)
+
+ @override_settings(SITE_URL='https://example.com')
+ def test_cached_media_urls_are_absolute(self):
+ """
+ Media URLs are absolute even when the serializer has no request.
+
+ The exercise cache is warmed by a celery task, which has no HTTP request
+ to build absolute URLs from. Without the SITE_URL fallback the cached
+ representation would carry host-less media paths.
+ """
+ exercise = ExerciseImage.objects.first().exercise
+
+ data = ExerciseInfoSerializer(exercise).data
+
+ self.assertTrue(data['images'], 'exercise needs at least one image')
+ for image in data['images']:
+ self.assertTrue(
+ image['image'].startswith('https://example.com/'),
+ f'Image URL is not absolute: {image["image"]}',
+ )
+
+ for video in data['videos']:
+ self.assertTrue(
+ video['video'].startswith('https://example.com/'),
+ f'Video URL is not absolute: {video["video"]}',
+ )
+
+ for muscle in data['muscles']:
+ self.assertTrue(
+ muscle['image_url_main'].startswith('https://example.com/'),
+ f'Muscle image URL is not absolute: {muscle["image_url_main"]}',
+ )
diff --git a/wger/utils/tests/test_url.py b/wger/utils/tests/test_url.py
index 9c25994d8..ea472784f 100644
--- a/wger/utils/tests/test_url.py
+++ b/wger/utils/tests/test_url.py
@@ -15,8 +15,17 @@
# Standard Library
import unittest
+# Django
+from django.test import (
+ RequestFactory,
+ override_settings,
+)
+
# wger
-from wger.utils.url import make_uri
+from wger.utils.url import (
+ make_absolute_url,
+ make_uri,
+)
class TestMakeUri(unittest.TestCase):
@@ -58,5 +67,25 @@ class TestMakeUri(unittest.TestCase):
)
+class TestMakeAbsoluteUrl(unittest.TestCase):
+ def test_with_request_uses_request_host(self):
+ request = RequestFactory().get('/')
+ self.assertEqual(
+ make_absolute_url('/media/exercise-images/foo.png', request),
+ 'http://testserver/media/exercise-images/foo.png',
+ )
+
+ def test_without_request_falls_back_to_site_url(self):
+ with override_settings(SITE_URL='https://example.com'):
+ self.assertEqual(
+ make_absolute_url('/media/exercise-images/foo.png'),
+ 'https://example.com/media/exercise-images/foo.png',
+ )
+
+ def test_empty_path_is_returned_unchanged(self):
+ self.assertIsNone(make_absolute_url(None))
+ self.assertEqual(make_absolute_url(''), '')
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/wger/utils/url.py b/wger/utils/url.py
index 3232a1694..3d06e09c1 100644
--- a/wger/utils/url.py
+++ b/wger/utils/url.py
@@ -19,12 +19,14 @@ from typing import (
Optional,
)
from urllib.parse import (
+ urljoin,
urlparse,
urlunparse,
)
# Django
from django.conf import settings
+from django.http import HttpRequest
def make_uri(
@@ -56,3 +58,25 @@ def make_uri(
)
return uri
+
+
+def make_absolute_url(path: Optional[str], request: Optional[HttpRequest] = None) -> Optional[str]:
+ """
+ Return an absolute URL for a path.
+
+ When a request is available the URL is built from it, so the host the client
+ connected to is preserved. When there is no request, e.g. while the exercise
+ cache is warmed by a celery task, the URL is built from settings.SITE_URL.
+ Empty paths are returned unchanged. Paths that are already absolute pass
+ through untouched, since neither build_absolute_uri nor urljoin alter them.
+ """
+ if not path:
+ return path
+
+ if request is not None:
+ return request.build_absolute_uri(path)
+
+ if site_url := getattr(settings, 'SITE_URL', None):
+ return urljoin(site_url, path)
+
+ return path