1use anyhow::{ensure, Context as _, Result};
4use std::sync::LazyLock;
5
6use crate::chat::{update_special_chat_names, Chat, ChatId, ChatVisibility};
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
20pub static IS_UNREAD_FILTER: LazyLock<regex::Regex> =
22 LazyLock::new(|| regex::Regex::new(r"\bis:unread\b").unwrap());
23
24#[derive(Debug)]
46pub struct Chatlist {
47 ids: Vec<(ChatId, Option<MsgId>)>,
49}
50
51impl Chatlist {
52 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 process_rows = |rows: rusqlite::MappedRows<_>| {
111 rows.collect::<std::result::Result<Vec<_>, _>>()
112 .map_err(Into::into)
113 };
114
115 let skip_id = if flag_for_forwarding {
116 ChatId::lookup_by_contact(context, ContactId::DEVICE)
117 .await?
118 .unwrap_or_default()
119 } else {
120 ChatId::new(0)
121 };
122
123 let ids = if let Some(query_contact_id) = query_contact_id {
134 context.sql.query_map(
136 "SELECT c.id, m.id
137 FROM chats c
138 LEFT JOIN msgs m
139 ON c.id=m.chat_id
140 AND m.id=(
141 SELECT id
142 FROM msgs
143 WHERE chat_id=c.id
144 AND (hidden=0 OR state=?1)
145 ORDER BY timestamp DESC, id DESC LIMIT 1)
146 WHERE c.id>9
147 AND c.blocked!=1
148 AND c.id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=?2 AND add_timestamp >= remove_timestamp)
149 GROUP BY c.id
150 ORDER BY c.archived=?3 DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
151 (MessageState::OutDraft, query_contact_id, ChatVisibility::Pinned),
152 process_row,
153 process_rows,
154 ).await?
155 } else if flag_archived_only {
156 context
161 .sql
162 .query_map(
163 "SELECT c.id, m.id
164 FROM chats c
165 LEFT JOIN msgs m
166 ON c.id=m.chat_id
167 AND m.id=(
168 SELECT id
169 FROM msgs
170 WHERE chat_id=c.id
171 AND (hidden=0 OR state=?)
172 ORDER BY timestamp DESC, id DESC LIMIT 1)
173 WHERE c.id>9
174 AND c.blocked!=1
175 AND c.archived=1
176 GROUP BY c.id
177 ORDER BY IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
178 (MessageState::OutDraft,),
179 process_row,
180 process_rows,
181 )
182 .await?
183 } else if let Some(query) = query {
184 let mut query = query.trim().to_string();
185 ensure!(!query.is_empty(), "query mustn't be empty");
186 let only_unread = IS_UNREAD_FILTER.find(&query).is_some();
187 query = IS_UNREAD_FILTER.replace(&query, "").trim().to_string();
188
189 if let Err(err) = update_special_chat_names(context).await {
192 warn!(context, "Cannot update special chat names: {err:#}.")
193 }
194
195 let str_like_cmd = format!("%{query}%");
196 context
197 .sql
198 .query_map(
199 "SELECT c.id, m.id
200 FROM chats c
201 LEFT JOIN msgs m
202 ON c.id=m.chat_id
203 AND m.id=(
204 SELECT id
205 FROM msgs
206 WHERE chat_id=c.id
207 AND (hidden=0 OR state=?1)
208 ORDER BY timestamp DESC, id DESC LIMIT 1)
209 WHERE c.id>9 AND c.id!=?2
210 AND c.blocked!=1
211 AND c.name LIKE ?3
212 AND (NOT ?4 OR EXISTS (SELECT 1 FROM msgs m WHERE m.chat_id = c.id AND m.state == ?5 AND hidden=0))
213 GROUP BY c.id
214 ORDER BY IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
215 (MessageState::OutDraft, skip_id, str_like_cmd, only_unread, MessageState::InFresh),
216 process_row,
217 process_rows,
218 )
219 .await?
220 } else {
221 let mut ids = if flag_for_forwarding {
222 let sort_id_up = ChatId::lookup_by_contact(context, ContactId::SELF)
223 .await?
224 .unwrap_or_default();
225 let process_row = |row: &rusqlite::Row| {
226 let chat_id: ChatId = row.get(0)?;
227 let typ: Chattype = row.get(1)?;
228 let param: Params = row.get::<_, String>(2)?.parse().unwrap_or_default();
229 let msg_id: Option<MsgId> = row.get(3)?;
230 Ok((chat_id, typ, param, msg_id))
231 };
232 let process_rows = |rows: rusqlite::MappedRows<_>| {
233 rows.filter_map(|row: std::result::Result<(_, _, Params, _), _>| match row {
234 Ok((chat_id, typ, param, msg_id)) => {
235 if typ == Chattype::Mailinglist
236 && param.get(Param::ListPost).is_none_or_empty()
237 {
238 None
239 } else {
240 Some(Ok((chat_id, msg_id)))
241 }
242 }
243 Err(e) => Some(Err(e)),
244 })
245 .collect::<std::result::Result<Vec<_>, _>>()
246 .map_err(Into::into)
247 };
248 context.sql.query_map(
252 "SELECT c.id, c.type, c.param, m.id
253 FROM chats c
254 LEFT JOIN msgs m
255 ON c.id=m.chat_id
256 AND m.id=(
257 SELECT id
258 FROM msgs
259 WHERE chat_id=c.id
260 AND (hidden=0 OR state=?)
261 ORDER BY timestamp DESC, id DESC LIMIT 1)
262 WHERE c.id>9 AND c.id!=?
263 AND c.blocked=0
264 AND NOT c.archived=?
265 AND (c.type!=? OR c.id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=? AND add_timestamp >= remove_timestamp))
266 GROUP BY c.id
267 ORDER BY c.id=? DESC, c.archived=? DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
268 (
269 MessageState::OutDraft, skip_id, ChatVisibility::Archived,
270 Chattype::Group, ContactId::SELF,
271 sort_id_up, ChatVisibility::Pinned,
272 ),
273 process_row,
274 process_rows,
275 ).await?
276 } else {
277 context.sql.query_map(
279 "SELECT c.id, m.id
280 FROM chats c
281 LEFT JOIN msgs m
282 ON c.id=m.chat_id
283 AND m.id=(
284 SELECT id
285 FROM msgs
286 WHERE chat_id=c.id
287 AND (hidden=0 OR state=?)
288 ORDER BY timestamp DESC, id DESC LIMIT 1)
289 WHERE c.id>9 AND c.id!=?
290 AND (c.blocked=0 OR c.blocked=2)
291 AND NOT c.archived=?
292 GROUP BY c.id
293 ORDER BY c.id=0 DESC, c.archived=? DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
294 (MessageState::OutDraft, skip_id, ChatVisibility::Archived, ChatVisibility::Pinned),
295 process_row,
296 process_rows,
297 ).await?
298 };
299 if !flag_no_specials && get_archived_cnt(context).await? > 0 {
300 if ids.is_empty() && flag_add_alldone_hint {
301 ids.push((DC_CHAT_ID_ALLDONE_HINT, None));
302 }
303 ids.insert(0, (DC_CHAT_ID_ARCHIVED_LINK, None));
304 }
305 ids
306 };
307
308 Ok(Chatlist { ids })
309 }
310
311 pub(crate) async fn from_chat_ids(context: &Context, chat_ids: &[ChatId]) -> Result<Self> {
313 let mut ids = Vec::new();
314 for &chat_id in chat_ids {
315 let msg_id: Option<MsgId> = context
316 .sql
317 .query_get_value(
318 "SELECT id
319 FROM msgs
320 WHERE chat_id=?1
321 AND (hidden=0 OR state=?2)
322 ORDER BY timestamp DESC, id DESC LIMIT 1",
323 (chat_id, MessageState::OutDraft),
324 )
325 .await
326 .with_context(|| format!("failed to get msg ID for chat {chat_id}"))?;
327 ids.push((chat_id, msg_id));
328 }
329 Ok(Chatlist { ids })
330 }
331
332 pub fn len(&self) -> usize {
334 self.ids.len()
335 }
336
337 pub fn is_empty(&self) -> bool {
339 self.ids.is_empty()
340 }
341
342 pub fn get_chat_id(&self, index: usize) -> Result<ChatId> {
346 let (chat_id, _msg_id) = self
347 .ids
348 .get(index)
349 .context("chatlist index is out of range")?;
350 Ok(*chat_id)
351 }
352
353 pub fn get_msg_id(&self, index: usize) -> Result<Option<MsgId>> {
357 let (_chat_id, msg_id) = self
358 .ids
359 .get(index)
360 .context("chatlist index is out of range")?;
361 Ok(*msg_id)
362 }
363
364 pub async fn get_summary(
366 &self,
367 context: &Context,
368 index: usize,
369 chat: Option<&Chat>,
370 ) -> Result<Summary> {
371 let (chat_id, lastmsg_id) = self
376 .ids
377 .get(index)
378 .context("chatlist index is out of range")?;
379 Chatlist::get_summary2(context, *chat_id, *lastmsg_id, chat).await
380 }
381
382 pub async fn get_summary2(
384 context: &Context,
385 chat_id: ChatId,
386 lastmsg_id: Option<MsgId>,
387 chat: Option<&Chat>,
388 ) -> Result<Summary> {
389 let chat_loaded: Chat;
390 let chat = if let Some(chat) = chat {
391 chat
392 } else {
393 let chat = Chat::load_from_db(context, chat_id).await?;
394 chat_loaded = chat;
395 &chat_loaded
396 };
397
398 let lastmsg = if let Some(lastmsg_id) = lastmsg_id {
399 Message::load_from_db_optional(context, lastmsg_id)
402 .await
403 .context("Loading message failed")?
404 } else {
405 None
406 };
407
408 let lastcontact = if let Some(lastmsg) = &lastmsg {
409 if lastmsg.from_id == ContactId::SELF {
410 None
411 } else if chat.typ == Chattype::Group
412 || chat.typ == Chattype::Broadcast
413 || chat.typ == Chattype::Mailinglist
414 || chat.is_self_talk()
415 {
416 let lastcontact = Contact::get_by_id(context, lastmsg.from_id)
417 .await
418 .context("loading contact failed")?;
419 Some(lastcontact)
420 } else {
421 None
422 }
423 } else {
424 None
425 };
426
427 if chat.id.is_archived_link() {
428 Ok(Default::default())
429 } else if let Some(lastmsg) = lastmsg.filter(|msg| msg.from_id != ContactId::UNDEFINED) {
430 Summary::new_with_reaction_details(context, &lastmsg, chat, lastcontact.as_ref()).await
431 } else {
432 Ok(Summary {
433 text: stock_str::no_messages(context).await,
434 ..Default::default()
435 })
436 }
437 }
438
439 pub fn get_index_for_id(&self, id: ChatId) -> Option<usize> {
441 self.ids.iter().position(|(chat_id, _)| chat_id == &id)
442 }
443
444 pub fn iter(&self) -> impl Iterator<Item = &(ChatId, Option<MsgId>)> {
446 self.ids.iter()
447 }
448}
449
450pub async fn get_archived_cnt(context: &Context) -> Result<usize> {
452 let count = context
453 .sql
454 .count(
455 "SELECT COUNT(*) FROM chats WHERE blocked!=? AND archived=?;",
456 (Blocked::Yes, ChatVisibility::Archived),
457 )
458 .await?;
459 Ok(count)
460}
461
462pub async fn get_last_message_for_chat(
465 context: &Context,
466 chat_id: ChatId,
467) -> Result<Option<MsgId>> {
468 context
469 .sql
470 .query_get_value(
471 "SELECT id
472 FROM msgs
473 WHERE chat_id=?2
474 AND (hidden=0 OR state=?1)
475 ORDER BY timestamp DESC, id DESC LIMIT 1",
476 (MessageState::OutDraft, chat_id),
477 )
478 .await
479}
480
481#[cfg(test)]
482mod tests {
483 use super::*;
484 use crate::chat::save_msgs;
485 use crate::chat::{
486 add_contact_to_chat, create_group_chat, get_chat_contacts, remove_contact_from_chat,
487 send_text_msg, ProtectionStatus,
488 };
489 use crate::receive_imf::receive_imf;
490 use crate::stock_str::StockMessage;
491 use crate::test_utils::TestContext;
492 use crate::test_utils::TestContextManager;
493
494 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
495 async fn test_try_load() {
496 let mut tcm = TestContextManager::new();
497 let bob = &tcm.bob().await;
498 let chat_id1 = create_group_chat(bob, ProtectionStatus::Unprotected, "a chat")
499 .await
500 .unwrap();
501 let chat_id2 = create_group_chat(bob, ProtectionStatus::Unprotected, "b chat")
502 .await
503 .unwrap();
504 let chat_id3 = create_group_chat(bob, ProtectionStatus::Unprotected, "c chat")
505 .await
506 .unwrap();
507
508 let chats = Chatlist::try_load(bob, 0, None, None).await.unwrap();
510 assert_eq!(chats.len(), 3);
511 assert_eq!(chats.get_chat_id(0).unwrap(), chat_id3);
512 assert_eq!(chats.get_chat_id(1).unwrap(), chat_id2);
513 assert_eq!(chats.get_chat_id(2).unwrap(), chat_id1);
514
515 for chat_id in &[chat_id1, chat_id3, chat_id2] {
524 let mut msg = Message::new_text("hello".to_string());
525 chat_id.set_draft(bob, Some(&mut msg)).await.unwrap();
526 }
527
528 let chats = Chatlist::try_load(bob, 0, None, None).await.unwrap();
529 assert_eq!(chats.get_chat_id(0).unwrap(), chat_id2);
530
531 let chats = Chatlist::try_load(bob, 0, Some("b"), None).await.unwrap();
533 assert_eq!(chats.len(), 1);
534
535 let alice = &tcm.alice().await;
537 let alice_chat_id = create_group_chat(alice, ProtectionStatus::Unprotected, "alice chat")
538 .await
539 .unwrap();
540 add_contact_to_chat(
541 alice,
542 alice_chat_id,
543 alice.add_or_lookup_contact_id(bob).await,
544 )
545 .await
546 .unwrap();
547 send_text_msg(alice, alice_chat_id, "hi".into())
548 .await
549 .unwrap();
550 let sent_msg = alice.pop_sent_msg().await;
551
552 bob.recv_msg(&sent_msg).await;
553 let chats = Chatlist::try_load(bob, 0, Some("is:unread"), None)
554 .await
555 .unwrap();
556 assert_eq!(chats.len(), 1);
557
558 let chats = Chatlist::try_load(bob, DC_GCL_ARCHIVED_ONLY, None, None)
559 .await
560 .unwrap();
561 assert_eq!(chats.len(), 0);
562
563 chat_id1
564 .set_visibility(bob, ChatVisibility::Archived)
565 .await
566 .ok();
567 let chats = Chatlist::try_load(bob, DC_GCL_ARCHIVED_ONLY, None, None)
568 .await
569 .unwrap();
570 assert_eq!(chats.len(), 1);
571 }
572
573 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
574 async fn test_sort_self_talk_up_on_forward() {
575 let t = TestContext::new_alice().await;
576 t.update_device_chats().await.unwrap();
577 create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
578 .await
579 .unwrap();
580
581 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
582 assert_eq!(chats.len(), 3);
583 assert!(!Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
584 .await
585 .unwrap()
586 .is_self_talk());
587
588 let chats = Chatlist::try_load(&t, DC_GCL_FOR_FORWARDING, None, None)
589 .await
590 .unwrap();
591 assert_eq!(chats.len(), 2); assert!(Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
593 .await
594 .unwrap()
595 .is_self_talk());
596
597 remove_contact_from_chat(&t, chats.get_chat_id(1).unwrap(), ContactId::SELF)
598 .await
599 .unwrap();
600 let chats = Chatlist::try_load(&t, DC_GCL_FOR_FORWARDING, None, None)
601 .await
602 .unwrap();
603 assert_eq!(chats.len(), 1);
604 }
605
606 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
607 async fn test_search_special_chat_names() {
608 let t = TestContext::new_alice().await;
609 t.update_device_chats().await.unwrap();
610
611 let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
612 .await
613 .unwrap();
614 assert_eq!(chats.len(), 0);
615 let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
616 .await
617 .unwrap();
618 assert_eq!(chats.len(), 0);
619
620 t.set_stock_translation(StockMessage::SavedMessages, "test-1234-save".to_string())
621 .await
622 .unwrap();
623 let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
624 .await
625 .unwrap();
626 assert_eq!(chats.len(), 1);
627
628 t.set_stock_translation(StockMessage::DeviceMessages, "test-5678-babbel".to_string())
629 .await
630 .unwrap();
631 let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
632 .await
633 .unwrap();
634 assert_eq!(chats.len(), 1);
635 }
636
637 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
638 async fn test_search_single_chat() -> anyhow::Result<()> {
639 let t = TestContext::new_alice().await;
640
641 receive_imf(
643 &t,
644 b"From: Bob Authname <bob@example.org>\n\
645 To: alice@example.org\n\
646 Subject: foo\n\
647 Message-ID: <msg1234@example.org>\n\
648 Chat-Version: 1.0\n\
649 Date: Sun, 22 Mar 2021 22:37:57 +0000\n\
650 \n\
651 hello foo\n",
652 false,
653 )
654 .await?;
655
656 let chats = Chatlist::try_load(&t, 0, Some("Bob Authname"), None).await?;
657 assert_eq!(chats.len(), 1);
659
660 let msg = t.get_last_msg().await;
661 let chat_id = msg.get_chat_id();
662 chat_id.accept(&t).await.unwrap();
663
664 let contacts = get_chat_contacts(&t, chat_id).await?;
665 let contact_id = *contacts.first().unwrap();
666 let chat = Chat::load_from_db(&t, chat_id).await?;
667 assert_eq!(chat.get_name(), "Bob Authname");
668
669 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
671 assert_eq!(chats.len(), 1);
672 assert_eq!(chats.get_chat_id(0).unwrap(), chat_id);
673
674 let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
676 assert_eq!(contact_id, test_id);
677 let chat = Chat::load_from_db(&t, chat_id).await?;
678 assert_eq!(chat.get_name(), "Bob Nickname");
679 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
680 assert_eq!(chats.len(), 0);
681 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
682 assert_eq!(chats.len(), 1);
683
684 let test_id = Contact::create(&t, "", "bob@example.org").await?;
686 assert_eq!(contact_id, test_id);
687 let chat = Chat::load_from_db(&t, chat_id).await?;
688 assert_eq!(chat.get_name(), "Bob Authname");
689 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
690 assert_eq!(chats.len(), 1);
691 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
692 assert_eq!(chats.len(), 0);
693
694 Ok(())
695 }
696
697 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
698 async fn test_search_single_chat_without_authname() -> anyhow::Result<()> {
699 let t = TestContext::new_alice().await;
700
701 receive_imf(
703 &t,
704 b"From: bob@example.org\n\
705 To: alice@example.org\n\
706 Subject: foo\n\
707 Message-ID: <msg5678@example.org>\n\
708 Chat-Version: 1.0\n\
709 Date: Sun, 22 Mar 2021 22:38:57 +0000\n\
710 \n\
711 hello foo\n",
712 false,
713 )
714 .await?;
715
716 let msg = t.get_last_msg().await;
717 let chat_id = msg.get_chat_id();
718 chat_id.accept(&t).await.unwrap();
719 let contacts = get_chat_contacts(&t, chat_id).await?;
720 let contact_id = *contacts.first().unwrap();
721 let chat = Chat::load_from_db(&t, chat_id).await?;
722 assert_eq!(chat.get_name(), "bob@example.org");
723
724 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
726 assert_eq!(chats.len(), 1);
727 assert_eq!(chats.get_chat_id(0)?, chat_id);
728
729 let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
731 assert_eq!(contact_id, test_id);
732 let chat = Chat::load_from_db(&t, chat_id).await?;
733 assert_eq!(chat.get_name(), "Bob Nickname");
734 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
735 assert_eq!(chats.len(), 0); let chats = Chatlist::try_load(&t, 0, Some("Bob Nickname"), None).await?;
737 assert_eq!(chats.len(), 1);
738 assert_eq!(chats.get_chat_id(0)?, chat_id);
739
740 let test_id = Contact::create(&t, "", "bob@example.org").await?;
742 assert_eq!(contact_id, test_id);
743 let chat = Chat::load_from_db(&t, chat_id).await?;
744 assert_eq!(chat.get_name(), "bob@example.org");
745 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
746 assert_eq!(chats.len(), 1);
747 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
748 assert_eq!(chats.len(), 0);
749
750 let chats = Chatlist::try_load(&t, 0, Some("b@exa"), None).await?;
752 assert_eq!(chats.len(), 1);
753 let chats = Chatlist::try_load(&t, 0, Some("b@exac"), None).await?;
754 assert_eq!(chats.len(), 0);
755
756 Ok(())
757 }
758
759 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
760 async fn test_get_summary_unwrap() {
761 let t = TestContext::new().await;
762 let chat_id1 = create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
763 .await
764 .unwrap();
765
766 let mut msg = Message::new_text("foo:\nbar \r\n test".to_string());
767 chat_id1.set_draft(&t, Some(&mut msg)).await.unwrap();
768
769 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
770 let summary = chats.get_summary(&t, 0, None).await.unwrap();
771 assert_eq!(summary.text, "foo: bar test"); }
773
774 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
777 async fn test_get_summary_deleted_draft() {
778 let t = TestContext::new().await;
779
780 let chat_id = create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
781 .await
782 .unwrap();
783 let mut msg = Message::new_text("Foobar".to_string());
784 chat_id.set_draft(&t, Some(&mut msg)).await.unwrap();
785
786 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
787 chat_id.set_draft(&t, None).await.unwrap();
788
789 let summary_res = chats.get_summary(&t, 0, None).await;
790 assert!(summary_res.is_ok());
791 }
792
793 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
794 async fn test_get_summary_for_saved_messages() -> Result<()> {
795 let mut tcm = TestContextManager::new();
796 let alice = tcm.alice().await;
797 let bob = tcm.bob().await;
798 let chat_alice = alice.create_chat(&bob).await;
799
800 send_text_msg(&alice, chat_alice.id, "hi".into()).await?;
801 let sent1 = alice.pop_sent_msg().await;
802 save_msgs(&alice, &[sent1.sender_msg_id]).await?;
803 let chatlist = Chatlist::try_load(&alice, 0, None, None).await?;
804 let summary = chatlist.get_summary(&alice, 0, None).await?;
805 assert_eq!(summary.prefix.unwrap().to_string(), "Me");
806 assert_eq!(summary.text, "hi");
807
808 let msg = bob.recv_msg(&sent1).await;
809 save_msgs(&bob, &[msg.id]).await?;
810 let chatlist = Chatlist::try_load(&bob, 0, None, None).await?;
811 let summary = chatlist.get_summary(&bob, 0, None).await?;
812 assert_eq!(summary.prefix.unwrap().to_string(), "alice@example.org");
813 assert_eq!(summary.text, "hi");
814
815 Ok(())
816 }
817
818 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
819 async fn test_load_broken() {
820 let t = TestContext::new_bob().await;
821 let chat_id1 = create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
822 .await
823 .unwrap();
824 create_group_chat(&t, ProtectionStatus::Unprotected, "b chat")
825 .await
826 .unwrap();
827 create_group_chat(&t, ProtectionStatus::Unprotected, "c chat")
828 .await
829 .unwrap();
830
831 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
833 assert_eq!(chats.len(), 3);
834
835 t.sql
837 .execute("UPDATE chats SET type=10 WHERE id=?", (chat_id1,))
838 .await
839 .unwrap();
840
841 assert!(Chat::load_from_db(&t, chat_id1).await.is_err());
843
844 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
846
847 assert!(chats.get_summary(&t, 0, None).await.is_ok());
849 assert!(chats.get_summary(&t, 1, None).await.is_ok());
850 assert!(chats.get_summary(&t, 2, None).await.is_err());
851 assert_eq!(chats.get_index_for_id(chat_id1).unwrap(), 2);
852 }
853}