BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / forwarded.rs

forwarded.rs

forwarded.rs 13.4 KiB Download Raw
1use std::sync::LazyLock;
2
3use chrono::{DateTime, Utc};
4use regex::Regex;
5use serde::Deserialize;
6use store::MessageRecord;
7
8use crate::markdown::escape_html;
9use crate::spans::html_to_spans;
10use crate::stored::{AttachmentInfo, attachments, push_plain};
11
12pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference";
13pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
14pub const FORWARD_LOADING_TEXT: &str = "Loading forwarded message";
15pub const FORWARD_UNAVAILABLE_TEXT: &str = "Original message not available";
16
17static MENTION_ID: LazyLock<Regex> =
18 LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern"));
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum ForwardState {
22 Ready,
23 /// Cached without its original; the heal fetches it.
24 Loading,
25 Unavailable,
26}
27
28/// The original message carried by a Graph `forwardedMessageReference` attachment.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ForwardInfo {
31 pub state: ForwardState,
32 pub attachment_id: Option<String>,
33 pub message_id: String,
34 pub conversation_id: Option<String>,
35 pub sender_id: Option<String>,
36 pub sender_name: Option<String>,
37 pub sent_at: Option<DateTime<Utc>>,
38 pub content_html: String,
39}
40
41#[derive(Deserialize)]
42#[serde(rename_all = "camelCase")]
43struct ForwardContent {
44 original_message_id: Option<String>,
45 #[serde(default)]
46 original_message_content: String,
47 original_conversation_id: Option<String>,
48 original_sent_date_time: Option<DateTime<Utc>>,
49 original_message_sender: Option<graph::Sender>,
50}
51
52impl ForwardInfo {
53 pub fn from_attachment(attachment: &AttachmentInfo) -> Option<ForwardInfo> {
54 if attachment.content_type.as_deref() != Some(FORWARDED_CONTENT_TYPE) {
55 return None;
56 }
57 let Some(raw) = attachment.content.as_deref() else {
58 return Some(ForwardInfo::without_content(attachment));
59 };
60 let content: ForwardContent = serde_json::from_str(raw).ok()?;
61 let sender = content.original_message_sender.as_ref();
62 Some(ForwardInfo {
63 state: ForwardState::Ready,
64 message_id: content
65 .original_message_id
66 .or_else(|| attachment.id.clone())?,
67 attachment_id: attachment.id.clone(),
68 conversation_id: content.original_conversation_id,
69 sender_id: sender
70 .and_then(|sender| sender.user_id())
71 .map(str::to_owned),
72 sender_name: sender
73 .and_then(|sender| sender.display_name())
74 .map(str::to_owned),
75 sent_at: content.original_sent_date_time,
76 content_html: content.original_message_content,
77 })
78 }
79
80 fn without_content(attachment: &AttachmentInfo) -> ForwardInfo {
81 ForwardInfo {
82 state: if attachment.unavailable {
83 ForwardState::Unavailable
84 } else {
85 ForwardState::Loading
86 },
87 attachment_id: attachment.id.clone(),
88 message_id: attachment.id.clone().unwrap_or_default(),
89 conversation_id: None,
90 sender_id: None,
91 sender_name: None,
92 sent_at: None,
93 content_html: String::new(),
94 }
95 }
96
97 pub fn text(&self) -> String {
98 let mut text = String::new();
99 push_plain(&mut text, &html_to_spans(&self.content_html));
100 text.trim().to_owned()
101 }
102
103 pub fn html(&self, header: &ForwardHeader) -> String {
104 let sender = header
105 .sender
106 .as_deref()
107 .or(self.sender_name.as_deref())
108 .map(|name| format!("<strong>{}</strong>", escape_html(name)))
109 .unwrap_or_default();
110 let time = header
111 .time
112 .as_deref()
113 .map(|time| format!(" <span>{}</span>", escape_html(time)))
114 .unwrap_or_default();
115 let content = match self.state {
116 ForwardState::Ready => MENTION_ID.replace_all(&self.content_html, "<at>"),
117 ForwardState::Loading => format!("<p><em>{FORWARD_LOADING_TEXT}</em></p>").into(),
118 ForwardState::Unavailable => {
119 format!("<p><em>{FORWARD_UNAVAILABLE_TEXT}</em></p>").into()
120 }
121 };
122 format!(
123 "<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>",
124 escape_html(&self.message_id),
125 )
126 }
127}
128
129/// What the forward quote names above the original: sender display name and sent time label.
130#[derive(Debug, Clone, Default, PartialEq, Eq)]
131pub struct ForwardHeader {
132 pub sender: Option<String>,
133 pub time: Option<String>,
134}
135
136pub fn forwards(record: &MessageRecord) -> Vec<ForwardInfo> {
137 if record.deleted || !record.attachments_json.contains(FORWARDED_CONTENT_TYPE) {
138 return Vec::new();
139 }
140 attachments(record)
141 .iter()
142 .filter_map(ForwardInfo::from_attachment)
143 .collect()
144}
145
146pub fn forwarded_texts(record: &MessageRecord) -> Vec<String> {
147 forwards(record)
148 .iter()
149 .map(ForwardInfo::text)
150 .filter(|text| !text.is_empty())
151 .collect()
152}
153
154pub fn is_forwarded(record: &MessageRecord) -> bool {
155 !record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty())
156}
157
158fn is_stale_forward(attachment: &AttachmentInfo) -> bool {
159 attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE)
160 && attachment.content.is_none()
161 && !attachment.unavailable
162}
163
164/// A forward attachment cached before its content was kept, and not given up on.
165pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool {
166 attachments(record).iter().any(is_stale_forward)
167}
168
169/// `record` with each stale forward marked as unavailable, so it is not fetched again.
170pub(crate) fn mark_forwards_unavailable(record: &MessageRecord) -> Option<MessageRecord> {
171 let mut stored = attachments(record);
172 let mut changed = false;
173 for attachment in stored.iter_mut().filter(|attachment| is_stale_forward(attachment)) {
174 attachment.unavailable = true;
175 changed = true;
176 }
177 let attachments_json = serde_json::to_string(&stored).ok()?;
178 changed.then(|| MessageRecord {
179 attachments_json,
180 ..record.clone()
181 })
182}
183
184/// `html` with each forward's `<attachment id>` tag replaced by its forward blockquote; a forward without a tag goes last.
185pub(crate) fn inline_forwards(
186 record: &MessageRecord,
187 mut html: String,
188 header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
189) -> String {
190 for forward in forwards(record) {
191 let block = forward.html(&header(&forward));
192 let tag = forward
193 .attachment_id
194 .as_deref()
195 .map(|id| format!("<attachment id=\"{id}\"></attachment>"))
196 .filter(|tag| html.contains(tag));
197 match tag {
198 Some(tag) => html = html.replacen(&tag, &block, 1),
199 None => html.push_str(&block),
200 }
201 }
202 html
203}
204
205pub fn no_forward_header(_: &ForwardInfo) -> ForwardHeader {
206 ForwardHeader::default()
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212 use crate::mapping::message_record;
213 use crate::spans::Span;
214 use crate::stored::{copy_text, edit_preserved, linked_message_spans_with, readable_text};
215
216 const CHAT_ID: &str = "19:11111111-1111-4111-8111-111111111111_22222222-2222-4222-8222-222222222222@unq.gbl.spaces";
217 const ORIGINAL_SENDER_ID: &str = "33333333-3333-4333-8333-333333333333";
218 const ORIGINAL_TEXT: &str = "Keep it short and make sure everyone gets the key part";
219
220 fn forwarded_record() -> MessageRecord {
221 let message: graph::Message =
222 serde_json::from_str(include_str!("../tests/fixtures/forwarded_message.json")).unwrap();
223 message_record(CHAT_ID, &message).unwrap()
224 }
225
226 fn plain(spans: &[Span]) -> String {
227 let mut text = String::new();
228 push_plain(&mut text, spans);
229 text
230 }
231
232 #[test]
233 fn a_graph_forward_keeps_the_original_message() {
234 let record = forwarded_record();
235 assert!(is_forwarded(&record));
236 let found = forwards(&record);
237 assert_eq!(found.len(), 1);
238 let forward = &found[0];
239 assert_eq!(forward.message_id, "1792149081221");
240 assert_eq!(forward.attachment_id.as_deref(), Some("1792149081221"));
241 assert_eq!(forward.sender_id.as_deref(), Some(ORIGINAL_SENDER_ID));
242 assert_eq!(forward.sender_name, None);
243 assert_eq!(
244 forward.conversation_id.as_deref(),
245 Some("19:5555555555554555a5555555555555aa@thread.v2")
246 );
247 assert_eq!(
248 forward.sent_at,
249 Some("2026-10-16T11:11:21.221Z".parse().unwrap())
250 );
251 assert!(forward.text().starts_with(ORIGINAL_TEXT));
252 }
253
254 #[test]
255 fn the_forward_replaces_its_attachment_tag_with_a_quote_naming_the_original_sender() {
256 let record = forwarded_record();
257 let spans = linked_message_spans_with(&record, &|_| None, &|forward| ForwardHeader {
258 sender: (forward.sender_id.as_deref() == Some(ORIGINAL_SENDER_ID))
259 .then(|| "Ada Original".to_owned()),
260 time: Some("13:11".to_owned()),
261 });
262 let [Span::BlockQuote(children)] = spans.as_slice() else {
263 panic!("expected one forward blockquote, got {spans:?}");
264 };
265 let text = plain(children);
266 assert!(text.starts_with("Ada Original 13:11"), "{text}");
267 assert!(text.contains(ORIGINAL_TEXT), "{text}");
268 }
269
270 #[test]
271 fn the_forwarded_text_is_copied_but_not_part_of_the_own_text() {
272 let record = forwarded_record();
273 assert_eq!(readable_text(&record), "");
274 assert!(copy_text(&record).starts_with(ORIGINAL_TEXT));
275 assert_eq!(forwarded_texts(&record).len(), 1);
276 }
277
278 #[test]
279 fn an_edit_keeps_the_forward_attachment() {
280 let preserved = edit_preserved(&forwarded_record());
281 assert_eq!(preserved.kept.len(), 1);
282 assert_eq!(
283 preserved.kept[0].content_type.as_deref(),
284 Some(FORWARDED_CONTENT_TYPE)
285 );
286 }
287
288 #[test]
289 fn a_mention_inside_the_forward_does_not_borrow_the_forwarders_mention() {
290 let mut record = forwarded_record();
291 record.body_html = format!(
292 r#"<p><at id="0">Bob Sample</at></p>{}"#,
293 record.body_html
294 );
295 record.attachments_json = record
296 .attachments_json
297 .replace("<p>Keep", r#"<p><at id=\\\"0\\\">Cleo Other</at> Keep"#);
298 record.mentions_json =
299 r#"[{"user_id":"user-bob","name":"Bob Sample","id":0}]"#.to_owned();
300 assert!(forwards(&record)[0].content_html.contains("Cleo Other"));
301 let spans = linked_message_spans_with(&record, &|_| None, &no_forward_header);
302 let mut mentions = Vec::new();
303 collect_mentions(&spans, &mut mentions);
304 assert_eq!(
305 mentions,
306 [
307 ("Bob Sample".to_owned(), Some("teams-profile:user-bob".to_owned())),
308 ("Cleo Other".to_owned(), None),
309 ]
310 );
311 }
312
313 fn collect_mentions(spans: &[Span], found: &mut Vec<(String, Option<String>)>) {
314 for span in spans {
315 match span {
316 Span::Mention { name, id } => found.push((name.clone(), id.clone())),
317 Span::BlockQuote(children) | Span::Bold(children) => {
318 collect_mentions(children, found);
319 }
320 _ => {}
321 }
322 }
323 }
324
325 #[test]
326 fn a_forward_cached_without_its_content_needs_a_refetch() {
327 let mut record = forwarded_record();
328 assert!(!lacks_forward_content(&record));
329 record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();
330 assert!(lacks_forward_content(&record));
331 let found = forwards(&record);
332 assert_eq!(found.len(), 1);
333 assert_eq!(found[0].state, ForwardState::Loading);
334 assert!(forwarded_texts(&record).is_empty());
335 }
336
337 fn quote_text(record: &MessageRecord) -> String {
338 let spans = linked_message_spans_with(record, &|_| None, &no_forward_header);
339 let [Span::BlockQuote(children)] = spans.as_slice() else {
340 panic!("expected one forward blockquote, got {spans:?}");
341 };
342 plain(children)
343 }
344
345 #[test]
346 fn a_forward_without_content_shows_a_loading_line_until_it_is_given_up() {
347 let mut record = forwarded_record();
348 record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();
349 assert!(is_forwarded(&record));
350 assert_eq!(quote_text(&record).trim(), FORWARD_LOADING_TEXT);
351
352 let given_up = mark_forwards_unavailable(&record).unwrap();
353 assert!(!lacks_forward_content(&given_up));
354 assert_eq!(forwards(&given_up)[0].state, ForwardState::Unavailable);
355 assert_eq!(quote_text(&given_up).trim(), FORWARD_UNAVAILABLE_TEXT);
356 assert!(mark_forwards_unavailable(&given_up).is_none());
357 assert!(edit_preserved(&given_up).kept.is_empty());
358 }
359
360 #[test]
361 fn a_deleted_forward_is_not_forwarded() {
362 let mut record = forwarded_record();
363 record.deleted = true;
364 assert!(!is_forwarded(&record));
365 assert!(forwards(&record).is_empty());
366 }
367}