aboutsummaryrefslogtreecommitdiff
path: root/watcher.py
blob: 9799baef2710da4dbe9864c6c26c2105960d3a7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/usr/bin/env python3
"""Email a generic notification for each drop that received an upload recently.

Intended to be run by a systemd timer every SCAN_INTERVAL_SECONDS. There is no
state tracking: a drop is reported when it contains an image whose modification
time falls within the last interval.
"""

from __future__ import annotations

import os
import smtplib
import stat
import time
from email.message import EmailMessage
from email.utils import formatdate, make_msgid
from pathlib import Path
from urllib.parse import quote

from server import DEFAULT_CONFIG_FILE, AppConfig, load_config


SCAN_INTERVAL_SECONDS = 5 * 60
IMAGE_SUFFIXES = {".jpg", ".png", ".heic"}
SUBJECT = "New upload received"
BODY = "A new file has been uploaded to your private drop."
SEPARATOR = "-" * 40
MAX_SIDECAR_BYTES = 16 * 1024


def recent_uploads(config: AppConfig, upload_dir: Path, now: float) -> dict[str, list[str]]:
    """Map each configured target to its image filenames modified in (now - interval, now]."""
    window_start = now - SCAN_INTERVAL_SECONDS
    recent: dict[str, list[str]] = {}
    for target in config.recipients:
        target_dir = upload_dir / target
        if not target_dir.is_dir():
            continue
        names: list[str] = []
        for candidate in target_dir.iterdir():
            if candidate.suffix.lower() not in IMAGE_SUFFIXES:
                continue
            try:
                file_stat = candidate.stat(follow_symlinks=False)
            except FileNotFoundError:
                continue
            if stat.S_ISREG(file_stat.st_mode) and window_start < file_stat.st_mtime <= now:
                names.append(candidate.name)
        if names:
            recent[target] = sorted(names)
    return recent


def read_sidecar(image_path: Path) -> str:
    """Return an image's submission details, or a placeholder if they cannot be read."""
    sidecar = image_path.with_suffix(".txt")
    try:
        if sidecar.is_symlink() or not sidecar.is_file():
            return "(Submission details are not available.)"
        with sidecar.open("rb") as handle:
            raw = handle.read(MAX_SIDECAR_BYTES)
    except OSError:
        return "(Submission details could not be read.)"
    text = raw.decode("utf-8", errors="replace")
    # Submitter-supplied text: keep newlines and tabs, drop other control characters.
    text = "".join(c for c in text if c in "\n\t" or (ord(c) >= 32 and ord(c) != 127))
    return text.strip() or "(Submission details are empty.)"


def build_message(config: AppConfig, target: str, target_dir: Path, filenames: list[str]) -> EmailMessage:
    message = EmailMessage()
    message["From"] = config.smtp.send_as
    message["To"] = config.recipients[target]
    message["Subject"] = SUBJECT
    message["Date"] = formatdate(localtime=True)
    message["Message-ID"] = make_msgid(domain=config.smtp.send_as.rsplit("@", 1)[1])
    prefix = config.view_url_prefixes.get(target)
    sections = [BODY]
    for name in filenames:
        # Stored names are server-generated hex plus an extension, so they are URL-safe.
        heading = prefix + quote(name) if prefix else f"File: {name}"
        sections.append(f"{SEPARATOR}\n{heading}\n\n{read_sidecar(target_dir / name)}")
    message.set_content("\n\n".join(sections) + "\n")
    return message


def send_recent_upload_notifications(
    config: AppConfig,
    upload_dir: Path,
    now: float | None = None,
    smtp_username: str | None = None,
    smtp_password: str | None = None,
) -> int:
    """Send one generic email per drop with recent uploads. Returns the number sent."""
    if bool(smtp_username) != bool(smtp_password):
        raise ValueError("SMTP_USERNAME and SMTP_PASSWORD must be set together")

    uploads = recent_uploads(config, upload_dir, time.time() if now is None else now)
    if not uploads:
        return 0

    connection_type = smtplib.SMTP_SSL if config.smtp.tls else smtplib.SMTP
    with connection_type(config.smtp.server, config.smtp.port, timeout=30) as connection:
        if config.smtp.starttls:
            connection.ehlo()
            connection.starttls()
            connection.ehlo()
        if smtp_username and smtp_password:
            connection.login(smtp_username, smtp_password)
        for target, filenames in uploads.items():
            connection.send_message(build_message(config, target, upload_dir / target, filenames))
    return len(uploads)


def main() -> None:
    config_path = Path(os.environ.get("CONFIG_FILE", DEFAULT_CONFIG_FILE))
    upload_dir = Path(os.environ.get("UPLOAD_DIR", Path(__file__).resolve().parent / "data" / "uploads"))
    # Snap to the timer's slot boundary so consecutive windows tile exactly,
    # regardless of how long after the boundary this process actually started.
    now = time.time() // SCAN_INTERVAL_SECONDS * SCAN_INTERVAL_SECONDS
    try:
        config = load_config(config_path)
        sent = send_recent_upload_notifications(
            config,
            upload_dir,
            now=now,
            smtp_username=os.environ.get("SMTP_USERNAME") or None,
            smtp_password=os.environ.get("SMTP_PASSWORD") or None,
        )
    except (OSError, ValueError, smtplib.SMTPException) as error:
        raise SystemExit(f"Upload notification failed: {error}") from error
    print(f"Sent {sent} upload notification(s)")


if __name__ == "__main__":
    main()