1use std::cmp;
4use std::collections::{HashMap, HashSet};
5use std::fmt;
6use std::io::Cursor;
7use std::marker::Sync;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10use std::time::Duration;
11
12use anyhow::{Context as _, Result, anyhow, bail, ensure};
13use chrono::TimeZone;
14use deltachat_contact_tools::{ContactAddress, sanitize_bidi_characters, sanitize_single_line};
15use humansize::{BINARY, format_size};
16use mail_builder::mime::MimePart;
17use serde::{Deserialize, Serialize};
18use strum_macros::EnumIter;
19
20use crate::blob::BlobObject;
21use crate::chatlist::Chatlist;
22use crate::chatlist_events;
23use crate::color::str_to_color;
24use crate::config::Config;
25use crate::constants::{
26 Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL,
27 DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, EDITED_PREFIX, 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::ephemeral::{Timer as EphemeralTimer, start_chat_ephemeral_timers};
36use crate::events::EventType;
37use crate::key::self_fingerprint;
38use crate::location;
39use crate::log::{LogExt, warn};
40use crate::logged_debug_assert;
41use crate::message::{self, Message, MessageState, MsgId, Viewtype};
42use crate::mimefactory::{MimeFactory, RenderedEmail};
43use crate::mimeparser::SystemMessage;
44use crate::param::{Param, Params};
45use crate::receive_imf::ReceivedMsg;
46use crate::smtp::{self, send_msg_to_smtp};
47use crate::stock_str;
48use crate::sync::{self, Sync::*, SyncData};
49use crate::tools::{
50 IsNoneOrEmpty, SystemTime, buf_compress, create_broadcast_secret, create_id,
51 create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path,
52 gm2local_offset, normalize_text, smeared_time, time, truncate_msg_text,
53};
54use crate::webxdc::StatusUpdateSerial;
55
56pub(crate) const PARAM_BROADCAST_SECRET: Param = Param::Arg3;
57
58#[derive(Debug, Copy, Clone, PartialEq, Eq)]
60pub enum ChatItem {
61 Message {
63 msg_id: MsgId,
65 },
66
67 DayMarker {
70 timestamp: i64,
72 },
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub(crate) enum CantSendReason {
80 SpecialChat,
82
83 DeviceChat,
85
86 ContactRequest,
88
89 ReadOnlyMailingList,
91
92 InBroadcast,
94
95 NotAMember,
97
98 MissingKey,
100}
101
102impl fmt::Display for CantSendReason {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 match self {
105 Self::SpecialChat => write!(f, "the chat is a special chat"),
106 Self::DeviceChat => write!(f, "the chat is a device chat"),
107 Self::ContactRequest => write!(
108 f,
109 "contact request chat should be accepted before sending messages"
110 ),
111 Self::ReadOnlyMailingList => {
112 write!(f, "mailing list does not have a know post address")
113 }
114 Self::InBroadcast => {
115 write!(f, "Broadcast channel is read-only")
116 }
117 Self::NotAMember => write!(f, "not a member of the chat"),
118 Self::MissingKey => write!(f, "key is missing"),
119 }
120 }
121}
122
123#[derive(
128 Debug, Copy, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Hash, PartialOrd, Ord,
129)]
130pub struct ChatId(u32);
131
132impl ChatId {
133 pub const fn new(id: u32) -> ChatId {
135 ChatId(id)
136 }
137
138 pub fn is_unset(self) -> bool {
142 self.0 == 0
143 }
144
145 pub fn is_special(self) -> bool {
149 (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)
150 }
151
152 pub fn is_trash(self) -> bool {
159 self == DC_CHAT_ID_TRASH
160 }
161
162 pub fn is_archived_link(self) -> bool {
169 self == DC_CHAT_ID_ARCHIVED_LINK
170 }
171
172 pub fn is_alldone_hint(self) -> bool {
181 self == DC_CHAT_ID_ALLDONE_HINT
182 }
183
184 pub(crate) fn lookup_by_message(msg: &Message) -> Option<Self> {
186 if msg.chat_id == DC_CHAT_ID_TRASH {
187 return None;
188 }
189 if msg.download_state == DownloadState::Undecipherable {
190 return None;
191 }
192 Some(msg.chat_id)
193 }
194
195 pub async fn lookup_by_contact(
200 context: &Context,
201 contact_id: ContactId,
202 ) -> Result<Option<Self>> {
203 let Some(chat_id_blocked) = ChatIdBlocked::lookup_by_contact(context, contact_id).await?
204 else {
205 return Ok(None);
206 };
207
208 let chat_id = match chat_id_blocked.blocked {
209 Blocked::Not | Blocked::Request => Some(chat_id_blocked.id),
210 Blocked::Yes => None,
211 };
212 Ok(chat_id)
213 }
214
215 pub(crate) async fn get_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
223 ChatIdBlocked::get_for_contact(context, contact_id, Blocked::Not)
224 .await
225 .map(|chat| chat.id)
226 }
227
228 pub async fn create_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
233 ChatId::create_for_contact_with_blocked(context, contact_id, Blocked::Not).await
234 }
235
236 pub(crate) async fn create_for_contact_with_blocked(
240 context: &Context,
241 contact_id: ContactId,
242 create_blocked: Blocked,
243 ) -> Result<Self> {
244 let chat_id = match ChatIdBlocked::lookup_by_contact(context, contact_id).await? {
245 Some(chat) => {
246 if create_blocked != Blocked::Not || chat.blocked == Blocked::Not {
247 return Ok(chat.id);
248 }
249 chat.id.set_blocked(context, Blocked::Not).await?;
250 chat.id
251 }
252 None => {
253 if Contact::real_exists_by_id(context, contact_id).await?
254 || contact_id == ContactId::SELF
255 {
256 let chat_id =
257 ChatIdBlocked::get_for_contact(context, contact_id, create_blocked)
258 .await
259 .map(|chat| chat.id)?;
260 ContactId::scaleup_origin(context, &[contact_id], Origin::CreateChat).await?;
261 chat_id
262 } else {
263 warn!(
264 context,
265 "Cannot create chat, contact {contact_id} does not exist."
266 );
267 bail!("Can not create chat for non-existing contact");
268 }
269 }
270 };
271 context.emit_msgs_changed_without_ids();
272 chatlist_events::emit_chatlist_changed(context);
273 chatlist_events::emit_chatlist_item_changed(context, chat_id);
274 Ok(chat_id)
275 }
276
277 pub(crate) async fn create_multiuser_record(
280 context: &Context,
281 chattype: Chattype,
282 grpid: &str,
283 grpname: &str,
284 create_blocked: Blocked,
285 param: Option<String>,
286 timestamp: i64,
287 ) -> Result<Self> {
288 let grpname = sanitize_single_line(grpname);
289 let timestamp = cmp::min(timestamp, smeared_time(context));
290 let row_id =
291 context.sql.insert(
292 "INSERT INTO chats (type, name, name_normalized, grpid, blocked, created_timestamp, protected, param) VALUES(?, ?, ?, ?, ?, ?, 0, ?)",
293 (
294 chattype,
295 &grpname,
296 normalize_text(&grpname),
297 grpid,
298 create_blocked,
299 timestamp,
300 param.unwrap_or_default(),
301 ),
302 ).await?;
303
304 let chat_id = ChatId::new(u32::try_from(row_id)?);
305 let chat = Chat::load_from_db(context, chat_id).await?;
306
307 if chat.is_encrypted(context).await? {
308 chat_id.add_e2ee_notice(context, timestamp).await?;
309 }
310
311 info!(
312 context,
313 "Created group/broadcast '{}' grpid={} as {}, blocked={}.",
314 &grpname,
315 grpid,
316 chat_id,
317 create_blocked,
318 );
319
320 Ok(chat_id)
321 }
322
323 async fn set_selfavatar_timestamp(self, context: &Context, timestamp: i64) -> Result<()> {
324 context
325 .sql
326 .execute(
327 "UPDATE contacts
328 SET selfavatar_sent=?
329 WHERE id IN(SELECT contact_id FROM chats_contacts WHERE chat_id=? AND add_timestamp >= remove_timestamp)",
330 (timestamp, self),
331 )
332 .await?;
333 Ok(())
334 }
335
336 pub(crate) async fn set_blocked(self, context: &Context, new_blocked: Blocked) -> Result<bool> {
340 if self.is_special() {
341 bail!("ignoring setting of Block-status for {self}");
342 }
343 let count = context
344 .sql
345 .execute(
346 "UPDATE chats SET blocked=?1 WHERE id=?2 AND blocked != ?1",
347 (new_blocked, self),
348 )
349 .await?;
350 Ok(count > 0)
351 }
352
353 pub async fn block(self, context: &Context) -> Result<()> {
355 self.block_ex(context, Sync).await
356 }
357
358 pub(crate) async fn block_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
359 let chat = Chat::load_from_db(context, self).await?;
360 let mut delete = false;
361
362 match chat.typ {
363 Chattype::OutBroadcast => {
364 bail!("Can't block chat of type {:?}", chat.typ)
365 }
366 Chattype::Single => {
367 for contact_id in get_chat_contacts(context, self).await? {
368 if contact_id != ContactId::SELF {
369 info!(
370 context,
371 "Blocking the contact {contact_id} to block 1:1 chat."
372 );
373 contact::set_blocked(context, Nosync, contact_id, true).await?;
374 }
375 }
376 }
377 Chattype::Group => {
378 info!(context, "Can't block groups yet, deleting the chat.");
379 delete = true;
380 }
381 Chattype::Mailinglist | Chattype::InBroadcast => {
382 if self.set_blocked(context, Blocked::Yes).await? {
383 context.emit_event(EventType::ChatModified(self));
384 }
385 }
386 }
387 chatlist_events::emit_chatlist_changed(context);
388
389 if sync.into() {
390 chat.sync(context, SyncAction::Block)
392 .await
393 .log_err(context)
394 .ok();
395 }
396 if delete {
397 self.delete_ex(context, Nosync).await?;
398 }
399 Ok(())
400 }
401
402 pub async fn unblock(self, context: &Context) -> Result<()> {
404 self.unblock_ex(context, Sync).await
405 }
406
407 pub(crate) async fn unblock_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
408 self.set_blocked(context, Blocked::Not).await?;
409
410 chatlist_events::emit_chatlist_changed(context);
411
412 if sync.into() {
413 let chat = Chat::load_from_db(context, self).await?;
414 chat.sync(context, SyncAction::Unblock)
418 .await
419 .log_err(context)
420 .ok();
421 }
422
423 Ok(())
424 }
425
426 pub async fn accept(self, context: &Context) -> Result<()> {
430 self.accept_ex(context, Sync).await
431 }
432
433 pub(crate) async fn accept_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
434 let chat = Chat::load_from_db(context, self).await?;
435
436 match chat.typ {
437 Chattype::Single | Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast => {
438 let origin = match chat.typ {
444 Chattype::Group => Origin::IncomingTo,
445 _ => Origin::CreateChat,
446 };
447 for contact_id in get_chat_contacts(context, self).await? {
448 if contact_id != ContactId::SELF {
449 ContactId::scaleup_origin(context, &[contact_id], origin).await?;
450 }
451 }
452 }
453 Chattype::Mailinglist => {
454 }
456 }
457
458 if self.set_blocked(context, Blocked::Not).await? {
459 context.emit_event(EventType::ChatModified(self));
460 chatlist_events::emit_chatlist_item_changed(context, self);
461 }
462
463 if sync.into() {
464 chat.sync(context, SyncAction::Accept)
465 .await
466 .log_err(context)
467 .ok();
468 }
469 Ok(())
470 }
471
472 pub(crate) async fn add_e2ee_notice(self, context: &Context, timestamp: i64) -> Result<()> {
474 let text = stock_str::messages_e2e_encrypted(context).await;
475 add_info_msg_with_cmd(
476 context,
477 self,
478 &text,
479 SystemMessage::ChatE2ee,
480 Some(timestamp),
481 timestamp,
482 None,
483 None,
484 None,
485 )
486 .await?;
487 Ok(())
488 }
489
490 pub async fn set_visibility(self, context: &Context, visibility: ChatVisibility) -> Result<()> {
492 self.set_visibility_ex(context, Sync, visibility).await
493 }
494
495 pub(crate) async fn set_visibility_ex(
496 self,
497 context: &Context,
498 sync: sync::Sync,
499 visibility: ChatVisibility,
500 ) -> Result<()> {
501 ensure!(
502 !self.is_special(),
503 "bad chat_id, can not be special chat: {self}"
504 );
505
506 context
507 .sql
508 .transaction(move |transaction| {
509 if visibility == ChatVisibility::Archived {
510 transaction.execute(
511 "UPDATE msgs SET state=? WHERE chat_id=? AND state=?;",
512 (MessageState::InNoticed, self, MessageState::InFresh),
513 )?;
514 }
515 transaction.execute(
516 "UPDATE chats SET archived=? WHERE id=?;",
517 (visibility, self),
518 )?;
519 Ok(())
520 })
521 .await?;
522
523 if visibility == ChatVisibility::Archived {
524 start_chat_ephemeral_timers(context, self).await?;
525 }
526
527 context.emit_msgs_changed_without_ids();
528 chatlist_events::emit_chatlist_changed(context);
529 chatlist_events::emit_chatlist_item_changed(context, self);
530
531 if sync.into() {
532 let chat = Chat::load_from_db(context, self).await?;
533 chat.sync(context, SyncAction::SetVisibility(visibility))
534 .await
535 .log_err(context)
536 .ok();
537 }
538 Ok(())
539 }
540
541 pub async fn unarchive_if_not_muted(
549 self,
550 context: &Context,
551 msg_state: MessageState,
552 ) -> Result<()> {
553 if msg_state != MessageState::InFresh {
554 context
555 .sql
556 .execute(
557 "UPDATE chats SET archived=0 WHERE id=? AND archived=1 \
558 AND NOT(muted_until=-1 OR muted_until>?)",
559 (self, time()),
560 )
561 .await?;
562 return Ok(());
563 }
564 let chat = Chat::load_from_db(context, self).await?;
565 if chat.visibility != ChatVisibility::Archived {
566 return Ok(());
567 }
568 if chat.is_muted() {
569 let unread_cnt = context
570 .sql
571 .count(
572 "SELECT COUNT(*)
573 FROM msgs
574 WHERE state=?
575 AND hidden=0
576 AND chat_id=?",
577 (MessageState::InFresh, self),
578 )
579 .await?;
580 if unread_cnt == 1 {
581 context.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
583 }
584 return Ok(());
585 }
586 context
587 .sql
588 .execute("UPDATE chats SET archived=0 WHERE id=?", (self,))
589 .await?;
590 Ok(())
591 }
592
593 pub(crate) fn emit_msg_event(self, context: &Context, msg_id: MsgId, important: bool) {
596 if important {
597 debug_assert!(!msg_id.is_unset());
598
599 context.emit_incoming_msg(self, msg_id);
600 } else {
601 context.emit_msgs_changed(self, msg_id);
602 }
603 }
604
605 pub async fn delete(self, context: &Context) -> Result<()> {
611 self.delete_ex(context, Sync).await
612 }
613
614 pub(crate) async fn delete_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
615 ensure!(
616 !self.is_special(),
617 "bad chat_id, can not be a special chat: {self}"
618 );
619
620 let chat = Chat::load_from_db(context, self).await?;
621 let sync_id = match sync {
622 Nosync => None,
623 Sync => chat.get_sync_id(context).await?,
624 };
625
626 context
627 .sql
628 .transaction(|transaction| {
629 transaction.execute(
630 "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT rfc724_mid FROM msgs WHERE chat_id=? AND rfc724_mid!='')",
631 (self,),
632 )?;
633 transaction.execute(
634 "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT pre_rfc724_mid FROM msgs WHERE chat_id=? AND pre_rfc724_mid!='')",
635 (self,),
636 )?;
637 transaction.execute(
638 "DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?)",
639 (self,),
640 )?;
641 transaction.execute(
644 "
645INSERT OR REPLACE INTO msgs (id, rfc724_mid, pre_rfc724_mid, timestamp, chat_id, deleted)
646SELECT id, rfc724_mid, pre_rfc724_mid, timestamp, ?, 1 FROM msgs WHERE chat_id=?
647 ",
648 (DC_CHAT_ID_TRASH, self),
649 )?;
650 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (self,))?;
651 transaction.execute("DELETE FROM chats WHERE id=?", (self,))?;
652 Ok(())
653 })
654 .await?;
655
656 context.emit_event(EventType::ChatDeleted { chat_id: self });
657 context.emit_msgs_changed_without_ids();
658
659 if let Some(id) = sync_id {
660 self::sync(context, id, SyncAction::Delete)
661 .await
662 .log_err(context)
663 .ok();
664 }
665
666 if chat.is_self_talk() {
667 let mut msg = Message::new_text(stock_str::self_deleted_msg_body(context).await);
668 add_device_msg(context, None, Some(&mut msg)).await?;
669 }
670 chatlist_events::emit_chatlist_changed(context);
671
672 context
673 .set_config_internal(Config::LastHousekeeping, None)
674 .await?;
675 context.scheduler.interrupt_smtp().await;
676
677 Ok(())
678 }
679
680 pub async fn set_draft(self, context: &Context, mut msg: Option<&mut Message>) -> Result<()> {
684 if self.is_special() {
685 return Ok(());
686 }
687
688 let changed = match &mut msg {
689 None => self.maybe_delete_draft(context).await?,
690 Some(msg) => self.do_set_draft(context, msg).await?,
691 };
692
693 if changed {
694 if msg.is_some() {
695 match self.get_draft_msg_id(context).await? {
696 Some(msg_id) => context.emit_msgs_changed(self, msg_id),
697 None => context.emit_msgs_changed_without_msg_id(self),
698 }
699 } else {
700 context.emit_msgs_changed_without_msg_id(self)
701 }
702 }
703
704 Ok(())
705 }
706
707 async fn get_draft_msg_id(self, context: &Context) -> Result<Option<MsgId>> {
709 let msg_id: Option<MsgId> = context
710 .sql
711 .query_get_value(
712 "SELECT id FROM msgs WHERE chat_id=? AND state=?;",
713 (self, MessageState::OutDraft),
714 )
715 .await?;
716 Ok(msg_id)
717 }
718
719 pub async fn get_draft(self, context: &Context) -> Result<Option<Message>> {
721 if self.is_special() {
722 return Ok(None);
723 }
724 match self.get_draft_msg_id(context).await? {
725 Some(draft_msg_id) => {
726 let msg = Message::load_from_db(context, draft_msg_id).await?;
727 Ok(Some(msg))
728 }
729 None => Ok(None),
730 }
731 }
732
733 async fn maybe_delete_draft(self, context: &Context) -> Result<bool> {
737 Ok(context
738 .sql
739 .execute(
740 "DELETE FROM msgs WHERE chat_id=? AND state=?",
741 (self, MessageState::OutDraft),
742 )
743 .await?
744 > 0)
745 }
746
747 async fn do_set_draft(self, context: &Context, msg: &mut Message) -> Result<bool> {
750 match msg.viewtype {
751 Viewtype::Unknown => bail!("Can not set draft of unknown type."),
752 Viewtype::Text => {
753 if msg.text.is_empty() && msg.in_reply_to.is_none_or_empty() {
754 bail!("No text and no quote in draft");
755 }
756 }
757 _ => {
758 if msg.viewtype == Viewtype::File
759 && let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg)
760 .filter(|&(vt, _)| vt == Viewtype::Webxdc || vt == Viewtype::Vcard)
765 {
766 msg.viewtype = better_type;
767 }
768 if msg.viewtype == Viewtype::Vcard {
769 let blob = msg
770 .param
771 .get_file_blob(context)?
772 .context("no file stored in params")?;
773 msg.try_set_vcard(context, &blob.to_abs_path()).await?;
774 }
775 }
776 }
777
778 msg.state = MessageState::OutDraft;
781 msg.chat_id = self;
782
783 if !msg.id.is_special()
785 && let Some(old_draft) = self.get_draft(context).await?
786 && old_draft.id == msg.id
787 && old_draft.chat_id == self
788 && old_draft.state == MessageState::OutDraft
789 {
790 let affected_rows = context
791 .sql.execute(
792 "UPDATE msgs
793 SET timestamp=?1,type=?2,txt=?3,txt_normalized=?4,param=?5,mime_in_reply_to=?6
794 WHERE id=?7
795 AND (type <> ?2
796 OR txt <> ?3
797 OR txt_normalized <> ?4
798 OR param <> ?5
799 OR mime_in_reply_to <> ?6);",
800 (
801 time(),
802 msg.viewtype,
803 &msg.text,
804 normalize_text(&msg.text),
805 msg.param.to_string(),
806 msg.in_reply_to.as_deref().unwrap_or_default(),
807 msg.id,
808 ),
809 ).await?;
810 return Ok(affected_rows > 0);
811 }
812
813 let row_id = context
814 .sql
815 .transaction(|transaction| {
816 transaction.execute(
818 "DELETE FROM msgs WHERE chat_id=? AND state=?",
819 (self, MessageState::OutDraft),
820 )?;
821
822 transaction.execute(
824 "INSERT INTO msgs (
825 chat_id,
826 rfc724_mid,
827 from_id,
828 timestamp,
829 type,
830 state,
831 txt,
832 txt_normalized,
833 param,
834 hidden,
835 mime_in_reply_to)
836 VALUES (?,?,?,?,?,?,?,?,?,?,?);",
837 (
838 self,
839 &msg.rfc724_mid,
840 ContactId::SELF,
841 time(),
842 msg.viewtype,
843 MessageState::OutDraft,
844 &msg.text,
845 normalize_text(&msg.text),
846 msg.param.to_string(),
847 1,
848 msg.in_reply_to.as_deref().unwrap_or_default(),
849 ),
850 )?;
851
852 Ok(transaction.last_insert_rowid())
853 })
854 .await?;
855 msg.id = MsgId::new(row_id.try_into()?);
856 Ok(true)
857 }
858
859 pub async fn get_msg_cnt(self, context: &Context) -> Result<usize> {
861 let count = context
862 .sql
863 .count(
864 "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id=?",
865 (self,),
866 )
867 .await?;
868 Ok(count)
869 }
870
871 pub async fn get_fresh_msg_cnt(self, context: &Context) -> Result<usize> {
873 let count = if self.is_archived_link() {
884 context
885 .sql
886 .count(
887 "SELECT COUNT(DISTINCT(m.chat_id))
888 FROM msgs m
889 LEFT JOIN chats c ON m.chat_id=c.id
890 WHERE m.state=10
891 and m.hidden=0
892 AND m.chat_id>9
893 AND c.blocked=0
894 AND c.archived=1
895 ",
896 (),
897 )
898 .await?
899 } else {
900 context
901 .sql
902 .count(
903 "SELECT COUNT(*)
904 FROM msgs
905 WHERE state=?
906 AND hidden=0
907 AND chat_id=?;",
908 (MessageState::InFresh, self),
909 )
910 .await?
911 };
912 Ok(count)
913 }
914
915 pub(crate) async fn created_timestamp(self, context: &Context) -> Result<i64> {
916 Ok(context
917 .sql
918 .query_get_value("SELECT created_timestamp FROM chats WHERE id=?", (self,))
919 .await?
920 .unwrap_or(0))
921 }
922
923 pub(crate) async fn get_timestamp(self, context: &Context) -> Result<Option<i64>> {
926 let timestamp = context
927 .sql
928 .query_get_value(
929 "SELECT MAX(timestamp)
930 FROM msgs
931 WHERE chat_id=?
932 HAVING COUNT(*) > 0",
933 (self,),
934 )
935 .await?;
936 Ok(timestamp)
937 }
938
939 pub async fn get_similar_chat_ids(self, context: &Context) -> Result<Vec<(ChatId, f64)>> {
945 let intersection = context
947 .sql
948 .query_map_vec(
949 "SELECT y.chat_id, SUM(x.contact_id = y.contact_id)
950 FROM chats_contacts as x
951 JOIN chats_contacts as y
952 WHERE x.contact_id > 9
953 AND y.contact_id > 9
954 AND x.add_timestamp >= x.remove_timestamp
955 AND y.add_timestamp >= y.remove_timestamp
956 AND x.chat_id=?
957 AND y.chat_id<>x.chat_id
958 AND y.chat_id>?
959 GROUP BY y.chat_id",
960 (self, DC_CHAT_ID_LAST_SPECIAL),
961 |row| {
962 let chat_id: ChatId = row.get(0)?;
963 let intersection: f64 = row.get(1)?;
964 Ok((chat_id, intersection))
965 },
966 )
967 .await
968 .context("failed to calculate member set intersections")?;
969
970 let chat_size: HashMap<ChatId, f64> = context
971 .sql
972 .query_map_collect(
973 "SELECT chat_id, count(*) AS n
974 FROM chats_contacts
975 WHERE contact_id > ? AND chat_id > ?
976 AND add_timestamp >= remove_timestamp
977 GROUP BY chat_id",
978 (ContactId::LAST_SPECIAL, DC_CHAT_ID_LAST_SPECIAL),
979 |row| {
980 let chat_id: ChatId = row.get(0)?;
981 let size: f64 = row.get(1)?;
982 Ok((chat_id, size))
983 },
984 )
985 .await
986 .context("failed to count chat member sizes")?;
987
988 let our_chat_size = chat_size.get(&self).copied().unwrap_or_default();
989 let mut chats_with_metrics = Vec::new();
990 for (chat_id, intersection_size) in intersection {
991 if intersection_size > 0.0 {
992 let other_chat_size = chat_size.get(&chat_id).copied().unwrap_or_default();
993 let union_size = our_chat_size + other_chat_size - intersection_size;
994 let metric = intersection_size / union_size;
995 chats_with_metrics.push((chat_id, metric))
996 }
997 }
998 chats_with_metrics.sort_unstable_by(|(chat_id1, metric1), (chat_id2, metric2)| {
999 metric2
1000 .partial_cmp(metric1)
1001 .unwrap_or(chat_id2.cmp(chat_id1))
1002 });
1003
1004 let mut res = Vec::new();
1006 let now = time();
1007 for (chat_id, metric) in chats_with_metrics {
1008 if let Some(chat_timestamp) = chat_id.get_timestamp(context).await?
1009 && now > chat_timestamp + 42 * 24 * 3600
1010 {
1011 continue;
1013 }
1014
1015 if metric < 0.1 {
1016 break;
1018 }
1019
1020 let chat = Chat::load_from_db(context, chat_id).await?;
1021 if chat.typ != Chattype::Group {
1022 continue;
1023 }
1024
1025 match chat.visibility {
1026 ChatVisibility::Normal | ChatVisibility::Pinned => {}
1027 ChatVisibility::Archived => continue,
1028 }
1029
1030 res.push((chat_id, metric));
1031 if res.len() >= 5 {
1032 break;
1033 }
1034 }
1035
1036 Ok(res)
1037 }
1038
1039 pub async fn get_similar_chatlist(self, context: &Context) -> Result<Chatlist> {
1043 let chat_ids: Vec<ChatId> = self
1044 .get_similar_chat_ids(context)
1045 .await
1046 .context("failed to get similar chat IDs")?
1047 .into_iter()
1048 .map(|(chat_id, _metric)| chat_id)
1049 .collect();
1050 let chatlist = Chatlist::from_chat_ids(context, &chat_ids).await?;
1051 Ok(chatlist)
1052 }
1053
1054 pub(crate) async fn get_param(self, context: &Context) -> Result<Params> {
1055 let res: Option<String> = context
1056 .sql
1057 .query_get_value("SELECT param FROM chats WHERE id=?", (self,))
1058 .await?;
1059 Ok(res
1060 .map(|s| s.parse().unwrap_or_default())
1061 .unwrap_or_default())
1062 }
1063
1064 pub(crate) async fn is_unpromoted(self, context: &Context) -> Result<bool> {
1066 let param = self.get_param(context).await?;
1067 let unpromoted = param.get_bool(Param::Unpromoted).unwrap_or_default();
1068 Ok(unpromoted)
1069 }
1070
1071 pub(crate) async fn is_promoted(self, context: &Context) -> Result<bool> {
1073 let promoted = !self.is_unpromoted(context).await?;
1074 Ok(promoted)
1075 }
1076
1077 pub async fn is_self_talk(self, context: &Context) -> Result<bool> {
1079 Ok(self.get_param(context).await?.exists(Param::Selftalk))
1080 }
1081
1082 pub async fn is_device_talk(self, context: &Context) -> Result<bool> {
1084 Ok(self.get_param(context).await?.exists(Param::Devicetalk))
1085 }
1086
1087 async fn parent_query<T, F>(
1088 self,
1089 context: &Context,
1090 fields: &str,
1091 state_out_min: MessageState,
1092 f: F,
1093 ) -> Result<Option<T>>
1094 where
1095 F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
1096 T: Send + 'static,
1097 {
1098 let sql = &context.sql;
1099 let query = format!(
1100 "SELECT {fields} \
1101 FROM msgs \
1102 WHERE chat_id=? \
1103 AND ((state BETWEEN {} AND {}) OR (state >= {})) \
1104 AND NOT hidden \
1105 AND download_state={} \
1106 AND from_id != {} \
1107 ORDER BY timestamp DESC, id DESC \
1108 LIMIT 1;",
1109 MessageState::InFresh as u32,
1110 MessageState::InSeen as u32,
1111 state_out_min as u32,
1112 DownloadState::Done as u32,
1115 ContactId::INFO.to_u32(),
1118 );
1119 sql.query_row_optional(&query, (self,), f).await
1120 }
1121
1122 async fn get_parent_mime_headers(
1123 self,
1124 context: &Context,
1125 state_out_min: MessageState,
1126 ) -> Result<Option<(String, String, String)>> {
1127 self.parent_query(
1128 context,
1129 "rfc724_mid, mime_in_reply_to, IFNULL(mime_references, '')",
1130 state_out_min,
1131 |row: &rusqlite::Row| {
1132 let rfc724_mid: String = row.get(0)?;
1133 let mime_in_reply_to: String = row.get(1)?;
1134 let mime_references: String = row.get(2)?;
1135 Ok((rfc724_mid, mime_in_reply_to, mime_references))
1136 },
1137 )
1138 .await
1139 }
1140
1141 pub async fn get_encryption_info(self, context: &Context) -> Result<String> {
1149 let chat = Chat::load_from_db(context, self).await?;
1150 if !chat.is_encrypted(context).await? {
1151 return Ok(stock_str::encr_none(context).await);
1152 }
1153
1154 let mut ret = stock_str::messages_e2e_encrypted(context).await + "\n";
1155
1156 for &contact_id in get_chat_contacts(context, self)
1157 .await?
1158 .iter()
1159 .filter(|&contact_id| !contact_id.is_special())
1160 {
1161 let contact = Contact::get_by_id(context, contact_id).await?;
1162 let addr = contact.get_addr();
1163 logged_debug_assert!(
1164 context,
1165 contact.is_key_contact(),
1166 "get_encryption_info: contact {contact_id} is not a key-contact."
1167 );
1168 let fingerprint = contact
1169 .fingerprint()
1170 .context("Contact does not have a fingerprint in encrypted chat")?;
1171 if contact.public_key(context).await?.is_some() {
1172 ret += &format!("\n{addr}\n{fingerprint}\n");
1173 } else {
1174 ret += &format!("\n{addr}\n(key missing)\n{fingerprint}\n");
1175 }
1176 }
1177
1178 Ok(ret.trim().to_string())
1179 }
1180
1181 pub fn to_u32(self) -> u32 {
1186 self.0
1187 }
1188
1189 pub(crate) async fn reset_gossiped_timestamp(self, context: &Context) -> Result<()> {
1190 context
1191 .sql
1192 .execute("DELETE FROM gossip_timestamp WHERE chat_id=?", (self,))
1193 .await?;
1194 Ok(())
1195 }
1196
1197 pub(crate) async fn calc_sort_timestamp(
1206 self,
1207 context: &Context,
1208 message_timestamp: i64,
1209 always_sort_to_bottom: bool,
1210 received: bool,
1211 incoming: bool,
1212 ) -> Result<i64> {
1213 let mut sort_timestamp = cmp::min(message_timestamp, smeared_time(context));
1214
1215 let last_msg_time: Option<i64> = if always_sort_to_bottom {
1216 context
1222 .sql
1223 .query_get_value(
1224 "SELECT MAX(timestamp)
1225 FROM msgs
1226 WHERE chat_id=? AND state!=?
1227 HAVING COUNT(*) > 0",
1228 (self, MessageState::OutDraft),
1229 )
1230 .await?
1231 } else if received {
1232 context
1243 .sql
1244 .query_row_optional(
1245 "SELECT MAX(timestamp), MAX(IIF(state=?,timestamp_sent,0))
1246 FROM msgs
1247 WHERE chat_id=? AND hidden=0 AND state>?
1248 HAVING COUNT(*) > 0",
1249 (MessageState::InSeen, self, MessageState::InFresh),
1250 |row| {
1251 let ts: i64 = row.get(0)?;
1252 let ts_sent_seen: i64 = row.get(1)?;
1253 Ok((ts, ts_sent_seen))
1254 },
1255 )
1256 .await?
1257 .and_then(|(ts, ts_sent_seen)| {
1258 match incoming || ts_sent_seen <= message_timestamp {
1259 true => Some(ts),
1260 false => None,
1261 }
1262 })
1263 } else {
1264 None
1265 };
1266
1267 if let Some(last_msg_time) = last_msg_time
1268 && last_msg_time > sort_timestamp
1269 {
1270 sort_timestamp = last_msg_time;
1271 }
1272
1273 Ok(sort_timestamp)
1274 }
1275}
1276
1277impl std::fmt::Display for ChatId {
1278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1279 if self.is_trash() {
1280 write!(f, "Chat#Trash")
1281 } else if self.is_archived_link() {
1282 write!(f, "Chat#ArchivedLink")
1283 } else if self.is_alldone_hint() {
1284 write!(f, "Chat#AlldoneHint")
1285 } else if self.is_special() {
1286 write!(f, "Chat#Special{}", self.0)
1287 } else {
1288 write!(f, "Chat#{}", self.0)
1289 }
1290 }
1291}
1292
1293impl rusqlite::types::ToSql for ChatId {
1298 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
1299 let val = rusqlite::types::Value::Integer(i64::from(self.0));
1300 let out = rusqlite::types::ToSqlOutput::Owned(val);
1301 Ok(out)
1302 }
1303}
1304
1305impl rusqlite::types::FromSql for ChatId {
1307 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
1308 i64::column_result(value).and_then(|val| {
1309 if 0 <= val && val <= i64::from(u32::MAX) {
1310 Ok(ChatId::new(val as u32))
1311 } else {
1312 Err(rusqlite::types::FromSqlError::OutOfRange(val))
1313 }
1314 })
1315 }
1316}
1317
1318#[derive(Debug, Clone, Deserialize, Serialize)]
1323pub struct Chat {
1324 pub id: ChatId,
1326
1327 pub typ: Chattype,
1329
1330 pub name: String,
1332
1333 pub visibility: ChatVisibility,
1335
1336 pub grpid: String,
1339
1340 pub blocked: Blocked,
1342
1343 pub param: Params,
1345
1346 is_sending_locations: bool,
1348
1349 pub mute_duration: MuteDuration,
1351}
1352
1353impl Chat {
1354 pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> {
1356 let mut chat = context
1357 .sql
1358 .query_row(
1359 "SELECT c.type, c.name, c.grpid, c.param, c.archived,
1360 c.blocked, c.locations_send_until, c.muted_until
1361 FROM chats c
1362 WHERE c.id=?;",
1363 (chat_id,),
1364 |row| {
1365 let c = Chat {
1366 id: chat_id,
1367 typ: row.get(0)?,
1368 name: row.get::<_, String>(1)?,
1369 grpid: row.get::<_, String>(2)?,
1370 param: row.get::<_, String>(3)?.parse().unwrap_or_default(),
1371 visibility: row.get(4)?,
1372 blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
1373 is_sending_locations: row.get(6)?,
1374 mute_duration: row.get(7)?,
1375 };
1376 Ok(c)
1377 },
1378 )
1379 .await
1380 .context(format!("Failed loading chat {chat_id} from database"))?;
1381
1382 if chat.id.is_archived_link() {
1383 chat.name = stock_str::archived_chats(context).await;
1384 } else {
1385 if chat.typ == Chattype::Single && chat.name.is_empty() {
1386 let mut chat_name = "Err [Name not found]".to_owned();
1389 match get_chat_contacts(context, chat.id).await {
1390 Ok(contacts) => {
1391 if let Some(contact_id) = contacts.first()
1392 && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1393 {
1394 contact.get_display_name().clone_into(&mut chat_name);
1395 }
1396 }
1397 Err(err) => {
1398 error!(
1399 context,
1400 "Failed to load contacts for {}: {:#}.", chat.id, err
1401 );
1402 }
1403 }
1404 chat.name = chat_name;
1405 }
1406 if chat.param.exists(Param::Selftalk) {
1407 chat.name = stock_str::saved_messages(context).await;
1408 } else if chat.param.exists(Param::Devicetalk) {
1409 chat.name = stock_str::device_messages(context).await;
1410 }
1411 }
1412
1413 Ok(chat)
1414 }
1415
1416 pub fn is_self_talk(&self) -> bool {
1418 self.param.exists(Param::Selftalk)
1419 }
1420
1421 pub fn is_device_talk(&self) -> bool {
1423 self.param.exists(Param::Devicetalk)
1424 }
1425
1426 pub fn is_mailing_list(&self) -> bool {
1428 self.typ == Chattype::Mailinglist
1429 }
1430
1431 pub(crate) async fn why_cant_send(&self, context: &Context) -> Result<Option<CantSendReason>> {
1435 self.why_cant_send_ex(context, &|_| false).await
1436 }
1437
1438 pub(crate) async fn why_cant_send_ex(
1439 &self,
1440 context: &Context,
1441 skip_fn: &(dyn Send + Sync + Fn(&CantSendReason) -> bool),
1442 ) -> Result<Option<CantSendReason>> {
1443 use CantSendReason::*;
1444 if self.id.is_special() {
1447 let reason = SpecialChat;
1448 if !skip_fn(&reason) {
1449 return Ok(Some(reason));
1450 }
1451 }
1452 if self.is_device_talk() {
1453 let reason = DeviceChat;
1454 if !skip_fn(&reason) {
1455 return Ok(Some(reason));
1456 }
1457 }
1458 if self.is_contact_request() {
1459 let reason = ContactRequest;
1460 if !skip_fn(&reason) {
1461 return Ok(Some(reason));
1462 }
1463 }
1464 if self.is_mailing_list() && self.get_mailinglist_addr().is_none_or_empty() {
1465 let reason = ReadOnlyMailingList;
1466 if !skip_fn(&reason) {
1467 return Ok(Some(reason));
1468 }
1469 }
1470 if self.typ == Chattype::InBroadcast {
1471 let reason = InBroadcast;
1472 if !skip_fn(&reason) {
1473 return Ok(Some(reason));
1474 }
1475 }
1476
1477 let reason = NotAMember;
1479 if !skip_fn(&reason) && !self.is_self_in_chat(context).await? {
1480 return Ok(Some(reason));
1481 }
1482
1483 let reason = MissingKey;
1484 if !skip_fn(&reason) && self.typ == Chattype::Single {
1485 let contact_ids = get_chat_contacts(context, self.id).await?;
1486 if let Some(contact_id) = contact_ids.first() {
1487 let contact = Contact::get_by_id(context, *contact_id).await?;
1488 if contact.is_key_contact() && contact.public_key(context).await?.is_none() {
1489 return Ok(Some(reason));
1490 }
1491 }
1492 }
1493
1494 Ok(None)
1495 }
1496
1497 pub async fn can_send(&self, context: &Context) -> Result<bool> {
1501 Ok(self.why_cant_send(context).await?.is_none())
1502 }
1503
1504 pub async fn is_self_in_chat(&self, context: &Context) -> Result<bool> {
1508 match self.typ {
1509 Chattype::Single | Chattype::OutBroadcast | Chattype::Mailinglist => Ok(true),
1510 Chattype::Group | Chattype::InBroadcast => {
1511 is_contact_in_chat(context, self.id, ContactId::SELF).await
1512 }
1513 }
1514 }
1515
1516 pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {
1517 context
1518 .sql
1519 .execute(
1520 "UPDATE chats SET param=? WHERE id=?",
1521 (self.param.to_string(), self.id),
1522 )
1523 .await?;
1524 Ok(())
1525 }
1526
1527 pub fn get_id(&self) -> ChatId {
1529 self.id
1530 }
1531
1532 pub fn get_type(&self) -> Chattype {
1534 self.typ
1535 }
1536
1537 pub fn get_name(&self) -> &str {
1539 &self.name
1540 }
1541
1542 pub fn get_mailinglist_addr(&self) -> Option<&str> {
1544 self.param.get(Param::ListPost)
1545 }
1546
1547 pub async fn get_profile_image(&self, context: &Context) -> Result<Option<PathBuf>> {
1549 if self.id.is_archived_link() {
1550 return Ok(Some(get_archive_icon(context).await?));
1553 } else if self.is_device_talk() {
1554 return Ok(Some(get_device_icon(context).await?));
1555 } else if self.is_self_talk() {
1556 return Ok(Some(get_saved_messages_icon(context).await?));
1557 } else if !self.is_encrypted(context).await? {
1558 return Ok(Some(get_abs_path(
1560 context,
1561 Path::new(&get_unencrypted_icon(context).await?),
1562 )));
1563 } else if self.typ == Chattype::Single {
1564 let contacts = get_chat_contacts(context, self.id).await?;
1568 if let Some(contact_id) = contacts.first() {
1569 let contact = Contact::get_by_id(context, *contact_id).await?;
1570 return contact.get_profile_image(context).await;
1571 }
1572 } else if let Some(image_rel) = self.param.get(Param::ProfileImage) {
1573 if !image_rel.is_empty() {
1575 return Ok(Some(get_abs_path(context, Path::new(&image_rel))));
1576 }
1577 }
1578 Ok(None)
1579 }
1580
1581 pub async fn get_color(&self, context: &Context) -> Result<u32> {
1587 let mut color = 0;
1588
1589 if self.typ == Chattype::Single {
1590 let contacts = get_chat_contacts(context, self.id).await?;
1591 if let Some(contact_id) = contacts.first()
1592 && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1593 {
1594 color = contact.get_color();
1595 }
1596 } else if !self.grpid.is_empty() {
1597 color = str_to_color(&self.grpid);
1598 } else {
1599 color = str_to_color(&self.name);
1600 }
1601
1602 Ok(color)
1603 }
1604
1605 pub async fn get_info(&self, context: &Context) -> Result<ChatInfo> {
1610 let draft = match self.id.get_draft(context).await? {
1611 Some(message) => message.text,
1612 _ => String::new(),
1613 };
1614 Ok(ChatInfo {
1615 id: self.id,
1616 type_: self.typ as u32,
1617 name: self.name.clone(),
1618 archived: self.visibility == ChatVisibility::Archived,
1619 param: self.param.to_string(),
1620 is_sending_locations: self.is_sending_locations,
1621 color: self.get_color(context).await?,
1622 profile_image: self
1623 .get_profile_image(context)
1624 .await?
1625 .unwrap_or_else(std::path::PathBuf::new),
1626 draft,
1627 is_muted: self.is_muted(),
1628 ephemeral_timer: self.id.get_ephemeral_timer(context).await?,
1629 })
1630 }
1631
1632 pub fn get_visibility(&self) -> ChatVisibility {
1634 self.visibility
1635 }
1636
1637 pub fn is_contact_request(&self) -> bool {
1642 self.blocked == Blocked::Request
1643 }
1644
1645 pub fn is_unpromoted(&self) -> bool {
1647 self.param.get_bool(Param::Unpromoted).unwrap_or_default()
1648 }
1649
1650 pub fn is_promoted(&self) -> bool {
1653 !self.is_unpromoted()
1654 }
1655
1656 pub async fn is_encrypted(&self, context: &Context) -> Result<bool> {
1658 let is_encrypted = self.is_self_talk()
1659 || match self.typ {
1660 Chattype::Single => {
1661 match context
1662 .sql
1663 .query_row_optional(
1664 "SELECT cc.contact_id, c.fingerprint<>''
1665 FROM chats_contacts cc LEFT JOIN contacts c
1666 ON c.id=cc.contact_id
1667 WHERE cc.chat_id=?
1668 ",
1669 (self.id,),
1670 |row| {
1671 let id: ContactId = row.get(0)?;
1672 let is_key: bool = row.get(1)?;
1673 Ok((id, is_key))
1674 },
1675 )
1676 .await?
1677 {
1678 Some((id, is_key)) => is_key || id == ContactId::DEVICE,
1679 None => true,
1680 }
1681 }
1682 Chattype::Group => {
1683 !self.grpid.is_empty()
1685 }
1686 Chattype::Mailinglist => false,
1687 Chattype::OutBroadcast | Chattype::InBroadcast => true,
1688 };
1689 Ok(is_encrypted)
1690 }
1691
1692 pub fn is_sending_locations(&self) -> bool {
1694 self.is_sending_locations
1695 }
1696
1697 pub fn is_muted(&self) -> bool {
1699 match self.mute_duration {
1700 MuteDuration::NotMuted => false,
1701 MuteDuration::Forever => true,
1702 MuteDuration::Until(when) => when > SystemTime::now(),
1703 }
1704 }
1705
1706 pub(crate) async fn member_list_timestamp(&self, context: &Context) -> Result<i64> {
1708 if let Some(member_list_timestamp) = self.param.get_i64(Param::MemberListTimestamp) {
1709 Ok(member_list_timestamp)
1710 } else {
1711 Ok(self.id.created_timestamp(context).await?)
1712 }
1713 }
1714
1715 pub(crate) async fn member_list_is_stale(&self, context: &Context) -> Result<bool> {
1721 let now = time();
1722 let member_list_ts = self.member_list_timestamp(context).await?;
1723 let is_stale = now.saturating_add(TIMESTAMP_SENT_TOLERANCE)
1724 >= member_list_ts.saturating_add(60 * 24 * 3600);
1725 Ok(is_stale)
1726 }
1727
1728 async fn prepare_msg_raw(
1734 &mut self,
1735 context: &Context,
1736 msg: &mut Message,
1737 update_msg_id: Option<MsgId>,
1738 ) -> Result<()> {
1739 let mut to_id = 0;
1740 let mut location_id = 0;
1741
1742 if msg.rfc724_mid.is_empty() {
1743 msg.rfc724_mid = create_outgoing_rfc724_mid();
1744 }
1745
1746 if self.typ == Chattype::Single {
1747 if let Some(id) = context
1748 .sql
1749 .query_get_value(
1750 "SELECT contact_id FROM chats_contacts WHERE chat_id=?;",
1751 (self.id,),
1752 )
1753 .await?
1754 {
1755 to_id = id;
1756 } else {
1757 error!(
1758 context,
1759 "Cannot send message, contact for {} not found.", self.id,
1760 );
1761 bail!("Cannot set message, contact for {} not found.", self.id);
1762 }
1763 } else if matches!(self.typ, Chattype::Group | Chattype::OutBroadcast)
1764 && self.param.get_int(Param::Unpromoted).unwrap_or_default() == 1
1765 {
1766 msg.param.set_int(Param::AttachGroupImage, 1);
1767 self.param
1768 .remove(Param::Unpromoted)
1769 .set_i64(Param::GroupNameTimestamp, msg.timestamp_sort);
1770 self.update_param(context).await?;
1771 context
1777 .sync_qr_code_tokens(Some(self.grpid.as_str()))
1778 .await
1779 .log_err(context)
1780 .ok();
1781 }
1782
1783 let is_bot = context.get_config_bool(Config::Bot).await?;
1784 msg.param
1785 .set_optional(Param::Bot, Some("1").filter(|_| is_bot));
1786
1787 let new_references;
1791 if self.is_self_talk() {
1792 new_references = String::new();
1795 } else if let Some((parent_rfc724_mid, parent_in_reply_to, parent_references)) =
1796 self
1802 .id
1803 .get_parent_mime_headers(context, MessageState::OutPending)
1804 .await?
1805 {
1806 if msg.in_reply_to.is_none() && !parent_rfc724_mid.is_empty() {
1810 msg.in_reply_to = Some(parent_rfc724_mid.clone());
1811 }
1812
1813 let parent_references = if parent_references.is_empty() {
1823 parent_in_reply_to
1824 } else {
1825 parent_references
1826 };
1827
1828 let mut references_vec: Vec<&str> = parent_references.rsplit(' ').take(2).collect();
1831 references_vec.reverse();
1832
1833 if !parent_rfc724_mid.is_empty()
1834 && !references_vec.contains(&parent_rfc724_mid.as_str())
1835 {
1836 references_vec.push(&parent_rfc724_mid)
1837 }
1838
1839 if references_vec.is_empty() {
1840 new_references = msg.rfc724_mid.clone();
1843 } else {
1844 new_references = references_vec.join(" ");
1845 }
1846 } else {
1847 new_references = msg.rfc724_mid.clone();
1853 }
1854
1855 if msg.param.exists(Param::SetLatitude)
1857 && let Ok(row_id) = context
1858 .sql
1859 .insert(
1860 "INSERT INTO locations \
1861 (timestamp,from_id,chat_id, latitude,longitude,independent)\
1862 VALUES (?,?,?, ?,?,1);",
1863 (
1864 msg.timestamp_sort,
1865 ContactId::SELF,
1866 self.id,
1867 msg.param.get_float(Param::SetLatitude).unwrap_or_default(),
1868 msg.param.get_float(Param::SetLongitude).unwrap_or_default(),
1869 ),
1870 )
1871 .await
1872 {
1873 location_id = row_id;
1874 }
1875
1876 let ephemeral_timer = if msg.param.get_cmd() == SystemMessage::EphemeralTimerChanged {
1877 EphemeralTimer::Disabled
1878 } else {
1879 self.id.get_ephemeral_timer(context).await?
1880 };
1881 let ephemeral_timestamp = match ephemeral_timer {
1882 EphemeralTimer::Disabled => 0,
1883 EphemeralTimer::Enabled { duration } => time().saturating_add(duration.into()),
1884 };
1885
1886 let (msg_text, was_truncated) = truncate_msg_text(context, msg.text.clone()).await?;
1887 let new_mime_headers = if msg.has_html() {
1888 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1889 } else {
1890 None
1891 };
1892 let new_mime_headers: Option<String> = new_mime_headers.map(|s| {
1893 let html_part = MimePart::new("text/html", s);
1894 let mut buffer = Vec::new();
1895 let cursor = Cursor::new(&mut buffer);
1896 html_part.write_part(cursor).ok();
1897 String::from_utf8_lossy(&buffer).to_string()
1898 });
1899 let new_mime_headers = new_mime_headers.or_else(|| match was_truncated {
1900 true => Some("Content-Type: text/plain; charset=utf-8\r\n\r\n".to_string() + &msg.text),
1904 false => None,
1905 });
1906 let new_mime_headers = match new_mime_headers {
1907 Some(h) => Some(tokio::task::block_in_place(move || {
1908 buf_compress(h.as_bytes())
1909 })?),
1910 None => None,
1911 };
1912
1913 msg.chat_id = self.id;
1914 msg.from_id = ContactId::SELF;
1915
1916 if let Some(update_msg_id) = update_msg_id {
1918 context
1919 .sql
1920 .execute(
1921 "UPDATE msgs
1922 SET rfc724_mid=?, chat_id=?, from_id=?, to_id=?, timestamp=?, type=?,
1923 state=?, txt=?, txt_normalized=?, subject=?, param=?,
1924 hidden=?, mime_in_reply_to=?, mime_references=?, mime_modified=?,
1925 mime_headers=?, mime_compressed=1, location_id=?, ephemeral_timer=?,
1926 ephemeral_timestamp=?
1927 WHERE id=?;",
1928 params_slice![
1929 msg.rfc724_mid,
1930 msg.chat_id,
1931 msg.from_id,
1932 to_id,
1933 msg.timestamp_sort,
1934 msg.viewtype,
1935 msg.state,
1936 msg_text,
1937 normalize_text(&msg_text),
1938 &msg.subject,
1939 msg.param.to_string(),
1940 msg.hidden,
1941 msg.in_reply_to.as_deref().unwrap_or_default(),
1942 new_references,
1943 new_mime_headers.is_some(),
1944 new_mime_headers.unwrap_or_default(),
1945 location_id as i32,
1946 ephemeral_timer,
1947 ephemeral_timestamp,
1948 update_msg_id
1949 ],
1950 )
1951 .await?;
1952 msg.id = update_msg_id;
1953 } else {
1954 let raw_id = context
1955 .sql
1956 .insert(
1957 "INSERT INTO msgs (
1958 rfc724_mid,
1959 chat_id,
1960 from_id,
1961 to_id,
1962 timestamp,
1963 type,
1964 state,
1965 txt,
1966 txt_normalized,
1967 subject,
1968 param,
1969 hidden,
1970 mime_in_reply_to,
1971 mime_references,
1972 mime_modified,
1973 mime_headers,
1974 mime_compressed,
1975 location_id,
1976 ephemeral_timer,
1977 ephemeral_timestamp)
1978 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?,?);",
1979 params_slice![
1980 msg.rfc724_mid,
1981 msg.chat_id,
1982 msg.from_id,
1983 to_id,
1984 msg.timestamp_sort,
1985 msg.viewtype,
1986 msg.state,
1987 msg_text,
1988 normalize_text(&msg_text),
1989 &msg.subject,
1990 msg.param.to_string(),
1991 msg.hidden,
1992 msg.in_reply_to.as_deref().unwrap_or_default(),
1993 new_references,
1994 new_mime_headers.is_some(),
1995 new_mime_headers.unwrap_or_default(),
1996 location_id as i32,
1997 ephemeral_timer,
1998 ephemeral_timestamp
1999 ],
2000 )
2001 .await?;
2002 context.new_msgs_notify.notify_one();
2003 msg.id = MsgId::new(u32::try_from(raw_id)?);
2004
2005 maybe_set_logging_xdc(context, msg, self.id).await?;
2006 context
2007 .update_webxdc_integration_database(msg, context)
2008 .await?;
2009 }
2010 context.scheduler.interrupt_ephemeral_task().await;
2011 Ok(())
2012 }
2013
2014 pub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> {
2016 if self.is_encrypted(context).await? {
2017 let self_fp = self_fingerprint(context).await?;
2018 let fingerprint_addrs = context
2019 .sql
2020 .query_map_vec(
2021 "SELECT c.id, c.fingerprint, c.addr
2022 FROM contacts c INNER JOIN chats_contacts cc
2023 ON c.id=cc.contact_id
2024 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2025 (self.id,),
2026 |row| {
2027 if row.get::<_, ContactId>(0)? == ContactId::SELF {
2028 return Ok((self_fp.to_string(), String::new()));
2029 }
2030 let fingerprint = row.get(1)?;
2031 let addr = row.get(2)?;
2032 Ok((fingerprint, addr))
2033 },
2034 )
2035 .await?;
2036 self.sync(context, SyncAction::SetPgpContacts(fingerprint_addrs))
2037 .await?;
2038 } else {
2039 let addrs = context
2040 .sql
2041 .query_map_vec(
2042 "SELECT c.addr \
2043 FROM contacts c INNER JOIN chats_contacts cc \
2044 ON c.id=cc.contact_id \
2045 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2046 (self.id,),
2047 |row| {
2048 let addr: String = row.get(0)?;
2049 Ok(addr)
2050 },
2051 )
2052 .await?;
2053 self.sync(context, SyncAction::SetContacts(addrs)).await?;
2054 }
2055 Ok(())
2056 }
2057
2058 async fn get_sync_id(&self, context: &Context) -> Result<Option<SyncId>> {
2060 match self.typ {
2061 Chattype::Single => {
2062 if self.is_device_talk() {
2063 return Ok(Some(SyncId::Device));
2064 }
2065
2066 let mut r = None;
2067 for contact_id in get_chat_contacts(context, self.id).await? {
2068 if contact_id == ContactId::SELF && !self.is_self_talk() {
2069 continue;
2070 }
2071 if r.is_some() {
2072 return Ok(None);
2073 }
2074 let contact = Contact::get_by_id(context, contact_id).await?;
2075 if let Some(fingerprint) = contact.fingerprint() {
2076 r = Some(SyncId::ContactFingerprint(fingerprint.hex()));
2077 } else {
2078 r = Some(SyncId::ContactAddr(contact.get_addr().to_string()));
2079 }
2080 }
2081 Ok(r)
2082 }
2083 Chattype::OutBroadcast
2084 | Chattype::InBroadcast
2085 | Chattype::Group
2086 | Chattype::Mailinglist => {
2087 if !self.grpid.is_empty() {
2088 return Ok(Some(SyncId::Grpid(self.grpid.clone())));
2089 }
2090
2091 let Some((parent_rfc724_mid, parent_in_reply_to, _)) = self
2092 .id
2093 .get_parent_mime_headers(context, MessageState::OutDelivered)
2094 .await?
2095 else {
2096 warn!(
2097 context,
2098 "Chat::get_sync_id({}): No good message identifying the chat found.",
2099 self.id
2100 );
2101 return Ok(None);
2102 };
2103 Ok(Some(SyncId::Msgids(vec![
2104 parent_in_reply_to,
2105 parent_rfc724_mid,
2106 ])))
2107 }
2108 }
2109 }
2110
2111 pub(crate) async fn sync(&self, context: &Context, action: SyncAction) -> Result<()> {
2113 if let Some(id) = self.get_sync_id(context).await? {
2114 sync(context, id, action).await?;
2115 }
2116 Ok(())
2117 }
2118}
2119
2120pub(crate) async fn sync(context: &Context, id: SyncId, action: SyncAction) -> Result<()> {
2121 context
2122 .add_sync_item(SyncData::AlterChat { id, action })
2123 .await?;
2124 context.scheduler.interrupt_smtp().await;
2125 Ok(())
2126}
2127
2128#[derive(Debug, Copy, Eq, PartialEq, Clone, Serialize, Deserialize, EnumIter, Default)]
2130#[repr(i8)]
2131pub enum ChatVisibility {
2132 #[default]
2134 Normal = 0,
2135
2136 Archived = 1,
2138
2139 Pinned = 2,
2141}
2142
2143impl rusqlite::types::ToSql for ChatVisibility {
2144 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
2145 let val = rusqlite::types::Value::Integer(*self as i64);
2146 let out = rusqlite::types::ToSqlOutput::Owned(val);
2147 Ok(out)
2148 }
2149}
2150
2151impl rusqlite::types::FromSql for ChatVisibility {
2152 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
2153 i64::column_result(value).map(|val| {
2154 match val {
2155 2 => ChatVisibility::Pinned,
2156 1 => ChatVisibility::Archived,
2157 0 => ChatVisibility::Normal,
2158 _ => ChatVisibility::Normal,
2160 }
2161 })
2162 }
2163}
2164
2165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2167#[non_exhaustive]
2168pub struct ChatInfo {
2169 pub id: ChatId,
2171
2172 #[serde(rename = "type")]
2179 pub type_: u32,
2180
2181 pub name: String,
2183
2184 pub archived: bool,
2186
2187 pub param: String,
2191
2192 pub is_sending_locations: bool,
2194
2195 pub color: u32,
2199
2200 pub profile_image: std::path::PathBuf,
2205
2206 pub draft: String,
2214
2215 pub is_muted: bool,
2219
2220 pub ephemeral_timer: EphemeralTimer,
2222 }
2228
2229async fn get_asset_icon(context: &Context, name: &str, bytes: &[u8]) -> Result<PathBuf> {
2230 ensure!(name.starts_with("icon-"));
2231 if let Some(icon) = context.sql.get_raw_config(name).await? {
2232 return Ok(get_abs_path(context, Path::new(&icon)));
2233 }
2234
2235 let blob =
2236 BlobObject::create_and_deduplicate_from_bytes(context, bytes, &format!("{name}.png"))?;
2237 let icon = blob.as_name().to_string();
2238 context.sql.set_raw_config(name, Some(&icon)).await?;
2239
2240 Ok(get_abs_path(context, Path::new(&icon)))
2241}
2242
2243pub(crate) async fn get_saved_messages_icon(context: &Context) -> Result<PathBuf> {
2244 get_asset_icon(
2245 context,
2246 "icon-saved-messages",
2247 include_bytes!("../assets/icon-saved-messages.png"),
2248 )
2249 .await
2250}
2251
2252pub(crate) async fn get_device_icon(context: &Context) -> Result<PathBuf> {
2253 get_asset_icon(
2254 context,
2255 "icon-device",
2256 include_bytes!("../assets/icon-device.png"),
2257 )
2258 .await
2259}
2260
2261pub(crate) async fn get_archive_icon(context: &Context) -> Result<PathBuf> {
2262 get_asset_icon(
2263 context,
2264 "icon-archive",
2265 include_bytes!("../assets/icon-archive.png"),
2266 )
2267 .await
2268}
2269
2270pub(crate) async fn get_unencrypted_icon(context: &Context) -> Result<PathBuf> {
2273 get_asset_icon(
2274 context,
2275 "icon-unencrypted",
2276 include_bytes!("../assets/icon-unencrypted.png"),
2277 )
2278 .await
2279}
2280
2281async fn update_special_chat_name(
2282 context: &Context,
2283 contact_id: ContactId,
2284 name: String,
2285) -> Result<()> {
2286 if let Some(ChatIdBlocked { id: chat_id, .. }) =
2287 ChatIdBlocked::lookup_by_contact(context, contact_id).await?
2288 {
2289 context
2291 .sql
2292 .execute(
2293 "UPDATE chats SET name=?, name_normalized=? WHERE id=? AND name!=?",
2294 (&name, normalize_text(&name), chat_id, &name),
2295 )
2296 .await?;
2297 }
2298 Ok(())
2299}
2300
2301pub(crate) async fn update_special_chat_names(context: &Context) -> Result<()> {
2302 update_special_chat_name(
2303 context,
2304 ContactId::DEVICE,
2305 stock_str::device_messages(context).await,
2306 )
2307 .await?;
2308 update_special_chat_name(
2309 context,
2310 ContactId::SELF,
2311 stock_str::saved_messages(context).await,
2312 )
2313 .await?;
2314 Ok(())
2315}
2316
2317#[derive(Debug)]
2325pub(crate) struct ChatIdBlocked {
2326 pub id: ChatId,
2328
2329 pub blocked: Blocked,
2331}
2332
2333impl ChatIdBlocked {
2334 pub async fn lookup_by_contact(
2338 context: &Context,
2339 contact_id: ContactId,
2340 ) -> Result<Option<Self>> {
2341 ensure!(context.sql.is_open().await, "Database not available");
2342 ensure!(
2343 contact_id != ContactId::UNDEFINED,
2344 "Invalid contact id requested"
2345 );
2346
2347 context
2348 .sql
2349 .query_row_optional(
2350 "SELECT c.id, c.blocked
2351 FROM chats c
2352 INNER JOIN chats_contacts j
2353 ON c.id=j.chat_id
2354 WHERE c.type=100 -- 100 = Chattype::Single
2355 AND c.id>9 -- 9 = DC_CHAT_ID_LAST_SPECIAL
2356 AND j.contact_id=?;",
2357 (contact_id,),
2358 |row| {
2359 let id: ChatId = row.get(0)?;
2360 let blocked: Blocked = row.get(1)?;
2361 Ok(ChatIdBlocked { id, blocked })
2362 },
2363 )
2364 .await
2365 }
2366
2367 pub async fn get_for_contact(
2372 context: &Context,
2373 contact_id: ContactId,
2374 create_blocked: Blocked,
2375 ) -> Result<Self> {
2376 ensure!(context.sql.is_open().await, "Database not available");
2377 ensure!(
2378 contact_id != ContactId::UNDEFINED,
2379 "Invalid contact id requested"
2380 );
2381
2382 if let Some(res) = Self::lookup_by_contact(context, contact_id).await? {
2383 return Ok(res);
2385 }
2386
2387 let contact = Contact::get_by_id(context, contact_id).await?;
2388 let chat_name = contact.get_display_name().to_string();
2389 let mut params = Params::new();
2390 match contact_id {
2391 ContactId::SELF => {
2392 params.set_int(Param::Selftalk, 1);
2393 }
2394 ContactId::DEVICE => {
2395 params.set_int(Param::Devicetalk, 1);
2396 }
2397 _ => (),
2398 }
2399
2400 let smeared_time = create_smeared_timestamp(context);
2401
2402 let chat_id = context
2403 .sql
2404 .transaction(move |transaction| {
2405 transaction.execute(
2406 "INSERT INTO chats
2407 (type, name, name_normalized, param, blocked, created_timestamp)
2408 VALUES(?, ?, ?, ?, ?, ?)",
2409 (
2410 Chattype::Single,
2411 &chat_name,
2412 normalize_text(&chat_name),
2413 params.to_string(),
2414 create_blocked as u8,
2415 smeared_time,
2416 ),
2417 )?;
2418 let chat_id = ChatId::new(
2419 transaction
2420 .last_insert_rowid()
2421 .try_into()
2422 .context("chat table rowid overflows u32")?,
2423 );
2424
2425 transaction.execute(
2426 "INSERT INTO chats_contacts
2427 (chat_id, contact_id)
2428 VALUES((SELECT last_insert_rowid()), ?)",
2429 (contact_id,),
2430 )?;
2431
2432 Ok(chat_id)
2433 })
2434 .await?;
2435
2436 let chat = Chat::load_from_db(context, chat_id).await?;
2437 if chat.is_encrypted(context).await?
2438 && !chat.param.exists(Param::Devicetalk)
2439 && !chat.param.exists(Param::Selftalk)
2440 {
2441 chat_id.add_e2ee_notice(context, smeared_time).await?;
2442 }
2443
2444 Ok(Self {
2445 id: chat_id,
2446 blocked: create_blocked,
2447 })
2448 }
2449}
2450
2451async fn prepare_msg_blob(context: &Context, msg: &mut Message) -> Result<()> {
2452 if msg.viewtype == Viewtype::Text || msg.viewtype == Viewtype::Call {
2453 } else if msg.viewtype.has_file() {
2455 let viewtype_orig = msg.viewtype;
2456 let mut blob = msg
2457 .param
2458 .get_file_blob(context)?
2459 .with_context(|| format!("attachment missing for message of type #{}", msg.viewtype))?;
2460 let mut maybe_image = false;
2461
2462 if msg.viewtype == Viewtype::File
2463 || msg.viewtype == Viewtype::Image
2464 || msg.viewtype == Viewtype::Sticker && !msg.param.exists(Param::ForceSticker)
2465 {
2466 if let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg) {
2473 if msg.viewtype == Viewtype::Sticker {
2474 if better_type != Viewtype::Image {
2475 msg.param.set_int(Param::ForceSticker, 1);
2477 }
2478 } else 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
2499 || msg.viewtype == Viewtype::Image
2500 || msg.viewtype == Viewtype::Sticker && !msg.param.exists(Param::ForceSticker)
2501 {
2502 let new_name = blob
2503 .check_or_recode_image(context, msg.get_filename(), &mut msg.viewtype)
2504 .await?;
2505 msg.param.set(Param::Filename, new_name);
2506 msg.param.set(Param::File, blob.as_name());
2507 }
2508
2509 if !msg.param.exists(Param::MimeType)
2510 && let Some((viewtype, mime)) = message::guess_msgtype_from_suffix(msg)
2511 {
2512 let mime = match viewtype != Viewtype::Image
2515 || matches!(msg.viewtype, Viewtype::Image | Viewtype::Sticker)
2516 {
2517 true => mime,
2518 false => "application/octet-stream",
2519 };
2520 msg.param.set(Param::MimeType, mime);
2521 }
2522
2523 msg.try_calc_and_set_dimensions(context).await?;
2524
2525 let filename = msg.get_filename().context("msg has no file")?;
2526 let suffix = Path::new(&filename)
2527 .extension()
2528 .and_then(|e| e.to_str())
2529 .unwrap_or("dat");
2530 let filename: String = match viewtype_orig {
2534 Viewtype::Voice => format!(
2535 "voice-messsage_{}.{}",
2536 chrono::Utc
2537 .timestamp_opt(msg.timestamp_sort, 0)
2538 .single()
2539 .map_or_else(
2540 || "YY-mm-dd_hh:mm:ss".to_string(),
2541 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2542 ),
2543 &suffix
2544 ),
2545 Viewtype::Image | Viewtype::Gif => format!(
2546 "image_{}.{}",
2547 chrono::Utc
2548 .timestamp_opt(msg.timestamp_sort, 0)
2549 .single()
2550 .map_or_else(
2551 || "YY-mm-dd_hh:mm:ss".to_string(),
2552 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string(),
2553 ),
2554 &suffix,
2555 ),
2556 Viewtype::Video => format!(
2557 "video_{}.{}",
2558 chrono::Utc
2559 .timestamp_opt(msg.timestamp_sort, 0)
2560 .single()
2561 .map_or_else(
2562 || "YY-mm-dd_hh:mm:ss".to_string(),
2563 |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2564 ),
2565 &suffix
2566 ),
2567 _ => filename,
2568 };
2569 msg.param.set(Param::Filename, filename);
2570
2571 info!(
2572 context,
2573 "Attaching \"{}\" for message type #{}.",
2574 blob.to_abs_path().display(),
2575 msg.viewtype
2576 );
2577 } else {
2578 bail!("Cannot send messages of type #{}.", msg.viewtype);
2579 }
2580 Ok(())
2581}
2582
2583pub async fn is_contact_in_chat(
2585 context: &Context,
2586 chat_id: ChatId,
2587 contact_id: ContactId,
2588) -> Result<bool> {
2589 let exists = context
2596 .sql
2597 .exists(
2598 "SELECT COUNT(*) FROM chats_contacts
2599 WHERE chat_id=? AND contact_id=?
2600 AND add_timestamp >= remove_timestamp",
2601 (chat_id, contact_id),
2602 )
2603 .await?;
2604 Ok(exists)
2605}
2606
2607pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2614 ensure!(
2615 !chat_id.is_special(),
2616 "chat_id cannot be a special chat: {chat_id}"
2617 );
2618
2619 if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {
2620 msg.param.remove(Param::GuaranteeE2ee);
2621 msg.param.remove(Param::ForcePlaintext);
2622 msg.update_param(context).await?;
2623 }
2624
2625 if msg.is_system_message() {
2627 msg.text = sanitize_bidi_characters(&msg.text);
2628 }
2629
2630 if !prepare_send_msg(context, chat_id, msg).await?.is_empty() {
2631 if !msg.hidden {
2632 context.emit_msgs_changed(msg.chat_id, msg.id);
2633 }
2634
2635 if msg.param.exists(Param::SetLatitude) {
2636 context.emit_location_changed(Some(ContactId::SELF)).await?;
2637 }
2638
2639 context.scheduler.interrupt_smtp().await;
2640 }
2641
2642 Ok(msg.id)
2643}
2644
2645pub async fn send_msg_sync(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2650 let rowids = prepare_send_msg(context, chat_id, msg).await?;
2651 if rowids.is_empty() {
2652 return Ok(msg.id);
2653 }
2654 let mut smtp = crate::smtp::Smtp::new();
2655 for rowid in rowids {
2656 send_msg_to_smtp(context, &mut smtp, rowid)
2657 .await
2658 .context("failed to send message, queued for later sending")?;
2659 }
2660 context.emit_msgs_changed(msg.chat_id, msg.id);
2661 Ok(msg.id)
2662}
2663
2664async fn prepare_send_msg(
2668 context: &Context,
2669 chat_id: ChatId,
2670 msg: &mut Message,
2671) -> Result<Vec<i64>> {
2672 let mut chat = Chat::load_from_db(context, chat_id).await?;
2673
2674 let skip_fn = |reason: &CantSendReason| match reason {
2675 CantSendReason::ContactRequest => {
2676 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
2679 }
2680 CantSendReason::NotAMember => msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup,
2684 CantSendReason::InBroadcast => {
2685 matches!(
2686 msg.param.get_cmd(),
2687 SystemMessage::MemberRemovedFromGroup | SystemMessage::SecurejoinMessage
2688 )
2689 }
2690 CantSendReason::MissingKey => msg
2691 .param
2692 .get_bool(Param::ForcePlaintext)
2693 .unwrap_or_default(),
2694 _ => false,
2695 };
2696 if let Some(reason) = chat.why_cant_send_ex(context, &skip_fn).await? {
2697 bail!("Cannot send to {chat_id}: {reason}");
2698 }
2699
2700 if chat.typ != Chattype::Single
2705 && !context.get_config_bool(Config::Bot).await?
2706 && let Some(quoted_message) = msg.quoted_message(context).await?
2707 && quoted_message.chat_id != chat_id
2708 {
2709 bail!(
2710 "Quote of message from {} cannot be sent to {chat_id}",
2711 quoted_message.chat_id
2712 );
2713 }
2714
2715 let update_msg_id = if msg.state == MessageState::OutDraft {
2717 msg.hidden = false;
2718 if !msg.id.is_special() && msg.chat_id == chat_id {
2719 Some(msg.id)
2720 } else {
2721 None
2722 }
2723 } else {
2724 None
2725 };
2726
2727 msg.state = MessageState::OutPending;
2729
2730 msg.timestamp_sort = create_smeared_timestamp(context);
2731 prepare_msg_blob(context, msg).await?;
2732 if !msg.hidden {
2733 chat_id.unarchive_if_not_muted(context, msg.state).await?;
2734 }
2735 chat.prepare_msg_raw(context, msg, update_msg_id).await?;
2736
2737 let row_ids = create_send_msg_jobs(context, msg)
2738 .await
2739 .context("Failed to create send jobs")?;
2740 if !row_ids.is_empty() {
2741 donation_request_maybe(context).await.log_err(context).ok();
2742 }
2743 Ok(row_ids)
2744}
2745
2746async fn render_mime_message_and_pre_message(
2753 context: &Context,
2754 msg: &mut Message,
2755 mimefactory: MimeFactory,
2756) -> Result<(Option<RenderedEmail>, RenderedEmail)> {
2757 let needs_pre_message = msg.viewtype.has_file()
2758 && mimefactory.will_be_encrypted() && msg
2760 .get_filebytes(context)
2761 .await?
2762 .context("filebytes not available, even though message has attachment")?
2763 > PRE_MSG_ATTACHMENT_SIZE_THRESHOLD;
2764
2765 if needs_pre_message {
2766 info!(
2767 context,
2768 "Message {} is large and will be split into pre- and post-messages.", msg.id,
2769 );
2770
2771 let mut mimefactory_post_msg = mimefactory.clone();
2772 mimefactory_post_msg.set_as_post_message();
2773 let rendered_msg = mimefactory_post_msg
2774 .render(context)
2775 .await
2776 .context("Failed to render post-message")?;
2777
2778 let mut mimefactory_pre_msg = mimefactory;
2779 mimefactory_pre_msg.set_as_pre_message_for(&rendered_msg);
2780 let rendered_pre_msg = mimefactory_pre_msg
2781 .render(context)
2782 .await
2783 .context("pre-message failed to render")?;
2784
2785 if rendered_pre_msg.message.len() > PRE_MSG_SIZE_WARNING_THRESHOLD {
2786 warn!(
2787 context,
2788 "Pre-message for message {} is larger than expected: {}.",
2789 msg.id,
2790 rendered_pre_msg.message.len()
2791 );
2792 }
2793
2794 Ok((Some(rendered_pre_msg), rendered_msg))
2795 } else {
2796 Ok((None, mimefactory.render(context).await?))
2797 }
2798}
2799
2800pub(crate) async fn create_send_msg_jobs(context: &Context, msg: &mut Message) -> Result<Vec<i64>> {
2810 if msg.param.get_cmd() == SystemMessage::GroupNameChanged {
2811 msg.chat_id
2812 .update_timestamp(context, Param::GroupNameTimestamp, msg.timestamp_sort)
2813 .await?;
2814 }
2815
2816 let needs_encryption = msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default();
2817 let mimefactory = match MimeFactory::from_msg(context, msg.clone()).await {
2818 Ok(mf) => mf,
2819 Err(err) => {
2820 message::set_msg_failed(context, msg, &err.to_string())
2822 .await
2823 .ok();
2824 return Err(err);
2825 }
2826 };
2827 let attach_selfavatar = mimefactory.attach_selfavatar;
2828 let mut recipients = mimefactory.recipients();
2829
2830 let from = context.get_primary_self_addr().await?;
2831 let lowercase_from = from.to_lowercase();
2832
2833 recipients.retain(|x| x.to_lowercase() != lowercase_from);
2834 if context.get_config_bool(Config::BccSelf).await?
2835 || msg.param.get_cmd() == SystemMessage::AutocryptSetupMessage
2836 {
2837 smtp::add_self_recipients(context, &mut recipients, needs_encryption).await?;
2838 }
2839
2840 if msg.param.get_int(Param::WebxdcIntegration).is_some() && msg.hidden {
2842 recipients.clear();
2843 }
2844
2845 if recipients.is_empty() {
2846 info!(
2848 context,
2849 "Message {} has no recipient, skipping smtp-send.", msg.id
2850 );
2851 msg.param.set_int(Param::GuaranteeE2ee, 1);
2852 msg.update_param(context).await?;
2853 msg.id.set_delivered(context).await?;
2854 msg.state = MessageState::OutDelivered;
2855 return Ok(Vec::new());
2856 }
2857
2858 let (rendered_pre_msg, rendered_msg) =
2859 match render_mime_message_and_pre_message(context, msg, mimefactory).await {
2860 Ok(res) => Ok(res),
2861 Err(err) => {
2862 message::set_msg_failed(context, msg, &err.to_string()).await?;
2863 Err(err)
2864 }
2865 }?;
2866
2867 if let (post_msg, Some(pre_msg)) = (&rendered_msg, &rendered_pre_msg) {
2868 info!(
2869 context,
2870 "Message {} sizes: pre-message: {}; post-message: {}.",
2871 msg.id,
2872 format_size(pre_msg.message.len(), BINARY),
2873 format_size(post_msg.message.len(), BINARY),
2874 );
2875 msg.pre_rfc724_mid = pre_msg.rfc724_mid.clone();
2876 } else {
2877 info!(
2878 context,
2879 "Message {} will be sent in one shot (no pre- and post-message). Size: {}.",
2880 msg.id,
2881 format_size(rendered_msg.message.len(), BINARY),
2882 );
2883 }
2884
2885 if needs_encryption && !rendered_msg.is_encrypted {
2886 message::set_msg_failed(
2888 context,
2889 msg,
2890 "End-to-end-encryption unavailable unexpectedly.",
2891 )
2892 .await?;
2893 bail!(
2894 "e2e encryption unavailable {} - {:?}",
2895 msg.id,
2896 needs_encryption
2897 );
2898 }
2899
2900 let now = smeared_time(context);
2901
2902 if rendered_msg.last_added_location_id.is_some()
2903 && let Err(err) = location::set_kml_sent_timestamp(context, msg.chat_id, now).await
2904 {
2905 error!(context, "Failed to set kml sent_timestamp: {err:#}.");
2906 }
2907
2908 if attach_selfavatar && let Err(err) = msg.chat_id.set_selfavatar_timestamp(context, now).await
2909 {
2910 error!(context, "Failed to set selfavatar timestamp: {err:#}.");
2911 }
2912
2913 if rendered_msg.is_encrypted {
2914 msg.param.set_int(Param::GuaranteeE2ee, 1);
2915 } else {
2916 msg.param.remove(Param::GuaranteeE2ee);
2917 }
2918 msg.subject.clone_from(&rendered_msg.subject);
2919 context
2920 .sql
2921 .execute(
2922 "UPDATE msgs SET pre_rfc724_mid=?, subject=?, param=? WHERE id=?",
2923 (
2924 &msg.pre_rfc724_mid,
2925 &msg.subject,
2926 msg.param.to_string(),
2927 msg.id,
2928 ),
2929 )
2930 .await?;
2931
2932 let chunk_size = context.get_max_smtp_rcpt_to().await?;
2933 let trans_fn = |t: &mut rusqlite::Transaction| {
2934 let mut row_ids = Vec::<i64>::new();
2935
2936 if let Some(sync_ids) = rendered_msg.sync_ids_to_delete {
2937 t.execute(
2938 &format!("DELETE FROM multi_device_sync WHERE id IN ({sync_ids})"),
2939 (),
2940 )?;
2941 }
2942 let mut stmt = t.prepare(
2943 "INSERT INTO smtp (rfc724_mid, recipients, mime, msg_id)
2944 VALUES (?1, ?2, ?3, ?4)",
2945 )?;
2946 for recipients_chunk in recipients.chunks(chunk_size) {
2947 let recipients_chunk = recipients_chunk.join(" ");
2948 if let Some(pre_msg) = &rendered_pre_msg {
2949 let row_id = stmt.execute((
2950 &pre_msg.rfc724_mid,
2951 &recipients_chunk,
2952 &pre_msg.message,
2953 msg.id,
2954 ))?;
2955 row_ids.push(row_id.try_into()?);
2956 }
2957 let row_id = stmt.execute((
2958 &rendered_msg.rfc724_mid,
2959 &recipients_chunk,
2960 &rendered_msg.message,
2961 msg.id,
2962 ))?;
2963 row_ids.push(row_id.try_into()?);
2964 }
2965 Ok(row_ids)
2966 };
2967 context.sql.transaction(trans_fn).await
2968}
2969
2970pub async fn send_text_msg(
2974 context: &Context,
2975 chat_id: ChatId,
2976 text_to_send: String,
2977) -> Result<MsgId> {
2978 ensure!(
2979 !chat_id.is_special(),
2980 "bad chat_id, can not be a special chat: {chat_id}"
2981 );
2982
2983 let mut msg = Message::new_text(text_to_send);
2984 send_msg(context, chat_id, &mut msg).await
2985}
2986
2987pub async fn send_edit_request(context: &Context, msg_id: MsgId, new_text: String) -> Result<()> {
2989 let mut original_msg = Message::load_from_db(context, msg_id).await?;
2990 ensure!(
2991 original_msg.from_id == ContactId::SELF,
2992 "Can edit only own messages"
2993 );
2994 ensure!(!original_msg.is_info(), "Cannot edit info messages");
2995 ensure!(!original_msg.has_html(), "Cannot edit HTML messages");
2996 ensure!(original_msg.viewtype != Viewtype::Call, "Cannot edit calls");
2997 ensure!(
2998 !original_msg.text.is_empty(), "Cannot add text"
3000 );
3001 ensure!(!new_text.trim().is_empty(), "Edited text cannot be empty");
3002 if original_msg.text == new_text {
3003 info!(context, "Text unchanged.");
3004 return Ok(());
3005 }
3006
3007 save_text_edit_to_db(context, &mut original_msg, &new_text).await?;
3008
3009 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() {
3012 edit_msg.param.set_int(Param::GuaranteeE2ee, 1);
3013 }
3014 edit_msg
3015 .param
3016 .set(Param::TextEditFor, original_msg.rfc724_mid);
3017 edit_msg.hidden = true;
3018 send_msg(context, original_msg.chat_id, &mut edit_msg).await?;
3019 Ok(())
3020}
3021
3022pub(crate) async fn save_text_edit_to_db(
3023 context: &Context,
3024 original_msg: &mut Message,
3025 new_text: &str,
3026) -> Result<()> {
3027 original_msg.param.set_int(Param::IsEdited, 1);
3028 context
3029 .sql
3030 .execute(
3031 "UPDATE msgs SET txt=?, txt_normalized=?, param=? WHERE id=?",
3032 (
3033 new_text,
3034 normalize_text(new_text),
3035 original_msg.param.to_string(),
3036 original_msg.id,
3037 ),
3038 )
3039 .await?;
3040 context.emit_msgs_changed(original_msg.chat_id, original_msg.id);
3041 Ok(())
3042}
3043
3044async fn donation_request_maybe(context: &Context) -> Result<()> {
3045 let secs_between_checks = 30 * 24 * 60 * 60;
3046 let now = time();
3047 let ts = context
3048 .get_config_i64(Config::DonationRequestNextCheck)
3049 .await?;
3050 if ts > now {
3051 return Ok(());
3052 }
3053 let msg_cnt = context.sql.count(
3054 "SELECT COUNT(*) FROM msgs WHERE state>=? AND hidden=0",
3055 (MessageState::OutDelivered,),
3056 );
3057 let ts = if ts == 0 || msg_cnt.await? < 100 {
3058 now.saturating_add(secs_between_checks)
3059 } else {
3060 let mut msg = Message::new_text(stock_str::donation_request(context).await);
3061 add_device_msg(context, None, Some(&mut msg)).await?;
3062 i64::MAX
3063 };
3064 context
3065 .set_config_internal(Config::DonationRequestNextCheck, Some(&ts.to_string()))
3066 .await
3067}
3068
3069#[derive(Debug)]
3071pub struct MessageListOptions {
3072 pub info_only: bool,
3074
3075 pub add_daymarker: bool,
3077}
3078
3079pub async fn get_chat_msgs(context: &Context, chat_id: ChatId) -> Result<Vec<ChatItem>> {
3081 get_chat_msgs_ex(
3082 context,
3083 chat_id,
3084 MessageListOptions {
3085 info_only: false,
3086 add_daymarker: false,
3087 },
3088 )
3089 .await
3090}
3091
3092pub async fn get_chat_msgs_ex(
3094 context: &Context,
3095 chat_id: ChatId,
3096 options: MessageListOptions,
3097) -> Result<Vec<ChatItem>> {
3098 let MessageListOptions {
3099 info_only,
3100 add_daymarker,
3101 } = options;
3102 let process_row = if info_only {
3103 |row: &rusqlite::Row| {
3104 let params = row.get::<_, String>("param")?;
3106 let (from_id, to_id) = (
3107 row.get::<_, ContactId>("from_id")?,
3108 row.get::<_, ContactId>("to_id")?,
3109 );
3110 let is_info_msg: bool = from_id == ContactId::INFO
3111 || to_id == ContactId::INFO
3112 || match Params::from_str(¶ms) {
3113 Ok(p) => {
3114 let cmd = p.get_cmd();
3115 cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage
3116 }
3117 _ => false,
3118 };
3119
3120 Ok((
3121 row.get::<_, i64>("timestamp")?,
3122 row.get::<_, MsgId>("id")?,
3123 !is_info_msg,
3124 ))
3125 }
3126 } else {
3127 |row: &rusqlite::Row| {
3128 Ok((
3129 row.get::<_, i64>("timestamp")?,
3130 row.get::<_, MsgId>("id")?,
3131 false,
3132 ))
3133 }
3134 };
3135 let process_rows = |rows: rusqlite::AndThenRows<_>| {
3136 let mut sorted_rows = Vec::new();
3139 for row in rows {
3140 let (ts, curr_id, exclude_message): (i64, MsgId, bool) = row?;
3141 if !exclude_message {
3142 sorted_rows.push((ts, curr_id));
3143 }
3144 }
3145 sorted_rows.sort_unstable();
3146
3147 let mut ret = Vec::new();
3148 let mut last_day = 0;
3149 let cnv_to_local = gm2local_offset();
3150
3151 for (ts, curr_id) in sorted_rows {
3152 if add_daymarker {
3153 let curr_local_timestamp = ts + cnv_to_local;
3154 let secs_in_day = 86400;
3155 let curr_day = curr_local_timestamp / secs_in_day;
3156 if curr_day != last_day {
3157 ret.push(ChatItem::DayMarker {
3158 timestamp: curr_day * secs_in_day - cnv_to_local,
3159 });
3160 last_day = curr_day;
3161 }
3162 }
3163 ret.push(ChatItem::Message { msg_id: curr_id });
3164 }
3165 Ok(ret)
3166 };
3167
3168 let items = if info_only {
3169 context
3170 .sql
3171 .query_map(
3172 "SELECT m.id AS id, m.timestamp AS timestamp, m.param AS param, m.from_id AS from_id, m.to_id AS to_id
3174 FROM msgs m
3175 WHERE m.chat_id=?
3176 AND m.hidden=0
3177 AND (
3178 m.param GLOB '*\nS=*' OR param GLOB 'S=*'
3179 OR m.from_id == ?
3180 OR m.to_id == ?
3181 );",
3182 (chat_id, ContactId::INFO, ContactId::INFO),
3183 process_row,
3184 process_rows,
3185 )
3186 .await?
3187 } else {
3188 context
3189 .sql
3190 .query_map(
3191 "SELECT m.id AS id, m.timestamp AS timestamp
3192 FROM msgs m
3193 WHERE m.chat_id=?
3194 AND m.hidden=0;",
3195 (chat_id,),
3196 process_row,
3197 process_rows,
3198 )
3199 .await?
3200 };
3201 Ok(items)
3202}
3203
3204pub async fn marknoticed_all_chats(context: &Context) -> Result<()> {
3207 let list = context
3209 .sql
3210 .query_map_vec(
3211 "SELECT DISTINCT(c.id)
3212 FROM msgs m
3213 INNER JOIN chats c
3214 ON m.chat_id=c.id
3215 WHERE m.state=?
3216 AND m.hidden=0
3217 AND m.chat_id>9
3218 AND c.blocked=0;",
3219 (MessageState::InFresh,),
3220 |row| {
3221 let msg_id: ChatId = row.get(0)?;
3222 Ok(msg_id)
3223 },
3224 )
3225 .await?;
3226
3227 for chat_id in list {
3228 marknoticed_chat(context, chat_id).await?;
3229 }
3230
3231 Ok(())
3232}
3233
3234pub async fn marknoticed_chat(context: &Context, chat_id: ChatId) -> Result<()> {
3237 if chat_id.is_archived_link() {
3240 let chat_ids_in_archive = context
3241 .sql
3242 .query_map_vec(
3243 "SELECT DISTINCT(m.chat_id) FROM msgs m
3244 LEFT JOIN chats c ON m.chat_id=c.id
3245 WHERE m.state=10 AND m.hidden=0 AND m.chat_id>9 AND c.archived=1",
3246 (),
3247 |row| {
3248 let chat_id: ChatId = row.get(0)?;
3249 Ok(chat_id)
3250 },
3251 )
3252 .await?;
3253 if chat_ids_in_archive.is_empty() {
3254 return Ok(());
3255 }
3256
3257 context
3258 .sql
3259 .transaction(|transaction| {
3260 let mut stmt = transaction.prepare(
3261 "UPDATE msgs SET state=13 WHERE state=10 AND hidden=0 AND chat_id = ?",
3262 )?;
3263 for chat_id_in_archive in &chat_ids_in_archive {
3264 stmt.execute((chat_id_in_archive,))?;
3265 }
3266 Ok(())
3267 })
3268 .await?;
3269
3270 for chat_id_in_archive in chat_ids_in_archive {
3271 start_chat_ephemeral_timers(context, chat_id_in_archive).await?;
3272 context.emit_event(EventType::MsgsNoticed(chat_id_in_archive));
3273 chatlist_events::emit_chatlist_item_changed(context, chat_id_in_archive);
3274 }
3275 } else {
3276 start_chat_ephemeral_timers(context, chat_id).await?;
3277
3278 let noticed_msgs_count = context
3279 .sql
3280 .execute(
3281 "UPDATE msgs
3282 SET state=?
3283 WHERE state=?
3284 AND hidden=0
3285 AND chat_id=?;",
3286 (MessageState::InNoticed, MessageState::InFresh, chat_id),
3287 )
3288 .await?;
3289
3290 let hidden_messages = context
3293 .sql
3294 .query_map_vec(
3295 "SELECT id FROM msgs
3296 WHERE state=?
3297 AND hidden=1
3298 AND chat_id=?
3299 ORDER BY id LIMIT 100", (MessageState::InFresh, chat_id), |row| {
3302 let msg_id: MsgId = row.get(0)?;
3303 Ok(msg_id)
3304 },
3305 )
3306 .await?;
3307 message::markseen_msgs(context, hidden_messages).await?;
3308 if noticed_msgs_count == 0 {
3309 return Ok(());
3310 }
3311 }
3312
3313 context.emit_event(EventType::MsgsNoticed(chat_id));
3314 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3315 context.on_archived_chats_maybe_noticed();
3316 Ok(())
3317}
3318
3319pub(crate) async fn mark_old_messages_as_noticed(
3326 context: &Context,
3327 mut msgs: Vec<ReceivedMsg>,
3328) -> Result<()> {
3329 if context.get_config_bool(Config::TeamProfile).await? {
3330 return Ok(());
3331 }
3332
3333 msgs.retain(|m| m.state.is_outgoing());
3334 if msgs.is_empty() {
3335 return Ok(());
3336 }
3337
3338 let mut msgs_by_chat: HashMap<ChatId, ReceivedMsg> = HashMap::new();
3339 for msg in msgs {
3340 let chat_id = msg.chat_id;
3341 if let Some(existing_msg) = msgs_by_chat.get(&chat_id) {
3342 if msg.sort_timestamp > existing_msg.sort_timestamp {
3343 msgs_by_chat.insert(chat_id, msg);
3344 }
3345 } else {
3346 msgs_by_chat.insert(chat_id, msg);
3347 }
3348 }
3349
3350 let changed_chats = context
3351 .sql
3352 .transaction(|transaction| {
3353 let mut changed_chats = Vec::new();
3354 for (_, msg) in msgs_by_chat {
3355 let changed_rows = transaction.execute(
3356 "UPDATE msgs
3357 SET state=?
3358 WHERE state=?
3359 AND hidden=0
3360 AND chat_id=?
3361 AND timestamp<=?;",
3362 (
3363 MessageState::InNoticed,
3364 MessageState::InFresh,
3365 msg.chat_id,
3366 msg.sort_timestamp,
3367 ),
3368 )?;
3369 if changed_rows > 0 {
3370 changed_chats.push(msg.chat_id);
3371 }
3372 }
3373 Ok(changed_chats)
3374 })
3375 .await?;
3376
3377 if !changed_chats.is_empty() {
3378 info!(
3379 context,
3380 "Marking chats as noticed because there are newer outgoing messages: {changed_chats:?}."
3381 );
3382 context.on_archived_chats_maybe_noticed();
3383 }
3384
3385 for c in changed_chats {
3386 start_chat_ephemeral_timers(context, c).await?;
3387 context.emit_event(EventType::MsgsNoticed(c));
3388 chatlist_events::emit_chatlist_item_changed(context, c);
3389 }
3390
3391 Ok(())
3392}
3393
3394pub async fn get_chat_media(
3401 context: &Context,
3402 chat_id: Option<ChatId>,
3403 msg_type: Viewtype,
3404 msg_type2: Viewtype,
3405 msg_type3: Viewtype,
3406) -> Result<Vec<MsgId>> {
3407 let list = if msg_type == Viewtype::Webxdc
3408 && msg_type2 == Viewtype::Unknown
3409 && msg_type3 == Viewtype::Unknown
3410 {
3411 context
3412 .sql
3413 .query_map_vec(
3414 "SELECT id
3415 FROM msgs
3416 WHERE (1=? OR chat_id=?)
3417 AND chat_id != ?
3418 AND type = ?
3419 AND hidden=0
3420 ORDER BY max(timestamp, timestamp_rcvd), id;",
3421 (
3422 chat_id.is_none(),
3423 chat_id.unwrap_or_else(|| ChatId::new(0)),
3424 DC_CHAT_ID_TRASH,
3425 Viewtype::Webxdc,
3426 ),
3427 |row| {
3428 let msg_id: MsgId = row.get(0)?;
3429 Ok(msg_id)
3430 },
3431 )
3432 .await?
3433 } else {
3434 context
3435 .sql
3436 .query_map_vec(
3437 "SELECT id
3438 FROM msgs
3439 WHERE (1=? OR chat_id=?)
3440 AND chat_id != ?
3441 AND type IN (?, ?, ?)
3442 AND hidden=0
3443 ORDER BY timestamp, id;",
3444 (
3445 chat_id.is_none(),
3446 chat_id.unwrap_or_else(|| ChatId::new(0)),
3447 DC_CHAT_ID_TRASH,
3448 msg_type,
3449 if msg_type2 != Viewtype::Unknown {
3450 msg_type2
3451 } else {
3452 msg_type
3453 },
3454 if msg_type3 != Viewtype::Unknown {
3455 msg_type3
3456 } else {
3457 msg_type
3458 },
3459 ),
3460 |row| {
3461 let msg_id: MsgId = row.get(0)?;
3462 Ok(msg_id)
3463 },
3464 )
3465 .await?
3466 };
3467 Ok(list)
3468}
3469
3470pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3472 context
3475 .sql
3476 .query_map_vec(
3477 "SELECT cc.contact_id
3478 FROM chats_contacts cc
3479 LEFT JOIN contacts c
3480 ON c.id=cc.contact_id
3481 WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp
3482 ORDER BY c.id=1, c.last_seen DESC, c.id DESC;",
3483 (chat_id,),
3484 |row| {
3485 let contact_id: ContactId = row.get(0)?;
3486 Ok(contact_id)
3487 },
3488 )
3489 .await
3490}
3491
3492pub async fn get_past_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3496 let now = time();
3497 context
3498 .sql
3499 .query_map_vec(
3500 "SELECT cc.contact_id
3501 FROM chats_contacts cc
3502 LEFT JOIN contacts c
3503 ON c.id=cc.contact_id
3504 WHERE cc.chat_id=?
3505 AND cc.add_timestamp < cc.remove_timestamp
3506 AND ? < cc.remove_timestamp
3507 ORDER BY c.id=1, cc.remove_timestamp DESC, c.id DESC",
3508 (chat_id, now.saturating_sub(60 * 24 * 3600)),
3509 |row| {
3510 let contact_id: ContactId = row.get(0)?;
3511 Ok(contact_id)
3512 },
3513 )
3514 .await
3515}
3516
3517pub async fn create_group(context: &Context, name: &str) -> Result<ChatId> {
3519 create_group_ex(context, Sync, create_id(), name).await
3520}
3521
3522pub async fn create_group_unencrypted(context: &Context, name: &str) -> Result<ChatId> {
3524 create_group_ex(context, Sync, String::new(), name).await
3525}
3526
3527pub(crate) async fn create_group_ex(
3534 context: &Context,
3535 sync: sync::Sync,
3536 grpid: String,
3537 name: &str,
3538) -> Result<ChatId> {
3539 let mut chat_name = sanitize_single_line(name);
3540 if chat_name.is_empty() {
3541 error!(context, "Invalid chat name: {name}.");
3544 chat_name = "…".to_string();
3545 }
3546
3547 let timestamp = create_smeared_timestamp(context);
3548 let row_id = context
3549 .sql
3550 .insert(
3551 "INSERT INTO chats
3552 (type, name, name_normalized, grpid, param, created_timestamp)
3553 VALUES(?, ?, ?, ?, \'U=1\', ?)",
3554 (
3555 Chattype::Group,
3556 &chat_name,
3557 normalize_text(&chat_name),
3558 &grpid,
3559 timestamp,
3560 ),
3561 )
3562 .await?;
3563
3564 let chat_id = ChatId::new(u32::try_from(row_id)?);
3565 add_to_chat_contacts_table(context, timestamp, chat_id, &[ContactId::SELF]).await?;
3566
3567 context.emit_msgs_changed_without_ids();
3568 chatlist_events::emit_chatlist_changed(context);
3569 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3570
3571 if !grpid.is_empty() {
3572 chat_id.add_e2ee_notice(context, timestamp).await?;
3574 }
3575
3576 if !context.get_config_bool(Config::Bot).await?
3577 && !context.get_config_bool(Config::SkipStartMessages).await?
3578 {
3579 let text = if !grpid.is_empty() {
3580 stock_str::new_group_send_first_message(context).await
3582 } else {
3583 stock_str::chat_unencrypted_explanation(context).await
3585 };
3586 add_info_msg(context, chat_id, &text).await?;
3587 }
3588 if let (true, true) = (sync.into(), !grpid.is_empty()) {
3589 let id = SyncId::Grpid(grpid);
3590 let action = SyncAction::CreateGroupEncrypted(chat_name);
3591 self::sync(context, id, action).await.log_err(context).ok();
3592 }
3593 Ok(chat_id)
3594}
3595
3596pub async fn create_broadcast(context: &Context, chat_name: String) -> Result<ChatId> {
3612 let grpid = create_id();
3613 let secret = create_broadcast_secret();
3614 create_out_broadcast_ex(context, Sync, grpid, chat_name, secret).await
3615}
3616
3617const SQL_INSERT_BROADCAST_SECRET: &str =
3618 "INSERT INTO broadcast_secrets (chat_id, secret) VALUES (?, ?)
3619 ON CONFLICT(chat_id) DO UPDATE SET secret=excluded.secret";
3620
3621pub(crate) async fn create_out_broadcast_ex(
3622 context: &Context,
3623 sync: sync::Sync,
3624 grpid: String,
3625 chat_name: String,
3626 secret: String,
3627) -> Result<ChatId> {
3628 let chat_name = sanitize_single_line(&chat_name);
3629 if chat_name.is_empty() {
3630 bail!("Invalid broadcast channel name: {chat_name}.");
3631 }
3632
3633 let timestamp = create_smeared_timestamp(context);
3634 let trans_fn = |t: &mut rusqlite::Transaction| -> Result<ChatId> {
3635 let cnt: u32 = t.query_row(
3636 "SELECT COUNT(*) FROM chats WHERE grpid=?",
3637 (&grpid,),
3638 |row| row.get(0),
3639 )?;
3640 ensure!(cnt == 0, "{cnt} chats exist with grpid {grpid}");
3641
3642 t.execute(
3643 "INSERT INTO chats
3644 (type, name, name_normalized, grpid, created_timestamp)
3645 VALUES(?, ?, ?, ?, ?)",
3646 (
3647 Chattype::OutBroadcast,
3648 &chat_name,
3649 normalize_text(&chat_name),
3650 &grpid,
3651 timestamp,
3652 ),
3653 )?;
3654 let chat_id = ChatId::new(t.last_insert_rowid().try_into()?);
3655
3656 t.execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, &secret))?;
3657 Ok(chat_id)
3658 };
3659 let chat_id = context.sql.transaction(trans_fn).await?;
3660 chat_id.add_e2ee_notice(context, timestamp).await?;
3661
3662 context.emit_msgs_changed_without_ids();
3663 chatlist_events::emit_chatlist_changed(context);
3664 chatlist_events::emit_chatlist_item_changed(context, chat_id);
3665
3666 if sync.into() {
3667 let id = SyncId::Grpid(grpid);
3668 let action = SyncAction::CreateOutBroadcast { chat_name, secret };
3669 self::sync(context, id, action).await.log_err(context).ok();
3670 }
3671
3672 Ok(chat_id)
3673}
3674
3675pub(crate) async fn load_broadcast_secret(
3676 context: &Context,
3677 chat_id: ChatId,
3678) -> Result<Option<String>> {
3679 context
3680 .sql
3681 .query_get_value(
3682 "SELECT secret FROM broadcast_secrets WHERE chat_id=?",
3683 (chat_id,),
3684 )
3685 .await
3686}
3687
3688pub(crate) async fn save_broadcast_secret(
3689 context: &Context,
3690 chat_id: ChatId,
3691 secret: &str,
3692) -> Result<()> {
3693 info!(context, "Saving broadcast secret for chat {chat_id}");
3694 context
3695 .sql
3696 .execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, secret))
3697 .await?;
3698
3699 Ok(())
3700}
3701
3702pub(crate) async fn delete_broadcast_secret(context: &Context, chat_id: ChatId) -> Result<()> {
3703 info!(context, "Removing broadcast secret for chat {chat_id}");
3704 context
3705 .sql
3706 .execute("DELETE FROM broadcast_secrets WHERE chat_id=?", (chat_id,))
3707 .await?;
3708
3709 Ok(())
3710}
3711
3712pub(crate) async fn update_chat_contacts_table(
3714 context: &Context,
3715 timestamp: i64,
3716 id: ChatId,
3717 contacts: &HashSet<ContactId>,
3718) -> Result<()> {
3719 context
3720 .sql
3721 .transaction(move |transaction| {
3722 transaction.execute(
3726 "UPDATE chats_contacts
3727 SET remove_timestamp=MAX(add_timestamp+1, ?)
3728 WHERE chat_id=?",
3729 (timestamp, id),
3730 )?;
3731
3732 if !contacts.is_empty() {
3733 let mut statement = transaction.prepare(
3734 "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp)
3735 VALUES (?1, ?2, ?3)
3736 ON CONFLICT (chat_id, contact_id)
3737 DO UPDATE SET add_timestamp=remove_timestamp",
3738 )?;
3739
3740 for contact_id in contacts {
3741 statement.execute((id, contact_id, timestamp))?;
3745 }
3746 }
3747 Ok(())
3748 })
3749 .await?;
3750 Ok(())
3751}
3752
3753pub(crate) async fn add_to_chat_contacts_table(
3755 context: &Context,
3756 timestamp: i64,
3757 chat_id: ChatId,
3758 contact_ids: &[ContactId],
3759) -> Result<()> {
3760 context
3761 .sql
3762 .transaction(move |transaction| {
3763 let mut add_statement = transaction.prepare(
3764 "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp) VALUES(?1, ?2, ?3)
3765 ON CONFLICT (chat_id, contact_id)
3766 DO UPDATE SET add_timestamp=MAX(remove_timestamp, ?3)",
3767 )?;
3768
3769 for contact_id in contact_ids {
3770 add_statement.execute((chat_id, contact_id, timestamp))?;
3771 }
3772 Ok(())
3773 })
3774 .await?;
3775
3776 Ok(())
3777}
3778
3779pub(crate) async fn remove_from_chat_contacts_table(
3782 context: &Context,
3783 chat_id: ChatId,
3784 contact_id: ContactId,
3785) -> Result<()> {
3786 let now = time();
3787 context
3788 .sql
3789 .execute(
3790 "UPDATE chats_contacts
3791 SET remove_timestamp=MAX(add_timestamp+1, ?)
3792 WHERE chat_id=? AND contact_id=?",
3793 (now, chat_id, contact_id),
3794 )
3795 .await?;
3796 Ok(())
3797}
3798
3799pub(crate) async fn remove_from_chat_contacts_table_without_trace(
3807 context: &Context,
3808 chat_id: ChatId,
3809 contact_id: ContactId,
3810) -> Result<()> {
3811 context
3812 .sql
3813 .execute(
3814 "DELETE FROM chats_contacts
3815 WHERE chat_id=? AND contact_id=?",
3816 (chat_id, contact_id),
3817 )
3818 .await?;
3819
3820 Ok(())
3821}
3822
3823pub async fn add_contact_to_chat(
3826 context: &Context,
3827 chat_id: ChatId,
3828 contact_id: ContactId,
3829) -> Result<()> {
3830 add_contact_to_chat_ex(context, Sync, chat_id, contact_id, false).await?;
3831 Ok(())
3832}
3833
3834pub(crate) async fn add_contact_to_chat_ex(
3835 context: &Context,
3836 mut sync: sync::Sync,
3837 chat_id: ChatId,
3838 contact_id: ContactId,
3839 from_handshake: bool,
3840) -> Result<bool> {
3841 ensure!(!chat_id.is_special(), "can not add member to special chats");
3842 let contact = Contact::get_by_id(context, contact_id).await?;
3843 let mut msg = Message::new(Viewtype::default());
3844
3845 chat_id.reset_gossiped_timestamp(context).await?;
3846
3847 let mut chat = Chat::load_from_db(context, chat_id).await?;
3849 ensure!(
3850 chat.typ == Chattype::Group || (from_handshake && chat.typ == Chattype::OutBroadcast),
3851 "{chat_id} is not a group where one can add members",
3852 );
3853 ensure!(
3854 Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF,
3855 "invalid contact_id {contact_id} for adding to group"
3856 );
3857 ensure!(
3858 chat.typ != Chattype::OutBroadcast || contact_id != ContactId::SELF,
3859 "Cannot add SELF to broadcast channel."
3860 );
3861 match chat.is_encrypted(context).await? {
3862 true => ensure!(
3863 contact.is_key_contact(),
3864 "Only key-contacts can be added to encrypted chats"
3865 ),
3866 false => ensure!(
3867 !contact.is_key_contact(),
3868 "Only address-contacts can be added to unencrypted chats"
3869 ),
3870 }
3871
3872 if !chat.is_self_in_chat(context).await? {
3873 context.emit_event(EventType::ErrorSelfNotInGroup(
3874 "Cannot add contact to group; self not in group.".into(),
3875 ));
3876 warn!(
3877 context,
3878 "Can not add contact because the account is not part of the group/broadcast."
3879 );
3880 return Ok(false);
3881 }
3882
3883 let sync_qr_code_tokens;
3884 if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {
3885 chat.param
3886 .remove(Param::Unpromoted)
3887 .set_i64(Param::GroupNameTimestamp, smeared_time(context));
3888 chat.update_param(context).await?;
3889 sync_qr_code_tokens = true;
3890 } else {
3891 sync_qr_code_tokens = false;
3892 }
3893
3894 if context.is_self_addr(contact.get_addr()).await? {
3895 warn!(
3898 context,
3899 "Invalid attempt to add self e-mail address to group."
3900 );
3901 return Ok(false);
3902 }
3903
3904 if is_contact_in_chat(context, chat_id, contact_id).await? {
3905 if !from_handshake {
3906 return Ok(true);
3907 }
3908 } else {
3909 add_to_chat_contacts_table(context, time(), chat_id, &[contact_id]).await?;
3911 }
3912 if chat.is_promoted() {
3913 msg.viewtype = Viewtype::Text;
3914
3915 let contact_addr = contact.get_addr().to_lowercase();
3916 let added_by = if from_handshake && chat.typ == Chattype::OutBroadcast {
3917 ContactId::UNDEFINED
3922 } else {
3923 ContactId::SELF
3924 };
3925 msg.text = stock_str::msg_add_member_local(context, contact.id, added_by).await;
3926 msg.param.set_cmd(SystemMessage::MemberAddedToGroup);
3927 msg.param.set(Param::Arg, contact_addr);
3928 msg.param.set_int(Param::Arg2, from_handshake.into());
3929 let fingerprint = contact.fingerprint().map(|f| f.hex());
3930 msg.param.set_optional(Param::Arg4, fingerprint);
3931 msg.param
3932 .set_int(Param::ContactAddedRemoved, contact.id.to_u32() as i32);
3933 if chat.typ == Chattype::OutBroadcast {
3934 let secret = load_broadcast_secret(context, chat_id)
3935 .await?
3936 .context("Failed to find broadcast shared secret")?;
3937 msg.param.set(PARAM_BROADCAST_SECRET, secret);
3938 }
3939 send_msg(context, chat_id, &mut msg).await?;
3940
3941 sync = Nosync;
3942 if sync_qr_code_tokens
3948 && context
3949 .sync_qr_code_tokens(Some(chat.grpid.as_str()))
3950 .await
3951 .log_err(context)
3952 .is_ok()
3953 {
3954 context.scheduler.interrupt_smtp().await;
3955 }
3956 }
3957 context.emit_event(EventType::ChatModified(chat_id));
3958 if sync.into() {
3959 chat.sync_contacts(context).await.log_err(context).ok();
3960 }
3961 Ok(true)
3962}
3963
3964pub(crate) async fn shall_attach_selfavatar(context: &Context, chat_id: ChatId) -> Result<bool> {
3970 let timestamp_some_days_ago = time() - DC_RESEND_USER_AVATAR_DAYS * 24 * 60 * 60;
3971 let needs_attach = context
3972 .sql
3973 .query_map(
3974 "SELECT c.selfavatar_sent
3975 FROM chats_contacts cc
3976 LEFT JOIN contacts c ON c.id=cc.contact_id
3977 WHERE cc.chat_id=? AND cc.contact_id!=? AND cc.add_timestamp >= cc.remove_timestamp",
3978 (chat_id, ContactId::SELF),
3979 |row| {
3980 let selfavatar_sent: i64 = row.get(0)?;
3981 Ok(selfavatar_sent)
3982 },
3983 |rows| {
3984 let mut needs_attach = false;
3985 for row in rows {
3986 let selfavatar_sent = row?;
3987 if selfavatar_sent < timestamp_some_days_ago {
3988 needs_attach = true;
3989 }
3990 }
3991 Ok(needs_attach)
3992 },
3993 )
3994 .await?;
3995 Ok(needs_attach)
3996}
3997
3998#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
4000pub enum MuteDuration {
4001 NotMuted,
4003
4004 Forever,
4006
4007 Until(std::time::SystemTime),
4009}
4010
4011impl rusqlite::types::ToSql for MuteDuration {
4012 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
4013 let duration: i64 = match &self {
4014 MuteDuration::NotMuted => 0,
4015 MuteDuration::Forever => -1,
4016 MuteDuration::Until(when) => {
4017 let duration = when
4018 .duration_since(SystemTime::UNIX_EPOCH)
4019 .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
4020 i64::try_from(duration.as_secs())
4021 .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?
4022 }
4023 };
4024 let val = rusqlite::types::Value::Integer(duration);
4025 let out = rusqlite::types::ToSqlOutput::Owned(val);
4026 Ok(out)
4027 }
4028}
4029
4030impl rusqlite::types::FromSql for MuteDuration {
4031 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
4032 match i64::column_result(value)? {
4035 0 => Ok(MuteDuration::NotMuted),
4036 -1 => Ok(MuteDuration::Forever),
4037 n if n > 0 => match SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(n as u64)) {
4038 Some(t) => Ok(MuteDuration::Until(t)),
4039 None => Err(rusqlite::types::FromSqlError::OutOfRange(n)),
4040 },
4041 _ => Ok(MuteDuration::NotMuted),
4042 }
4043 }
4044}
4045
4046pub async fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuration) -> Result<()> {
4048 set_muted_ex(context, Sync, chat_id, duration).await
4049}
4050
4051pub(crate) async fn set_muted_ex(
4052 context: &Context,
4053 sync: sync::Sync,
4054 chat_id: ChatId,
4055 duration: MuteDuration,
4056) -> Result<()> {
4057 ensure!(!chat_id.is_special(), "Invalid chat ID");
4058 context
4059 .sql
4060 .execute(
4061 "UPDATE chats SET muted_until=? WHERE id=?;",
4062 (duration, chat_id),
4063 )
4064 .await
4065 .context(format!("Failed to set mute duration for {chat_id}"))?;
4066 context.emit_event(EventType::ChatModified(chat_id));
4067 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4068 if sync.into() {
4069 let chat = Chat::load_from_db(context, chat_id).await?;
4070 chat.sync(context, SyncAction::SetMuted(duration))
4071 .await
4072 .log_err(context)
4073 .ok();
4074 }
4075 Ok(())
4076}
4077
4078pub async fn remove_contact_from_chat(
4080 context: &Context,
4081 chat_id: ChatId,
4082 contact_id: ContactId,
4083) -> Result<()> {
4084 ensure!(
4085 !chat_id.is_special(),
4086 "bad chat_id, can not be special chat: {chat_id}"
4087 );
4088 ensure!(
4089 !contact_id.is_special() || contact_id == ContactId::SELF,
4090 "Cannot remove special contact"
4091 );
4092
4093 let chat = Chat::load_from_db(context, chat_id).await?;
4094 if chat.typ == Chattype::InBroadcast {
4095 ensure!(
4096 contact_id == ContactId::SELF,
4097 "Cannot remove other member from incoming broadcast channel"
4098 );
4099 delete_broadcast_secret(context, chat_id).await?;
4100 }
4101
4102 if matches!(
4103 chat.typ,
4104 Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast
4105 ) {
4106 if !chat.is_self_in_chat(context).await? {
4107 let err_msg = format!(
4108 "Cannot remove contact {contact_id} from chat {chat_id}: self not in group."
4109 );
4110 context.emit_event(EventType::ErrorSelfNotInGroup(err_msg.clone()));
4111 bail!("{err_msg}");
4112 } else {
4113 let mut sync = Nosync;
4114
4115 if chat.is_promoted() && chat.typ != Chattype::OutBroadcast {
4116 remove_from_chat_contacts_table(context, chat_id, contact_id).await?;
4117 } else {
4118 remove_from_chat_contacts_table_without_trace(context, chat_id, contact_id).await?;
4119 }
4120
4121 if let Some(contact) = Contact::get_by_id_optional(context, contact_id).await? {
4125 if chat.is_promoted() {
4126 let addr = contact.get_addr();
4127 let fingerprint = contact.fingerprint().map(|f| f.hex());
4128
4129 let res = send_member_removal_msg(
4130 context,
4131 &chat,
4132 contact_id,
4133 addr,
4134 fingerprint.as_deref(),
4135 )
4136 .await;
4137
4138 if contact_id == ContactId::SELF {
4139 res?;
4140 } else if let Err(e) = res {
4141 warn!(
4142 context,
4143 "remove_contact_from_chat({chat_id}, {contact_id}): send_msg() failed: {e:#}."
4144 );
4145 }
4146 } else {
4147 sync = Sync;
4148 }
4149 }
4150 context.emit_event(EventType::ChatModified(chat_id));
4151 if sync.into() {
4152 chat.sync_contacts(context).await.log_err(context).ok();
4153 }
4154 }
4155 } else {
4156 bail!("Cannot remove members from non-group chats.");
4157 }
4158
4159 Ok(())
4160}
4161
4162async fn send_member_removal_msg(
4163 context: &Context,
4164 chat: &Chat,
4165 contact_id: ContactId,
4166 addr: &str,
4167 fingerprint: Option<&str>,
4168) -> Result<MsgId> {
4169 let mut msg = Message::new(Viewtype::Text);
4170
4171 if contact_id == ContactId::SELF {
4172 if chat.typ == Chattype::InBroadcast {
4173 msg.text = stock_str::msg_you_left_broadcast(context).await;
4174 } else {
4175 msg.text = stock_str::msg_group_left_local(context, ContactId::SELF).await;
4176 }
4177 } else {
4178 msg.text = stock_str::msg_del_member_local(context, contact_id, ContactId::SELF).await;
4179 }
4180
4181 msg.param.set_cmd(SystemMessage::MemberRemovedFromGroup);
4182 msg.param.set(Param::Arg, addr.to_lowercase());
4183 msg.param.set_optional(Param::Arg4, fingerprint);
4184 msg.param
4185 .set(Param::ContactAddedRemoved, contact_id.to_u32());
4186
4187 send_msg(context, chat.id, &mut msg).await
4188}
4189
4190pub async fn set_chat_name(context: &Context, chat_id: ChatId, new_name: &str) -> Result<()> {
4192 rename_ex(context, Sync, chat_id, new_name).await
4193}
4194
4195async fn rename_ex(
4196 context: &Context,
4197 mut sync: sync::Sync,
4198 chat_id: ChatId,
4199 new_name: &str,
4200) -> Result<()> {
4201 let new_name = sanitize_single_line(new_name);
4202 let mut success = false;
4204
4205 ensure!(!new_name.is_empty(), "Invalid name");
4206 ensure!(!chat_id.is_special(), "Invalid chat ID");
4207
4208 let chat = Chat::load_from_db(context, chat_id).await?;
4209 let mut msg = Message::new(Viewtype::default());
4210
4211 if chat.typ == Chattype::Group
4212 || chat.typ == Chattype::Mailinglist
4213 || chat.typ == Chattype::OutBroadcast
4214 {
4215 if chat.name == new_name {
4216 success = true;
4217 } else if !chat.is_self_in_chat(context).await? {
4218 context.emit_event(EventType::ErrorSelfNotInGroup(
4219 "Cannot set chat name; self not in group".into(),
4220 ));
4221 } else {
4222 context
4223 .sql
4224 .execute(
4225 "UPDATE chats SET name=?, name_normalized=? WHERE id=?",
4226 (&new_name, normalize_text(&new_name), chat_id),
4227 )
4228 .await?;
4229 if chat.is_promoted()
4230 && !chat.is_mailing_list()
4231 && sanitize_single_line(&chat.name) != new_name
4232 {
4233 msg.viewtype = Viewtype::Text;
4234 msg.text =
4235 stock_str::msg_grp_name(context, &chat.name, &new_name, ContactId::SELF).await;
4236 msg.param.set_cmd(SystemMessage::GroupNameChanged);
4237 if !chat.name.is_empty() {
4238 msg.param.set(Param::Arg, &chat.name);
4239 }
4240 msg.id = send_msg(context, chat_id, &mut msg).await?;
4241 context.emit_msgs_changed(chat_id, msg.id);
4242 sync = Nosync;
4243 }
4244 context.emit_event(EventType::ChatModified(chat_id));
4245 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4246 success = true;
4247 }
4248 }
4249
4250 if !success {
4251 bail!("Failed to set name");
4252 }
4253 if sync.into() && chat.name != new_name {
4254 let sync_name = new_name.to_string();
4255 chat.sync(context, SyncAction::Rename(sync_name))
4256 .await
4257 .log_err(context)
4258 .ok();
4259 }
4260 Ok(())
4261}
4262
4263pub async fn set_chat_profile_image(
4269 context: &Context,
4270 chat_id: ChatId,
4271 new_image: &str, ) -> Result<()> {
4273 ensure!(!chat_id.is_special(), "Invalid chat ID");
4274 let mut chat = Chat::load_from_db(context, chat_id).await?;
4275 ensure!(
4276 chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4277 "Can only set profile image for groups / broadcasts"
4278 );
4279 ensure!(
4280 !chat.grpid.is_empty(),
4281 "Cannot set profile image for ad hoc groups"
4282 );
4283 if !chat.is_self_in_chat(context).await? {
4285 context.emit_event(EventType::ErrorSelfNotInGroup(
4286 "Cannot set chat profile image; self not in group.".into(),
4287 ));
4288 bail!("Failed to set profile image");
4289 }
4290 let mut msg = Message::new(Viewtype::Text);
4291 msg.param
4292 .set_int(Param::Cmd, SystemMessage::GroupImageChanged as i32);
4293 if new_image.is_empty() {
4294 chat.param.remove(Param::ProfileImage);
4295 msg.param.remove(Param::Arg);
4296 msg.text = stock_str::msg_grp_img_deleted(context, ContactId::SELF).await;
4297 } else {
4298 let mut image_blob = BlobObject::create_and_deduplicate(
4299 context,
4300 Path::new(new_image),
4301 Path::new(new_image),
4302 )?;
4303 image_blob.recode_to_avatar_size(context).await?;
4304 chat.param.set(Param::ProfileImage, image_blob.as_name());
4305 msg.param.set(Param::Arg, image_blob.as_name());
4306 msg.text = stock_str::msg_grp_img_changed(context, ContactId::SELF).await;
4307 }
4308 chat.update_param(context).await?;
4309 if chat.is_promoted() {
4310 msg.id = send_msg(context, chat_id, &mut msg).await?;
4311 context.emit_msgs_changed(chat_id, msg.id);
4312 }
4313 context.emit_event(EventType::ChatModified(chat_id));
4314 chatlist_events::emit_chatlist_item_changed(context, chat_id);
4315 Ok(())
4316}
4317
4318pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) -> Result<()> {
4320 forward_msgs_2ctx(context, msg_ids, context, chat_id).await
4321}
4322
4323pub async fn forward_msgs_2ctx(
4325 ctx_src: &Context,
4326 msg_ids: &[MsgId],
4327 ctx_dst: &Context,
4328 chat_id: ChatId,
4329) -> Result<()> {
4330 ensure!(!msg_ids.is_empty(), "empty msgs_ids: nothing to forward");
4331 ensure!(!chat_id.is_special(), "can not forward to special chat");
4332
4333 let mut created_msgs: Vec<MsgId> = Vec::new();
4334 let mut curr_timestamp: i64;
4335
4336 chat_id
4337 .unarchive_if_not_muted(ctx_dst, MessageState::Undefined)
4338 .await?;
4339 let mut chat = Chat::load_from_db(ctx_dst, chat_id).await?;
4340 if let Some(reason) = chat.why_cant_send(ctx_dst).await? {
4341 bail!("cannot send to {chat_id}: {reason}");
4342 }
4343 curr_timestamp = create_smeared_timestamps(ctx_dst, msg_ids.len());
4344 let mut msgs = Vec::with_capacity(msg_ids.len());
4345 for id in msg_ids {
4346 let ts: i64 = ctx_src
4347 .sql
4348 .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4349 .await?
4350 .with_context(|| format!("No message {id}"))?;
4351 msgs.push((ts, *id));
4352 }
4353 msgs.sort_unstable();
4354 for (_, id) in msgs {
4355 let src_msg_id: MsgId = id;
4356 let mut msg = Message::load_from_db(ctx_src, src_msg_id).await?;
4357 if msg.state == MessageState::OutDraft {
4358 bail!("cannot forward drafts.");
4359 }
4360
4361 let mut param = msg.param;
4362 msg.param = Params::new();
4363
4364 if msg.get_viewtype() != Viewtype::Sticker {
4365 let forwarded_msg_id = match ctx_src.blobdir == ctx_dst.blobdir {
4366 true => src_msg_id,
4367 false => MsgId::new_unset(),
4368 };
4369 msg.param
4370 .set_int(Param::Forwarded, forwarded_msg_id.to_u32() as i32);
4371 }
4372
4373 if msg.get_viewtype() == Viewtype::Call {
4374 msg.viewtype = Viewtype::Text;
4375 }
4376 msg.text += &msg.additional_text;
4377
4378 let param = &mut param;
4379
4380 if ctx_src.blobdir == ctx_dst.blobdir {
4383 msg.param.steal(param, Param::File);
4384 } else if let Some(src_path) = param.get_file_path(ctx_src)? {
4385 let new_blob = BlobObject::create_and_deduplicate(ctx_dst, &src_path, &src_path)
4386 .context("Failed to copy blob file to destination account")?;
4387 msg.param.set(Param::File, new_blob.as_name());
4388 }
4389 msg.param.steal(param, Param::Filename);
4390 msg.param.steal(param, Param::Width);
4391 msg.param.steal(param, Param::Height);
4392 msg.param.steal(param, Param::Duration);
4393 msg.param.steal(param, Param::MimeType);
4394 msg.param.steal(param, Param::ProtectQuote);
4395 msg.param.steal(param, Param::Quote);
4396 msg.param.steal(param, Param::Summary1);
4397 if msg.has_html() {
4398 msg.set_html(src_msg_id.get_html(ctx_src).await?);
4399 }
4400 msg.in_reply_to = None;
4401
4402 msg.subject = "".to_string();
4404
4405 msg.state = MessageState::OutPending;
4406 msg.rfc724_mid = create_outgoing_rfc724_mid();
4407 msg.timestamp_sort = curr_timestamp;
4408 chat.prepare_msg_raw(ctx_dst, &mut msg, None).await?;
4409
4410 curr_timestamp += 1;
4411 if !create_send_msg_jobs(ctx_dst, &mut msg).await?.is_empty() {
4412 ctx_dst.scheduler.interrupt_smtp().await;
4413 }
4414 created_msgs.push(msg.id);
4415 }
4416 for msg_id in created_msgs {
4417 ctx_dst.emit_msgs_changed(chat_id, msg_id);
4418 }
4419 Ok(())
4420}
4421
4422pub async fn save_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4425 let mut msgs = Vec::with_capacity(msg_ids.len());
4426 for id in msg_ids {
4427 let ts: i64 = context
4428 .sql
4429 .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4430 .await?
4431 .with_context(|| format!("No message {id}"))?;
4432 msgs.push((ts, *id));
4433 }
4434 msgs.sort_unstable();
4435 for (_, src_msg_id) in msgs {
4436 let dest_rfc724_mid = create_outgoing_rfc724_mid();
4437 let src_rfc724_mid = save_copy_in_self_talk(context, src_msg_id, &dest_rfc724_mid).await?;
4438 context
4439 .add_sync_item(SyncData::SaveMessage {
4440 src: src_rfc724_mid,
4441 dest: dest_rfc724_mid,
4442 })
4443 .await?;
4444 }
4445 context.scheduler.interrupt_smtp().await;
4446 Ok(())
4447}
4448
4449pub(crate) async fn save_copy_in_self_talk(
4455 context: &Context,
4456 src_msg_id: MsgId,
4457 dest_rfc724_mid: &String,
4458) -> Result<String> {
4459 let dest_chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?;
4460 let mut msg = Message::load_from_db(context, src_msg_id).await?;
4461 msg.param.remove(Param::Cmd);
4462 msg.param.remove(Param::WebxdcDocument);
4463 msg.param.remove(Param::WebxdcDocumentTimestamp);
4464 msg.param.remove(Param::WebxdcSummary);
4465 msg.param.remove(Param::WebxdcSummaryTimestamp);
4466 msg.param.remove(Param::PostMessageFileBytes);
4467 msg.param.remove(Param::PostMessageViewtype);
4468
4469 msg.text += &msg.additional_text;
4470
4471 if !msg.original_msg_id.is_unset() {
4472 bail!("message already saved.");
4473 }
4474
4475 let copy_fields = "from_id, to_id, timestamp_rcvd, type,
4476 mime_modified, mime_headers, mime_compressed, mime_in_reply_to, subject, msgrmsg";
4477 let row_id = context
4478 .sql
4479 .insert(
4480 &format!(
4481 "INSERT INTO msgs ({copy_fields},
4482 timestamp_sent,
4483 txt, chat_id, rfc724_mid, state, timestamp, param, starred)
4484 SELECT {copy_fields},
4485 -- Outgoing messages on originating device
4486 -- have timestamp_sent == 0.
4487 -- We copy sort timestamp instead
4488 -- so UIs display the same timestamp
4489 -- for saved and original message.
4490 IIF(timestamp_sent == 0, timestamp, timestamp_sent),
4491 ?, ?, ?, ?, ?, ?, ?
4492 FROM msgs WHERE id=?;"
4493 ),
4494 (
4495 msg.text,
4496 dest_chat_id,
4497 dest_rfc724_mid,
4498 if msg.from_id == ContactId::SELF {
4499 MessageState::OutDelivered
4500 } else {
4501 MessageState::InSeen
4502 },
4503 create_smeared_timestamp(context),
4504 msg.param.to_string(),
4505 src_msg_id,
4506 src_msg_id,
4507 ),
4508 )
4509 .await?;
4510 let dest_msg_id = MsgId::new(row_id.try_into()?);
4511
4512 context.emit_msgs_changed(msg.chat_id, src_msg_id);
4513 context.emit_msgs_changed(dest_chat_id, dest_msg_id);
4514 chatlist_events::emit_chatlist_changed(context);
4515 chatlist_events::emit_chatlist_item_changed(context, dest_chat_id);
4516
4517 Ok(msg.rfc724_mid)
4518}
4519
4520pub async fn resend_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4524 let mut msgs: Vec<Message> = Vec::new();
4525 for msg_id in msg_ids {
4526 let msg = Message::load_from_db(context, *msg_id).await?;
4527 ensure!(
4528 msg.from_id == ContactId::SELF,
4529 "can resend only own messages"
4530 );
4531 ensure!(!msg.is_info(), "cannot resend info messages");
4532 msgs.push(msg)
4533 }
4534
4535 for mut msg in msgs {
4536 match msg.get_state() {
4537 MessageState::OutPending
4539 | MessageState::OutFailed
4540 | MessageState::OutDelivered
4541 | MessageState::OutMdnRcvd => {
4542 message::update_msg_state(context, msg.id, MessageState::OutPending).await?
4543 }
4544 msg_state => bail!("Unexpected message state {msg_state}"),
4545 }
4546 msg.timestamp_sort = create_smeared_timestamp(context);
4547 if create_send_msg_jobs(context, &mut msg).await?.is_empty() {
4548 continue;
4549 }
4550
4551 context.emit_event(EventType::MsgsChanged {
4555 chat_id: msg.chat_id,
4556 msg_id: msg.id,
4557 });
4558 chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
4560
4561 if msg.viewtype == Viewtype::Webxdc {
4562 let conn_fn = |conn: &mut rusqlite::Connection| {
4563 let range = conn.query_row(
4564 "SELECT IFNULL(min(id), 1), IFNULL(max(id), 0) \
4565 FROM msgs_status_updates WHERE msg_id=?",
4566 (msg.id,),
4567 |row| {
4568 let min_id: StatusUpdateSerial = row.get(0)?;
4569 let max_id: StatusUpdateSerial = row.get(1)?;
4570 Ok((min_id, max_id))
4571 },
4572 )?;
4573 if range.0 > range.1 {
4574 return Ok(());
4575 };
4576 conn.execute(
4580 "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) \
4581 VALUES(?, ?, ?, '') \
4582 ON CONFLICT(msg_id) \
4583 DO UPDATE SET first_serial=min(first_serial - 1, excluded.first_serial)",
4584 (msg.id, range.0, range.1),
4585 )?;
4586 Ok(())
4587 };
4588 context.sql.call_write(conn_fn).await?;
4589 }
4590 context.scheduler.interrupt_smtp().await;
4591 }
4592 Ok(())
4593}
4594
4595pub(crate) async fn get_chat_cnt(context: &Context) -> Result<usize> {
4596 if context.sql.is_open().await {
4597 let count = context
4599 .sql
4600 .count("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;", ())
4601 .await?;
4602 Ok(count)
4603 } else {
4604 Ok(0)
4605 }
4606}
4607
4608pub(crate) async fn get_chat_id_by_grpid(
4610 context: &Context,
4611 grpid: &str,
4612) -> Result<Option<(ChatId, Blocked)>> {
4613 context
4614 .sql
4615 .query_row_optional(
4616 "SELECT id, blocked FROM chats WHERE grpid=?;",
4617 (grpid,),
4618 |row| {
4619 let chat_id = row.get::<_, ChatId>(0)?;
4620
4621 let b = row.get::<_, Option<Blocked>>(1)?.unwrap_or_default();
4622 Ok((chat_id, b))
4623 },
4624 )
4625 .await
4626}
4627
4628pub async fn add_device_msg_with_importance(
4633 context: &Context,
4634 label: Option<&str>,
4635 msg: Option<&mut Message>,
4636 important: bool,
4637) -> Result<MsgId> {
4638 ensure!(
4639 label.is_some() || msg.is_some(),
4640 "device-messages need label, msg or both"
4641 );
4642 let mut chat_id = ChatId::new(0);
4643 let mut msg_id = MsgId::new_unset();
4644
4645 if let Some(label) = label
4646 && was_device_msg_ever_added(context, label).await?
4647 {
4648 info!(context, "Device-message {label} already added.");
4649 return Ok(msg_id);
4650 }
4651
4652 if let Some(msg) = msg {
4653 chat_id = ChatId::get_for_contact(context, ContactId::DEVICE).await?;
4654
4655 let rfc724_mid = create_outgoing_rfc724_mid();
4656 let timestamp_sent = create_smeared_timestamp(context);
4657
4658 msg.timestamp_sort = timestamp_sent;
4661 if let Some(last_msg_time) = chat_id.get_timestamp(context).await?
4662 && msg.timestamp_sort <= last_msg_time
4663 {
4664 msg.timestamp_sort = last_msg_time + 1;
4665 }
4666 prepare_msg_blob(context, msg).await?;
4667 let state = MessageState::InFresh;
4668 let row_id = context
4669 .sql
4670 .insert(
4671 "INSERT INTO msgs (
4672 chat_id,
4673 from_id,
4674 to_id,
4675 timestamp,
4676 timestamp_sent,
4677 timestamp_rcvd,
4678 type,state,
4679 txt,
4680 txt_normalized,
4681 param,
4682 rfc724_mid)
4683 VALUES (?,?,?,?,?,?,?,?,?,?,?,?);",
4684 (
4685 chat_id,
4686 ContactId::DEVICE,
4687 ContactId::SELF,
4688 msg.timestamp_sort,
4689 timestamp_sent,
4690 timestamp_sent, msg.viewtype,
4692 state,
4693 &msg.text,
4694 normalize_text(&msg.text),
4695 msg.param.to_string(),
4696 rfc724_mid,
4697 ),
4698 )
4699 .await?;
4700 context.new_msgs_notify.notify_one();
4701
4702 msg_id = MsgId::new(u32::try_from(row_id)?);
4703 if !msg.hidden {
4704 chat_id.unarchive_if_not_muted(context, state).await?;
4705 }
4706 }
4707
4708 if let Some(label) = label {
4709 context
4710 .sql
4711 .execute("INSERT INTO devmsglabels (label) VALUES (?);", (label,))
4712 .await?;
4713 }
4714
4715 if !msg_id.is_unset() {
4716 chat_id.emit_msg_event(context, msg_id, important);
4717 }
4718
4719 Ok(msg_id)
4720}
4721
4722pub async fn add_device_msg(
4724 context: &Context,
4725 label: Option<&str>,
4726 msg: Option<&mut Message>,
4727) -> Result<MsgId> {
4728 add_device_msg_with_importance(context, label, msg, false).await
4729}
4730
4731pub async fn was_device_msg_ever_added(context: &Context, label: &str) -> Result<bool> {
4733 ensure!(!label.is_empty(), "empty label");
4734 let exists = context
4735 .sql
4736 .exists(
4737 "SELECT COUNT(label) FROM devmsglabels WHERE label=?",
4738 (label,),
4739 )
4740 .await?;
4741
4742 Ok(exists)
4743}
4744
4745pub(crate) async fn delete_and_reset_all_device_msgs(context: &Context) -> Result<()> {
4753 context
4754 .sql
4755 .execute("DELETE FROM msgs WHERE from_id=?;", (ContactId::DEVICE,))
4756 .await?;
4757 context.sql.execute("DELETE FROM devmsglabels;", ()).await?;
4758
4759 context
4761 .sql
4762 .execute(
4763 r#"INSERT INTO devmsglabels (label) VALUES ("core-welcome-image"), ("core-welcome")"#,
4764 (),
4765 )
4766 .await?;
4767 context
4768 .set_config_internal(Config::QuotaExceeding, None)
4769 .await?;
4770 Ok(())
4771}
4772
4773#[expect(clippy::too_many_arguments)]
4778pub(crate) async fn add_info_msg_with_cmd(
4779 context: &Context,
4780 chat_id: ChatId,
4781 text: &str,
4782 cmd: SystemMessage,
4783 timestamp_sort: Option<i64>,
4786 timestamp_sent_rcvd: i64,
4788 parent: Option<&Message>,
4789 from_id: Option<ContactId>,
4790 added_removed_id: Option<ContactId>,
4791) -> Result<MsgId> {
4792 let rfc724_mid = create_outgoing_rfc724_mid();
4793 let ephemeral_timer = chat_id.get_ephemeral_timer(context).await?;
4794
4795 let mut param = Params::new();
4796 if cmd != SystemMessage::Unknown {
4797 param.set_cmd(cmd);
4798 }
4799 if let Some(contact_id) = added_removed_id {
4800 param.set(Param::ContactAddedRemoved, contact_id.to_u32().to_string());
4801 }
4802
4803 let timestamp_sort = if let Some(ts) = timestamp_sort {
4804 ts
4805 } else {
4806 let sort_to_bottom = true;
4807 let (received, incoming) = (false, false);
4808 chat_id
4809 .calc_sort_timestamp(
4810 context,
4811 smeared_time(context),
4812 sort_to_bottom,
4813 received,
4814 incoming,
4815 )
4816 .await?
4817 };
4818
4819 let row_id =
4820 context.sql.insert(
4821 "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)
4822 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);",
4823 (
4824 chat_id,
4825 from_id.unwrap_or(ContactId::INFO),
4826 ContactId::INFO,
4827 timestamp_sort,
4828 timestamp_sent_rcvd,
4829 timestamp_sent_rcvd,
4830 Viewtype::Text,
4831 MessageState::InNoticed,
4832 text,
4833 normalize_text(text),
4834 rfc724_mid,
4835 ephemeral_timer,
4836 param.to_string(),
4837 parent.map(|msg|msg.rfc724_mid.clone()).unwrap_or_default()
4838 )
4839 ).await?;
4840 context.new_msgs_notify.notify_one();
4841
4842 let msg_id = MsgId::new(row_id.try_into()?);
4843 context.emit_msgs_changed(chat_id, msg_id);
4844
4845 Ok(msg_id)
4846}
4847
4848pub(crate) async fn add_info_msg(context: &Context, chat_id: ChatId, text: &str) -> Result<MsgId> {
4850 add_info_msg_with_cmd(
4851 context,
4852 chat_id,
4853 text,
4854 SystemMessage::Unknown,
4855 None,
4856 time(),
4857 None,
4858 None,
4859 None,
4860 )
4861 .await
4862}
4863
4864pub(crate) async fn update_msg_text_and_timestamp(
4865 context: &Context,
4866 chat_id: ChatId,
4867 msg_id: MsgId,
4868 text: &str,
4869 timestamp: i64,
4870) -> Result<()> {
4871 context
4872 .sql
4873 .execute(
4874 "UPDATE msgs SET txt=?, txt_normalized=?, timestamp=? WHERE id=?;",
4875 (text, normalize_text(text), timestamp, msg_id),
4876 )
4877 .await?;
4878 context.emit_msgs_changed(chat_id, msg_id);
4879 Ok(())
4880}
4881
4882async fn set_contacts_by_addrs(context: &Context, id: ChatId, addrs: &[String]) -> Result<()> {
4884 let chat = Chat::load_from_db(context, id).await?;
4885 ensure!(
4886 !chat.is_encrypted(context).await?,
4887 "Cannot add address-contacts to encrypted chat {id}"
4888 );
4889 ensure!(
4890 chat.typ == Chattype::OutBroadcast,
4891 "{id} is not a broadcast list",
4892 );
4893 let mut contacts = HashSet::new();
4894 for addr in addrs {
4895 let contact_addr = ContactAddress::new(addr)?;
4896 let contact = Contact::add_or_lookup(context, "", &contact_addr, Origin::Hidden)
4897 .await?
4898 .0;
4899 contacts.insert(contact);
4900 }
4901 let contacts_old = HashSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
4902 if contacts == contacts_old {
4903 return Ok(());
4904 }
4905 context
4906 .sql
4907 .transaction(move |transaction| {
4908 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
4909
4910 let mut statement = transaction
4913 .prepare("INSERT INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)")?;
4914 for contact_id in &contacts {
4915 statement.execute((id, contact_id))?;
4916 }
4917 Ok(())
4918 })
4919 .await?;
4920 context.emit_event(EventType::ChatModified(id));
4921 Ok(())
4922}
4923
4924async fn set_contacts_by_fingerprints(
4928 context: &Context,
4929 id: ChatId,
4930 fingerprint_addrs: &[(String, String)],
4931) -> Result<()> {
4932 let chat = Chat::load_from_db(context, id).await?;
4933 ensure!(
4934 chat.is_encrypted(context).await?,
4935 "Cannot add key-contacts to unencrypted chat {id}"
4936 );
4937 ensure!(
4938 matches!(chat.typ, Chattype::Group | Chattype::OutBroadcast),
4939 "{id} is not a group or broadcast",
4940 );
4941 let mut contacts = HashSet::new();
4942 for (fingerprint, addr) in fingerprint_addrs {
4943 let contact = Contact::add_or_lookup_ex(context, "", addr, fingerprint, Origin::Hidden)
4944 .await?
4945 .0;
4946 contacts.insert(contact);
4947 }
4948 let contacts_old = HashSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
4949 if contacts == contacts_old {
4950 return Ok(());
4951 }
4952 context
4953 .sql
4954 .transaction(move |transaction| {
4955 if chat.typ != Chattype::OutBroadcast {
4961 transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
4962 }
4963
4964 let mut statement = transaction.prepare(
4967 "INSERT OR IGNORE INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)",
4968 )?;
4969 for contact_id in &contacts {
4970 statement.execute((id, contact_id))?;
4971 }
4972 Ok(())
4973 })
4974 .await?;
4975 context.emit_event(EventType::ChatModified(id));
4976 Ok(())
4977}
4978
4979#[derive(Debug, Serialize, Deserialize, PartialEq)]
4981pub(crate) enum SyncId {
4982 ContactAddr(String),
4984
4985 ContactFingerprint(String),
4987
4988 Grpid(String),
4989 Msgids(Vec<String>),
4991
4992 Device,
4994}
4995
4996#[derive(Debug, Serialize, Deserialize, PartialEq)]
4998pub(crate) enum SyncAction {
4999 Block,
5000 Unblock,
5001 Accept,
5002 SetVisibility(ChatVisibility),
5003 SetMuted(MuteDuration),
5004 CreateOutBroadcast {
5006 chat_name: String,
5007 secret: String,
5008 },
5009 CreateGroupEncrypted(String),
5011 Rename(String),
5012 SetContacts(Vec<String>),
5014 SetPgpContacts(Vec<(String, String)>),
5018 Delete,
5019}
5020
5021impl Context {
5022 pub(crate) async fn sync_alter_chat(&self, id: &SyncId, action: &SyncAction) -> Result<()> {
5024 let chat_id = match id {
5025 SyncId::ContactAddr(addr) => {
5026 if let SyncAction::Rename(to) = action {
5027 Contact::create_ex(self, Nosync, to, addr).await?;
5028 return Ok(());
5029 }
5030 let addr = ContactAddress::new(addr).context("Invalid address")?;
5031 let (contact_id, _) =
5032 Contact::add_or_lookup(self, "", &addr, Origin::Hidden).await?;
5033 match action {
5034 SyncAction::Block => {
5035 return contact::set_blocked(self, Nosync, contact_id, true).await;
5036 }
5037 SyncAction::Unblock => {
5038 return contact::set_blocked(self, Nosync, contact_id, false).await;
5039 }
5040 _ => (),
5041 }
5042 ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5045 .await?
5046 .id
5047 }
5048 SyncId::ContactFingerprint(fingerprint) => {
5049 let name = "";
5050 let addr = "";
5051 let (contact_id, _) =
5052 Contact::add_or_lookup_ex(self, name, addr, fingerprint, Origin::Hidden)
5053 .await?;
5054 match action {
5055 SyncAction::Rename(to) => {
5056 contact_id.set_name_ex(self, Nosync, to).await?;
5057 self.emit_event(EventType::ContactsChanged(Some(contact_id)));
5058 return Ok(());
5059 }
5060 SyncAction::Block => {
5061 return contact::set_blocked(self, Nosync, contact_id, true).await;
5062 }
5063 SyncAction::Unblock => {
5064 return contact::set_blocked(self, Nosync, contact_id, false).await;
5065 }
5066 _ => (),
5067 }
5068 ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5069 .await?
5070 .id
5071 }
5072 SyncId::Grpid(grpid) => {
5073 match action {
5074 SyncAction::CreateOutBroadcast { chat_name, secret } => {
5075 create_out_broadcast_ex(
5076 self,
5077 Nosync,
5078 grpid.to_string(),
5079 chat_name.clone(),
5080 secret.to_string(),
5081 )
5082 .await?;
5083 return Ok(());
5084 }
5085 SyncAction::CreateGroupEncrypted(name) => {
5086 create_group_ex(self, Nosync, grpid.clone(), name).await?;
5087 return Ok(());
5088 }
5089 _ => {}
5090 }
5091 get_chat_id_by_grpid(self, grpid)
5092 .await?
5093 .with_context(|| format!("No chat for grpid '{grpid}'"))?
5094 .0
5095 }
5096 SyncId::Msgids(msgids) => {
5097 let msg = message::get_by_rfc724_mids(self, msgids)
5098 .await?
5099 .with_context(|| format!("No message found for Message-IDs {msgids:?}"))?;
5100 ChatId::lookup_by_message(&msg)
5101 .with_context(|| format!("No chat found for Message-IDs {msgids:?}"))?
5102 }
5103 SyncId::Device => ChatId::get_for_contact(self, ContactId::DEVICE).await?,
5104 };
5105 match action {
5106 SyncAction::Block => chat_id.block_ex(self, Nosync).await,
5107 SyncAction::Unblock => chat_id.unblock_ex(self, Nosync).await,
5108 SyncAction::Accept => chat_id.accept_ex(self, Nosync).await,
5109 SyncAction::SetVisibility(v) => chat_id.set_visibility_ex(self, Nosync, *v).await,
5110 SyncAction::SetMuted(duration) => set_muted_ex(self, Nosync, chat_id, *duration).await,
5111 SyncAction::CreateOutBroadcast { .. } | SyncAction::CreateGroupEncrypted(..) => {
5112 Err(anyhow!("sync_alter_chat({id:?}, {action:?}): Bad request."))
5114 }
5115 SyncAction::Rename(to) => rename_ex(self, Nosync, chat_id, to).await,
5116 SyncAction::SetContacts(addrs) => set_contacts_by_addrs(self, chat_id, addrs).await,
5117 SyncAction::SetPgpContacts(fingerprint_addrs) => {
5118 set_contacts_by_fingerprints(self, chat_id, fingerprint_addrs).await
5119 }
5120 SyncAction::Delete => chat_id.delete_ex(self, Nosync).await,
5121 }
5122 }
5123
5124 pub(crate) fn on_archived_chats_maybe_noticed(&self) {
5129 self.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
5130 }
5131}
5132
5133#[cfg(test)]
5134mod chat_tests;