]> git.ipfire.org Git - ipfire.org.git/commitdiff
messages: Add function to embed images
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 26 Oct 2023 08:13:09 +0000 (08:13 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 26 Oct 2023 08:13:09 +0000 (08:13 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/backend/messages.py

index 9dbcdb6acc66c8f9a1d817f32d2b83c85c34eabf..0aea14e8a38cbf98b7b0d0459c569be86279f17b 100644 (file)
@@ -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