Skip to main content

tuwunel_service/pusher/email/
render.rs

1use std::{borrow::Cow, fmt::Write};
2
3use futures::StreamExt;
4use ruma::{OwnedRoomId, RoomId, UserId, events::TimelineEventType};
5use serde::Deserialize;
6use tuwunel_core::{
7	Result, debug_warn, implement,
8	itertools::Itertools,
9	result::{FlatOk, NotFound},
10	utils::{
11		BoolExt,
12		stream::{IterStream, WidebandExt},
13		string::{plural, single_line},
14		time::format as format_time,
15	},
16};
17use tuwunel_matrix::{Event, pdu::Pdu};
18
19use super::evaluate::{Pending, Scan, invites};
20use crate::sendmail::Address;
21
22pub(super) struct Mail {
23	pub(super) subject: String,
24	pub(super) text: String,
25}
26
27/// What a notification email says, with every name already resolved.
28///
29/// Rooms come most recent first, so the renderers only lay it out.
30pub(super) struct Digest<'a> {
31	pub(super) brand: &'a str,
32
33	pub(super) address: &'a str,
34
35	pub(super) rooms: Vec<Room>,
36
37	/// Notifications left out past `SHOWN`.
38	pub(super) hidden: usize,
39
40	/// Rooms with notifications to mail, including any whose notifications are
41	/// all left out.
42	pub(super) room_count: usize,
43
44	/// Whether the mail's only notification is an invite, whose sender the
45	/// subject names.
46	pub(super) invite: bool,
47}
48
49pub(super) struct Room {
50	/// The room's name or canonical alias, when it has either.
51	pub(super) name: Option<String>,
52
53	pub(super) id: OwnedRoomId,
54
55	pub(super) lines: Vec<Line>,
56}
57
58pub(super) struct Line {
59	pub(super) sender: String,
60	pub(super) time: String,
61	pub(super) snippet: Cow<'static, str>,
62}
63
64#[derive(Deserialize)]
65struct Body {
66	body: String,
67}
68
69/// Notifications shown in one email.
70///
71/// The rest are counted at the end.
72pub(super) const SHOWN: usize = 20;
73
74const SNIPPET_CHARS: usize = 300;
75
76const UNNAMED_ROOM: &str = "an unnamed room";
77
78/// Renders the email for a scan's newest pending notifications.
79///
80/// Rooms come most recent first and each lists its notifications newest first;
81/// the scan's remaining notifications are counted after them, and the subject
82/// counts every room in the scan. A lone pending invite names its inviter in
83/// the subject.
84#[implement(super::super::Service)]
85#[tracing::instrument(
86	level = "debug",
87	skip_all,
88	fields(
89		%user_id,
90	),
91)]
92pub(super) async fn render_email(
93	&self,
94	user_id: &UserId,
95	address: &Address,
96	brand: &str,
97	scan: &Scan,
98) -> Mail {
99	let shown = &scan.newest;
100	let newest = shown.iter().rev();
101	let rooms: Vec<_> = newest
102		.clone()
103		.map(|pending| pending.pdu.room_id())
104		.unique()
105		.stream()
106		.wide_then(async |room_id| {
107			let notifications = newest
108				.clone()
109				.filter(|pending| pending.pdu.room_id() == room_id);
110
111			self.render_room(user_id, room_id, notifications)
112				.await
113		})
114		.collect()
115		.await;
116
117	let invite = shown
118		.iter()
119		.exactly_one()
120		.is_ok_and(|only| invites(&only.pdu, user_id));
121
122	let digest = Digest {
123		brand,
124		address: address.as_ref(),
125		rooms,
126		hidden: scan.total.saturating_sub(shown.len()),
127		room_count: scan.rooms.len(),
128		invite,
129	};
130
131	Mail {
132		subject: subject(&digest),
133		text: text(&digest),
134	}
135}
136
137#[implement(super::super::Service)]
138async fn render_room<'a, Shown>(&self, user_id: &UserId, room_id: &RoomId, shown: Shown) -> Room
139where
140	Shown: Iterator<Item = &'a Pending> + Send,
141{
142	// Sequential: the room fan-out in `render_email` is the parallelism budget.
143	let lines: Vec<_> = shown
144		.stream()
145		.then(async |pending| {
146			let sender = self
147				.sender_name(room_id, pending.pdu.sender())
148				.await;
149
150			Line {
151				sender,
152				time: sent_at(&pending.pdu),
153				snippet: snippet(&pending.pdu, user_id),
154			}
155		})
156		.collect()
157		.await;
158
159	let name = self.room_name(room_id).await;
160
161	Room { name, id: room_id.to_owned(), lines }
162}
163
164/// The sender's name in the room, else in their profile, else their ID.
165///
166/// Clients label a sender with the name set for the room, so the mail does too.
167/// Each name is put on one line first, and one left with no text falls through
168/// to the next.
169#[implement(super::super::Service)]
170async fn sender_name(&self, room_id: &RoomId, sender: &UserId) -> String {
171	let member = self
172		.services
173		.state_accessor
174		.get_member(room_id, sender)
175		.await;
176
177	let name = found(member, room_id, Some(sender))
178		.and_then(|member| member.displayname)
179		.and_then(visible_name);
180
181	if let Some(name) = name {
182		return name;
183	}
184
185	let displayname = self.services.profile.displayname(sender).await;
186
187	found(displayname, room_id, Some(sender))
188		.and_then(visible_name)
189		.unwrap_or_else(|| one_line(sender.to_string()))
190}
191
192/// A name read's value, or `None` when it is absent or cannot be read.
193///
194/// A failed read is logged at debug level, since it costs the mail only a
195/// label.
196fn found<T>(read: Result<T>, room_id: &RoomId, sender: Option<&UserId>) -> Option<T> {
197	read.optional()
198		.inspect_err(|error| {
199			// Debug: a remote's malformed member or name event fails here at every mail.
200			debug_warn!(%room_id, ?sender, %error, "Failed to read a name for an email");
201		})
202		.flat_ok()
203}
204
205/// Remote-supplied text put on one line, or `None` when that leaves no text.
206///
207/// A name with nothing to show falls through to the next one.
208fn visible_name(text: String) -> Option<String> {
209	Some(one_line(text)).filter(|name| !name.trim().is_empty())
210}
211
212/// Remote-supplied text put on one line.
213///
214/// Names and message bodies come from remote users, so they could otherwise add
215/// lines to the mail; text already on one line is returned as it is.
216fn one_line(text: String) -> String {
217	if let Cow::Owned(line) = single_line(&text) {
218		line
219	} else {
220		text
221	}
222}
223
224fn sent_at(pdu: &Pdu) -> String {
225	pdu.origin_server_ts()
226		.to_system_time()
227		.map(|timepoint| format_time(timepoint, "%Y-%m-%d %H:%M UTC"))
228		.unwrap_or_default()
229}
230
231/// What a notification says in the email.
232///
233/// A message shows its body on one line, cut at `SNIPPET_CHARS` characters,
234/// and never its formatted body. An encrypted event shows only that it is one.
235pub(super) fn snippet(pdu: &Pdu, user_id: &UserId) -> Cow<'static, str> {
236	match pdu.kind() {
237		| TimelineEventType::RoomEncrypted => "Encrypted message".into(),
238		| TimelineEventType::RoomMember if invites(pdu, user_id) => "invited you".into(),
239		| TimelineEventType::RoomMessage => pdu
240			.get_content()
241			.map(|Body { body }| shorten(body).into())
242			.unwrap_or_else(|_| "sent a message".into()),
243		| _ => "sent an event".into(),
244	}
245}
246
247/// The body cut at `SNIPPET_CHARS` characters and put on one line.
248///
249/// The cut counts characters, so it never splits one.
250fn shorten(mut body: String) -> String {
251	if let Some((end, _)) = body.char_indices().nth(SNIPPET_CHARS) {
252		body.truncate(end);
253	}
254
255	one_line(body)
256}
257
258/// The room's name, else its canonical alias, put on one line.
259///
260/// A name left with no text counts as none. A room with neither is `None`, and
261/// the mail labels it by its first sender.
262#[implement(super::super::Service)]
263async fn room_name(&self, room_id: &RoomId) -> Option<String> {
264	let state = &self.services.state_accessor;
265	let name = state.get_name(room_id).await;
266	let name = found(name, room_id, None).and_then(visible_name);
267
268	if name.is_some() {
269		return name;
270	}
271
272	let alias = state.get_canonical_alias(room_id).await;
273
274	found(alias, room_id, None)
275		.map(String::from)
276		.and_then(visible_name)
277}
278
279/// The email's subject line.
280///
281/// It names the most recent room and counts the others, or names the inviter
282/// of a lone invite, and the room when it has a name of its own.
283pub(super) fn subject(digest: &Digest<'_>) -> String {
284	let brand = digest.brand;
285	let latest = digest.rooms.first();
286	let name = latest.map_or(UNNAMED_ROOM, Room::label);
287	let inviter = digest.invite.and_then(|| latest?.first_sender());
288
289	match (inviter, digest.room_count) {
290		| (None, 0 | 1) => format!("[{brand}] New messages in {name}"),
291		| (Some(inviter), _) => {
292			let room = latest
293				.and_then(|room| room.name.as_deref())
294				.unwrap_or("a room");
295
296			format!("[{brand}] {inviter} invited you to {room}")
297		},
298		| (None, count) => {
299			let others = count.saturating_sub(1);
300			let noun = plural(others, "room", "rooms");
301
302			format!("[{brand}] New messages in {name} and {others} other {noun}")
303		},
304	}
305}
306
307/// What the mail calls a room: its name, else its first sender shown.
308///
309/// A room with neither reads as an unnamed room.
310#[implement(Room)]
311fn label(&self) -> &str {
312	self.name
313		.as_deref()
314		.or_else(|| self.first_sender())
315		.unwrap_or(UNNAMED_ROOM)
316}
317
318#[implement(Room)]
319fn first_sender(&self) -> Option<&str> {
320	self.lines
321		.first()
322		.map(|line| line.sender.as_str())
323}
324
325/// The email's body.
326///
327/// Each room lists its notifications under its name, then its link.
328pub(super) fn text(digest: &Digest<'_>) -> String {
329	let header = format!("You have unread notifications on {}.\n\n", digest.brand);
330	let body = digest.rooms.iter().fold(header, text_room);
331
332	footer(body, digest)
333}
334
335fn text_room(mut out: String, room: &Room) -> String {
336	writeln!(out, "{}", room.label()).ok();
337	for line in &room.lines {
338		writeln!(out, "  {} ({}): {}", line.sender, line.time, line.snippet).ok();
339	}
340
341	writeln!(out, "  {}\n", room.id.matrix_to_uri()).ok();
342	out
343}
344
345fn footer(mut out: String, digest: &Digest<'_>) -> String {
346	let (hidden, address, brand) = (digest.hidden, digest.address, digest.brand);
347
348	if hidden > 0 {
349		let noun = plural(hidden, "notification", "notifications");
350
351		writeln!(out, "And {hidden} more {noun}.\n").ok();
352	}
353
354	writeln!(
355		out,
356		"You received this email because email notifications are on for {address} on your \
357		 {brand} account. To stop them, turn email notifications off in your client's \
358		 notification settings."
359	)
360	.ok();
361
362	out
363}