From 624017a0f95cdd77b295162c57ffbc326b6574b4 Mon Sep 17 00:00:00 2001 From: paulusbrand <75862178+paulusbrand@users.noreply.github.com> Date: Fri, 7 Jun 2024 17:01:35 +0200 Subject: [PATCH] Add template Base64 decode encoding parameter (#116603) Co-authored-by: Robert Resch --- homeassistant/helpers/template.py | 12 ++++++++---- tests/helpers/test_template.py | 12 ++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index f5c796ef46d..f10913c2478 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -2397,14 +2397,18 @@ def struct_unpack(value: bytes, format_string: str, offset: int = 0) -> Any | No return None -def base64_encode(value): +def base64_encode(value: str) -> str: """Perform base64 encode.""" return base64.b64encode(value.encode("utf-8")).decode("utf-8") -def base64_decode(value): - """Perform base64 denode.""" - return base64.b64decode(value).decode("utf-8") +def base64_decode(value: str, encoding: str | None = "utf-8") -> str | bytes: + """Perform base64 decode.""" + decoded = base64.b64decode(value) + if encoding: + return decoded.decode(encoding) + + return decoded def ordinal(value): diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 71e1bc748a6..3d8dad1d23e 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1643,6 +1643,18 @@ def test_base64_decode(hass: HomeAssistant) -> None: ).async_render() == "homeassistant" ) + assert ( + template.Template( + '{{ "aG9tZWFzc2lzdGFudA==" | base64_decode(None) }}', hass + ).async_render() + == b"homeassistant" + ) + assert ( + template.Template( + '{{ "aG9tZWFzc2lzdGFudA==" | base64_decode("ascii") }}', hass + ).async_render() + == "homeassistant" + ) def test_slugify(hass: HomeAssistant) -> None: