1use std::cmp;
4use std::collections::{HashMap, HashSet};
5use std::fmt;
6use std::io::Cursor;
7use std::marker::Sync;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10use std::time::Duration;
11
12use anyhow::{Context as _, Result, anyhow, bail, ensure};
13use chrono::TimeZone;
14use deltachat_contact_tools::{ContactAddress, sanitize_bidi_characters, sanitize_single_line};
15use mail_builder::mime::MimePart;
16use serde::{Deserialize, Serialize};
17use strum_macros::EnumIter;
18
19use crate::blob::BlobObject;
20use crate::chatlist::Chatlist;
21use crate::color::str_to_color;
22use crate::config::Config;
23use crate::constants::{
24 Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL,
25 DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, EDITED_PREFIX, TIMESTAMP_SENT_TOLERANCE,
26};
27use crate::contact::{self, Contact, ContactId, Origin};
28use crate::context::Context;
29use crate::debug_logging::maybe_set_logging_xdc;
30use crate::download::DownloadState;
31use crate::ephemeral::{Timer as EphemeralTimer, start_chat_ephemeral_timers};
32use crate::events::EventType;
33use crate::key::self_fingerprint;
34use crate::location;
35use crate::log::{LogExt, warn};
36use crate::logged_debug_assert;
37use crate::message::{self, Message, MessageState, MsgId, Viewtype};
38use crate::mimefactory::MimeFactory;
39use crate::mimeparser::SystemMessage;
40use crate::param::{Param, Params};
41use crate::receive_imf::ReceivedMsg;
42use crate::smtp::send_msg_to_smtp;
43use crate::stock_str;
44use crate::sync::{self, Sync::*, SyncData};
45use crate::tools::{
46 IsNoneOrEmpty, SystemTime, buf_compress, create_broadcast_secret, create_id,
47 create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path,
48 gm2local_offset, normalize_text, smeared_time, time, truncate_msg_text,
49};
50use crate::webxdc::StatusUpdateSerial;
51use crate::{chatlist_events, imap};
52
53pub(crate) const PARAM_BROADCAST_SECRET: Param = Param::Arg3;
54
55#[derive(Debug, Copy, Clone, PartialEq, Eq)]
57pub enum ChatItem {
58 Message {
60 msg_id: MsgId,
62 },
63
64 DayMarker {
67 timestamp: i64,
69 },
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub(crate) enum CantSendReason {
77 SpecialChat,
79
80 DeviceChat,
82
83 ContactRequest,
85
86 ReadOnlyMailingList,
88
89 InBroadcast,
91
92 NotAMember,
94
95 MissingKey,
97}
98
99impl fmt::Display for CantSendReason {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 match self {
102 Self::SpecialChat => write!(f, "the chat is a special chat"),
103 Self::DeviceChat => write!(f, "the chat is a device chat"),
104 Self::ContactRequest => write!(
105 f,
106 "contact request chat should be accepted before sending messages"
107 ),
108 Self::ReadOnlyMailingList => {
109 write!(f, "mailing list does not have a know post address")
110 }
111 Self::InBroadcast => {
112 write!(f, "Broadcast channel is read-only")
113 }
114 Self::NotAMember => write!(f, "not a member of the chat"),
115 Self::MissingKey => write!(f, "key is missing"),
116 }
117 }
118}
119
120#[derive(
125 Debug, Copy, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Hash, PartialOrd, Ord,
126)]
127pub struct ChatId(u32);
128
129impl ChatId {
130 pub const fn new(id: u32) -> ChatId {
132 ChatId(id)
133 }
134
135 pub fn is_unset(self) -> bool {
139 self.0 == 0
140 }
141
142 pub fn is_special(self) -> bool {
146 (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)
147 }
148
149 pub fn is_trash(self) -> bool {
156 self == DC_CHAT_ID_TRASH
157 }
158
159 pub fn is_archived_link(self) -> bool {
166 self == DC_CHAT_ID_ARCHIVED_LINK
167 }
168
169 pub fn is_alldone_hint(self) -> bool {
178 self == DC_CHAT_ID_ALLDONE_HINT
179 }
180
181 pub(crate) fn lookup_by_message(msg: &Message) -> Option<Self> {
183 if msg.chat_id == DC_CHAT_ID_TRASH {
184 return None;
185 }
186 if msg.download_state == DownloadState::Undecipherable {
187 return None;
188 }
189 Some(msg.chat_id)
190 }
191
192 pub async fn lookup_by_contact(
197 context: &Context,
198 contact_id: ContactId,
199 ) -> Result<Option<Self>> {
200 let Some(chat_id_blocked) = ChatIdBlocked::lookup_by_contact(context, contact_id).await?
201 else {
202 return Ok(None);
203 };
204
205 let chat_id = match chat_id_blocked.blocked {
206 Blocked::Not | Blocked::Request => Some(chat_id_blocked.id),
207 Blocked::Yes => None,
208 };
209 Ok(chat_id)
210 }
211
212 pub(crate) async fn get_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
220 ChatIdBlocked::get_for_contact(context, contact_id, Blocked::Not)
221 .await
222 .map(|chat| chat.id)
223 }
224
225 pub async fn create_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
230 ChatId::create_for_contact_with_blocked(context, contact_id, Blocked::Not).await
231 }
232
233 pub(crate) async fn create_for_contact_with_blocked(
237 context: &Context,
238 contact_id: ContactId,
239 create_blocked: Blocked,
240 ) -> Result<Self> {
241 let chat_id = match ChatIdBlocked::lookup_by_contact(context, contact_id).await? {
242 Some(chat) => {
243 if create_blocked != Blocked::Not || chat.blocked == Blocked::Not {
244 return Ok(chat.id);
245 }
246 chat.id.set_blocked(context, Blocked::Not).await?;
247 chat.id
248 }
249 None => {
250 if Contact::real_exists_by_id(context, contact_id).await?
251 || contact_id == ContactId::SELF
252 {
253 let chat_id =
254 ChatIdBlocked::get_for_contact(context, contact_id, create_blocked)
255 .await
256 .map(|chat| chat.id)?;
257 ContactId::scaleup_origin(context, &[contact_id], Origin::CreateChat).await?;
258 chat_id
259 } else {
260 warn!(
261 context,
262 "Cannot create chat, contact {contact_id} does not exist."
263 );
264 bail!("Can not create chat for non-existing contact");
265 }
266 }
267 };
268 context.emit_msgs_changed_without_ids();
269 chatlist_events::emit_chatlist_changed(context);
270 chatlist_events::emit_chatlist_item_changed(context, chat_id);
271 Ok(chat_id)
272 }
273
274 pub(crate) async fn create_multiuser_record(
277 context: &Context,
278 chattype: Chattype,
279 grpid: &str,
280 grpname: &str,
281 create_blocked: Blocked,
282 param: Option<String>,
283 timestamp: i64,
284 ) -> Result<Self> {
285 let grpname = sanitize_single_line(grpname);
286 let timestamp = cmp::min(timestamp, smeared_time(context));
287 let row_id =
288 context.sql.insert(
289 "INSERT INTO chats (type, name, name_normalized, grpid, blocked, created_timestamp, protected, param) VALUES(?, ?, ?, ?, ?, ?, 0, ?)",
290 (
291 chattype,
292 &grpname,
293 normalize_text(&grpname),
294 grpid,
295 create_blocked,
296 timestamp,
297 param.unwrap_or_default(),
298 ),
299 ).await?;
300
301 let chat_id = ChatId::new(u32::try_from(row_id)?);
302 let chat = Chat::load_from_db(context, chat_id).await?;
303
304 if chat.is_encrypted(context).await? {
305 chat_id.add_e2ee_notice(context, timestamp).await?;
306 }
307
308 info!(
309 context,
310 "Created group/broadcast '{}' grpid={} as {}, blocked={}.",
311 &grpname,
312 grpid,
313 chat_id,
314 create_blocked,
315 );
316
317 Ok(chat_id)
318 }
319
320 async fn set_selfavatar_timestamp(self, context: &Context, timestamp: i64) -> Result<()> {
321 context
322 .sql
323 .execute(
324 "UPDATE contacts
325 SET selfavatar_sent=?
326 WHERE id IN(SELECT contact_id FROM chats_contacts WHERE chat_id=? AND add_timestamp >= remove_timestamp)",
327 (timestamp, self),
328 )
329 .await?;
330 Ok(())
331 }
332
333 pub(crate) async fn set_blocked(self, context: &Context, new_blocked: Blocked) -> Result<bool> {
337 if self.is_special() {
338 bail!("ignoring setting of Block-status for {self}");
339 }
340 let count = context
341 .sql
342 .execute(
343 "UPDATE chats SET blocked=?1 WHERE id=?2 AND blocked != ?1",
344 (new_blocked, self),
345 )
346 .await?;
347 Ok(count > 0)
348 }
349
350 pub async fn block(self, context: &Context) -> Result<()> {
352 self.block_ex(context, Sync).await
353 }
354
355 pub(crate) async fn block_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
356 let chat = Chat::load_from_db(context, self).await?;
357 let mut delete = false;
358
359 match chat.typ {
360 Chattype::OutBroadcast => {
361 bail!("Can't block chat of type {:?}", chat.typ)
362 }
363 Chattype::Single => {
364 for contact_id in get_chat_contacts(context, self).await? {
365 if contact_id != ContactId::SELF {
366 info!(
367 context,
368 "Blocking the contact {contact_id} to block 1:1 chat."
369 );
370 contact::set_blocked(context, Nosync, contact_id, true).await?;
371 }
372 }
373 }
374 Chattype::Group => {
375 info!(context, "Can't block groups yet, deleting the chat.");
376 delete = true;
377 }
378 Chattype::Mailinglist | Chattype::InBroadcast => {
379 if self.set_blocked(context, Blocked::Yes).await? {
380 context.emit_event(EventType::ChatModified(self));
381 }
382 }
383 }
384 chatlist_events::emit_chatlist_changed(context);
385
386 if sync.into() {
387 chat.sync(context, SyncAction::Block)
389 .await
390 .log_err(context)
391 .ok();
392 }
393 if delete {
394 self.delete_ex(context, Nosync).await?;
395 }
396 Ok(())
397 }
398
399 pub async fn unblock(self, context: &Context) -> Result<()> {
401 self.unblock_ex(context, Sync).await
402 }
403
404 pub(crate) async fn unblock_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
405 self.set_blocked(context, Blocked::Not).await?;
406
407 chatlist_events::emit_chatlist_changed(context);
408
409 if sync.into() {
410 let chat = Chat::load_from_db(context, self).await?;
411 chat.sync(context, SyncAction::Unblock)
415 .await
416 .log_err(context)
417 .ok();
418 }
419
420 Ok(())
421 }
422
423 pub async fn accept(self, context: &Context) -> Result<()> {
427 self.accept_ex(context, Sync).await
428 }
429
430 pub(crate) async fn accept_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
431 let chat = Chat::load_from_db(context, self).await?;
432
433 match chat.typ {
434 Chattype::Single | Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast => {
435 let origin = match chat.typ {
441 Chattype::Group => Origin::IncomingTo,
442 _ => Origin::CreateChat,
443 };
444 for contact_id in get_chat_contacts(context, self).await? {
445 if contact_id != ContactId::SELF {
446 ContactId::scaleup_origin(context, &[contact_id], origin).await?;
447 }
448 }
449 }
450 Chattype::Mailinglist => {
451 }
453 }
454
455 if self.set_blocked(context, Blocked::Not).await? {
456 context.emit_event(EventType::ChatModified(self));
457 chatlist_events::emit_chatlist_item_changed(context, self);
458 }
459
460 if sync.into() {
461 chat.sync(context, SyncAction::Accept)
462 .await
463 .log_err(context)
464 .ok();
465 }
466 Ok(())
467 }
468
469 pub(crate) async fn add_e2ee_notice(self, context: &Context, timestamp: i64) -> Result<()> {
471 let text = stock_str::messages_e2e_encrypted(context).await;
472 add_info_msg_with_cmd(
473 context,
474 self,
475 &text,
476 SystemMessage::ChatE2ee,
477 Some(timestamp),
478 timestamp,
479 None,
480 None,
481 None,
482 )
483 .await?;
484 Ok(())
485 }
486
487 pub async fn set_visibility(self, context: &Context, visibility: ChatVisibility) -> Result<()> {
489 self.set_visibility_ex(context, Sync, visibility).await
490 }
491
492 pub(crate) async fn set_visibility_ex(
493 self,
494 context: &Context,
495 sync: sync::Sync,
496 visibility: ChatVisibility,
497 ) -> Result<()> {
498 ensure!(
499 !self.is_special(),
500 "bad chat_id, can not be special chat: {self}"
501 );
502
503 context
504 .sql
505 .transaction(move |transaction| {
506 if visibility == ChatVisibility::Archived {
507 transaction.execute(
508 "UPDATE msgs SET state=? WHERE chat_id=? AND state=?;",
509 (MessageState::InNoticed, self, MessageState::InFresh),
510 )?;
511 }
512 transaction.execute(
513 "UPDATE chats SET archived=? WHERE id=?;",
514 (visibility, self),
515 )?;
516 Ok(())
517 })
518 .await?;
519
520 if visibility == ChatVisibility::Archived {
521 start_chat_ephemeral_timers(context, self).await?;
522 }
523
524 context.emit_msgs_changed_without_ids();
525 chatlist_events::emit_chatlist_changed(context);
526 chatlist_events::emit_chatlist_item_changed(context, self);
527
528 if sync.into() {
529 let chat = Chat::load_from_db(context, self).await?;
530 chat.sync(context, SyncAction::SetVisibility(visibility))
531 .await
532 .log_err(context)
533 .ok();
534 }
535 Ok(())
536 }
537
538 pub async fn unarchive_if_not_muted(
546 self,
547 context: &Context,
548 msg_state: MessageState,
549 ) -> Result<()> {
550 if msg_state != MessageState::InFresh {
551 context
552 .sql
553 .execute(
554 "UPDATE chats SET archived=0 WHERE id=? AND archived=1 \
555 AND NOT(muted_until=-1 OR muted_until>?)",
556 (self, time()),
557 )
558 .await?;
559 return Ok(());
560 }
561 let chat = Chat::load_from_db(context, self).await?;
562 if chat.visibility != ChatVisibility::Archived {
563 return Ok(());
564 }
565 if chat.is_muted() {
566 let unread_cnt = context
567 .sql
568 .count(
569 "SELECT COUNT(*)
570 FROM msgs
571 WHERE state=?
572 AND hidden=0
573 AND chat_id=?",
574 (MessageState::InFresh, self),
575 )
576 .await?;
577 if unread_cnt == 1 {
578 context.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
580 }
581 return Ok(());
582 }
583 context
584 .sql
585 .execute("UPDATE chats SET archived=0 WHERE id=?", (self,))
586 .await?;
587 Ok(())
588 }
589
590 pub(crate) fn emit_msg_event(self, context: &Context, msg_id: MsgId, important: bool) {
593 if important {
594 debug_assert!(!msg_id.is_unset());
595
596 context.emit_incoming_msg(self, msg_id);
597 } else {
598 context.emit_msgs_changed(self, msg_id);
599 }
600 }
601
602 pub async fn delete(self, context: &Context) -> Result<()> {
608 self.delete_ex(context, Sync).await
609 }
610
611 pub(crate) async fn delete_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
612 ensure!(
613 !self.is_special(),
614 "bad chat_id, can not be a special chat: {self}"
615 );
616
617 let chat = Chat::load_from_db(context, self).await?;
618 let delete_msgs_target = context.get_delete_msgs_target().await?;
619 let sync_id = match sync {
620 Nosync => None,
621 Sync => chat.get_sync_id(context).await?,
622 };
623
624 context
625 .sql
626 .transaction(|transaction| {
627 transaction.execute(
628 "UPDATE imap SET target=? WHERE rfc724_mid IN (SELECT rfc724_mid FROM msgs WHERE chat_id=?)",
629 (delete_msgs_target, self,),
630 )?;
631 transaction.execute(
632 "DELETE FROM smtp WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?)",
633 (self,),
634 )?;
635 transaction.execute(
636 "DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?)",
637 (self,),
638 )?;
639 transaction.execute("DELETE FROM msgs WHERE chat_id=?", (self,))?;
640 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (self,))?;
641 transaction.execute("DELETE FROM chats WHERE id=?", (self,))?;
642 Ok(())
643 })
644 .await?;
645
646 context.emit_event(EventType::ChatDeleted { chat_id: self });
647 context.emit_msgs_changed_without_ids();
648
649 if let Some(id) = sync_id {
650 self::sync(context, id, SyncAction::Delete)
651 .await
652 .log_err(context)
653 .ok();
654 }
655
656 if chat.is_self_talk() {
657 let mut msg = Message::new_text(stock_str::self_deleted_msg_body(context).await);
658 add_device_msg(context, None, Some(&mut msg)).await?;
659 }
660 chatlist_events::emit_chatlist_changed(context);
661
662 context
663 .set_config_internal(Config::LastHousekeeping, None)
664 .await?;
665 context.scheduler.interrupt_smtp().await;
666
667 Ok(())
668 }
669
670 pub async fn set_draft(self, context: &Context, mut msg: Option<&mut Message>) -> Result<()> {
674 if self.is_special() {
675 return Ok(());
676 }
677
678 let changed = match &mut msg {
679 None => self.maybe_delete_draft(context).await?,
680 Some(msg) => self.do_set_draft(context, msg).await?,
681 };
682
683 if changed {
684 if msg.is_some() {
685 match self.get_draft_msg_id(context).await? {
686 Some(msg_id) => context.emit_msgs_changed(self, msg_id),
687 None => context.emit_msgs_changed_without_msg_id(self),
688 }
689 } else {
690 context.emit_msgs_changed_without_msg_id(self)
691 }
692 }
693
694 Ok(())
695 }
696
697 async fn get_draft_msg_id(self, context: &Context) -> Result<Option<MsgId>> {
699 let msg_id: Option<MsgId> = context
700 .sql
701 .query_get_value(
702 "SELECT id FROM msgs WHERE chat_id=? AND state=?;",
703 (self, MessageState::OutDraft),
704 )
705 .await?;
706 Ok(msg_id)
707 }
708
709 pub async fn get_draft(self, context: &Context) -> Result<Option<Message>> {
711 if self.is_special() {
712 return Ok(None);
713 }
714 match self.get_draft_msg_id(context).await? {
715 Some(draft_msg_id) => {
716 let msg = Message::load_from_db(context, draft_msg_id).await?;
717 Ok(Some(msg))
718 }
719 None => Ok(None),
720 }
721 }
722
723 async fn maybe_delete_draft(self, context: &Context) -> Result<bool> {
727 Ok(context
728 .sql
729 .execute(
730 "DELETE FROM msgs WHERE chat_id=? AND state=?",
731 (self, MessageState::OutDraft),
732 )
733 .await?
734 > 0)
735 }
736
737 async fn do_set_draft(self, context: &Context, msg: &mut Message) -> Result<bool> {
740 match msg.viewtype {
741 Viewtype::Unknown => bail!("Can not set draft of unknown type."),
742 Viewtype::Text => {
743 if msg.text.is_empty() && msg.in_reply_to.is_none_or_empty() {
744 bail!("No text and no quote in draft");
745 }
746 }
747 _ => {
748 if msg.viewtype == Viewtype::File
749 && let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg)
750 .filter(|&(vt, _)| vt == Viewtype::Webxdc || vt == Viewtype::Vcard)
755 {
756 msg.viewtype = better_type;
757 }
758 if msg.viewtype == Viewtype::Vcard {
759 let blob = msg
760 .param
761 .get_file_blob(context)?
762 .context("no file stored in params")?;
763 msg.try_set_vcard(context, &blob.to_abs_path()).await?;
764 }
765 }
766 }
767
768 msg.state = MessageState::OutDraft;
771 msg.chat_id = self;
772
773 if !msg.id.is_special()
775 && let Some(old_draft) = self.get_draft(context).await?
776 && old_draft.id == msg.id
777 && old_draft.chat_id == self
778 && old_draft.state == MessageState::OutDraft
779 {
780 let affected_rows = context
781 .sql.execute(
782 "UPDATE msgs
783 SET timestamp=?1,type=?2,txt=?3,txt_normalized=?4,param=?5,mime_in_reply_to=?6
784 WHERE id=?7
785 AND (type <> ?2
786 OR txt <> ?3
787 OR txt_normalized <> ?4
788 OR param <> ?5
789 OR mime_in_reply_to <> ?6);",
790 (
791 time(),
792 msg.viewtype,
793 &msg.text,
794 normalize_text(&msg.text),
795 msg.param.to_string(),
796 msg.in_reply_to.as_deref().unwrap_or_default(),
797 msg.id,
798 ),
799 ).await?;
800 return Ok(affected_rows > 0);
801 }
802
803 let row_id = context
804 .sql
805 .transaction(|transaction| {
806 transaction.execute(
808 "DELETE FROM msgs WHERE chat_id=? AND state=?",
809 (self, MessageState::OutDraft),
810 )?;
811
812 transaction.execute(
814 "INSERT INTO msgs (
815 chat_id,
816 rfc724_mid,
817 from_id,
818 timestamp,
819 type,
820 state,
821 txt,
822 txt_normalized,
823 param,
824 hidden,
825 mime_in_reply_to)
826 VALUES (?,?,?,?,?,?,?,?,?,?,?);",
827 (
828 self,
829 &msg.rfc724_mid,
830 ContactId::SELF,
831 time(),
832 msg.viewtype,
833 MessageState::OutDraft,
834 &msg.text,
835 normalize_text(&msg.text),
836 msg.param.to_string(),
837 1,
838 msg.in_reply_to.as_deref().unwrap_or_default(),
839 ),
840 )?;
841
842 Ok(transaction.last_insert_rowid())
843 })
844 .await?;
845 msg.id = MsgId::new(row_id.try_into()?);
846 Ok(true)
847 }
848
849 pub async fn get_msg_cnt(self, context: &Context) -> Result<usize> {
851 let count = context
852 .sql
853 .count(
854 "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id=?",
855 (self,),
856 )
857 .await?;
858 Ok(count)
859 }
860
861 pub async fn get_fresh_msg_cnt(self, context: &Context) -> Result<usize> {
863 let count = if self.is_archived_link() {
874 context
875 .sql
876 .count(
877 "SELECT COUNT(DISTINCT(m.chat_id))
878 FROM msgs m
879 LEFT JOIN chats c ON m.chat_id=c.id
880 WHERE m.state=10
881 and m.hidden=0
882 AND m.chat_id>9
883 AND c.blocked=0
884 AND c.archived=1
885 ",
886 (),
887 )
888 .await?
889 } else {
890 context
891 .sql
892 .count(
893 "SELECT COUNT(*)
894 FROM msgs
895 WHERE state=?
896 AND hidden=0
897 AND chat_id=?;",
898 (MessageState::InFresh, self),
899 )
900 .await?
901 };
902 Ok(count)
903 }
904
905 pub(crate) async fn created_timestamp(self, context: &Context) -> Result<i64> {
906 Ok(context
907 .sql
908 .query_get_value("SELECT created_timestamp FROM chats WHERE id=?", (self,))
909 .await?
910 .unwrap_or(0))
911 }
912
913 pub(crate) async fn get_timestamp(self, context: &Context) -> Result<Option<i64>> {
916 let timestamp = context
917 .sql
918 .query_get_value(
919 "SELECT MAX(timestamp)
920 FROM msgs
921 WHERE chat_id=?
922 HAVING COUNT(*) > 0",
923 (self,),
924 )
925 .await?;
926 Ok(timestamp)
927 }
928
929 pub async fn get_similar_chat_ids(self, context: &Context) -> Result<Vec<(ChatId, f64)>> {
935 let intersection = context
937 .sql
938 .query_map_vec(
939 "SELECT y.chat_id, SUM(x.contact_id = y.contact_id)
940 FROM chats_contacts as x
941 JOIN chats_contacts as y
942 WHERE x.contact_id > 9
943 AND y.contact_id > 9
944 AND x.add_timestamp >= x.remove_timestamp
945 AND y.add_timestamp >= y.remove_timestamp
946 AND x.chat_id=?
947 AND y.chat_id<>x.chat_id
948 AND y.chat_id>?
949 GROUP BY y.chat_id",
950 (self, DC_CHAT_ID_LAST_SPECIAL),
951 |row| {
952 let chat_id: ChatId = row.get(0)?;
953 let intersection: f64 = row.get(1)?;
954 Ok((chat_id, intersection))
955 },
956 )
957 .await
958 .context("failed to calculate member set intersections")?;
959
960 let chat_size: HashMap<ChatId, f64> = context
961 .sql
962 .query_map_collect(
963 "SELECT chat_id, count(*) AS n
964 FROM chats_contacts
965 WHERE contact_id > ? AND chat_id > ?
966 AND add_timestamp >= remove_timestamp
967 GROUP BY chat_id",
968 (ContactId::LAST_SPECIAL, DC_CHAT_ID_LAST_SPECIAL),
969 |row| {
970 let chat_id: ChatId = row.get(0)?;
971 let size: f64 = row.get(1)?;
972 Ok((chat_id, size))
973 },
974 )
975 .await
976 .context("failed to count chat member sizes")?;
977
978 let our_chat_size = chat_size.get(&self).copied().unwrap_or_default();
979 let mut chats_with_metrics = Vec::new();
980 for (chat_id, intersection_size) in intersection {
981 if intersection_size > 0.0 {
982 let other_chat_size = chat_size.get(&chat_id).copied().unwrap_or_default();
983 let union_size = our_chat_size + other_chat_size - intersection_size;
984 let metric = intersection_size / union_size;
985 chats_with_metrics.push((chat_id, metric))
986 }
987 }
988 chats_with_metrics.sort_unstable_by(|(chat_id1, metric1), (chat_id2, metric2)| {
989 metric2
990 .partial_cmp(metric1)
991 .unwrap_or(chat_id2.cmp(chat_id1))
992 });
993
994 let mut res = Vec::new();
996 let now = time();
997 for (chat_id, metric) in chats_with_metrics {
998 if let Some(chat_timestamp) = chat_id.get_timestamp(context).await?
999 && now > chat_timestamp + 42 * 24 * 3600
1000 {
1001 continue;
1003 }
1004
1005 if metric < 0.1 {
1006 break;
1008 }
1009
1010 let chat = Chat::load_from_db(context, chat_id).await?;
1011 if chat.typ != Chattype::Group {
1012 continue;
1013 }
1014
1015 match chat.visibility {
1016 ChatVisibility::Normal | ChatVisibility::Pinned => {}
1017 ChatVisibility::Archived => continue,
1018 }
1019
1020 res.push((chat_id, metric));
1021 if res.len() >= 5 {
1022 break;
1023 }
1024 }
1025
1026 Ok(res)
1027 }
1028
1029 pub async fn get_similar_chatlist(self, context: &Context) -> Result<Chatlist> {
1033 let chat_ids: Vec<ChatId> = self
1034 .get_similar_chat_ids(context)
1035 .await
1036 .context("failed to get similar chat IDs")?
1037 .into_iter()
1038 .map(|(chat_id, _metric)| chat_id)
1039 .collect();
1040 let chatlist = Chatlist::from_chat_ids(context, &chat_ids).await?;
1041 Ok(chatlist)
1042 }
1043
1044 pub(crate) async fn get_param(self, context: &Context) -> Result<Params> {
1045 let res: Option<String> = context
1046 .sql
1047 .query_get_value("SELECT param FROM chats WHERE id=?", (self,))
1048 .await?;
1049 Ok(res
1050 .map(|s| s.parse().unwrap_or_default())
1051 .unwrap_or_default())
1052 }
1053
1054 pub(crate) async fn is_unpromoted(self, context: &Context) -> Result<bool> {
1056 let param = self.get_param(context).await?;
1057 let unpromoted = param.get_bool(Param::Unpromoted).unwrap_or_default();
1058 Ok(unpromoted)
1059 }
1060
1061 pub(crate) async fn is_promoted(self, context: &Context) -> Result<bool> {
1063 let promoted = !self.is_unpromoted(context).await?;
1064 Ok(promoted)
1065 }
1066
1067 pub async fn is_self_talk(self, context: &Context) -> Result<bool> {
1069 Ok(self.get_param(context).await?.exists(Param::Selftalk))
1070 }
1071
1072 pub async fn is_device_talk(self, context: &Context) -> Result<bool> {
1074 Ok(self.get_param(context).await?.exists(Param::Devicetalk))
1075 }
1076
1077 async fn parent_query<T, F>(
1078 self,
1079 context: &Context,
1080 fields: &str,
1081 state_out_min: MessageState,
1082 f: F,
1083 ) -> Result<Option<T>>
1084 where
1085 F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
1086 T: Send + 'static,
1087 {
1088 let sql = &context.sql;
1089 let query = format!(
1090 "SELECT {fields} \
1091 FROM msgs \
1092 WHERE chat_id=? \
1093 AND ((state BETWEEN {} AND {}) OR (state >= {})) \
1094 AND NOT hidden \
1095 AND download_state={} \
1096 AND from_id != {} \
1097 ORDER BY timestamp DESC, id DESC \
1098 LIMIT 1;",
1099 MessageState::InFresh as u32,
1100 MessageState::InSeen as u32,
1101 state_out_min as u32,
1102 DownloadState::Done as u32,
1105 ContactId::INFO.to_u32(),
1108 );
1109 sql.query_row_optional(&query, (self,), f).await
1110 }
1111
1112 async fn get_parent_mime_headers(
1113 self,
1114 context: &Context,
1115 state_out_min: MessageState,
1116 ) -> Result<Option<(String, String, String)>> {
1117 self.parent_query(
1118 context,
1119 "rfc724_mid, mime_in_reply_to, IFNULL(mime_references, '')",
1120 state_out_min,
1121 |row: &rusqlite::Row| {
1122 let rfc724_mid: String = row.get(0)?;
1123 let mime_in_reply_to: String = row.get(1)?;
1124 let mime_references: String = row.get(2)?;
1125 Ok((rfc724_mid, mime_in_reply_to, mime_references))
1126 },
1127 )
1128 .await
1129 }
1130
1131 pub async fn get_encryption_info(self, context: &Context) -> Result<String> {
1139 let chat = Chat::load_from_db(context, self).await?;
1140 if !chat.is_encrypted(context).await? {
1141 return Ok(stock_str::encr_none(context).await);
1142 }
1143
1144 let mut ret = stock_str::e2e_available(context).await + "\n";
1145
1146 for &contact_id in get_chat_contacts(context, self)
1147 .await?
1148 .iter()
1149 .filter(|&contact_id| !contact_id.is_special())
1150 {
1151 let contact = Contact::get_by_id(context, contact_id).await?;
1152 let addr = contact.get_addr();
1153 logged_debug_assert!(
1154 context,
1155 contact.is_key_contact(),
1156 "get_encryption_info: contact {contact_id} is not a key-contact."
1157 );
1158 let fingerprint = contact
1159 .fingerprint()
1160 .context("Contact does not have a fingerprint in encrypted chat")?;
1161 if contact.public_key(context).await?.is_some() {
1162 ret += &format!("\n{addr}\n{fingerprint}\n");
1163 } else {
1164 ret += &format!("\n{addr}\n(key missing)\n{fingerprint}\n");
1165 }
1166 }
1167
1168 Ok(ret.trim().to_string())
1169 }
1170
1171 pub fn to_u32(self) -> u32 {
1176 self.0
1177 }
1178
1179 pub(crate) async fn reset_gossiped_timestamp(self, context: &Context) -> Result<()> {
1180 context
1181 .sql
1182 .execute("DELETE FROM gossip_timestamp WHERE chat_id=?", (self,))
1183 .await?;
1184 Ok(())
1185 }
1186
1187 pub(crate) async fn calc_sort_timestamp(
1196 self,
1197 context: &Context,
1198 message_timestamp: i64,
1199 always_sort_to_bottom: bool,
1200 received: bool,
1201 incoming: bool,
1202 ) -> Result<i64> {
1203 let mut sort_timestamp = cmp::min(message_timestamp, smeared_time(context));
1204
1205 let last_msg_time: Option<i64> = if always_sort_to_bottom {
1206 context
1212 .sql
1213 .query_get_value(
1214 "SELECT MAX(timestamp)
1215 FROM msgs
1216 WHERE chat_id=? AND state!=?
1217 HAVING COUNT(*) > 0",
1218 (self, MessageState::OutDraft),
1219 )
1220 .await?
1221 } else if received {
1222 context
1233 .sql
1234 .query_row_optional(
1235 "SELECT MAX(timestamp), MAX(IIF(state=?,timestamp_sent,0))
1236 FROM msgs
1237 WHERE chat_id=? AND hidden=0 AND state>?
1238 HAVING COUNT(*) > 0",
1239 (MessageState::InSeen, self, MessageState::InFresh),
1240 |row| {
1241 let ts: i64 = row.get(0)?;
1242 let ts_sent_seen: i64 = row.get(1)?;
1243 Ok((ts, ts_sent_seen))
1244 },
1245 )
1246 .await?
1247 .and_then(|(ts, ts_sent_seen)| {
1248 match incoming || ts_sent_seen <= message_timestamp {
1249 true => Some(ts),
1250 false => None,
1251 }
1252 })
1253 } else {
1254 None
1255 };
1256
1257 if let Some(last_msg_time) = last_msg_time
1258 && last_msg_time > sort_timestamp
1259 {
1260 sort_timestamp = last_msg_time;
1261 }
1262
1263 Ok(sort_timestamp)
1264 }
1265}
1266
1267impl std::fmt::Display for ChatId {
1268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1269 if self.is_trash() {
1270 write!(f, "Chat#Trash")
1271 } else if self.is_archived_link() {
1272 write!(f, "Chat#ArchivedLink")
1273 } else if self.is_alldone_hint() {
1274 write!(f, "Chat#AlldoneHint")
1275 } else if self.is_special() {
1276 write!(f, "Chat#Special{}", self.0)
1277 } else {
1278 write!(f, "Chat#{}", self.0)
1279 }
1280 }
1281}
1282
1283impl rusqlite::types::ToSql for ChatId {
1288 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
1289 let val = rusqlite::types::Value::Integer(i64::from(self.0));
1290 let out = rusqlite::types::ToSqlOutput::Owned(val);
1291 Ok(out)
1292 }
1293}
1294
1295impl rusqlite::types::FromSql for ChatId {
1297 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
1298 i64::column_result(value).and_then(|val| {
1299 if 0 <= val && val <= i64::from(u32::MAX) {
1300 Ok(ChatId::new(val as u32))
1301 } else {
1302 Err(rusqlite::types::FromSqlError::OutOfRange(val))
1303 }
1304 })
1305 }
1306}
1307
1308#[derive(Debug, Clone, Deserialize, Serialize)]
1313pub struct Chat {
1314 pub id: ChatId,
1316
1317 pub typ: Chattype,
1319
1320 pub name: String,
1322
1323 pub visibility: ChatVisibility,
1325
1326 pub grpid: String,
1329
1330 pub blocked: Blocked,
1332
1333 pub param: Params,
1335
1336 is_sending_locations: bool,
1338
1339 pub mute_duration: MuteDuration,
1341}
1342
1343impl Chat {
1344 pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> {
1346 let mut chat = context
1347 .sql
1348 .query_row(
1349 "SELECT c.type, c.name, c.grpid, c.param, c.archived,
1350 c.blocked, c.locations_send_until, c.muted_until
1351 FROM chats c
1352 WHERE c.id=?;",
1353 (chat_id,),
1354 |row| {
1355 let c = Chat {
1356 id: chat_id,
1357 typ: row.get(0)?,
1358 name: row.get::<_, String>(1)?,
1359 grpid: row.get::<_, String>(2)?,
1360 param: row.get::<_, String>(3)?.parse().unwrap_or_default(),
1361 visibility: row.get(4)?,
1362 blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
1363 is_sending_locations: row.get(6)?,
1364 mute_duration: row.get(7)?,
1365 };
1366 Ok(c)
1367 },
1368 )
1369 .await
1370 .context(format!("Failed loading chat {chat_id} from database"))?;
1371
1372 if chat.id.is_archived_link() {
1373 chat.name = stock_str::archived_chats(context).await;
1374 } else {
1375 if chat.typ == Chattype::Single && chat.name.is_empty() {
1376 let mut chat_name = "Err [Name not found]".to_owned();
1379 match get_chat_contacts(context, chat.id).await {
1380 Ok(contacts) => {
1381 if let Some(contact_id) = contacts.first()
1382 && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1383 {
1384 contact.get_display_name().clone_into(&mut chat_name);
1385 }
1386 }
1387 Err(err) => {
1388 error!(
1389 context,
1390 "Failed to load contacts for {}: {:#}.", chat.id, err
1391 );
1392 }
1393 }
1394 chat.name = chat_name;
1395 }
1396 if chat.param.exists(Param::Selftalk) {
1397 chat.name = stock_str::saved_messages(context).await;
1398 } else if chat.param.exists(Param::Devicetalk) {
1399 chat.name = stock_str::device_messages(context).await;
1400 }
1401 }
1402
1403 Ok(chat)
1404 }
1405
1406 pub fn is_self_talk(&self) -> bool {
1408 self.param.exists(Param::Selftalk)
1409 }
1410
1411 pub fn is_device_talk(&self) -> bool {
1413 self.param.exists(Param::Devicetalk)
1414 }
1415
1416 pub fn is_mailing_list(&self) -> bool {
1418 self.typ == Chattype::Mailinglist
1419 }
1420
1421 pub(crate) async fn why_cant_send(&self, context: &Context) -> Result<Option<CantSendReason>> {
1425 self.why_cant_send_ex(context, &|_| false).await
1426 }
1427
1428 pub(crate) async fn why_cant_send_ex(
1429 &self,
1430 context: &Context,
1431 skip_fn: &(dyn Send + Sync + Fn(&CantSendReason) -> bool),
1432 ) -> Result<Option<CantSendReason>> {
1433 use CantSendReason::*;
1434 if self.id.is_special() {
1437 let reason = SpecialChat;
1438 if !skip_fn(&reason) {
1439 return Ok(Some(reason));
1440 }
1441 }
1442 if self.is_device_talk() {
1443 let reason = DeviceChat;
1444 if !skip_fn(&reason) {
1445 return Ok(Some(reason));
1446 }
1447 }
1448 if self.is_contact_request() {
1449 let reason = ContactRequest;
1450 if !skip_fn(&reason) {
1451 return Ok(Some(reason));
1452 }
1453 }
1454 if self.is_mailing_list() && self.get_mailinglist_addr().is_none_or_empty() {
1455 let reason = ReadOnlyMailingList;
1456 if !skip_fn(&reason) {
1457 return Ok(Some(reason));
1458 }
1459 }
1460 if self.typ == Chattype::InBroadcast {
1461 let reason = InBroadcast;
1462 if !skip_fn(&reason) {
1463 return Ok(Some(reason));
1464 }
1465 }
1466
1467 let reason = NotAMember;
1469 if !skip_fn(&reason) && !self.is_self_in_chat(context).await? {
1470 return Ok(Some(reason));
1471 }
1472
1473 let reason = MissingKey;
1474 if !skip_fn(&reason) && self.typ == Chattype::Single {
1475 let contact_ids = get_chat_contacts(context, self.id).await?;
1476 if let Some(contact_id) = contact_ids.first() {
1477 let contact = Contact::get_by_id(context, *contact_id).await?;
1478 if contact.is_key_contact() && contact.public_key(context).await?.is_none() {
1479 return Ok(Some(reason));
1480 }
1481 }
1482 }
1483
1484 Ok(None)
1485 }
1486
1487 pub async fn can_send(&self, context: &Context) -> Result<bool> {
1491 Ok(self.why_cant_send(context).await?.is_none())
1492 }
1493
1494 pub async fn is_self_in_chat(&self, context: &Context) -> Result<bool> {
1498 match self.typ {
1499 Chattype::Single | Chattype::OutBroadcast | Chattype::Mailinglist => Ok(true),
1500 Chattype::Group | Chattype::InBroadcast => {
1501 is_contact_in_chat(context, self.id, ContactId::SELF).await
1502 }
1503 }
1504 }
1505
1506 pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {
1507 context
1508 .sql
1509 .execute(
1510 "UPDATE chats SET param=? WHERE id=?",
1511 (self.param.to_string(), self.id),
1512 )
1513 .await?;
1514 Ok(())
1515 }
1516
1517 pub fn get_id(&self) -> ChatId {
1519 self.id
1520 }
1521
1522 pub fn get_type(&self) -> Chattype {
1524 self.typ
1525 }
1526
1527 pub fn get_name(&self) -> &str {
1529 &self.name
1530 }
1531
1532 pub fn get_mailinglist_addr(&self) -> Option<&str> {
1534 self.param.get(Param::ListPost)
1535 }
1536
1537 pub async fn get_profile_image(&self, context: &Context) -> Result<Option<PathBuf>> {
1539 if self.id.is_archived_link() {
1540 return Ok(Some(get_archive_icon(context).await?));
1543 } else if self.is_device_talk() {
1544 return Ok(Some(get_device_icon(context).await?));
1545 } else if self.is_self_talk() {
1546 return Ok(Some(get_saved_messages_icon(context).await?));
1547 } else if !self.is_encrypted(context).await? {
1548 return Ok(Some(get_abs_path(
1550 context,
1551 Path::new(&get_unencrypted_icon(context).await?),
1552 )));
1553 } else if self.typ == Chattype::Single {
1554 let contacts = get_chat_contacts(context, self.id).await?;
1558 if let Some(contact_id) = contacts.first() {
1559 let contact = Contact::get_by_id(context, *contact_id).await?;
1560 return contact.get_profile_image(context).await;
1561 }
1562 } else if let Some(image_rel) = self.param.get(Param::ProfileImage) {
1563 if !image_rel.is_empty() {
1565 return Ok(Some(get_abs_path(context, Path::new(&image_rel))));
1566 }
1567 }
1568 Ok(None)
1569 }
1570
1571 pub async fn get_color(&self, context: &Context) -> Result<u32> {
1577 let mut color = 0;
1578
1579 if self.typ == Chattype::Single {
1580 let contacts = get_chat_contacts(context, self.id).await?;
1581 if let Some(contact_id) = contacts.first()
1582 && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1583 {
1584 color = contact.get_color();
1585 }
1586 } else if !self.grpid.is_empty() {
1587 color = str_to_color(&self.grpid);
1588 } else {
1589 color = str_to_color(&self.name);
1590 }
1591
1592 Ok(color)
1593 }
1594
1595 pub async fn get_info(&self, context: &Context) -> Result<ChatInfo> {
1600 let draft = match self.id.get_draft(context).await? {
1601 Some(message) => message.text,
1602 _ => String::new(),
1603 };
1604 Ok(ChatInfo {
1605 id: self.id,
1606 type_: self.typ as u32,
1607 name: self.name.clone(),
1608 archived: self.visibility == ChatVisibility::Archived,
1609 param: self.param.to_string(),
1610 is_sending_locations: self.is_sending_locations,
1611 color: self.get_color(context).await?,
1612 profile_image: self
1613 .get_profile_image(context)
1614 .await?
1615 .unwrap_or_else(std::path::PathBuf::new),
1616 draft,
1617 is_muted: self.is_muted(),
1618 ephemeral_timer: self.id.get_ephemeral_timer(context).await?,
1619 })
1620 }
1621
1622 pub fn get_visibility(&self) -> ChatVisibility {
1624 self.visibility
1625 }
1626
1627 pub fn is_contact_request(&self) -> bool {
1632 self.blocked == Blocked::Request
1633 }
1634
1635 pub fn is_unpromoted(&self) -> bool {
1637 self.param.get_bool(Param::Unpromoted).unwrap_or_default()
1638 }
1639
1640 pub fn is_promoted(&self) -> bool {
1643 !self.is_unpromoted()
1644 }
1645
1646 pub async fn is_encrypted(&self, context: &Context) -> Result<bool> {
1648 let is_encrypted = self.is_self_talk()
1649 || match self.typ {
1650 Chattype::Single => {
1651 match context
1652 .sql
1653 .query_row_optional(
1654 "SELECT cc.contact_id, c.fingerprint<>''
1655 FROM chats_contacts cc LEFT JOIN contacts c
1656 ON c.id=cc.contact_id
1657 WHERE cc.chat_id=?
1658 ",
1659 (self.id,),
1660 |row| {
1661 let id: ContactId = row.get(0)?;
1662 let is_key: bool = row.get(1)?;
1663 Ok((id, is_key))
1664 },
1665 )
1666 .await?
1667 {
1668 Some((id, is_key)) => is_key || id == ContactId::DEVICE,
1669 None => true,
1670 }
1671 }
1672 Chattype::Group => {
1673 !self.grpid.is_empty()
1675 }
1676 Chattype::Mailinglist => false,
1677 Chattype::OutBroadcast | Chattype::InBroadcast => true,
1678 };
1679 Ok(is_encrypted)
1680 }
1681
1682 pub fn is_sending_locations(&self) -> bool {
1684 self.is_sending_locations
1685 }
1686
1687 pub fn is_muted(&self) -> bool {
1689 match self.mute_duration {
1690 MuteDuration::NotMuted => false,
1691 MuteDuration::Forever => true,
1692 MuteDuration::Until(when) => when > SystemTime::now(),
1693 }
1694 }
1695
1696 pub(crate) async fn member_list_timestamp(&self, context: &Context) -> Result<i64> {
1698 if let Some(member_list_timestamp) = self.param.get_i64(Param::MemberListTimestamp) {
1699 Ok(member_list_timestamp)
1700 } else {
1701 Ok(self.id.created_timestamp(context).await?)
1702 }
1703 }
1704
1705 pub(crate) async fn member_list_is_stale(&self, context: &Context) -> Result<bool> {
1711 let now = time();
1712 let member_list_ts = self.member_list_timestamp(context).await?;
1713 let is_stale = now.saturating_add(TIMESTAMP_SENT_TOLERANCE)
1714 >= member_list_ts.saturating_add(60 * 24 * 3600);
1715 Ok(is_stale)
1716 }
1717
1718 async fn prepare_msg_raw(
1724 &mut self,
1725 context: &Context,
1726 msg: &mut Message,
1727 update_msg_id: Option<MsgId>,
1728 ) -> Result<()> {
1729 let mut to_id = 0;
1730 let mut location_id = 0;
1731
1732 if msg.rfc724_mid.is_empty() {
1733 msg.rfc724_mid = create_outgoing_rfc724_mid();
1734 }
1735
1736 if self.typ == Chattype::Single {
1737 if let Some(id) = context
1738 .sql
1739 .query_get_value(
1740 "SELECT contact_id FROM chats_contacts WHERE chat_id=?;",
1741 (self.id,),
1742 )
1743 .await?
1744 {
1745 to_id = id;
1746 } else {
1747 error!(
1748 context,
1749 "Cannot send message, contact for {} not found.", self.id,
1750 );
1751 bail!("Cannot set message, contact for {} not found.", self.id);
1752 }
1753 } else if matches!(self.typ, Chattype::Group | Chattype::OutBroadcast)
1754 && self.param.get_int(Param::Unpromoted).unwrap_or_default() == 1
1755 {
1756 msg.param.set_int(Param::AttachGroupImage, 1);
1757 self.param
1758 .remove(Param::Unpromoted)
1759 .set_i64(Param::GroupNameTimestamp, msg.timestamp_sort);
1760 self.update_param(context).await?;
1761 context
1767 .sync_qr_code_tokens(Some(self.grpid.as_str()))
1768 .await
1769 .log_err(context)
1770 .ok();
1771 }
1772
1773 let is_bot = context.get_config_bool(Config::Bot).await?;
1774 msg.param
1775 .set_optional(Param::Bot, Some("1").filter(|_| is_bot));
1776
1777 let new_references;
1781 if self.is_self_talk() {
1782 new_references = String::new();
1785 } else if let Some((parent_rfc724_mid, parent_in_reply_to, parent_references)) =
1786 self
1792 .id
1793 .get_parent_mime_headers(context, MessageState::OutPending)
1794 .await?
1795 {
1796 if msg.in_reply_to.is_none() && !parent_rfc724_mid.is_empty() {
1800 msg.in_reply_to = Some(parent_rfc724_mid.clone());
1801 }
1802
1803 let parent_references = if parent_references.is_empty() {
1813 parent_in_reply_to
1814 } else {
1815 parent_references
1816 };
1817
1818 let mut references_vec: Vec<&str> = parent_references.rsplit(' ').take(2).collect();
1821 references_vec.reverse();
1822
1823 if !parent_rfc724_mid.is_empty()
1824 && !references_vec.contains(&parent_rfc724_mid.as_str())
1825 {
1826 references_vec.push(&parent_rfc724_mid)
1827 }
1828
1829 if references_vec.is_empty() {
1830 new_references = msg.rfc724_mid.clone();
1833 } else {
1834 new_references = references_vec.join(" ");
1835 }
1836 } else {
1837 new_references = msg.rfc724_mid.clone();
1843 }
1844
1845 if msg.param.exists(Param::SetLatitude)
1847 && let Ok(row_id) = context
1848 .sql
1849 .insert(
1850 "INSERT INTO locations \
1851 (timestamp,from_id,chat_id, latitude,longitude,independent)\
1852 VALUES (?,?,?, ?,?,1);",
1853 (
1854 msg.timestamp_sort,
1855 ContactId::SELF,
1856 self.id,
1857 msg.param.get_float(Param::SetLatitude).unwrap_or_default(),
1858 msg.param.get_float(Param::SetLongitude).unwrap_or_default(),
1859 ),
1860 )
1861 .await
1862 {
1863 location_id = row_id;
1864 }
1865
1866 let ephemeral_timer = if msg.param.get_cmd() == SystemMessage::EphemeralTimerChanged {
1867 EphemeralTimer::Disabled
1868 } else {
1869 self.id.get_ephemeral_timer(context).await?
1870 };
1871 let ephemeral_timestamp = match ephemeral_timer {
1872 EphemeralTimer::Disabled => 0,
1873 EphemeralTimer::Enabled { duration } => time().saturating_add(duration.into()),
1874 };
1875
1876 let (msg_text, was_truncated) = truncate_msg_text(context, msg.text.clone()).await?;
1877 let new_mime_headers = if msg.has_html() {
1878 if msg.param.exists(Param::Forwarded) {
1879 msg.get_id().get_html(context).await?
1880 } else {
1881 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1882 }
1883 } else {
1884 None
1885 };
1886 let new_mime_headers: Option<String> = new_mime_headers.map(|s| {
1887 let html_part = MimePart::new("text/html", s);
1888 let mut buffer = Vec::new();
1889 let cursor = Cursor::new(&mut buffer);
1890 html_part.write_part(cursor).ok();
1891 String::from_utf8_lossy(&buffer).to_string()
1892 });
1893 let new_mime_headers = new_mime_headers.or_else(|| match was_truncated {
1894 true => Some("Content-Type: text/plain; charset=utf-8\r\n\r\n".to_string() + &msg.text),
1898 false => None,
1899 });
1900 let new_mime_headers = match new_mime_headers {
1901 Some(h) => Some(tokio::task::block_in_place(move || {
1902 buf_compress(h.as_bytes())
1903 })?),
1904 None => None,
1905 };
1906
1907 msg.chat_id = self.id;
1908 msg.from_id = ContactId::SELF;
1909
1910 if let Some(update_msg_id) = update_msg_id {
1912 context
1913 .sql
1914 .execute(
1915 "UPDATE msgs
1916 SET rfc724_mid=?, chat_id=?, from_id=?, to_id=?, timestamp=?, type=?,
1917 state=?, txt=?, txt_normalized=?, subject=?, param=?,
1918 hidden=?, mime_in_reply_to=?, mime_references=?, mime_modified=?,
1919 mime_headers=?, mime_compressed=1, location_id=?, ephemeral_timer=?,
1920 ephemeral_timestamp=?
1921 WHERE id=?;",
1922 params_slice![
1923 msg.rfc724_mid,
1924 msg.chat_id,
1925 msg.from_id,
1926 to_id,
1927 msg.timestamp_sort,
1928 msg.viewtype,
1929 msg.state,
1930 msg_text,
1931 normalize_text(&msg_text),
1932 &msg.subject,
1933 msg.param.to_string(),
1934 msg.hidden,
1935 msg.in_reply_to.as_deref().unwrap_or_default(),
1936 new_references,
1937 new_mime_headers.is_some(),
1938 new_mime_headers.unwrap_or_default(),
1939 location_id as i32,
1940 ephemeral_timer,
1941 ephemeral_timestamp,
1942 update_msg_id
1943 ],
1944 )
1945 .await?;
1946 msg.id = update_msg_id;
1947 } else {
1948 let raw_id = context
1949 .sql
1950 .insert(
1951 "INSERT INTO msgs (
1952 rfc724_mid,
1953 chat_id,
1954 from_id,
1955 to_id,
1956 timestamp,
1957 type,
1958 state,
1959 txt,
1960 txt_normalized,
1961 subject,
1962 param,
1963 hidden,
1964 mime_in_reply_to,
1965 mime_references,
1966 mime_modified,
1967 mime_headers,
1968 mime_compressed,
1969 location_id,
1970 ephemeral_timer,
1971 ephemeral_timestamp)
1972 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?,?);",
1973 params_slice![
1974 msg.rfc724_mid,
1975 msg.chat_id,
1976 msg.from_id,
1977 to_id,
1978 msg.timestamp_sort,
1979 msg.viewtype,
1980 msg.state,
1981 msg_text,
1982 normalize_text(&msg_text),
1983 &msg.subject,
1984 msg.param.to_string(),
1985 msg.hidden,
1986 msg.in_reply_to.as_deref().unwrap_or_default(),
1987 new_references,
1988 new_mime_headers.is_some(),
1989 new_mime_headers.unwrap_or_default(),
1990 location_id as i32,
1991 ephemeral_timer,
1992 ephemeral_timestamp
1993 ],
1994 )
1995 .await?;
1996 context.new_msgs_notify.notify_one();
1997 msg.id = MsgId::new(u32::try_from(raw_id)?);
1998
1999 maybe_set_logging_xdc(context, msg, self.id).await?;
2000 context
2001 .update_webxdc_integration_database(msg, context)
2002 .await?;
2003 }
2004 context.scheduler.interrupt_ephemeral_task().await;
2005 Ok(())
2006 }
2007
2008 pub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> {
2010 if self.is_encrypted(context).await? {
2011 let self_fp = self_fingerprint(context).await?;
2012 let fingerprint_addrs = context
2013 .sql
2014 .query_map_vec(
2015 "SELECT c.id, c.fingerprint, c.addr
2016 FROM contacts c INNER JOIN chats_contacts cc
2017 ON c.id=cc.contact_id
2018 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2019 (self.id,),
2020 |row| {
2021 if row.get::<_, ContactId>(0)? == ContactId::SELF {
2022 return Ok((self_fp.to_string(), String::new()));
2023 }
2024 let fingerprint = row.get(1)?;
2025 let addr = row.get(2)?;
2026 Ok((fingerprint, addr))
2027 },
2028 )
2029 .await?;
2030 self.sync(context, SyncAction::SetPgpContacts(fingerprint_addrs))
2031 .await?;
2032 } else {
2033 let addrs = context
2034 .sql
2035 .query_map_vec(
2036 "SELECT c.addr \
2037 FROM contacts c INNER JOIN chats_contacts cc \
2038 ON c.id=cc.contact_id \
2039 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2040 (self.id,),
2041 |row| {
2042 let addr: String = row.get(0)?;
2043 Ok(addr)
2044 },
2045 )
2046 .await?;
2047 self.sync(context, SyncAction::SetContacts(addrs)).await?;
2048 }
2049 Ok(())
2050 }
2051
2052 async fn get_sync_id(&self, context: &Context) -> Result<Option<SyncId>> {
2054 match self.typ {
2055 Chattype::Single => {
2056 if self.is_device_talk() {
2057 return Ok(Some(SyncId::Device));
2058 }
2059
2060 let mut r = None;
2061 for contact_id in get_chat_contacts(context, self.id).await? {
2062 if contact_id == ContactId::SELF && !self.is_self_talk() {
2063 continue;
2064 }
2065 if r.is_some() {
2066 return Ok(None);
2067 }
2068 let contact = Contact::get_by_id(context, contact_id).await?;
2069 if let Some(fingerprint) = contact.fingerprint() {
2070 r = Some(SyncId::ContactFingerprint(fingerprint.hex()));
2071 } else {
2072 r = Some(SyncId::ContactAddr(contact.get_addr().to_string()));
2073 }
2074 }
2075 Ok(r)
2076 }
2077 Chattype::OutBroadcast
2078 | Chattype::InBroadcast
2079 | Chattype::Group
2080 | Chattype::Mailinglist => {
2081 if !self.grpid.is_empty() {
2082 return Ok(Some(SyncId::Grpid(self.grpid.clone())));
2083 }
2084
2085 let Some((parent_rfc724_mid, parent_in_reply_to, _)) = self
2086 .id
2087 .get_parent_mime_headers(context, MessageState::OutDelivered)
2088 .await?
2089 else {
2090 warn!(
2091 context,
2092 "Chat::get_sync_id({}): No good message identifying the chat found.",
2093 self.id
2094 );
2095 return Ok(None);
2096 };
2097 Ok(Some(SyncId::Msgids(vec![
2098 parent_in_reply_to,
2099 parent_rfc724_mid,
2100 ])))
2101 }
2102 }
2103 }
2104
2105 pub(crate) async fn sync(&self, context: &Context, action: SyncAction) -> Result<()> {
2107 if let Some(id) = self.get_sync_id(context).await? {
2108 sync(context, id, action).await?;
2109 }
2110 Ok(())
2111 }
2112}
2113
2114pub(crate) async fn sync(context: &Context, id: SyncId, action: SyncAction) -> Result<()> {
2115 context
2116 .add_sync_item(SyncData::AlterChat { id, action })
2117 .await?;
2118 context.scheduler.interrupt_smtp().await;
2119 Ok(())
2120}
2121
2122#[derive(Debug, Copy, Eq, PartialEq, Clone, Serialize, Deserialize, EnumIter)]
2124#[repr(i8)]
2125pub enum ChatVisibility {
2126 Normal = 0,
2128
2129 Archived = 1,
2131
2132 Pinned = 2,
2134}
2135
2136impl rusqlite::types::ToSql for ChatVisibility {
2137 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
2138 let val = rusqlite::types::Value::Integer(*self as i64);
2139 let out = rusqlite::types::ToSqlOutput::Owned(val);
2140 Ok(out)
2141 }
2142}
2143
2144impl rusqlite::types::FromSql for ChatVisibility {
2145 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
2146 i64::column_result(value).map(|val| {
2147 match val {
2148 2 => ChatVisibility::Pinned,
2149 1 => ChatVisibility::Archived,
2150 0 => ChatVisibility::Normal,
2151 _ => ChatVisibility::Normal,
2153 }
2154 })
2155 }
2156}
2157
2158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2160#[non_exhaustive]
2161pub struct ChatInfo {
2162 pub id: ChatId,
2164
2165 #[serde(rename = "type")]
2172 pub type_: u32,
2173
2174 pub name: String,
2176
2177 pub archived: bool,
2179
2180 pub param: String,
2184
2185 pub is_sending_locations: bool,
2187
2188 pub color: u32,
2192
2193 pub profile_image: std::path::PathBuf,
2198
2199 pub draft: String,
2207
2208 pub is_muted: bool,
2212
2213 pub ephemeral_timer: EphemeralTimer,
2215 }
2221
2222async fn get_asset_icon(context: &Context, name: &str, bytes: &[u8]) -> Result<PathBuf> {
2223 ensure!(name.starts_with("icon-"));
2224 if let Some(icon) = context.sql.get_raw_config(name).await? {
2225 return Ok(get_abs_path(context, Path::new(&icon)));
2226 }
2227
2228 let blob =
2229 BlobObject::create_and_deduplicate_from_bytes(context, bytes, &format!("{name}.png"))?;
2230 let icon = blob.as_name().to_string();
2231 context.sql.set_raw_config(name, Some(&icon)).await?;
2232
2233 Ok(get_abs_path(context, Path::new(&icon)))
2234}
2235
2236pub(crate) async fn get_saved_messages_icon(context: &Context) -> Result<PathBuf> {
2237 get_asset_icon(
2238 context,
2239 "icon-saved-messages",
2240 include_bytes!("../assets/icon-saved-messages.png"),
2241 )
2242 .await
2243}
2244
2245pub(crate) async fn get_device_icon(context: &Context) -> Result<PathBuf> {
2246 get_asset_icon(
2247 context,
2248 "icon-device",
2249 include_bytes!("../assets/icon-device.png"),
2250 )
2251 .await
2252}
2253
2254pub(crate) async fn get_archive_icon(context: &Context) -> Result<PathBuf> {
2255 get_asset_icon(
2256 context,
2257 "icon-archive",
2258 include_bytes!("../assets/icon-archive.png"),
2259 )
2260 .await
2261}
2262
2263pub(crate) async fn get_unencrypted_icon(context: &Context) -> Result<PathBuf> {
2266 get_asset_icon(
2267 context,
2268 "icon-unencrypted",
2269 include_bytes!("../assets/icon-unencrypted.png"),
2270 )
2271 .await
2272}
2273
2274async fn update_special_chat_name(
2275 context: &Context,
2276 contact_id: ContactId,
2277 name: String,
2278) -> Result<()> {
2279 if let Some(ChatIdBlocked { id: chat_id, .. }) =
2280 ChatIdBlocked::lookup_by_contact(context, contact_id).await?
2281 {
2282 context
2284 .sql
2285 .execute(
2286 "UPDATE chats SET name=?, name_normalized=? WHERE id=? AND name!=?",
2287 (&name, normalize_text(&name), chat_id, &name),
2288 )
2289 .await?;
2290 }
2291 Ok(())
2292}
2293
2294pub(crate) async fn update_special_chat_names(context: &Context) -> Result<()> {
2295 update_special_chat_name(
2296 context,
2297 ContactId::DEVICE,
2298 stock_str::device_messages(context).await,
2299 )
2300 .await?;
2301 update_special_chat_name(
2302 context,
2303 ContactId::SELF,
2304 stock_str::saved_messages(context).await,
2305 )
2306 .await?;
2307 Ok(())
2308}
2309
2310#[derive(Debug)]
2318pub(crate) struct ChatIdBlocked {
2319 pub id: ChatId,
2321
2322 pub blocked: Blocked,
2324}
2325
2326impl ChatIdBlocked {
2327 pub async fn lookup_by_contact(
2331 context: &Context,
2332 contact_id: ContactId,
2333 ) -> Result<Option<Self>> {
2334 ensure!(context.sql.is_open().await, "Database not available");
2335 ensure!(
2336 contact_id != ContactId::UNDEFINED,
2337 "Invalid contact id requested"
2338 );
2339
2340 context
2341 .sql
2342 .query_row_optional(
2343 "SELECT c.id, c.blocked
2344 FROM chats c
2345 INNER JOIN chats_contacts j
2346 ON c.id=j.chat_id
2347 WHERE c.type=100 -- 100 = Chattype::Single
2348 AND c.id>9 -- 9 = DC_CHAT_ID_LAST_SPECIAL
2349 AND j.contact_id=?;",
2350 (contact_id,),
2351 |row| {
2352 let id: ChatId = row.get(0)?;
2353 let blocked: Blocked = row.get(1)?;
2354 Ok(ChatIdBlocked { id, blocked })
2355 },
2356 )
2357 .await
2358 }
2359
2360 pub async fn get_for_contact(
2365 context: &Context,
2366 contact_id: ContactId,
2367 create_blocked: Blocked,
2368 ) -> Result<Self> {
2369 ensure!(context.sql.is_open().await, "Database not available");
2370 ensure!(
2371 contact_id != ContactId::UNDEFINED,
2372 "Invalid contact id requested"
2373 );
2374
2375 if let Some(res) = Self::lookup_by_contact(context, contact_id).await? {
2376 return Ok(res);
2378 }
2379
2380 let contact = Contact::get_by_id(context, contact_id).await?;
2381 let chat_name = contact.get_display_name().to_string();
2382 let mut params = Params::new();
2383 match contact_id {
2384 ContactId::SELF => {
2385 params.set_int(Param::Selftalk, 1);
2386 }
2387 ContactId::DEVICE => {
2388 params.set_int(Param::Devicetalk, 1);
2389 }
2390 _ => (),
2391 }
2392
2393 let smeared_time = create_smeared_timestamp(context);
2394
2395 let chat_id = context
2396 .sql
2397 .transaction(move |transaction| {
2398 transaction.execute(
2399 "INSERT INTO chats
2400 (type, name, name_normalized, param, blocked, created_timestamp)
2401 VALUES(?, ?, ?, ?, ?, ?)",
2402 (
2403 Chattype::Single,
2404 &chat_name,
2405 normalize_text(&chat_name),
2406 params.to_string(),
2407 create_blocked as u8,
2408 smeared_time,
2409 ),
2410 )?;
2411 let chat_id = ChatId::new(
2412 transaction
2413 .last_insert_rowid()
2414 .try_into()
2415 .context("chat table rowid overflows u32")?,
2416 );
2417
2418 transaction.execute(
2419 "INSERT INTO chats_contacts
2420 (chat_id, contact_id)
2421 VALUES((SELECT last_insert_rowid()), ?)",
2422 (contact_id,),
2423 )?;
2424
2425 Ok(chat_id)
2426 })
2427 .await?;
2428
2429 let chat = Chat::load_from_db(context, chat_id).await?;
2430 if chat.is_encrypted(context).await?
2431 && !chat.param.exists(Param::Devicetalk)
2432 && !chat.param.exists(Param::Selftalk)
2433 {
2434 chat_id.add_e2ee_notice(context, smeared_time).await?;
2435 }
2436
2437 Ok(Self {
2438 id: chat_id,
2439 blocked: create_blocked,
2440 })
2441 }
2442}
2443
2444async fn prepare_msg_blob(context: &Context, msg: &mut Message) -> Result<()> {
2445 if msg.viewtype == Viewtype::Text || msg.viewtype == Viewtype::Call {
2446 } else if msg.viewtype.has_file() {
2448 let viewtype_orig = msg.viewtype;
2449 let mut blob = msg
2450 .param
2451 .get_file_blob(context)?
2452 .with_context(|| format!("attachment missing for message of type #{}", msg.viewtype))?;
2453 let mut maybe_image = false;
2454
2455 if msg.viewtype == Viewtype::File
2456 || msg.viewtype == Viewtype::Image
2457 || msg.viewtype == Viewtype::Sticker && !msg.param.exists(Param::ForceSticker)
2458 {
2459 if let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg) {
2466 if msg.viewtype == Viewtype::Sticker {
2467 if better_type != Viewtype::Image {
2468 msg.param.set_int(Param::ForceSticker, 1);
2470 }
2471 } else if better_type == Viewtype::Image {
2472 maybe_image = true;
2473 } else if better_type != Viewtype::Webxdc
2474 || context
2475 .ensure_sendable_webxdc_file(&blob.to_abs_path())
2476 .await
2477 .is_ok()
2478 {
2479 msg.viewtype = better_type;
2480 }
2481 }
2482 } else if msg.viewtype == Viewtype::Webxdc {
2483 context
2484 .ensure_sendable_webxdc_file(&blob.to_abs_path())
2485 .await?;
2486 }
2487
2488 if msg.viewtype == Viewtype::Vcard {
2489 msg.try_set_vcard(context, &blob.to_abs_path()).await?;
2490 }
2491 if msg.viewtype == Viewtype::File && maybe_image
2492 || msg.viewtype == Viewtype::Image
2493 || msg.viewtype == Viewtype::Sticker && !msg.param.exists(Param::ForceSticker)
2494 {
2495 let new_name = blob
2496 .check_or_recode_image(context, msg.get_filename(), &mut msg.viewtype)
2497 .await?;
2498 msg.param.set(Param::Filename, new_name);
2499 msg.param.set(Param::File, blob.as_name());
2500 }
2501
2502 if !msg.param.exists(Param::MimeType)
2503 && let Some((viewtype, mime)) = message::guess_msgtype_from_suffix(msg)
2504 {
2505 let mime = match viewtype != Viewtype::Image
2508 || matches!(msg.viewtype, Viewtype::Image | Viewtype::Sticker)
2509 {
2510 true => mime,
2511 false => "application/octet-stream",
2512 };
2513 msg.param.set(Param::MimeType, mime);
2514 }
2515
2516 msg.try_calc_and_set_dimensions(context).await?;
2517
2518 let filename = msg.get_filename().context("msg has no file")?;
2519 let suffix = Path::new(&filename)
2520 .extension()
2521 .and_then(|e| e.to_str())
2522 .unwrap_or("dat");
2523 let filename: String = match viewtype_orig {
2527 Viewtype::Voice => format!(
2528 "voice-messsage_{}.{}",
2529 chrono::Utc
2530 .timestamp_opt(msg.timestamp_sort, 0)
2531 .single()
2532 .map_or_else(
2533 || "YY-mm-dd_hh:mm:ss".to_string(),
2534 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2535 ),
2536 &suffix
2537 ),
2538 Viewtype::Image | Viewtype::Gif => format!(
2539 "image_{}.{}",
2540 chrono::Utc
2541 .timestamp_opt(msg.timestamp_sort, 0)
2542 .single()
2543 .map_or_else(
2544 || "YY-mm-dd_hh:mm:ss".to_string(),
2545 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string(),
2546 ),
2547 &suffix,
2548 ),
2549 Viewtype::Video => format!(
2550 "video_{}.{}",
2551 chrono::Utc
2552 .timestamp_opt(msg.timestamp_sort, 0)
2553 .single()
2554 .map_or_else(
2555 || "YY-mm-dd_hh:mm:ss".to_string(),
2556 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2557 ),
2558 &suffix
2559 ),
2560 _ => filename,
2561 };
2562 msg.param.set(Param::Filename, filename);
2563
2564 info!(
2565 context,
2566 "Attaching \"{}\" for message type #{}.",
2567 blob.to_abs_path().display(),
2568 msg.viewtype
2569 );
2570 } else {
2571 bail!("Cannot send messages of type #{}.", msg.viewtype);
2572 }
2573 Ok(())
2574}
2575
2576pub async fn is_contact_in_chat(
2578 context: &Context,
2579 chat_id: ChatId,
2580 contact_id: ContactId,
2581) -> Result<bool> {
2582 let exists = context
2589 .sql
2590 .exists(
2591 "SELECT COUNT(*) FROM chats_contacts
2592 WHERE chat_id=? AND contact_id=?
2593 AND add_timestamp >= remove_timestamp",
2594 (chat_id, contact_id),
2595 )
2596 .await?;
2597 Ok(exists)
2598}
2599
2600pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2607 ensure!(
2608 !chat_id.is_special(),
2609 "chat_id cannot be a special chat: {chat_id}"
2610 );
2611
2612 if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {
2613 msg.param.remove(Param::GuaranteeE2ee);
2614 msg.param.remove(Param::ForcePlaintext);
2615 msg.update_param(context).await?;
2616 }
2617
2618 if msg.is_system_message() {
2620 msg.text = sanitize_bidi_characters(&msg.text);
2621 }
2622
2623 if !prepare_send_msg(context, chat_id, msg).await?.is_empty() {
2624 if !msg.hidden {
2625 context.emit_msgs_changed(msg.chat_id, msg.id);
2626 }
2627
2628 if msg.param.exists(Param::SetLatitude) {
2629 context.emit_location_changed(Some(ContactId::SELF)).await?;
2630 }
2631
2632 context.scheduler.interrupt_smtp().await;
2633 }
2634
2635 Ok(msg.id)
2636}
2637
2638pub async fn send_msg_sync(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2643 let rowids = prepare_send_msg(context, chat_id, msg).await?;
2644 if rowids.is_empty() {
2645 return Ok(msg.id);
2646 }
2647 let mut smtp = crate::smtp::Smtp::new();
2648 for rowid in rowids {
2649 send_msg_to_smtp(context, &mut smtp, rowid)
2650 .await
2651 .context("failed to send message, queued for later sending")?;
2652 }
2653 context.emit_msgs_changed(msg.chat_id, msg.id);
2654 Ok(msg.id)
2655}
2656
2657async fn prepare_send_msg(
2661 context: &Context,
2662 chat_id: ChatId,
2663 msg: &mut Message,
2664) -> Result<Vec<i64>> {
2665 let mut chat = Chat::load_from_db(context, chat_id).await?;
2666
2667 let skip_fn = |reason: &CantSendReason| match reason {
2668 CantSendReason::ContactRequest => {
2669 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
2672 }
2673 CantSendReason::NotAMember => msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup,
2677 CantSendReason::InBroadcast => {
2678 matches!(
2679 msg.param.get_cmd(),
2680 SystemMessage::MemberRemovedFromGroup | SystemMessage::SecurejoinMessage
2681 )
2682 }
2683 CantSendReason::MissingKey => msg
2684 .param
2685 .get_bool(Param::ForcePlaintext)
2686 .unwrap_or_default(),
2687 _ => false,
2688 };
2689 if let Some(reason) = chat.why_cant_send_ex(context, &skip_fn).await? {
2690 bail!("Cannot send to {chat_id}: {reason}");
2691 }
2692
2693 if chat.typ != Chattype::Single
2698 && !context.get_config_bool(Config::Bot).await?
2699 && let Some(quoted_message) = msg.quoted_message(context).await?
2700 && quoted_message.chat_id != chat_id
2701 {
2702 bail!(
2703 "Quote of message from {} cannot be sent to {chat_id}",
2704 quoted_message.chat_id
2705 );
2706 }
2707
2708 let update_msg_id = if msg.state == MessageState::OutDraft {
2710 msg.hidden = false;
2711 if !msg.id.is_special() && msg.chat_id == chat_id {
2712 Some(msg.id)
2713 } else {
2714 None
2715 }
2716 } else {
2717 None
2718 };
2719
2720 msg.state = MessageState::OutPending;
2722
2723 msg.timestamp_sort = create_smeared_timestamp(context);
2724 prepare_msg_blob(context, msg).await?;
2725 if !msg.hidden {
2726 chat_id.unarchive_if_not_muted(context, msg.state).await?;
2727 }
2728 chat.prepare_msg_raw(context, msg, update_msg_id).await?;
2729
2730 let row_ids = create_send_msg_jobs(context, msg)
2731 .await
2732 .context("Failed to create send jobs")?;
2733 if !row_ids.is_empty() {
2734 donation_request_maybe(context).await.log_err(context).ok();
2735 }
2736 Ok(row_ids)
2737}
2738
2739pub(crate) async fn create_send_msg_jobs(context: &Context, msg: &mut Message) -> Result<Vec<i64>> {
2749 if msg.param.get_cmd() == SystemMessage::GroupNameChanged {
2750 msg.chat_id
2751 .update_timestamp(context, Param::GroupNameTimestamp, msg.timestamp_sort)
2752 .await?;
2753 }
2754
2755 let needs_encryption = msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default();
2756 let mimefactory = match MimeFactory::from_msg(context, msg.clone()).await {
2757 Ok(mf) => mf,
2758 Err(err) => {
2759 message::set_msg_failed(context, msg, &err.to_string())
2761 .await
2762 .ok();
2763 return Err(err);
2764 }
2765 };
2766 let attach_selfavatar = mimefactory.attach_selfavatar;
2767 let mut recipients = mimefactory.recipients();
2768
2769 let from = context.get_primary_self_addr().await?;
2770 let lowercase_from = from.to_lowercase();
2771
2772 recipients.retain(|x| x.to_lowercase() != lowercase_from);
2785 if (context.get_config_bool(Config::BccSelf).await?
2786 || msg.param.get_cmd() == SystemMessage::AutocryptSetupMessage)
2787 && (context.get_config_delete_server_after().await? != Some(0) || !recipients.is_empty())
2788 {
2789 recipients.push(from);
2790 }
2791
2792 if msg.param.get_int(Param::WebxdcIntegration).is_some() && msg.hidden {
2794 recipients.clear();
2795 }
2796
2797 if recipients.is_empty() {
2798 info!(
2800 context,
2801 "Message {} has no recipient, skipping smtp-send.", msg.id
2802 );
2803 msg.param.set_int(Param::GuaranteeE2ee, 1);
2804 msg.update_param(context).await?;
2805 msg.id.set_delivered(context).await?;
2806 msg.state = MessageState::OutDelivered;
2807 return Ok(Vec::new());
2808 }
2809
2810 let rendered_msg = match mimefactory.render(context).await {
2811 Ok(res) => Ok(res),
2812 Err(err) => {
2813 message::set_msg_failed(context, msg, &err.to_string()).await?;
2814 Err(err)
2815 }
2816 }?;
2817
2818 if needs_encryption && !rendered_msg.is_encrypted {
2819 message::set_msg_failed(
2821 context,
2822 msg,
2823 "End-to-end-encryption unavailable unexpectedly.",
2824 )
2825 .await?;
2826 bail!(
2827 "e2e encryption unavailable {} - {:?}",
2828 msg.id,
2829 needs_encryption
2830 );
2831 }
2832
2833 let now = smeared_time(context);
2834
2835 if rendered_msg.last_added_location_id.is_some()
2836 && let Err(err) = location::set_kml_sent_timestamp(context, msg.chat_id, now).await
2837 {
2838 error!(context, "Failed to set kml sent_timestamp: {err:#}.");
2839 }
2840
2841 if attach_selfavatar && let Err(err) = msg.chat_id.set_selfavatar_timestamp(context, now).await
2842 {
2843 error!(context, "Failed to set selfavatar timestamp: {err:#}.");
2844 }
2845
2846 if rendered_msg.is_encrypted {
2847 msg.param.set_int(Param::GuaranteeE2ee, 1);
2848 } else {
2849 msg.param.remove(Param::GuaranteeE2ee);
2850 }
2851 msg.subject.clone_from(&rendered_msg.subject);
2852 context
2853 .sql
2854 .execute(
2855 "UPDATE msgs SET subject=?, param=? WHERE id=?",
2856 (&msg.subject, msg.param.to_string(), msg.id),
2857 )
2858 .await?;
2859
2860 let chunk_size = context.get_max_smtp_rcpt_to().await?;
2861 let trans_fn = |t: &mut rusqlite::Transaction| {
2862 let mut row_ids = Vec::<i64>::new();
2863
2864 if let Some(sync_ids) = rendered_msg.sync_ids_to_delete {
2865 t.execute(
2866 &format!("DELETE FROM multi_device_sync WHERE id IN ({sync_ids})"),
2867 (),
2868 )?;
2869 }
2870
2871 for recipients_chunk in recipients.chunks(chunk_size) {
2872 let recipients_chunk = recipients_chunk.join(" ");
2873 let row_id = t.execute(
2874 "INSERT INTO smtp (rfc724_mid, recipients, mime, msg_id) \
2875 VALUES (?1, ?2, ?3, ?4)",
2876 (
2877 &rendered_msg.rfc724_mid,
2878 recipients_chunk,
2879 &rendered_msg.message,
2880 msg.id,
2881 ),
2882 )?;
2883 row_ids.push(row_id.try_into()?);
2884 }
2885 Ok(row_ids)
2886 };
2887 context.sql.transaction(trans_fn).await
2888}
2889
2890pub async fn send_text_msg(
2894 context: &Context,
2895 chat_id: ChatId,
2896 text_to_send: String,
2897) -> Result<MsgId> {
2898 ensure!(
2899 !chat_id.is_special(),
2900 "bad chat_id, can not be a special chat: {chat_id}"
2901 );
2902
2903 let mut msg = Message::new_text(text_to_send);
2904 send_msg(context, chat_id, &mut msg).await
2905}
2906
2907pub async fn send_edit_request(context: &Context, msg_id: MsgId, new_text: String) -> Result<()> {
2909 let mut original_msg = Message::load_from_db(context, msg_id).await?;
2910 ensure!(
2911 original_msg.from_id == ContactId::SELF,
2912 "Can edit only own messages"
2913 );
2914 ensure!(!original_msg.is_info(), "Cannot edit info messages");
2915 ensure!(!original_msg.has_html(), "Cannot edit HTML messages");
2916 ensure!(original_msg.viewtype != Viewtype::Call, "Cannot edit calls");
2917 ensure!(
2918 !original_msg.text.is_empty(), "Cannot add text"
2920 );
2921 ensure!(!new_text.trim().is_empty(), "Edited text cannot be empty");
2922 if original_msg.text == new_text {
2923 info!(context, "Text unchanged.");
2924 return Ok(());
2925 }
2926
2927 save_text_edit_to_db(context, &mut original_msg, &new_text).await?;
2928
2929 let mut edit_msg = Message::new_text(EDITED_PREFIX.to_owned() + &new_text); edit_msg.set_quote(context, Some(&original_msg)).await?; if original_msg.get_showpadlock() {
2932 edit_msg.param.set_int(Param::GuaranteeE2ee, 1);
2933 }
2934 edit_msg
2935 .param
2936 .set(Param::TextEditFor, original_msg.rfc724_mid);
2937 edit_msg.hidden = true;
2938 send_msg(context, original_msg.chat_id, &mut edit_msg).await?;
2939 Ok(())
2940}
2941
2942pub(crate) async fn save_text_edit_to_db(
2943 context: &Context,
2944 original_msg: &mut Message,
2945 new_text: &str,
2946) -> Result<()> {
2947 original_msg.param.set_int(Param::IsEdited, 1);
2948 context
2949 .sql
2950 .execute(
2951 "UPDATE msgs SET txt=?, txt_normalized=?, param=? WHERE id=?",
2952 (
2953 new_text,
2954 normalize_text(new_text),
2955 original_msg.param.to_string(),
2956 original_msg.id,
2957 ),
2958 )
2959 .await?;
2960 context.emit_msgs_changed(original_msg.chat_id, original_msg.id);
2961 Ok(())
2962}
2963
2964async fn donation_request_maybe(context: &Context) -> Result<()> {
2965 let secs_between_checks = 30 * 24 * 60 * 60;
2966 let now = time();
2967 let ts = context
2968 .get_config_i64(Config::DonationRequestNextCheck)
2969 .await?;
2970 if ts > now {
2971 return Ok(());
2972 }
2973 let msg_cnt = context.sql.count(
2974 "SELECT COUNT(*) FROM msgs WHERE state>=? AND hidden=0",
2975 (MessageState::OutDelivered,),
2976 );
2977 let ts = if ts == 0 || msg_cnt.await? < 100 {
2978 now.saturating_add(secs_between_checks)
2979 } else {
2980 let mut msg = Message::new_text(stock_str::donation_request(context).await);
2981 add_device_msg(context, None, Some(&mut msg)).await?;
2982 i64::MAX
2983 };
2984 context
2985 .set_config_internal(Config::DonationRequestNextCheck, Some(&ts.to_string()))
2986 .await
2987}
2988
2989#[derive(Debug)]
2991pub struct MessageListOptions {
2992 pub info_only: bool,
2994
2995 pub add_daymarker: bool,
2997}
2998
2999pub async fn get_chat_msgs(context: &Context, chat_id: ChatId) -> Result<Vec<ChatItem>> {
3001 get_chat_msgs_ex(
3002 context,
3003 chat_id,
3004 MessageListOptions {
3005 info_only: false,
3006 add_daymarker: false,
3007 },
3008 )
3009 .await
3010}
3011
3012pub async fn get_chat_msgs_ex(
3014 context: &Context,
3015 chat_id: ChatId,
3016 options: MessageListOptions,
3017) -> Result<Vec<ChatItem>> {
3018 let MessageListOptions {
3019 info_only,
3020 add_daymarker,
3021 } = options;
3022 let process_row = if info_only {
3023 |row: &rusqlite::Row| {
3024 let params = row.get::<_, String>("param")?;
3026 let (from_id, to_id) = (
3027 row.get::<_, ContactId>("from_id")?,
3028 row.get::<_, ContactId>("to_id")?,
3029 );
3030 let is_info_msg: bool = from_id == ContactId::INFO
3031 || to_id == ContactId::INFO
3032 || match Params::from_str(¶ms) {
3033 Ok(p) => {
3034 let cmd = p.get_cmd();
3035 cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage
3036 }
3037 _ => false,
3038 };
3039
3040 Ok((
3041 row.get::<_, i64>("timestamp")?,
3042 row.get::<_, MsgId>("id")?,
3043 !is_info_msg,
3044 ))
3045 }
3046 } else {
3047 |row: &rusqlite::Row| {
3048 Ok((
3049 row.get::<_, i64>("timestamp")?,
3050 row.get::<_, MsgId>("id")?,
3051 false,
3052 ))
3053 }
3054 };
3055 let process_rows = |rows: rusqlite::AndThenRows<_>| {
3056 let mut sorted_rows = Vec::new();
3059 for row in rows {
3060 let (ts, curr_id, exclude_message): (i64, MsgId, bool) = row?;
3061 if !exclude_message {
3062 sorted_rows.push((ts, curr_id));
3063 }
3064 }
3065 sorted_rows.sort_unstable();
3066
3067 let mut ret = Vec::new();
3068 let mut last_day = 0;
3069 let cnv_to_local = gm2local_offset();
3070
3071 for (ts, curr_id) in sorted_rows {
3072 if add_daymarker {
3073 let curr_local_timestamp = ts + cnv_to_local;
3074 let secs_in_day = 86400;
3075 let curr_day = curr_local_timestamp / secs_in_day;
3076 if curr_day != last_day {
3077 ret.push(ChatItem::DayMarker {
3078 timestamp: curr_day * secs_in_day - cnv_to_local,
3079 });
3080 last_day = curr_day;
3081 }
3082 }
3083 ret.push(ChatItem::Message { msg_id: curr_id });
3084 }
3085 Ok(ret)
3086 };
3087
3088 let items = if info_only {
3089 context
3090 .sql
3091 .query_map(
3092 "SELECT m.id AS id, m.timestamp AS timestamp, m.param AS param, m.from_id AS from_id, m.to_id AS to_id
3094 FROM msgs m
3095 WHERE m.chat_id=?
3096 AND m.hidden=0
3097 AND (
3098 m.param GLOB '*\nS=*' OR param GLOB 'S=*'
3099 OR m.from_id == ?
3100 OR m.to_id == ?
3101 );",
3102 (chat_id, ContactId::INFO, ContactId::INFO),
3103 process_row,
3104 process_rows,
3105 )
3106 .await?
3107 } else {
3108 context
3109 .sql
3110 .query_map(
3111 "SELECT m.id AS id, m.timestamp AS timestamp
3112 FROM msgs m
3113 WHERE m.chat_id=?
3114 AND m.hidden=0;",
3115 (chat_id,),
3116 process_row,
3117 process_rows,
3118 )
3119 .await?
3120 };
3121 Ok(items)
3122}
3123
3124pub async fn marknoticed_chat(context: &Context, chat_id: ChatId) -> Result<()> {
3127 if chat_id.is_archived_link() {
3130 let chat_ids_in_archive = context
3131 .sql
3132 .query_map_vec(
3133 "SELECT DISTINCT(m.chat_id) FROM msgs m
3134 LEFT JOIN chats c ON m.chat_id=c.id
3135 WHERE m.state=10 AND m.hidden=0 AND m.chat_id>9 AND c.archived=1",
3136 (),
3137 |row| {
3138 let chat_id: ChatId = row.get(0)?;
3139 Ok(chat_id)
3140 },
3141 )
3142 .await?;
3143 if chat_ids_in_archive.is_empty() {
3144 return Ok(());
3145 }
3146
3147 context
3148 .sql
3149 .transaction(|transaction| {
3150 let mut stmt = transaction.prepare(
3151 "UPDATE msgs SET state=13 WHERE state=10 AND hidden=0 AND chat_id = ?",
3152 )?;
3153 for chat_id_in_archive in &chat_ids_in_archive {
3154 stmt.execute((chat_id_in_archive,))?;
3155 }
3156 Ok(())
3157 })
3158 .await?;
3159
3160 for chat_id_in_archive in chat_ids_in_archive {
3161 start_chat_ephemeral_timers(context, chat_id_in_archive).await?;
3162 context.emit_event(EventType::MsgsNoticed(chat_id_in_archive));
3163 chatlist_events::emit_chatlist_item_changed(context, chat_id_in_archive);
3164 }
3165 } else {
3166 start_chat_ephemeral_timers(context, chat_id).await?;
3167
3168 let noticed_msgs_count = context
3169 .sql
3170 .execute(
3171 "UPDATE msgs
3172 SET state=?
3173 WHERE state=?
3174 AND hidden=0
3175 AND chat_id=?;",
3176 (MessageState::InNoticed, MessageState::InFresh, chat_id),
3177 )
3178 .await?;
3179
3180 let hidden_messages = context
3183 .sql
3184 .query_map_vec(
3185 "SELECT id, rfc724_mid FROM msgs
3186 WHERE state=?
3187 AND hidden=1
3188 AND chat_id=?
3189 ORDER BY id LIMIT 100", (MessageState::InFresh, chat_id), |row| {
3192 let msg_id: MsgId = row.get(0)?;
3193 let rfc724_mid: String = row.get(1)?;
3194 Ok((msg_id, rfc724_mid))
3195 },
3196 )
3197 .await?;
3198 for (msg_id, rfc724_mid) in &hidden_messages {
3199 message::update_msg_state(context, *msg_id, MessageState::InSeen).await?;
3200 imap::markseen_on_imap_table(context, rfc724_mid).await?;
3201 }
3202
3203 if noticed_msgs_count == 0 {
3204 return Ok(());
3205 }
3206 }
3207
3208 context.emit_event(EventType::MsgsNoticed(chat_id));
3209 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3210 context.on_archived_chats_maybe_noticed();
3211 Ok(())
3212}
3213
3214pub(crate) async fn mark_old_messages_as_noticed(
3221 context: &Context,
3222 mut msgs: Vec<ReceivedMsg>,
3223) -> Result<()> {
3224 msgs.retain(|m| m.state.is_outgoing());
3225 if msgs.is_empty() {
3226 return Ok(());
3227 }
3228
3229 let mut msgs_by_chat: HashMap<ChatId, ReceivedMsg> = HashMap::new();
3230 for msg in msgs {
3231 let chat_id = msg.chat_id;
3232 if let Some(existing_msg) = msgs_by_chat.get(&chat_id) {
3233 if msg.sort_timestamp > existing_msg.sort_timestamp {
3234 msgs_by_chat.insert(chat_id, msg);
3235 }
3236 } else {
3237 msgs_by_chat.insert(chat_id, msg);
3238 }
3239 }
3240
3241 let changed_chats = context
3242 .sql
3243 .transaction(|transaction| {
3244 let mut changed_chats = Vec::new();
3245 for (_, msg) in msgs_by_chat {
3246 let changed_rows = transaction.execute(
3247 "UPDATE msgs
3248 SET state=?
3249 WHERE state=?
3250 AND hidden=0
3251 AND chat_id=?
3252 AND timestamp<=?;",
3253 (
3254 MessageState::InNoticed,
3255 MessageState::InFresh,
3256 msg.chat_id,
3257 msg.sort_timestamp,
3258 ),
3259 )?;
3260 if changed_rows > 0 {
3261 changed_chats.push(msg.chat_id);
3262 }
3263 }
3264 Ok(changed_chats)
3265 })
3266 .await?;
3267
3268 if !changed_chats.is_empty() {
3269 info!(
3270 context,
3271 "Marking chats as noticed because there are newer outgoing messages: {changed_chats:?}."
3272 );
3273 context.on_archived_chats_maybe_noticed();
3274 }
3275
3276 for c in changed_chats {
3277 start_chat_ephemeral_timers(context, c).await?;
3278 context.emit_event(EventType::MsgsNoticed(c));
3279 chatlist_events::emit_chatlist_item_changed(context, c);
3280 }
3281
3282 Ok(())
3283}
3284
3285pub async fn get_chat_media(
3292 context: &Context,
3293 chat_id: Option<ChatId>,
3294 msg_type: Viewtype,
3295 msg_type2: Viewtype,
3296 msg_type3: Viewtype,
3297) -> Result<Vec<MsgId>> {
3298 let list = if msg_type == Viewtype::Webxdc
3299 && msg_type2 == Viewtype::Unknown
3300 && msg_type3 == Viewtype::Unknown
3301 {
3302 context
3303 .sql
3304 .query_map_vec(
3305 "SELECT id
3306 FROM msgs
3307 WHERE (1=? OR chat_id=?)
3308 AND chat_id != ?
3309 AND type = ?
3310 AND hidden=0
3311 ORDER BY max(timestamp, timestamp_rcvd), id;",
3312 (
3313 chat_id.is_none(),
3314 chat_id.unwrap_or_else(|| ChatId::new(0)),
3315 DC_CHAT_ID_TRASH,
3316 Viewtype::Webxdc,
3317 ),
3318 |row| {
3319 let msg_id: MsgId = row.get(0)?;
3320 Ok(msg_id)
3321 },
3322 )
3323 .await?
3324 } else {
3325 context
3326 .sql
3327 .query_map_vec(
3328 "SELECT id
3329 FROM msgs
3330 WHERE (1=? OR chat_id=?)
3331 AND chat_id != ?
3332 AND type IN (?, ?, ?)
3333 AND hidden=0
3334 ORDER BY timestamp, id;",
3335 (
3336 chat_id.is_none(),
3337 chat_id.unwrap_or_else(|| ChatId::new(0)),
3338 DC_CHAT_ID_TRASH,
3339 msg_type,
3340 if msg_type2 != Viewtype::Unknown {
3341 msg_type2
3342 } else {
3343 msg_type
3344 },
3345 if msg_type3 != Viewtype::Unknown {
3346 msg_type3
3347 } else {
3348 msg_type
3349 },
3350 ),
3351 |row| {
3352 let msg_id: MsgId = row.get(0)?;
3353 Ok(msg_id)
3354 },
3355 )
3356 .await?
3357 };
3358 Ok(list)
3359}
3360
3361pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3363 context
3366 .sql
3367 .query_map_vec(
3368 "SELECT cc.contact_id
3369 FROM chats_contacts cc
3370 LEFT JOIN contacts c
3371 ON c.id=cc.contact_id
3372 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp
3373 ORDER BY c.id=1, c.last_seen DESC, c.id DESC;",
3374 (chat_id,),
3375 |row| {
3376 let contact_id: ContactId = row.get(0)?;
3377 Ok(contact_id)
3378 },
3379 )
3380 .await
3381}
3382
3383pub async fn get_past_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3387 let now = time();
3388 context
3389 .sql
3390 .query_map_vec(
3391 "SELECT cc.contact_id
3392 FROM chats_contacts cc
3393 LEFT JOIN contacts c
3394 ON c.id=cc.contact_id
3395 WHERE cc.chat_id=?
3396 AND cc.add_timestamp < cc.remove_timestamp
3397 AND ? < cc.remove_timestamp
3398 ORDER BY c.id=1, cc.remove_timestamp DESC, c.id DESC",
3399 (chat_id, now.saturating_sub(60 * 24 * 3600)),
3400 |row| {
3401 let contact_id: ContactId = row.get(0)?;
3402 Ok(contact_id)
3403 },
3404 )
3405 .await
3406}
3407
3408pub async fn create_group(context: &Context, name: &str) -> Result<ChatId> {
3410 create_group_ex(context, Sync, create_id(), name).await
3411}
3412
3413pub async fn create_group_unencrypted(context: &Context, name: &str) -> Result<ChatId> {
3415 create_group_ex(context, Sync, String::new(), name).await
3416}
3417
3418pub(crate) async fn create_group_ex(
3425 context: &Context,
3426 sync: sync::Sync,
3427 grpid: String,
3428 name: &str,
3429) -> Result<ChatId> {
3430 let mut chat_name = sanitize_single_line(name);
3431 if chat_name.is_empty() {
3432 error!(context, "Invalid chat name: {name}.");
3435 chat_name = "…".to_string();
3436 }
3437
3438 let timestamp = create_smeared_timestamp(context);
3439 let row_id = context
3440 .sql
3441 .insert(
3442 "INSERT INTO chats
3443 (type, name, name_normalized, grpid, param, created_timestamp)
3444 VALUES(?, ?, ?, ?, \'U=1\', ?)",
3445 (
3446 Chattype::Group,
3447 &chat_name,
3448 normalize_text(&chat_name),
3449 &grpid,
3450 timestamp,
3451 ),
3452 )
3453 .await?;
3454
3455 let chat_id = ChatId::new(u32::try_from(row_id)?);
3456 add_to_chat_contacts_table(context, timestamp, chat_id, &[ContactId::SELF]).await?;
3457
3458 context.emit_msgs_changed_without_ids();
3459 chatlist_events::emit_chatlist_changed(context);
3460 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3461
3462 if !grpid.is_empty() {
3463 chat_id.add_e2ee_notice(context, timestamp).await?;
3465 }
3466
3467 if !context.get_config_bool(Config::Bot).await?
3468 && !context.get_config_bool(Config::SkipStartMessages).await?
3469 {
3470 let text = if !grpid.is_empty() {
3471 stock_str::new_group_send_first_message(context).await
3473 } else {
3474 stock_str::chat_unencrypted_explanation(context).await
3476 };
3477 add_info_msg(context, chat_id, &text).await?;
3478 }
3479 if let (true, true) = (sync.into(), !grpid.is_empty()) {
3480 let id = SyncId::Grpid(grpid);
3481 let action = SyncAction::CreateGroupEncrypted(chat_name);
3482 self::sync(context, id, action).await.log_err(context).ok();
3483 }
3484 Ok(chat_id)
3485}
3486
3487pub async fn create_broadcast(context: &Context, chat_name: String) -> Result<ChatId> {
3503 let grpid = create_id();
3504 let secret = create_broadcast_secret();
3505 create_out_broadcast_ex(context, Sync, grpid, chat_name, secret).await
3506}
3507
3508const SQL_INSERT_BROADCAST_SECRET: &str =
3509 "INSERT INTO broadcast_secrets (chat_id, secret) VALUES (?, ?)
3510 ON CONFLICT(chat_id) DO UPDATE SET secret=excluded.secret";
3511
3512pub(crate) async fn create_out_broadcast_ex(
3513 context: &Context,
3514 sync: sync::Sync,
3515 grpid: String,
3516 chat_name: String,
3517 secret: String,
3518) -> Result<ChatId> {
3519 let chat_name = sanitize_single_line(&chat_name);
3520 if chat_name.is_empty() {
3521 bail!("Invalid broadcast channel name: {chat_name}.");
3522 }
3523
3524 let timestamp = create_smeared_timestamp(context);
3525 let trans_fn = |t: &mut rusqlite::Transaction| -> Result<ChatId> {
3526 let cnt: u32 = t.query_row(
3527 "SELECT COUNT(*) FROM chats WHERE grpid=?",
3528 (&grpid,),
3529 |row| row.get(0),
3530 )?;
3531 ensure!(cnt == 0, "{cnt} chats exist with grpid {grpid}");
3532
3533 t.execute(
3534 "INSERT INTO chats
3535 (type, name, name_normalized, grpid, created_timestamp)
3536 VALUES(?, ?, ?, ?, ?)",
3537 (
3538 Chattype::OutBroadcast,
3539 &chat_name,
3540 normalize_text(&chat_name),
3541 &grpid,
3542 timestamp,
3543 ),
3544 )?;
3545 let chat_id = ChatId::new(t.last_insert_rowid().try_into()?);
3546
3547 t.execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, &secret))?;
3548 Ok(chat_id)
3549 };
3550 let chat_id = context.sql.transaction(trans_fn).await?;
3551 chat_id.add_e2ee_notice(context, timestamp).await?;
3552
3553 context.emit_msgs_changed_without_ids();
3554 chatlist_events::emit_chatlist_changed(context);
3555 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3556
3557 if sync.into() {
3558 let id = SyncId::Grpid(grpid);
3559 let action = SyncAction::CreateOutBroadcast { chat_name, secret };
3560 self::sync(context, id, action).await.log_err(context).ok();
3561 }
3562
3563 Ok(chat_id)
3564}
3565
3566pub(crate) async fn load_broadcast_secret(
3567 context: &Context,
3568 chat_id: ChatId,
3569) -> Result<Option<String>> {
3570 context
3571 .sql
3572 .query_get_value(
3573 "SELECT secret FROM broadcast_secrets WHERE chat_id=?",
3574 (chat_id,),
3575 )
3576 .await
3577}
3578
3579pub(crate) async fn save_broadcast_secret(
3580 context: &Context,
3581 chat_id: ChatId,
3582 secret: &str,
3583) -> Result<()> {
3584 info!(context, "Saving broadcast secret for chat {chat_id}");
3585 context
3586 .sql
3587 .execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, secret))
3588 .await?;
3589
3590 Ok(())
3591}
3592
3593pub(crate) async fn delete_broadcast_secret(context: &Context, chat_id: ChatId) -> Result<()> {
3594 info!(context, "Removing broadcast secret for chat {chat_id}");
3595 context
3596 .sql
3597 .execute("DELETE FROM broadcast_secrets WHERE chat_id=?", (chat_id,))
3598 .await?;
3599
3600 Ok(())
3601}
3602
3603pub(crate) async fn update_chat_contacts_table(
3605 context: &Context,
3606 timestamp: i64,
3607 id: ChatId,
3608 contacts: &HashSet<ContactId>,
3609) -> Result<()> {
3610 context
3611 .sql
3612 .transaction(move |transaction| {
3613 transaction.execute(
3617 "UPDATE chats_contacts
3618 SET remove_timestamp=MAX(add_timestamp+1, ?)
3619 WHERE chat_id=?",
3620 (timestamp, id),
3621 )?;
3622
3623 if !contacts.is_empty() {
3624 let mut statement = transaction.prepare(
3625 "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp)
3626 VALUES (?1, ?2, ?3)
3627 ON CONFLICT (chat_id, contact_id)
3628 DO UPDATE SET add_timestamp=remove_timestamp",
3629 )?;
3630
3631 for contact_id in contacts {
3632 statement.execute((id, contact_id, timestamp))?;
3636 }
3637 }
3638 Ok(())
3639 })
3640 .await?;
3641 Ok(())
3642}
3643
3644pub(crate) async fn add_to_chat_contacts_table(
3646 context: &Context,
3647 timestamp: i64,
3648 chat_id: ChatId,
3649 contact_ids: &[ContactId],
3650) -> Result<()> {
3651 context
3652 .sql
3653 .transaction(move |transaction| {
3654 let mut add_statement = transaction.prepare(
3655 "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp) VALUES(?1, ?2, ?3)
3656 ON CONFLICT (chat_id, contact_id)
3657 DO UPDATE SET add_timestamp=MAX(remove_timestamp, ?3)",
3658 )?;
3659
3660 for contact_id in contact_ids {
3661 add_statement.execute((chat_id, contact_id, timestamp))?;
3662 }
3663 Ok(())
3664 })
3665 .await?;
3666
3667 Ok(())
3668}
3669
3670pub(crate) async fn remove_from_chat_contacts_table(
3673 context: &Context,
3674 chat_id: ChatId,
3675 contact_id: ContactId,
3676) -> Result<()> {
3677 let now = time();
3678 context
3679 .sql
3680 .execute(
3681 "UPDATE chats_contacts
3682 SET remove_timestamp=MAX(add_timestamp+1, ?)
3683 WHERE chat_id=? AND contact_id=?",
3684 (now, chat_id, contact_id),
3685 )
3686 .await?;
3687 Ok(())
3688}
3689
3690pub(crate) async fn remove_from_chat_contacts_table_without_trace(
3698 context: &Context,
3699 chat_id: ChatId,
3700 contact_id: ContactId,
3701) -> Result<()> {
3702 context
3703 .sql
3704 .execute(
3705 "DELETE FROM chats_contacts
3706 WHERE chat_id=? AND contact_id=?",
3707 (chat_id, contact_id),
3708 )
3709 .await?;
3710
3711 Ok(())
3712}
3713
3714pub async fn add_contact_to_chat(
3717 context: &Context,
3718 chat_id: ChatId,
3719 contact_id: ContactId,
3720) -> Result<()> {
3721 add_contact_to_chat_ex(context, Sync, chat_id, contact_id, false).await?;
3722 Ok(())
3723}
3724
3725pub(crate) async fn add_contact_to_chat_ex(
3726 context: &Context,
3727 mut sync: sync::Sync,
3728 chat_id: ChatId,
3729 contact_id: ContactId,
3730 from_handshake: bool,
3731) -> Result<bool> {
3732 ensure!(!chat_id.is_special(), "can not add member to special chats");
3733 let contact = Contact::get_by_id(context, contact_id).await?;
3734 let mut msg = Message::new(Viewtype::default());
3735
3736 chat_id.reset_gossiped_timestamp(context).await?;
3737
3738 let mut chat = Chat::load_from_db(context, chat_id).await?;
3740 ensure!(
3741 chat.typ == Chattype::Group || (from_handshake && chat.typ == Chattype::OutBroadcast),
3742 "{chat_id} is not a group where one can add members",
3743 );
3744 ensure!(
3745 Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF,
3746 "invalid contact_id {contact_id} for adding to group"
3747 );
3748 ensure!(
3749 chat.typ != Chattype::OutBroadcast || contact_id != ContactId::SELF,
3750 "Cannot add SELF to broadcast channel."
3751 );
3752 match chat.is_encrypted(context).await? {
3753 true => ensure!(
3754 contact.is_key_contact(),
3755 "Only key-contacts can be added to encrypted chats"
3756 ),
3757 false => ensure!(
3758 !contact.is_key_contact(),
3759 "Only address-contacts can be added to unencrypted chats"
3760 ),
3761 }
3762
3763 if !chat.is_self_in_chat(context).await? {
3764 context.emit_event(EventType::ErrorSelfNotInGroup(
3765 "Cannot add contact to group; self not in group.".into(),
3766 ));
3767 warn!(
3768 context,
3769 "Can not add contact because the account is not part of the group/broadcast."
3770 );
3771 return Ok(false);
3772 }
3773
3774 let sync_qr_code_tokens;
3775 if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {
3776 chat.param
3777 .remove(Param::Unpromoted)
3778 .set_i64(Param::GroupNameTimestamp, smeared_time(context));
3779 chat.update_param(context).await?;
3780 sync_qr_code_tokens = true;
3781 } else {
3782 sync_qr_code_tokens = false;
3783 }
3784
3785 if context.is_self_addr(contact.get_addr()).await? {
3786 warn!(
3789 context,
3790 "Invalid attempt to add self e-mail address to group."
3791 );
3792 return Ok(false);
3793 }
3794
3795 if is_contact_in_chat(context, chat_id, contact_id).await? {
3796 if !from_handshake {
3797 return Ok(true);
3798 }
3799 } else {
3800 add_to_chat_contacts_table(context, time(), chat_id, &[contact_id]).await?;
3802 }
3803 if chat.is_promoted() {
3804 msg.viewtype = Viewtype::Text;
3805
3806 let contact_addr = contact.get_addr().to_lowercase();
3807 let added_by = if from_handshake && chat.typ == Chattype::OutBroadcast {
3808 ContactId::UNDEFINED
3813 } else {
3814 ContactId::SELF
3815 };
3816 msg.text = stock_str::msg_add_member_local(context, contact.id, added_by).await;
3817 msg.param.set_cmd(SystemMessage::MemberAddedToGroup);
3818 msg.param.set(Param::Arg, contact_addr);
3819 msg.param.set_int(Param::Arg2, from_handshake.into());
3820 let fingerprint = contact.fingerprint().map(|f| f.hex());
3821 msg.param.set_optional(Param::Arg4, fingerprint);
3822 msg.param
3823 .set_int(Param::ContactAddedRemoved, contact.id.to_u32() as i32);
3824 if chat.typ == Chattype::OutBroadcast {
3825 let secret = load_broadcast_secret(context, chat_id)
3826 .await?
3827 .context("Failed to find broadcast shared secret")?;
3828 msg.param.set(PARAM_BROADCAST_SECRET, secret);
3829 }
3830 send_msg(context, chat_id, &mut msg).await?;
3831
3832 sync = Nosync;
3833 if sync_qr_code_tokens
3839 && context
3840 .sync_qr_code_tokens(Some(chat.grpid.as_str()))
3841 .await
3842 .log_err(context)
3843 .is_ok()
3844 {
3845 context.scheduler.interrupt_smtp().await;
3846 }
3847 }
3848 context.emit_event(EventType::ChatModified(chat_id));
3849 if sync.into() {
3850 chat.sync_contacts(context).await.log_err(context).ok();
3851 }
3852 Ok(true)
3853}
3854
3855pub(crate) async fn shall_attach_selfavatar(context: &Context, chat_id: ChatId) -> Result<bool> {
3861 let timestamp_some_days_ago = time() - DC_RESEND_USER_AVATAR_DAYS * 24 * 60 * 60;
3862 let needs_attach = context
3863 .sql
3864 .query_map(
3865 "SELECT c.selfavatar_sent
3866 FROM chats_contacts cc
3867 LEFT JOIN contacts c ON c.id=cc.contact_id
3868 WHERE cc.chat_id=? AND cc.contact_id!=? AND cc.add_timestamp >= cc.remove_timestamp",
3869 (chat_id, ContactId::SELF),
3870 |row| {
3871 let selfavatar_sent: i64 = row.get(0)?;
3872 Ok(selfavatar_sent)
3873 },
3874 |rows| {
3875 let mut needs_attach = false;
3876 for row in rows {
3877 let selfavatar_sent = row?;
3878 if selfavatar_sent < timestamp_some_days_ago {
3879 needs_attach = true;
3880 }
3881 }
3882 Ok(needs_attach)
3883 },
3884 )
3885 .await?;
3886 Ok(needs_attach)
3887}
3888
3889#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
3891pub enum MuteDuration {
3892 NotMuted,
3894
3895 Forever,
3897
3898 Until(std::time::SystemTime),
3900}
3901
3902impl rusqlite::types::ToSql for MuteDuration {
3903 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
3904 let duration: i64 = match &self {
3905 MuteDuration::NotMuted => 0,
3906 MuteDuration::Forever => -1,
3907 MuteDuration::Until(when) => {
3908 let duration = when
3909 .duration_since(SystemTime::UNIX_EPOCH)
3910 .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
3911 i64::try_from(duration.as_secs())
3912 .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?
3913 }
3914 };
3915 let val = rusqlite::types::Value::Integer(duration);
3916 let out = rusqlite::types::ToSqlOutput::Owned(val);
3917 Ok(out)
3918 }
3919}
3920
3921impl rusqlite::types::FromSql for MuteDuration {
3922 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
3923 match i64::column_result(value)? {
3926 0 => Ok(MuteDuration::NotMuted),
3927 -1 => Ok(MuteDuration::Forever),
3928 n if n > 0 => match SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(n as u64)) {
3929 Some(t) => Ok(MuteDuration::Until(t)),
3930 None => Err(rusqlite::types::FromSqlError::OutOfRange(n)),
3931 },
3932 _ => Ok(MuteDuration::NotMuted),
3933 }
3934 }
3935}
3936
3937pub async fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuration) -> Result<()> {
3939 set_muted_ex(context, Sync, chat_id, duration).await
3940}
3941
3942pub(crate) async fn set_muted_ex(
3943 context: &Context,
3944 sync: sync::Sync,
3945 chat_id: ChatId,
3946 duration: MuteDuration,
3947) -> Result<()> {
3948 ensure!(!chat_id.is_special(), "Invalid chat ID");
3949 context
3950 .sql
3951 .execute(
3952 "UPDATE chats SET muted_until=? WHERE id=?;",
3953 (duration, chat_id),
3954 )
3955 .await
3956 .context(format!("Failed to set mute duration for {chat_id}"))?;
3957 context.emit_event(EventType::ChatModified(chat_id));
3958 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3959 if sync.into() {
3960 let chat = Chat::load_from_db(context, chat_id).await?;
3961 chat.sync(context, SyncAction::SetMuted(duration))
3962 .await
3963 .log_err(context)
3964 .ok();
3965 }
3966 Ok(())
3967}
3968
3969pub async fn remove_contact_from_chat(
3971 context: &Context,
3972 chat_id: ChatId,
3973 contact_id: ContactId,
3974) -> Result<()> {
3975 ensure!(
3976 !chat_id.is_special(),
3977 "bad chat_id, can not be special chat: {chat_id}"
3978 );
3979 ensure!(
3980 !contact_id.is_special() || contact_id == ContactId::SELF,
3981 "Cannot remove special contact"
3982 );
3983
3984 let chat = Chat::load_from_db(context, chat_id).await?;
3985 if chat.typ == Chattype::InBroadcast {
3986 ensure!(
3987 contact_id == ContactId::SELF,
3988 "Cannot remove other member from incoming broadcast channel"
3989 );
3990 delete_broadcast_secret(context, chat_id).await?;
3991 }
3992
3993 if matches!(
3994 chat.typ,
3995 Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast
3996 ) {
3997 if !chat.is_self_in_chat(context).await? {
3998 let err_msg = format!(
3999 "Cannot remove contact {contact_id} from chat {chat_id}: self not in group."
4000 );
4001 context.emit_event(EventType::ErrorSelfNotInGroup(err_msg.clone()));
4002 bail!("{err_msg}");
4003 } else {
4004 let mut sync = Nosync;
4005
4006 if chat.is_promoted() {
4007 remove_from_chat_contacts_table(context, chat_id, contact_id).await?;
4008 } else {
4009 remove_from_chat_contacts_table_without_trace(context, chat_id, contact_id).await?;
4010 }
4011
4012 if let Some(contact) = Contact::get_by_id_optional(context, contact_id).await? {
4016 if chat.is_promoted() {
4017 let addr = contact.get_addr();
4018 let fingerprint = contact.fingerprint().map(|f| f.hex());
4019
4020 let res = send_member_removal_msg(
4021 context,
4022 &chat,
4023 contact_id,
4024 addr,
4025 fingerprint.as_deref(),
4026 )
4027 .await;
4028
4029 if contact_id == ContactId::SELF {
4030 res?;
4031 } else if let Err(e) = res {
4032 warn!(
4033 context,
4034 "remove_contact_from_chat({chat_id}, {contact_id}): send_msg() failed: {e:#}."
4035 );
4036 }
4037 } else {
4038 sync = Sync;
4039 }
4040 }
4041 context.emit_event(EventType::ChatModified(chat_id));
4042 if sync.into() {
4043 chat.sync_contacts(context).await.log_err(context).ok();
4044 }
4045 }
4046 } else {
4047 bail!("Cannot remove members from non-group chats.");
4048 }
4049
4050 Ok(())
4051}
4052
4053async fn send_member_removal_msg(
4054 context: &Context,
4055 chat: &Chat,
4056 contact_id: ContactId,
4057 addr: &str,
4058 fingerprint: Option<&str>,
4059) -> Result<MsgId> {
4060 let mut msg = Message::new(Viewtype::Text);
4061
4062 if contact_id == ContactId::SELF {
4063 if chat.typ == Chattype::InBroadcast {
4064 msg.text = stock_str::msg_you_left_broadcast(context).await;
4065 } else {
4066 msg.text = stock_str::msg_group_left_local(context, ContactId::SELF).await;
4067 }
4068 } else {
4069 msg.text = stock_str::msg_del_member_local(context, contact_id, ContactId::SELF).await;
4070 }
4071
4072 msg.param.set_cmd(SystemMessage::MemberRemovedFromGroup);
4073 msg.param.set(Param::Arg, addr.to_lowercase());
4074 msg.param.set_optional(Param::Arg4, fingerprint);
4075 msg.param
4076 .set(Param::ContactAddedRemoved, contact_id.to_u32());
4077
4078 send_msg(context, chat.id, &mut msg).await
4079}
4080
4081pub async fn set_chat_name(context: &Context, chat_id: ChatId, new_name: &str) -> Result<()> {
4083 rename_ex(context, Sync, chat_id, new_name).await
4084}
4085
4086async fn rename_ex(
4087 context: &Context,
4088 mut sync: sync::Sync,
4089 chat_id: ChatId,
4090 new_name: &str,
4091) -> Result<()> {
4092 let new_name = sanitize_single_line(new_name);
4093 let mut success = false;
4095
4096 ensure!(!new_name.is_empty(), "Invalid name");
4097 ensure!(!chat_id.is_special(), "Invalid chat ID");
4098
4099 let chat = Chat::load_from_db(context, chat_id).await?;
4100 let mut msg = Message::new(Viewtype::default());
4101
4102 if chat.typ == Chattype::Group
4103 || chat.typ == Chattype::Mailinglist
4104 || chat.typ == Chattype::OutBroadcast
4105 {
4106 if chat.name == new_name {
4107 success = true;
4108 } else if !chat.is_self_in_chat(context).await? {
4109 context.emit_event(EventType::ErrorSelfNotInGroup(
4110 "Cannot set chat name; self not in group".into(),
4111 ));
4112 } else {
4113 context
4114 .sql
4115 .execute(
4116 "UPDATE chats SET name=?, name_normalized=? WHERE id=?",
4117 (&new_name, normalize_text(&new_name), chat_id),
4118 )
4119 .await?;
4120 if chat.is_promoted()
4121 && !chat.is_mailing_list()
4122 && sanitize_single_line(&chat.name) != new_name
4123 {
4124 msg.viewtype = Viewtype::Text;
4125 msg.text =
4126 stock_str::msg_grp_name(context, &chat.name, &new_name, ContactId::SELF).await;
4127 msg.param.set_cmd(SystemMessage::GroupNameChanged);
4128 if !chat.name.is_empty() {
4129 msg.param.set(Param::Arg, &chat.name);
4130 }
4131 msg.id = send_msg(context, chat_id, &mut msg).await?;
4132 context.emit_msgs_changed(chat_id, msg.id);
4133 sync = Nosync;
4134 }
4135 context.emit_event(EventType::ChatModified(chat_id));
4136 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4137 success = true;
4138 }
4139 }
4140
4141 if !success {
4142 bail!("Failed to set name");
4143 }
4144 if sync.into() && chat.name != new_name {
4145 let sync_name = new_name.to_string();
4146 chat.sync(context, SyncAction::Rename(sync_name))
4147 .await
4148 .log_err(context)
4149 .ok();
4150 }
4151 Ok(())
4152}
4153
4154pub async fn set_chat_profile_image(
4160 context: &Context,
4161 chat_id: ChatId,
4162 new_image: &str, ) -> Result<()> {
4164 ensure!(!chat_id.is_special(), "Invalid chat ID");
4165 let mut chat = Chat::load_from_db(context, chat_id).await?;
4166 ensure!(
4167 chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4168 "Can only set profile image for groups / broadcasts"
4169 );
4170 ensure!(
4171 !chat.grpid.is_empty(),
4172 "Cannot set profile image for ad hoc groups"
4173 );
4174 if !chat.is_self_in_chat(context).await? {
4176 context.emit_event(EventType::ErrorSelfNotInGroup(
4177 "Cannot set chat profile image; self not in group.".into(),
4178 ));
4179 bail!("Failed to set profile image");
4180 }
4181 let mut msg = Message::new(Viewtype::Text);
4182 msg.param
4183 .set_int(Param::Cmd, SystemMessage::GroupImageChanged as i32);
4184 if new_image.is_empty() {
4185 chat.param.remove(Param::ProfileImage);
4186 msg.param.remove(Param::Arg);
4187 msg.text = stock_str::msg_grp_img_deleted(context, ContactId::SELF).await;
4188 } else {
4189 let mut image_blob = BlobObject::create_and_deduplicate(
4190 context,
4191 Path::new(new_image),
4192 Path::new(new_image),
4193 )?;
4194 image_blob.recode_to_avatar_size(context).await?;
4195 chat.param.set(Param::ProfileImage, image_blob.as_name());
4196 msg.param.set(Param::Arg, image_blob.as_name());
4197 msg.text = stock_str::msg_grp_img_changed(context, ContactId::SELF).await;
4198 }
4199 chat.update_param(context).await?;
4200 if chat.is_promoted() {
4201 msg.id = send_msg(context, chat_id, &mut msg).await?;
4202 context.emit_msgs_changed(chat_id, msg.id);
4203 }
4204 context.emit_event(EventType::ChatModified(chat_id));
4205 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4206 Ok(())
4207}
4208
4209pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) -> Result<()> {
4211 forward_msgs_2ctx(context, msg_ids, context, chat_id).await
4212}
4213
4214pub async fn forward_msgs_2ctx(
4216 ctx_src: &Context,
4217 msg_ids: &[MsgId],
4218 ctx_dst: &Context,
4219 chat_id: ChatId,
4220) -> Result<()> {
4221 ensure!(!msg_ids.is_empty(), "empty msgs_ids: nothing to forward");
4222 ensure!(!chat_id.is_special(), "can not forward to special chat");
4223
4224 let mut created_msgs: Vec<MsgId> = Vec::new();
4225 let mut curr_timestamp: i64;
4226
4227 chat_id
4228 .unarchive_if_not_muted(ctx_dst, MessageState::Undefined)
4229 .await?;
4230 let mut chat = Chat::load_from_db(ctx_dst, chat_id).await?;
4231 if let Some(reason) = chat.why_cant_send(ctx_dst).await? {
4232 bail!("cannot send to {chat_id}: {reason}");
4233 }
4234 curr_timestamp = create_smeared_timestamps(ctx_dst, msg_ids.len());
4235 let mut msgs = Vec::with_capacity(msg_ids.len());
4236 for id in msg_ids {
4237 let ts: i64 = ctx_src
4238 .sql
4239 .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4240 .await?
4241 .with_context(|| format!("No message {id}"))?;
4242 msgs.push((ts, *id));
4243 }
4244 msgs.sort_unstable();
4245 for (_, id) in msgs {
4246 let src_msg_id: MsgId = id;
4247 let mut msg = Message::load_from_db(ctx_src, src_msg_id).await?;
4248 if msg.state == MessageState::OutDraft {
4249 bail!("cannot forward drafts.");
4250 }
4251
4252 let mut param = msg.param;
4253 msg.param = Params::new();
4254
4255 if msg.get_viewtype() != Viewtype::Sticker {
4256 msg.param
4257 .set_int(Param::Forwarded, src_msg_id.to_u32() as i32);
4258 }
4259
4260 if msg.get_viewtype() == Viewtype::Call {
4261 msg.viewtype = Viewtype::Text;
4262 }
4263
4264 let param = &mut param;
4265 msg.param.steal(param, Param::File);
4266 msg.param.steal(param, Param::Filename);
4267 msg.param.steal(param, Param::Width);
4268 msg.param.steal(param, Param::Height);
4269 msg.param.steal(param, Param::Duration);
4270 msg.param.steal(param, Param::MimeType);
4271 msg.param.steal(param, Param::ProtectQuote);
4272 msg.param.steal(param, Param::Quote);
4273 msg.param.steal(param, Param::Summary1);
4274 msg.in_reply_to = None;
4275
4276 msg.subject = "".to_string();
4278
4279 msg.state = MessageState::OutPending;
4280 msg.rfc724_mid = create_outgoing_rfc724_mid();
4281 msg.timestamp_sort = curr_timestamp;
4282 chat.prepare_msg_raw(ctx_dst, &mut msg, None).await?;
4283
4284 curr_timestamp += 1;
4285 if !create_send_msg_jobs(ctx_dst, &mut msg).await?.is_empty() {
4286 ctx_dst.scheduler.interrupt_smtp().await;
4287 }
4288 created_msgs.push(msg.id);
4289 }
4290 for msg_id in created_msgs {
4291 ctx_dst.emit_msgs_changed(chat_id, msg_id);
4292 }
4293 Ok(())
4294}
4295
4296pub async fn save_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4299 let mut msgs = Vec::with_capacity(msg_ids.len());
4300 for id in msg_ids {
4301 let ts: i64 = context
4302 .sql
4303 .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4304 .await?
4305 .with_context(|| format!("No message {id}"))?;
4306 msgs.push((ts, *id));
4307 }
4308 msgs.sort_unstable();
4309 for (_, src_msg_id) in msgs {
4310 let dest_rfc724_mid = create_outgoing_rfc724_mid();
4311 let src_rfc724_mid = save_copy_in_self_talk(context, src_msg_id, &dest_rfc724_mid).await?;
4312 context
4313 .add_sync_item(SyncData::SaveMessage {
4314 src: src_rfc724_mid,
4315 dest: dest_rfc724_mid,
4316 })
4317 .await?;
4318 }
4319 context.scheduler.interrupt_smtp().await;
4320 Ok(())
4321}
4322
4323pub(crate) async fn save_copy_in_self_talk(
4329 context: &Context,
4330 src_msg_id: MsgId,
4331 dest_rfc724_mid: &String,
4332) -> Result<String> {
4333 let dest_chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?;
4334 let mut msg = Message::load_from_db(context, src_msg_id).await?;
4335 msg.param.remove(Param::Cmd);
4336 msg.param.remove(Param::WebxdcDocument);
4337 msg.param.remove(Param::WebxdcDocumentTimestamp);
4338 msg.param.remove(Param::WebxdcSummary);
4339 msg.param.remove(Param::WebxdcSummaryTimestamp);
4340
4341 if !msg.original_msg_id.is_unset() {
4342 bail!("message already saved.");
4343 }
4344
4345 let copy_fields = "from_id, to_id, timestamp_rcvd, type, txt,
4346 mime_modified, mime_headers, mime_compressed, mime_in_reply_to, subject, msgrmsg";
4347 let row_id = context
4348 .sql
4349 .insert(
4350 &format!(
4351 "INSERT INTO msgs ({copy_fields},
4352 timestamp_sent,
4353 chat_id, rfc724_mid, state, timestamp, param, starred)
4354 SELECT {copy_fields},
4355 -- Outgoing messages on originating device
4356 -- have timestamp_sent == 0.
4357 -- We copy sort timestamp instead
4358 -- so UIs display the same timestamp
4359 -- for saved and original message.
4360 IIF(timestamp_sent == 0, timestamp, timestamp_sent),
4361 ?, ?, ?, ?, ?, ?
4362 FROM msgs WHERE id=?;"
4363 ),
4364 (
4365 dest_chat_id,
4366 dest_rfc724_mid,
4367 if msg.from_id == ContactId::SELF {
4368 MessageState::OutDelivered
4369 } else {
4370 MessageState::InSeen
4371 },
4372 create_smeared_timestamp(context),
4373 msg.param.to_string(),
4374 src_msg_id,
4375 src_msg_id,
4376 ),
4377 )
4378 .await?;
4379 let dest_msg_id = MsgId::new(row_id.try_into()?);
4380
4381 context.emit_msgs_changed(msg.chat_id, src_msg_id);
4382 context.emit_msgs_changed(dest_chat_id, dest_msg_id);
4383 chatlist_events::emit_chatlist_changed(context);
4384 chatlist_events::emit_chatlist_item_changed(context, dest_chat_id);
4385
4386 Ok(msg.rfc724_mid)
4387}
4388
4389pub async fn resend_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4393 let mut msgs: Vec<Message> = Vec::new();
4394 for msg_id in msg_ids {
4395 let msg = Message::load_from_db(context, *msg_id).await?;
4396 ensure!(
4397 msg.from_id == ContactId::SELF,
4398 "can resend only own messages"
4399 );
4400 ensure!(!msg.is_info(), "cannot resend info messages");
4401 msgs.push(msg)
4402 }
4403
4404 for mut msg in msgs {
4405 match msg.get_state() {
4406 MessageState::OutPending
4408 | MessageState::OutFailed
4409 | MessageState::OutDelivered
4410 | MessageState::OutMdnRcvd => {
4411 message::update_msg_state(context, msg.id, MessageState::OutPending).await?
4412 }
4413 msg_state => bail!("Unexpected message state {msg_state}"),
4414 }
4415 msg.timestamp_sort = create_smeared_timestamp(context);
4416 if create_send_msg_jobs(context, &mut msg).await?.is_empty() {
4417 continue;
4418 }
4419
4420 context.emit_event(EventType::MsgsChanged {
4424 chat_id: msg.chat_id,
4425 msg_id: msg.id,
4426 });
4427 chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
4429
4430 if msg.viewtype == Viewtype::Webxdc {
4431 let conn_fn = |conn: &mut rusqlite::Connection| {
4432 let range = conn.query_row(
4433 "SELECT IFNULL(min(id), 1), IFNULL(max(id), 0) \
4434 FROM msgs_status_updates WHERE msg_id=?",
4435 (msg.id,),
4436 |row| {
4437 let min_id: StatusUpdateSerial = row.get(0)?;
4438 let max_id: StatusUpdateSerial = row.get(1)?;
4439 Ok((min_id, max_id))
4440 },
4441 )?;
4442 if range.0 > range.1 {
4443 return Ok(());
4444 };
4445 conn.execute(
4449 "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) \
4450 VALUES(?, ?, ?, '') \
4451 ON CONFLICT(msg_id) \
4452 DO UPDATE SET first_serial=min(first_serial - 1, excluded.first_serial)",
4453 (msg.id, range.0, range.1),
4454 )?;
4455 Ok(())
4456 };
4457 context.sql.call_write(conn_fn).await?;
4458 }
4459 context.scheduler.interrupt_smtp().await;
4460 }
4461 Ok(())
4462}
4463
4464pub(crate) async fn get_chat_cnt(context: &Context) -> Result<usize> {
4465 if context.sql.is_open().await {
4466 let count = context
4468 .sql
4469 .count("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;", ())
4470 .await?;
4471 Ok(count)
4472 } else {
4473 Ok(0)
4474 }
4475}
4476
4477pub(crate) async fn get_chat_id_by_grpid(
4479 context: &Context,
4480 grpid: &str,
4481) -> Result<Option<(ChatId, Blocked)>> {
4482 context
4483 .sql
4484 .query_row_optional(
4485 "SELECT id, blocked FROM chats WHERE grpid=?;",
4486 (grpid,),
4487 |row| {
4488 let chat_id = row.get::<_, ChatId>(0)?;
4489
4490 let b = row.get::<_, Option<Blocked>>(1)?.unwrap_or_default();
4491 Ok((chat_id, b))
4492 },
4493 )
4494 .await
4495}
4496
4497pub async fn add_device_msg_with_importance(
4502 context: &Context,
4503 label: Option<&str>,
4504 msg: Option<&mut Message>,
4505 important: bool,
4506) -> Result<MsgId> {
4507 ensure!(
4508 label.is_some() || msg.is_some(),
4509 "device-messages need label, msg or both"
4510 );
4511 let mut chat_id = ChatId::new(0);
4512 let mut msg_id = MsgId::new_unset();
4513
4514 if let Some(label) = label
4515 && was_device_msg_ever_added(context, label).await?
4516 {
4517 info!(context, "Device-message {label} already added.");
4518 return Ok(msg_id);
4519 }
4520
4521 if let Some(msg) = msg {
4522 chat_id = ChatId::get_for_contact(context, ContactId::DEVICE).await?;
4523
4524 let rfc724_mid = create_outgoing_rfc724_mid();
4525 let timestamp_sent = create_smeared_timestamp(context);
4526
4527 msg.timestamp_sort = timestamp_sent;
4530 if let Some(last_msg_time) = chat_id.get_timestamp(context).await?
4531 && msg.timestamp_sort <= last_msg_time
4532 {
4533 msg.timestamp_sort = last_msg_time + 1;
4534 }
4535 prepare_msg_blob(context, msg).await?;
4536 let state = MessageState::InFresh;
4537 let row_id = context
4538 .sql
4539 .insert(
4540 "INSERT INTO msgs (
4541 chat_id,
4542 from_id,
4543 to_id,
4544 timestamp,
4545 timestamp_sent,
4546 timestamp_rcvd,
4547 type,state,
4548 txt,
4549 txt_normalized,
4550 param,
4551 rfc724_mid)
4552 VALUES (?,?,?,?,?,?,?,?,?,?,?,?);",
4553 (
4554 chat_id,
4555 ContactId::DEVICE,
4556 ContactId::SELF,
4557 msg.timestamp_sort,
4558 timestamp_sent,
4559 timestamp_sent, msg.viewtype,
4561 state,
4562 &msg.text,
4563 normalize_text(&msg.text),
4564 msg.param.to_string(),
4565 rfc724_mid,
4566 ),
4567 )
4568 .await?;
4569 context.new_msgs_notify.notify_one();
4570
4571 msg_id = MsgId::new(u32::try_from(row_id)?);
4572 if !msg.hidden {
4573 chat_id.unarchive_if_not_muted(context, state).await?;
4574 }
4575 }
4576
4577 if let Some(label) = label {
4578 context
4579 .sql
4580 .execute("INSERT INTO devmsglabels (label) VALUES (?);", (label,))
4581 .await?;
4582 }
4583
4584 if !msg_id.is_unset() {
4585 chat_id.emit_msg_event(context, msg_id, important);
4586 }
4587
4588 Ok(msg_id)
4589}
4590
4591pub async fn add_device_msg(
4593 context: &Context,
4594 label: Option<&str>,
4595 msg: Option<&mut Message>,
4596) -> Result<MsgId> {
4597 add_device_msg_with_importance(context, label, msg, false).await
4598}
4599
4600pub async fn was_device_msg_ever_added(context: &Context, label: &str) -> Result<bool> {
4602 ensure!(!label.is_empty(), "empty label");
4603 let exists = context
4604 .sql
4605 .exists(
4606 "SELECT COUNT(label) FROM devmsglabels WHERE label=?",
4607 (label,),
4608 )
4609 .await?;
4610
4611 Ok(exists)
4612}
4613
4614pub(crate) async fn delete_and_reset_all_device_msgs(context: &Context) -> Result<()> {
4622 context
4623 .sql
4624 .execute("DELETE FROM msgs WHERE from_id=?;", (ContactId::DEVICE,))
4625 .await?;
4626 context.sql.execute("DELETE FROM devmsglabels;", ()).await?;
4627
4628 context
4630 .sql
4631 .execute(
4632 r#"INSERT INTO devmsglabels (label) VALUES ("core-welcome-image"), ("core-welcome")"#,
4633 (),
4634 )
4635 .await?;
4636 context
4637 .set_config_internal(Config::QuotaExceeding, None)
4638 .await?;
4639 Ok(())
4640}
4641
4642#[expect(clippy::too_many_arguments)]
4647pub(crate) async fn add_info_msg_with_cmd(
4648 context: &Context,
4649 chat_id: ChatId,
4650 text: &str,
4651 cmd: SystemMessage,
4652 timestamp_sort: Option<i64>,
4655 timestamp_sent_rcvd: i64,
4657 parent: Option<&Message>,
4658 from_id: Option<ContactId>,
4659 added_removed_id: Option<ContactId>,
4660) -> Result<MsgId> {
4661 let rfc724_mid = create_outgoing_rfc724_mid();
4662 let ephemeral_timer = chat_id.get_ephemeral_timer(context).await?;
4663
4664 let mut param = Params::new();
4665 if cmd != SystemMessage::Unknown {
4666 param.set_cmd(cmd);
4667 }
4668 if let Some(contact_id) = added_removed_id {
4669 param.set(Param::ContactAddedRemoved, contact_id.to_u32().to_string());
4670 }
4671
4672 let timestamp_sort = if let Some(ts) = timestamp_sort {
4673 ts
4674 } else {
4675 let sort_to_bottom = true;
4676 let (received, incoming) = (false, false);
4677 chat_id
4678 .calc_sort_timestamp(
4679 context,
4680 smeared_time(context),
4681 sort_to_bottom,
4682 received,
4683 incoming,
4684 )
4685 .await?
4686 };
4687
4688 let row_id =
4689 context.sql.insert(
4690 "INSERT INTO msgs (chat_id,from_id,to_id,timestamp,timestamp_sent,timestamp_rcvd,type,state,txt,txt_normalized,rfc724_mid,ephemeral_timer,param,mime_in_reply_to)
4691 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);",
4692 (
4693 chat_id,
4694 from_id.unwrap_or(ContactId::INFO),
4695 ContactId::INFO,
4696 timestamp_sort,
4697 timestamp_sent_rcvd,
4698 timestamp_sent_rcvd,
4699 Viewtype::Text,
4700 MessageState::InNoticed,
4701 text,
4702 normalize_text(text),
4703 rfc724_mid,
4704 ephemeral_timer,
4705 param.to_string(),
4706 parent.map(|msg|msg.rfc724_mid.clone()).unwrap_or_default()
4707 )
4708 ).await?;
4709 context.new_msgs_notify.notify_one();
4710
4711 let msg_id = MsgId::new(row_id.try_into()?);
4712 context.emit_msgs_changed(chat_id, msg_id);
4713
4714 Ok(msg_id)
4715}
4716
4717pub(crate) async fn add_info_msg(context: &Context, chat_id: ChatId, text: &str) -> Result<MsgId> {
4719 add_info_msg_with_cmd(
4720 context,
4721 chat_id,
4722 text,
4723 SystemMessage::Unknown,
4724 None,
4725 time(),
4726 None,
4727 None,
4728 None,
4729 )
4730 .await
4731}
4732
4733pub(crate) async fn update_msg_text_and_timestamp(
4734 context: &Context,
4735 chat_id: ChatId,
4736 msg_id: MsgId,
4737 text: &str,
4738 timestamp: i64,
4739) -> Result<()> {
4740 context
4741 .sql
4742 .execute(
4743 "UPDATE msgs SET txt=?, txt_normalized=?, timestamp=? WHERE id=?;",
4744 (text, normalize_text(text), timestamp, msg_id),
4745 )
4746 .await?;
4747 context.emit_msgs_changed(chat_id, msg_id);
4748 Ok(())
4749}
4750
4751async fn set_contacts_by_addrs(context: &Context, id: ChatId, addrs: &[String]) -> Result<()> {
4753 let chat = Chat::load_from_db(context, id).await?;
4754 ensure!(
4755 !chat.is_encrypted(context).await?,
4756 "Cannot add address-contacts to encrypted chat {id}"
4757 );
4758 ensure!(
4759 chat.typ == Chattype::OutBroadcast,
4760 "{id} is not a broadcast list",
4761 );
4762 let mut contacts = HashSet::new();
4763 for addr in addrs {
4764 let contact_addr = ContactAddress::new(addr)?;
4765 let contact = Contact::add_or_lookup(context, "", &contact_addr, Origin::Hidden)
4766 .await?
4767 .0;
4768 contacts.insert(contact);
4769 }
4770 let contacts_old = HashSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
4771 if contacts == contacts_old {
4772 return Ok(());
4773 }
4774 context
4775 .sql
4776 .transaction(move |transaction| {
4777 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
4778
4779 let mut statement = transaction
4782 .prepare("INSERT INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)")?;
4783 for contact_id in &contacts {
4784 statement.execute((id, contact_id))?;
4785 }
4786 Ok(())
4787 })
4788 .await?;
4789 context.emit_event(EventType::ChatModified(id));
4790 Ok(())
4791}
4792
4793async fn set_contacts_by_fingerprints(
4797 context: &Context,
4798 id: ChatId,
4799 fingerprint_addrs: &[(String, String)],
4800) -> Result<()> {
4801 let chat = Chat::load_from_db(context, id).await?;
4802 ensure!(
4803 chat.is_encrypted(context).await?,
4804 "Cannot add key-contacts to unencrypted chat {id}"
4805 );
4806 ensure!(
4807 matches!(chat.typ, Chattype::Group | Chattype::OutBroadcast),
4808 "{id} is not a group or broadcast",
4809 );
4810 let mut contacts = HashSet::new();
4811 for (fingerprint, addr) in fingerprint_addrs {
4812 let contact = Contact::add_or_lookup_ex(context, "", addr, fingerprint, Origin::Hidden)
4813 .await?
4814 .0;
4815 contacts.insert(contact);
4816 }
4817 let contacts_old = HashSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
4818 if contacts == contacts_old {
4819 return Ok(());
4820 }
4821 context
4822 .sql
4823 .transaction(move |transaction| {
4824 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
4825
4826 let mut statement = transaction
4829 .prepare("INSERT INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)")?;
4830 for contact_id in &contacts {
4831 statement.execute((id, contact_id))?;
4832 }
4833 Ok(())
4834 })
4835 .await?;
4836 context.emit_event(EventType::ChatModified(id));
4837 Ok(())
4838}
4839
4840#[derive(Debug, Serialize, Deserialize, PartialEq)]
4842pub(crate) enum SyncId {
4843 ContactAddr(String),
4845
4846 ContactFingerprint(String),
4848
4849 Grpid(String),
4850 Msgids(Vec<String>),
4852
4853 Device,
4855}
4856
4857#[derive(Debug, Serialize, Deserialize, PartialEq)]
4859pub(crate) enum SyncAction {
4860 Block,
4861 Unblock,
4862 Accept,
4863 SetVisibility(ChatVisibility),
4864 SetMuted(MuteDuration),
4865 CreateOutBroadcast {
4867 chat_name: String,
4868 secret: String,
4869 },
4870 CreateGroupEncrypted(String),
4872 Rename(String),
4873 SetContacts(Vec<String>),
4875 SetPgpContacts(Vec<(String, String)>),
4879 Delete,
4880}
4881
4882impl Context {
4883 pub(crate) async fn sync_alter_chat(&self, id: &SyncId, action: &SyncAction) -> Result<()> {
4885 let chat_id = match id {
4886 SyncId::ContactAddr(addr) => {
4887 if let SyncAction::Rename(to) = action {
4888 Contact::create_ex(self, Nosync, to, addr).await?;
4889 return Ok(());
4890 }
4891 let addr = ContactAddress::new(addr).context("Invalid address")?;
4892 let (contact_id, _) =
4893 Contact::add_or_lookup(self, "", &addr, Origin::Hidden).await?;
4894 match action {
4895 SyncAction::Block => {
4896 return contact::set_blocked(self, Nosync, contact_id, true).await;
4897 }
4898 SyncAction::Unblock => {
4899 return contact::set_blocked(self, Nosync, contact_id, false).await;
4900 }
4901 _ => (),
4902 }
4903 ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
4906 .await?
4907 .id
4908 }
4909 SyncId::ContactFingerprint(fingerprint) => {
4910 let name = "";
4911 let addr = "";
4912 let (contact_id, _) =
4913 Contact::add_or_lookup_ex(self, name, addr, fingerprint, Origin::Hidden)
4914 .await?;
4915 match action {
4916 SyncAction::Rename(to) => {
4917 contact_id.set_name_ex(self, Nosync, to).await?;
4918 self.emit_event(EventType::ContactsChanged(Some(contact_id)));
4919 return Ok(());
4920 }
4921 SyncAction::Block => {
4922 return contact::set_blocked(self, Nosync, contact_id, true).await;
4923 }
4924 SyncAction::Unblock => {
4925 return contact::set_blocked(self, Nosync, contact_id, false).await;
4926 }
4927 _ => (),
4928 }
4929 ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
4930 .await?
4931 .id
4932 }
4933 SyncId::Grpid(grpid) => {
4934 match action {
4935 SyncAction::CreateOutBroadcast { chat_name, secret } => {
4936 create_out_broadcast_ex(
4937 self,
4938 Nosync,
4939 grpid.to_string(),
4940 chat_name.clone(),
4941 secret.to_string(),
4942 )
4943 .await?;
4944 return Ok(());
4945 }
4946 SyncAction::CreateGroupEncrypted(name) => {
4947 create_group_ex(self, Nosync, grpid.clone(), name).await?;
4948 return Ok(());
4949 }
4950 _ => {}
4951 }
4952 get_chat_id_by_grpid(self, grpid)
4953 .await?
4954 .with_context(|| format!("No chat for grpid '{grpid}'"))?
4955 .0
4956 }
4957 SyncId::Msgids(msgids) => {
4958 let msg = message::get_by_rfc724_mids(self, msgids)
4959 .await?
4960 .with_context(|| format!("No message found for Message-IDs {msgids:?}"))?;
4961 ChatId::lookup_by_message(&msg)
4962 .with_context(|| format!("No chat found for Message-IDs {msgids:?}"))?
4963 }
4964 SyncId::Device => ChatId::get_for_contact(self, ContactId::DEVICE).await?,
4965 };
4966 match action {
4967 SyncAction::Block => chat_id.block_ex(self, Nosync).await,
4968 SyncAction::Unblock => chat_id.unblock_ex(self, Nosync).await,
4969 SyncAction::Accept => chat_id.accept_ex(self, Nosync).await,
4970 SyncAction::SetVisibility(v) => chat_id.set_visibility_ex(self, Nosync, *v).await,
4971 SyncAction::SetMuted(duration) => set_muted_ex(self, Nosync, chat_id, *duration).await,
4972 SyncAction::CreateOutBroadcast { .. } | SyncAction::CreateGroupEncrypted(..) => {
4973 Err(anyhow!("sync_alter_chat({id:?}, {action:?}): Bad request."))
4975 }
4976 SyncAction::Rename(to) => rename_ex(self, Nosync, chat_id, to).await,
4977 SyncAction::SetContacts(addrs) => set_contacts_by_addrs(self, chat_id, addrs).await,
4978 SyncAction::SetPgpContacts(fingerprint_addrs) => {
4979 set_contacts_by_fingerprints(self, chat_id, fingerprint_addrs).await
4980 }
4981 SyncAction::Delete => chat_id.delete_ex(self, Nosync).await,
4982 }
4983 }
4984
4985 pub(crate) fn on_archived_chats_maybe_noticed(&self) {
4990 self.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
4991 }
4992}
4993
4994#[cfg(test)]
4995mod chat_tests;