Matthias Andreas Benkard | b382b10 | 2021-01-02 15:32:21 +0100 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | |
| 3 | import smtplib |
| 4 | import os |
| 5 | from email.mime.multipart import MIMEMultipart |
| 6 | from email.mime.text import MIMEText |
| 7 | from email.utils import COMMASPACE, formatdate |
| 8 | import jinja2 |
| 9 | from jinja2 import Template |
| 10 | import redis |
| 11 | import time |
| 12 | import sys |
| 13 | import html2text |
| 14 | from subprocess import Popen, PIPE, STDOUT |
| 15 | |
| 16 | if len(sys.argv) > 2: |
| 17 | percent = int(sys.argv[1]) |
| 18 | username = str(sys.argv[2]) |
| 19 | else: |
| 20 | print("Args missing") |
| 21 | sys.exit(1) |
| 22 | |
| 23 | while True: |
| 24 | try: |
| 25 | r = redis.StrictRedis(host='redis', decode_responses=True, port=6379, db=0) |
| 26 | r.ping() |
| 27 | except Exception as ex: |
| 28 | print('%s - trying again...' % (ex)) |
| 29 | time.sleep(3) |
| 30 | else: |
| 31 | break |
| 32 | |
| 33 | if r.get('QW_HTML'): |
| 34 | try: |
| 35 | template = Template(r.get('QW_HTML')) |
| 36 | except: |
| 37 | print("Error: Cannot parse quarantine template, falling back to default template.") |
| 38 | with open('/templates/quota.tpl') as file_: |
| 39 | template = Template(file_.read()) |
| 40 | else: |
| 41 | with open('/templates/quota.tpl') as file_: |
| 42 | template = Template(file_.read()) |
| 43 | |
| 44 | html = template.render(username=username, percent=percent) |
| 45 | text = html2text.html2text(html) |
| 46 | |
| 47 | try: |
| 48 | msg = MIMEMultipart('alternative') |
| 49 | msg['From'] = r.get('QW_SENDER') or "quota-warning@localhost" |
| 50 | msg['Subject'] = r.get('QW_SUBJ') or "Quota warning" |
| 51 | msg['Date'] = formatdate(localtime = True) |
| 52 | text_part = MIMEText(text, 'plain', 'utf-8') |
| 53 | html_part = MIMEText(html, 'html', 'utf-8') |
| 54 | msg.attach(text_part) |
| 55 | msg.attach(html_part) |
| 56 | msg['To'] = username |
| 57 | p = Popen(['/usr/lib/dovecot/dovecot-lda', '-d', username, '-o', '"plugin/quota=maildir:User quota:noenforcing"'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) |
| 58 | p.communicate(input=bytes(msg.as_string(), 'utf-8')) |
| 59 | |
| 60 | except Exception as ex: |
| 61 | print('Failed to send quota notification: %s' % (ex)) |
| 62 | sys.exit(1) |
| 63 | |
| 64 | try: |
| 65 | sys.stdout.close() |
| 66 | except: |
| 67 | pass |
| 68 | |
| 69 | try: |
| 70 | sys.stderr.close() |
| 71 | except: |
| 72 | pass |