From 4892b28af37b1cf6e9d67dd35c7cfe0ca1625b9b Mon Sep 17 00:00:00 2001 From: Delena Malan Date: Sun, 19 May 2024 13:49:57 +0200 Subject: [PATCH] Add jinja fromjson custom filter --- changedetectionio/filters.py | 6 ++++++ changedetectionio/forms.py | 2 ++ changedetectionio/safe_jinja.py | 3 +++ 3 files changed, 11 insertions(+) create mode 100644 changedetectionio/filters.py diff --git a/changedetectionio/filters.py b/changedetectionio/filters.py new file mode 100644 index 00000000..f8d1bf19 --- /dev/null +++ b/changedetectionio/filters.py @@ -0,0 +1,6 @@ +import json + +def fromjson(value): + if value is None or not value: + return "" + return json.loads(value) diff --git a/changedetectionio/forms.py b/changedetectionio/forms.py index 2d64a227..95f2b2f8 100644 --- a/changedetectionio/forms.py +++ b/changedetectionio/forms.py @@ -32,6 +32,7 @@ from changedetectionio import html_tools, content_fetchers from changedetectionio.notification import ( valid_notification_formats, ) +from changedetectionio.filters import fromjson from wtforms.fields import FormField @@ -246,6 +247,7 @@ class ValidateJinja2Template(object): try: jinja2_env = ImmutableSandboxedEnvironment(loader=BaseLoader) + jinja2_env.filters['fromjson'] = fromjson jinja2_env.globals.update(notification.valid_tokens) jinja2_env.from_string(joined_data).render() except TemplateSyntaxError as e: diff --git a/changedetectionio/safe_jinja.py b/changedetectionio/safe_jinja.py index 8a6e1d38..0fe99403 100644 --- a/changedetectionio/safe_jinja.py +++ b/changedetectionio/safe_jinja.py @@ -8,11 +8,14 @@ import jinja2.sandbox import typing as t import os +from changedetectionio.filters import fromjson + JINJA2_MAX_RETURN_PAYLOAD_SIZE = 1024 * int(os.getenv("JINJA2_MAX_RETURN_PAYLOAD_SIZE_KB", 1024 * 10)) def render(template_str, **args: t.Any) -> str: jinja2_env = jinja2.sandbox.ImmutableSandboxedEnvironment(extensions=['jinja2_time.TimeExtension']) + jinja2_env.filters['fromjson'] = fromjson output = jinja2_env.from_string(template_str).render(args) return output[:JINJA2_MAX_RETURN_PAYLOAD_SIZE]