deltachat/
chatlist.rs

1//! # Chat list module.
2
3use anyhow::{Context as _, Result, ensure};
4use std::sync::LazyLock;
5
6use crate::chat::{Chat, ChatId, ChatVisibility, update_special_chat_names};
7use crate::constants::{
8    Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_GCL_ADD_ALLDONE_HINT,
9    DC_GCL_ARCHIVED_ONLY, DC_GCL_FOR_FORWARDING, DC_GCL_NO_SPECIALS,
10};
11use crate::contact::{Contact, ContactId};
12use crate::context::Context;
13use crate::log::warn;
14use crate::message::{Message, MessageState, MsgId};
15use crate::param::{Param, Params};
16use crate::stock_str;
17use crate::summary::Summary;
18use crate::tools::IsNoneOrEmpty;
19
20/// Regex to find out if a query should filter by unread messages.
21pub static IS_UNREAD_FILTER: LazyLock<regex::Regex> =
22    LazyLock::new(|| regex::Regex::new(r"\bis:unread\b").unwrap());
23
24/// An object representing a single chatlist in memory.
25///
26/// Chatlist objects contain chat IDs and, if possible, message IDs belonging to them.
27/// The chatlist object is not updated; if you want an update, you have to recreate the object.
28///
29/// For a **typical chat overview**, the idea is to get the list of all chats via dc_get_chatlist()
30/// without any listflags (see below) and to implement a "virtual list" or so
31/// (the count of chats is known by chatlist.len()).
32///
33/// Only for the items that are in view (the list may have several hundreds chats),
34/// the UI should call chatlist.get_summary() then.
35/// chatlist.get_summary() provides all elements needed for painting the item.
36///
37/// On a click of such an item, the UI should change to the chat view
38/// and get all messages from this view via dc_get_chat_msgs().
39/// Again, a "virtual list" is created (the count of messages is known)
40/// and for each messages that is scrolled into view, dc_get_msg() is called then.
41///
42/// Why no listflags?
43/// Without listflags, dc_get_chatlist() adds the archive "link" automatically as needed.
44/// The UI can just render these items differently then.
45#[derive(Debug)]
46pub struct Chatlist {
47    /// Stores pairs of `chat_id, message_id`
48    ids: Vec<(ChatId, Option<MsgId>)>,
49}
50
51impl Chatlist {
52    /// Get a list of chats.
53    /// The list can be filtered by query parameters.
54    ///
55    /// The list is already sorted and starts with the most recent chat in use.
56    /// The sorting takes care of invalid sending dates, drafts and chats without messages.
57    /// Clients should not try to re-sort the list as this would be an expensive action
58    /// and would result in inconsistencies between clients.
59    ///
60    /// To get information about each entry, use eg. chatlist.get_summary().
61    ///
62    /// By default, the function adds some special entries to the list.
63    /// These special entries can be identified by the ID returned by chatlist.get_chat_id():
64    /// - DC_CHAT_ID_ARCHIVED_LINK (6) - this special chat is present if the user has
65    ///   archived *any* chat using dc_set_chat_visibility(). The UI should show a link as
66    ///   "Show archived chats", if the user clicks this item, the UI should show a
67    ///   list of all archived chats that can be created by this function hen using
68    ///   the DC_GCL_ARCHIVED_ONLY flag.
69    /// - DC_CHAT_ID_ALLDONE_HINT (7) - this special chat is present
70    ///   if DC_GCL_ADD_ALLDONE_HINT is added to listflags
71    ///   and if there are only archived chats.
72    ///
73    /// The `listflags` is a combination of flags:
74    /// - if the flag DC_GCL_ARCHIVED_ONLY is set, only archived chats are returned.
75    ///   if DC_GCL_ARCHIVED_ONLY is not set, only unarchived chats are returned and
76    ///   the pseudo-chat DC_CHAT_ID_ARCHIVED_LINK is added if there are *any* archived
77    ///   chats
78    /// - the flag DC_GCL_FOR_FORWARDING sorts "Saved messages" to the top of the chatlist
79    ///   and hides the device-chat and contact requests
80    ///   typically used on forwarding, may be combined with DC_GCL_NO_SPECIALS
81    /// - if the flag DC_GCL_NO_SPECIALS is set, archive link is not added
82    ///   to the list (may be used eg. for selecting chats on forwarding, the flag is
83    ///   not needed when DC_GCL_ARCHIVED_ONLY is already set)
84    /// - if the flag DC_GCL_ADD_ALLDONE_HINT is set, DC_CHAT_ID_ALLDONE_HINT
85    ///   is added as needed.
86    ///
87    /// `query`: An optional query for filtering the list. Only chats matching this query
88    /// are returned. When `is:unread` is contained in the query, the chatlist is
89    /// filtered such that only chats with unread messages show up.
90    ///
91    /// `query_contact_id`: An optional contact ID for filtering the list. Only chats including this contact ID
92    /// are returned.
93    pub async fn try_load(
94        context: &Context,
95        listflags: usize,
96        query: Option<&str>,
97        query_contact_id: Option<ContactId>,
98    ) -> Result<Self> {
99        let flag_archived_only = 0 != listflags & DC_GCL_ARCHIVED_ONLY;
100        let flag_for_forwarding = 0 != listflags & DC_GCL_FOR_FORWARDING;
101        let flag_no_specials = 0 != listflags & DC_GCL_NO_SPECIALS;
102        let flag_add_alldone_hint = 0 != listflags & DC_GCL_ADD_ALLDONE_HINT;
103
104        let process_row = |row: &rusqlite::Row| {
105            let chat_id: ChatId = row.get(0)?;
106            let msg_id: Option<MsgId> = row.get(1)?;
107            Ok((chat_id, msg_id))
108        };
109
110        let skip_id = if flag_for_forwarding {
111            ChatId::lookup_by_contact(context, ContactId::DEVICE)
112                .await?
113                .unwrap_or_default()
114        } else {
115            ChatId::new(0)
116        };
117
118        // select with left join and minimum:
119        //
120        // - the inner select must use `hidden` and _not_ `m.hidden`
121        //   which would refer the outer select and take a lot of time
122        // - `GROUP BY` is needed several messages may have the same
123        //   timestamp
124        // - the list starts with the newest chats
125        //
126        // The query shows messages from blocked contacts in
127        // groups. Otherwise it would be hard to follow conversations.
128        let ids = if let Some(query_contact_id) = query_contact_id {
129            // show chats shared with a given contact
130            context.sql.query_map_vec(
131                "SELECT c.id, m.id
132                 FROM chats c
133                 LEFT JOIN msgs m
134                        ON c.id=m.chat_id
135                       AND m.id=(
136                               SELECT id
137                                 FROM msgs
138                                WHERE chat_id=c.id
139                                  AND (hidden=0 OR state=?1)
140                                  ORDER BY timestamp DESC, id DESC LIMIT 1)
141                 WHERE c.id>9
142                   AND c.blocked!=1
143                   AND c.id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=?2 AND add_timestamp >= remove_timestamp)
144                 GROUP BY c.id
145                 ORDER BY c.archived=?3 DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
146                (MessageState::OutDraft, query_contact_id, ChatVisibility::Pinned),
147                process_row,
148            ).await?
149        } else if flag_archived_only {
150            // show archived chats
151            // (this includes the archived device-chat; we could skip it,
152            // however, then the number of archived chats do not match, which might be even more irritating.
153            // and adapting the number requires larger refactorings and seems not to be worth the effort)
154            context
155                .sql
156                .query_map_vec(
157                    "SELECT c.id, m.id
158                 FROM chats c
159                 LEFT JOIN msgs m
160                        ON c.id=m.chat_id
161                       AND m.id=(
162                               SELECT id
163                                 FROM msgs
164                                WHERE chat_id=c.id
165                                  AND (hidden=0 OR state=?)
166                                  ORDER BY timestamp DESC, id DESC LIMIT 1)
167                 WHERE c.id>9
168                   AND c.blocked!=1
169                   AND c.archived=1
170                 GROUP BY c.id
171                 ORDER BY IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
172                    (MessageState::OutDraft,),
173                    process_row,
174                )
175                .await?
176        } else if let Some(query) = query {
177            let mut query = query.trim().to_string();
178            ensure!(!query.is_empty(), "query mustn't be empty");
179            let only_unread = IS_UNREAD_FILTER.find(&query).is_some();
180            query = IS_UNREAD_FILTER.replace(&query, "").trim().to_string();
181
182            // allow searching over special names that may change at any time
183            // when the ui calls set_stock_translation()
184            if let Err(err) = update_special_chat_names(context).await {
185                warn!(context, "Cannot update special chat names: {err:#}.")
186            }
187
188            let str_like_cmd = format!("%{query}%");
189            context
190                .sql
191                .query_map_vec(
192                    "SELECT c.id, m.id
193                 FROM chats c
194                 LEFT JOIN msgs m
195                        ON c.id=m.chat_id
196                       AND m.id=(
197                               SELECT id
198                                 FROM msgs
199                                WHERE chat_id=c.id
200                                  AND (hidden=0 OR state=?1)
201                                  ORDER BY timestamp DESC, id DESC LIMIT 1)
202                 WHERE c.id>9 AND c.id!=?2
203                   AND c.blocked!=1
204                   AND c.name LIKE ?3
205                   AND (NOT ?4 OR EXISTS (SELECT 1 FROM msgs m WHERE m.chat_id = c.id AND m.state == ?5 AND hidden=0))
206                 GROUP BY c.id
207                 ORDER BY IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
208                    (MessageState::OutDraft, skip_id, str_like_cmd, only_unread, MessageState::InFresh),
209                    process_row,
210                )
211                .await?
212        } else {
213            let mut ids = if flag_for_forwarding {
214                let sort_id_up = ChatId::lookup_by_contact(context, ContactId::SELF)
215                    .await?
216                    .unwrap_or_default();
217                let process_row = |row: &rusqlite::Row| {
218                    let chat_id: ChatId = row.get(0)?;
219                    let typ: Chattype = row.get(1)?;
220                    let param: Params = row.get::<_, String>(2)?.parse().unwrap_or_default();
221                    let msg_id: Option<MsgId> = row.get(3)?;
222                    Ok((chat_id, typ, param, msg_id))
223                };
224                let process_rows = |rows: rusqlite::AndThenRows<_>| {
225                    rows.filter_map(|row: std::result::Result<(_, _, Params, _), _>| match row {
226                        Ok((chat_id, typ, param, msg_id)) => {
227                            if typ == Chattype::Mailinglist
228                                && param.get(Param::ListPost).is_none_or_empty()
229                            {
230                                None
231                            } else {
232                                Some(Ok((chat_id, msg_id)))
233                            }
234                        }
235                        Err(e) => Some(Err(e)),
236                    })
237                    .collect::<std::result::Result<Vec<_>, _>>()
238                };
239                context.sql.query_map(
240                    "SELECT c.id, c.type, c.param, m.id
241                     FROM chats c
242                     LEFT JOIN msgs m
243                            ON c.id=m.chat_id
244                           AND m.id=(
245                                   SELECT id
246                                     FROM msgs
247                                    WHERE chat_id=c.id
248                                      AND (hidden=0 OR state=?)
249                                      ORDER BY timestamp DESC, id DESC LIMIT 1)
250                     WHERE c.id>9 AND c.id!=?
251                       AND c.blocked=0
252                       AND NOT c.archived=?
253                       AND (c.type!=? OR c.id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=? AND add_timestamp >= remove_timestamp))
254                     GROUP BY c.id
255                     ORDER BY c.id=? DESC, c.archived=? DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
256                    (
257                        MessageState::OutDraft, skip_id, ChatVisibility::Archived,
258                        Chattype::Group, ContactId::SELF,
259                        sort_id_up, ChatVisibility::Pinned,
260                    ),
261                    process_row,
262                    process_rows,
263                ).await?
264            } else {
265                //  show normal chatlist
266                context.sql.query_map_vec(
267                    "SELECT c.id, m.id
268                     FROM chats c
269                     LEFT JOIN msgs m
270                            ON c.id=m.chat_id
271                           AND m.id=(
272                                   SELECT id
273                                     FROM msgs
274                                    WHERE chat_id=c.id
275                                      AND (hidden=0 OR state=?)
276                                      ORDER BY timestamp DESC, id DESC LIMIT 1)
277                     WHERE c.id>9 AND c.id!=?
278                       AND (c.blocked=0 OR c.blocked=2)
279                       AND NOT c.archived=?
280                     GROUP BY c.id
281                     ORDER BY c.id=0 DESC, c.archived=? DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
282                    (MessageState::OutDraft, skip_id, ChatVisibility::Archived, ChatVisibility::Pinned),
283                    process_row,
284                ).await?
285            };
286            if !flag_no_specials && get_archived_cnt(context).await? > 0 {
287                if ids.is_empty() && flag_add_alldone_hint {
288                    ids.push((DC_CHAT_ID_ALLDONE_HINT, None));
289                }
290                ids.insert(0, (DC_CHAT_ID_ARCHIVED_LINK, None));
291            }
292            ids
293        };
294
295        Ok(Chatlist { ids })
296    }
297
298    /// Converts list of chat IDs to a chatlist.
299    pub(crate) async fn from_chat_ids(context: &Context, chat_ids: &[ChatId]) -> Result<Self> {
300        let mut ids = Vec::new();
301        for &chat_id in chat_ids {
302            let msg_id: Option<MsgId> = context
303                .sql
304                .query_get_value(
305                    "SELECT id
306                   FROM msgs
307                  WHERE chat_id=?1
308                    AND (hidden=0 OR state=?2)
309                  ORDER BY timestamp DESC, id DESC LIMIT 1",
310                    (chat_id, MessageState::OutDraft),
311                )
312                .await
313                .with_context(|| format!("failed to get msg ID for chat {chat_id}"))?;
314            ids.push((chat_id, msg_id));
315        }
316        Ok(Chatlist { ids })
317    }
318
319    /// Find out the number of chats.
320    pub fn len(&self) -> usize {
321        self.ids.len()
322    }
323
324    /// Returns true if chatlist is empty.
325    pub fn is_empty(&self) -> bool {
326        self.ids.is_empty()
327    }
328
329    /// Get a single chat ID of a chatlist.
330    ///
331    /// To get the message object from the message ID, use dc_get_chat().
332    pub fn get_chat_id(&self, index: usize) -> Result<ChatId> {
333        let (chat_id, _msg_id) = self
334            .ids
335            .get(index)
336            .context("chatlist index is out of range")?;
337        Ok(*chat_id)
338    }
339
340    /// Get a single message ID of a chatlist.
341    ///
342    /// To get the message object from the message ID, use dc_get_msg().
343    pub fn get_msg_id(&self, index: usize) -> Result<Option<MsgId>> {
344        let (_chat_id, msg_id) = self
345            .ids
346            .get(index)
347            .context("chatlist index is out of range")?;
348        Ok(*msg_id)
349    }
350
351    /// Returns a summary for a given chatlist index.
352    pub async fn get_summary(
353        &self,
354        context: &Context,
355        index: usize,
356        chat: Option<&Chat>,
357    ) -> Result<Summary> {
358        // The summary is created by the chat, not by the last message.
359        // This is because we may want to display drafts here or stuff as
360        // "is typing".
361        // Also, sth. as "No messages" would not work if the summary comes from a message.
362        let (chat_id, lastmsg_id) = self
363            .ids
364            .get(index)
365            .context("chatlist index is out of range")?;
366        Chatlist::get_summary2(context, *chat_id, *lastmsg_id, chat).await
367    }
368
369    /// Returns a summary for a given chatlist item.
370    pub async fn get_summary2(
371        context: &Context,
372        chat_id: ChatId,
373        lastmsg_id: Option<MsgId>,
374        chat: Option<&Chat>,
375    ) -> Result<Summary> {
376        let chat_loaded: Chat;
377        let chat = if let Some(chat) = chat {
378            chat
379        } else {
380            let chat = Chat::load_from_db(context, chat_id).await?;
381            chat_loaded = chat;
382            &chat_loaded
383        };
384
385        let lastmsg = if let Some(lastmsg_id) = lastmsg_id {
386            // Message may be deleted by the time we try to load it,
387            // so use `load_from_db_optional` instead of `load_from_db`.
388            Message::load_from_db_optional(context, lastmsg_id)
389                .await
390                .context("Loading message failed")?
391        } else {
392            None
393        };
394
395        let lastcontact = if let Some(lastmsg) = &lastmsg {
396            if lastmsg.from_id == ContactId::SELF {
397                None
398            } else if chat.typ == Chattype::Group
399                || chat.typ == Chattype::OutBroadcast
400                || chat.typ == Chattype::InBroadcast
401                || chat.typ == Chattype::Mailinglist
402                || chat.is_self_talk()
403            {
404                let lastcontact = Contact::get_by_id(context, lastmsg.from_id)
405                    .await
406                    .context("loading contact failed")?;
407                Some(lastcontact)
408            } else {
409                None
410            }
411        } else {
412            None
413        };
414
415        if chat.id.is_archived_link() {
416            Ok(Default::default())
417        } else if let Some(lastmsg) = lastmsg.filter(|msg| msg.from_id != ContactId::UNDEFINED) {
418            Summary::new_with_reaction_details(context, &lastmsg, chat, lastcontact.as_ref()).await
419        } else {
420            Ok(Summary {
421                text: stock_str::no_messages(context).await,
422                ..Default::default()
423            })
424        }
425    }
426
427    /// Returns chatlist item position for the given chat ID.
428    pub fn get_index_for_id(&self, id: ChatId) -> Option<usize> {
429        self.ids.iter().position(|(chat_id, _)| chat_id == &id)
430    }
431
432    /// An iterator visiting all chatlist items.
433    pub fn iter(&self) -> impl Iterator<Item = &(ChatId, Option<MsgId>)> {
434        self.ids.iter()
435    }
436}
437
438/// Returns the number of archived chats
439pub async fn get_archived_cnt(context: &Context) -> Result<usize> {
440    let count = context
441        .sql
442        .count(
443            "SELECT COUNT(*) FROM chats WHERE blocked!=? AND archived=?;",
444            (Blocked::Yes, ChatVisibility::Archived),
445        )
446        .await?;
447    Ok(count)
448}
449
450/// Gets the last message of a chat, the message that would also be displayed in the ChatList
451/// Used for passing to `deltachat::chatlist::Chatlist::get_summary2`
452pub async fn get_last_message_for_chat(
453    context: &Context,
454    chat_id: ChatId,
455) -> Result<Option<MsgId>> {
456    context
457        .sql
458        .query_get_value(
459            "SELECT id
460                FROM msgs
461                WHERE chat_id=?2
462                AND (hidden=0 OR state=?1)
463                ORDER BY timestamp DESC, id DESC LIMIT 1",
464            (MessageState::OutDraft, chat_id),
465        )
466        .await
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472    use crate::chat::save_msgs;
473    use crate::chat::{
474        add_contact_to_chat, create_group, get_chat_contacts, remove_contact_from_chat,
475        send_text_msg,
476    };
477    use crate::receive_imf::receive_imf;
478    use crate::stock_str::StockMessage;
479    use crate::test_utils::TestContext;
480    use crate::test_utils::TestContextManager;
481    use crate::tools::SystemTime;
482    use std::time::Duration;
483
484    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
485    async fn test_try_load() {
486        let mut tcm = TestContextManager::new();
487        let bob = &tcm.bob().await;
488        let chat_id1 = create_group(bob, "a chat").await.unwrap();
489        let chat_id2 = create_group(bob, "b chat").await.unwrap();
490        let chat_id3 = create_group(bob, "c chat").await.unwrap();
491
492        // check that the chatlist starts with the most recent message
493        let chats = Chatlist::try_load(bob, 0, None, None).await.unwrap();
494        assert_eq!(chats.len(), 3);
495        assert_eq!(chats.get_chat_id(0).unwrap(), chat_id3);
496        assert_eq!(chats.get_chat_id(1).unwrap(), chat_id2);
497        assert_eq!(chats.get_chat_id(2).unwrap(), chat_id1);
498
499        SystemTime::shift(Duration::from_secs(5));
500
501        // New drafts are sorted to the top
502        // We have to set a draft on the other two messages, too, as
503        // chat timestamps are only exact to the second and sorting by timestamp
504        // would not work.
505        // Message timestamps are "smeared" and unique, so we don't have this problem
506        // if we have any message (can be a draft) in all chats.
507        // Instead of setting drafts for chat_id1 and chat_id3, we could also sleep
508        // 2s here.
509        for chat_id in &[chat_id1, chat_id3, chat_id2] {
510            let mut msg = Message::new_text("hello".to_string());
511            chat_id.set_draft(bob, Some(&mut msg)).await.unwrap();
512        }
513
514        let chats = Chatlist::try_load(bob, 0, None, None).await.unwrap();
515        assert_eq!(chats.get_chat_id(0).unwrap(), chat_id2);
516
517        // check chatlist query and archive functionality
518        let chats = Chatlist::try_load(bob, 0, Some("b"), None).await.unwrap();
519        assert_eq!(chats.len(), 1);
520
521        // receive a message from alice
522        let alice = &tcm.alice().await;
523        let alice_chat_id = create_group(alice, "alice chat").await.unwrap();
524        add_contact_to_chat(
525            alice,
526            alice_chat_id,
527            alice.add_or_lookup_contact_id(bob).await,
528        )
529        .await
530        .unwrap();
531        send_text_msg(alice, alice_chat_id, "hi".into())
532            .await
533            .unwrap();
534        let sent_msg = alice.pop_sent_msg().await;
535
536        bob.recv_msg(&sent_msg).await;
537        let chats = Chatlist::try_load(bob, 0, Some("is:unread"), None)
538            .await
539            .unwrap();
540        assert_eq!(chats.len(), 1);
541
542        let chats = Chatlist::try_load(bob, DC_GCL_ARCHIVED_ONLY, None, None)
543            .await
544            .unwrap();
545        assert_eq!(chats.len(), 0);
546
547        chat_id1
548            .set_visibility(bob, ChatVisibility::Archived)
549            .await
550            .ok();
551        let chats = Chatlist::try_load(bob, DC_GCL_ARCHIVED_ONLY, None, None)
552            .await
553            .unwrap();
554        assert_eq!(chats.len(), 1);
555    }
556
557    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
558    async fn test_sort_self_talk_up_on_forward() {
559        let t = TestContext::new_alice().await;
560        t.update_device_chats().await.unwrap();
561        create_group(&t, "a chat").await.unwrap();
562
563        let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
564        assert_eq!(chats.len(), 3);
565        assert!(
566            !Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
567                .await
568                .unwrap()
569                .is_self_talk()
570        );
571
572        let chats = Chatlist::try_load(&t, DC_GCL_FOR_FORWARDING, None, None)
573            .await
574            .unwrap();
575        assert_eq!(chats.len(), 2); // device chat cannot be written and is skipped on forwarding
576        assert!(
577            Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
578                .await
579                .unwrap()
580                .is_self_talk()
581        );
582
583        remove_contact_from_chat(&t, chats.get_chat_id(1).unwrap(), ContactId::SELF)
584            .await
585            .unwrap();
586        let chats = Chatlist::try_load(&t, DC_GCL_FOR_FORWARDING, None, None)
587            .await
588            .unwrap();
589        assert_eq!(chats.len(), 1);
590    }
591
592    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
593    async fn test_search_special_chat_names() {
594        let t = TestContext::new_alice().await;
595        t.update_device_chats().await.unwrap();
596
597        let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
598            .await
599            .unwrap();
600        assert_eq!(chats.len(), 0);
601        let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
602            .await
603            .unwrap();
604        assert_eq!(chats.len(), 0);
605
606        t.set_stock_translation(StockMessage::SavedMessages, "test-1234-save".to_string())
607            .await
608            .unwrap();
609        let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
610            .await
611            .unwrap();
612        assert_eq!(chats.len(), 1);
613
614        t.set_stock_translation(StockMessage::DeviceMessages, "test-5678-babbel".to_string())
615            .await
616            .unwrap();
617        let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
618            .await
619            .unwrap();
620        assert_eq!(chats.len(), 1);
621    }
622
623    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
624    async fn test_search_single_chat() -> anyhow::Result<()> {
625        let t = TestContext::new_alice().await;
626
627        // receive a one-to-one-message
628        receive_imf(
629            &t,
630            b"From: Bob Authname <bob@example.org>\n\
631                 To: alice@example.org\n\
632                 Subject: foo\n\
633                 Message-ID: <msg1234@example.org>\n\
634                 Chat-Version: 1.0\n\
635                 Date: Sun, 22 Mar 2021 22:37:57 +0000\n\
636                 \n\
637                 hello foo\n",
638            false,
639        )
640        .await?;
641
642        let chats = Chatlist::try_load(&t, 0, Some("Bob Authname"), None).await?;
643        // Contact request should be searchable
644        assert_eq!(chats.len(), 1);
645
646        let msg = t.get_last_msg().await;
647        let chat_id = msg.get_chat_id();
648        chat_id.accept(&t).await.unwrap();
649
650        let contacts = get_chat_contacts(&t, chat_id).await?;
651        let contact_id = *contacts.first().unwrap();
652        let chat = Chat::load_from_db(&t, chat_id).await?;
653        assert_eq!(chat.get_name(), "Bob Authname");
654
655        // check, the one-to-one-chat can be found using chatlist search query
656        let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
657        assert_eq!(chats.len(), 1);
658        assert_eq!(chats.get_chat_id(0).unwrap(), chat_id);
659
660        // change the name of the contact; this also changes the name of the one-to-one-chat
661        let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
662        assert_eq!(contact_id, test_id);
663        let chat = Chat::load_from_db(&t, chat_id).await?;
664        assert_eq!(chat.get_name(), "Bob Nickname");
665        let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
666        assert_eq!(chats.len(), 0);
667        let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
668        assert_eq!(chats.len(), 1);
669
670        // revert contact to authname, this again changes the name of the one-to-one-chat
671        let test_id = Contact::create(&t, "", "bob@example.org").await?;
672        assert_eq!(contact_id, test_id);
673        let chat = Chat::load_from_db(&t, chat_id).await?;
674        assert_eq!(chat.get_name(), "Bob Authname");
675        let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
676        assert_eq!(chats.len(), 1);
677        let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
678        assert_eq!(chats.len(), 0);
679
680        Ok(())
681    }
682
683    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
684    async fn test_search_single_chat_without_authname() -> anyhow::Result<()> {
685        let t = TestContext::new_alice().await;
686
687        // receive a one-to-one-message without authname set
688        receive_imf(
689            &t,
690            b"From: bob@example.org\n\
691                 To: alice@example.org\n\
692                 Subject: foo\n\
693                 Message-ID: <msg5678@example.org>\n\
694                 Chat-Version: 1.0\n\
695                 Date: Sun, 22 Mar 2021 22:38:57 +0000\n\
696                 \n\
697                 hello foo\n",
698            false,
699        )
700        .await?;
701
702        let msg = t.get_last_msg().await;
703        let chat_id = msg.get_chat_id();
704        chat_id.accept(&t).await.unwrap();
705        let contacts = get_chat_contacts(&t, chat_id).await?;
706        let contact_id = *contacts.first().unwrap();
707        let chat = Chat::load_from_db(&t, chat_id).await?;
708        assert_eq!(chat.get_name(), "bob@example.org");
709
710        // check, the one-to-one-chat can be found using chatlist search query
711        let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
712        assert_eq!(chats.len(), 1);
713        assert_eq!(chats.get_chat_id(0)?, chat_id);
714
715        // change the name of the contact; this also changes the name of the one-to-one-chat
716        let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
717        assert_eq!(contact_id, test_id);
718        let chat = Chat::load_from_db(&t, chat_id).await?;
719        assert_eq!(chat.get_name(), "Bob Nickname");
720        let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
721        assert_eq!(chats.len(), 0); // email-addresses are searchable in contacts, not in chats
722        let chats = Chatlist::try_load(&t, 0, Some("Bob Nickname"), None).await?;
723        assert_eq!(chats.len(), 1);
724        assert_eq!(chats.get_chat_id(0)?, chat_id);
725
726        // revert name change, this again changes the name of the one-to-one-chat to the email-address
727        let test_id = Contact::create(&t, "", "bob@example.org").await?;
728        assert_eq!(contact_id, test_id);
729        let chat = Chat::load_from_db(&t, chat_id).await?;
730        assert_eq!(chat.get_name(), "bob@example.org");
731        let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
732        assert_eq!(chats.len(), 1);
733        let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
734        assert_eq!(chats.len(), 0);
735
736        // finally, also check that a simple substring-search is working with email-addresses
737        let chats = Chatlist::try_load(&t, 0, Some("b@exa"), None).await?;
738        assert_eq!(chats.len(), 1);
739        let chats = Chatlist::try_load(&t, 0, Some("b@exac"), None).await?;
740        assert_eq!(chats.len(), 0);
741
742        Ok(())
743    }
744
745    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
746    async fn test_get_summary_unwrap() {
747        let t = TestContext::new().await;
748        let chat_id1 = create_group(&t, "a chat").await.unwrap();
749
750        let mut msg = Message::new_text("foo:\nbar \r\n test".to_string());
751        chat_id1.set_draft(&t, Some(&mut msg)).await.unwrap();
752
753        let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
754        let summary = chats.get_summary(&t, 0, None).await.unwrap();
755        assert_eq!(summary.text, "foo: bar test"); // the linebreak should be removed from summary
756    }
757
758    /// Tests that summary does not fail to load
759    /// if the draft was deleted after loading the chatlist.
760    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
761    async fn test_get_summary_deleted_draft() {
762        let t = TestContext::new().await;
763
764        let chat_id = create_group(&t, "a chat").await.unwrap();
765        let mut msg = Message::new_text("Foobar".to_string());
766        chat_id.set_draft(&t, Some(&mut msg)).await.unwrap();
767
768        let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
769        chat_id.set_draft(&t, None).await.unwrap();
770
771        let summary_res = chats.get_summary(&t, 0, None).await;
772        assert!(summary_res.is_ok());
773    }
774
775    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
776    async fn test_get_summary_for_saved_messages() -> Result<()> {
777        let mut tcm = TestContextManager::new();
778        let alice = tcm.alice().await;
779        let bob = tcm.bob().await;
780        let chat_alice = alice.create_chat(&bob).await;
781
782        send_text_msg(&alice, chat_alice.id, "hi".into()).await?;
783        let sent1 = alice.pop_sent_msg().await;
784        save_msgs(&alice, &[sent1.sender_msg_id]).await?;
785        let chatlist = Chatlist::try_load(&alice, 0, None, None).await?;
786        let summary = chatlist.get_summary(&alice, 0, None).await?;
787        assert_eq!(summary.prefix.unwrap().to_string(), "Me");
788        assert_eq!(summary.text, "hi");
789
790        let msg = bob.recv_msg(&sent1).await;
791        save_msgs(&bob, &[msg.id]).await?;
792        let chatlist = Chatlist::try_load(&bob, 0, None, None).await?;
793        let summary = chatlist.get_summary(&bob, 0, None).await?;
794        assert_eq!(summary.prefix.unwrap().to_string(), "alice@example.org");
795        assert_eq!(summary.text, "hi");
796
797        Ok(())
798    }
799
800    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
801    async fn test_load_broken() {
802        let t = TestContext::new_bob().await;
803        let chat_id1 = create_group(&t, "a chat").await.unwrap();
804        create_group(&t, "b chat").await.unwrap();
805        create_group(&t, "c chat").await.unwrap();
806
807        // check that the chatlist starts with the most recent message
808        let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
809        assert_eq!(chats.len(), 3);
810
811        // obfuscated one chat
812        t.sql
813            .execute("UPDATE chats SET type=10 WHERE id=?", (chat_id1,))
814            .await
815            .unwrap();
816
817        // obfuscated chat can't be loaded
818        assert!(Chat::load_from_db(&t, chat_id1).await.is_err());
819
820        // chatlist loads fine
821        let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
822
823        // only corrupted chat fails to create summary
824        assert!(chats.get_summary(&t, 0, None).await.is_ok());
825        assert!(chats.get_summary(&t, 1, None).await.is_ok());
826        assert!(chats.get_summary(&t, 2, None).await.is_err());
827        assert_eq!(chats.get_index_for_id(chat_id1).unwrap(), 2);
828    }
829}