1use std::borrow::Cow;
4use std::fmt;
5use std::str;
6
7use anyhow::Result;
8use num_traits::FromPrimitive;
9
10use crate::calls::{CallState, call_state};
11use crate::chat::Chat;
12use crate::constants::Chattype;
13use crate::contact::{Contact, ContactId};
14use crate::context::Context;
15use crate::message::{Message, MessageState, Viewtype};
16use crate::mimeparser::SystemMessage;
17use crate::param::Param;
18use crate::stock_str;
19use crate::stock_str::msg_reacted;
20use crate::tools::truncate;
21
22#[derive(Debug)]
24pub enum SummaryPrefix {
25 Username(String),
27
28 Draft(String),
30
31 Me(String),
33}
34
35impl fmt::Display for SummaryPrefix {
36 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 match self {
38 SummaryPrefix::Username(username) => write!(f, "{username}"),
39 SummaryPrefix::Draft(text) => write!(f, "{text}"),
40 SummaryPrefix::Me(text) => write!(f, "{text}"),
41 }
42 }
43}
44
45#[derive(Debug, Default)]
47pub struct Summary {
48 pub prefix: Option<SummaryPrefix>,
50
51 pub text: String,
53
54 pub timestamp: i64,
56
57 pub state: MessageState,
59
60 pub thumbnail_path: Option<String>,
62}
63
64impl Summary {
65 pub async fn new_with_reaction_details(
68 context: &Context,
69 msg: &Message,
70 chat: &Chat,
71 contact: Option<&Contact>,
72 ) -> Result<Summary> {
73 if let Some((reaction_msg, reaction_contact_id, reaction)) = chat
74 .get_last_reaction_if_newer_than(context, msg.timestamp_sort)
75 .await?
76 {
77 let summary = reaction_msg.get_summary_text_without_prefix(context).await;
81 return Ok(Summary {
82 prefix: None,
83 text: msg_reacted(context, reaction_contact_id, &reaction, &summary).await,
84 timestamp: msg.get_timestamp(), state: msg.state, thumbnail_path: None,
87 });
88 }
89 Self::new(context, msg, chat, contact).await
90 }
91
92 pub async fn new(
95 context: &Context,
96 msg: &Message,
97 chat: &Chat,
98 contact: Option<&Contact>,
99 ) -> Result<Summary> {
100 let prefix = if msg.state == MessageState::OutDraft {
101 Some(SummaryPrefix::Draft(stock_str::draft(context).await))
102 } else if msg.from_id == ContactId::SELF {
103 if msg.is_info() || msg.viewtype == Viewtype::Call || chat.typ == Chattype::OutBroadcast
104 {
105 None
106 } else {
107 Some(SummaryPrefix::Me(stock_str::self_msg(context).await))
108 }
109 } else if chat.typ == Chattype::Group
110 || chat.typ == Chattype::Mailinglist
111 || chat.is_self_talk()
112 {
113 if msg.is_info() || contact.is_none() {
114 None
115 } else {
116 msg.get_override_sender_name()
117 .or_else(|| contact.map(|contact| msg.get_sender_name(contact)))
118 .map(SummaryPrefix::Username)
119 }
120 } else {
121 None
122 };
123
124 let mut text = msg.get_summary_text(context).await;
125
126 if text.is_empty() && msg.quoted_text().is_some() {
127 text = stock_str::reply_noun(context).await
128 }
129
130 let thumbnail_path = if msg.viewtype == Viewtype::Image
131 || msg.viewtype == Viewtype::Gif
132 || msg.viewtype == Viewtype::Sticker
133 {
134 msg.get_file(context)
135 .and_then(|path| path.to_str().map(|p| p.to_owned()))
136 } else if msg.viewtype == Viewtype::Webxdc {
137 Some("webxdc-icon://last-msg-id".to_string())
138 } else {
139 None
140 };
141
142 Ok(Summary {
143 prefix,
144 text,
145 timestamp: msg.get_timestamp(),
146 state: msg.state,
147 thumbnail_path,
148 })
149 }
150
151 pub fn truncated_text(&self, approx_chars: usize) -> Cow<'_, str> {
153 truncate(&self.text, approx_chars)
154 }
155}
156
157impl Message {
158 pub(crate) async fn get_summary_text(&self, context: &Context) -> String {
160 let summary = self.get_summary_text_without_prefix(context).await;
161
162 if self.is_forwarded() {
163 format!("{}: {}", stock_str::forwarded(context).await, summary)
164 } else {
165 summary
166 }
167 }
168
169 async fn get_summary_text_without_prefix(&self, context: &Context) -> String {
171 let (emoji, type_name, type_file, append_text);
172 let viewtype = match self
173 .param
174 .get_i64(Param::PostMessageViewtype)
175 .and_then(Viewtype::from_i64)
176 {
177 Some(vt) => vt,
178 None => self.viewtype,
179 };
180 match viewtype {
181 Viewtype::Image => {
182 emoji = Some("📷");
183 type_name = Some(stock_str::image(context).await);
184 type_file = None;
185 append_text = true;
186 }
187 Viewtype::Gif => {
188 emoji = None;
189 type_name = Some(stock_str::gif(context).await);
190 type_file = None;
191 append_text = true;
192 }
193 Viewtype::Sticker => {
194 emoji = None;
195 type_name = Some(stock_str::sticker(context).await);
196 type_file = None;
197 append_text = true;
198 }
199 Viewtype::Video => {
200 emoji = Some("🎥");
201 type_name = Some(stock_str::video(context).await);
202 type_file = None;
203 append_text = true;
204 }
205 Viewtype::Voice => {
206 emoji = Some("🎤");
207 type_name = Some(stock_str::voice_message(context).await);
208 type_file = None;
209 append_text = true;
210 }
211 Viewtype::Audio => {
212 emoji = Some("🎵");
213 type_name = Some(stock_str::audio(context).await);
214 type_file = self.get_filename();
215 append_text = true
216 }
217 Viewtype::File => {
218 emoji = Some("📎");
219 type_name = Some(stock_str::file(context).await);
220 type_file = self.get_filename();
221 append_text = true
222 }
223 Viewtype::Webxdc => {
224 type_name = None;
225 if self.viewtype == Viewtype::Webxdc {
226 emoji = None;
227 type_file = Some(
228 self.get_webxdc_info(context)
229 .await
230 .map(|info| info.name)
231 .unwrap_or_else(|_| "ErrWebxdcName".to_string()),
232 );
233 } else {
234 emoji = Some("📱");
235 type_file = Some(viewtype.to_locale_string(context).await);
236 }
237 append_text = true;
238 }
239 Viewtype::Vcard => {
240 emoji = Some("👤");
241 type_name = None;
242 if self.viewtype == Viewtype::Vcard {
243 type_file = self.param.get(Param::Summary1).map(|s| s.to_string());
244 } else {
245 type_file = None;
246 }
247 append_text = true;
248 }
249 Viewtype::Call => {
250 let call_state = call_state(context, self.id)
251 .await
252 .unwrap_or(CallState::Alerting);
253 emoji = Some("📞");
254 type_name = Some(match call_state {
255 CallState::Alerting | CallState::Active | CallState::Completed { .. } => {
256 if self.from_id == ContactId::SELF {
257 stock_str::outgoing_call(context).await
258 } else {
259 stock_str::incoming_call(context).await
260 }
261 }
262 CallState::Missed => stock_str::missed_call(context).await,
263 CallState::Declined => stock_str::declined_call(context).await,
264 CallState::Canceled => stock_str::canceled_call(context).await,
265 });
266 type_file = None;
267 append_text = false
268 }
269 Viewtype::Text | Viewtype::Unknown => {
270 emoji = None;
271 if self.param.get_cmd() == SystemMessage::LocationOnly {
272 type_name = Some(stock_str::location(context).await);
273 type_file = None;
274 append_text = false;
275 } else {
276 type_name = None;
277 type_file = None;
278 append_text = true;
279 }
280 }
281 };
282
283 let text = self.text.clone();
284
285 let summary = if let Some(type_file) = type_file {
286 if append_text && !text.is_empty() {
287 format!("{type_file} – {text}")
288 } else {
289 type_file
290 }
291 } else if append_text && !text.is_empty() {
292 if emoji.is_some() {
293 text
294 } else if let Some(type_name) = type_name {
295 format!("{type_name} – {text}")
296 } else {
297 text
298 }
299 } else if let Some(type_name) = type_name {
300 type_name
301 } else {
302 "".to_string()
303 };
304
305 let summary = if let Some(emoji) = emoji {
306 format!("{emoji} {summary}")
307 } else {
308 summary
309 };
310
311 summary.split_whitespace().collect::<Vec<&str>>().join(" ")
312 }
313}
314
315#[cfg(test)]
316pub async fn assert_summary_texts(msg: &Message, ctx: &Context, expected: &str) {
318 assert_eq!(msg.get_summary_text(ctx).await, expected);
319 assert_eq!(msg.get_summary_text_without_prefix(ctx).await, expected);
320}
321
322#[cfg(test)]
323mod tests {
324 use std::path::PathBuf;
325
326 use super::*;
327 use crate::chat::ChatId;
328 use crate::param::Param;
329 use crate::test_utils::TestContext;
330
331 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
332 async fn test_get_summary_text() {
333 let d = TestContext::new_alice().await;
334 let ctx = &d.ctx;
335 let chat_id = ChatId::create_for_contact(ctx, ContactId::SELF)
336 .await
337 .unwrap();
338 let some_text = " bla \t\n\tbla\n\t".to_string();
339
340 async fn write_file_to_blobdir(d: &TestContext) -> PathBuf {
341 let bytes = &[38, 209, 39, 29]; let file = d.get_blobdir().join("random_filename_392438");
343 tokio::fs::write(&file, bytes).await.unwrap();
344 file
345 }
346
347 let msg = Message::new_text(some_text.to_string());
348 assert_summary_texts(&msg, ctx, "bla bla").await; let file = write_file_to_blobdir(&d).await;
351 let mut msg = Message::new(Viewtype::Image);
352 msg.set_file_and_deduplicate(&d, &file, Some("foo.jpg"), None)
353 .unwrap();
354 assert_summary_texts(&msg, ctx, "📷 Image").await; let file = write_file_to_blobdir(&d).await;
357 let mut msg = Message::new(Viewtype::Image);
358 msg.set_text(some_text.to_string());
359 msg.set_file_and_deduplicate(&d, &file, Some("foo.jpg"), None)
360 .unwrap();
361 assert_summary_texts(&msg, ctx, "📷 bla bla").await; let file = write_file_to_blobdir(&d).await;
364 let mut msg = Message::new(Viewtype::Video);
365 msg.set_file_and_deduplicate(&d, &file, Some("foo.mp4"), None)
366 .unwrap();
367 assert_summary_texts(&msg, ctx, "🎥 Video").await; let file = write_file_to_blobdir(&d).await;
370 let mut msg = Message::new(Viewtype::Video);
371 msg.set_text(some_text.to_string());
372 msg.set_file_and_deduplicate(&d, &file, Some("foo.mp4"), None)
373 .unwrap();
374 assert_summary_texts(&msg, ctx, "🎥 bla bla").await; let file = write_file_to_blobdir(&d).await;
377 let mut msg = Message::new(Viewtype::Gif);
378 msg.set_file_and_deduplicate(&d, &file, Some("foo.gif"), None)
379 .unwrap();
380 assert_summary_texts(&msg, ctx, "GIF").await; let file = write_file_to_blobdir(&d).await;
383 let mut msg = Message::new(Viewtype::Gif);
384 msg.set_text(some_text.to_string());
385 msg.set_file_and_deduplicate(&d, &file, Some("foo.gif"), None)
386 .unwrap();
387 assert_summary_texts(&msg, ctx, "GIF \u{2013} bla bla").await; let file = write_file_to_blobdir(&d).await;
390 let mut msg = Message::new(Viewtype::Sticker);
391 msg.set_file_and_deduplicate(&d, &file, Some("foo.png"), None)
392 .unwrap();
393 assert_summary_texts(&msg, ctx, "Sticker").await; let file = write_file_to_blobdir(&d).await;
396 let mut msg = Message::new(Viewtype::Voice);
397 msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
398 .unwrap();
399 assert_summary_texts(&msg, ctx, "🎤 Voice message").await; let file = write_file_to_blobdir(&d).await;
402 let mut msg = Message::new(Viewtype::Voice);
403 msg.set_text(some_text.clone());
404 msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
405 .unwrap();
406 assert_summary_texts(&msg, ctx, "🎤 bla bla").await;
407
408 let file = write_file_to_blobdir(&d).await;
409 let mut msg = Message::new(Viewtype::Audio);
410 msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
411 .unwrap();
412 assert_summary_texts(&msg, ctx, "🎵 foo.mp3").await; let file = write_file_to_blobdir(&d).await;
415 let mut msg = Message::new(Viewtype::Audio);
416 msg.set_text(some_text.clone());
417 msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
418 .unwrap();
419 assert_summary_texts(&msg, ctx, "🎵 foo.mp3 \u{2013} bla bla").await; let mut msg = Message::new(Viewtype::File);
422 let bytes = include_bytes!("../test-data/webxdc/with-minimal-manifest.xdc");
423 msg.set_file_from_bytes(ctx, "foo.xdc", bytes, None)
424 .unwrap();
425 chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
426 assert_eq!(msg.viewtype, Viewtype::Webxdc);
427 assert_summary_texts(&msg, ctx, "nice app!").await;
428 msg.set_text(some_text.clone());
429 chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
430 assert_summary_texts(&msg, ctx, "nice app! \u{2013} bla bla").await;
431
432 let file = write_file_to_blobdir(&d).await;
433 let mut msg = Message::new(Viewtype::File);
434 msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
435 .unwrap();
436 assert_summary_texts(&msg, ctx, "📎 foo.bar").await; let file = write_file_to_blobdir(&d).await;
439 let mut msg = Message::new(Viewtype::File);
440 msg.set_text(some_text.clone());
441 msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
442 .unwrap();
443 assert_summary_texts(&msg, ctx, "📎 foo.bar \u{2013} bla bla").await; let mut msg = Message::new(Viewtype::Vcard);
446 msg.set_file_from_bytes(ctx, "foo.vcf", b"", None).unwrap();
447 chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
448 assert_eq!(msg.viewtype, Viewtype::File);
450 assert_summary_texts(&msg, ctx, "📎 foo.vcf").await;
451 msg.set_text(some_text.clone());
452 assert_summary_texts(&msg, ctx, "📎 foo.vcf \u{2013} bla bla").await;
453
454 for vt in [Viewtype::Vcard, Viewtype::File] {
455 let mut msg = Message::new(vt);
456 msg.set_file_from_bytes(
457 ctx,
458 "alice.vcf",
459 b"BEGIN:VCARD\n\
460 VERSION:4.0\n\
461 FN:Alice Wonderland\n\
462 EMAIL;TYPE=work:alice@example.org\n\
463 END:VCARD",
464 None,
465 )
466 .unwrap();
467 chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
468 assert_eq!(msg.viewtype, Viewtype::Vcard);
469 assert_summary_texts(&msg, ctx, "👤 Alice Wonderland").await;
470 }
471
472 let mut msg = Message::new_text(some_text.clone());
474 msg.param.set_int(Param::Forwarded, 1);
475 assert_eq!(msg.get_summary_text(ctx).await, "Forwarded: bla bla"); assert_eq!(msg.get_summary_text_without_prefix(ctx).await, "bla bla"); let file = write_file_to_blobdir(&d).await;
479 let mut msg = Message::new(Viewtype::File);
480 msg.set_text(some_text.clone());
481 msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
482 .unwrap();
483 msg.param.set_int(Param::Forwarded, 1);
484 assert_eq!(
485 msg.get_summary_text(ctx).await,
486 "Forwarded: 📎 foo.bar \u{2013} bla bla"
487 );
488 assert_eq!(
489 msg.get_summary_text_without_prefix(ctx).await,
490 "📎 foo.bar \u{2013} bla bla"
491 ); let mut msg = Message::new(Viewtype::File);
494 msg.set_file_from_bytes(ctx, "autocrypt-setup-message.html", b"data", None)
495 .unwrap();
496 msg.param.set_cmd(SystemMessage::AutocryptSetupMessage);
497 assert_summary_texts(&msg, ctx, "📎 autocrypt-setup-message.html").await;
498 }
500}