1use std::cmp;
4use std::collections::{BTreeSet, HashMap};
5use std::fmt;
6use std::io::Cursor;
7use std::marker::Sync;
8use std::path::{Path, PathBuf};
9use std::time::Duration;
10
11use anyhow::{Context as _, Result, anyhow, bail, ensure};
12use chrono::TimeZone;
13use deltachat_contact_tools::{ContactAddress, sanitize_bidi_characters, sanitize_single_line};
14use humansize::{BINARY, format_size};
15use mail_builder::mime::MimePart;
16use serde::{Deserialize, Serialize};
17use strum_macros::EnumIter;
18
19use crate::blob::BlobObject;
20use crate::chatlist::Chatlist;
21use crate::chatlist_events;
22use crate::color::str_to_color;
23use crate::config::Config;
24use crate::constants::{
25 self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,
26 DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, EDITED_PREFIX,
27 TIMESTAMP_SENT_TOLERANCE,
28};
29use crate::contact::{self, Contact, ContactId, Origin};
30use crate::context::Context;
31use crate::debug_logging::maybe_set_logging_xdc;
32use crate::download::{
33 DownloadState, PRE_MSG_ATTACHMENT_SIZE_THRESHOLD, PRE_MSG_SIZE_WARNING_THRESHOLD,
34};
35use crate::ensure_and_debug_assert_eq;
36use crate::ephemeral::{Timer as EphemeralTimer, start_chat_ephemeral_timers};
37use crate::events::EventType;
38use crate::key::{Fingerprint, self_fingerprint};
39use crate::location;
40use crate::log::{LogExt, warn};
41use crate::logged_debug_assert;
42use crate::message::{self, Message, MessageState, MsgId, Viewtype};
43use crate::mimefactory::{MimeFactory, RenderedEmail};
44use crate::mimeparser::SystemMessage;
45use crate::param::{Param, Params};
46use crate::pgp::addresses_from_public_key;
47use crate::receive_imf::ReceivedMsg;
48use crate::smtp::{self, send_msg_to_smtp};
49use crate::stock_str;
50use crate::sync::{self, Sync::*, SyncData};
51use crate::tools::{
52 IsNoneOrEmpty, SystemTime, buf_compress, create_broadcast_secret, create_id,
53 create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path,
54 gm2local_offset, normalize_text, smeared_time, time, truncate_msg_text,
55};
56use crate::webxdc::StatusUpdateSerial;
57
58pub(crate) const PARAM_BROADCAST_SECRET: Param = Param::Arg3;
59
60#[derive(Debug, Copy, Clone, PartialEq, Eq)]
62pub enum ChatItem {
63 Message {
65 msg_id: MsgId,
67 },
68
69 DayMarker {
72 timestamp: i64,
74 },
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub(crate) enum CantSendReason {
82 SpecialChat,
84
85 DeviceChat,
87
88 ContactRequest,
90
91 ReadOnlyMailingList,
93
94 InBroadcast,
96
97 NotAMember,
99
100 MissingKey,
102}
103
104impl fmt::Display for CantSendReason {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 match self {
107 Self::SpecialChat => write!(f, "the chat is a special chat"),
108 Self::DeviceChat => write!(f, "the chat is a device chat"),
109 Self::ContactRequest => write!(
110 f,
111 "contact request chat should be accepted before sending messages"
112 ),
113 Self::ReadOnlyMailingList => {
114 write!(f, "mailing list does not have a know post address")
115 }
116 Self::InBroadcast => {
117 write!(f, "Broadcast channel is read-only")
118 }
119 Self::NotAMember => write!(f, "not a member of the chat"),
120 Self::MissingKey => write!(f, "key is missing"),
121 }
122 }
123}
124
125#[derive(
130 Debug, Copy, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Hash, PartialOrd, Ord,
131)]
132pub struct ChatId(u32);
133
134impl ChatId {
135 pub const fn new(id: u32) -> ChatId {
137 ChatId(id)
138 }
139
140 pub fn is_unset(self) -> bool {
144 self.0 == 0
145 }
146
147 pub fn is_special(self) -> bool {
151 (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)
152 }
153
154 pub fn is_trash(self) -> bool {
161 self == DC_CHAT_ID_TRASH
162 }
163
164 pub fn is_archived_link(self) -> bool {
171 self == DC_CHAT_ID_ARCHIVED_LINK
172 }
173
174 pub fn is_alldone_hint(self) -> bool {
183 self == DC_CHAT_ID_ALLDONE_HINT
184 }
185
186 pub(crate) fn lookup_by_message(msg: &Message) -> Option<Self> {
188 if msg.chat_id == DC_CHAT_ID_TRASH {
189 return None;
190 }
191 if msg.download_state == DownloadState::Undecipherable {
192 return None;
193 }
194 Some(msg.chat_id)
195 }
196
197 pub async fn lookup_by_contact(
202 context: &Context,
203 contact_id: ContactId,
204 ) -> Result<Option<Self>> {
205 let Some(chat_id_blocked) = ChatIdBlocked::lookup_by_contact(context, contact_id).await?
206 else {
207 return Ok(None);
208 };
209
210 let chat_id = match chat_id_blocked.blocked {
211 Blocked::Not | Blocked::Request => Some(chat_id_blocked.id),
212 Blocked::Yes => None,
213 };
214 Ok(chat_id)
215 }
216
217 pub(crate) async fn get_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
225 ChatIdBlocked::get_for_contact(context, contact_id, Blocked::Not)
226 .await
227 .map(|chat| chat.id)
228 }
229
230 pub async fn create_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
235 ChatId::create_for_contact_with_blocked(context, contact_id, Blocked::Not).await
236 }
237
238 pub(crate) async fn create_for_contact_with_blocked(
242 context: &Context,
243 contact_id: ContactId,
244 create_blocked: Blocked,
245 ) -> Result<Self> {
246 let chat_id = match ChatIdBlocked::lookup_by_contact(context, contact_id).await? {
247 Some(chat) => {
248 if create_blocked != Blocked::Not || chat.blocked == Blocked::Not {
249 return Ok(chat.id);
250 }
251 chat.id.set_blocked(context, Blocked::Not).await?;
252 chat.id
253 }
254 None => {
255 if Contact::real_exists_by_id(context, contact_id).await?
256 || contact_id == ContactId::SELF
257 {
258 let chat_id =
259 ChatIdBlocked::get_for_contact(context, contact_id, create_blocked)
260 .await
261 .map(|chat| chat.id)?;
262 if create_blocked != Blocked::Yes {
263 info!(context, "Scale up origin of {contact_id} to CreateChat.");
264 ContactId::scaleup_origin(context, &[contact_id], Origin::CreateChat)
265 .await?;
266 }
267 chat_id
268 } else {
269 warn!(
270 context,
271 "Cannot create chat, contact {contact_id} does not exist."
272 );
273 bail!("Can not create chat for non-existing contact");
274 }
275 }
276 };
277 context.emit_msgs_changed_without_ids();
278 chatlist_events::emit_chatlist_changed(context);
279 chatlist_events::emit_chatlist_item_changed(context, chat_id);
280 Ok(chat_id)
281 }
282
283 pub(crate) async fn create_multiuser_record(
286 context: &Context,
287 chattype: Chattype,
288 grpid: &str,
289 grpname: &str,
290 create_blocked: Blocked,
291 param: Option<String>,
292 timestamp: i64,
293 ) -> Result<Self> {
294 let grpname = sanitize_single_line(grpname);
295 let timestamp = cmp::min(timestamp, smeared_time(context));
296 let row_id =
297 context.sql.insert(
298 "INSERT INTO chats (type, name, name_normalized, grpid, blocked, created_timestamp, protected, param) VALUES(?, ?, ?, ?, ?, ?, 0, ?)",
299 (
300 chattype,
301 &grpname,
302 normalize_text(&grpname),
303 grpid,
304 create_blocked,
305 timestamp,
306 param.unwrap_or_default(),
307 ),
308 ).await?;
309
310 let chat_id = ChatId::new(u32::try_from(row_id)?);
311 let chat = Chat::load_from_db(context, chat_id).await?;
312
313 if chat.is_encrypted(context).await? {
314 chat_id.add_e2ee_notice(context, timestamp).await?;
315 }
316
317 info!(
318 context,
319 "Created group/broadcast '{}' grpid={} as {}, blocked={}.",
320 &grpname,
321 grpid,
322 chat_id,
323 create_blocked,
324 );
325
326 Ok(chat_id)
327 }
328
329 async fn set_selfavatar_timestamp(self, context: &Context, timestamp: i64) -> Result<()> {
330 context
331 .sql
332 .execute(
333 "UPDATE contacts
334 SET selfavatar_sent=?
335 WHERE id IN(SELECT contact_id FROM chats_contacts WHERE chat_id=? AND add_timestamp >= remove_timestamp)",
336 (timestamp, self),
337 )
338 .await?;
339 Ok(())
340 }
341
342 pub(crate) async fn set_blocked(self, context: &Context, new_blocked: Blocked) -> Result<bool> {
346 if self.is_special() {
347 bail!("ignoring setting of Block-status for {self}");
348 }
349 let count = context
350 .sql
351 .execute(
352 "UPDATE chats SET blocked=?1 WHERE id=?2 AND blocked != ?1",
353 (new_blocked, self),
354 )
355 .await?;
356 Ok(count > 0)
357 }
358
359 pub async fn block(self, context: &Context) -> Result<()> {
361 self.block_ex(context, Sync).await
362 }
363
364 pub(crate) async fn block_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
365 let chat = Chat::load_from_db(context, self).await?;
366 let mut delete = false;
367
368 match chat.typ {
369 Chattype::OutBroadcast => {
370 bail!("Can't block chat of type {:?}", chat.typ)
371 }
372 Chattype::Single => {
373 for contact_id in get_chat_contacts(context, self).await? {
374 if contact_id != ContactId::SELF {
375 info!(
376 context,
377 "Blocking the contact {contact_id} to block 1:1 chat."
378 );
379 contact::set_blocked(context, Nosync, contact_id, true).await?;
380 }
381 }
382 }
383 Chattype::Group => {
384 info!(context, "Can't block groups yet, deleting the chat.");
385 delete = true;
386 }
387 Chattype::Mailinglist | Chattype::InBroadcast => {
388 if self.set_blocked(context, Blocked::Yes).await? {
389 context.emit_event(EventType::ChatModified(self));
390 }
391 }
392 }
393 chatlist_events::emit_chatlist_changed(context);
394
395 if sync.into() {
396 chat.sync(context, SyncAction::Block)
398 .await
399 .log_err(context)
400 .ok();
401 }
402 if delete {
403 self.delete_ex(context, Nosync).await?;
404 }
405 Ok(())
406 }
407
408 pub async fn unblock(self, context: &Context) -> Result<()> {
410 self.unblock_ex(context, Sync).await
411 }
412
413 pub(crate) async fn unblock_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
414 self.set_blocked(context, Blocked::Not).await?;
415
416 chatlist_events::emit_chatlist_changed(context);
417
418 if sync.into() {
419 let chat = Chat::load_from_db(context, self).await?;
420 chat.sync(context, SyncAction::Unblock)
424 .await
425 .log_err(context)
426 .ok();
427 }
428
429 Ok(())
430 }
431
432 pub async fn accept(self, context: &Context) -> Result<()> {
436 self.accept_ex(context, Sync).await
437 }
438
439 pub(crate) async fn accept_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
440 let chat = Chat::load_from_db(context, self).await?;
441
442 match chat.typ {
443 Chattype::Single | Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast => {
444 let origin = match chat.typ {
450 Chattype::Group => Origin::IncomingTo,
451 _ => Origin::CreateChat,
452 };
453 for contact_id in get_chat_contacts(context, self).await? {
454 if contact_id != ContactId::SELF {
455 ContactId::scaleup_origin(context, &[contact_id], origin).await?;
456 }
457 }
458 }
459 Chattype::Mailinglist => {
460 }
462 }
463
464 if self.set_blocked(context, Blocked::Not).await? {
465 context.emit_event(EventType::ChatModified(self));
466 chatlist_events::emit_chatlist_item_changed(context, self);
467 }
468
469 if sync.into() {
470 chat.sync(context, SyncAction::Accept)
471 .await
472 .log_err(context)
473 .ok();
474 }
475 Ok(())
476 }
477
478 pub(crate) async fn add_e2ee_notice(self, context: &Context, timestamp: i64) -> Result<()> {
480 let text = stock_str::messages_e2ee_info_msg(context);
481
482 let sort_timestamp = 0;
486 add_info_msg_with_cmd(
487 context,
488 self,
489 &text,
490 SystemMessage::ChatE2ee,
491 Some(sort_timestamp),
492 timestamp,
493 None,
494 None,
495 None,
496 )
497 .await?;
498 Ok(())
499 }
500
501 pub(crate) async fn add_start_info_message(self, context: &Context, text: &str) -> Result<()> {
506 let sort_timestamp = 0;
507 add_info_msg_with_cmd(
508 context,
509 self,
510 text,
511 SystemMessage::Unknown,
512 Some(sort_timestamp),
513 time(),
514 None,
515 None,
516 None,
517 )
518 .await?;
519 Ok(())
520 }
521
522 pub async fn set_visibility(self, context: &Context, visibility: ChatVisibility) -> Result<()> {
524 self.set_visibility_ex(context, Sync, visibility).await
525 }
526
527 pub(crate) async fn set_visibility_ex(
528 self,
529 context: &Context,
530 sync: sync::Sync,
531 visibility: ChatVisibility,
532 ) -> Result<()> {
533 ensure!(
534 !self.is_special(),
535 "bad chat_id, can not be special chat: {self}"
536 );
537
538 context
539 .sql
540 .transaction(move |transaction| {
541 if visibility == ChatVisibility::Archived {
542 transaction.execute(
543 "UPDATE msgs SET state=? WHERE chat_id=? AND state=?;",
544 (MessageState::InNoticed, self, MessageState::InFresh),
545 )?;
546 }
547 transaction.execute(
548 "UPDATE chats SET archived=? WHERE id=?;",
549 (visibility, self),
550 )?;
551 Ok(())
552 })
553 .await?;
554
555 if visibility == ChatVisibility::Archived {
556 start_chat_ephemeral_timers(context, self).await?;
557 }
558
559 context.emit_msgs_changed_without_ids();
560 chatlist_events::emit_chatlist_changed(context);
561 chatlist_events::emit_chatlist_item_changed(context, self);
562
563 if sync.into() {
564 let chat = Chat::load_from_db(context, self).await?;
565 chat.sync(context, SyncAction::SetVisibility(visibility))
566 .await
567 .log_err(context)
568 .ok();
569 }
570 Ok(())
571 }
572
573 pub async fn unarchive_if_not_muted(
581 self,
582 context: &Context,
583 msg_state: MessageState,
584 ) -> Result<()> {
585 if msg_state != MessageState::InFresh {
586 context
587 .sql
588 .execute(
589 "UPDATE chats SET archived=0 WHERE id=? AND archived=1 \
590 AND NOT(muted_until=-1 OR muted_until>?)",
591 (self, time()),
592 )
593 .await?;
594 return Ok(());
595 }
596 let chat = Chat::load_from_db(context, self).await?;
597 if chat.visibility != ChatVisibility::Archived {
598 return Ok(());
599 }
600 if chat.is_muted() {
601 let unread_cnt = context
602 .sql
603 .count(
604 "SELECT COUNT(*)
605 FROM msgs
606 WHERE state=?
607 AND hidden=0
608 AND chat_id=?",
609 (MessageState::InFresh, self),
610 )
611 .await?;
612 if unread_cnt == 1 {
613 context.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
615 }
616 return Ok(());
617 }
618 context
619 .sql
620 .execute("UPDATE chats SET archived=0 WHERE id=?", (self,))
621 .await?;
622 Ok(())
623 }
624
625 pub(crate) fn emit_msg_event(self, context: &Context, msg_id: MsgId, important: bool) {
628 if important {
629 debug_assert!(!msg_id.is_unset());
630
631 context.emit_incoming_msg(self, msg_id);
632 } else {
633 context.emit_msgs_changed(self, msg_id);
634 }
635 }
636
637 pub async fn delete(self, context: &Context) -> Result<()> {
643 self.delete_ex(context, Sync).await
644 }
645
646 pub(crate) async fn delete_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
647 ensure!(
648 !self.is_special(),
649 "bad chat_id, can not be a special chat: {self}"
650 );
651
652 let chat = Chat::load_from_db(context, self).await?;
653 let sync_id = match sync {
654 Nosync => None,
655 Sync => chat.get_sync_id(context).await?,
656 };
657
658 context
659 .sql
660 .transaction(|transaction| {
661 transaction.execute(
662 "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT rfc724_mid FROM msgs WHERE chat_id=? AND rfc724_mid!='')",
663 (self,),
664 )?;
665 transaction.execute(
666 "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT pre_rfc724_mid FROM msgs WHERE chat_id=? AND pre_rfc724_mid!='')",
667 (self,),
668 )?;
669 transaction.execute(
670 "DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?)",
671 (self,),
672 )?;
673 transaction.execute(
676 "
677INSERT OR REPLACE INTO msgs (id, rfc724_mid, pre_rfc724_mid, timestamp, chat_id, deleted)
678SELECT id, rfc724_mid, pre_rfc724_mid, timestamp, ?, 1 FROM msgs WHERE chat_id=?
679 ",
680 (DC_CHAT_ID_TRASH, self),
681 )?;
682 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (self,))?;
683 transaction.execute("DELETE FROM chats WHERE id=?", (self,))?;
684 Ok(())
685 })
686 .await?;
687
688 context.emit_event(EventType::ChatDeleted { chat_id: self });
689 context.emit_msgs_changed_without_ids();
690
691 if let Some(id) = sync_id {
692 self::sync(context, id, SyncAction::Delete)
693 .await
694 .log_err(context)
695 .ok();
696 }
697
698 if chat.is_self_talk() {
699 let mut msg = Message::new_text(stock_str::self_deleted_msg_body(context));
700 add_device_msg(context, None, Some(&mut msg)).await?;
701 }
702 chatlist_events::emit_chatlist_changed(context);
703
704 context
705 .set_config_internal(Config::LastHousekeeping, None)
706 .await?;
707 context.scheduler.interrupt_smtp().await;
708
709 Ok(())
710 }
711
712 pub async fn set_draft(self, context: &Context, mut msg: Option<&mut Message>) -> Result<()> {
716 if self.is_special() {
717 return Ok(());
718 }
719
720 let changed = match &mut msg {
721 None => self.maybe_delete_draft(context).await?,
722 Some(msg) => self.do_set_draft(context, msg).await?,
723 };
724
725 if changed {
726 if msg.is_some() {
727 match self.get_draft_msg_id(context).await? {
728 Some(msg_id) => context.emit_msgs_changed(self, msg_id),
729 None => context.emit_msgs_changed_without_msg_id(self),
730 }
731 } else {
732 context.emit_msgs_changed_without_msg_id(self)
733 }
734 }
735
736 Ok(())
737 }
738
739 async fn get_draft_msg_id(self, context: &Context) -> Result<Option<MsgId>> {
741 let msg_id: Option<MsgId> = context
742 .sql
743 .query_get_value(
744 "SELECT id FROM msgs WHERE chat_id=? AND state=?;",
745 (self, MessageState::OutDraft),
746 )
747 .await?;
748 Ok(msg_id)
749 }
750
751 pub async fn get_draft(self, context: &Context) -> Result<Option<Message>> {
753 if self.is_special() {
754 return Ok(None);
755 }
756 match self.get_draft_msg_id(context).await? {
757 Some(draft_msg_id) => {
758 let msg = Message::load_from_db(context, draft_msg_id).await?;
759 Ok(Some(msg))
760 }
761 None => Ok(None),
762 }
763 }
764
765 async fn maybe_delete_draft(self, context: &Context) -> Result<bool> {
769 Ok(context
770 .sql
771 .execute(
772 "DELETE FROM msgs WHERE chat_id=? AND state=?",
773 (self, MessageState::OutDraft),
774 )
775 .await?
776 > 0)
777 }
778
779 async fn do_set_draft(self, context: &Context, msg: &mut Message) -> Result<bool> {
782 match msg.viewtype {
783 Viewtype::Unknown => bail!("Can not set draft of unknown type."),
784 Viewtype::Text => {
785 if msg.text.is_empty() && msg.in_reply_to.is_none_or_empty() {
786 bail!("No text and no quote in draft");
787 }
788 }
789 _ => {
790 if msg.viewtype == Viewtype::File
791 && let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg)
792 .filter(|&(vt, _)| vt == Viewtype::Webxdc || vt == Viewtype::Vcard)
797 {
798 msg.viewtype = better_type;
799 }
800 if msg.viewtype == Viewtype::Vcard {
801 let blob = msg
802 .param
803 .get_file_blob(context)?
804 .context("no file stored in params")?;
805 msg.try_set_vcard(context, &blob.to_abs_path()).await?;
806 }
807 }
808 }
809
810 msg.state = MessageState::OutDraft;
813 msg.chat_id = self;
814
815 if !msg.id.is_special()
817 && let Some(old_draft) = self.get_draft(context).await?
818 && old_draft.id == msg.id
819 && old_draft.chat_id == self
820 && old_draft.state == MessageState::OutDraft
821 {
822 let affected_rows = context
823 .sql.execute(
824 "UPDATE msgs
825 SET timestamp=?1,type=?2,txt=?3,txt_normalized=?4,param=?5,mime_in_reply_to=?6
826 WHERE id=?7
827 AND (type <> ?2
828 OR txt <> ?3
829 OR txt_normalized <> ?4
830 OR param <> ?5
831 OR mime_in_reply_to <> ?6);",
832 (
833 time(),
834 msg.viewtype,
835 &msg.text,
836 normalize_text(&msg.text),
837 msg.param.to_string(),
838 msg.in_reply_to.as_deref().unwrap_or_default(),
839 msg.id,
840 ),
841 ).await?;
842 return Ok(affected_rows > 0);
843 }
844
845 let row_id = context
846 .sql
847 .transaction(|transaction| {
848 transaction.execute(
850 "DELETE FROM msgs WHERE chat_id=? AND state=?",
851 (self, MessageState::OutDraft),
852 )?;
853
854 transaction.execute(
856 "INSERT INTO msgs (
857 chat_id,
858 rfc724_mid,
859 from_id,
860 timestamp,
861 type,
862 state,
863 txt,
864 txt_normalized,
865 param,
866 hidden,
867 mime_in_reply_to)
868 VALUES (?,?,?,?,?,?,?,?,?,?,?);",
869 (
870 self,
871 &msg.rfc724_mid,
872 ContactId::SELF,
873 time(),
874 msg.viewtype,
875 MessageState::OutDraft,
876 &msg.text,
877 normalize_text(&msg.text),
878 msg.param.to_string(),
879 1,
880 msg.in_reply_to.as_deref().unwrap_or_default(),
881 ),
882 )?;
883
884 Ok(transaction.last_insert_rowid())
885 })
886 .await?;
887 msg.id = MsgId::new(row_id.try_into()?);
888 Ok(true)
889 }
890
891 pub async fn get_msg_cnt(self, context: &Context) -> Result<usize> {
893 let count = context
894 .sql
895 .count(
896 "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id=?",
897 (self,),
898 )
899 .await?;
900 Ok(count)
901 }
902
903 pub async fn get_fresh_msg_cnt(self, context: &Context) -> Result<usize> {
905 let count = if self.is_archived_link() {
916 context
917 .sql
918 .count(
919 "SELECT COUNT(DISTINCT(m.chat_id))
920 FROM msgs m
921 LEFT JOIN chats c ON m.chat_id=c.id
922 WHERE m.state=10
923 and m.hidden=0
924 AND m.chat_id>9
925 AND c.blocked=0
926 AND c.archived=1
927 ",
928 (),
929 )
930 .await?
931 } else {
932 context
933 .sql
934 .count(
935 "SELECT COUNT(*)
936 FROM msgs
937 WHERE state=?
938 AND hidden=0
939 AND chat_id=?;",
940 (MessageState::InFresh, self),
941 )
942 .await?
943 };
944 Ok(count)
945 }
946
947 pub(crate) async fn created_timestamp(self, context: &Context) -> Result<i64> {
948 Ok(context
949 .sql
950 .query_get_value("SELECT created_timestamp FROM chats WHERE id=?", (self,))
951 .await?
952 .unwrap_or(0))
953 }
954
955 pub(crate) async fn join_timestamp(self, context: &Context) -> Result<Option<i64>> {
957 context
958 .sql
959 .query_get_value(
960 "SELECT add_timestamp FROM chats_contacts WHERE chat_id=? AND contact_id=?",
961 (self, ContactId::SELF),
962 )
963 .await
964 }
965
966 pub(crate) async fn get_timestamp(self, context: &Context) -> Result<Option<i64>> {
969 let timestamp = context
970 .sql
971 .query_get_value(
972 "SELECT MAX(timestamp)
973 FROM msgs
974 WHERE chat_id=?
975 HAVING COUNT(*) > 0",
976 (self,),
977 )
978 .await?;
979 Ok(timestamp)
980 }
981
982 #[expect(clippy::arithmetic_side_effects)]
988 pub async fn get_similar_chat_ids(self, context: &Context) -> Result<Vec<(ChatId, f64)>> {
989 let intersection = context
991 .sql
992 .query_map_vec(
993 "SELECT y.chat_id, SUM(x.contact_id = y.contact_id)
994 FROM chats_contacts as x
995 JOIN chats_contacts as y
996 WHERE x.contact_id > 9
997 AND y.contact_id > 9
998 AND x.add_timestamp >= x.remove_timestamp
999 AND y.add_timestamp >= y.remove_timestamp
1000 AND x.chat_id=?
1001 AND y.chat_id<>x.chat_id
1002 AND y.chat_id>?
1003 GROUP BY y.chat_id",
1004 (self, DC_CHAT_ID_LAST_SPECIAL),
1005 |row| {
1006 let chat_id: ChatId = row.get(0)?;
1007 let intersection: f64 = row.get(1)?;
1008 Ok((chat_id, intersection))
1009 },
1010 )
1011 .await
1012 .context("failed to calculate member set intersections")?;
1013
1014 let chat_size: HashMap<ChatId, f64> = context
1015 .sql
1016 .query_map_collect(
1017 "SELECT chat_id, count(*) AS n
1018 FROM chats_contacts
1019 WHERE contact_id > ? AND chat_id > ?
1020 AND add_timestamp >= remove_timestamp
1021 GROUP BY chat_id",
1022 (ContactId::LAST_SPECIAL, DC_CHAT_ID_LAST_SPECIAL),
1023 |row| {
1024 let chat_id: ChatId = row.get(0)?;
1025 let size: f64 = row.get(1)?;
1026 Ok((chat_id, size))
1027 },
1028 )
1029 .await
1030 .context("failed to count chat member sizes")?;
1031
1032 let our_chat_size = chat_size.get(&self).copied().unwrap_or_default();
1033 let mut chats_with_metrics = Vec::new();
1034 for (chat_id, intersection_size) in intersection {
1035 if intersection_size > 0.0 {
1036 let other_chat_size = chat_size.get(&chat_id).copied().unwrap_or_default();
1037 let union_size = our_chat_size + other_chat_size - intersection_size;
1038 let metric = intersection_size / union_size;
1039 chats_with_metrics.push((chat_id, metric))
1040 }
1041 }
1042 chats_with_metrics.sort_unstable_by(|(chat_id1, metric1), (chat_id2, metric2)| {
1043 metric2
1044 .partial_cmp(metric1)
1045 .unwrap_or(chat_id2.cmp(chat_id1))
1046 });
1047
1048 let mut res = Vec::new();
1050 let now = time();
1051 for (chat_id, metric) in chats_with_metrics {
1052 if let Some(chat_timestamp) = chat_id.get_timestamp(context).await?
1053 && now > chat_timestamp + 42 * 24 * 3600
1054 {
1055 continue;
1057 }
1058
1059 if metric < 0.1 {
1060 break;
1062 }
1063
1064 let chat = Chat::load_from_db(context, chat_id).await?;
1065 if chat.typ != Chattype::Group {
1066 continue;
1067 }
1068
1069 match chat.visibility {
1070 ChatVisibility::Normal | ChatVisibility::Pinned => {}
1071 ChatVisibility::Archived => continue,
1072 }
1073
1074 res.push((chat_id, metric));
1075 if res.len() >= 5 {
1076 break;
1077 }
1078 }
1079
1080 Ok(res)
1081 }
1082
1083 pub async fn get_similar_chatlist(self, context: &Context) -> Result<Chatlist> {
1087 let chat_ids: Vec<ChatId> = self
1088 .get_similar_chat_ids(context)
1089 .await
1090 .context("failed to get similar chat IDs")?
1091 .into_iter()
1092 .map(|(chat_id, _metric)| chat_id)
1093 .collect();
1094 let chatlist = Chatlist::from_chat_ids(context, &chat_ids).await?;
1095 Ok(chatlist)
1096 }
1097
1098 pub(crate) async fn get_param(self, context: &Context) -> Result<Params> {
1099 let res: Option<String> = context
1100 .sql
1101 .query_get_value("SELECT param FROM chats WHERE id=?", (self,))
1102 .await?;
1103 Ok(res
1104 .map(|s| s.parse().unwrap_or_default())
1105 .unwrap_or_default())
1106 }
1107
1108 pub(crate) async fn is_unpromoted(self, context: &Context) -> Result<bool> {
1110 let param = self.get_param(context).await?;
1111 let unpromoted = param.get_bool(Param::Unpromoted).unwrap_or_default();
1112 Ok(unpromoted)
1113 }
1114
1115 pub(crate) async fn is_promoted(self, context: &Context) -> Result<bool> {
1117 let promoted = !self.is_unpromoted(context).await?;
1118 Ok(promoted)
1119 }
1120
1121 pub async fn is_self_talk(self, context: &Context) -> Result<bool> {
1123 Ok(self.get_param(context).await?.exists(Param::Selftalk))
1124 }
1125
1126 pub async fn is_device_talk(self, context: &Context) -> Result<bool> {
1128 Ok(self.get_param(context).await?.exists(Param::Devicetalk))
1129 }
1130
1131 async fn parent_query<T, F>(
1132 self,
1133 context: &Context,
1134 fields: &str,
1135 state_out_min: MessageState,
1136 f: F,
1137 ) -> Result<Option<T>>
1138 where
1139 F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
1140 T: Send + 'static,
1141 {
1142 let sql = &context.sql;
1143 let query = format!(
1144 "SELECT {fields} \
1145 FROM msgs \
1146 WHERE chat_id=? \
1147 AND ((state BETWEEN {} AND {}) OR (state >= {})) \
1148 AND NOT hidden \
1149 AND download_state={} \
1150 AND from_id != {} \
1151 ORDER BY timestamp DESC, id DESC \
1152 LIMIT 1;",
1153 MessageState::InFresh as u32,
1154 MessageState::InSeen as u32,
1155 state_out_min as u32,
1156 DownloadState::Done as u32,
1159 ContactId::INFO.to_u32(),
1162 );
1163 sql.query_row_optional(&query, (self,), f).await
1164 }
1165
1166 async fn get_parent_mime_headers(
1167 self,
1168 context: &Context,
1169 state_out_min: MessageState,
1170 ) -> Result<Option<(String, String, String)>> {
1171 self.parent_query(
1172 context,
1173 "rfc724_mid, mime_in_reply_to, IFNULL(mime_references, '')",
1174 state_out_min,
1175 |row: &rusqlite::Row| {
1176 let rfc724_mid: String = row.get(0)?;
1177 let mime_in_reply_to: String = row.get(1)?;
1178 let mime_references: String = row.get(2)?;
1179 Ok((rfc724_mid, mime_in_reply_to, mime_references))
1180 },
1181 )
1182 .await
1183 }
1184
1185 pub async fn get_encryption_info(self, context: &Context) -> Result<String> {
1193 let chat = Chat::load_from_db(context, self).await?;
1194 if !chat.is_encrypted(context).await? {
1195 return Ok(stock_str::encr_none(context));
1196 }
1197
1198 let mut ret = stock_str::messages_are_e2ee(context) + "\n";
1199
1200 for &contact_id in get_chat_contacts(context, self)
1201 .await?
1202 .iter()
1203 .filter(|&contact_id| !contact_id.is_special())
1204 {
1205 let contact = Contact::get_by_id(context, contact_id).await?;
1206 let addr = contact.get_addr();
1207 logged_debug_assert!(
1208 context,
1209 contact.is_key_contact(),
1210 "get_encryption_info: contact {contact_id} is not a key-contact."
1211 );
1212 let fingerprint = contact
1213 .fingerprint()
1214 .context("Contact does not have a fingerprint in encrypted chat")?
1215 .human_readable();
1216 if let Some(public_key) = contact.public_key(context).await? {
1217 if let Some(relay_addrs) = addresses_from_public_key(&public_key) {
1218 let relays = relay_addrs.join(",");
1219 ret += &format!("\n{addr}({relays})\n{fingerprint}\n");
1220 } else {
1221 ret += &format!("\n{addr}\n{fingerprint}\n");
1222 }
1223 } else {
1224 ret += &format!("\n{addr}\n(key missing)\n{fingerprint}\n");
1225 }
1226 }
1227
1228 Ok(ret.trim().to_string())
1229 }
1230
1231 pub fn to_u32(self) -> u32 {
1236 self.0
1237 }
1238
1239 pub(crate) async fn reset_gossiped_timestamp(self, context: &Context) -> Result<()> {
1240 context
1241 .sql
1242 .execute("DELETE FROM gossip_timestamp WHERE chat_id=?", (self,))
1243 .await?;
1244 Ok(())
1245 }
1246
1247 pub(crate) async fn calc_sort_timestamp(
1254 self,
1255 context: &Context,
1256 message_timestamp: i64,
1257 always_sort_to_bottom: bool,
1258 ) -> Result<i64> {
1259 let mut sort_timestamp = cmp::min(message_timestamp, smeared_time(context));
1260
1261 let last_msg_time: Option<i64> = if always_sort_to_bottom {
1262 context
1268 .sql
1269 .query_get_value(
1270 "SELECT MAX(timestamp)
1271 FROM msgs
1272 WHERE chat_id=? AND state!=?
1273 HAVING COUNT(*) > 0",
1274 (self, MessageState::OutDraft),
1275 )
1276 .await?
1277 } else {
1278 None
1279 };
1280
1281 if let Some(last_msg_time) = last_msg_time
1282 && last_msg_time > sort_timestamp
1283 {
1284 sort_timestamp = last_msg_time;
1285 }
1286
1287 if let Some(join_timestamp) = self.join_timestamp(context).await? {
1288 Ok(std::cmp::max(sort_timestamp, join_timestamp))
1294 } else {
1295 Ok(sort_timestamp)
1296 }
1297 }
1298}
1299
1300impl std::fmt::Display for ChatId {
1301 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1302 if self.is_trash() {
1303 write!(f, "Chat#Trash")
1304 } else if self.is_archived_link() {
1305 write!(f, "Chat#ArchivedLink")
1306 } else if self.is_alldone_hint() {
1307 write!(f, "Chat#AlldoneHint")
1308 } else if self.is_special() {
1309 write!(f, "Chat#Special{}", self.0)
1310 } else {
1311 write!(f, "Chat#{}", self.0)
1312 }
1313 }
1314}
1315
1316impl rusqlite::types::ToSql for ChatId {
1321 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
1322 let val = rusqlite::types::Value::Integer(i64::from(self.0));
1323 let out = rusqlite::types::ToSqlOutput::Owned(val);
1324 Ok(out)
1325 }
1326}
1327
1328impl rusqlite::types::FromSql for ChatId {
1330 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
1331 i64::column_result(value).and_then(|val| {
1332 if 0 <= val && val <= i64::from(u32::MAX) {
1333 Ok(ChatId::new(val as u32))
1334 } else {
1335 Err(rusqlite::types::FromSqlError::OutOfRange(val))
1336 }
1337 })
1338 }
1339}
1340
1341#[derive(Debug, Clone, Deserialize, Serialize)]
1346pub struct Chat {
1347 pub id: ChatId,
1349
1350 pub typ: Chattype,
1352
1353 pub name: String,
1355
1356 pub visibility: ChatVisibility,
1358
1359 pub grpid: String,
1362
1363 pub blocked: Blocked,
1365
1366 pub param: Params,
1368
1369 is_sending_locations: bool,
1371
1372 pub mute_duration: MuteDuration,
1374}
1375
1376impl Chat {
1377 pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> {
1379 let mut chat = context
1380 .sql
1381 .query_row(
1382 "SELECT c.type, c.name, c.grpid, c.param, c.archived,
1383 c.blocked, c.locations_send_until, c.muted_until
1384 FROM chats c
1385 WHERE c.id=?;",
1386 (chat_id,),
1387 |row| {
1388 let c = Chat {
1389 id: chat_id,
1390 typ: row.get(0)?,
1391 name: row.get::<_, String>(1)?,
1392 grpid: row.get::<_, String>(2)?,
1393 param: row.get::<_, String>(3)?.parse().unwrap_or_default(),
1394 visibility: row.get(4)?,
1395 blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
1396 is_sending_locations: row.get(6)?,
1397 mute_duration: row.get(7)?,
1398 };
1399 Ok(c)
1400 },
1401 )
1402 .await
1403 .context(format!("Failed loading chat {chat_id} from database"))?;
1404
1405 if chat.id.is_archived_link() {
1406 chat.name = stock_str::archived_chats(context);
1407 } else {
1408 if chat.typ == Chattype::Single && chat.name.is_empty() {
1409 let mut chat_name = "Err [Name not found]".to_owned();
1412 match get_chat_contacts(context, chat.id).await {
1413 Ok(contacts) => {
1414 if let Some(contact_id) = contacts.first()
1415 && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1416 {
1417 contact.get_display_name().clone_into(&mut chat_name);
1418 }
1419 }
1420 Err(err) => {
1421 error!(
1422 context,
1423 "Failed to load contacts for {}: {:#}.", chat.id, err
1424 );
1425 }
1426 }
1427 chat.name = chat_name;
1428 }
1429 if chat.param.exists(Param::Selftalk) {
1430 chat.name = stock_str::saved_messages(context);
1431 } else if chat.param.exists(Param::Devicetalk) {
1432 chat.name = stock_str::device_messages(context);
1433 }
1434 }
1435
1436 Ok(chat)
1437 }
1438
1439 pub fn is_self_talk(&self) -> bool {
1441 self.param.exists(Param::Selftalk)
1442 }
1443
1444 pub fn is_device_talk(&self) -> bool {
1446 self.param.exists(Param::Devicetalk)
1447 }
1448
1449 pub fn is_mailing_list(&self) -> bool {
1451 self.typ == Chattype::Mailinglist
1452 }
1453
1454 pub(crate) async fn why_cant_send(&self, context: &Context) -> Result<Option<CantSendReason>> {
1458 self.why_cant_send_ex(context, &|_| false).await
1459 }
1460
1461 pub(crate) async fn why_cant_send_ex(
1462 &self,
1463 context: &Context,
1464 skip_fn: &(dyn Send + Sync + Fn(&CantSendReason) -> bool),
1465 ) -> Result<Option<CantSendReason>> {
1466 use CantSendReason::*;
1467 if self.id.is_special() {
1470 let reason = SpecialChat;
1471 if !skip_fn(&reason) {
1472 return Ok(Some(reason));
1473 }
1474 }
1475 if self.is_device_talk() {
1476 let reason = DeviceChat;
1477 if !skip_fn(&reason) {
1478 return Ok(Some(reason));
1479 }
1480 }
1481 if self.is_contact_request() {
1482 let reason = ContactRequest;
1483 if !skip_fn(&reason) {
1484 return Ok(Some(reason));
1485 }
1486 }
1487 if self.is_mailing_list() && self.get_mailinglist_addr().is_none_or_empty() {
1488 let reason = ReadOnlyMailingList;
1489 if !skip_fn(&reason) {
1490 return Ok(Some(reason));
1491 }
1492 }
1493 if self.typ == Chattype::InBroadcast {
1494 let reason = InBroadcast;
1495 if !skip_fn(&reason) {
1496 return Ok(Some(reason));
1497 }
1498 }
1499
1500 let reason = NotAMember;
1502 if !skip_fn(&reason) && !self.is_self_in_chat(context).await? {
1503 return Ok(Some(reason));
1504 }
1505
1506 let reason = MissingKey;
1507 if !skip_fn(&reason) && self.typ == Chattype::Single {
1508 let contact_ids = get_chat_contacts(context, self.id).await?;
1509 if let Some(contact_id) = contact_ids.first() {
1510 let contact = Contact::get_by_id(context, *contact_id).await?;
1511 if contact.is_key_contact() && contact.public_key(context).await?.is_none() {
1512 return Ok(Some(reason));
1513 }
1514 }
1515 }
1516
1517 Ok(None)
1518 }
1519
1520 pub async fn can_send(&self, context: &Context) -> Result<bool> {
1524 Ok(self.why_cant_send(context).await?.is_none())
1525 }
1526
1527 pub async fn is_self_in_chat(&self, context: &Context) -> Result<bool> {
1531 match self.typ {
1532 Chattype::Single | Chattype::OutBroadcast | Chattype::Mailinglist => Ok(true),
1533 Chattype::Group | Chattype::InBroadcast => {
1534 is_contact_in_chat(context, self.id, ContactId::SELF).await
1535 }
1536 }
1537 }
1538
1539 pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {
1540 context
1541 .sql
1542 .execute(
1543 "UPDATE chats SET param=? WHERE id=?",
1544 (self.param.to_string(), self.id),
1545 )
1546 .await?;
1547 Ok(())
1548 }
1549
1550 pub fn get_id(&self) -> ChatId {
1552 self.id
1553 }
1554
1555 pub fn get_type(&self) -> Chattype {
1557 self.typ
1558 }
1559
1560 pub fn get_name(&self) -> &str {
1562 &self.name
1563 }
1564
1565 pub fn get_mailinglist_addr(&self) -> Option<&str> {
1567 self.param.get(Param::ListPost)
1568 }
1569
1570 pub async fn get_profile_image(&self, context: &Context) -> Result<Option<PathBuf>> {
1572 if self.id.is_archived_link() {
1573 return Ok(Some(get_archive_icon(context).await?));
1576 } else if self.is_device_talk() {
1577 return Ok(Some(get_device_icon(context).await?));
1578 } else if self.is_self_talk() {
1579 return Ok(Some(get_saved_messages_icon(context).await?));
1580 } else if !self.is_encrypted(context).await? {
1581 return Ok(Some(get_abs_path(
1583 context,
1584 Path::new(&get_unencrypted_icon(context).await?),
1585 )));
1586 } else if self.typ == Chattype::Single {
1587 let contacts = get_chat_contacts(context, self.id).await?;
1591 if let Some(contact_id) = contacts.first() {
1592 let contact = Contact::get_by_id(context, *contact_id).await?;
1593 return contact.get_profile_image(context).await;
1594 }
1595 } else if let Some(image_rel) = self.param.get(Param::ProfileImage) {
1596 if !image_rel.is_empty() {
1598 return Ok(Some(get_abs_path(context, Path::new(&image_rel))));
1599 }
1600 }
1601 Ok(None)
1602 }
1603
1604 pub async fn get_color(&self, context: &Context) -> Result<u32> {
1610 let mut color = 0;
1611
1612 if self.typ == Chattype::Single {
1613 let contacts = get_chat_contacts(context, self.id).await?;
1614 if let Some(contact_id) = contacts.first()
1615 && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1616 {
1617 color = contact.get_color();
1618 }
1619 } else if !self.grpid.is_empty() {
1620 color = str_to_color(&self.grpid);
1621 } else {
1622 color = str_to_color(&self.name);
1623 }
1624
1625 Ok(color)
1626 }
1627
1628 pub async fn get_info(&self, context: &Context) -> Result<ChatInfo> {
1633 let draft = match self.id.get_draft(context).await? {
1634 Some(message) => message.text,
1635 _ => String::new(),
1636 };
1637 Ok(ChatInfo {
1638 id: self.id,
1639 type_: self.typ as u32,
1640 name: self.name.clone(),
1641 archived: self.visibility == ChatVisibility::Archived,
1642 param: self.param.to_string(),
1643 is_sending_locations: self.is_sending_locations,
1644 color: self.get_color(context).await?,
1645 profile_image: self
1646 .get_profile_image(context)
1647 .await?
1648 .unwrap_or_else(std::path::PathBuf::new),
1649 draft,
1650 is_muted: self.is_muted(),
1651 ephemeral_timer: self.id.get_ephemeral_timer(context).await?,
1652 })
1653 }
1654
1655 pub fn get_visibility(&self) -> ChatVisibility {
1657 self.visibility
1658 }
1659
1660 pub fn is_contact_request(&self) -> bool {
1665 self.blocked == Blocked::Request
1666 }
1667
1668 pub fn is_unpromoted(&self) -> bool {
1670 self.param.get_bool(Param::Unpromoted).unwrap_or_default()
1671 }
1672
1673 pub fn is_promoted(&self) -> bool {
1676 !self.is_unpromoted()
1677 }
1678
1679 pub async fn is_encrypted(&self, context: &Context) -> Result<bool> {
1681 let is_encrypted = self.is_self_talk()
1682 || match self.typ {
1683 Chattype::Single => {
1684 match context
1685 .sql
1686 .query_row_optional(
1687 "SELECT cc.contact_id, c.fingerprint<>''
1688 FROM chats_contacts cc LEFT JOIN contacts c
1689 ON c.id=cc.contact_id
1690 WHERE cc.chat_id=?
1691 ",
1692 (self.id,),
1693 |row| {
1694 let id: ContactId = row.get(0)?;
1695 let is_key: bool = row.get(1)?;
1696 Ok((id, is_key))
1697 },
1698 )
1699 .await?
1700 {
1701 Some((id, is_key)) => is_key || id == ContactId::DEVICE,
1702 None => true,
1703 }
1704 }
1705 Chattype::Group => {
1706 !self.grpid.is_empty()
1708 }
1709 Chattype::Mailinglist => false,
1710 Chattype::OutBroadcast | Chattype::InBroadcast => true,
1711 };
1712 Ok(is_encrypted)
1713 }
1714
1715 pub fn is_sending_locations(&self) -> bool {
1717 self.is_sending_locations
1718 }
1719
1720 pub fn is_muted(&self) -> bool {
1722 match self.mute_duration {
1723 MuteDuration::NotMuted => false,
1724 MuteDuration::Forever => true,
1725 MuteDuration::Until(when) => when > SystemTime::now(),
1726 }
1727 }
1728
1729 pub(crate) async fn member_list_timestamp(&self, context: &Context) -> Result<i64> {
1731 if let Some(member_list_timestamp) = self.param.get_i64(Param::MemberListTimestamp) {
1732 Ok(member_list_timestamp)
1733 } else {
1734 Ok(self.id.created_timestamp(context).await?)
1735 }
1736 }
1737
1738 pub(crate) async fn member_list_is_stale(&self, context: &Context) -> Result<bool> {
1744 let now = time();
1745 let member_list_ts = self.member_list_timestamp(context).await?;
1746 let is_stale = now.saturating_add(TIMESTAMP_SENT_TOLERANCE)
1747 >= member_list_ts.saturating_add(60 * 24 * 3600);
1748 Ok(is_stale)
1749 }
1750
1751 async fn prepare_msg_raw(
1757 &mut self,
1758 context: &Context,
1759 msg: &mut Message,
1760 update_msg_id: Option<MsgId>,
1761 ) -> Result<()> {
1762 let mut to_id = 0;
1763 let mut location_id = 0;
1764
1765 if msg.rfc724_mid.is_empty() {
1766 msg.rfc724_mid = create_outgoing_rfc724_mid();
1767 }
1768
1769 if self.typ == Chattype::Single {
1770 if let Some(id) = context
1771 .sql
1772 .query_get_value(
1773 "SELECT contact_id FROM chats_contacts WHERE chat_id=?;",
1774 (self.id,),
1775 )
1776 .await?
1777 {
1778 to_id = id;
1779 } else {
1780 error!(
1781 context,
1782 "Cannot send message, contact for {} not found.", self.id,
1783 );
1784 bail!("Cannot set message, contact for {} not found.", self.id);
1785 }
1786 } else if self.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {
1787 ensure_and_debug_assert_eq!(self.typ, Chattype::Group,);
1788 msg.param.set_int(Param::AttachChatAvatarAndDescription, 1);
1789 self.param
1790 .remove(Param::Unpromoted)
1791 .set_i64(Param::GroupNameTimestamp, msg.timestamp_sort)
1792 .set_i64(Param::GroupDescriptionTimestamp, msg.timestamp_sort);
1793 self.update_param(context).await?;
1794 }
1795
1796 let is_bot = context.get_config_bool(Config::Bot).await?;
1797 msg.param
1798 .set_optional(Param::Bot, Some("1").filter(|_| is_bot));
1799
1800 let new_references;
1804 if self.is_self_talk() {
1805 new_references = String::new();
1808 } else if let Some((parent_rfc724_mid, parent_in_reply_to, parent_references)) =
1809 self
1815 .id
1816 .get_parent_mime_headers(context, MessageState::OutPending)
1817 .await?
1818 {
1819 if msg.in_reply_to.is_none() && !parent_rfc724_mid.is_empty() {
1823 msg.in_reply_to = Some(parent_rfc724_mid.clone());
1824 }
1825
1826 let parent_references = if parent_references.is_empty() {
1836 parent_in_reply_to
1837 } else {
1838 parent_references
1839 };
1840
1841 let mut references_vec: Vec<&str> = parent_references.rsplit(' ').take(2).collect();
1844 references_vec.reverse();
1845
1846 if !parent_rfc724_mid.is_empty()
1847 && !references_vec.contains(&parent_rfc724_mid.as_str())
1848 {
1849 references_vec.push(&parent_rfc724_mid)
1850 }
1851
1852 if references_vec.is_empty() {
1853 new_references = msg.rfc724_mid.clone();
1856 } else {
1857 new_references = references_vec.join(" ");
1858 }
1859 } else {
1860 new_references = msg.rfc724_mid.clone();
1866 }
1867
1868 if msg.param.exists(Param::SetLatitude)
1870 && let Ok(row_id) = context
1871 .sql
1872 .insert(
1873 "INSERT INTO locations \
1874 (timestamp,from_id,chat_id, latitude,longitude,independent)\
1875 VALUES (?,?,?, ?,?,1);",
1876 (
1877 msg.timestamp_sort,
1878 ContactId::SELF,
1879 self.id,
1880 msg.param.get_float(Param::SetLatitude).unwrap_or_default(),
1881 msg.param.get_float(Param::SetLongitude).unwrap_or_default(),
1882 ),
1883 )
1884 .await
1885 {
1886 location_id = row_id;
1887 }
1888
1889 let ephemeral_timer = if msg.param.get_cmd() == SystemMessage::EphemeralTimerChanged {
1890 EphemeralTimer::Disabled
1891 } else {
1892 self.id.get_ephemeral_timer(context).await?
1893 };
1894 let ephemeral_timestamp = match ephemeral_timer {
1895 EphemeralTimer::Disabled => 0,
1896 EphemeralTimer::Enabled { duration } => time().saturating_add(duration.into()),
1897 };
1898
1899 let (msg_text, was_truncated) = truncate_msg_text(context, msg.text.clone()).await?;
1900 let new_mime_headers = if msg.has_html() {
1901 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1902 } else {
1903 None
1904 };
1905 let new_mime_headers: Option<String> = new_mime_headers.map(|s| {
1906 let html_part = MimePart::new("text/html", s);
1907 let mut buffer = Vec::new();
1908 let cursor = Cursor::new(&mut buffer);
1909 html_part.write_part(cursor).ok();
1910 String::from_utf8_lossy(&buffer).to_string()
1911 });
1912 let new_mime_headers = new_mime_headers.or_else(|| match was_truncated {
1913 true => Some("Content-Type: text/plain; charset=utf-8\r\n\r\n".to_string() + &msg.text),
1917 false => None,
1918 });
1919 let new_mime_headers = match new_mime_headers {
1920 Some(h) => Some(tokio::task::block_in_place(move || {
1921 buf_compress(h.as_bytes())
1922 })?),
1923 None => None,
1924 };
1925
1926 msg.chat_id = self.id;
1927 msg.from_id = ContactId::SELF;
1928
1929 if let Some(update_msg_id) = update_msg_id {
1931 context
1932 .sql
1933 .execute(
1934 "UPDATE msgs
1935 SET rfc724_mid=?, chat_id=?, from_id=?, to_id=?, timestamp=?, type=?,
1936 state=?, txt=?, txt_normalized=?, subject=?, param=?,
1937 hidden=?, mime_in_reply_to=?, mime_references=?, mime_modified=?,
1938 mime_headers=?, mime_compressed=1, location_id=?, ephemeral_timer=?,
1939 ephemeral_timestamp=?
1940 WHERE id=?;",
1941 params_slice![
1942 msg.rfc724_mid,
1943 msg.chat_id,
1944 msg.from_id,
1945 to_id,
1946 msg.timestamp_sort,
1947 msg.viewtype,
1948 msg.state,
1949 msg_text,
1950 normalize_text(&msg_text),
1951 &msg.subject,
1952 msg.param.to_string(),
1953 msg.hidden,
1954 msg.in_reply_to.as_deref().unwrap_or_default(),
1955 new_references,
1956 new_mime_headers.is_some(),
1957 new_mime_headers.unwrap_or_default(),
1958 location_id as i32,
1959 ephemeral_timer,
1960 ephemeral_timestamp,
1961 update_msg_id
1962 ],
1963 )
1964 .await?;
1965 msg.id = update_msg_id;
1966 } else {
1967 let raw_id = context
1968 .sql
1969 .insert(
1970 "INSERT INTO msgs (
1971 rfc724_mid,
1972 chat_id,
1973 from_id,
1974 to_id,
1975 timestamp,
1976 type,
1977 state,
1978 txt,
1979 txt_normalized,
1980 subject,
1981 param,
1982 hidden,
1983 mime_in_reply_to,
1984 mime_references,
1985 mime_modified,
1986 mime_headers,
1987 mime_compressed,
1988 location_id,
1989 ephemeral_timer,
1990 ephemeral_timestamp)
1991 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?,?);",
1992 params_slice![
1993 msg.rfc724_mid,
1994 msg.chat_id,
1995 msg.from_id,
1996 to_id,
1997 msg.timestamp_sort,
1998 msg.viewtype,
1999 msg.state,
2000 msg_text,
2001 normalize_text(&msg_text),
2002 &msg.subject,
2003 msg.param.to_string(),
2004 msg.hidden,
2005 msg.in_reply_to.as_deref().unwrap_or_default(),
2006 new_references,
2007 new_mime_headers.is_some(),
2008 new_mime_headers.unwrap_or_default(),
2009 location_id as i32,
2010 ephemeral_timer,
2011 ephemeral_timestamp
2012 ],
2013 )
2014 .await?;
2015 context.new_msgs_notify.notify_one();
2016 msg.id = MsgId::new(u32::try_from(raw_id)?);
2017
2018 maybe_set_logging_xdc(context, msg, self.id).await?;
2019 context
2020 .update_webxdc_integration_database(msg, context)
2021 .await?;
2022 }
2023 context.scheduler.interrupt_ephemeral_task().await;
2024 Ok(())
2025 }
2026
2027 pub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> {
2029 if self.is_encrypted(context).await? {
2030 let self_fp = self_fingerprint(context).await?;
2031 let fingerprint_addrs = context
2032 .sql
2033 .query_map_vec(
2034 "SELECT c.id, c.fingerprint, c.addr
2035 FROM contacts c INNER JOIN chats_contacts cc
2036 ON c.id=cc.contact_id
2037 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2038 (self.id,),
2039 |row| {
2040 if row.get::<_, ContactId>(0)? == ContactId::SELF {
2041 return Ok((self_fp.to_string(), String::new()));
2042 }
2043 let fingerprint = row.get(1)?;
2044 let addr = row.get(2)?;
2045 Ok((fingerprint, addr))
2046 },
2047 )
2048 .await?;
2049 self.sync(context, SyncAction::SetPgpContacts(fingerprint_addrs))
2050 .await?;
2051 } else {
2052 let addrs = context
2053 .sql
2054 .query_map_vec(
2055 "SELECT c.addr \
2056 FROM contacts c INNER JOIN chats_contacts cc \
2057 ON c.id=cc.contact_id \
2058 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2059 (self.id,),
2060 |row| {
2061 let addr: String = row.get(0)?;
2062 Ok(addr)
2063 },
2064 )
2065 .await?;
2066 self.sync(context, SyncAction::SetContacts(addrs)).await?;
2067 }
2068 Ok(())
2069 }
2070
2071 async fn get_sync_id(&self, context: &Context) -> Result<Option<SyncId>> {
2073 match self.typ {
2074 Chattype::Single => {
2075 if self.is_device_talk() {
2076 return Ok(Some(SyncId::Device));
2077 }
2078
2079 let mut r = None;
2080 for contact_id in get_chat_contacts(context, self.id).await? {
2081 if contact_id == ContactId::SELF && !self.is_self_talk() {
2082 continue;
2083 }
2084 if r.is_some() {
2085 return Ok(None);
2086 }
2087 let contact = Contact::get_by_id(context, contact_id).await?;
2088 if let Some(fingerprint) = contact.fingerprint() {
2089 r = Some(SyncId::ContactFingerprint(fingerprint.hex()));
2090 } else {
2091 r = Some(SyncId::ContactAddr(contact.get_addr().to_string()));
2092 }
2093 }
2094 Ok(r)
2095 }
2096 Chattype::OutBroadcast
2097 | Chattype::InBroadcast
2098 | Chattype::Group
2099 | Chattype::Mailinglist => {
2100 if !self.grpid.is_empty() {
2101 return Ok(Some(SyncId::Grpid(self.grpid.clone())));
2102 }
2103
2104 let Some((parent_rfc724_mid, parent_in_reply_to, _)) = self
2105 .id
2106 .get_parent_mime_headers(context, MessageState::OutDelivered)
2107 .await?
2108 else {
2109 warn!(
2110 context,
2111 "Chat::get_sync_id({}): No good message identifying the chat found.",
2112 self.id
2113 );
2114 return Ok(None);
2115 };
2116 Ok(Some(SyncId::Msgids(vec![
2117 parent_in_reply_to,
2118 parent_rfc724_mid,
2119 ])))
2120 }
2121 }
2122 }
2123
2124 pub(crate) async fn sync(&self, context: &Context, action: SyncAction) -> Result<()> {
2126 if let Some(id) = self.get_sync_id(context).await? {
2127 sync(context, id, action).await?;
2128 }
2129 Ok(())
2130 }
2131}
2132
2133pub(crate) async fn sync(context: &Context, id: SyncId, action: SyncAction) -> Result<()> {
2134 context
2135 .add_sync_item(SyncData::AlterChat { id, action })
2136 .await?;
2137 context.scheduler.interrupt_smtp().await;
2138 Ok(())
2139}
2140
2141#[derive(Debug, Copy, Eq, PartialEq, Clone, Serialize, Deserialize, EnumIter, Default)]
2143#[repr(i8)]
2144pub enum ChatVisibility {
2145 #[default]
2147 Normal = 0,
2148
2149 Archived = 1,
2151
2152 Pinned = 2,
2154}
2155
2156impl rusqlite::types::ToSql for ChatVisibility {
2157 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
2158 let val = rusqlite::types::Value::Integer(*self as i64);
2159 let out = rusqlite::types::ToSqlOutput::Owned(val);
2160 Ok(out)
2161 }
2162}
2163
2164impl rusqlite::types::FromSql for ChatVisibility {
2165 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
2166 i64::column_result(value).map(|val| {
2167 match val {
2168 2 => ChatVisibility::Pinned,
2169 1 => ChatVisibility::Archived,
2170 0 => ChatVisibility::Normal,
2171 _ => ChatVisibility::Normal,
2173 }
2174 })
2175 }
2176}
2177
2178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2180#[non_exhaustive]
2181pub struct ChatInfo {
2182 pub id: ChatId,
2184
2185 #[serde(rename = "type")]
2192 pub type_: u32,
2193
2194 pub name: String,
2196
2197 pub archived: bool,
2199
2200 pub param: String,
2204
2205 pub is_sending_locations: bool,
2207
2208 pub color: u32,
2212
2213 pub profile_image: std::path::PathBuf,
2218
2219 pub draft: String,
2227
2228 pub is_muted: bool,
2232
2233 pub ephemeral_timer: EphemeralTimer,
2235 }
2241
2242async fn get_asset_icon(context: &Context, name: &str, bytes: &[u8]) -> Result<PathBuf> {
2243 ensure!(name.starts_with("icon-"));
2244 if let Some(icon) = context.sql.get_raw_config(name).await? {
2245 return Ok(get_abs_path(context, Path::new(&icon)));
2246 }
2247
2248 let blob =
2249 BlobObject::create_and_deduplicate_from_bytes(context, bytes, &format!("{name}.png"))?;
2250 let icon = blob.as_name().to_string();
2251 context.sql.set_raw_config(name, Some(&icon)).await?;
2252
2253 Ok(get_abs_path(context, Path::new(&icon)))
2254}
2255
2256pub(crate) async fn get_saved_messages_icon(context: &Context) -> Result<PathBuf> {
2257 get_asset_icon(
2258 context,
2259 "icon-saved-messages",
2260 include_bytes!("../assets/icon-saved-messages.png"),
2261 )
2262 .await
2263}
2264
2265pub(crate) async fn get_device_icon(context: &Context) -> Result<PathBuf> {
2266 get_asset_icon(
2267 context,
2268 "icon-device",
2269 include_bytes!("../assets/icon-device.png"),
2270 )
2271 .await
2272}
2273
2274pub(crate) async fn get_archive_icon(context: &Context) -> Result<PathBuf> {
2275 get_asset_icon(
2276 context,
2277 "icon-archive",
2278 include_bytes!("../assets/icon-archive.png"),
2279 )
2280 .await
2281}
2282
2283pub(crate) async fn get_unencrypted_icon(context: &Context) -> Result<PathBuf> {
2286 get_asset_icon(
2287 context,
2288 "icon-unencrypted",
2289 include_bytes!("../assets/icon-unencrypted.png"),
2290 )
2291 .await
2292}
2293
2294async fn update_special_chat_name(
2295 context: &Context,
2296 contact_id: ContactId,
2297 name: String,
2298) -> Result<()> {
2299 if let Some(ChatIdBlocked { id: chat_id, .. }) =
2300 ChatIdBlocked::lookup_by_contact(context, contact_id).await?
2301 {
2302 context
2304 .sql
2305 .execute(
2306 "UPDATE chats SET name=?, name_normalized=? WHERE id=? AND name!=?",
2307 (&name, normalize_text(&name), chat_id, &name),
2308 )
2309 .await?;
2310 }
2311 Ok(())
2312}
2313
2314pub(crate) async fn update_special_chat_names(context: &Context) -> Result<()> {
2315 update_special_chat_name(
2316 context,
2317 ContactId::DEVICE,
2318 stock_str::device_messages(context),
2319 )
2320 .await?;
2321 update_special_chat_name(context, ContactId::SELF, stock_str::saved_messages(context)).await?;
2322 Ok(())
2323}
2324
2325#[derive(Debug)]
2333pub(crate) struct ChatIdBlocked {
2334 pub id: ChatId,
2336
2337 pub blocked: Blocked,
2339}
2340
2341impl ChatIdBlocked {
2342 pub async fn lookup_by_contact(
2346 context: &Context,
2347 contact_id: ContactId,
2348 ) -> Result<Option<Self>> {
2349 ensure!(context.sql.is_open().await, "Database not available");
2350 ensure!(
2351 contact_id != ContactId::UNDEFINED,
2352 "Invalid contact id requested"
2353 );
2354
2355 context
2356 .sql
2357 .query_row_optional(
2358 "SELECT c.id, c.blocked
2359 FROM chats c
2360 INNER JOIN chats_contacts j
2361 ON c.id=j.chat_id
2362 WHERE c.type=100 -- 100 = Chattype::Single
2363 AND c.id>9 -- 9 = DC_CHAT_ID_LAST_SPECIAL
2364 AND j.contact_id=?;",
2365 (contact_id,),
2366 |row| {
2367 let id: ChatId = row.get(0)?;
2368 let blocked: Blocked = row.get(1)?;
2369 Ok(ChatIdBlocked { id, blocked })
2370 },
2371 )
2372 .await
2373 }
2374
2375 pub async fn get_for_contact(
2380 context: &Context,
2381 contact_id: ContactId,
2382 create_blocked: Blocked,
2383 ) -> Result<Self> {
2384 ensure!(context.sql.is_open().await, "Database not available");
2385 ensure!(
2386 contact_id != ContactId::UNDEFINED,
2387 "Invalid contact id requested"
2388 );
2389
2390 if let Some(res) = Self::lookup_by_contact(context, contact_id).await? {
2391 return Ok(res);
2393 }
2394
2395 let contact = Contact::get_by_id(context, contact_id).await?;
2396 let chat_name = contact.get_display_name().to_string();
2397 let mut params = Params::new();
2398 match contact_id {
2399 ContactId::SELF => {
2400 params.set_int(Param::Selftalk, 1);
2401 }
2402 ContactId::DEVICE => {
2403 params.set_int(Param::Devicetalk, 1);
2404 }
2405 _ => (),
2406 }
2407
2408 let smeared_time = create_smeared_timestamp(context);
2409
2410 let chat_id = context
2411 .sql
2412 .transaction(move |transaction| {
2413 transaction.execute(
2414 "INSERT INTO chats
2415 (type, name, name_normalized, param, blocked, created_timestamp)
2416 VALUES(?, ?, ?, ?, ?, ?)",
2417 (
2418 Chattype::Single,
2419 &chat_name,
2420 normalize_text(&chat_name),
2421 params.to_string(),
2422 create_blocked as u8,
2423 smeared_time,
2424 ),
2425 )?;
2426 let chat_id = ChatId::new(
2427 transaction
2428 .last_insert_rowid()
2429 .try_into()
2430 .context("chat table rowid overflows u32")?,
2431 );
2432
2433 transaction.execute(
2434 "INSERT INTO chats_contacts
2435 (chat_id, contact_id)
2436 VALUES((SELECT last_insert_rowid()), ?)",
2437 (contact_id,),
2438 )?;
2439
2440 Ok(chat_id)
2441 })
2442 .await?;
2443
2444 let chat = Chat::load_from_db(context, chat_id).await?;
2445 if chat.is_encrypted(context).await?
2446 && !chat.param.exists(Param::Devicetalk)
2447 && !chat.param.exists(Param::Selftalk)
2448 {
2449 chat_id.add_e2ee_notice(context, smeared_time).await?;
2450 }
2451
2452 Ok(Self {
2453 id: chat_id,
2454 blocked: create_blocked,
2455 })
2456 }
2457}
2458
2459async fn prepare_msg_blob(context: &Context, msg: &mut Message) -> Result<()> {
2460 if msg.viewtype == Viewtype::Text || msg.viewtype == Viewtype::Call {
2461 } else if msg.viewtype.has_file() {
2463 let viewtype_orig = msg.viewtype;
2464 let mut blob = msg
2465 .param
2466 .get_file_blob(context)?
2467 .with_context(|| format!("attachment missing for message of type #{}", msg.viewtype))?;
2468 let mut maybe_image = false;
2469
2470 if msg.viewtype == Viewtype::File || msg.viewtype == Viewtype::Image {
2471 if let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg) {
2478 if better_type == Viewtype::Image {
2479 maybe_image = true;
2480 } else if better_type != Viewtype::Webxdc
2481 || context
2482 .ensure_sendable_webxdc_file(&blob.to_abs_path())
2483 .await
2484 .is_ok()
2485 {
2486 msg.viewtype = better_type;
2487 }
2488 }
2489 } else if msg.viewtype == Viewtype::Webxdc {
2490 context
2491 .ensure_sendable_webxdc_file(&blob.to_abs_path())
2492 .await?;
2493 }
2494
2495 if msg.viewtype == Viewtype::Vcard {
2496 msg.try_set_vcard(context, &blob.to_abs_path()).await?;
2497 }
2498 if msg.viewtype == Viewtype::File && maybe_image || msg.viewtype == Viewtype::Image {
2499 let new_name = blob
2500 .check_or_recode_image(context, msg.get_filename(), &mut msg.viewtype)
2501 .await?;
2502 msg.param.set(Param::Filename, new_name);
2503 msg.param.set(Param::File, blob.as_name());
2504 }
2505
2506 if !msg.param.exists(Param::MimeType)
2507 && let Some((viewtype, mime)) = message::guess_msgtype_from_suffix(msg)
2508 {
2509 let mime = match viewtype != Viewtype::Image
2512 || matches!(msg.viewtype, Viewtype::Image | Viewtype::Sticker)
2513 {
2514 true => mime,
2515 false => "application/octet-stream",
2516 };
2517 msg.param.set(Param::MimeType, mime);
2518 }
2519
2520 msg.try_calc_and_set_dimensions(context).await?;
2521
2522 let filename = msg.get_filename().context("msg has no file")?;
2523 let suffix = Path::new(&filename)
2524 .extension()
2525 .and_then(|e| e.to_str())
2526 .unwrap_or("dat");
2527 let filename: String = match viewtype_orig {
2531 Viewtype::Voice => format!(
2532 "voice-messsage_{}.{suffix}",
2533 chrono::Utc
2534 .timestamp_opt(msg.timestamp_sort, 0)
2535 .single()
2536 .map_or_else(
2537 || "YY-mm-dd_hh:mm:ss".to_string(),
2538 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2539 ),
2540 ),
2541 Viewtype::Image | Viewtype::Gif => format!(
2542 "image_{}.{suffix}",
2543 chrono::Utc
2544 .timestamp_opt(msg.timestamp_sort, 0)
2545 .single()
2546 .map_or_else(
2547 || "YY-mm-dd_hh:mm:ss".to_string(),
2548 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string(),
2549 ),
2550 ),
2551 Viewtype::Video => format!(
2552 "video_{}.{suffix}",
2553 chrono::Utc
2554 .timestamp_opt(msg.timestamp_sort, 0)
2555 .single()
2556 .map_or_else(
2557 || "YY-mm-dd_hh:mm:ss".to_string(),
2558 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2559 ),
2560 ),
2561 _ => filename,
2562 };
2563 msg.param.set(Param::Filename, filename);
2564
2565 info!(
2566 context,
2567 "Attaching \"{}\" for message type #{}.",
2568 blob.to_abs_path().display(),
2569 msg.viewtype
2570 );
2571 } else {
2572 bail!("Cannot send messages of type #{}.", msg.viewtype);
2573 }
2574 Ok(())
2575}
2576
2577pub async fn is_contact_in_chat(
2579 context: &Context,
2580 chat_id: ChatId,
2581 contact_id: ContactId,
2582) -> Result<bool> {
2583 let exists = context
2590 .sql
2591 .exists(
2592 "SELECT COUNT(*) FROM chats_contacts
2593 WHERE chat_id=? AND contact_id=?
2594 AND add_timestamp >= remove_timestamp",
2595 (chat_id, contact_id),
2596 )
2597 .await?;
2598 Ok(exists)
2599}
2600
2601pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2608 ensure!(
2609 !chat_id.is_special(),
2610 "chat_id cannot be a special chat: {chat_id}"
2611 );
2612
2613 if msg.state != MessageState::Undefined {
2614 msg.param.remove(Param::GuaranteeE2ee);
2615 msg.param.remove(Param::ForcePlaintext);
2616 }
2618
2619 if msg.is_system_message() {
2621 msg.text = sanitize_bidi_characters(&msg.text);
2622 }
2623
2624 if !prepare_send_msg(context, chat_id, msg).await?.is_empty() {
2625 if !msg.hidden {
2626 context.emit_msgs_changed(msg.chat_id, msg.id);
2627 }
2628
2629 if msg.param.exists(Param::SetLatitude) {
2630 context.emit_location_changed(Some(ContactId::SELF)).await?;
2631 }
2632
2633 context.scheduler.interrupt_smtp().await;
2634 }
2635
2636 Ok(msg.id)
2637}
2638
2639pub async fn send_msg_sync(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2644 let rowids = prepare_send_msg(context, chat_id, msg).await?;
2645 if rowids.is_empty() {
2646 return Ok(msg.id);
2647 }
2648 let mut smtp = crate::smtp::Smtp::new();
2649 for rowid in rowids {
2650 send_msg_to_smtp(context, &mut smtp, rowid)
2651 .await
2652 .context("failed to send message, queued for later sending")?;
2653 }
2654 context.emit_msgs_changed(msg.chat_id, msg.id);
2655 Ok(msg.id)
2656}
2657
2658async fn prepare_send_msg(
2662 context: &Context,
2663 chat_id: ChatId,
2664 msg: &mut Message,
2665) -> Result<Vec<i64>> {
2666 let mut chat = Chat::load_from_db(context, chat_id).await?;
2667
2668 let skip_fn = |reason: &CantSendReason| match reason {
2669 CantSendReason::ContactRequest => {
2670 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
2673 }
2674 CantSendReason::NotAMember => msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup,
2678 CantSendReason::InBroadcast => {
2679 matches!(
2680 msg.param.get_cmd(),
2681 SystemMessage::MemberRemovedFromGroup | SystemMessage::SecurejoinMessage
2682 )
2683 }
2684 CantSendReason::MissingKey => msg
2685 .param
2686 .get_bool(Param::ForcePlaintext)
2687 .unwrap_or_default(),
2688 _ => false,
2689 };
2690 if let Some(reason) = chat.why_cant_send_ex(context, &skip_fn).await? {
2691 bail!("Cannot send to {chat_id}: {reason}");
2692 }
2693
2694 if chat.typ != Chattype::Single
2699 && !context.get_config_bool(Config::Bot).await?
2700 && let Some(quoted_message) = msg.quoted_message(context).await?
2701 && quoted_message.chat_id != chat_id
2702 {
2703 bail!(
2704 "Quote of message from {} cannot be sent to {chat_id}",
2705 quoted_message.chat_id
2706 );
2707 }
2708
2709 let update_msg_id = if msg.state == MessageState::OutDraft {
2711 msg.hidden = false;
2712 if !msg.id.is_special() && msg.chat_id == chat_id {
2713 Some(msg.id)
2714 } else {
2715 None
2716 }
2717 } else {
2718 None
2719 };
2720
2721 if msg.state == MessageState::Undefined
2722 && msg.param.get_cmd() != SystemMessage::SecurejoinMessage
2724 && chat.is_encrypted(context).await?
2725 {
2726 msg.param.set_int(Param::GuaranteeE2ee, 1);
2727 if !msg.id.is_unset() {
2728 msg.update_param(context).await?;
2729 }
2730 }
2731 msg.state = MessageState::OutPending;
2732
2733 msg.timestamp_sort = create_smeared_timestamp(context);
2734 prepare_msg_blob(context, msg).await?;
2735 if !msg.hidden {
2736 chat_id.unarchive_if_not_muted(context, msg.state).await?;
2737 }
2738 chat.prepare_msg_raw(context, msg, update_msg_id).await?;
2739
2740 let row_ids = create_send_msg_jobs(context, msg)
2741 .await
2742 .context("Failed to create send jobs")?;
2743 if !row_ids.is_empty() {
2744 donation_request_maybe(context).await.log_err(context).ok();
2745 }
2746 Ok(row_ids)
2747}
2748
2749async fn render_mime_message_and_pre_message(
2756 context: &Context,
2757 msg: &mut Message,
2758 mimefactory: MimeFactory,
2759) -> Result<(Option<RenderedEmail>, RenderedEmail)> {
2760 let needs_pre_message = msg.viewtype.has_file()
2761 && mimefactory.will_be_encrypted() && msg
2763 .get_filebytes(context)
2764 .await?
2765 .context("filebytes not available, even though message has attachment")?
2766 > PRE_MSG_ATTACHMENT_SIZE_THRESHOLD;
2767
2768 if needs_pre_message {
2769 info!(
2770 context,
2771 "Message {} is large and will be split into pre- and post-messages.", msg.id,
2772 );
2773
2774 let mut mimefactory_post_msg = mimefactory.clone();
2775 mimefactory_post_msg.set_as_post_message();
2776 let rendered_msg = Box::pin(mimefactory_post_msg.render(context))
2777 .await
2778 .context("Failed to render post-message")?;
2779
2780 let mut mimefactory_pre_msg = mimefactory;
2781 mimefactory_pre_msg.set_as_pre_message_for(&rendered_msg);
2782 let rendered_pre_msg = Box::pin(mimefactory_pre_msg.render(context))
2783 .await
2784 .context("pre-message failed to render")?;
2785
2786 if rendered_pre_msg.message.len() > PRE_MSG_SIZE_WARNING_THRESHOLD {
2787 warn!(
2788 context,
2789 "Pre-message for message {} is larger than expected: {}.",
2790 msg.id,
2791 rendered_pre_msg.message.len()
2792 );
2793 }
2794
2795 Ok((Some(rendered_pre_msg), rendered_msg))
2796 } else {
2797 Ok((None, Box::pin(mimefactory.render(context)).await?))
2798 }
2799}
2800
2801pub(crate) async fn create_send_msg_jobs(context: &Context, msg: &mut Message) -> Result<Vec<i64>> {
2811 let cmd = msg.param.get_cmd();
2812 if cmd == SystemMessage::GroupNameChanged || cmd == SystemMessage::GroupDescriptionChanged {
2813 msg.chat_id
2814 .update_timestamp(
2815 context,
2816 if cmd == SystemMessage::GroupNameChanged {
2817 Param::GroupNameTimestamp
2818 } else {
2819 Param::GroupDescriptionTimestamp
2820 },
2821 msg.timestamp_sort,
2822 )
2823 .await?;
2824 }
2825
2826 let needs_encryption = msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
2827 || (!msg
2828 .param
2829 .get_bool(Param::ForcePlaintext)
2830 .unwrap_or_default()
2831 && context.get_config_bool(Config::ForceEncryption).await?);
2832 let mimefactory = match MimeFactory::from_msg(context, msg.clone()).await {
2833 Ok(mf) => mf,
2834 Err(err) => {
2835 message::set_msg_failed(context, msg, &err.to_string())
2837 .await
2838 .ok();
2839 return Err(err);
2840 }
2841 };
2842 let attach_selfavatar = mimefactory.attach_selfavatar;
2843 let mut recipients = mimefactory.recipients();
2844
2845 let from = context.get_primary_self_addr().await?;
2846 let lowercase_from = from.to_lowercase();
2847
2848 recipients.retain(|x| x.to_lowercase() != lowercase_from);
2849
2850 if (msg.param.get_int(Param::WebxdcIntegration).is_some() && msg.hidden)
2852 || (!context.get_config_bool(Config::BccSelf).await? && recipients.is_empty())
2854 {
2855 info!(
2856 context,
2857 "Message {} has no recipient, skipping smtp-send.", msg.id
2858 );
2859 msg.param.set_int(Param::GuaranteeE2ee, 1);
2860 msg.update_param(context).await?;
2861 msg.id.set_delivered(context).await?;
2862 msg.state = MessageState::OutDelivered;
2863 return Ok(Vec::new());
2864 }
2865
2866 let (rendered_pre_msg, rendered_msg) =
2867 match render_mime_message_and_pre_message(context, msg, mimefactory).await {
2868 Ok(res) => Ok(res),
2869 Err(err) => {
2870 message::set_msg_failed(context, msg, &err.to_string()).await?;
2871 Err(err)
2872 }
2873 }?;
2874
2875 if let (post_msg, Some(pre_msg)) = (&rendered_msg, &rendered_pre_msg) {
2876 info!(
2877 context,
2878 "Message {} sizes: pre-message: {}; post-message: {}.",
2879 msg.id,
2880 format_size(pre_msg.message.len(), BINARY),
2881 format_size(post_msg.message.len(), BINARY),
2882 );
2883 msg.pre_rfc724_mid = pre_msg.rfc724_mid.clone();
2884 } else {
2885 info!(
2886 context,
2887 "Message {} will be sent in one shot (no pre- and post-message). Size: {}.",
2888 msg.id,
2889 format_size(rendered_msg.message.len(), BINARY),
2890 );
2891 }
2892
2893 if context.get_config_bool(Config::BccSelf).await? {
2894 smtp::add_self_recipients(context, &mut recipients, rendered_msg.is_encrypted).await?;
2895 }
2896
2897 if needs_encryption && !rendered_msg.is_encrypted {
2898 let addr = context.get_config(Config::ConfiguredAddr).await?;
2899 let text = stock_str::unencrypted_email(
2900 context,
2901 addr.unwrap_or_default()
2902 .split('@')
2903 .nth(1)
2904 .unwrap_or_default(),
2905 )
2906 .await;
2907 message::set_msg_failed(context, msg, &text).await?;
2908 add_info_msg_with_cmd(
2909 context,
2910 msg.chat_id,
2911 &text,
2912 SystemMessage::InvalidUnencryptedMail,
2913 Some(msg.timestamp_sort),
2914 msg.timestamp_sort,
2915 None,
2916 None,
2917 None,
2918 )
2919 .await?;
2920 bail!(
2921 "e2e encryption unavailable {} - {:?}",
2922 msg.id,
2923 needs_encryption
2924 );
2925 }
2926
2927 let now = smeared_time(context);
2928
2929 if rendered_msg.last_added_location_id.is_some()
2930 && let Err(err) = location::set_kml_sent_timestamp(context, msg.chat_id, now).await
2931 {
2932 error!(context, "Failed to set kml sent_timestamp: {err:#}.");
2933 }
2934
2935 if attach_selfavatar && let Err(err) = msg.chat_id.set_selfavatar_timestamp(context, now).await
2936 {
2937 error!(context, "Failed to set selfavatar timestamp: {err:#}.");
2938 }
2939
2940 if rendered_msg.is_encrypted {
2941 msg.param.set_int(Param::GuaranteeE2ee, 1);
2942 } else {
2943 msg.param.remove(Param::GuaranteeE2ee);
2944 }
2945 msg.subject.clone_from(&rendered_msg.subject);
2946 context
2948 .sql
2949 .execute(
2950 "
2951UPDATE msgs SET
2952 timestamp=(
2953 SELECT MAX(timestamp) FROM msgs INDEXED BY msgs_index7 WHERE
2954 -- From `InFresh` to `OutDelivered` inclusive, except `OutDraft`.
2955 state IN(10,13,16,18,20,24,26) AND
2956 hidden IN(0,1) AND
2957 chat_id=? AND
2958 id<=?
2959 ),
2960 pre_rfc724_mid=?, subject=?, param=?
2961WHERE id=?
2962 ",
2963 (
2964 msg.chat_id,
2965 msg.id,
2966 &msg.pre_rfc724_mid,
2967 &msg.subject,
2968 msg.param.to_string(),
2969 msg.id,
2970 ),
2971 )
2972 .await?;
2973
2974 let chunk_size = context.get_max_smtp_rcpt_to().await?;
2975 let trans_fn = |t: &mut rusqlite::Transaction| {
2976 let mut row_ids = Vec::<i64>::new();
2977
2978 if let Some(sync_ids) = rendered_msg.sync_ids_to_delete {
2979 t.execute(
2980 &format!("DELETE FROM multi_device_sync WHERE id IN ({sync_ids})"),
2981 (),
2982 )?;
2983 }
2984 let mut stmt = t.prepare(
2985 "INSERT INTO smtp (rfc724_mid, recipients, mime, msg_id)
2986 VALUES (?1, ?2, ?3, ?4)",
2987 )?;
2988 for recipients_chunk in recipients.chunks(chunk_size) {
2989 let recipients_chunk = recipients_chunk.join(" ");
2990 if let Some(pre_msg) = &rendered_pre_msg {
2991 let row_id = stmt.execute((
2992 &pre_msg.rfc724_mid,
2993 &recipients_chunk,
2994 &pre_msg.message,
2995 msg.id,
2996 ))?;
2997 row_ids.push(row_id.try_into()?);
2998 }
2999 let row_id = stmt.execute((
3000 &rendered_msg.rfc724_mid,
3001 &recipients_chunk,
3002 &rendered_msg.message,
3003 msg.id,
3004 ))?;
3005 row_ids.push(row_id.try_into()?);
3006 }
3007 Ok(row_ids)
3008 };
3009 context.sql.transaction(trans_fn).await
3010}
3011
3012pub async fn send_text_msg(
3016 context: &Context,
3017 chat_id: ChatId,
3018 text_to_send: String,
3019) -> Result<MsgId> {
3020 ensure!(
3021 !chat_id.is_special(),
3022 "bad chat_id, can not be a special chat: {chat_id}"
3023 );
3024
3025 let mut msg = Message::new_text(text_to_send);
3026 send_msg(context, chat_id, &mut msg).await
3027}
3028
3029pub async fn send_edit_request(context: &Context, msg_id: MsgId, new_text: String) -> Result<()> {
3031 let mut original_msg = Message::load_from_db(context, msg_id).await?;
3032 ensure!(
3033 original_msg.from_id == ContactId::SELF,
3034 "Can edit only own messages"
3035 );
3036 ensure!(!original_msg.is_info(), "Cannot edit info messages");
3037 ensure!(!original_msg.has_html(), "Cannot edit HTML messages");
3038 ensure!(original_msg.viewtype != Viewtype::Call, "Cannot edit calls");
3039 ensure!(
3040 !original_msg.text.is_empty(), "Cannot add text"
3042 );
3043 ensure!(!new_text.trim().is_empty(), "Edited text cannot be empty");
3044 if original_msg.text == new_text {
3045 info!(context, "Text unchanged.");
3046 return Ok(());
3047 }
3048
3049 save_text_edit_to_db(context, &mut original_msg, &new_text).await?;
3050
3051 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() {
3054 edit_msg.param.set_int(Param::GuaranteeE2ee, 1);
3055 }
3056 edit_msg
3057 .param
3058 .set(Param::TextEditFor, original_msg.rfc724_mid);
3059 edit_msg.hidden = true;
3060 send_msg(context, original_msg.chat_id, &mut edit_msg).await?;
3061 Ok(())
3062}
3063
3064pub(crate) async fn save_text_edit_to_db(
3065 context: &Context,
3066 original_msg: &mut Message,
3067 new_text: &str,
3068) -> Result<()> {
3069 original_msg.param.set_int(Param::IsEdited, 1);
3070 context
3071 .sql
3072 .execute(
3073 "UPDATE msgs SET txt=?, txt_normalized=?, param=? WHERE id=?",
3074 (
3075 new_text,
3076 normalize_text(new_text),
3077 original_msg.param.to_string(),
3078 original_msg.id,
3079 ),
3080 )
3081 .await?;
3082 context.emit_msgs_changed(original_msg.chat_id, original_msg.id);
3083 Ok(())
3084}
3085
3086async fn donation_request_maybe(context: &Context) -> Result<()> {
3087 let secs_between_checks = 30 * 24 * 60 * 60;
3088 let now = time();
3089 let ts = context
3090 .get_config_i64(Config::DonationRequestNextCheck)
3091 .await?;
3092 if ts > now {
3093 return Ok(());
3094 }
3095 let msg_cnt = context.sql.count(
3096 "SELECT COUNT(*) FROM msgs WHERE state>=? AND hidden=0",
3097 (MessageState::OutDelivered,),
3098 );
3099 let ts = if ts == 0 || msg_cnt.await? < 100 {
3100 now.saturating_add(secs_between_checks)
3101 } else {
3102 let mut msg = Message::new_text(stock_str::donation_request(context));
3103 add_device_msg(context, None, Some(&mut msg)).await?;
3104 i64::MAX
3105 };
3106 context
3107 .set_config_internal(Config::DonationRequestNextCheck, Some(&ts.to_string()))
3108 .await
3109}
3110
3111#[derive(Debug)]
3113pub struct MessageListOptions {
3114 pub add_daymarker: bool,
3116}
3117
3118pub async fn get_chat_msgs(context: &Context, chat_id: ChatId) -> Result<Vec<ChatItem>> {
3120 get_chat_msgs_ex(
3121 context,
3122 chat_id,
3123 MessageListOptions {
3124 add_daymarker: false,
3125 },
3126 )
3127 .await
3128}
3129
3130#[expect(clippy::arithmetic_side_effects)]
3133pub async fn get_chat_msgs_ex(
3134 context: &Context,
3135 chat_id: ChatId,
3136 options: MessageListOptions,
3137) -> Result<Vec<ChatItem>> {
3138 let MessageListOptions { add_daymarker } = options;
3139 let process_row = |row: &rusqlite::Row| {
3140 Ok((
3141 row.get::<_, i64>("timestamp")?,
3142 row.get::<_, MsgId>("id")?,
3143 false,
3144 ))
3145 };
3146 let process_rows = |rows: rusqlite::AndThenRows<_>| {
3147 let mut sorted_rows = Vec::new();
3150 for row in rows {
3151 let (ts, curr_id, exclude_message): (i64, MsgId, bool) = row?;
3152 if !exclude_message {
3153 sorted_rows.push((ts, curr_id));
3154 }
3155 }
3156 sorted_rows.sort_unstable();
3157
3158 let mut ret = Vec::new();
3159 let mut last_day = 0;
3160 let cnv_to_local = gm2local_offset();
3161
3162 for (ts, curr_id) in sorted_rows {
3163 if add_daymarker {
3164 let curr_local_timestamp = ts + cnv_to_local;
3165 let secs_in_day = 86400;
3166 let curr_day = curr_local_timestamp / secs_in_day;
3167 if curr_day != last_day {
3168 ret.push(ChatItem::DayMarker {
3169 timestamp: curr_day * secs_in_day - cnv_to_local,
3170 });
3171 last_day = curr_day;
3172 }
3173 }
3174 ret.push(ChatItem::Message { msg_id: curr_id });
3175 }
3176 Ok(ret)
3177 };
3178
3179 let items = context
3180 .sql
3181 .query_map(
3182 "SELECT m.id AS id, m.timestamp AS timestamp
3183 FROM msgs m
3184 WHERE m.chat_id=?
3185 AND m.hidden=0;",
3186 (chat_id,),
3187 process_row,
3188 process_rows,
3189 )
3190 .await?;
3191 Ok(items)
3192}
3193
3194pub async fn marknoticed_all_chats(context: &Context) -> Result<()> {
3197 let list = context
3199 .sql
3200 .query_map_vec(
3201 "SELECT DISTINCT(c.id)
3202 FROM msgs m
3203 INNER JOIN chats c
3204 ON m.chat_id=c.id
3205 WHERE m.state=?
3206 AND m.hidden=0
3207 AND m.chat_id>9
3208 AND c.blocked=0;",
3209 (MessageState::InFresh,),
3210 |row| {
3211 let msg_id: ChatId = row.get(0)?;
3212 Ok(msg_id)
3213 },
3214 )
3215 .await?;
3216
3217 for chat_id in list {
3218 marknoticed_chat(context, chat_id).await?;
3219 }
3220
3221 Ok(())
3222}
3223
3224pub async fn marknoticed_chat(context: &Context, chat_id: ChatId) -> Result<()> {
3227 if chat_id.is_archived_link() {
3230 let chat_ids_in_archive = context
3231 .sql
3232 .query_map_vec(
3233 "SELECT DISTINCT(m.chat_id) FROM msgs m
3234 LEFT JOIN chats c ON m.chat_id=c.id
3235 WHERE m.state=10 AND m.hidden=0 AND m.chat_id>9 AND c.archived=1",
3236 (),
3237 |row| {
3238 let chat_id: ChatId = row.get(0)?;
3239 Ok(chat_id)
3240 },
3241 )
3242 .await?;
3243 if chat_ids_in_archive.is_empty() {
3244 return Ok(());
3245 }
3246
3247 context
3248 .sql
3249 .transaction(|transaction| {
3250 let mut stmt = transaction.prepare(
3251 "UPDATE msgs SET state=13 WHERE state=10 AND hidden=0 AND chat_id = ?",
3252 )?;
3253 for chat_id_in_archive in &chat_ids_in_archive {
3254 stmt.execute((chat_id_in_archive,))?;
3255 }
3256 Ok(())
3257 })
3258 .await?;
3259
3260 for chat_id_in_archive in chat_ids_in_archive {
3261 start_chat_ephemeral_timers(context, chat_id_in_archive).await?;
3262 context.emit_event(EventType::MsgsNoticed(chat_id_in_archive));
3263 chatlist_events::emit_chatlist_item_changed(context, chat_id_in_archive);
3264 }
3265 } else {
3266 start_chat_ephemeral_timers(context, chat_id).await?;
3267
3268 let noticed_msgs_count = context
3269 .sql
3270 .execute(
3271 "UPDATE msgs
3272 SET state=?
3273 WHERE state=?
3274 AND hidden=0
3275 AND chat_id=?;",
3276 (MessageState::InNoticed, MessageState::InFresh, chat_id),
3277 )
3278 .await?;
3279
3280 let hidden_messages = context
3283 .sql
3284 .query_map_vec(
3285 "SELECT id FROM msgs
3286 WHERE state=?
3287 AND hidden=1
3288 AND chat_id=?
3289 ORDER BY id LIMIT 100", (MessageState::InFresh, chat_id), |row| {
3292 let msg_id: MsgId = row.get(0)?;
3293 Ok(msg_id)
3294 },
3295 )
3296 .await?;
3297 message::markseen_msgs(context, hidden_messages).await?;
3298 if noticed_msgs_count == 0 {
3299 return Ok(());
3300 }
3301 }
3302
3303 context.emit_event(EventType::MsgsNoticed(chat_id));
3304 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3305 context.on_archived_chats_maybe_noticed();
3306 Ok(())
3307}
3308
3309pub(crate) async fn mark_old_messages_as_noticed(
3316 context: &Context,
3317 mut msgs: Vec<ReceivedMsg>,
3318) -> Result<()> {
3319 if context.get_config_bool(Config::TeamProfile).await? {
3320 return Ok(());
3321 }
3322
3323 msgs.retain(|m| m.state.is_outgoing());
3324 if msgs.is_empty() {
3325 return Ok(());
3326 }
3327
3328 let mut msgs_by_chat: HashMap<ChatId, ReceivedMsg> = HashMap::new();
3329 for msg in msgs {
3330 let chat_id = msg.chat_id;
3331 if let Some(existing_msg) = msgs_by_chat.get(&chat_id) {
3332 if msg.sort_timestamp > existing_msg.sort_timestamp {
3333 msgs_by_chat.insert(chat_id, msg);
3334 }
3335 } else {
3336 msgs_by_chat.insert(chat_id, msg);
3337 }
3338 }
3339
3340 let changed_chats = context
3341 .sql
3342 .transaction(|transaction| {
3343 let mut changed_chats = Vec::new();
3344 for (_, msg) in msgs_by_chat {
3345 let changed_rows = transaction.execute(
3346 "UPDATE msgs
3347 SET state=?
3348 WHERE state=?
3349 AND hidden=0
3350 AND chat_id=?
3351 AND timestamp<=?;",
3352 (
3353 MessageState::InNoticed,
3354 MessageState::InFresh,
3355 msg.chat_id,
3356 msg.sort_timestamp,
3357 ),
3358 )?;
3359 if changed_rows > 0 {
3360 changed_chats.push(msg.chat_id);
3361 }
3362 }
3363 Ok(changed_chats)
3364 })
3365 .await?;
3366
3367 if !changed_chats.is_empty() {
3368 info!(
3369 context,
3370 "Marking chats as noticed because there are newer outgoing messages: {changed_chats:?}."
3371 );
3372 context.on_archived_chats_maybe_noticed();
3373 }
3374
3375 for c in changed_chats {
3376 start_chat_ephemeral_timers(context, c).await?;
3377 context.emit_event(EventType::MsgsNoticed(c));
3378 chatlist_events::emit_chatlist_item_changed(context, c);
3379 }
3380
3381 Ok(())
3382}
3383
3384pub async fn markfresh_chat(context: &Context, chat_id: ChatId) -> Result<()> {
3386 let affected_rows = context
3387 .sql
3388 .execute(
3389 "UPDATE msgs
3390 SET state=?1
3391 WHERE id=(SELECT id
3392 FROM msgs
3393 WHERE state IN (?1, ?2, ?3) AND hidden=0 AND chat_id=?4
3394 ORDER BY timestamp DESC, id DESC
3395 LIMIT 1)
3396 AND state!=?1",
3397 (
3398 MessageState::InFresh,
3399 MessageState::InNoticed,
3400 MessageState::InSeen,
3401 chat_id,
3402 ),
3403 )
3404 .await?;
3405
3406 if affected_rows == 0 {
3407 return Ok(());
3408 }
3409
3410 context.emit_msgs_changed_without_msg_id(chat_id);
3411 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3412
3413 Ok(())
3414}
3415
3416pub async fn get_chat_media(
3423 context: &Context,
3424 chat_id: Option<ChatId>,
3425 msg_type: Viewtype,
3426 msg_type2: Viewtype,
3427 msg_type3: Viewtype,
3428) -> Result<Vec<MsgId>> {
3429 let list = if msg_type == Viewtype::Webxdc
3430 && msg_type2 == Viewtype::Unknown
3431 && msg_type3 == Viewtype::Unknown
3432 {
3433 context
3434 .sql
3435 .query_map_vec(
3436 "SELECT id
3437 FROM msgs
3438 WHERE (1=? OR chat_id=?)
3439 AND chat_id != ?
3440 AND type = ?
3441 AND hidden=0
3442 ORDER BY max(timestamp, timestamp_rcvd), id;",
3443 (
3444 chat_id.is_none(),
3445 chat_id.unwrap_or_else(|| ChatId::new(0)),
3446 DC_CHAT_ID_TRASH,
3447 Viewtype::Webxdc,
3448 ),
3449 |row| {
3450 let msg_id: MsgId = row.get(0)?;
3451 Ok(msg_id)
3452 },
3453 )
3454 .await?
3455 } else {
3456 context
3457 .sql
3458 .query_map_vec(
3459 "SELECT id
3460 FROM msgs
3461 WHERE (1=? OR chat_id=?)
3462 AND chat_id != ?
3463 AND type IN (?, ?, ?)
3464 AND hidden=0
3465 ORDER BY timestamp, id;",
3466 (
3467 chat_id.is_none(),
3468 chat_id.unwrap_or_else(|| ChatId::new(0)),
3469 DC_CHAT_ID_TRASH,
3470 msg_type,
3471 if msg_type2 != Viewtype::Unknown {
3472 msg_type2
3473 } else {
3474 msg_type
3475 },
3476 if msg_type3 != Viewtype::Unknown {
3477 msg_type3
3478 } else {
3479 msg_type
3480 },
3481 ),
3482 |row| {
3483 let msg_id: MsgId = row.get(0)?;
3484 Ok(msg_id)
3485 },
3486 )
3487 .await?
3488 };
3489 Ok(list)
3490}
3491
3492pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3494 context
3497 .sql
3498 .query_map_vec(
3499 "SELECT cc.contact_id
3500 FROM chats_contacts cc
3501 LEFT JOIN contacts c
3502 ON c.id=cc.contact_id
3503 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp
3504 ORDER BY c.id=1, c.last_seen DESC, c.id DESC;",
3505 (chat_id,),
3506 |row| {
3507 let contact_id: ContactId = row.get(0)?;
3508 Ok(contact_id)
3509 },
3510 )
3511 .await
3512}
3513
3514pub async fn get_past_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3518 let now = time();
3519 context
3520 .sql
3521 .query_map_vec(
3522 "SELECT cc.contact_id
3523 FROM chats_contacts cc
3524 LEFT JOIN contacts c
3525 ON c.id=cc.contact_id
3526 WHERE cc.chat_id=?
3527 AND cc.add_timestamp < cc.remove_timestamp
3528 AND ? < cc.remove_timestamp
3529 ORDER BY c.id=1, cc.remove_timestamp DESC, c.id DESC",
3530 (chat_id, now.saturating_sub(60 * 24 * 3600)),
3531 |row| {
3532 let contact_id: ContactId = row.get(0)?;
3533 Ok(contact_id)
3534 },
3535 )
3536 .await
3537}
3538
3539pub async fn create_group(context: &Context, name: &str) -> Result<ChatId> {
3541 create_group_ex(context, Sync, create_id(), name).await
3542}
3543
3544pub async fn create_group_unencrypted(context: &Context, name: &str) -> Result<ChatId> {
3546 create_group_ex(context, Sync, String::new(), name).await
3547}
3548
3549pub(crate) async fn create_group_ex(
3556 context: &Context,
3557 sync: sync::Sync,
3558 grpid: String,
3559 name: &str,
3560) -> Result<ChatId> {
3561 let mut chat_name = sanitize_single_line(name);
3562 if chat_name.is_empty() {
3563 error!(context, "Invalid chat name: {name}.");
3566 chat_name = "…".to_string();
3567 }
3568
3569 let timestamp = create_smeared_timestamp(context);
3570 let row_id = context
3571 .sql
3572 .insert(
3573 "INSERT INTO chats
3574 (type, name, name_normalized, grpid, param, created_timestamp)
3575 VALUES(?, ?, ?, ?, \'U=1\', ?)",
3576 (
3577 Chattype::Group,
3578 &chat_name,
3579 normalize_text(&chat_name),
3580 &grpid,
3581 timestamp,
3582 ),
3583 )
3584 .await?;
3585
3586 let chat_id = ChatId::new(u32::try_from(row_id)?);
3587 add_to_chat_contacts_table(context, timestamp, chat_id, &[ContactId::SELF]).await?;
3588
3589 context.emit_msgs_changed_without_ids();
3590 chatlist_events::emit_chatlist_changed(context);
3591 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3592
3593 if !grpid.is_empty() {
3594 chat_id.add_e2ee_notice(context, timestamp).await?;
3596 }
3597
3598 if !context.get_config_bool(Config::Bot).await?
3599 && !context.get_config_bool(Config::SkipStartMessages).await?
3600 {
3601 let text = if !grpid.is_empty() {
3602 stock_str::new_group_send_first_message(context)
3604 } else {
3605 stock_str::chat_unencrypted_explanation(context)
3607 };
3608 chat_id.add_start_info_message(context, &text).await?;
3609 }
3610 if let (true, true) = (sync.into(), !grpid.is_empty()) {
3611 let id = SyncId::Grpid(grpid);
3612 let action = SyncAction::CreateGroupEncrypted(chat_name);
3613 self::sync(context, id, action).await.log_err(context).ok();
3614 }
3615 Ok(chat_id)
3616}
3617
3618pub async fn create_broadcast(context: &Context, chat_name: String) -> Result<ChatId> {
3631 let grpid = create_id();
3632 let secret = create_broadcast_secret();
3633 create_out_broadcast_ex(context, Sync, grpid, chat_name, secret).await
3634}
3635
3636const SQL_INSERT_BROADCAST_SECRET: &str =
3637 "INSERT INTO broadcast_secrets (chat_id, secret) VALUES (?, ?)
3638 ON CONFLICT(chat_id) DO UPDATE SET secret=excluded.secret";
3639
3640pub(crate) async fn create_out_broadcast_ex(
3641 context: &Context,
3642 sync: sync::Sync,
3643 grpid: String,
3644 chat_name: String,
3645 secret: String,
3646) -> Result<ChatId> {
3647 let chat_name = sanitize_single_line(&chat_name);
3648 if chat_name.is_empty() {
3649 bail!("Invalid broadcast channel name: {chat_name}.");
3650 }
3651
3652 let timestamp = create_smeared_timestamp(context);
3653 let trans_fn = |t: &mut rusqlite::Transaction| -> Result<ChatId> {
3654 let cnt: u32 = t.query_row(
3655 "SELECT COUNT(*) FROM chats WHERE grpid=?",
3656 (&grpid,),
3657 |row| row.get(0),
3658 )?;
3659 ensure!(cnt == 0, "{cnt} chats exist with grpid {grpid}");
3660 let mut params: Params = Params::new();
3661 params.update_timestamp(Param::GroupNameTimestamp, time())?;
3662
3663 t.execute(
3664 "INSERT INTO chats
3665 (type, name, name_normalized, grpid, created_timestamp, param)
3666 VALUES(?, ?, ?, ?, ?, ?)",
3667 (
3668 Chattype::OutBroadcast,
3669 &chat_name,
3670 normalize_text(&chat_name),
3671 &grpid,
3672 timestamp,
3673 params.to_string(),
3674 ),
3675 )?;
3676 let chat_id = ChatId::new(t.last_insert_rowid().try_into()?);
3677
3678 t.execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, &secret))?;
3679 Ok(chat_id)
3680 };
3681 let chat_id = context.sql.transaction(trans_fn).await?;
3682 chat_id.add_e2ee_notice(context, timestamp).await?;
3683
3684 context.emit_msgs_changed_without_ids();
3685 chatlist_events::emit_chatlist_changed(context);
3686 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3687
3688 if sync.into() {
3689 let id = SyncId::Grpid(grpid);
3690 let action = SyncAction::CreateOutBroadcast { chat_name, secret };
3691 self::sync(context, id, action).await.log_err(context).ok();
3692 }
3693
3694 Ok(chat_id)
3695}
3696
3697pub(crate) async fn load_broadcast_secret(
3698 context: &Context,
3699 chat_id: ChatId,
3700) -> Result<Option<String>> {
3701 context
3702 .sql
3703 .query_get_value(
3704 "SELECT secret FROM broadcast_secrets WHERE chat_id=?",
3705 (chat_id,),
3706 )
3707 .await
3708}
3709
3710pub(crate) async fn save_broadcast_secret(
3711 context: &Context,
3712 chat_id: ChatId,
3713 secret: &str,
3714) -> Result<()> {
3715 info!(context, "Saving broadcast secret for chat {chat_id}");
3716 context
3717 .sql
3718 .execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, secret))
3719 .await?;
3720
3721 Ok(())
3722}
3723
3724pub(crate) async fn delete_broadcast_secret(context: &Context, chat_id: ChatId) -> Result<()> {
3725 info!(context, "Removing broadcast secret for chat {chat_id}");
3726 context
3727 .sql
3728 .execute("DELETE FROM broadcast_secrets WHERE chat_id=?", (chat_id,))
3729 .await?;
3730
3731 Ok(())
3732}
3733
3734pub(crate) async fn update_chat_contacts_table(
3736 context: &Context,
3737 timestamp: i64,
3738 id: ChatId,
3739 contacts: &BTreeSet<ContactId>,
3740) -> Result<()> {
3741 context
3742 .sql
3743 .transaction(move |transaction| {
3744 transaction.execute(
3748 "UPDATE chats_contacts
3749 SET remove_timestamp=MAX(add_timestamp+1, ?)
3750 WHERE chat_id=?",
3751 (timestamp, id),
3752 )?;
3753
3754 if !contacts.is_empty() {
3755 let mut statement = transaction.prepare(
3756 "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp)
3757 VALUES (?1, ?2, ?3)
3758 ON CONFLICT (chat_id, contact_id)
3759 DO UPDATE SET add_timestamp=remove_timestamp",
3760 )?;
3761
3762 for contact_id in contacts {
3763 statement.execute((id, contact_id, timestamp))?;
3767 }
3768 }
3769 Ok(())
3770 })
3771 .await?;
3772 Ok(())
3773}
3774
3775pub(crate) async fn add_to_chat_contacts_table(
3777 context: &Context,
3778 timestamp: i64,
3779 chat_id: ChatId,
3780 contact_ids: &[ContactId],
3781) -> Result<()> {
3782 context
3783 .sql
3784 .transaction(move |transaction| {
3785 let mut add_statement = transaction.prepare(
3786 "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp) VALUES(?1, ?2, ?3)
3787 ON CONFLICT (chat_id, contact_id)
3788 DO UPDATE SET add_timestamp=MAX(remove_timestamp, ?3)",
3789 )?;
3790
3791 for contact_id in contact_ids {
3792 add_statement.execute((chat_id, contact_id, timestamp))?;
3793 }
3794 Ok(())
3795 })
3796 .await?;
3797
3798 Ok(())
3799}
3800
3801pub(crate) async fn remove_from_chat_contacts_table(
3806 context: &Context,
3807 chat_id: ChatId,
3808 contact_id: ContactId,
3809) -> Result<bool> {
3810 let now = time();
3811 let is_past_member = context
3812 .sql
3813 .execute(
3814 "UPDATE chats_contacts
3815 SET remove_timestamp=MAX(add_timestamp+1, ?)
3816 WHERE chat_id=? AND contact_id=?",
3817 (now, chat_id, contact_id),
3818 )
3819 .await?
3820 > 0;
3821 Ok(is_past_member)
3822}
3823
3824pub(crate) async fn remove_from_chat_contacts_table_without_trace(
3834 context: &Context,
3835 chat_id: ChatId,
3836 contact_id: ContactId,
3837) -> Result<bool> {
3838 let removed = context
3839 .sql
3840 .execute(
3841 "DELETE FROM chats_contacts
3842 WHERE chat_id=? AND contact_id=?",
3843 (chat_id, contact_id),
3844 )
3845 .await?
3846 > 0;
3847 Ok(removed)
3848}
3849
3850pub async fn add_contact_to_chat(
3853 context: &Context,
3854 chat_id: ChatId,
3855 contact_id: ContactId,
3856) -> Result<()> {
3857 add_contact_to_chat_ex(context, Sync, chat_id, contact_id, false).await?;
3858 Ok(())
3859}
3860
3861pub(crate) async fn add_contact_to_chat_ex(
3862 context: &Context,
3863 mut sync: sync::Sync,
3864 chat_id: ChatId,
3865 contact_id: ContactId,
3866 from_handshake: bool,
3867) -> Result<bool> {
3868 ensure!(!chat_id.is_special(), "can not add member to special chats");
3869 let contact = Contact::get_by_id(context, contact_id).await?;
3870 let mut msg = Message::new(Viewtype::default());
3871
3872 chat_id.reset_gossiped_timestamp(context).await?;
3873
3874 let mut chat = Chat::load_from_db(context, chat_id).await?;
3876 ensure!(
3877 chat.typ == Chattype::Group || (from_handshake && chat.typ == Chattype::OutBroadcast),
3878 "{chat_id} is not a group where one can add members",
3879 );
3880 ensure!(
3881 Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF,
3882 "invalid contact_id {contact_id} for adding to group"
3883 );
3884 ensure!(
3885 chat.typ != Chattype::OutBroadcast || contact_id != ContactId::SELF,
3886 "Cannot add SELF to broadcast channel."
3887 );
3888 match chat.is_encrypted(context).await? {
3889 true => ensure!(
3890 contact.is_key_contact(),
3891 "Only key-contacts can be added to encrypted chats"
3892 ),
3893 false => ensure!(
3894 !contact.is_key_contact(),
3895 "Only address-contacts can be added to unencrypted chats"
3896 ),
3897 }
3898
3899 if !chat.is_self_in_chat(context).await? {
3900 context.emit_event(EventType::ErrorSelfNotInGroup(
3901 "Cannot add contact to group; self not in group.".into(),
3902 ));
3903 warn!(
3904 context,
3905 "Can not add contact because the account is not part of the group/broadcast."
3906 );
3907 return Ok(false);
3908 }
3909 if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {
3910 let smeared_time = smeared_time(context);
3911 chat.param
3912 .remove(Param::Unpromoted)
3913 .set_i64(Param::GroupNameTimestamp, smeared_time)
3914 .set_i64(Param::GroupDescriptionTimestamp, smeared_time);
3915 chat.update_param(context).await?;
3916 }
3917 if context.is_self_addr(contact.get_addr()).await? {
3918 warn!(
3921 context,
3922 "Invalid attempt to add self e-mail address to group."
3923 );
3924 return Ok(false);
3925 }
3926
3927 if is_contact_in_chat(context, chat_id, contact_id).await? {
3928 if !from_handshake {
3929 return Ok(true);
3930 }
3931 } else {
3932 add_to_chat_contacts_table(context, time(), chat_id, &[contact_id]).await?;
3934 }
3935 if chat.is_promoted() {
3936 msg.viewtype = Viewtype::Text;
3937
3938 let contact_addr = contact.get_addr().to_lowercase();
3939 let added_by = if from_handshake && chat.typ == Chattype::OutBroadcast {
3940 ContactId::UNDEFINED
3945 } else {
3946 ContactId::SELF
3947 };
3948 msg.text = stock_str::msg_add_member_local(context, contact.id, added_by).await;
3949 msg.param.set_cmd(SystemMessage::MemberAddedToGroup);
3950 msg.param.set(Param::Arg, contact_addr);
3951 msg.param.set_int(Param::Arg2, from_handshake.into());
3952 let fingerprint = contact.fingerprint().map(|f| f.hex());
3953 msg.param.set_optional(Param::Arg4, fingerprint);
3954 msg.param
3955 .set_int(Param::ContactAddedRemoved, contact.id.to_u32() as i32);
3956 if chat.typ == Chattype::OutBroadcast {
3957 let secret = load_broadcast_secret(context, chat_id)
3958 .await?
3959 .context("Failed to find broadcast shared secret")?;
3960 msg.param.set(PARAM_BROADCAST_SECRET, secret);
3961 }
3962 send_msg(context, chat_id, &mut msg).await?;
3963
3964 sync = Nosync;
3965 }
3966 context.emit_event(EventType::ChatModified(chat_id));
3967 if sync.into() {
3968 chat.sync_contacts(context).await.log_err(context).ok();
3969 }
3970 if chat.typ == Chattype::OutBroadcast {
3971 resend_last_msgs(context, chat.id, &contact)
3972 .await
3973 .log_err(context)
3974 .ok();
3975 }
3976 Ok(true)
3977}
3978
3979async fn resend_last_msgs(context: &Context, chat_id: ChatId, to_contact: &Contact) -> Result<()> {
3980 let msgs: Vec<MsgId> = context
3981 .sql
3982 .query_map_vec(
3983 "
3984SELECT id
3985FROM msgs
3986WHERE chat_id=?
3987 AND hidden=0
3988 AND NOT ( -- Exclude info and system messages
3989 param GLOB '*\nS=*' OR param GLOB 'S=*'
3990 OR from_id=?
3991 OR to_id=?
3992 )
3993 AND type!=?
3994ORDER BY timestamp DESC, id DESC LIMIT ?",
3995 (
3996 chat_id,
3997 ContactId::INFO,
3998 ContactId::INFO,
3999 Viewtype::Webxdc,
4000 constants::N_MSGS_TO_NEW_BROADCAST_MEMBER,
4001 ),
4002 |row: &rusqlite::Row| Ok(row.get::<_, MsgId>(0)?),
4003 )
4004 .await?
4005 .into_iter()
4006 .rev()
4007 .collect();
4008 resend_msgs_ex(context, &msgs, to_contact.fingerprint()).await
4009}
4010
4011#[expect(clippy::arithmetic_side_effects)]
4017pub(crate) async fn shall_attach_selfavatar(context: &Context, chat_id: ChatId) -> Result<bool> {
4018 let timestamp_some_days_ago = time() - DC_RESEND_USER_AVATAR_DAYS * 24 * 60 * 60;
4019 let needs_attach = context
4020 .sql
4021 .query_map(
4022 "SELECT c.selfavatar_sent
4023 FROM chats_contacts cc
4024 LEFT JOIN contacts c ON c.id=cc.contact_id
4025 WHERE cc.chat_id=? AND cc.contact_id!=? AND cc.add_timestamp >= cc.remove_timestamp",
4026 (chat_id, ContactId::SELF),
4027 |row| {
4028 let selfavatar_sent: i64 = row.get(0)?;
4029 Ok(selfavatar_sent)
4030 },
4031 |rows| {
4032 let mut needs_attach = false;
4033 for row in rows {
4034 let selfavatar_sent = row?;
4035 if selfavatar_sent < timestamp_some_days_ago {
4036 needs_attach = true;
4037 }
4038 }
4039 Ok(needs_attach)
4040 },
4041 )
4042 .await?;
4043 Ok(needs_attach)
4044}
4045
4046#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
4048pub enum MuteDuration {
4049 NotMuted,
4051
4052 Forever,
4054
4055 Until(std::time::SystemTime),
4057}
4058
4059impl rusqlite::types::ToSql for MuteDuration {
4060 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
4061 let duration: i64 = match &self {
4062 MuteDuration::NotMuted => 0,
4063 MuteDuration::Forever => -1,
4064 MuteDuration::Until(when) => {
4065 let duration = when
4066 .duration_since(SystemTime::UNIX_EPOCH)
4067 .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
4068 i64::try_from(duration.as_secs())
4069 .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?
4070 }
4071 };
4072 let val = rusqlite::types::Value::Integer(duration);
4073 let out = rusqlite::types::ToSqlOutput::Owned(val);
4074 Ok(out)
4075 }
4076}
4077
4078impl rusqlite::types::FromSql for MuteDuration {
4079 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
4080 match i64::column_result(value)? {
4083 0 => Ok(MuteDuration::NotMuted),
4084 -1 => Ok(MuteDuration::Forever),
4085 n if n > 0 => match SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(n as u64)) {
4086 Some(t) => Ok(MuteDuration::Until(t)),
4087 None => Err(rusqlite::types::FromSqlError::OutOfRange(n)),
4088 },
4089 _ => Ok(MuteDuration::NotMuted),
4090 }
4091 }
4092}
4093
4094pub async fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuration) -> Result<()> {
4096 set_muted_ex(context, Sync, chat_id, duration).await
4097}
4098
4099pub(crate) async fn set_muted_ex(
4100 context: &Context,
4101 sync: sync::Sync,
4102 chat_id: ChatId,
4103 duration: MuteDuration,
4104) -> Result<()> {
4105 ensure!(!chat_id.is_special(), "Invalid chat ID");
4106 context
4107 .sql
4108 .execute(
4109 "UPDATE chats SET muted_until=? WHERE id=?;",
4110 (duration, chat_id),
4111 )
4112 .await
4113 .context(format!("Failed to set mute duration for {chat_id}"))?;
4114 context.emit_event(EventType::ChatModified(chat_id));
4115 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4116 if sync.into() {
4117 let chat = Chat::load_from_db(context, chat_id).await?;
4118 chat.sync(context, SyncAction::SetMuted(duration))
4119 .await
4120 .log_err(context)
4121 .ok();
4122 }
4123 Ok(())
4124}
4125
4126pub async fn remove_contact_from_chat(
4128 context: &Context,
4129 chat_id: ChatId,
4130 contact_id: ContactId,
4131) -> Result<()> {
4132 ensure!(
4133 !chat_id.is_special(),
4134 "bad chat_id, can not be special chat: {chat_id}"
4135 );
4136 ensure!(
4137 !contact_id.is_special() || contact_id == ContactId::SELF,
4138 "Cannot remove special contact"
4139 );
4140
4141 let chat = Chat::load_from_db(context, chat_id).await?;
4142 if chat.typ == Chattype::InBroadcast {
4143 ensure!(
4144 contact_id == ContactId::SELF,
4145 "Cannot remove other member from incoming broadcast channel"
4146 );
4147 delete_broadcast_secret(context, chat_id).await?;
4148 }
4149
4150 ensure!(
4151 matches!(
4152 chat.typ,
4153 Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast
4154 ),
4155 "Cannot remove members from non-group chats."
4156 );
4157
4158 if !chat.is_self_in_chat(context).await? {
4159 let err_msg =
4160 format!("Cannot remove contact {contact_id} from chat {chat_id}: self not in group.");
4161 context.emit_event(EventType::ErrorSelfNotInGroup(err_msg.clone()));
4162 bail!("{err_msg}");
4163 }
4164
4165 let mut sync = Nosync;
4166
4167 let removed = if chat.is_promoted() && chat.typ != Chattype::OutBroadcast {
4168 remove_from_chat_contacts_table(context, chat_id, contact_id).await?
4169 } else {
4170 remove_from_chat_contacts_table_without_trace(context, chat_id, contact_id).await?
4171 };
4172 if !removed {
4173 return Ok(());
4174 }
4175
4176 if let Some(contact) = Contact::get_by_id_optional(context, contact_id).await? {
4180 if chat.is_promoted() {
4181 let addr = contact.get_addr();
4182 let fingerprint = contact.fingerprint().map(|f| f.hex());
4183
4184 let res =
4185 send_member_removal_msg(context, &chat, contact_id, addr, fingerprint.as_deref())
4186 .await;
4187
4188 if contact_id == ContactId::SELF {
4189 res?;
4190 } else if let Err(e) = res {
4191 warn!(
4192 context,
4193 "remove_contact_from_chat({chat_id}, {contact_id}): send_msg() failed: {e:#}."
4194 );
4195 }
4196 } else {
4197 sync = Sync;
4198 }
4199 }
4200 context.emit_event(EventType::ChatModified(chat_id));
4201 if sync.into() {
4202 chat.sync_contacts(context).await.log_err(context).ok();
4203 }
4204
4205 Ok(())
4206}
4207
4208async fn send_member_removal_msg(
4209 context: &Context,
4210 chat: &Chat,
4211 contact_id: ContactId,
4212 addr: &str,
4213 fingerprint: Option<&str>,
4214) -> Result<MsgId> {
4215 let mut msg = Message::new(Viewtype::Text);
4216
4217 if contact_id == ContactId::SELF {
4218 if chat.typ == Chattype::InBroadcast {
4219 msg.text = stock_str::msg_you_left_broadcast(context);
4220 } else {
4221 msg.text = stock_str::msg_group_left_local(context, ContactId::SELF).await;
4222 }
4223 } else {
4224 msg.text = stock_str::msg_del_member_local(context, contact_id, ContactId::SELF).await;
4225 }
4226
4227 msg.param.set_cmd(SystemMessage::MemberRemovedFromGroup);
4228 msg.param.set(Param::Arg, addr.to_lowercase());
4229 msg.param.set_optional(Param::Arg4, fingerprint);
4230 msg.param
4231 .set(Param::ContactAddedRemoved, contact_id.to_u32());
4232
4233 send_msg(context, chat.id, &mut msg).await
4234}
4235
4236pub async fn set_chat_description(
4246 context: &Context,
4247 chat_id: ChatId,
4248 new_description: &str,
4249) -> Result<()> {
4250 set_chat_description_ex(context, Sync, chat_id, new_description).await
4251}
4252
4253async fn set_chat_description_ex(
4254 context: &Context,
4255 mut sync: sync::Sync,
4256 chat_id: ChatId,
4257 new_description: &str,
4258) -> Result<()> {
4259 let new_description = sanitize_bidi_characters(new_description.trim());
4260
4261 ensure!(!chat_id.is_special(), "Invalid chat ID");
4262
4263 let chat = Chat::load_from_db(context, chat_id).await?;
4264 ensure!(
4265 chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4266 "Can only set description for groups / broadcasts"
4267 );
4268 ensure!(
4269 !chat.grpid.is_empty(),
4270 "Cannot set description for ad hoc groups"
4271 );
4272 if !chat.is_self_in_chat(context).await? {
4273 context.emit_event(EventType::ErrorSelfNotInGroup(
4274 "Cannot set chat description; self not in group".into(),
4275 ));
4276 bail!("Cannot set chat description; self not in group");
4277 }
4278
4279 let old_description = get_chat_description(context, chat_id).await?;
4280 if old_description == new_description {
4281 return Ok(());
4282 }
4283
4284 context
4285 .sql
4286 .execute(
4287 "INSERT OR REPLACE INTO chats_descriptions(chat_id, description) VALUES(?, ?)",
4288 (chat_id, &new_description),
4289 )
4290 .await?;
4291
4292 if chat.is_promoted() {
4293 let mut msg = Message::new(Viewtype::Text);
4294 msg.text = stock_str::msg_chat_description_changed(context, ContactId::SELF).await;
4295 msg.param.set_cmd(SystemMessage::GroupDescriptionChanged);
4296
4297 msg.id = send_msg(context, chat_id, &mut msg).await?;
4298 context.emit_msgs_changed(chat_id, msg.id);
4299 sync = Nosync;
4300 }
4301 context.emit_event(EventType::ChatModified(chat_id));
4302
4303 if sync.into() {
4304 chat.sync(context, SyncAction::SetDescription(new_description))
4305 .await
4306 .log_err(context)
4307 .ok();
4308 }
4309
4310 Ok(())
4311}
4312
4313pub async fn get_chat_description(context: &Context, chat_id: ChatId) -> Result<String> {
4318 let description = context
4319 .sql
4320 .query_get_value(
4321 "SELECT description FROM chats_descriptions WHERE chat_id=?",
4322 (chat_id,),
4323 )
4324 .await?
4325 .unwrap_or_default();
4326 Ok(description)
4327}
4328
4329pub async fn set_chat_name(context: &Context, chat_id: ChatId, new_name: &str) -> Result<()> {
4337 rename_ex(context, Sync, chat_id, new_name).await
4338}
4339
4340async fn rename_ex(
4341 context: &Context,
4342 mut sync: sync::Sync,
4343 chat_id: ChatId,
4344 new_name: &str,
4345) -> Result<()> {
4346 let new_name = sanitize_single_line(new_name);
4347 let mut success = false;
4349
4350 ensure!(!new_name.is_empty(), "Invalid name");
4351 ensure!(!chat_id.is_special(), "Invalid chat ID");
4352
4353 let chat = Chat::load_from_db(context, chat_id).await?;
4354 let mut msg = Message::new(Viewtype::default());
4355
4356 if chat.typ == Chattype::Group
4357 || chat.typ == Chattype::Mailinglist
4358 || chat.typ == Chattype::OutBroadcast
4359 {
4360 if chat.name == new_name {
4361 success = true;
4362 } else if !chat.is_self_in_chat(context).await? {
4363 context.emit_event(EventType::ErrorSelfNotInGroup(
4364 "Cannot set chat name; self not in group".into(),
4365 ));
4366 } else {
4367 context
4368 .sql
4369 .execute(
4370 "UPDATE chats SET name=?, name_normalized=? WHERE id=?",
4371 (&new_name, normalize_text(&new_name), chat_id),
4372 )
4373 .await?;
4374 if chat.is_promoted()
4375 && !chat.is_mailing_list()
4376 && sanitize_single_line(&chat.name) != new_name
4377 {
4378 msg.viewtype = Viewtype::Text;
4379 msg.text = if chat.typ == Chattype::OutBroadcast {
4380 stock_str::msg_broadcast_name_changed(context, &chat.name, &new_name)
4381 } else {
4382 stock_str::msg_grp_name(context, &chat.name, &new_name, ContactId::SELF).await
4383 };
4384 msg.param.set_cmd(SystemMessage::GroupNameChanged);
4385 if !chat.name.is_empty() {
4386 msg.param.set(Param::Arg, &chat.name);
4387 }
4388 msg.id = send_msg(context, chat_id, &mut msg).await?;
4389 context.emit_msgs_changed(chat_id, msg.id);
4390 sync = Nosync;
4391 }
4392 context.emit_event(EventType::ChatModified(chat_id));
4393 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4394 success = true;
4395 }
4396 }
4397
4398 if !success {
4399 bail!("Failed to set name");
4400 }
4401 if sync.into() && chat.name != new_name {
4402 let sync_name = new_name.to_string();
4403 chat.sync(context, SyncAction::Rename(sync_name))
4404 .await
4405 .log_err(context)
4406 .ok();
4407 }
4408 Ok(())
4409}
4410
4411pub async fn set_chat_profile_image(
4417 context: &Context,
4418 chat_id: ChatId,
4419 new_image: &str, ) -> Result<()> {
4421 ensure!(!chat_id.is_special(), "Invalid chat ID");
4422 let mut chat = Chat::load_from_db(context, chat_id).await?;
4423 ensure!(
4424 chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4425 "Can only set profile image for groups / broadcasts"
4426 );
4427 ensure!(
4428 !chat.grpid.is_empty(),
4429 "Cannot set profile image for ad hoc groups"
4430 );
4431 if !chat.is_self_in_chat(context).await? {
4433 context.emit_event(EventType::ErrorSelfNotInGroup(
4434 "Cannot set chat profile image; self not in group.".into(),
4435 ));
4436 bail!("Failed to set profile image");
4437 }
4438 let mut msg = Message::new(Viewtype::Text);
4439 msg.param
4440 .set_int(Param::Cmd, SystemMessage::GroupImageChanged as i32);
4441 if new_image.is_empty() {
4442 chat.param.remove(Param::ProfileImage);
4443 msg.param.remove(Param::Arg);
4444 msg.text = if chat.typ == Chattype::OutBroadcast {
4445 stock_str::msg_broadcast_img_changed(context)
4446 } else {
4447 stock_str::msg_grp_img_deleted(context, ContactId::SELF).await
4448 };
4449 } else {
4450 let mut image_blob = BlobObject::create_and_deduplicate(
4451 context,
4452 Path::new(new_image),
4453 Path::new(new_image),
4454 )?;
4455 image_blob.recode_to_avatar_size(context).await?;
4456 chat.param.set(Param::ProfileImage, image_blob.as_name());
4457 msg.param.set(Param::Arg, image_blob.as_name());
4458 msg.text = if chat.typ == Chattype::OutBroadcast {
4459 stock_str::msg_broadcast_img_changed(context)
4460 } else {
4461 stock_str::msg_grp_img_changed(context, ContactId::SELF).await
4462 };
4463 }
4464 chat.update_param(context).await?;
4465 if chat.is_promoted() {
4466 msg.id = send_msg(context, chat_id, &mut msg).await?;
4467 context.emit_msgs_changed(chat_id, msg.id);
4468 }
4469 context.emit_event(EventType::ChatModified(chat_id));
4470 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4471 Ok(())
4472}
4473
4474pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) -> Result<()> {
4476 forward_msgs_2ctx(context, msg_ids, context, chat_id).await
4477}
4478
4479#[expect(clippy::arithmetic_side_effects)]
4481pub async fn forward_msgs_2ctx(
4482 ctx_src: &Context,
4483 msg_ids: &[MsgId],
4484 ctx_dst: &Context,
4485 chat_id: ChatId,
4486) -> Result<()> {
4487 ensure!(!msg_ids.is_empty(), "empty msgs_ids: nothing to forward");
4488 ensure!(!chat_id.is_special(), "can not forward to special chat");
4489
4490 let mut created_msgs: Vec<MsgId> = Vec::new();
4491 let mut curr_timestamp: i64;
4492
4493 chat_id
4494 .unarchive_if_not_muted(ctx_dst, MessageState::Undefined)
4495 .await?;
4496 let mut chat = Chat::load_from_db(ctx_dst, chat_id).await?;
4497 if let Some(reason) = chat.why_cant_send(ctx_dst).await? {
4498 bail!("cannot send to {chat_id}: {reason}");
4499 }
4500 curr_timestamp = create_smeared_timestamps(ctx_dst, msg_ids.len());
4501 let mut msgs = Vec::with_capacity(msg_ids.len());
4502 for id in msg_ids {
4503 let ts: i64 = ctx_src
4504 .sql
4505 .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4506 .await?
4507 .with_context(|| format!("No message {id}"))?;
4508 msgs.push((ts, *id));
4509 }
4510 msgs.sort_unstable();
4511 for (_, id) in msgs {
4512 let src_msg_id: MsgId = id;
4513 let mut msg = Message::load_from_db(ctx_src, src_msg_id).await?;
4514 if msg.state == MessageState::OutDraft {
4515 bail!("cannot forward drafts.");
4516 }
4517
4518 let mut param = msg.param;
4519 msg.param = Params::new();
4520
4521 if msg.get_viewtype() != Viewtype::Sticker {
4522 let forwarded_msg_id = match ctx_src.blobdir == ctx_dst.blobdir {
4523 true => src_msg_id,
4524 false => MsgId::new_unset(),
4525 };
4526 msg.param
4527 .set_int(Param::Forwarded, forwarded_msg_id.to_u32() as i32);
4528 }
4529
4530 if msg.get_viewtype() == Viewtype::Call {
4531 msg.viewtype = Viewtype::Text;
4532 }
4533 msg.text += &msg.additional_text;
4534
4535 let param = &mut param;
4536
4537 if ctx_src.blobdir == ctx_dst.blobdir {
4540 msg.param.steal(param, Param::File);
4541 } else if let Some(src_path) = param.get_file_path(ctx_src)? {
4542 let new_blob = BlobObject::create_and_deduplicate(ctx_dst, &src_path, &src_path)
4543 .context("Failed to copy blob file to destination account")?;
4544 msg.param.set(Param::File, new_blob.as_name());
4545 }
4546 msg.param.steal(param, Param::Filename);
4547 msg.param.steal(param, Param::Width);
4548 msg.param.steal(param, Param::Height);
4549 msg.param.steal(param, Param::Duration);
4550 msg.param.steal(param, Param::MimeType);
4551 msg.param.steal(param, Param::ProtectQuote);
4552 msg.param.steal(param, Param::Quote);
4553 msg.param.steal(param, Param::Summary1);
4554 if msg.has_html() {
4555 msg.set_html(src_msg_id.get_html(ctx_src).await?);
4556 }
4557 msg.in_reply_to = None;
4558
4559 msg.subject = "".to_string();
4561
4562 msg.state = MessageState::OutPending;
4563 msg.rfc724_mid = create_outgoing_rfc724_mid();
4564 msg.pre_rfc724_mid.clear();
4565 msg.timestamp_sort = curr_timestamp;
4566 chat.prepare_msg_raw(ctx_dst, &mut msg, None).await?;
4567
4568 curr_timestamp += 1;
4569 if !create_send_msg_jobs(ctx_dst, &mut msg).await?.is_empty() {
4570 ctx_dst.scheduler.interrupt_smtp().await;
4571 }
4572 created_msgs.push(msg.id);
4573 }
4574 for msg_id in created_msgs {
4575 ctx_dst.emit_msgs_changed(chat_id, msg_id);
4576 }
4577 Ok(())
4578}
4579
4580pub async fn save_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4583 let mut msgs = Vec::with_capacity(msg_ids.len());
4584 for id in msg_ids {
4585 let ts: i64 = context
4586 .sql
4587 .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4588 .await?
4589 .with_context(|| format!("No message {id}"))?;
4590 msgs.push((ts, *id));
4591 }
4592 msgs.sort_unstable();
4593 for (_, src_msg_id) in msgs {
4594 let dest_rfc724_mid = create_outgoing_rfc724_mid();
4595 let src_rfc724_mid = save_copy_in_self_talk(context, src_msg_id, &dest_rfc724_mid).await?;
4596 context
4597 .add_sync_item(SyncData::SaveMessage {
4598 src: src_rfc724_mid,
4599 dest: dest_rfc724_mid,
4600 })
4601 .await?;
4602 }
4603 context.scheduler.interrupt_smtp().await;
4604 Ok(())
4605}
4606
4607pub(crate) async fn save_copy_in_self_talk(
4613 context: &Context,
4614 src_msg_id: MsgId,
4615 dest_rfc724_mid: &String,
4616) -> Result<String> {
4617 let dest_chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?;
4618 let mut msg = Message::load_from_db(context, src_msg_id).await?;
4619 msg.param.remove(Param::Cmd);
4620 msg.param.remove(Param::WebxdcDocument);
4621 msg.param.remove(Param::WebxdcDocumentTimestamp);
4622 msg.param.remove(Param::WebxdcSummary);
4623 msg.param.remove(Param::WebxdcSummaryTimestamp);
4624 msg.param.remove(Param::PostMessageFileBytes);
4625 msg.param.remove(Param::PostMessageViewtype);
4626
4627 msg.text += &msg.additional_text;
4628
4629 if !msg.original_msg_id.is_unset() {
4630 bail!("message already saved.");
4631 }
4632
4633 let copy_fields = "from_id, to_id, timestamp_rcvd, type,
4634 mime_modified, mime_headers, mime_compressed, mime_in_reply_to, subject, msgrmsg";
4635 let row_id = context
4636 .sql
4637 .insert(
4638 &format!(
4639 "INSERT INTO msgs ({copy_fields},
4640 timestamp_sent,
4641 txt, chat_id, rfc724_mid, state, timestamp, param, starred)
4642 SELECT {copy_fields},
4643 -- Outgoing messages on originating device
4644 -- have timestamp_sent == 0.
4645 -- We copy sort timestamp instead
4646 -- so UIs display the same timestamp
4647 -- for saved and original message.
4648 IIF(timestamp_sent == 0, timestamp, timestamp_sent),
4649 ?, ?, ?, ?, ?, ?, ?
4650 FROM msgs WHERE id=?;"
4651 ),
4652 (
4653 msg.text,
4654 dest_chat_id,
4655 dest_rfc724_mid,
4656 if msg.from_id == ContactId::SELF {
4657 MessageState::OutDelivered
4658 } else {
4659 MessageState::InSeen
4660 },
4661 create_smeared_timestamp(context),
4662 msg.param.to_string(),
4663 src_msg_id,
4664 src_msg_id,
4665 ),
4666 )
4667 .await?;
4668 let dest_msg_id = MsgId::new(row_id.try_into()?);
4669
4670 context.emit_msgs_changed(msg.chat_id, src_msg_id);
4671 context.emit_msgs_changed(dest_chat_id, dest_msg_id);
4672 chatlist_events::emit_chatlist_changed(context);
4673 chatlist_events::emit_chatlist_item_changed(context, dest_chat_id);
4674
4675 Ok(msg.rfc724_mid)
4676}
4677
4678pub async fn resend_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4682 resend_msgs_ex(context, msg_ids, None).await
4683}
4684
4685pub(crate) async fn resend_msgs_ex(
4693 context: &Context,
4694 msg_ids: &[MsgId],
4695 to_fingerprint: Option<Fingerprint>,
4696) -> Result<()> {
4697 let to_fingerprint = to_fingerprint.map(|f| f.hex());
4698 let mut msgs: Vec<Message> = Vec::new();
4699 for msg_id in msg_ids {
4700 let msg = Message::load_from_db(context, *msg_id).await?;
4701 ensure!(
4702 msg.from_id == ContactId::SELF,
4703 "can resend only own messages"
4704 );
4705 ensure!(!msg.is_info(), "cannot resend info messages");
4706 msgs.push(msg)
4707 }
4708
4709 for mut msg in msgs {
4710 match msg.get_state() {
4711 MessageState::OutPending
4713 | MessageState::OutFailed
4714 | MessageState::OutDelivered
4715 | MessageState::OutMdnRcvd => {
4716 if to_fingerprint.is_none() {
4719 message::update_msg_state(context, msg.id, MessageState::OutPending).await?;
4720 }
4721 }
4722 msg_state => bail!("Unexpected message state {msg_state}"),
4723 }
4724 if let Some(to_fingerprint) = &to_fingerprint {
4725 msg.param.set(Param::Arg4, to_fingerprint.clone());
4726 }
4727 if create_send_msg_jobs(context, &mut msg).await?.is_empty() {
4728 continue;
4729 }
4730
4731 context.emit_event(EventType::MsgsChanged {
4735 chat_id: msg.chat_id,
4736 msg_id: msg.id,
4737 });
4738 chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
4741
4742 if msg.viewtype == Viewtype::Webxdc {
4743 let conn_fn = |conn: &mut rusqlite::Connection| {
4744 let range = conn.query_row(
4745 "SELECT IFNULL(min(id), 1), IFNULL(max(id), 0) \
4746 FROM msgs_status_updates WHERE msg_id=?",
4747 (msg.id,),
4748 |row| {
4749 let min_id: StatusUpdateSerial = row.get(0)?;
4750 let max_id: StatusUpdateSerial = row.get(1)?;
4751 Ok((min_id, max_id))
4752 },
4753 )?;
4754 if range.0 > range.1 {
4755 return Ok(());
4756 };
4757 conn.execute(
4761 "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) \
4762 VALUES(?, ?, ?, '') \
4763 ON CONFLICT(msg_id) \
4764 DO UPDATE SET first_serial=min(first_serial - 1, excluded.first_serial)",
4765 (msg.id, range.0, range.1),
4766 )?;
4767 Ok(())
4768 };
4769 context.sql.call_write(conn_fn).await?;
4770 }
4771 context.scheduler.interrupt_smtp().await;
4772 }
4773 Ok(())
4774}
4775
4776pub(crate) async fn get_chat_cnt(context: &Context) -> Result<usize> {
4777 if context.sql.is_open().await {
4778 let count = context
4780 .sql
4781 .count("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;", ())
4782 .await?;
4783 Ok(count)
4784 } else {
4785 Ok(0)
4786 }
4787}
4788
4789pub(crate) async fn get_chat_id_by_grpid(
4791 context: &Context,
4792 grpid: &str,
4793) -> Result<Option<(ChatId, Blocked)>> {
4794 context
4795 .sql
4796 .query_row_optional(
4797 "SELECT id, blocked FROM chats WHERE grpid=?;",
4798 (grpid,),
4799 |row| {
4800 let chat_id = row.get::<_, ChatId>(0)?;
4801
4802 let b = row.get::<_, Option<Blocked>>(1)?.unwrap_or_default();
4803 Ok((chat_id, b))
4804 },
4805 )
4806 .await
4807}
4808
4809#[expect(clippy::arithmetic_side_effects)]
4814pub async fn add_device_msg_with_importance(
4815 context: &Context,
4816 label: Option<&str>,
4817 msg: Option<&mut Message>,
4818 important: bool,
4819) -> Result<MsgId> {
4820 ensure!(
4821 label.is_some() || msg.is_some(),
4822 "device-messages need label, msg or both"
4823 );
4824 let mut chat_id = ChatId::new(0);
4825 let mut msg_id = MsgId::new_unset();
4826
4827 if let Some(label) = label
4828 && was_device_msg_ever_added(context, label).await?
4829 {
4830 info!(context, "Device-message {label} already added.");
4831 return Ok(msg_id);
4832 }
4833
4834 if let Some(msg) = msg {
4835 chat_id = ChatId::get_for_contact(context, ContactId::DEVICE).await?;
4836
4837 let rfc724_mid = create_outgoing_rfc724_mid();
4838 let timestamp_sent = create_smeared_timestamp(context);
4839
4840 msg.timestamp_sort = timestamp_sent;
4843 if let Some(last_msg_time) = chat_id.get_timestamp(context).await?
4844 && msg.timestamp_sort <= last_msg_time
4845 {
4846 msg.timestamp_sort = last_msg_time + 1;
4847 }
4848 prepare_msg_blob(context, msg).await?;
4849 let state = MessageState::InFresh;
4850 let row_id = context
4851 .sql
4852 .insert(
4853 "INSERT INTO msgs (
4854 chat_id,
4855 from_id,
4856 to_id,
4857 timestamp,
4858 timestamp_sent,
4859 timestamp_rcvd,
4860 type,state,
4861 txt,
4862 txt_normalized,
4863 param,
4864 rfc724_mid)
4865 VALUES (?,?,?,?,?,?,?,?,?,?,?,?);",
4866 (
4867 chat_id,
4868 ContactId::DEVICE,
4869 ContactId::SELF,
4870 msg.timestamp_sort,
4871 timestamp_sent,
4872 timestamp_sent, msg.viewtype,
4874 state,
4875 &msg.text,
4876 normalize_text(&msg.text),
4877 msg.param.to_string(),
4878 rfc724_mid,
4879 ),
4880 )
4881 .await?;
4882 context.new_msgs_notify.notify_one();
4883
4884 msg_id = MsgId::new(u32::try_from(row_id)?);
4885 if !msg.hidden {
4886 chat_id.unarchive_if_not_muted(context, state).await?;
4887 }
4888 }
4889
4890 if let Some(label) = label {
4891 context
4892 .sql
4893 .execute("INSERT INTO devmsglabels (label) VALUES (?);", (label,))
4894 .await?;
4895 }
4896
4897 if !msg_id.is_unset() {
4898 chat_id.emit_msg_event(context, msg_id, important);
4899 }
4900
4901 Ok(msg_id)
4902}
4903
4904pub async fn add_device_msg(
4906 context: &Context,
4907 label: Option<&str>,
4908 msg: Option<&mut Message>,
4909) -> Result<MsgId> {
4910 add_device_msg_with_importance(context, label, msg, false).await
4911}
4912
4913pub async fn was_device_msg_ever_added(context: &Context, label: &str) -> Result<bool> {
4915 ensure!(!label.is_empty(), "empty label");
4916 let exists = context
4917 .sql
4918 .exists(
4919 "SELECT COUNT(label) FROM devmsglabels WHERE label=?",
4920 (label,),
4921 )
4922 .await?;
4923
4924 Ok(exists)
4925}
4926
4927pub(crate) async fn delete_and_reset_all_device_msgs(context: &Context) -> Result<()> {
4933 context
4934 .sql
4935 .execute("DELETE FROM msgs WHERE from_id=?;", (ContactId::DEVICE,))
4936 .await?;
4937 context.sql.execute("DELETE FROM devmsglabels;", ()).await?;
4938
4939 context
4941 .sql
4942 .execute(
4943 r#"INSERT INTO devmsglabels (label) VALUES ("core-welcome-image"), ("core-welcome")"#,
4944 (),
4945 )
4946 .await?;
4947 Ok(())
4948}
4949
4950#[expect(clippy::too_many_arguments)]
4955pub(crate) async fn add_info_msg_with_cmd(
4956 context: &Context,
4957 chat_id: ChatId,
4958 text: &str,
4959 cmd: SystemMessage,
4960 timestamp_sort: Option<i64>,
4963 timestamp_sent_rcvd: i64,
4965 parent: Option<&Message>,
4966 from_id: Option<ContactId>,
4967 added_removed_id: Option<ContactId>,
4968) -> Result<MsgId> {
4969 let rfc724_mid = create_outgoing_rfc724_mid();
4970 let ephemeral_timer = chat_id.get_ephemeral_timer(context).await?;
4971
4972 let mut param = Params::new();
4973 if cmd != SystemMessage::Unknown {
4974 param.set_cmd(cmd);
4975 }
4976 if let Some(contact_id) = added_removed_id {
4977 param.set(Param::ContactAddedRemoved, contact_id.to_u32().to_string());
4978 }
4979
4980 let timestamp_sort = if let Some(ts) = timestamp_sort {
4981 ts
4982 } else {
4983 let sort_to_bottom = true;
4984 chat_id
4985 .calc_sort_timestamp(context, smeared_time(context), sort_to_bottom)
4986 .await?
4987 };
4988
4989 let row_id =
4990 context.sql.insert(
4991 "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)
4992 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);",
4993 (
4994 chat_id,
4995 from_id.unwrap_or(ContactId::INFO),
4996 ContactId::INFO,
4997 timestamp_sort,
4998 timestamp_sent_rcvd,
4999 timestamp_sent_rcvd,
5000 Viewtype::Text,
5001 MessageState::InNoticed,
5002 text,
5003 normalize_text(text),
5004 rfc724_mid,
5005 ephemeral_timer,
5006 param.to_string(),
5007 parent.map(|msg|msg.rfc724_mid.clone()).unwrap_or_default()
5008 )
5009 ).await?;
5010 context.new_msgs_notify.notify_one();
5011
5012 let msg_id = MsgId::new(row_id.try_into()?);
5013 context.emit_msgs_changed(chat_id, msg_id);
5014
5015 Ok(msg_id)
5016}
5017
5018pub(crate) async fn add_info_msg(context: &Context, chat_id: ChatId, text: &str) -> Result<MsgId> {
5020 add_info_msg_with_cmd(
5021 context,
5022 chat_id,
5023 text,
5024 SystemMessage::Unknown,
5025 None,
5026 time(),
5027 None,
5028 None,
5029 None,
5030 )
5031 .await
5032}
5033
5034pub(crate) async fn update_msg_text_and_timestamp(
5035 context: &Context,
5036 chat_id: ChatId,
5037 msg_id: MsgId,
5038 text: &str,
5039 timestamp: i64,
5040) -> Result<()> {
5041 context
5042 .sql
5043 .execute(
5044 "UPDATE msgs SET txt=?, txt_normalized=?, timestamp=? WHERE id=?;",
5045 (text, normalize_text(text), timestamp, msg_id),
5046 )
5047 .await?;
5048 context.emit_msgs_changed(chat_id, msg_id);
5049 Ok(())
5050}
5051
5052async fn set_contacts_by_addrs(context: &Context, id: ChatId, addrs: &[String]) -> Result<()> {
5054 let chat = Chat::load_from_db(context, id).await?;
5055 ensure!(
5056 !chat.is_encrypted(context).await?,
5057 "Cannot add address-contacts to encrypted chat {id}"
5058 );
5059 ensure!(
5060 chat.typ == Chattype::OutBroadcast,
5061 "{id} is not a broadcast list",
5062 );
5063 let mut contacts = BTreeSet::new();
5064 for addr in addrs {
5065 let contact_addr = ContactAddress::new(addr)?;
5066 let contact = Contact::add_or_lookup(context, "", &contact_addr, Origin::Hidden)
5067 .await?
5068 .0;
5069 contacts.insert(contact);
5070 }
5071 let contacts_old = BTreeSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
5072 if contacts == contacts_old {
5073 return Ok(());
5074 }
5075 context
5076 .sql
5077 .transaction(move |transaction| {
5078 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
5079
5080 let mut statement = transaction
5083 .prepare("INSERT INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)")?;
5084 for contact_id in &contacts {
5085 statement.execute((id, contact_id))?;
5086 }
5087 Ok(())
5088 })
5089 .await?;
5090 context.emit_event(EventType::ChatModified(id));
5091 Ok(())
5092}
5093
5094async fn set_contacts_by_fingerprints(
5098 context: &Context,
5099 id: ChatId,
5100 fingerprint_addrs: &[(String, String)],
5101) -> Result<()> {
5102 let chat = Chat::load_from_db(context, id).await?;
5103 ensure!(
5104 chat.is_encrypted(context).await?,
5105 "Cannot add key-contacts to unencrypted chat {id}"
5106 );
5107 ensure!(
5108 matches!(chat.typ, Chattype::Group | Chattype::OutBroadcast),
5109 "{id} is not a group or broadcast",
5110 );
5111 let mut contacts = BTreeSet::new();
5112 for (fingerprint, addr) in fingerprint_addrs {
5113 let contact = Contact::add_or_lookup_ex(context, "", addr, fingerprint, Origin::Hidden)
5114 .await?
5115 .0;
5116 contacts.insert(contact);
5117 }
5118 let contacts_old = BTreeSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
5119 if contacts == contacts_old {
5120 return Ok(());
5121 }
5122 let broadcast_contacts_added = context
5123 .sql
5124 .transaction(move |transaction| {
5125 if chat.typ != Chattype::OutBroadcast {
5131 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
5132 }
5133
5134 let mut statement = transaction.prepare(
5137 "INSERT OR IGNORE INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)",
5138 )?;
5139 let mut broadcast_contacts_added = Vec::new();
5140 for contact_id in &contacts {
5141 if statement.execute((id, contact_id))? > 0 && chat.typ == Chattype::OutBroadcast {
5142 broadcast_contacts_added.push(*contact_id);
5143 }
5144 }
5145 Ok(broadcast_contacts_added)
5146 })
5147 .await?;
5148 let timestamp = smeared_time(context);
5149 for added_id in broadcast_contacts_added {
5150 let msg = stock_str::msg_add_member_local(context, added_id, ContactId::UNDEFINED).await;
5151 add_info_msg_with_cmd(
5152 context,
5153 id,
5154 &msg,
5155 SystemMessage::MemberAddedToGroup,
5156 Some(timestamp),
5157 timestamp,
5158 None,
5159 Some(ContactId::SELF),
5160 Some(added_id),
5161 )
5162 .await?;
5163 }
5164 context.emit_event(EventType::ChatModified(id));
5165 Ok(())
5166}
5167
5168#[derive(Debug, Serialize, Deserialize, PartialEq)]
5170pub(crate) enum SyncId {
5171 ContactAddr(String),
5173
5174 ContactFingerprint(String),
5176
5177 Grpid(String),
5178 Msgids(Vec<String>),
5180
5181 Device,
5183}
5184
5185#[derive(Debug, Serialize, Deserialize, PartialEq)]
5187pub(crate) enum SyncAction {
5188 Block,
5189 Unblock,
5190 Accept,
5191 SetVisibility(ChatVisibility),
5192 SetMuted(MuteDuration),
5193 CreateOutBroadcast {
5195 chat_name: String,
5196 secret: String,
5197 },
5198 CreateGroupEncrypted(String),
5200 Rename(String),
5201 SetContacts(Vec<String>),
5203 SetPgpContacts(Vec<(String, String)>),
5207 SetDescription(String),
5208 Delete,
5209}
5210
5211impl Context {
5212 pub(crate) async fn sync_alter_chat(&self, id: &SyncId, action: &SyncAction) -> Result<()> {
5214 let chat_id = match id {
5215 SyncId::ContactAddr(addr) => {
5216 if let SyncAction::Rename(to) = action {
5217 Contact::create_ex(self, Nosync, to, addr).await?;
5218 return Ok(());
5219 }
5220 let addr = ContactAddress::new(addr).context("Invalid address")?;
5221 let (contact_id, _) =
5222 Contact::add_or_lookup(self, "", &addr, Origin::Hidden).await?;
5223 match action {
5224 SyncAction::Block => {
5225 return contact::set_blocked(self, Nosync, contact_id, true).await;
5226 }
5227 SyncAction::Unblock => {
5228 return contact::set_blocked(self, Nosync, contact_id, false).await;
5229 }
5230 _ => (),
5231 }
5232 ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5235 .await?
5236 .id
5237 }
5238 SyncId::ContactFingerprint(fingerprint) => {
5239 let name = "";
5240 let addr = "";
5241 let (contact_id, _) =
5242 Contact::add_or_lookup_ex(self, name, addr, fingerprint, Origin::Hidden)
5243 .await?;
5244 match action {
5245 SyncAction::Rename(to) => {
5246 contact_id.set_name_ex(self, Nosync, to).await?;
5247 self.emit_event(EventType::ContactsChanged(Some(contact_id)));
5248 return Ok(());
5249 }
5250 SyncAction::Block => {
5251 return contact::set_blocked(self, Nosync, contact_id, true).await;
5252 }
5253 SyncAction::Unblock => {
5254 return contact::set_blocked(self, Nosync, contact_id, false).await;
5255 }
5256 _ => (),
5257 }
5258 ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5259 .await?
5260 .id
5261 }
5262 SyncId::Grpid(grpid) => {
5263 match action {
5264 SyncAction::CreateOutBroadcast { chat_name, secret } => {
5265 create_out_broadcast_ex(
5266 self,
5267 Nosync,
5268 grpid.to_string(),
5269 chat_name.clone(),
5270 secret.to_string(),
5271 )
5272 .await?;
5273 return Ok(());
5274 }
5275 SyncAction::CreateGroupEncrypted(name) => {
5276 create_group_ex(self, Nosync, grpid.clone(), name).await?;
5277 return Ok(());
5278 }
5279 _ => {}
5280 }
5281 get_chat_id_by_grpid(self, grpid)
5282 .await?
5283 .with_context(|| format!("No chat for grpid '{grpid}'"))?
5284 .0
5285 }
5286 SyncId::Msgids(msgids) => {
5287 let msg = message::get_by_rfc724_mids(self, msgids)
5288 .await?
5289 .with_context(|| format!("No message found for Message-IDs {msgids:?}"))?;
5290 ChatId::lookup_by_message(&msg)
5291 .with_context(|| format!("No chat found for Message-IDs {msgids:?}"))?
5292 }
5293 SyncId::Device => ChatId::get_for_contact(self, ContactId::DEVICE).await?,
5294 };
5295 match action {
5296 SyncAction::Block => chat_id.block_ex(self, Nosync).await,
5297 SyncAction::Unblock => chat_id.unblock_ex(self, Nosync).await,
5298 SyncAction::Accept => chat_id.accept_ex(self, Nosync).await,
5299 SyncAction::SetVisibility(v) => chat_id.set_visibility_ex(self, Nosync, *v).await,
5300 SyncAction::SetMuted(duration) => set_muted_ex(self, Nosync, chat_id, *duration).await,
5301 SyncAction::CreateOutBroadcast { .. } | SyncAction::CreateGroupEncrypted(..) => {
5302 Err(anyhow!("sync_alter_chat({id:?}, {action:?}): Bad request."))
5304 }
5305 SyncAction::Rename(to) => rename_ex(self, Nosync, chat_id, to).await,
5306 SyncAction::SetDescription(to) => {
5307 set_chat_description_ex(self, Nosync, chat_id, to).await
5308 }
5309 SyncAction::SetContacts(addrs) => set_contacts_by_addrs(self, chat_id, addrs).await,
5310 SyncAction::SetPgpContacts(fingerprint_addrs) => {
5311 set_contacts_by_fingerprints(self, chat_id, fingerprint_addrs).await
5312 }
5313 SyncAction::Delete => chat_id.delete_ex(self, Nosync).await,
5314 }
5315 }
5316
5317 pub(crate) fn on_archived_chats_maybe_noticed(&self) {
5322 self.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
5323 }
5324}
5325
5326#[cfg(test)]
5327mod chat_tests;