ctucx.git: nixfiles

ctucx' nixfiles

commit 689e7feb29b6752e6892f22b758c2f100c6b31db
parent e016f8c0ba45c39ccf42458acadf598597dcfd1c
Author: Leah (ctucx) <leah@ctu.cx>
Date: Thu, 8 Sep 2022 12:23:42 +0200

machines/osterei/maddy: parse message-body to get headers in mailbox-filter
1 file changed, 28 insertions(+), 14 deletions(-)
M
machines/osterei/maddy.nix
|
42
++++++++++++++++++++++++++++--------------
diff --git a/machines/osterei/maddy.nix b/machines/osterei/maddy.nix
@@ -7,18 +7,12 @@ let
   secrets = import ../../secrets/default.nix;
   std     = import <nix-std>;
 
-  mailboxFilterScript = writePythonScriptBin "mailbox-filter.py" (ps: [ ps.toml ]) ''
+  mailboxFilterScript = writePythonScriptBin "mailbox-filter.py" (ps: [ ps.toml ps.mail-parser ]) ''
     from email.header import Header, decode_header, make_header
-    import sys, toml, re
-
-    try:
-      account_name = sys.argv[1]
-      sender       = sys.argv[2]
-      recipient    = sys.argv[3]
-      subject      = make_header(decode_header(sys.argv[4]))
-
-      config       = toml.load('/etc/maddy/filters/mailbox/' + account_name + '.toml')
+    import sys, re
+    import toml, mailparser
 
+    def filter_mail(config, sender, recipient, subject):
       for type in [ 'recipient', 'subject', 'sender' ]:
         if type not in config:
           continue

@@ -28,6 +22,26 @@ let
             print(value.replace(",", "\n"))
             sys.exit(0)
 
+    try:
+      account_name = sys.argv[1]
+      config       = toml.load('/etc/maddy/filters/mailbox/' + account_name + '.toml')
+
+      if len(sys.argv) > 2:
+        filter_mail(config, sys.argv[2], sys.argv[3], make_header(decode_header(sys.argv[4])))
+      else:
+        sender = subject = ""
+        message          = mailparser.parse_from_string(sys.stdin.read())
+
+        if len(message.from_) > 0:
+          if len(message.from_[0]) == 2:
+            sender = message.from_[0][1]
+
+        if message.subject is not None:
+          subject = message.subject
+
+        for recipient in message.to:
+          filter_mail(config, sender, recipient[1], subject)
+
     except:
       pass
 

@@ -47,11 +61,11 @@ let
           continue
 
         if 'reject' in config[type]:
-          if(eval(type) in config[type]['reject']):
+          if eval(type) in config[type]['reject']:
             sys.exit(10)
 
-        if('quarantine' in config[type]):
-          if(eval(type) in config[type]['quarantine']):
+        if 'quarantine' in config[type]:
+          if eval(type) in config[type]['quarantine']:
             sys.exit(20)
 
     except SystemExit as e:

@@ -151,7 +165,7 @@ in {
           compression zstd
 
           imap_filter {
-              command ${mailboxFilterScript} {account_name} {sender} {original_rcpt_to} {subject}
+              command ${mailboxFilterScript} {account_name}
           }
       }