diff options
Diffstat (limited to 'watcher.py')
| -rw-r--r-- | watcher.py | 136 |
1 files changed, 136 insertions, 0 deletions
diff --git a/watcher.py b/watcher.py new file mode 100644 index 0000000..9799bae --- /dev/null +++ b/watcher.py @@ -0,0 +1,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() |
