1use 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
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 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 let ids = if let Some(query_contact_id) = query_contact_id {
129 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 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 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 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 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 pub fn len(&self) -> usize {
321 self.ids.len()
322 }
323
324 pub fn is_empty(&self) -> bool {
326 self.ids.is_empty()
327 }
328
329 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 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 pub async fn get_summary(
353 &self,
354 context: &Context,
355 index: usize,
356 chat: Option<&Chat>,
357 ) -> Result<Summary> {
358 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 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::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 pub fn get_index_for_id(&self, id: ChatId) -> Option<usize> {
429 self.ids.iter().position(|(chat_id, _)| chat_id == &id)
430 }
431
432 pub fn iter(&self) -> impl Iterator<Item = &(ChatId, Option<MsgId>)> {
434 self.ids.iter()
435 }
436}
437
438pub 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
450pub 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 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 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 let chats = Chatlist::try_load(bob, 0, Some("b"), None).await.unwrap();
519 assert_eq!(chats.len(), 1);
520
521 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); 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_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 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 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 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 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_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 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 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); 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 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 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"); }
757
758 #[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 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
809 assert_eq!(chats.len(), 3);
810
811 t.sql
813 .execute("UPDATE chats SET type=10 WHERE id=?", (chat_id1,))
814 .await
815 .unwrap();
816
817 assert!(Chat::load_from_db(&t, chat_id1).await.is_err());
819
820 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
822
823 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}