deltachat/
summary.rs

1//! # Message summary for chatlist.
2
3use 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/// Prefix displayed before message and separated by ":" in the chatlist.
23#[derive(Debug)]
24pub enum SummaryPrefix {
25    /// Username.
26    Username(String),
27
28    /// Stock string saying "Draft".
29    Draft(String),
30
31    /// Stock string saying "Me".
32    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/// Message summary.
46#[derive(Debug, Default)]
47pub struct Summary {
48    /// Part displayed before ":", such as an username or a string "Draft".
49    pub prefix: Option<SummaryPrefix>,
50
51    /// Summary text, always present.
52    pub text: String,
53
54    /// Message timestamp.
55    pub timestamp: i64,
56
57    /// Message state.
58    pub state: MessageState,
59
60    /// Message preview image path
61    pub thumbnail_path: Option<String>,
62}
63
64impl Summary {
65    /// Constructs chatlist summary
66    /// from the provided message, chat and message author contact snapshots.
67    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            // there is a reaction newer than the latest message, show that.
78            // sorting and therefore date is still the one of the last message,
79            // the reaction is is more sth. that overlays temporarily.
80            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(), // message timestamp (not reaction) to make timestamps more consistent with chats ordering
85                state: msg.state, // message state (not reaction) - indicating if it was me sending the last message
86                thumbnail_path: None,
87            });
88        }
89        Self::new(context, msg, chat, contact).await
90    }
91
92    /// Constructs search result summary
93    /// from the provided message, chat and message author contact snapshots.
94    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    /// Returns the [`Summary::text`] attribute truncated to an approximate length.
152    pub fn truncated_text(&self, approx_chars: usize) -> Cow<'_, str> {
153        truncate(&self.text, approx_chars)
154    }
155}
156
157impl Message {
158    /// Returns a summary text.
159    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    /// Returns a summary text without "Forwarded:" prefix.
170    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                emoji = Some("📱");
225                type_name = None;
226                if self.viewtype == Viewtype::Webxdc {
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                    type_file = self.get_filename();
235                }
236                append_text = true;
237            }
238            Viewtype::Vcard => {
239                emoji = Some("👤");
240                type_name = None;
241                if self.viewtype == Viewtype::Vcard {
242                    type_file = self.param.get(Param::Summary1).map(|s| s.to_string());
243                } else {
244                    type_file = None;
245                }
246                append_text = true;
247            }
248            Viewtype::Call => {
249                let call_info = context.load_call_by_id(self.id).await.unwrap_or(None);
250                let has_video = call_info.is_some_and(|c| c.has_video_initially());
251                let call_state = call_state(context, self.id)
252                    .await
253                    .unwrap_or(CallState::Alerting);
254                emoji = Some(if has_video { "🎥" } else { "📞" });
255                type_name = Some(match call_state {
256                    CallState::Alerting | CallState::Active | CallState::Completed { .. } => {
257                        if self.from_id == ContactId::SELF {
258                            stock_str::outgoing_call(context, has_video).await
259                        } else {
260                            stock_str::incoming_call(context, has_video).await
261                        }
262                    }
263                    CallState::Missed => stock_str::missed_call(context).await,
264                    CallState::Declined => stock_str::declined_call(context).await,
265                    CallState::Canceled => stock_str::canceled_call(context).await,
266                });
267                type_file = None;
268                append_text = false
269            }
270            Viewtype::Text | Viewtype::Unknown => {
271                emoji = None;
272                if self.param.get_cmd() == SystemMessage::LocationOnly {
273                    type_name = Some(stock_str::location(context).await);
274                    type_file = None;
275                    append_text = false;
276                } else {
277                    type_name = None;
278                    type_file = None;
279                    append_text = true;
280                }
281            }
282        };
283
284        let text = self.text.clone();
285
286        let summary = if let Some(type_file) = type_file {
287            if append_text && !text.is_empty() {
288                format!("{type_file} – {text}")
289            } else {
290                type_file
291            }
292        } else if append_text && !text.is_empty() {
293            if emoji.is_some() {
294                text
295            } else if let Some(type_name) = type_name {
296                format!("{type_name} – {text}")
297            } else {
298                text
299            }
300        } else if let Some(type_name) = type_name {
301            type_name
302        } else {
303            "".to_string()
304        };
305
306        let summary = if let Some(emoji) = emoji {
307            format!("{emoji} {summary}")
308        } else {
309            summary
310        };
311
312        summary.split_whitespace().collect::<Vec<&str>>().join(" ")
313    }
314}
315
316#[cfg(test)]
317/// Asserts that the summary text with and w/o prefix is `expected`.
318pub async fn assert_summary_texts(msg: &Message, ctx: &Context, expected: &str) {
319    assert_eq!(msg.get_summary_text(ctx).await, expected);
320    assert_eq!(msg.get_summary_text_without_prefix(ctx).await, expected);
321}
322
323#[cfg(test)]
324mod tests {
325    use std::path::PathBuf;
326
327    use super::*;
328    use crate::chat::ChatId;
329    use crate::param::Param;
330    use crate::test_utils::TestContext;
331
332    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
333    async fn test_get_summary_text() {
334        let d = TestContext::new_alice().await;
335        let ctx = &d.ctx;
336        let chat_id = ChatId::create_for_contact(ctx, ContactId::SELF)
337            .await
338            .unwrap();
339        let some_text = " bla \t\n\tbla\n\t".to_string();
340
341        async fn write_file_to_blobdir(d: &TestContext) -> PathBuf {
342            let bytes = &[38, 209, 39, 29]; // Just some random bytes
343            let file = d.get_blobdir().join("random_filename_392438");
344            tokio::fs::write(&file, bytes).await.unwrap();
345            file
346        }
347
348        let msg = Message::new_text(some_text.to_string());
349        assert_summary_texts(&msg, ctx, "bla bla").await; // for simple text, the type is not added to the summary
350
351        let file = write_file_to_blobdir(&d).await;
352        let mut msg = Message::new(Viewtype::Image);
353        msg.set_file_and_deduplicate(&d, &file, Some("foo.jpg"), None)
354            .unwrap();
355        assert_summary_texts(&msg, ctx, "📷 Image").await; // file names are not added for images
356
357        let file = write_file_to_blobdir(&d).await;
358        let mut msg = Message::new(Viewtype::Image);
359        msg.set_text(some_text.to_string());
360        msg.set_file_and_deduplicate(&d, &file, Some("foo.jpg"), None)
361            .unwrap();
362        assert_summary_texts(&msg, ctx, "📷 bla bla").await; // type is visible by emoji if text is set
363
364        let file = write_file_to_blobdir(&d).await;
365        let mut msg = Message::new(Viewtype::Video);
366        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp4"), None)
367            .unwrap();
368        assert_summary_texts(&msg, ctx, "🎥 Video").await; // file names are not added for videos
369
370        let file = write_file_to_blobdir(&d).await;
371        let mut msg = Message::new(Viewtype::Video);
372        msg.set_text(some_text.to_string());
373        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp4"), None)
374            .unwrap();
375        assert_summary_texts(&msg, ctx, "🎥 bla bla").await; // type is visible by emoji if text is set
376
377        let file = write_file_to_blobdir(&d).await;
378        let mut msg = Message::new(Viewtype::Gif);
379        msg.set_file_and_deduplicate(&d, &file, Some("foo.gif"), None)
380            .unwrap();
381        assert_summary_texts(&msg, ctx, "GIF").await; // file names are not added for GIFs
382
383        let file = write_file_to_blobdir(&d).await;
384        let mut msg = Message::new(Viewtype::Gif);
385        msg.set_text(some_text.to_string());
386        msg.set_file_and_deduplicate(&d, &file, Some("foo.gif"), None)
387            .unwrap();
388        assert_summary_texts(&msg, ctx, "GIF \u{2013} bla bla").await; // file names are not added for GIFs
389
390        let file = write_file_to_blobdir(&d).await;
391        let mut msg = Message::new(Viewtype::Sticker);
392        msg.set_file_and_deduplicate(&d, &file, Some("foo.png"), None)
393            .unwrap();
394        assert_summary_texts(&msg, ctx, "Sticker").await; // file names are not added for stickers
395
396        let file = write_file_to_blobdir(&d).await;
397        let mut msg = Message::new(Viewtype::Voice);
398        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
399            .unwrap();
400        assert_summary_texts(&msg, ctx, "🎤 Voice message").await; // file names are not added for voice messages
401
402        let file = write_file_to_blobdir(&d).await;
403        let mut msg = Message::new(Viewtype::Voice);
404        msg.set_text(some_text.clone());
405        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
406            .unwrap();
407        assert_summary_texts(&msg, ctx, "🎤 bla bla").await;
408
409        let file = write_file_to_blobdir(&d).await;
410        let mut msg = Message::new(Viewtype::Audio);
411        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
412            .unwrap();
413        assert_summary_texts(&msg, ctx, "🎵 foo.mp3").await; // file name is added for audio
414
415        let file = write_file_to_blobdir(&d).await;
416        let mut msg = Message::new(Viewtype::Audio);
417        msg.set_text(some_text.clone());
418        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
419            .unwrap();
420        assert_summary_texts(&msg, ctx, "🎵 foo.mp3 \u{2013} bla bla").await; // file name and text added for audio
421
422        let mut msg = Message::new(Viewtype::File);
423        let bytes = include_bytes!("../test-data/webxdc/with-minimal-manifest.xdc");
424        msg.set_file_from_bytes(ctx, "foo.xdc", bytes, None)
425            .unwrap();
426        chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
427        assert_eq!(msg.viewtype, Viewtype::Webxdc);
428        assert_summary_texts(&msg, ctx, "📱 nice app!").await;
429        msg.set_text(some_text.clone());
430        chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
431        assert_summary_texts(&msg, ctx, "📱 nice app! \u{2013} bla bla").await;
432
433        let file = write_file_to_blobdir(&d).await;
434        let mut msg = Message::new(Viewtype::File);
435        msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
436            .unwrap();
437        assert_summary_texts(&msg, ctx, "📎 foo.bar").await; // file name is added for files
438
439        let file = write_file_to_blobdir(&d).await;
440        let mut msg = Message::new(Viewtype::File);
441        msg.set_text(some_text.clone());
442        msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
443            .unwrap();
444        assert_summary_texts(&msg, ctx, "📎 foo.bar \u{2013} bla bla").await; // file name is added for files
445
446        let mut msg = Message::new(Viewtype::Vcard);
447        msg.set_file_from_bytes(ctx, "foo.vcf", b"", None).unwrap();
448        chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
449        // If a vCard can't be parsed, the message becomes `Viewtype::File`.
450        assert_eq!(msg.viewtype, Viewtype::File);
451        assert_summary_texts(&msg, ctx, "📎 foo.vcf").await;
452        msg.set_text(some_text.clone());
453        assert_summary_texts(&msg, ctx, "📎 foo.vcf \u{2013} bla bla").await;
454
455        for vt in [Viewtype::Vcard, Viewtype::File] {
456            let mut msg = Message::new(vt);
457            msg.set_file_from_bytes(
458                ctx,
459                "alice.vcf",
460                b"BEGIN:VCARD\n\
461                  VERSION:4.0\n\
462                  FN:Alice Wonderland\n\
463                  EMAIL;TYPE=work:alice@example.org\n\
464                  END:VCARD",
465                None,
466            )
467            .unwrap();
468            chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
469            assert_eq!(msg.viewtype, Viewtype::Vcard);
470            assert_summary_texts(&msg, ctx, "👤 Alice Wonderland").await;
471        }
472
473        // Forwarded
474        let mut msg = Message::new_text(some_text.clone());
475        msg.param.set_int(Param::Forwarded, 1);
476        assert_eq!(msg.get_summary_text(ctx).await, "Forwarded: bla bla"); // for simple text, the type is not added to the summary
477        assert_eq!(msg.get_summary_text_without_prefix(ctx).await, "bla bla"); // skipping prefix used for reactions summaries
478
479        let file = write_file_to_blobdir(&d).await;
480        let mut msg = Message::new(Viewtype::File);
481        msg.set_text(some_text.clone());
482        msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
483            .unwrap();
484        msg.param.set_int(Param::Forwarded, 1);
485        assert_eq!(
486            msg.get_summary_text(ctx).await,
487            "Forwarded: 📎 foo.bar \u{2013} bla bla"
488        );
489        assert_eq!(
490            msg.get_summary_text_without_prefix(ctx).await,
491            "📎 foo.bar \u{2013} bla bla"
492        ); // skipping prefix used for reactions summaries
493
494        let mut msg = Message::new(Viewtype::File);
495        msg.set_file_from_bytes(ctx, "autocrypt-setup-message.html", b"data", None)
496            .unwrap();
497        msg.param.set_cmd(SystemMessage::AutocryptSetupMessage);
498        assert_summary_texts(&msg, ctx, "📎 autocrypt-setup-message.html").await;
499        // no special handling of ASM
500    }
501}