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 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(
249 "SELECT c.id, c.type, c.param, m.id
250 FROM chats c
251 LEFT JOIN msgs m
252 ON c.id=m.chat_id
253 AND m.id=(
254 SELECT id
255 FROM msgs
256 WHERE chat_id=c.id
257 AND (hidden=0 OR state=?)
258 ORDER BY timestamp DESC, id DESC LIMIT 1)
259 WHERE c.id>9 AND c.id!=?
260 AND c.blocked=0
261 AND NOT c.archived=?
262 AND (c.type!=? OR c.id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=? AND add_timestamp >= remove_timestamp))
263 GROUP BY c.id
264 ORDER BY c.id=? DESC, c.archived=? DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
265 (
266 MessageState::OutDraft, skip_id, ChatVisibility::Archived,
267 Chattype::Group, ContactId::SELF,
268 sort_id_up, ChatVisibility::Pinned,
269 ),
270 process_row,
271 process_rows,
272 ).await?
273 } else {
274 context.sql.query_map(
276 "SELECT c.id, m.id
277 FROM chats c
278 LEFT JOIN msgs m
279 ON c.id=m.chat_id
280 AND m.id=(
281 SELECT id
282 FROM msgs
283 WHERE chat_id=c.id
284 AND (hidden=0 OR state=?)
285 ORDER BY timestamp DESC, id DESC LIMIT 1)
286 WHERE c.id>9 AND c.id!=?
287 AND (c.blocked=0 OR c.blocked=2)
288 AND NOT c.archived=?
289 GROUP BY c.id
290 ORDER BY c.id=0 DESC, c.archived=? DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
291 (MessageState::OutDraft, skip_id, ChatVisibility::Archived, ChatVisibility::Pinned),
292 process_row,
293 process_rows,
294 ).await?
295 };
296 if !flag_no_specials && get_archived_cnt(context).await? > 0 {
297 if ids.is_empty() && flag_add_alldone_hint {
298 ids.push((DC_CHAT_ID_ALLDONE_HINT, None));
299 }
300 ids.insert(0, (DC_CHAT_ID_ARCHIVED_LINK, None));
301 }
302 ids
303 };
304
305 Ok(Chatlist { ids })
306 }
307
308 pub(crate) async fn from_chat_ids(context: &Context, chat_ids: &[ChatId]) -> Result<Self> {
310 let mut ids = Vec::new();
311 for &chat_id in chat_ids {
312 let msg_id: Option<MsgId> = context
313 .sql
314 .query_get_value(
315 "SELECT id
316 FROM msgs
317 WHERE chat_id=?1
318 AND (hidden=0 OR state=?2)
319 ORDER BY timestamp DESC, id DESC LIMIT 1",
320 (chat_id, MessageState::OutDraft),
321 )
322 .await
323 .with_context(|| format!("failed to get msg ID for chat {chat_id}"))?;
324 ids.push((chat_id, msg_id));
325 }
326 Ok(Chatlist { ids })
327 }
328
329 pub fn len(&self) -> usize {
331 self.ids.len()
332 }
333
334 pub fn is_empty(&self) -> bool {
336 self.ids.is_empty()
337 }
338
339 pub fn get_chat_id(&self, index: usize) -> Result<ChatId> {
343 let (chat_id, _msg_id) = self
344 .ids
345 .get(index)
346 .context("chatlist index is out of range")?;
347 Ok(*chat_id)
348 }
349
350 pub fn get_msg_id(&self, index: usize) -> Result<Option<MsgId>> {
354 let (_chat_id, msg_id) = self
355 .ids
356 .get(index)
357 .context("chatlist index is out of range")?;
358 Ok(*msg_id)
359 }
360
361 pub async fn get_summary(
363 &self,
364 context: &Context,
365 index: usize,
366 chat: Option<&Chat>,
367 ) -> Result<Summary> {
368 let (chat_id, lastmsg_id) = self
373 .ids
374 .get(index)
375 .context("chatlist index is out of range")?;
376 Chatlist::get_summary2(context, *chat_id, *lastmsg_id, chat).await
377 }
378
379 pub async fn get_summary2(
381 context: &Context,
382 chat_id: ChatId,
383 lastmsg_id: Option<MsgId>,
384 chat: Option<&Chat>,
385 ) -> Result<Summary> {
386 let chat_loaded: Chat;
387 let chat = if let Some(chat) = chat {
388 chat
389 } else {
390 let chat = Chat::load_from_db(context, chat_id).await?;
391 chat_loaded = chat;
392 &chat_loaded
393 };
394
395 let lastmsg = if let Some(lastmsg_id) = lastmsg_id {
396 Message::load_from_db_optional(context, lastmsg_id)
399 .await
400 .context("Loading message failed")?
401 } else {
402 None
403 };
404
405 let lastcontact = if let Some(lastmsg) = &lastmsg {
406 if lastmsg.from_id == ContactId::SELF {
407 None
408 } else if chat.typ == Chattype::Group
409 || chat.typ == Chattype::OutBroadcast
410 || chat.typ == Chattype::InBroadcast
411 || chat.typ == Chattype::Mailinglist
412 || chat.is_self_talk()
413 {
414 let lastcontact = Contact::get_by_id(context, lastmsg.from_id)
415 .await
416 .context("loading contact failed")?;
417 Some(lastcontact)
418 } else {
419 None
420 }
421 } else {
422 None
423 };
424
425 if chat.id.is_archived_link() {
426 Ok(Default::default())
427 } else if let Some(lastmsg) = lastmsg.filter(|msg| msg.from_id != ContactId::UNDEFINED) {
428 Summary::new_with_reaction_details(context, &lastmsg, chat, lastcontact.as_ref()).await
429 } else {
430 Ok(Summary {
431 text: stock_str::no_messages(context).await,
432 ..Default::default()
433 })
434 }
435 }
436
437 pub fn get_index_for_id(&self, id: ChatId) -> Option<usize> {
439 self.ids.iter().position(|(chat_id, _)| chat_id == &id)
440 }
441
442 pub fn iter(&self) -> impl Iterator<Item = &(ChatId, Option<MsgId>)> {
444 self.ids.iter()
445 }
446}
447
448pub async fn get_archived_cnt(context: &Context) -> Result<usize> {
450 let count = context
451 .sql
452 .count(
453 "SELECT COUNT(*) FROM chats WHERE blocked!=? AND archived=?;",
454 (Blocked::Yes, ChatVisibility::Archived),
455 )
456 .await?;
457 Ok(count)
458}
459
460pub async fn get_last_message_for_chat(
463 context: &Context,
464 chat_id: ChatId,
465) -> Result<Option<MsgId>> {
466 context
467 .sql
468 .query_get_value(
469 "SELECT id
470 FROM msgs
471 WHERE chat_id=?2
472 AND (hidden=0 OR state=?1)
473 ORDER BY timestamp DESC, id DESC LIMIT 1",
474 (MessageState::OutDraft, chat_id),
475 )
476 .await
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482 use crate::chat::save_msgs;
483 use crate::chat::{
484 ProtectionStatus, add_contact_to_chat, create_group_chat, get_chat_contacts,
485 remove_contact_from_chat, send_text_msg,
486 };
487 use crate::receive_imf::receive_imf;
488 use crate::stock_str::StockMessage;
489 use crate::test_utils::TestContext;
490 use crate::test_utils::TestContextManager;
491
492 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
493 async fn test_try_load() {
494 let mut tcm = TestContextManager::new();
495 let bob = &tcm.bob().await;
496 let chat_id1 = create_group_chat(bob, ProtectionStatus::Unprotected, "a chat")
497 .await
498 .unwrap();
499 let chat_id2 = create_group_chat(bob, ProtectionStatus::Unprotected, "b chat")
500 .await
501 .unwrap();
502 let chat_id3 = create_group_chat(bob, ProtectionStatus::Unprotected, "c chat")
503 .await
504 .unwrap();
505
506 let chats = Chatlist::try_load(bob, 0, None, None).await.unwrap();
508 assert_eq!(chats.len(), 3);
509 assert_eq!(chats.get_chat_id(0).unwrap(), chat_id3);
510 assert_eq!(chats.get_chat_id(1).unwrap(), chat_id2);
511 assert_eq!(chats.get_chat_id(2).unwrap(), chat_id1);
512
513 for chat_id in &[chat_id1, chat_id3, chat_id2] {
522 let mut msg = Message::new_text("hello".to_string());
523 chat_id.set_draft(bob, Some(&mut msg)).await.unwrap();
524 }
525
526 let chats = Chatlist::try_load(bob, 0, None, None).await.unwrap();
527 assert_eq!(chats.get_chat_id(0).unwrap(), chat_id2);
528
529 let chats = Chatlist::try_load(bob, 0, Some("b"), None).await.unwrap();
531 assert_eq!(chats.len(), 1);
532
533 let alice = &tcm.alice().await;
535 let alice_chat_id = create_group_chat(alice, ProtectionStatus::Unprotected, "alice chat")
536 .await
537 .unwrap();
538 add_contact_to_chat(
539 alice,
540 alice_chat_id,
541 alice.add_or_lookup_contact_id(bob).await,
542 )
543 .await
544 .unwrap();
545 send_text_msg(alice, alice_chat_id, "hi".into())
546 .await
547 .unwrap();
548 let sent_msg = alice.pop_sent_msg().await;
549
550 bob.recv_msg(&sent_msg).await;
551 let chats = Chatlist::try_load(bob, 0, Some("is:unread"), None)
552 .await
553 .unwrap();
554 assert_eq!(chats.len(), 1);
555
556 let chats = Chatlist::try_load(bob, DC_GCL_ARCHIVED_ONLY, None, None)
557 .await
558 .unwrap();
559 assert_eq!(chats.len(), 0);
560
561 chat_id1
562 .set_visibility(bob, ChatVisibility::Archived)
563 .await
564 .ok();
565 let chats = Chatlist::try_load(bob, DC_GCL_ARCHIVED_ONLY, None, None)
566 .await
567 .unwrap();
568 assert_eq!(chats.len(), 1);
569 }
570
571 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
572 async fn test_sort_self_talk_up_on_forward() {
573 let t = TestContext::new_alice().await;
574 t.update_device_chats().await.unwrap();
575 create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
576 .await
577 .unwrap();
578
579 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
580 assert_eq!(chats.len(), 3);
581 assert!(
582 !Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
583 .await
584 .unwrap()
585 .is_self_talk()
586 );
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!(
593 Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
594 .await
595 .unwrap()
596 .is_self_talk()
597 );
598
599 remove_contact_from_chat(&t, chats.get_chat_id(1).unwrap(), ContactId::SELF)
600 .await
601 .unwrap();
602 let chats = Chatlist::try_load(&t, DC_GCL_FOR_FORWARDING, None, None)
603 .await
604 .unwrap();
605 assert_eq!(chats.len(), 1);
606 }
607
608 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
609 async fn test_search_special_chat_names() {
610 let t = TestContext::new_alice().await;
611 t.update_device_chats().await.unwrap();
612
613 let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
614 .await
615 .unwrap();
616 assert_eq!(chats.len(), 0);
617 let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
618 .await
619 .unwrap();
620 assert_eq!(chats.len(), 0);
621
622 t.set_stock_translation(StockMessage::SavedMessages, "test-1234-save".to_string())
623 .await
624 .unwrap();
625 let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
626 .await
627 .unwrap();
628 assert_eq!(chats.len(), 1);
629
630 t.set_stock_translation(StockMessage::DeviceMessages, "test-5678-babbel".to_string())
631 .await
632 .unwrap();
633 let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
634 .await
635 .unwrap();
636 assert_eq!(chats.len(), 1);
637 }
638
639 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
640 async fn test_search_single_chat() -> anyhow::Result<()> {
641 let t = TestContext::new_alice().await;
642
643 receive_imf(
645 &t,
646 b"From: Bob Authname <bob@example.org>\n\
647 To: alice@example.org\n\
648 Subject: foo\n\
649 Message-ID: <msg1234@example.org>\n\
650 Chat-Version: 1.0\n\
651 Date: Sun, 22 Mar 2021 22:37:57 +0000\n\
652 \n\
653 hello foo\n",
654 false,
655 )
656 .await?;
657
658 let chats = Chatlist::try_load(&t, 0, Some("Bob Authname"), None).await?;
659 assert_eq!(chats.len(), 1);
661
662 let msg = t.get_last_msg().await;
663 let chat_id = msg.get_chat_id();
664 chat_id.accept(&t).await.unwrap();
665
666 let contacts = get_chat_contacts(&t, chat_id).await?;
667 let contact_id = *contacts.first().unwrap();
668 let chat = Chat::load_from_db(&t, chat_id).await?;
669 assert_eq!(chat.get_name(), "Bob Authname");
670
671 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
673 assert_eq!(chats.len(), 1);
674 assert_eq!(chats.get_chat_id(0).unwrap(), chat_id);
675
676 let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
678 assert_eq!(contact_id, test_id);
679 let chat = Chat::load_from_db(&t, chat_id).await?;
680 assert_eq!(chat.get_name(), "Bob Nickname");
681 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
682 assert_eq!(chats.len(), 0);
683 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
684 assert_eq!(chats.len(), 1);
685
686 let test_id = Contact::create(&t, "", "bob@example.org").await?;
688 assert_eq!(contact_id, test_id);
689 let chat = Chat::load_from_db(&t, chat_id).await?;
690 assert_eq!(chat.get_name(), "Bob Authname");
691 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
692 assert_eq!(chats.len(), 1);
693 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
694 assert_eq!(chats.len(), 0);
695
696 Ok(())
697 }
698
699 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
700 async fn test_search_single_chat_without_authname() -> anyhow::Result<()> {
701 let t = TestContext::new_alice().await;
702
703 receive_imf(
705 &t,
706 b"From: bob@example.org\n\
707 To: alice@example.org\n\
708 Subject: foo\n\
709 Message-ID: <msg5678@example.org>\n\
710 Chat-Version: 1.0\n\
711 Date: Sun, 22 Mar 2021 22:38:57 +0000\n\
712 \n\
713 hello foo\n",
714 false,
715 )
716 .await?;
717
718 let msg = t.get_last_msg().await;
719 let chat_id = msg.get_chat_id();
720 chat_id.accept(&t).await.unwrap();
721 let contacts = get_chat_contacts(&t, chat_id).await?;
722 let contact_id = *contacts.first().unwrap();
723 let chat = Chat::load_from_db(&t, chat_id).await?;
724 assert_eq!(chat.get_name(), "bob@example.org");
725
726 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
728 assert_eq!(chats.len(), 1);
729 assert_eq!(chats.get_chat_id(0)?, chat_id);
730
731 let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
733 assert_eq!(contact_id, test_id);
734 let chat = Chat::load_from_db(&t, chat_id).await?;
735 assert_eq!(chat.get_name(), "Bob Nickname");
736 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
737 assert_eq!(chats.len(), 0); let chats = Chatlist::try_load(&t, 0, Some("Bob Nickname"), None).await?;
739 assert_eq!(chats.len(), 1);
740 assert_eq!(chats.get_chat_id(0)?, chat_id);
741
742 let test_id = Contact::create(&t, "", "bob@example.org").await?;
744 assert_eq!(contact_id, test_id);
745 let chat = Chat::load_from_db(&t, chat_id).await?;
746 assert_eq!(chat.get_name(), "bob@example.org");
747 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
748 assert_eq!(chats.len(), 1);
749 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
750 assert_eq!(chats.len(), 0);
751
752 let chats = Chatlist::try_load(&t, 0, Some("b@exa"), None).await?;
754 assert_eq!(chats.len(), 1);
755 let chats = Chatlist::try_load(&t, 0, Some("b@exac"), None).await?;
756 assert_eq!(chats.len(), 0);
757
758 Ok(())
759 }
760
761 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
762 async fn test_get_summary_unwrap() {
763 let t = TestContext::new().await;
764 let chat_id1 = create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
765 .await
766 .unwrap();
767
768 let mut msg = Message::new_text("foo:\nbar \r\n test".to_string());
769 chat_id1.set_draft(&t, Some(&mut msg)).await.unwrap();
770
771 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
772 let summary = chats.get_summary(&t, 0, None).await.unwrap();
773 assert_eq!(summary.text, "foo: bar test"); }
775
776 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
779 async fn test_get_summary_deleted_draft() {
780 let t = TestContext::new().await;
781
782 let chat_id = create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
783 .await
784 .unwrap();
785 let mut msg = Message::new_text("Foobar".to_string());
786 chat_id.set_draft(&t, Some(&mut msg)).await.unwrap();
787
788 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
789 chat_id.set_draft(&t, None).await.unwrap();
790
791 let summary_res = chats.get_summary(&t, 0, None).await;
792 assert!(summary_res.is_ok());
793 }
794
795 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
796 async fn test_get_summary_for_saved_messages() -> Result<()> {
797 let mut tcm = TestContextManager::new();
798 let alice = tcm.alice().await;
799 let bob = tcm.bob().await;
800 let chat_alice = alice.create_chat(&bob).await;
801
802 send_text_msg(&alice, chat_alice.id, "hi".into()).await?;
803 let sent1 = alice.pop_sent_msg().await;
804 save_msgs(&alice, &[sent1.sender_msg_id]).await?;
805 let chatlist = Chatlist::try_load(&alice, 0, None, None).await?;
806 let summary = chatlist.get_summary(&alice, 0, None).await?;
807 assert_eq!(summary.prefix.unwrap().to_string(), "Me");
808 assert_eq!(summary.text, "hi");
809
810 let msg = bob.recv_msg(&sent1).await;
811 save_msgs(&bob, &[msg.id]).await?;
812 let chatlist = Chatlist::try_load(&bob, 0, None, None).await?;
813 let summary = chatlist.get_summary(&bob, 0, None).await?;
814 assert_eq!(summary.prefix.unwrap().to_string(), "alice@example.org");
815 assert_eq!(summary.text, "hi");
816
817 Ok(())
818 }
819
820 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
821 async fn test_load_broken() {
822 let t = TestContext::new_bob().await;
823 let chat_id1 = create_group_chat(&t, ProtectionStatus::Unprotected, "a chat")
824 .await
825 .unwrap();
826 create_group_chat(&t, ProtectionStatus::Unprotected, "b chat")
827 .await
828 .unwrap();
829 create_group_chat(&t, ProtectionStatus::Unprotected, "c chat")
830 .await
831 .unwrap();
832
833 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
835 assert_eq!(chats.len(), 3);
836
837 t.sql
839 .execute("UPDATE chats SET type=10 WHERE id=?", (chat_id1,))
840 .await
841 .unwrap();
842
843 assert!(Chat::load_from_db(&t, chat_id1).await.is_err());
845
846 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
848
849 assert!(chats.get_summary(&t, 0, None).await.is_ok());
851 assert!(chats.get_summary(&t, 1, None).await.is_ok());
852 assert!(chats.get_summary(&t, 2, None).await.is_err());
853 assert_eq!(chats.get_index_for_id(chat_id1).unwrap(), 2);
854 }
855}