aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJason McCormick <jason@mfamily.org>2026-11-05 18:37:48 -0500
committerJason McCormick <jason@mfamily.org>2026-11-05 18:37:48 -0500
commitc2382d8b4cf93489614c5fe70a604ab698b9f613 (patch)
tree8a8b28d010292271b24b9c3cd6bc175fc58e2a95
parent75719aa37f7317f3a8feeb516f1444edb4274410 (diff)
feat: 1-minute watcher and per-stanza email subject/header
Run the notification timer every minute and shrink the scan window to match. Each upload URI stanza may now set subject and body_header to override the default notification text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--README.md4
-rw-r--r--config.toml4
-rw-r--r--deploy/blind-uploader-watcher.timer6
-rw-r--r--server.py29
-rw-r--r--tests/test_server.py40
-rw-r--r--watcher.py6
6 files changed, 79 insertions, 10 deletions
diff --git a/README.md b/README.md
index 9945aae..163b5f9 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,8 @@ starttls = true # STARTTLS upgrade (typically port 587)
[logo-contest]
recipient = "reviewer@example.com"
view_url_prefix = "https://review.example.com/logo-contest/" # optional
+subject = "New logo contest entry" # optional
+body_header = "A new logo contest entry has arrived." # optional
["911u19jasdl"] # quote names that TOML would not accept bare
recipient = "other@example.com"
@@ -36,7 +38,7 @@ Stanza names must be a single segment made of letters, numbers, underscores, or
## Upload notifications
-`watcher.py` is run every 5 minutes by `blind-uploader-watcher.timer`, which fires at :00, :05, :10, and so on. It checks each configured drop for an image modified during the last 5-minute slot. If it finds one, it sends a single email to that drop's recipient. The email has no attachment. It includes the submission details (callsign, name, email, and description) from each new image's `.txt` sidecar. If the stanza sets `view_url_prefix`, the email links to each new image as `<view_url_prefix><stored filename>`, for example `https://review.example.com/logo-contest/3f9c…a1.png`. The prefix must be an absolute `http`/`https` URL, and a trailing `/` is added if missing. It should point at the separately protected nginx location that serves this drop's upload directory. Without a prefix, the email contains only the generic message. Nothing is stored between runs. If the system is down or the timer is stopped during a slot, uploads from that slot are never reported.
+`watcher.py` is run every minute by `blind-uploader-watcher.timer`, at the top of each minute. It checks each configured drop for an image modified during the last 1-minute slot. If it finds one, it sends a single email to that drop's recipient. The email has no attachment. It includes the submission details (callsign, name, email, and description) from each new image's `.txt` sidecar. If the stanza sets `view_url_prefix`, the email links to each new image as `<view_url_prefix><stored filename>`, for example `https://review.example.com/logo-contest/3f9c…a1.png`. The prefix must be an absolute `http`/`https` URL, and a trailing `/` is added if missing. It should point at the separately protected nginx location that serves this drop's upload directory. Without a prefix, each image is identified by its stored filename. A stanza can also set `subject` (one line, up to 200 characters) and `body_header` (the text above the per-image details, up to 2000 characters, and multi-line `"""` strings are allowed). Without them, the subject is "New upload received" and the header is "A new file has been uploaded to your private drop." Nothing is stored between runs. If the system is down or the timer is stopped during a slot, uploads from that slot are never reported.
If your SMTP server requires authentication, put the credentials in `/etc/default/blind-uploader-watcher` and make the file `root:root` mode `0600`:
diff --git a/config.toml b/config.toml
index c373438..448e729 100644
--- a/config.toml
+++ b/config.toml
@@ -10,3 +10,7 @@ recipient = "reviewer@example.com"
# Optional: where nginx serves this drop's files for viewing. Each notification
# links to <view_url_prefix><stored filename>.
view_url_prefix = "https://review.example.com/logo-contest/"
+# Optional: notification subject (one line) and the text above the per-image
+# details (may be multi-line with """...""").
+subject = "New logo contest entry"
+body_header = "A new logo contest entry has arrived."
diff --git a/deploy/blind-uploader-watcher.timer b/deploy/blind-uploader-watcher.timer
index d076334..9ae1395 100644
--- a/deploy/blind-uploader-watcher.timer
+++ b/deploy/blind-uploader-watcher.timer
@@ -1,10 +1,10 @@
[Unit]
-Description=Run the Private Drop upload notifier every 5 minutes
+Description=Run the Private Drop upload notifier every minute
[Timer]
-# Fixed wall-clock slots keep consecutive 5-minute scan windows aligned, so an
+# Fixed wall-clock slots keep consecutive 1-minute scan windows aligned, so an
# upload is reported once. Keep this in sync with SCAN_INTERVAL_SECONDS.
-OnCalendar=*:0/5
+OnCalendar=*:*:00
AccuracySec=1s
Persistent=false
diff --git a/server.py b/server.py
index b28db69..11de344 100644
--- a/server.py
+++ b/server.py
@@ -51,6 +51,9 @@ class AppConfig:
recipients: dict[str, str]
# Absolute http(s) URL, ending in "/", under which a target's stored files are viewable.
view_url_prefixes: dict[str, str] = field(default_factory=dict)
+ # Optional per-target notification email overrides.
+ subjects: dict[str, str] = field(default_factory=dict)
+ body_headers: dict[str, str] = field(default_factory=dict)
def target_from_path(path: str) -> str | None:
@@ -82,6 +85,19 @@ def _validate_view_url_prefix(value: object, setting: str) -> str:
return value if value.endswith("/") else value + "/"
+def _validate_text(value: object, setting: str, max_length: int, multiline: bool) -> str:
+ allowed = "\n\t" if multiline else "\t"
+ if (
+ not isinstance(value, str)
+ or not value.strip()
+ or len(value) > max_length
+ or any((ord(character) < 32 and character not in allowed) or ord(character) == 127 for character in value)
+ ):
+ kind = "text" if multiline else "single-line text"
+ raise ValueError(f"{setting} must be non-empty {kind} of at most {max_length} characters")
+ return value.strip()
+
+
def load_config(path: Path) -> AppConfig:
"""Load SMTP settings and URI-to-recipient mappings from TOML."""
try:
@@ -111,7 +127,9 @@ def load_config(path: Path) -> AppConfig:
recipients: dict[str, str] = {}
view_url_prefixes: dict[str, str] = {}
- allowed_keys = {"recipient", "view_url_prefix"}
+ subjects: dict[str, str] = {}
+ body_headers: dict[str, str] = {}
+ allowed_keys = {"recipient", "view_url_prefix", "subject", "body_header"}
for stanza, values in raw_config.items():
if stanza == "GLOBAL":
continue
@@ -120,13 +138,18 @@ def load_config(path: Path) -> AppConfig:
raise ValueError(f"Invalid upload URI stanza in {path}: {stanza!r}")
if not isinstance(values, dict) or "recipient" not in values or not set(values) <= allowed_keys:
raise ValueError(
- f"[{stanza}] in {path} must define recipient and may define only view_url_prefix besides it"
+ f"[{stanza}] in {path} must define recipient and may also define only: "
+ f"{', '.join(sorted(allowed_keys - {'recipient'}))}"
)
recipients[target] = _validate_email(values["recipient"], f"{stanza}.recipient")
if "view_url_prefix" in values:
view_url_prefixes[target] = _validate_view_url_prefix(
values["view_url_prefix"], f"{stanza}.view_url_prefix"
)
+ if "subject" in values:
+ subjects[target] = _validate_text(values["subject"], f"{stanza}.subject", 200, multiline=False)
+ if "body_header" in values:
+ body_headers[target] = _validate_text(values["body_header"], f"{stanza}.body_header", 2000, multiline=True)
if not recipients:
raise ValueError(f"No upload URI stanzas are configured in {path}")
@@ -134,6 +157,8 @@ def load_config(path: Path) -> AppConfig:
smtp=SMTPSettings(send_as, smtp_server, smtp_port, tls, starttls),
recipients=recipients,
view_url_prefixes=view_url_prefixes,
+ subjects=subjects,
+ body_headers=body_headers,
)
diff --git a/tests/test_server.py b/tests/test_server.py
index 4644ecc..888568f 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -225,7 +225,7 @@ class ServerTests(unittest.TestCase):
encoding="utf-8",
)
config = load_config(config_file)
- for target, mtime in (("alpha", 1990), ("beta", 1700), ("gamma", 2000)):
+ for target, mtime in (("alpha", 1990), ("beta", 1940), ("gamma", 2000)):
directory = self.upload_dir / target
directory.mkdir(parents=True)
(directory / "x.png").write_bytes(PNG)
@@ -287,6 +287,44 @@ class ServerTests(unittest.TestCase):
with self.subTest(prefix=prefix), self.assertRaises(ValueError):
load_config(config_file)
+ def test_watcher_uses_per_stanza_subject_and_body_header(self):
+ config_file = Path(self.temp.name) / "watcher.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 25\ntls = false\nstarttls = false\n\n"
+ '[custom]\nrecipient = "a@example.com"\nsubject = "Logo entry"\n'
+ 'body_header = """\nHello reviewers,\nA new entry arrived.\n"""\n\n'
+ '[plain]\nrecipient = "b@example.com"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
+ for target in ("custom", "plain"):
+ directory = self.upload_dir / target
+ directory.mkdir(parents=True)
+ (directory / "x.png").write_bytes(PNG)
+ os.utime(directory / "x.png", (1990, 1990))
+ smtp_context = MagicMock()
+ with patch("watcher.smtplib.SMTP", return_value=smtp_context):
+ send_recent_upload_notifications(config, self.upload_dir, now=2000)
+
+ custom, plain = (call.args[0] for call in smtp_context.__enter__.return_value.send_message.call_args_list)
+ self.assertEqual(custom["Subject"], "Logo entry")
+ self.assertTrue(custom.get_content().startswith("Hello reviewers,\nA new entry arrived.\n\n---"))
+ self.assertEqual(plain["Subject"], "New upload received")
+ self.assertTrue(plain.get_content().startswith("A new file has been uploaded to your private drop."))
+
+ def test_rejects_invalid_subject_and_body_header(self):
+ config_file = Path(self.temp.name) / "config.toml"
+ for setting in ('subject = "two\\nlines"', 'subject = " "', 'body_header = "bell\\u0007"', "subject = 5"):
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 25\ntls = false\nstarttls = false\n\n"
+ f'[logo-contest]\nrecipient = "reviewer@example.com"\n{setting}\n',
+ encoding="utf-8",
+ )
+ with self.subTest(setting=setting), self.assertRaises(ValueError):
+ load_config(config_file)
+
def test_watcher_skips_smtp_when_nothing_is_new(self):
config_file = Path(self.temp.name) / "watcher.toml"
config_file.write_text(
diff --git a/watcher.py b/watcher.py
index 9799bae..e5df0b6 100644
--- a/watcher.py
+++ b/watcher.py
@@ -20,7 +20,7 @@ from urllib.parse import quote
from server import DEFAULT_CONFIG_FILE, AppConfig, load_config
-SCAN_INTERVAL_SECONDS = 5 * 60
+SCAN_INTERVAL_SECONDS = 60
IMAGE_SUFFIXES = {".jpg", ".png", ".heic"}
SUBJECT = "New upload received"
BODY = "A new file has been uploaded to your private drop."
@@ -71,11 +71,11 @@ def build_message(config: AppConfig, target: str, target_dir: Path, filenames: l
message = EmailMessage()
message["From"] = config.smtp.send_as
message["To"] = config.recipients[target]
- message["Subject"] = SUBJECT
+ message["Subject"] = config.subjects.get(target, 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]
+ sections = [config.body_headers.get(target, 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}"