From 3b432fc7d61b04e48e1542ed8dea5707366ec853 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Fri, 23 Jun 2023 09:33:24 -0500 Subject: [PATCH] ntfy: Handle non-ASCII characters in message In order to set the message for a notification with an attachment, the text must be specified in the `Message` request header. Unfortunately, HTTP header values are limited to the Latin-1 character set, so Unicode characters cannot be included. As of *ntfy* 2.4.0, however, the server can decode base64-encoded headers using the RFC 2047 scheme. To maintain compatibility with older *ntfy* servers, the `ntfy` function will only encode message contents this way if the string cannoto be encoded as ASCII. --- xactfetch.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/xactfetch.py b/xactfetch.py index a1f109c..0ed529c 100644 --- a/xactfetch.py +++ b/xactfetch.py @@ -1,3 +1,4 @@ +import base64 import copy import datetime import json @@ -51,7 +52,13 @@ def ntfy( if filename: headers['Filename'] = filename if message: - headers['Message'] = message.replace('\n', '\\n') + try: + message.encode("ascii") + except UnicodeEncodeError: + message = rfc2047_base64encode(message) + else: + message = message.replace('\n', '\\n') + headers['Message'] = message r = requests.put( url, headers=headers, @@ -117,6 +124,13 @@ def rbw_code( return p.stdout.rstrip('\n') +def rfc2047_base64encode( + message: str, +) -> str: + encoded = base64.b64encode(message.encode("utf-8")).decode("ascii") + return f"=?UTF-8?B?{encoded}?=" + + def firefly_import(csv: Path, config: dict[str, Any], token: str) -> None: log.debug('Importing transactions from %s to Firefly III', csv) env = {