#!/usr/bin/python3
# Wombat-Email: the daily Spam summary (installed by installer/70-spam.sh as
# /usr/local/sbin/wombat-email-spam-summary; run each morning by wombat-email-spam-summary.timer;
# docs/spam-and-senders.md). To each mailbox whose Spam folder got unread mail in the last day: who it's
# from and its subject, each with a "Not spam" link (a random key in summary_links, used once, good for
# 7 days: the panel's not-spam.php shows it and moves it on a button press), and a link to stop these.
# Off for the whole server in Settings (spam_summary), or per mailbox. While it's on, Spam older than 90 days
# is deleted from every mailbox, after the summaries go out.
#   wombat-email-spam-summary                   every mailbox, as the timer does
#   wombat-email-spam-summary --only ADDRESS    one mailbox, even when the server's setting is off (tests)
#   wombat-email-spam-summary --print           write the messages out instead of sending them
#   wombat-email-spam-summary --stats           only count the last 7 days for the Spam page (the installer does)
# Every full run (and --stats) also counts, per mailbox, the last 7 days for the panel's Spam page:
# messages in Spam, their top sender domains, and mail refused at the door (from Rspamd's log, as many days as
# it keeps) -> /var/lib/wombat-email/spam-week.json (640 root:wombat-panel).
import collections, datetime, email.header, email.utils, glob, gzip, html, json, re, secrets, subprocess, sys
from email.message import EmailMessage

sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share

LIMIT = 30          # messages listed in one summary; the rest are counted
DAYS_GOOD = 7       # how long a link works
KEEP_DAYS = 90      # Spam older than this is deleted (only while the summary is on)
LOG = "/var/log/wombat-email/spam-summary.log"
S = we.settings()
HOST = S["HOSTNAME"]
args = sys.argv[1:]
only = args[args.index("--only") + 1].lower() if "--only" in args else None
printing = "--print" in args


def log(text):
    with open(LOG, "a") as f:
        f.write(f"{datetime.datetime.now().isoformat(timespec='seconds')} {text}\n")


def sql(query, **v):
    """One statement; variables as psql :'name'. Rows of tab-separated fields."""
    return we.psql(query, rows=True, **v)


def decoded(raw):
    """A header as text on one line, without control characters (a NUL can't go to psql)."""
    try:
        text = str(email.header.make_header(email.header.decode_header(raw or "")))
    except Exception:
        text = raw or ""
    return re.sub(r"[\x00-\x1f\x7f]+", " ", text).strip()


def spam_of(mailbox):
    out = subprocess.run(["doveadm", "-f", "json", "fetch", "-u", mailbox, "mailbox-guid uid hdr.from hdr.subject date.saved",
                          "mailbox", "Spam", "savedsince", "1d", "unseen"], capture_output=True, text=True)
    try:
        return sorted(json.loads(out.stdout or "[]"), key=lambda m: m.get("date.saved", ""))
    except ValueError:
        return []


def when(saved):
    try:
        t = datetime.datetime.strptime(saved, "%Y-%m-%d %H:%M:%S")
        return t.strftime("%b %-d, %H:%M")
    except ValueError:
        return saved


def link(key): return f"https://{HOST}/panel/not-spam.php?k={key}"


def org_domain(addr):   # the sender's domain, without subdomains (mg-d1.substack.com -> substack.com)
    d = addr.rsplit("@", 1)[-1].lower().strip(">")
    parts = d.split(".")
    keep = 3 if len(parts) > 2 and len(parts[-1]) == 2 and parts[-2] in ("co", "com", "org", "net", "ac", "gov") else 2
    return ".".join(parts[-keep:]) if d else ""


def week_stats():
    """The last 7 days per mailbox, for the Spam page: in Spam (and from which domains), refused at the door."""
    boxes = [b[0] for b in sql("SELECT email FROM mailboxes WHERE NOT relay ORDER BY email")]
    aliases = {}
    for a in sql("SELECT source, destination FROM aliases WHERE enabled"):
        aliases.setdefault(a[0], []).append(a[1])
    def mailboxes_of(rcpt):
        r = rcpt.lower()
        user, _, dom = r.partition("@")
        r = user.split("+", 1)[0] + "@" + dom
        return aliases.get(r) or ([r] if r in boxes else aliases.get("@" + dom, []))
    out, days = {}, set()
    for box in boxes:
        f = subprocess.run(["doveadm", "-f", "json", "fetch", "-u", box, "hdr.from", "mailbox", "Spam", "savedsince", "7d"],
                           capture_output=True, text=True)
        try:
            msgs = json.loads(f.stdout or "[]")
        except ValueError:
            msgs = []
        top = collections.Counter(org_domain(email.utils.parseaddr(decoded(m.get("hdr.from", "")))[1]) for m in msgs)
        top.pop("", None)
        out[box] = {"spam": len(msgs), "top": top.most_common(3), "refused": 0}
    since = datetime.datetime.now() - datetime.timedelta(days=7)
    for path in sorted(glob.glob("/var/log/rspamd/rspamd.log*")):
        try:
            fh = gzip.open(path, "rt", errors="replace") if path.endswith(".gz") else open(path, errors="replace")
            for line in fh:
                if "rspamd_task_write_log" not in line or "(normal)" not in line:
                    continue
                try:
                    t = datetime.datetime.strptime(line[:19], "%Y-%m-%d %H:%M:%S")
                except ValueError:
                    continue
                if t < since:
                    continue
                days.add(t.date())
                if "(reject)" not in line or "user: " in line:
                    continue
                m = re.search(r"rcpts: <([^>]*)>", line)
                for rcpt in (m.group(1).split(",") if m else []):
                    for box in mailboxes_of(rcpt.strip()):
                        if box in out:
                            out[box]["refused"] += 1
            fh.close()
        except OSError:
            pass
    data = {"at": int(datetime.datetime.now().timestamp()), "log_days": len(days), "mailboxes": out}
    we.write_json("/var/lib/wombat-email/spam-week.json", data, mode=0o640, group="wombat-panel")


if "--stats" in args or (not only and not printing):
    try:
        week_stats()
    except Exception as e:
        log(f"counting the last 7 days failed: {e}")
if "--stats" in args:
    sys.exit(0)
if not only and (sql("SELECT value FROM settings WHERE key = 'spam_summary'") or [["on"]])[0][0] == "off":
    sys.exit(0)
sql("DELETE FROM summary_links WHERE expires_at < now() - interval '30 days'")   # kept a while: "this link has expired"

boxes = sql("""SELECT m.id, m.email FROM mailboxes m JOIN domains d ON d.id = m.domain_id
               WHERE NOT m.relay AND m.enabled AND d.enabled AND d.mail_here AND (m.spam_summary OR m.email = :'only')
               ORDER BY m.email""", only=only or "")
if only:
    boxes = [b for b in boxes if b[1] == only]
def one_box(mid, box):
    """One mailbox's summary; 1 when it was sent."""
    msgs = spam_of(box)
    if not msgs:
        return 0
    lines = []
    for m in msgs[:LIMIT]:
        name, addr = email.utils.parseaddr(decoded(m.get("hdr.from", "")))
        addr = addr.lower()[:254]
        subject = decoded(m.get("hdr.subject", ""))[:200] or "(no subject)"
        if not re.fullmatch(r"[0-9a-f]{32}", m.get("mailbox-guid", "")) or not str(m.get("uid", "")).isdigit():
            continue
        key = secrets.token_urlsafe(16)
        sql(f"""INSERT INTO summary_links (key, kind, mailbox_id, mailbox_guid, uid, sender, subject, expires_at)
                VALUES (:'k', 'not-spam', {int(mid)}, :'g', {int(m['uid'])}, :'s', :'subj', now() + interval '{DAYS_GOOD} days')""",
            k=key, g=m["mailbox-guid"], s=addr, subj=subject)
        who = f"{name} <{addr}>" if name and addr else (addr or name or "(no sender)")
        lines.append((when(m.get('date.saved', '')), who, subject, link(key)))
    if not lines:
        return 0
    stop = secrets.token_urlsafe(16)
    sql(f"INSERT INTO summary_links (key, kind, mailbox_id, expires_at) VALUES (:'k', 'stop', {int(mid)}, now() + interval '{DAYS_GOOD} days')", k=stop)
    n = len(msgs)
    # short: people read the list and click; how it works is on the page the link opens
    more = f"... and {n - len(lines)} more in your Spam folder." if n > len(lines) else ""
    footer = ("Real mail? Click Not spam. That sender won't land in Spam again.\n"
              f"Real spam? Do nothing. It's deleted after {KEEP_DAYS} days.\n"
              "This is how your mailbox learns what is spam and what is not.\n"
              f"Links work for {DAYS_GOOD} days.")
    about = f"https://{HOST}/panel/about-spam.php"
    # plain text: the links written out
    text = "Check these:\n\n" + "\n\n".join(
        f"{w}  {who}\n              {subj}\n              Not spam: {url}" for w, who, subj, url in lines) + "\n"
    text += (f"\n{more}\n" if more else "") + f"\n{footer}\n\nFull explanation: {about}\n\nShut off these notifications? {link(stop)}\n"
    # HTML: the same text in the mail program's fixed-width font (as the server's other mail), the words as the links
    e = html.escape
    page = "Check these:\n\n" + "\n\n".join(
        f"{e(w)}  {e(who)}\n              {e(subj)}\n              <a href=\"{e(url)}\">Not spam</a>" for w, who, subj, url in lines) + "\n"
    page += (f"\n{e(more)}\n" if more else "") + f"\n{e(footer)}\n\n<a href=\"{e(about)}\">Full explanation</a>\n\nShut off these notifications? <a href=\"{e(link(stop))}\">Click here</a>\n"
    msg = EmailMessage()
    msg["From"] = f"Wombat-Email <postmaster@{HOST}>"
    msg["To"] = box
    msg["Subject"] = f"Check {n} Spam message{'' if n == 1 else 's'}"
    msg["Date"] = email.utils.formatdate(localtime=True)
    msg["Message-ID"] = f"<summary-{secrets.token_hex(8)}@{HOST}>"
    msg["Auto-Submitted"] = "auto-generated"
    msg["X-Wombat-Summary"] = "1"
    msg.set_content(text, cte="8bit")
    msg.add_alternative('<html><body><pre style="white-space: pre-wrap; word-wrap: break-word;">' + page + "</pre></body></html>\n",
                        subtype="html", cte="quoted-printable")
    mime = msg.as_string()
    if printing:
        print(mime)
        return 0
    r = subprocess.run(["/usr/sbin/sendmail", "-i", "-f", f"postmaster@{HOST}", "--", box], input=mime, text=True)
    log(f"{box}: {n} in Spam, {len(lines)} listed" + ("" if r.returncode == 0 else f", sendmail failed ({r.returncode})"))
    return int(r.returncode == 0)


sent = 0
for mid, box in boxes:
    try:   # one mailbox's odd message or a failed step never stops the others, or the cleanup below
        sent += one_box(mid, box)
    except Exception as e:
        log(f"{box}: the summary failed: {e!r}"[:300])
        if printing:
            raise
if boxes and not printing:
    log(f"done: {sent} summar{'y' if sent == 1 else 'ies'} sent")

# Spam older than 90 days is deleted, every mailbox: only while the summary is on (people hear about their spam
# every day, so nothing real sits there unseen for three months), and never in a one-mailbox test run.
if not only and not printing:
    r = subprocess.run(["doveadm", "expunge", "-A", "mailbox", "Spam", "savedbefore", f"{KEEP_DAYS}d"], capture_output=True, text=True)
    log(f"Spam older than {KEEP_DAYS} days deleted" + ("" if r.returncode == 0 else f": doveadm said {(r.stderr or '').strip()[:200]}"))
