Self hosted FLOSS fitness/workout, nutrition and weight tracker
Adds validator for (exercise) images
Roland Geider16aa8c7ce530
diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex 9707d1287..87e0cdca1 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -17,6 +17,10 @@import loggingfrom uuid import UUID+# Third Party+import bleach+from actstream import action as actstream_action+from bleach.css_sanitizer import CSSSanitizer# Djangofrom django.conf import settingsfrom django.contrib.postgres.search import TrigramSimilarity@@ -24,11 +28,6 @@ from django.db.models import Qfrom django.utils.decorators import method_decoratorfrom django.utils.translation import gettext as _from django.views.decorators.cache import cache_page--# Third Party-import bleach-from actstream import action as actstream_action-from bleach.css_sanitizer import CSSSanitizerfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import (OpenApiParameter,@@ -90,7 +89,6 @@ from wger.utils.constants import (from wger.utils.db import is_postgres_dbfrom wger.utils.language import load_language-logger = logging.getLogger(__name__)@@ -298,9 +296,9 @@ def search(request):try:thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).urlexcept InvalidImageFormatError as e:- logger.info(f'InvalidImageFormatError while processing a thumbnail: {e}')+ logger.warning(f'InvalidImageFormatError while processing a thumbnail: {e}')except OSError as e:- logger.info(f'OSError while processing a thumbnail: {e}')+ logger.warning(f'OSError while processing a thumbnail: {e}')result_json = {'value': translation.name,diff --git a/wger/exercises/models/image.py b/wger/exercises/models/image.pyindex 1c4315ce3..3185d65a1 100644--- a/wger/exercises/models/image.py+++ b/wger/exercises/models/image.py@@ -21,7 +21,6 @@ import uuid# Djangofrom django.db import modelsfrom django.utils.translation import gettext_lazy as _-# Third Partyfrom simple_history.models import HistoricalRecords@@ -29,6 +28,7 @@ from simple_history.models import HistoricalRecordsfrom wger.exercises.models import Exercisefrom wger.utils.cache import reset_exercise_api_cachefrom wger.utils.helpers import BaseImage+from wger.utils.images import validate_image_static_no_animationfrom wger.utils.models import (AbstractHistoryMixin,AbstractLicenseModel,@@ -78,25 +78,20 @@ class ExerciseImage(AbstractLicenseModel, AbstractHistoryMixin, models.Model, Baimage = models.ImageField(verbose_name=_('Image'),- help_text=_('Only PNG and JPEG formats are supported'),+ help_text='Only PNG and JPEG formats are supported',upload_to=exercise_image_upload_dir,+ validators=[validate_image_static_no_animation],)"""Uploaded image"""is_main = models.BooleanField(verbose_name=_('Main picture'),default=False,- help_text=_(- 'Tick the box if you want to set this image as the '- 'main one for the exercise (will be shown e.g. in '- 'the search). The first image is automatically '- 'marked by the system.'- ),)"""A flag indicating whether the image is the exercise's main image"""style = models.CharField(- help_text=_('The art style of your image'),+ help_text='The art style of your image',max_length=1,choices=STYLE,default=PHOTO,@@ -104,13 +99,13 @@ class ExerciseImage(AbstractLicenseModel, AbstractHistoryMixin, models.Model, Ba"""The art style of the image"""created = models.DateTimeField(- _('Date'),+ 'Date',auto_now_add=True,)"""The creation time"""last_update = models.DateTimeField(- _('Date'),+ 'Date',auto_now=True,)"""Datetime of last modification"""diff --git a/wger/utils/images.py b/wger/utils/images.pynew file mode 100644index 000000000..e76eb1306--- /dev/null+++ b/wger/utils/images.py@@ -0,0 +1,48 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Third Party+from PIL import (+ Image,+ UnidentifiedImageError,+)+# Django+from django.core.exceptions import ValidationError++MAX_FILE_SIZE_MB = 20+++def validate_image_static_no_animation(value):+ # File size check+ if value.size > 1024 * 1024 * MAX_FILE_SIZE_MB:+ raise ValidationError(f'The maximum image file size is {MAX_FILE_SIZE_MB}MB.')++ # Try opening the file with PIL+ try:+ value.open()+ img = Image.open(value)+ img_format = img.format.lower()+ except UnidentifiedImageError:+ raise ValidationError('File is not a valid image.')++ # Supported types+ allowed_formats = {'jpeg', 'jpg', 'png', 'webp'}+ if img_format not in allowed_formats:+ raise ValidationError(+ f'File type is not supported. Allowed formats: {", ".join(allowed_formats)}.'+ )++ # Check for animation+ if img_format == 'webp' and getattr(img, 'is_animated'):+ raise ValidationError('Animated images are not supported.')