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.to_lowercase());
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 IFNULL(c.name_normalized,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, set_chat_name,
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() -> Result<()> {
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 let chat_id = create_group(bob, "Δ-chat").await.unwrap();
557 let chats = Chatlist::try_load(bob, 0, Some("δ"), None).await?;
558 assert_eq!(chats.len(), 1);
559 assert_eq!(chats.ids[0].0, chat_id);
560 set_chat_name(bob, chat_id, "abcδe").await?;
561 let chats = Chatlist::try_load(bob, 0, Some("Δ"), None).await?;
562 assert_eq!(chats.len(), 1);
563 Ok(())
564 }
565
566 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
567 async fn test_sort_self_talk_up_on_forward() {
568 let t = TestContext::new_alice().await;
569 t.update_device_chats().await.unwrap();
570 create_group(&t, "a chat").await.unwrap();
571
572 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
573 assert_eq!(chats.len(), 3);
574 assert!(
575 !Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
576 .await
577 .unwrap()
578 .is_self_talk()
579 );
580
581 let chats = Chatlist::try_load(&t, DC_GCL_FOR_FORWARDING, None, None)
582 .await
583 .unwrap();
584 assert_eq!(chats.len(), 2); assert!(
586 Chat::load_from_db(&t, chats.get_chat_id(0).unwrap())
587 .await
588 .unwrap()
589 .is_self_talk()
590 );
591
592 remove_contact_from_chat(&t, chats.get_chat_id(1).unwrap(), ContactId::SELF)
593 .await
594 .unwrap();
595 let chats = Chatlist::try_load(&t, DC_GCL_FOR_FORWARDING, None, None)
596 .await
597 .unwrap();
598 assert_eq!(chats.len(), 1);
599 }
600
601 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
602 async fn test_search_special_chat_names() {
603 let t = TestContext::new_alice().await;
604 t.update_device_chats().await.unwrap();
605
606 let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
607 .await
608 .unwrap();
609 assert_eq!(chats.len(), 0);
610 let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
611 .await
612 .unwrap();
613 assert_eq!(chats.len(), 0);
614
615 t.set_stock_translation(StockMessage::SavedMessages, "test-1234-save".to_string())
616 .await
617 .unwrap();
618 let chats = Chatlist::try_load(&t, 0, Some("t-1234-s"), None)
619 .await
620 .unwrap();
621 assert_eq!(chats.len(), 1);
622
623 t.set_stock_translation(StockMessage::DeviceMessages, "test-5678-babbel".to_string())
624 .await
625 .unwrap();
626 let chats = Chatlist::try_load(&t, 0, Some("t-5678-b"), None)
627 .await
628 .unwrap();
629 assert_eq!(chats.len(), 1);
630 }
631
632 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
633 async fn test_search_single_chat() -> anyhow::Result<()> {
634 let t = TestContext::new_alice().await;
635
636 receive_imf(
638 &t,
639 b"From: Bob Authname <bob@example.org>\n\
640 To: alice@example.org\n\
641 Subject: foo\n\
642 Message-ID: <msg1234@example.org>\n\
643 Chat-Version: 1.0\n\
644 Date: Sun, 22 Mar 2021 22:37:57 +0000\n\
645 \n\
646 hello foo\n",
647 false,
648 )
649 .await?;
650
651 let chats = Chatlist::try_load(&t, 0, Some("Bob Authname"), None).await?;
652 assert_eq!(chats.len(), 1);
654
655 let msg = t.get_last_msg().await;
656 let chat_id = msg.get_chat_id();
657 chat_id.accept(&t).await.unwrap();
658
659 let contacts = get_chat_contacts(&t, chat_id).await?;
660 let contact_id = *contacts.first().unwrap();
661 let chat = Chat::load_from_db(&t, chat_id).await?;
662 assert_eq!(chat.get_name(), "Bob Authname");
663
664 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
666 assert_eq!(chats.len(), 1);
667 assert_eq!(chats.get_chat_id(0).unwrap(), chat_id);
668
669 let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
671 assert_eq!(contact_id, test_id);
672 let chat = Chat::load_from_db(&t, chat_id).await?;
673 assert_eq!(chat.get_name(), "Bob Nickname");
674 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
675 assert_eq!(chats.len(), 0);
676 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
677 assert_eq!(chats.len(), 1);
678
679 let test_id = Contact::create(&t, "", "bob@example.org").await?;
681 assert_eq!(contact_id, test_id);
682 let chat = Chat::load_from_db(&t, chat_id).await?;
683 assert_eq!(chat.get_name(), "Bob Authname");
684 let chats = Chatlist::try_load(&t, 0, Some("bob authname"), None).await?;
685 assert_eq!(chats.len(), 1);
686 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
687 assert_eq!(chats.len(), 0);
688
689 Ok(())
690 }
691
692 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
693 async fn test_search_single_chat_without_authname() -> anyhow::Result<()> {
694 let t = TestContext::new_alice().await;
695
696 receive_imf(
698 &t,
699 b"From: bob@example.org\n\
700 To: alice@example.org\n\
701 Subject: foo\n\
702 Message-ID: <msg5678@example.org>\n\
703 Chat-Version: 1.0\n\
704 Date: Sun, 22 Mar 2021 22:38:57 +0000\n\
705 \n\
706 hello foo\n",
707 false,
708 )
709 .await?;
710
711 let msg = t.get_last_msg().await;
712 let chat_id = msg.get_chat_id();
713 chat_id.accept(&t).await.unwrap();
714 let contacts = get_chat_contacts(&t, chat_id).await?;
715 let contact_id = *contacts.first().unwrap();
716 let chat = Chat::load_from_db(&t, chat_id).await?;
717 assert_eq!(chat.get_name(), "bob@example.org");
718
719 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
721 assert_eq!(chats.len(), 1);
722 assert_eq!(chats.get_chat_id(0)?, chat_id);
723
724 let test_id = Contact::create(&t, "Bob Nickname", "bob@example.org").await?;
726 assert_eq!(contact_id, test_id);
727 let chat = Chat::load_from_db(&t, chat_id).await?;
728 assert_eq!(chat.get_name(), "Bob Nickname");
729 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
730 assert_eq!(chats.len(), 0); let chats = Chatlist::try_load(&t, 0, Some("Bob Nickname"), None).await?;
732 assert_eq!(chats.len(), 1);
733 assert_eq!(chats.get_chat_id(0)?, chat_id);
734
735 let test_id = Contact::create(&t, "", "bob@example.org").await?;
737 assert_eq!(contact_id, test_id);
738 let chat = Chat::load_from_db(&t, chat_id).await?;
739 assert_eq!(chat.get_name(), "bob@example.org");
740 let chats = Chatlist::try_load(&t, 0, Some("bob@example.org"), None).await?;
741 assert_eq!(chats.len(), 1);
742 let chats = Chatlist::try_load(&t, 0, Some("bob nickname"), None).await?;
743 assert_eq!(chats.len(), 0);
744
745 let chats = Chatlist::try_load(&t, 0, Some("b@exa"), None).await?;
747 assert_eq!(chats.len(), 1);
748 let chats = Chatlist::try_load(&t, 0, Some("b@exac"), None).await?;
749 assert_eq!(chats.len(), 0);
750
751 Ok(())
752 }
753
754 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
755 async fn test_get_summary_unwrap() {
756 let t = TestContext::new().await;
757 let chat_id1 = create_group(&t, "a chat").await.unwrap();
758
759 let mut msg = Message::new_text("foo:\nbar \r\n test".to_string());
760 chat_id1.set_draft(&t, Some(&mut msg)).await.unwrap();
761
762 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
763 let summary = chats.get_summary(&t, 0, None).await.unwrap();
764 assert_eq!(summary.text, "foo: bar test"); }
766
767 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
770 async fn test_get_summary_deleted_draft() {
771 let t = TestContext::new().await;
772
773 let chat_id = create_group(&t, "a chat").await.unwrap();
774 let mut msg = Message::new_text("Foobar".to_string());
775 chat_id.set_draft(&t, Some(&mut msg)).await.unwrap();
776
777 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
778 chat_id.set_draft(&t, None).await.unwrap();
779
780 let summary_res = chats.get_summary(&t, 0, None).await;
781 assert!(summary_res.is_ok());
782 }
783
784 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
785 async fn test_get_summary_for_saved_messages() -> Result<()> {
786 let mut tcm = TestContextManager::new();
787 let alice = tcm.alice().await;
788 let bob = tcm.bob().await;
789 let chat_alice = alice.create_chat(&bob).await;
790
791 send_text_msg(&alice, chat_alice.id, "hi".into()).await?;
792 let sent1 = alice.pop_sent_msg().await;
793 save_msgs(&alice, &[sent1.sender_msg_id]).await?;
794 let chatlist = Chatlist::try_load(&alice, 0, None, None).await?;
795 let summary = chatlist.get_summary(&alice, 0, None).await?;
796 assert_eq!(summary.prefix.unwrap().to_string(), "Me");
797 assert_eq!(summary.text, "hi");
798
799 let msg = bob.recv_msg(&sent1).await;
800 save_msgs(&bob, &[msg.id]).await?;
801 let chatlist = Chatlist::try_load(&bob, 0, None, None).await?;
802 let summary = chatlist.get_summary(&bob, 0, None).await?;
803 assert_eq!(summary.prefix.unwrap().to_string(), "alice@example.org");
804 assert_eq!(summary.text, "hi");
805
806 Ok(())
807 }
808
809 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
810 async fn test_load_broken() {
811 let t = TestContext::new_bob().await;
812 let chat_id1 = create_group(&t, "a chat").await.unwrap();
813 create_group(&t, "b chat").await.unwrap();
814 create_group(&t, "c chat").await.unwrap();
815
816 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
818 assert_eq!(chats.len(), 3);
819
820 t.sql
822 .execute("UPDATE chats SET type=10 WHERE id=?", (chat_id1,))
823 .await
824 .unwrap();
825
826 assert!(Chat::load_from_db(&t, chat_id1).await.is_err());
828
829 let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
831
832 assert!(chats.get_summary(&t, 0, None).await.is_ok());
834 assert!(chats.get_summary(&t, 1, None).await.is_ok());
835 assert!(chats.get_summary(&t, 2, None).await.is_err());
836 assert_eq!(chats.get_index_for_id(chat_id1).unwrap(), 2);
837 }
838}