"""Best-effort notifications for new (moderated) comments. Two independent channels, both configured with env vars: * Email over plain SMTP, so any provider works (Postmark, SendGrid, Mailgun, Fastmail, a self-hosted relay, ...). * Push via ntfy (https://ntfy.sh) — by default the self-hosted ntfy service in this project's docker-compose file, but any ntfy server works. When a channel is unconfigured it does nothing. Delivery runs on daemon threads and never raises into the comment request: a mail or push outage must not lose a visitor's comment. """ import logging import os import smtplib import ssl import threading import urllib.parse import urllib.request from email.message import EmailMessage log = logging.getLogger(__name__) NTFY_PRIORITIES = { "min", "low", "default", "high", "urgent", "max", "1", "2", "3", "4", "5", } def smtp_config(): """Return SMTP settings from the environment, or None when unconfigured.""" host = (os.environ.get("BLOG_SMTP_HOST") or "").strip() recipient = (os.environ.get("BLOG_NOTIFY_EMAIL") or "").strip() if not host or not recipient: return None try: port = int(os.environ.get("BLOG_SMTP_PORT") or 587) except ValueError: port = 587 user = (os.environ.get("BLOG_SMTP_USER") or "").strip() sender = (os.environ.get("BLOG_SMTP_FROM") or "").strip() or user or recipient tls = (os.environ.get("BLOG_SMTP_TLS") or "1").strip().lower() not in ( "0", "false", "no", "off", ) return { "host": host, "port": port, "user": user, "password": os.environ.get("BLOG_SMTP_PASSWORD") or "", "sender": sender, "recipient": recipient, "tls": tls, } def ntfy_config(): """Return ntfy settings from the environment, or None when unconfigured.""" base = (os.environ.get("BLOG_NTFY_URL") or "").strip().rstrip("/") topic = (os.environ.get("BLOG_NTFY_TOPIC") or "").strip().strip("/") if not base or not topic: return None priority = (os.environ.get("BLOG_NTFY_PRIORITY") or "").strip().lower() if priority not in NTFY_PRIORITIES: priority = "default" return { "url": "%s/%s" % (base, urllib.parse.quote(topic, safe="")), "token": (os.environ.get("BLOG_NTFY_TOKEN") or "").strip(), "priority": priority, } def notify_new_comment(comment_author, comment_body, comment_email, target_title, target_url, moderation_url=""): """Queue admin alerts about a pending comment. No-op when unconfigured. Returns True when at least one channel was configured and queued. """ queued = False email_config = smtp_config() if email_config: threading.Thread( target=_send_email, args=(email_config, comment_author, comment_body, comment_email, target_title, target_url, moderation_url), daemon=True, ).start() queued = True push_config = ntfy_config() if push_config: threading.Thread( target=_send_ntfy, args=(push_config, comment_author, comment_body, target_title, target_url, moderation_url), daemon=True, ).start() queued = True return queued def _send_email(config, author, body, email, title, url, moderation_url): try: message = EmailMessage() message["Subject"] = "New comment awaiting moderation: %s" % (title or "your blog") message["From"] = config["sender"] message["To"] = config["recipient"] if email: # Replying to the notification goes straight to the commenter. message["Reply-To"] = email excerpt = body if len(body) <= 2000 else body[:2000] + "..." message.set_content( "A new comment is waiting for moderation.\n\n" "Post: %s\n" "URL: %s\n" "Author: %s\n" "Email: %s\n\n" "%s\n\n" "Moderate: %s\n" % (title or "", url or "", author or "", email or "not provided", excerpt, moderation_url or "") ) with smtplib.SMTP(config["host"], config["port"], timeout=15) as smtp: smtp.ehlo() if config["tls"]: smtp.starttls(context=ssl.create_default_context()) smtp.ehlo() if config["user"]: smtp.login(config["user"], config["password"]) smtp.send_message(message) except Exception: log.warning("comment notification email failed", exc_info=True) def _send_ntfy(config, author, body, title, url, moderation_url): try: excerpt = body.strip() if len(excerpt) > 1000: excerpt = excerpt[:1000].rstrip() + "..." lines = ["%s commented on %s" % (author or "Someone", title or "your blog")] if url: lines.append(url) lines.extend(["", excerpt]) headers = { # ntfy shows this as the push title. Kept ASCII so urllib can always # encode it; the post title is in the message body instead. "Title": "New comment awaiting moderation", "Priority": config["priority"], "Tags": "speech_balloon", "Content-Type": "text/plain; charset=utf-8", } if moderation_url and moderation_url.isascii(): # Tapping the notification opens the moderation queue. headers["Click"] = moderation_url request = urllib.request.Request( config["url"], data="\n".join(lines).encode("utf-8"), headers=headers, method="POST", ) if config["token"]: request.add_header("Authorization", "Bearer " + config["token"]) with urllib.request.urlopen(request, timeout=10) as response: response.read(1) except Exception: log.warning("ntfy notification failed", exc_info=True)