deltachat/
summary.rs

1//! # Message summary for chatlist.
2
3use std::borrow::Cow;
4use std::fmt;
5use std::str;
6
7use crate::chat::Chat;
8use crate::constants::Chattype;
9use crate::contact::{Contact, ContactId};
10use crate::context::Context;
11use crate::message::{Message, MessageState, Viewtype};
12use crate::mimeparser::SystemMessage;
13use crate::param::Param;
14use crate::stock_str;
15use crate::stock_str::msg_reacted;
16use crate::tools::truncate;
17use anyhow::Result;
18
19/// Prefix displayed before message and separated by ":" in the chatlist.
20#[derive(Debug)]
21pub enum SummaryPrefix {
22    /// Username.
23    Username(String),
24
25    /// Stock string saying "Draft".
26    Draft(String),
27
28    /// Stock string saying "Me".
29    Me(String),
30}
31
32impl fmt::Display for SummaryPrefix {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        match self {
35            SummaryPrefix::Username(username) => write!(f, "{username}"),
36            SummaryPrefix::Draft(text) => write!(f, "{text}"),
37            SummaryPrefix::Me(text) => write!(f, "{text}"),
38        }
39    }
40}
41
42/// Message summary.
43#[derive(Debug, Default)]
44pub struct Summary {
45    /// Part displayed before ":", such as an username or a string "Draft".
46    pub prefix: Option<SummaryPrefix>,
47
48    /// Summary text, always present.
49    pub text: String,
50
51    /// Message timestamp.
52    pub timestamp: i64,
53
54    /// Message state.
55    pub state: MessageState,
56
57    /// Message preview image path
58    pub thumbnail_path: Option<String>,
59}
60
61impl Summary {
62    /// Constructs chatlist summary
63    /// from the provided message, chat and message author contact snapshots.
64    pub async fn new_with_reaction_details(
65        context: &Context,
66        msg: &Message,
67        chat: &Chat,
68        contact: Option<&Contact>,
69    ) -> Result<Summary> {
70        if let Some((reaction_msg, reaction_contact_id, reaction)) = chat
71            .get_last_reaction_if_newer_than(context, msg.timestamp_sort)
72            .await?
73        {
74            // there is a reaction newer than the latest message, show that.
75            // sorting and therefore date is still the one of the last message,
76            // the reaction is is more sth. that overlays temporarily.
77            let summary = reaction_msg.get_summary_text_without_prefix(context).await;
78            return Ok(Summary {
79                prefix: None,
80                text: msg_reacted(context, reaction_contact_id, &reaction, &summary).await,
81                timestamp: msg.get_timestamp(), // message timestamp (not reaction) to make timestamps more consistent with chats ordering
82                state: msg.state, // message state (not reaction) - indicating if it was me sending the last message
83                thumbnail_path: None,
84            });
85        }
86        Self::new(context, msg, chat, contact).await
87    }
88
89    /// Constructs search result summary
90    /// from the provided message, chat and message author contact snapshots.
91    pub async fn new(
92        context: &Context,
93        msg: &Message,
94        chat: &Chat,
95        contact: Option<&Contact>,
96    ) -> Result<Summary> {
97        let prefix = if msg.state == MessageState::OutDraft {
98            Some(SummaryPrefix::Draft(stock_str::draft(context).await))
99        } else if msg.from_id == ContactId::SELF {
100            if msg.is_info() {
101                None
102            } else {
103                Some(SummaryPrefix::Me(stock_str::self_msg(context).await))
104            }
105        } else if chat.typ == Chattype::Group
106            || chat.typ == Chattype::OutBroadcast
107            || chat.typ == Chattype::InBroadcast
108            || chat.typ == Chattype::Mailinglist
109            || chat.is_self_talk()
110        {
111            if msg.is_info() || contact.is_none() {
112                None
113            } else {
114                msg.get_override_sender_name()
115                    .or_else(|| contact.map(|contact| msg.get_sender_name(contact)))
116                    .map(SummaryPrefix::Username)
117            }
118        } else {
119            None
120        };
121
122        let mut text = msg.get_summary_text(context).await;
123
124        if text.is_empty() && msg.quoted_text().is_some() {
125            text = stock_str::reply_noun(context).await
126        }
127
128        let thumbnail_path = if msg.viewtype == Viewtype::Image
129            || msg.viewtype == Viewtype::Gif
130            || msg.viewtype == Viewtype::Sticker
131        {
132            msg.get_file(context)
133                .and_then(|path| path.to_str().map(|p| p.to_owned()))
134        } else if msg.viewtype == Viewtype::Webxdc {
135            Some("webxdc-icon://last-msg-id".to_string())
136        } else {
137            None
138        };
139
140        Ok(Summary {
141            prefix,
142            text,
143            timestamp: msg.get_timestamp(),
144            state: msg.state,
145            thumbnail_path,
146        })
147    }
148
149    /// Returns the [`Summary::text`] attribute truncated to an approximate length.
150    pub fn truncated_text(&self, approx_chars: usize) -> Cow<'_, str> {
151        truncate(&self.text, approx_chars)
152    }
153}
154
155impl Message {
156    /// Returns a summary text.
157    pub(crate) async fn get_summary_text(&self, context: &Context) -> String {
158        let summary = self.get_summary_text_without_prefix(context).await;
159
160        if self.is_forwarded() {
161            format!("{}: {}", stock_str::forwarded(context).await, summary)
162        } else {
163            summary
164        }
165    }
166
167    /// Returns a summary text without "Forwarded:" prefix.
168    async fn get_summary_text_without_prefix(&self, context: &Context) -> String {
169        let (emoji, type_name, type_file, append_text);
170        match self.viewtype {
171            Viewtype::Image => {
172                emoji = Some("📷");
173                type_name = Some(stock_str::image(context).await);
174                type_file = None;
175                append_text = true;
176            }
177            Viewtype::Gif => {
178                emoji = None;
179                type_name = Some(stock_str::gif(context).await);
180                type_file = None;
181                append_text = true;
182            }
183            Viewtype::Sticker => {
184                emoji = None;
185                type_name = Some(stock_str::sticker(context).await);
186                type_file = None;
187                append_text = true;
188            }
189            Viewtype::Video => {
190                emoji = Some("🎥");
191                type_name = Some(stock_str::video(context).await);
192                type_file = None;
193                append_text = true;
194            }
195            Viewtype::Voice => {
196                emoji = Some("🎤");
197                type_name = Some(stock_str::voice_message(context).await);
198                type_file = None;
199                append_text = true;
200            }
201            Viewtype::Audio => {
202                emoji = Some("🎵");
203                type_name = Some(stock_str::audio(context).await);
204                type_file = self.get_filename();
205                append_text = true
206            }
207            Viewtype::File => {
208                emoji = Some("📎");
209                type_name = Some(stock_str::file(context).await);
210                type_file = self.get_filename();
211                append_text = true
212            }
213            Viewtype::VideochatInvitation => {
214                emoji = None;
215                type_name = Some(stock_str::videochat_invitation(context).await);
216                type_file = None;
217                append_text = false;
218            }
219            Viewtype::Webxdc => {
220                emoji = None;
221                type_name = None;
222                type_file = Some(
223                    self.get_webxdc_info(context)
224                        .await
225                        .map(|info| info.name)
226                        .unwrap_or_else(|_| "ErrWebxdcName".to_string()),
227                );
228                append_text = true;
229            }
230            Viewtype::Vcard => {
231                emoji = Some("👤");
232                type_name = None;
233                type_file = self.param.get(Param::Summary1).map(|s| s.to_string());
234                append_text = true;
235            }
236            Viewtype::Text | Viewtype::Unknown => {
237                emoji = None;
238                if self.param.get_cmd() == SystemMessage::LocationOnly {
239                    type_name = Some(stock_str::location(context).await);
240                    type_file = None;
241                    append_text = false;
242                } else {
243                    type_name = None;
244                    type_file = None;
245                    append_text = true;
246                }
247            }
248        };
249
250        let text = self.text.clone();
251
252        let summary = if let Some(type_file) = type_file {
253            if append_text && !text.is_empty() {
254                format!("{type_file} – {text}")
255            } else {
256                type_file
257            }
258        } else if append_text && !text.is_empty() {
259            if emoji.is_some() {
260                text
261            } else if let Some(type_name) = type_name {
262                format!("{type_name} – {text}")
263            } else {
264                text
265            }
266        } else if let Some(type_name) = type_name {
267            type_name
268        } else {
269            "".to_string()
270        };
271
272        let summary = if let Some(emoji) = emoji {
273            format!("{emoji} {summary}")
274        } else {
275            summary
276        };
277
278        summary.split_whitespace().collect::<Vec<&str>>().join(" ")
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use std::path::PathBuf;
285
286    use super::*;
287    use crate::chat::ChatId;
288    use crate::param::Param;
289    use crate::test_utils::TestContext;
290
291    async fn assert_summary_texts(msg: &Message, ctx: &Context, expected: &str) {
292        assert_eq!(msg.get_summary_text(ctx).await, expected);
293        assert_eq!(msg.get_summary_text_without_prefix(ctx).await, expected);
294    }
295
296    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
297    async fn test_get_summary_text() {
298        let d = TestContext::new_alice().await;
299        let ctx = &d.ctx;
300        let chat_id = ChatId::create_for_contact(ctx, ContactId::SELF)
301            .await
302            .unwrap();
303        let some_text = " bla \t\n\tbla\n\t".to_string();
304
305        async fn write_file_to_blobdir(d: &TestContext) -> PathBuf {
306            let bytes = &[38, 209, 39, 29]; // Just some random bytes
307            let file = d.get_blobdir().join("random_filename_392438");
308            tokio::fs::write(&file, bytes).await.unwrap();
309            file
310        }
311
312        let msg = Message::new_text(some_text.to_string());
313        assert_summary_texts(&msg, ctx, "bla bla").await; // for simple text, the type is not added to the summary
314
315        let file = write_file_to_blobdir(&d).await;
316        let mut msg = Message::new(Viewtype::Image);
317        msg.set_file_and_deduplicate(&d, &file, Some("foo.jpg"), None)
318            .unwrap();
319        assert_summary_texts(&msg, ctx, "📷 Image").await; // file names are not added for images
320
321        let file = write_file_to_blobdir(&d).await;
322        let mut msg = Message::new(Viewtype::Image);
323        msg.set_text(some_text.to_string());
324        msg.set_file_and_deduplicate(&d, &file, Some("foo.jpg"), None)
325            .unwrap();
326        assert_summary_texts(&msg, ctx, "📷 bla bla").await; // type is visible by emoji if text is set
327
328        let file = write_file_to_blobdir(&d).await;
329        let mut msg = Message::new(Viewtype::Video);
330        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp4"), None)
331            .unwrap();
332        assert_summary_texts(&msg, ctx, "🎥 Video").await; // file names are not added for videos
333
334        let file = write_file_to_blobdir(&d).await;
335        let mut msg = Message::new(Viewtype::Video);
336        msg.set_text(some_text.to_string());
337        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp4"), None)
338            .unwrap();
339        assert_summary_texts(&msg, ctx, "🎥 bla bla").await; // type is visible by emoji if text is set
340
341        let file = write_file_to_blobdir(&d).await;
342        let mut msg = Message::new(Viewtype::Gif);
343        msg.set_file_and_deduplicate(&d, &file, Some("foo.gif"), None)
344            .unwrap();
345        assert_summary_texts(&msg, ctx, "GIF").await; // file names are not added for GIFs
346
347        let file = write_file_to_blobdir(&d).await;
348        let mut msg = Message::new(Viewtype::Gif);
349        msg.set_text(some_text.to_string());
350        msg.set_file_and_deduplicate(&d, &file, Some("foo.gif"), None)
351            .unwrap();
352        assert_summary_texts(&msg, ctx, "GIF \u{2013} bla bla").await; // file names are not added for GIFs
353
354        let file = write_file_to_blobdir(&d).await;
355        let mut msg = Message::new(Viewtype::Sticker);
356        msg.set_file_and_deduplicate(&d, &file, Some("foo.png"), None)
357            .unwrap();
358        assert_summary_texts(&msg, ctx, "Sticker").await; // file names are not added for stickers
359
360        let file = write_file_to_blobdir(&d).await;
361        let mut msg = Message::new(Viewtype::Voice);
362        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
363            .unwrap();
364        assert_summary_texts(&msg, ctx, "🎤 Voice message").await; // file names are not added for voice messages
365
366        let file = write_file_to_blobdir(&d).await;
367        let mut msg = Message::new(Viewtype::Voice);
368        msg.set_text(some_text.clone());
369        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
370            .unwrap();
371        assert_summary_texts(&msg, ctx, "🎤 bla bla").await;
372
373        let file = write_file_to_blobdir(&d).await;
374        let mut msg = Message::new(Viewtype::Audio);
375        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
376            .unwrap();
377        assert_summary_texts(&msg, ctx, "🎵 foo.mp3").await; // file name is added for audio
378
379        let file = write_file_to_blobdir(&d).await;
380        let mut msg = Message::new(Viewtype::Audio);
381        msg.set_text(some_text.clone());
382        msg.set_file_and_deduplicate(&d, &file, Some("foo.mp3"), None)
383            .unwrap();
384        assert_summary_texts(&msg, ctx, "🎵 foo.mp3 \u{2013} bla bla").await; // file name and text added for audio
385
386        let mut msg = Message::new(Viewtype::File);
387        let bytes = include_bytes!("../test-data/webxdc/with-minimal-manifest.xdc");
388        msg.set_file_from_bytes(ctx, "foo.xdc", bytes, None)
389            .unwrap();
390        chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
391        assert_eq!(msg.viewtype, Viewtype::Webxdc);
392        assert_summary_texts(&msg, ctx, "nice app!").await;
393        msg.set_text(some_text.clone());
394        chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
395        assert_summary_texts(&msg, ctx, "nice app! \u{2013} bla bla").await;
396
397        let file = write_file_to_blobdir(&d).await;
398        let mut msg = Message::new(Viewtype::File);
399        msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
400            .unwrap();
401        assert_summary_texts(&msg, ctx, "📎 foo.bar").await; // file name is added for files
402
403        let file = write_file_to_blobdir(&d).await;
404        let mut msg = Message::new(Viewtype::File);
405        msg.set_text(some_text.clone());
406        msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
407            .unwrap();
408        assert_summary_texts(&msg, ctx, "📎 foo.bar \u{2013} bla bla").await; // file name is added for files
409
410        let file = write_file_to_blobdir(&d).await;
411        let mut msg = Message::new(Viewtype::VideochatInvitation);
412        msg.set_text(some_text.clone());
413        msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
414            .unwrap();
415        assert_summary_texts(&msg, ctx, "Video chat invitation").await; // text is not added for videochat invitations
416
417        let mut msg = Message::new(Viewtype::Vcard);
418        msg.set_file_from_bytes(ctx, "foo.vcf", b"", None).unwrap();
419        chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
420        // If a vCard can't be parsed, the message becomes `Viewtype::File`.
421        assert_eq!(msg.viewtype, Viewtype::File);
422        assert_summary_texts(&msg, ctx, "📎 foo.vcf").await;
423        msg.set_text(some_text.clone());
424        assert_summary_texts(&msg, ctx, "📎 foo.vcf \u{2013} bla bla").await;
425
426        for vt in [Viewtype::Vcard, Viewtype::File] {
427            let mut msg = Message::new(vt);
428            msg.set_file_from_bytes(
429                ctx,
430                "alice.vcf",
431                b"BEGIN:VCARD\n\
432                  VERSION:4.0\n\
433                  FN:Alice Wonderland\n\
434                  EMAIL;TYPE=work:alice@example.org\n\
435                  END:VCARD",
436                None,
437            )
438            .unwrap();
439            chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
440            assert_eq!(msg.viewtype, Viewtype::Vcard);
441            assert_summary_texts(&msg, ctx, "👤 Alice Wonderland").await;
442        }
443
444        // Forwarded
445        let mut msg = Message::new_text(some_text.clone());
446        msg.param.set_int(Param::Forwarded, 1);
447        assert_eq!(msg.get_summary_text(ctx).await, "Forwarded: bla bla"); // for simple text, the type is not added to the summary
448        assert_eq!(msg.get_summary_text_without_prefix(ctx).await, "bla bla"); // skipping prefix used for reactions summaries
449
450        let file = write_file_to_blobdir(&d).await;
451        let mut msg = Message::new(Viewtype::File);
452        msg.set_text(some_text.clone());
453        msg.set_file_and_deduplicate(&d, &file, Some("foo.bar"), None)
454            .unwrap();
455        msg.param.set_int(Param::Forwarded, 1);
456        assert_eq!(
457            msg.get_summary_text(ctx).await,
458            "Forwarded: 📎 foo.bar \u{2013} bla bla"
459        );
460        assert_eq!(
461            msg.get_summary_text_without_prefix(ctx).await,
462            "📎 foo.bar \u{2013} bla bla"
463        ); // skipping prefix used for reactions summaries
464
465        let mut msg = Message::new(Viewtype::File);
466        msg.set_file_from_bytes(ctx, "autocrypt-setup-message.html", b"data", None)
467            .unwrap();
468        msg.param.set_cmd(SystemMessage::AutocryptSetupMessage);
469        assert_summary_texts(&msg, ctx, "📎 autocrypt-setup-message.html").await;
470        // no special handling of ASM
471    }
472}