Self hosted FLOSS fitness/workout, nutrition and weight tracker
Auto-reformatted code
Mannai65218731957b
diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.pyindex 7c4cee4ce..7ad4318b3 100644--- a/wger/exercises/api/serializers.py+++ b/wger/exercises/api/serializers.py@@ -487,7 +487,8 @@ class ExerciseTranslationSerializer(serializers.ModelSerializer):'language','license_author',)- read_only_fields = ('description') # Prevents API from accepting raw HTML++ read_only_fields = 'description' # Prevents API from accepting raw HTMLdef validate(self, value):"""diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex db71a798c..e38728818 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -171,7 +171,7 @@ class ExerciseTranslationViewSet(ModelViewSet):"""Save entry to activity stream"""-+super().perform_create(serializer)actstream_action.send(@@ -193,7 +193,7 @@ class ExerciseTranslationViewSet(ModelViewSet):del serializer.validated_data['language']super().perform_update(serializer)-+actstream_action.send(self.request.user,verb=StreamVerbs.UPDATED.value,diff --git a/wger/exercises/management/commands/migrate_descriptions_to_markdown.py b/wger/exercises/management/commands/migrate_descriptions_to_markdown.pyindex d5deb0d99..70d4cbcd7 100644--- a/wger/exercises/management/commands/migrate_descriptions_to_markdown.py+++ b/wger/exercises/management/commands/migrate_descriptions_to_markdown.py@@ -51,15 +51,14 @@ class Command(BaseCommand):def handle(self, **options):dry_run = options['dry_run']-+# Filter: Has description, but NO source (to avoid re-migrating).translations_to_migrate = Translation.objects.filter(- Q(description_source__isnull=True) | Q(description_source=''),- description__isnull=False+ Q(description_source__isnull=True) | Q(description_source=''), description__isnull=False).exclude(description='')total = translations_to_migrate.count()- self.stdout.write(f"Found {total} translations to migrate.")+ self.stdout.write(f'Found {total} translations to migrate.')count = 0errors = 0@@ -67,34 +66,34 @@ class Command(BaseCommand):for trans in translations_to_migrate:try:# ATX to ensure # headings instead of underlined headings.- md_source = markdownify(trans.description, heading_style="ATX")+ md_source = markdownify(trans.description, heading_style='ATX')if dry_run:self.stdout.write(- f"[Dry Run] ID {trans.id}: "- f"converted length {len(trans.description)} -> {len(md_source)}"- )+ f'[Dry Run] ID {trans.id}: '+ f'converted length {len(trans.description)} -> {len(md_source)}'+ )else:trans.description_source = md_source-+# save() triggers:# description = render_markdown(description_source)# To ensure a clean HTML cache.trans.save()-+count += 1-+if count % 100 == 0:- self.stdout.write(f"Processed {count}/{total}...")+ self.stdout.write(f'Processed {count}/{total}...')except Exception as e:errors += 1- self.stdout.write(self.style.ERROR(f"Error converting ID {trans.id}: {e}"))+ self.stdout.write(self.style.ERROR(f'Error converting ID {trans.id}: {e}'))- success_msg = f"Successfully migrated {count} descriptions."+ success_msg = f'Successfully migrated {count} descriptions.'if dry_run:- success_msg += " (Dry Run)"-+ success_msg += ' (Dry Run)'+self.stdout.write(self.style.SUCCESS(success_msg))if errors > 0:- self.stdout.write(self.style.WARNING(f"Finished with {errors} errors."))\ No newline at end of file+ self.stdout.write(self.style.WARNING(f'Finished with {errors} errors.'))diff --git a/wger/exercises/migrations/0035_rename_exercises_e_name_ac11f4_gin_exercises_t_name_6264c9_gin_and_more.py b/wger/exercises/migrations/0035_rename_exercises_e_name_ac11f4_gin_exercises_t_name_6264c9_gin_and_more.pyindex ea9ac1a34..0c60fc014 100644--- a/wger/exercises/migrations/0035_rename_exercises_e_name_ac11f4_gin_exercises_t_name_6264c9_gin_and_more.py+++ b/wger/exercises/migrations/0035_rename_exercises_e_name_ac11f4_gin_exercises_t_name_6264c9_gin_and_more.py@@ -7,7 +7,6 @@ from django.db import migrations, modelsclass Migration(migrations.Migration):-dependencies = [('exercises', '0034_add_exercise_image_dimensions'),]diff --git a/wger/exercises/models/translation.py b/wger/exercises/models/translation.pyindex 752789f47..24c24ac26 100644--- a/wger/exercises/models/translation.py+++ b/wger/exercises/models/translation.py@@ -32,8 +32,11 @@ from simple_history.models import HistoricalRecords# wgerfrom wger.core.models import Languagefrom wger.exercises.models import Exercise-from wger.utils.markdown import render_markdown, sanitize_htmlfrom wger.utils.cache import reset_exercise_api_cache+from wger.utils.markdown import (+ render_markdown,+ sanitize_html,+)from wger.utils.models import (AbstractHistoryMixin,AbstractLicenseModel,@@ -53,9 +56,7 @@ class Translation(AbstractLicenseModel, AbstractHistoryMixin, models.Model):"""Description on how to perform the exercise"""description_source = models.TextField(- verbose_name=_('Description (Source)'),- blank=True,- null=True+ verbose_name=_('Description (Source)'), blank=True, null=True)"""The raw Markdown source"""@@ -141,7 +142,7 @@ class Translation(AbstractLicenseModel, AbstractHistoryMixin, models.Model):self.description = render_markdown(self.description_source)elif self.description:self.description = sanitize_html(self.description)-+super().save(*args, **kwargs)# Api cachediff --git a/wger/exercises/tests/test_command_migrate_descriptions.py b/wger/exercises/tests/test_command_migrate_descriptions.pyindex b5a0dfcd9..dd93af960 100644--- a/wger/exercises/tests/test_command_migrate_descriptions.py+++ b/wger/exercises/tests/test_command_migrate_descriptions.py@@ -31,17 +31,13 @@ class TestMigrateDescriptionsCommand(WgerTestCase):def setUp(self):super().setUp()self.translation = Translation.objects.get(pk=1)-+self.raw_html = (- "<p>This is <b>bold</b> and <i>italic</i>.</p>"- "<ul><li>Item 1</li><li>Item 2</li></ul>"+ '<p>This is <b>bold</b> and <i>italic</i>.</p><ul><li>Item 1</li><li>Item 2</li></ul>')-+# Set to Legacy State (no markdown).- Translation.objects.filter(pk=1).update(- description=self.raw_html,- description_source=None- )+ Translation.objects.filter(pk=1).update(description=self.raw_html, description_source=None)self.translation.refresh_from_db()def test_migration_command(self):@@ -53,21 +49,20 @@ class TestMigrateDescriptionsCommand(WgerTestCase):call_command('migrate_descriptions_to_markdown', stdout=out)self.translation.refresh_from_db()-+src = self.translation.description_sourceself.assertIsNotNone(src)- self.assertTrue("**bold**" in src or "__bold__" in src) # Markdownify config dependant- self.assertTrue("*italic*" in src or "_italic_" in src)- self.assertIn("* Item 1", src)- self.assertIn("* Item 2", src)+ self.assertTrue('**bold**' in src or '__bold__' in src) # Markdownify config dependant+ self.assertTrue('*italic*' in src or '_italic_' in src)+ self.assertIn('* Item 1', src)+ self.assertIn('* Item 2', src)desc = self.translation.description- self.assertIn("<strong>bold</strong>", desc)- self.assertIn("<em>italic</em>", desc)- self.assertIn("<ul>", desc)- self.assertIn("<li>Item 1</li>", desc)- self.assertIn("<p>", desc)-+ self.assertIn('<strong>bold</strong>', desc)+ self.assertIn('<em>italic</em>', desc)+ self.assertIn('<ul>', desc)+ self.assertIn('<li>Item 1</li>', desc)+ self.assertIn('<p>', desc)def test_dry_run(self):"""@@ -76,9 +71,9 @@ class TestMigrateDescriptionsCommand(WgerTestCase):out = StringIO()call_command('migrate_descriptions_to_markdown', '--dry-run', stdout=out)-+self.translation.refresh_from_db()-+self.assertIsNone(self.translation.description_source)- self.assertIn("[Dry Run]", out.getvalue())- self.assertEqual(self.translation.description, self.raw_html)\ No newline at end of file+ self.assertIn('[Dry Run]', out.getvalue())+ self.assertEqual(self.translation.description, self.raw_html)diff --git a/wger/utils/generic_views.py b/wger/utils/generic_views.pyindex b449e8256..15564fd94 100644--- a/wger/utils/generic_views.py+++ b/wger/utils/generic_views.py@@ -39,12 +39,12 @@ from crispy_forms.layout import ()# wger-from wger.utils.markdown import sanitize_htmlfrom wger.utils.constants import (HTML_ATTRIBUTES_WHITELIST,HTML_STYLES_WHITELIST,HTML_TAG_WHITELIST,)+from wger.utils.markdown import sanitize_htmllogger = logging.getLogger(__name__)diff --git a/wger/utils/markdown.py b/wger/utils/markdown.pyindex 0ce59e590..ec1c01460 100644--- a/wger/utils/markdown.py+++ b/wger/utils/markdown.py@@ -14,38 +14,37 @@## You should have received a copy of the GNU Affero General Public License+# Third Party# Third partyimport nh3from markdown_it import MarkdownIt+def render_markdown(text):"""Renders markdown text to HTML and sanitizes it to allow only basic markup."""if not text:- return ""+ return ''# Render Markdown to HTML- md = MarkdownIt("commonmark", {"breaks": True, "html": True})+ md = MarkdownIt('commonmark', {'breaks': True, 'html': True})raw_html = md.render(text)# Sanitize HTMLALLOWED_TAGS = {'b', 'strong', 'i', 'em', 'ul', 'ol', 'li', 'p'}- clean_html = nh3.clean(- raw_html,- tags=ALLOWED_TAGS,- attributes={}- )+ clean_html = nh3.clean(raw_html, tags=ALLOWED_TAGS, attributes={})return clean_html+def sanitize_html(text):"""Directly sanitizes HTML (for legacy fields or non-markdown inputs)"""if not text:- return ""-+ return ''+ALLOWED_TAGS = {'b', 'strong', 'i', 'em', 'ul', 'ol', 'li', 'p'}- return nh3.clean(text, tags=ALLOWED_TAGS, attributes={})\ No newline at end of file+ return nh3.clean(text, tags=ALLOWED_TAGS, attributes={})diff --git a/wger/utils/tests/test_markdown.py b/wger/utils/tests/test_markdown.pyindex d2643e943..630479423 100644--- a/wger/utils/tests/test_markdown.py+++ b/wger/utils/tests/test_markdown.py@@ -33,9 +33,9 @@ class TestMarkdown(unittest.TestCase):Test that basic markdown syntax is rendered to HTML."""# Bold and Italic- text = "I like **osaka** and eating *sata-andagi*."+ text = 'I like **osaka** and eating *sata-andagi*.'output = render_markdown(text)-+self.assertTrue('<strong>osaka</strong>' in output or '<b>osaka</b>' in output)self.assertTrue('<em>sata-andagi</em>' in output or '<i>sata-andagi</i>' in output)self.assertIn('<p>', output)@@ -44,9 +44,9 @@ class TestMarkdown(unittest.TestCase):"""Test that lists are rendered correctly."""- text = "- Item 1\n- Item 2"+ text = '- Item 1\n- Item 2'output = render_markdown(text)-+self.assertIn('<ul>', output)self.assertIn('<li>Item 1</li>', output)self.assertIn('<li>Item 2</li>', output)@@ -57,16 +57,16 @@ class TestMarkdown(unittest.TestCase):results in the tag being stripped."""# Heading 1 (<h1> is not allowed)- text = "# Big Title"+ text = '# Big Title'output = render_markdown(text)-+self.assertNotIn('<h1>', output)self.assertIn('Big Title', output) # Content remains, tag is removed# Image (<img> is not allowed)- text = ""+ text = ''output = render_markdown(text)-+self.assertNotIn('<img', output)def test_render_markdown_xss_prevention(self):@@ -76,14 +76,14 @@ class TestMarkdown(unittest.TestCase):# Script injection via Markdown/HTML mixtext = "Hello <script>alert('XSS')</script>"output = render_markdown(text)-+self.assertNotIn('<script>', output)self.assertNotIn('alert', output)# Dangerous attributestext = '<p onclick="maliciousCode()">Click me</p>'output = render_markdown(text)-+self.assertNotIn('onclick', output)self.assertIn('<p>Click me</p>', output)@@ -95,18 +95,18 @@ class TestMarkdown(unittest.TestCase):output = sanitize_html(html)self.assertIn('<b>Bold</b>', output)- self.assertNotIn('<a href', output) # Links are not in the allowed list- self.assertIn('Link', output) # Content usually preserved+ self.assertNotIn('<a href', output) # Links are not in the allowed list+ self.assertIn('Link', output) # Content usually preserveddef test_empty_inputs(self):"""Test handling of None or empty strings."""- self.assertEqual(render_markdown(None), "")- self.assertEqual(render_markdown(""), "")- self.assertEqual(sanitize_html(None), "")- self.assertEqual(sanitize_html(""), "")+ self.assertEqual(render_markdown(None), '')+ self.assertEqual(render_markdown(''), '')+ self.assertEqual(sanitize_html(None), '')+ self.assertEqual(sanitize_html(''), '')if __name__ == '__main__':- unittest.main()\ No newline at end of file+ unittest.main()