Coverage for app/backend/src/couchers/email/rendering.py: 95%
130 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-10 09:48 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-10 09:48 +0000
1"""
2Renders blocks-based emails to HTML or plaintext emails for a locale.
3"""
5import re
6from dataclasses import asdict, dataclass
7from email.headerregistry import Address
8from functools import cache
9from pathlib import Path
10from typing import Any
12from markupsafe import Markup
14from couchers.config import config
15from couchers.email.blocks import ActionBlock, EmailBase, EmailBlock, EmailFooter, ParaBlock, QuoteBlock, UserBlock
16from couchers.email.locales import get_emails_i18next
17from couchers.email.smtp import embed_html_relative_images
18from couchers.i18n import LocalizationContext
19from couchers.i18n.i18next import SubstitutionDict, full_string_key
20from couchers.markup import html_mailto_link, html_to_plaintext, markdown_to_html
21from couchers.proto.internal import jobs_pb2
22from couchers.templating import Jinja2Template
24template_folder = Path(__file__).parent.parent.parent.parent / "templates" / "v2"
27@dataclass(kw_only=True, slots=True)
28class RenderedEmail:
29 subject: str
30 body_plaintext: str
31 body_html: str
32 html_image_parts: list[jobs_pb2.EmailPart]
35def render_email(
36 email: EmailBase, footer: EmailFooter, loc_context: LocalizationContext, *, embed_images: bool = True
37) -> RenderedEmail:
38 """Renders an EmailBase object to subject and body strings."""
39 subject = email.get_subject_line(loc_context)
40 preview = email.get_preview_line(loc_context)
41 body_blocks = email.get_body_blocks(loc_context)
43 body_plaintext = render_plaintext_body(blocks=body_blocks, footer=footer, loc_context=loc_context)
44 body_html = render_html_body(
45 subject=subject, preview=preview, blocks=body_blocks, footer=footer, loc_context=loc_context
46 )
48 related_parts: list[jobs_pb2.EmailPart] = []
49 if embed_images:
50 content_id_domain = Address(addr_spec=config.NOTIFICATION_EMAIL_ADDRESS).domain
51 body_html, related_parts = embed_html_relative_images(
52 body_html, base_dir=template_folder, content_id_domain=content_id_domain
53 )
55 return RenderedEmail(
56 subject=subject, body_plaintext=body_plaintext, body_html=body_html, html_image_parts=related_parts
57 )
60def render_plaintext_body(*, blocks: list[EmailBlock], footer: EmailFooter, loc_context: LocalizationContext) -> str:
61 """Renders the body of an email as plaintext."""
62 concat: list[str] = []
64 previous_block: EmailBlock | None = None
65 for block in blocks:
66 # Blank line between every two blocks except subsequent actions.
67 if previous_block is not None:
68 if isinstance(block, ActionBlock) and isinstance(previous_block, ActionBlock):
69 concat.append("\n")
70 else:
71 concat.append("\n\n")
73 match block:
74 case ParaBlock():
75 concat.append(_to_plaintext(block.text))
76 case UserBlock():
77 line = loc_context.localize_string(
78 "plaintext_formats.user",
79 i18next=get_emails_i18next(),
80 substitutions={"name": block.info.name, "age": str(block.info.age), "city": block.info.city},
81 )
82 concat.append(line)
83 if block.comment:
84 concat.append("\n")
85 concat.append(_to_plaintext(block.comment))
86 case QuoteBlock():
87 for line in block.text.splitlines():
88 concat.append(f"> {line}")
89 case ActionBlock(): 89 ↛ 96line 89 didn't jump to line 96 because the pattern on line 89 always matched
90 line = loc_context.localize_string(
91 "plaintext_formats.action",
92 i18next=get_emails_i18next(),
93 substitutions={"text": block.text, "url": block.target_url},
94 )
95 concat.append(line)
96 case _:
97 raise TypeError(f"Unexpected email block type: {block.__class__}")
98 previous_block = block
100 concat.append("\n\n")
102 footer_template = Jinja2Template(
103 source=(template_folder / "_footer.txt").read_text(encoding="utf8").strip(), html=False
104 )
105 footer_template_args = _get_footer_template_args(footer, loc_context)
106 concat.append(footer_template.render(footer_template_args))
108 return "".join(concat)
111def _to_plaintext(text: str | Markup) -> str:
112 """
113 Converts any markup in its plaintext equivalent, allowing reuse of translations that have span-level markup
114 like <b> when formatting as plaintext email bodies.
115 """
116 if isinstance(text, Markup): 116 ↛ 119line 116 didn't jump to line 119 because the condition on line 116 was always true
117 return html_to_plaintext(text)
118 else:
119 return text
122def _get_footer_template_args(footer: EmailFooter, loc_context: LocalizationContext) -> dict[str, Any]:
123 i18n = get_emails_i18next()
125 def localize(key: str, substitutions: SubstitutionDict | None = None) -> Markup:
126 key = full_string_key(key, relative_base="generic.footer")
127 return i18n.localize_with_markup(key, loc_context.locale_list, substitutions)
129 args: dict[str, Any] = {
130 "received_because": localize(".received_because"),
131 "contact_support": localize(".contact_support", {"email_link": html_mailto_link("support@couchers.org")}),
132 "copyright_year": footer.copyright_year,
133 "donate_link": localize(".donate_link"),
134 "volunteer_link": localize(".volunteer_link"),
135 "blog_link": localize(".blog_link"),
136 "nonprofit_note": localize(".nonprofit_note"),
137 "is_critical": footer.unsubscribe_info is None,
138 }
140 if unsubscribe_info := footer.unsubscribe_info:
141 # TODO(#7420): Localize "Turn off emails for: " text, avoiding string concatenations.
142 args.update(
143 {
144 "notification_settings_link": localize(".notification_settings_link"),
145 "manage_notifications_url": unsubscribe_info.manage_notifications_url,
146 "do_not_email_link": localize(".do_not_email_link"),
147 "do_not_email_url": unsubscribe_info.do_not_email_url,
148 "topic_action_description": unsubscribe_info.topic_action_link.text,
149 "unsubscribe_topic_action_url": unsubscribe_info.topic_action_link.url,
150 }
151 )
153 if topic_key_link := unsubscribe_info.topic_key_link:
154 args["topic_key_description"] = topic_key_link.text
155 args["unsubscribe_topic_key_url"] = topic_key_link.url
156 else:
157 args["security_email_note"] = localize(".security_email_note")
159 return args
162def render_html_body(
163 *,
164 subject: str,
165 preview: str | None,
166 blocks: list[EmailBlock],
167 footer: EmailFooter,
168 loc_context: LocalizationContext,
169) -> str:
170 """Renders the body of an email as HTML."""
171 return HTMLRenderer.default().render(
172 subject=subject, preview=preview, blocks=blocks, footer=footer, loc_context=loc_context
173 )
176@dataclass(kw_only=True, slots=True)
177class TwoButtonHTMLBlock(EmailBlock):
178 """An HTML-only block used internally for rendering as side-by-side buttons."""
180 text_1: str
181 target_url_1: str
182 text_2: str
183 target_url_2: str
186# Matches a begin-block / end-block pair of comments in the html file containing template
187_block_regex = re.compile(
188 r"""
189<!-- begin-block:(?P<name>[\w-]+) -->\s*
190(?P<snippet>[\s\S]*?)
191\s*<!-- end-block:(?P=name) -->
192""".strip(),
193 re.MULTILINE,
194)
197@dataclass
198class HTMLRenderer:
199 """Renders an email as HTML using template snippets for the header, footer and each block."""
201 header_template: Jinja2Template
202 footer_template: Jinja2Template
203 para_block_template: Jinja2Template
204 user_block_template: Jinja2Template
205 quote_block_template: Jinja2Template
206 action_block_template: Jinja2Template
207 two_buttons_block_template: Jinja2Template
209 def render(
210 self,
211 *,
212 subject: str,
213 preview: str | None,
214 blocks: list[EmailBlock],
215 footer: EmailFooter,
216 loc_context: LocalizationContext,
217 ) -> str:
218 concats: list[str] = []
220 # Render the header
221 concats.append(
222 self.header_template.render(
223 {
224 "header_subject": subject,
225 "header_preview": preview or "",
226 },
227 )
228 )
230 # Render each block
231 for block in type(self)._merge_action_blocks(blocks):
232 match block:
233 case ParaBlock():
234 concats.append(self.para_block_template.render(asdict(block)))
235 case UserBlock():
236 concats.append(
237 self.user_block_template.render(
238 {
239 "name": block.info.name,
240 "age": block.info.age,
241 "city": block.info.city,
242 "profile_url": block.info.profile_url,
243 "avatar_url": block.info.avatar_url,
244 "comment": block.comment,
245 },
246 )
247 )
248 case QuoteBlock():
249 args = {"text": Markup(markdown_to_html(block.text)) if block.markdown else block.text}
250 concats.append(self.quote_block_template.render(args))
251 case ActionBlock():
252 concats.append(self.action_block_template.render(asdict(block)))
253 case TwoButtonHTMLBlock(): 253 ↛ 255line 253 didn't jump to line 255 because the pattern on line 253 always matched
254 concats.append(self.two_buttons_block_template.render(asdict(block)))
255 case _:
256 raise TypeError(f"Unexpected email block type: {block.__class__}")
258 # Render the footer
259 footer_template_args = _get_footer_template_args(footer, loc_context)
260 concats.append(self.footer_template.render(footer_template_args))
262 return "\n".join(concats)
264 @staticmethod
265 def _merge_action_blocks(blocks: list[EmailBlock]) -> list[EmailBlock]:
266 """Merge any two subsequent action blocks into a single two-button block."""
267 blocks = blocks.copy()
269 block_index = 0
270 while block_index + 1 < len(blocks):
271 block = blocks[block_index]
272 next_block = blocks[block_index + 1]
273 if isinstance(block, ActionBlock) and isinstance(next_block, ActionBlock):
274 blocks[block_index] = TwoButtonHTMLBlock(
275 target_url_1=block.target_url,
276 text_1=block.text,
277 target_url_2=next_block.target_url,
278 text_2=next_block.text,
279 )
280 blocks.pop(block_index + 1)
282 block_index += 1
284 return blocks
286 @cache
287 @staticmethod
288 def default() -> HTMLRenderer:
289 template = (template_folder / "generated_html" / "blocks.html").read_text(encoding="utf8")
290 return HTMLRenderer.from_template(template)
292 @staticmethod
293 def from_template(template: str) -> HTMLRenderer:
294 section_matches = list(_block_regex.finditer(template))
296 header_template = template[: section_matches[0].start()]
297 footer_template = template[section_matches[-1].end() :]
298 block_templates = {match.group("name"): match.group("snippet") for match in section_matches}
300 return HTMLRenderer(
301 header_template=Jinja2Template(source=header_template, html=True),
302 footer_template=Jinja2Template(source=footer_template, html=True),
303 para_block_template=Jinja2Template(source=block_templates["para"], html=True),
304 user_block_template=Jinja2Template(source=block_templates["user"], html=True),
305 quote_block_template=Jinja2Template(source=block_templates["quote"], html=True),
306 action_block_template=Jinja2Template(source=block_templates["action"], html=True),
307 two_buttons_block_template=Jinja2Template(source=block_templates["two-buttons"], html=True),
308 )