added
This commit is contained in:
1 parent
eac3d5dc45
commit
2a2b00733b
83 files changed
+4840
No files matched your search
@@ -0,0 +1,87 @@
|
||||
"""Campaign front-matter validation and dependency-free rendering."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
REQUIRED_FIELDS = {"schema_version", "campaign_id", "subject", "from_name", "reply_to", "audience"}
|
||||
ALLOWED_FIELDS = REQUIRED_FIELDS | {"preheader"}
|
||||
CAMPAIGN_ID = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
|
||||
|
||||
def parse_campaign(path: Path) -> tuple[dict[str, str], str]:
|
||||
source = path.read_text(encoding="utf-8")
|
||||
if not source.startswith("---\n"):
|
||||
raise ValueError("Campaign must begin with YAML front matter")
|
||||
try:
|
||||
front_matter, body = source[4:].split("\n---\n", 1)
|
||||
except ValueError as error:
|
||||
raise ValueError("Campaign front matter must end with ---") from error
|
||||
metadata: dict[str, str] = {}
|
||||
for line in front_matter.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
if ":" not in line:
|
||||
raise ValueError(f"Invalid front-matter line: {line}")
|
||||
key, value = line.split(":", 1)
|
||||
metadata[key.strip()] = value.strip().strip('"')
|
||||
missing = sorted(REQUIRED_FIELDS - metadata.keys())
|
||||
unknown = sorted(metadata.keys() - ALLOWED_FIELDS)
|
||||
if missing:
|
||||
raise ValueError(f"Missing campaign metadata: {', '.join(missing)}")
|
||||
if unknown:
|
||||
raise ValueError(f"Unsupported campaign metadata: {', '.join(unknown)}")
|
||||
if metadata["schema_version"] != "1.0" or not CAMPAIGN_ID.fullmatch(metadata["campaign_id"]):
|
||||
raise ValueError("Campaign schema_version or campaign_id is invalid")
|
||||
if metadata["audience"] != "active" or "@" not in metadata["reply_to"]:
|
||||
raise ValueError("Campaign audience or reply_to is invalid")
|
||||
if not body.strip():
|
||||
raise ValueError("Campaign body may not be empty")
|
||||
for url in re.findall(r"\[[^\]]+\]\(([^)]+)\)", body):
|
||||
if not url.startswith("https://"):
|
||||
raise ValueError("Campaign links must use https")
|
||||
return metadata, body.strip()
|
||||
|
||||
|
||||
def render_markdown(body: str) -> tuple[str, str]:
|
||||
paragraphs = [part.strip() for part in re.split(r"\n\s*\n", body) if part.strip()]
|
||||
html_parts: list[str] = []
|
||||
text_parts: list[str] = []
|
||||
for paragraph in paragraphs:
|
||||
if paragraph.startswith("# "):
|
||||
content = paragraph[2:].strip()
|
||||
html_parts.append(f"<h1>{html.escape(content)}</h1>")
|
||||
text_parts.append(content)
|
||||
else:
|
||||
content = html.escape(paragraph).replace("\n", "<br> ")
|
||||
content = re.sub(r"\[([^\]]+)\]\((https?://[^)\s]+)\)", r'<a href="\2">\1</a>', content)
|
||||
html_parts.append(f"<p>{content}</p>")
|
||||
text_parts.append(re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", paragraph))
|
||||
return "\n".join(html_parts), "\n\n".join(text_parts)
|
||||
|
||||
|
||||
def campaign_result(path: Path) -> dict[str, object]:
|
||||
metadata, body = parse_campaign(path)
|
||||
rendered_html, rendered_text = render_markdown(body)
|
||||
source = path.read_bytes()
|
||||
template_path = Path(os.environ.get("EMAIL_LIST_TEMPLATE_DIR", "templates")) / "campaign.html"
|
||||
if not template_path.is_file():
|
||||
raise FileNotFoundError(f"Campaign template is missing: {template_path}")
|
||||
template = template_path.read_text(encoding="utf-8")
|
||||
final_html = template.replace("{{subject}}", html.escape(metadata["subject"]))
|
||||
final_html = final_html.replace("{{content}}", rendered_html)
|
||||
rendered_text = rendered_text + "\n\nUnsubscribe: {{{ pm:unsubscribe }}}"
|
||||
return {
|
||||
"schema_version": "1.0",
|
||||
"campaign_id": metadata["campaign_id"],
|
||||
"metadata": metadata,
|
||||
"content_hash": hashlib.sha256(source).hexdigest(),
|
||||
"template_hash": hashlib.sha256(template.encode()).hexdigest(),
|
||||
"rendered_html": final_html,
|
||||
"rendered_text": rendered_text,
|
||||
}
|
||||
Reference in new issue
Block a user