From ebfeb8dd08c459d75b818d3af3a04076be964a8e Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Thu, 26 Oct 2023 08:13:09 +0000 Subject: [PATCH] messages: Add function to embed images Signed-off-by: Michael Tremer --- src/backend/messages.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/backend/messages.py b/src/backend/messages.py index 9dbcdb6a..0aea14e8 100644 --- a/src/backend/messages.py +++ b/src/backend/messages.py @@ -1,10 +1,13 @@ #!/usr/bin/python3 +import base64 import email import email.mime.multipart import email.mime.text import email.utils import logging +import mimetypes +import os.path import random import smtplib import socket @@ -33,7 +36,12 @@ class Messages(misc.Object): templates_dir = self.backend.config.get("global", "templates_dir") assert templates_dir - return tornado.template.Loader(templates_dir, autoescape=None) + # Setup namespace + namespace = { + "embed_image" : self.embed_image, + } + + return tornado.template.Loader(templates_dir, namespace=namespace, autoescape=None) def make_recipient(self, recipient): # Use the contact instead of the account @@ -156,6 +164,26 @@ class Messages(misc.Object): if self.backend.debug: self.template_loader.reset() + def embed_image(self, path): + static_dir = self.backend.config.get("global", "static_dir") + assert static_dir + + # Make the path absolute + path = os.path.join(static_dir, path) + + # Fetch the mimetype + mimetype, encoding = mimetypes.guess_type(path) + + # Read the file + with open(path, "rb") as f: + data = f.read() + + # Convert data into base64 + data = base64.b64encode(data) + + # Return everything + return "data:%s;base64,%s" % (mimetype, data.decode()) + async def send_cli(self, template, recipient): """ Send a test message from the CLI -- 2.47.3