deltachat/
chat.rs

1//! # Chat module.
2
3use std::cmp;
4use std::collections::{BTreeSet, HashMap};
5use std::fmt;
6use std::io::Cursor;
7use std::marker::Sync;
8use std::path::{Path, PathBuf};
9use std::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::pgp::addresses_from_public_key;
46use crate::receive_imf::ReceivedMsg;
47use crate::smtp::{self, send_msg_to_smtp};
48use crate::stock_str;
49use crate::sync::{self, Sync::*, SyncData};
50use crate::tools::{
51    IsNoneOrEmpty, SystemTime, buf_compress, create_broadcast_secret, create_id,
52    create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path,
53    gm2local_offset, normalize_text, smeared_time, time, truncate_msg_text,
54};
55use crate::webxdc::StatusUpdateSerial;
56
57pub(crate) const PARAM_BROADCAST_SECRET: Param = Param::Arg3;
58
59/// An chat item, such as a message or a marker.
60#[derive(Debug, Copy, Clone, PartialEq, Eq)]
61pub enum ChatItem {
62    /// Chat message stored in the database.
63    Message {
64        /// Database ID of the message.
65        msg_id: MsgId,
66    },
67
68    /// Day marker, separating messages that correspond to different
69    /// days according to local time.
70    DayMarker {
71        /// Marker timestamp, for day markers
72        timestamp: i64,
73    },
74}
75
76/// The reason why messages cannot be sent to the chat.
77///
78/// The reason is mainly for logging and displaying in debug REPL, thus not translated.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub(crate) enum CantSendReason {
81    /// Special chat.
82    SpecialChat,
83
84    /// The chat is a device chat.
85    DeviceChat,
86
87    /// The chat is a contact request, it needs to be accepted before sending a message.
88    ContactRequest,
89
90    /// Mailing list without known List-Post header.
91    ReadOnlyMailingList,
92
93    /// Incoming broadcast channel where the user can't send messages.
94    InBroadcast,
95
96    /// Not a member of the chat.
97    NotAMember,
98
99    /// State for 1:1 chat with a key-contact that does not have a key.
100    MissingKey,
101}
102
103impl fmt::Display for CantSendReason {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Self::SpecialChat => write!(f, "the chat is a special chat"),
107            Self::DeviceChat => write!(f, "the chat is a device chat"),
108            Self::ContactRequest => write!(
109                f,
110                "contact request chat should be accepted before sending messages"
111            ),
112            Self::ReadOnlyMailingList => {
113                write!(f, "mailing list does not have a know post address")
114            }
115            Self::InBroadcast => {
116                write!(f, "Broadcast channel is read-only")
117            }
118            Self::NotAMember => write!(f, "not a member of the chat"),
119            Self::MissingKey => write!(f, "key is missing"),
120        }
121    }
122}
123
124/// Chat ID, including reserved IDs.
125///
126/// Some chat IDs are reserved to identify special chat types.  This
127/// type can represent both the special as well as normal chats.
128#[derive(
129    Debug, Copy, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Hash, PartialOrd, Ord,
130)]
131pub struct ChatId(u32);
132
133impl ChatId {
134    /// Create a new [ChatId].
135    pub const fn new(id: u32) -> ChatId {
136        ChatId(id)
137    }
138
139    /// An unset ChatId
140    ///
141    /// This is transitional and should not be used in new code.
142    pub fn is_unset(self) -> bool {
143        self.0 == 0
144    }
145
146    /// Whether the chat ID signifies a special chat.
147    ///
148    /// This kind of chat ID can not be used for real chats.
149    pub fn is_special(self) -> bool {
150        (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)
151    }
152
153    /// Chat ID for messages which need to be deleted.
154    ///
155    /// Messages which should be deleted get this chat ID and are
156    /// deleted later.  Deleted messages need to stay around as long
157    /// as they are not deleted on the server so that their rfc724_mid
158    /// remains known and downloading them again can be avoided.
159    pub fn is_trash(self) -> bool {
160        self == DC_CHAT_ID_TRASH
161    }
162
163    /// Chat ID signifying there are **any** number of archived chats.
164    ///
165    /// This chat ID can be returned in a [`Chatlist`] and signals to
166    /// the UI to include a link to the archived chats.
167    ///
168    /// [`Chatlist`]: crate::chatlist::Chatlist
169    pub fn is_archived_link(self) -> bool {
170        self == DC_CHAT_ID_ARCHIVED_LINK
171    }
172
173    /// Virtual chat ID signalling there are **only** archived chats.
174    ///
175    /// This can be included in the chatlist if the
176    /// [`DC_GCL_ADD_ALLDONE_HINT`] flag is used to build the
177    /// [`Chatlist`].
178    ///
179    /// [`DC_GCL_ADD_ALLDONE_HINT`]: crate::constants::DC_GCL_ADD_ALLDONE_HINT
180    /// [`Chatlist`]: crate::chatlist::Chatlist
181    pub fn is_alldone_hint(self) -> bool {
182        self == DC_CHAT_ID_ALLDONE_HINT
183    }
184
185    /// Returns [`ChatId`] of a chat that `msg` belongs to.
186    pub(crate) fn lookup_by_message(msg: &Message) -> Option<Self> {
187        if msg.chat_id == DC_CHAT_ID_TRASH {
188            return None;
189        }
190        if msg.download_state == DownloadState::Undecipherable {
191            return None;
192        }
193        Some(msg.chat_id)
194    }
195
196    /// Returns the [`ChatId`] for the 1:1 chat with `contact_id`
197    /// if it exists and is not blocked.
198    ///
199    /// If the chat does not exist or is blocked, `None` is returned.
200    pub async fn lookup_by_contact(
201        context: &Context,
202        contact_id: ContactId,
203    ) -> Result<Option<Self>> {
204        let Some(chat_id_blocked) = ChatIdBlocked::lookup_by_contact(context, contact_id).await?
205        else {
206            return Ok(None);
207        };
208
209        let chat_id = match chat_id_blocked.blocked {
210            Blocked::Not | Blocked::Request => Some(chat_id_blocked.id),
211            Blocked::Yes => None,
212        };
213        Ok(chat_id)
214    }
215
216    /// Returns the [`ChatId`] for the 1:1 chat with `contact_id`.
217    ///
218    /// If the chat does not yet exist an unblocked chat ([`Blocked::Not`]) is created.
219    ///
220    /// This is an internal API, if **a user action** needs to get a chat
221    /// [`ChatId::create_for_contact`] should be used as this also scales up the
222    /// [`Contact`]'s origin.
223    pub(crate) async fn get_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
224        ChatIdBlocked::get_for_contact(context, contact_id, Blocked::Not)
225            .await
226            .map(|chat| chat.id)
227    }
228
229    /// Returns the unblocked 1:1 chat with `contact_id`.
230    ///
231    /// This should be used when **a user action** creates a chat 1:1, it ensures the chat
232    /// exists, is unblocked and scales the [`Contact`]'s origin.
233    pub async fn create_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
234        ChatId::create_for_contact_with_blocked(context, contact_id, Blocked::Not).await
235    }
236
237    /// Same as `create_for_contact()` with an additional `create_blocked` parameter
238    /// that is used in case the chat does not exist or to unblock existing chats.
239    /// `create_blocked` won't block already unblocked chats again.
240    pub(crate) async fn create_for_contact_with_blocked(
241        context: &Context,
242        contact_id: ContactId,
243        create_blocked: Blocked,
244    ) -> Result<Self> {
245        let chat_id = match ChatIdBlocked::lookup_by_contact(context, contact_id).await? {
246            Some(chat) => {
247                if create_blocked != Blocked::Not || chat.blocked == Blocked::Not {
248                    return Ok(chat.id);
249                }
250                chat.id.set_blocked(context, Blocked::Not).await?;
251                chat.id
252            }
253            None => {
254                if Contact::real_exists_by_id(context, contact_id).await?
255                    || contact_id == ContactId::SELF
256                {
257                    let chat_id =
258                        ChatIdBlocked::get_for_contact(context, contact_id, create_blocked)
259                            .await
260                            .map(|chat| chat.id)?;
261                    if create_blocked != Blocked::Yes {
262                        info!(context, "Scale up origin of {contact_id} to CreateChat.");
263                        ContactId::scaleup_origin(context, &[contact_id], Origin::CreateChat)
264                            .await?;
265                    }
266                    chat_id
267                } else {
268                    warn!(
269                        context,
270                        "Cannot create chat, contact {contact_id} does not exist."
271                    );
272                    bail!("Can not create chat for non-existing contact");
273                }
274            }
275        };
276        context.emit_msgs_changed_without_ids();
277        chatlist_events::emit_chatlist_changed(context);
278        chatlist_events::emit_chatlist_item_changed(context, chat_id);
279        Ok(chat_id)
280    }
281
282    /// Create a group or mailinglist raw database record with the given parameters.
283    /// The function does not add SELF nor checks if the record already exists.
284    pub(crate) async fn create_multiuser_record(
285        context: &Context,
286        chattype: Chattype,
287        grpid: &str,
288        grpname: &str,
289        create_blocked: Blocked,
290        param: Option<String>,
291        timestamp: i64,
292    ) -> Result<Self> {
293        let grpname = sanitize_single_line(grpname);
294        let timestamp = cmp::min(timestamp, smeared_time(context));
295        let row_id =
296            context.sql.insert(
297                "INSERT INTO chats (type, name, name_normalized, grpid, blocked, created_timestamp, protected, param) VALUES(?, ?, ?, ?, ?, ?, 0, ?)",
298                (
299                    chattype,
300                    &grpname,
301                    normalize_text(&grpname),
302                    grpid,
303                    create_blocked,
304                    timestamp,
305                    param.unwrap_or_default(),
306                ),
307            ).await?;
308
309        let chat_id = ChatId::new(u32::try_from(row_id)?);
310        let chat = Chat::load_from_db(context, chat_id).await?;
311
312        if chat.is_encrypted(context).await? {
313            chat_id.add_e2ee_notice(context, timestamp).await?;
314        }
315
316        info!(
317            context,
318            "Created group/broadcast '{}' grpid={} as {}, blocked={}.",
319            &grpname,
320            grpid,
321            chat_id,
322            create_blocked,
323        );
324
325        Ok(chat_id)
326    }
327
328    async fn set_selfavatar_timestamp(self, context: &Context, timestamp: i64) -> Result<()> {
329        context
330            .sql
331            .execute(
332                "UPDATE contacts
333                 SET selfavatar_sent=?
334                 WHERE id IN(SELECT contact_id FROM chats_contacts WHERE chat_id=? AND add_timestamp >= remove_timestamp)",
335                (timestamp, self),
336            )
337            .await?;
338        Ok(())
339    }
340
341    /// Updates chat blocked status.
342    ///
343    /// Returns true if the value was modified.
344    pub(crate) async fn set_blocked(self, context: &Context, new_blocked: Blocked) -> Result<bool> {
345        if self.is_special() {
346            bail!("ignoring setting of Block-status for {self}");
347        }
348        let count = context
349            .sql
350            .execute(
351                "UPDATE chats SET blocked=?1 WHERE id=?2 AND blocked != ?1",
352                (new_blocked, self),
353            )
354            .await?;
355        Ok(count > 0)
356    }
357
358    /// Blocks the chat as a result of explicit user action.
359    pub async fn block(self, context: &Context) -> Result<()> {
360        self.block_ex(context, Sync).await
361    }
362
363    pub(crate) async fn block_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
364        let chat = Chat::load_from_db(context, self).await?;
365        let mut delete = false;
366
367        match chat.typ {
368            Chattype::OutBroadcast => {
369                bail!("Can't block chat of type {:?}", chat.typ)
370            }
371            Chattype::Single => {
372                for contact_id in get_chat_contacts(context, self).await? {
373                    if contact_id != ContactId::SELF {
374                        info!(
375                            context,
376                            "Blocking the contact {contact_id} to block 1:1 chat."
377                        );
378                        contact::set_blocked(context, Nosync, contact_id, true).await?;
379                    }
380                }
381            }
382            Chattype::Group => {
383                info!(context, "Can't block groups yet, deleting the chat.");
384                delete = true;
385            }
386            Chattype::Mailinglist | Chattype::InBroadcast => {
387                if self.set_blocked(context, Blocked::Yes).await? {
388                    context.emit_event(EventType::ChatModified(self));
389                }
390            }
391        }
392        chatlist_events::emit_chatlist_changed(context);
393
394        if sync.into() {
395            // NB: For a 1:1 chat this currently triggers `Contact::block()` on other devices.
396            chat.sync(context, SyncAction::Block)
397                .await
398                .log_err(context)
399                .ok();
400        }
401        if delete {
402            self.delete_ex(context, Nosync).await?;
403        }
404        Ok(())
405    }
406
407    /// Unblocks the chat.
408    pub async fn unblock(self, context: &Context) -> Result<()> {
409        self.unblock_ex(context, Sync).await
410    }
411
412    pub(crate) async fn unblock_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
413        self.set_blocked(context, Blocked::Not).await?;
414
415        chatlist_events::emit_chatlist_changed(context);
416
417        if sync.into() {
418            let chat = Chat::load_from_db(context, self).await?;
419            // TODO: For a 1:1 chat this currently triggers `Contact::unblock()` on other devices.
420            // Maybe we should unblock the contact locally too, this would also resolve discrepancy
421            // with `block()` which also blocks the contact.
422            chat.sync(context, SyncAction::Unblock)
423                .await
424                .log_err(context)
425                .ok();
426        }
427
428        Ok(())
429    }
430
431    /// Accept the contact request.
432    ///
433    /// Unblocks the chat and scales up origin of contacts.
434    pub async fn accept(self, context: &Context) -> Result<()> {
435        self.accept_ex(context, Sync).await
436    }
437
438    pub(crate) async fn accept_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
439        let chat = Chat::load_from_db(context, self).await?;
440
441        match chat.typ {
442            Chattype::Single | Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast => {
443                // Previously accepting a chat literally created a chat because unaccepted chats
444                // went to "contact requests" list rather than normal chatlist.
445                // But for groups we use lower origin because users don't always check all members
446                // before accepting a chat and may not want to have the group members mixed with
447                // existing contacts. `IncomingTo` fits here by its definition.
448                let origin = match chat.typ {
449                    Chattype::Group => Origin::IncomingTo,
450                    _ => Origin::CreateChat,
451                };
452                for contact_id in get_chat_contacts(context, self).await? {
453                    if contact_id != ContactId::SELF {
454                        ContactId::scaleup_origin(context, &[contact_id], origin).await?;
455                    }
456                }
457            }
458            Chattype::Mailinglist => {
459                // If the message is from a mailing list, the contacts are not counted as "known"
460            }
461        }
462
463        if self.set_blocked(context, Blocked::Not).await? {
464            context.emit_event(EventType::ChatModified(self));
465            chatlist_events::emit_chatlist_item_changed(context, self);
466        }
467
468        if sync.into() {
469            chat.sync(context, SyncAction::Accept)
470                .await
471                .log_err(context)
472                .ok();
473        }
474        Ok(())
475    }
476
477    /// Adds message "Messages are end-to-end encrypted".
478    pub(crate) async fn add_e2ee_notice(self, context: &Context, timestamp: i64) -> Result<()> {
479        let text = stock_str::messages_e2ee_info_msg(context);
480
481        // Sort this notice to the very beginning of the chat.
482        // We don't want any message to appear before this notice
483        // which is normally added when encrypted chat is created.
484        let sort_timestamp = 0;
485        add_info_msg_with_cmd(
486            context,
487            self,
488            &text,
489            SystemMessage::ChatE2ee,
490            Some(sort_timestamp),
491            timestamp,
492            None,
493            None,
494            None,
495        )
496        .await?;
497        Ok(())
498    }
499
500    /// Adds info message to the beginning of the chat.
501    ///
502    /// Used for messages such as
503    /// "Others will only see this group after you sent a first message."
504    pub(crate) async fn add_start_info_message(self, context: &Context, text: &str) -> Result<()> {
505        let sort_timestamp = 0;
506        add_info_msg_with_cmd(
507            context,
508            self,
509            text,
510            SystemMessage::Unknown,
511            Some(sort_timestamp),
512            time(),
513            None,
514            None,
515            None,
516        )
517        .await?;
518        Ok(())
519    }
520
521    /// Archives or unarchives a chat.
522    pub async fn set_visibility(self, context: &Context, visibility: ChatVisibility) -> Result<()> {
523        self.set_visibility_ex(context, Sync, visibility).await
524    }
525
526    pub(crate) async fn set_visibility_ex(
527        self,
528        context: &Context,
529        sync: sync::Sync,
530        visibility: ChatVisibility,
531    ) -> Result<()> {
532        ensure!(
533            !self.is_special(),
534            "bad chat_id, can not be special chat: {self}"
535        );
536
537        context
538            .sql
539            .transaction(move |transaction| {
540                if visibility == ChatVisibility::Archived {
541                    transaction.execute(
542                        "UPDATE msgs SET state=? WHERE chat_id=? AND state=?;",
543                        (MessageState::InNoticed, self, MessageState::InFresh),
544                    )?;
545                }
546                transaction.execute(
547                    "UPDATE chats SET archived=? WHERE id=?;",
548                    (visibility, self),
549                )?;
550                Ok(())
551            })
552            .await?;
553
554        if visibility == ChatVisibility::Archived {
555            start_chat_ephemeral_timers(context, self).await?;
556        }
557
558        context.emit_msgs_changed_without_ids();
559        chatlist_events::emit_chatlist_changed(context);
560        chatlist_events::emit_chatlist_item_changed(context, self);
561
562        if sync.into() {
563            let chat = Chat::load_from_db(context, self).await?;
564            chat.sync(context, SyncAction::SetVisibility(visibility))
565                .await
566                .log_err(context)
567                .ok();
568        }
569        Ok(())
570    }
571
572    /// Unarchives a chat that is archived and not muted.
573    /// Needed after a message is added to a chat so that the chat gets a normal visibility again.
574    /// `msg_state` is the state of the message. Matters only for incoming messages currently. For
575    /// multiple outgoing messages the function may be called once with MessageState::Undefined.
576    /// Sending an appropriate event is up to the caller.
577    /// Also emits DC_EVENT_MSGS_CHANGED for DC_CHAT_ID_ARCHIVED_LINK when the number of archived
578    /// chats with unread messages increases (which is possible if the chat is muted).
579    pub async fn unarchive_if_not_muted(
580        self,
581        context: &Context,
582        msg_state: MessageState,
583    ) -> Result<()> {
584        if msg_state != MessageState::InFresh {
585            context
586                .sql
587                .execute(
588                    "UPDATE chats SET archived=0 WHERE id=? AND archived=1 \
589                AND NOT(muted_until=-1 OR muted_until>?)",
590                    (self, time()),
591                )
592                .await?;
593            return Ok(());
594        }
595        let chat = Chat::load_from_db(context, self).await?;
596        if chat.visibility != ChatVisibility::Archived {
597            return Ok(());
598        }
599        if chat.is_muted() {
600            let unread_cnt = context
601                .sql
602                .count(
603                    "SELECT COUNT(*)
604                FROM msgs
605                WHERE state=?
606                AND hidden=0
607                AND chat_id=?",
608                    (MessageState::InFresh, self),
609                )
610                .await?;
611            if unread_cnt == 1 {
612                // Added the first unread message in the chat.
613                context.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
614            }
615            return Ok(());
616        }
617        context
618            .sql
619            .execute("UPDATE chats SET archived=0 WHERE id=?", (self,))
620            .await?;
621        Ok(())
622    }
623
624    /// Emits an appropriate event for a message. `important` is whether a notification should be
625    /// shown.
626    pub(crate) fn emit_msg_event(self, context: &Context, msg_id: MsgId, important: bool) {
627        if important {
628            debug_assert!(!msg_id.is_unset());
629
630            context.emit_incoming_msg(self, msg_id);
631        } else {
632            context.emit_msgs_changed(self, msg_id);
633        }
634    }
635
636    /// Deletes a chat.
637    ///
638    /// Messages are deleted from the device and the chat database entry is deleted.
639    /// After that, a `MsgsChanged` event is emitted.
640    /// Messages are deleted from the server in background.
641    pub async fn delete(self, context: &Context) -> Result<()> {
642        self.delete_ex(context, Sync).await
643    }
644
645    pub(crate) async fn delete_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
646        ensure!(
647            !self.is_special(),
648            "bad chat_id, can not be a special chat: {self}"
649        );
650
651        let chat = Chat::load_from_db(context, self).await?;
652        let sync_id = match sync {
653            Nosync => None,
654            Sync => chat.get_sync_id(context).await?,
655        };
656
657        context
658            .sql
659            .transaction(|transaction| {
660                transaction.execute(
661                    "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT rfc724_mid FROM msgs WHERE chat_id=? AND rfc724_mid!='')",
662                    (self,),
663                )?;
664                transaction.execute(
665                    "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT pre_rfc724_mid FROM msgs WHERE chat_id=? AND pre_rfc724_mid!='')",
666                    (self,),
667                )?;
668                transaction.execute(
669                    "DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?)",
670                    (self,),
671                )?;
672                // If you change which information is preserved here, also change `MsgId::trash()`
673                // and other places it references.
674                transaction.execute(
675                    "
676INSERT OR REPLACE INTO msgs (id, rfc724_mid, pre_rfc724_mid, timestamp, chat_id, deleted)
677SELECT id, rfc724_mid, pre_rfc724_mid, timestamp, ?, 1 FROM msgs WHERE chat_id=?
678                    ",
679                    (DC_CHAT_ID_TRASH, self),
680                )?;
681                transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (self,))?;
682                transaction.execute("DELETE FROM chats WHERE id=?", (self,))?;
683                Ok(())
684            })
685            .await?;
686
687        context.emit_event(EventType::ChatDeleted { chat_id: self });
688        context.emit_msgs_changed_without_ids();
689
690        if let Some(id) = sync_id {
691            self::sync(context, id, SyncAction::Delete)
692                .await
693                .log_err(context)
694                .ok();
695        }
696
697        if chat.is_self_talk() {
698            let mut msg = Message::new_text(stock_str::self_deleted_msg_body(context));
699            add_device_msg(context, None, Some(&mut msg)).await?;
700        }
701        chatlist_events::emit_chatlist_changed(context);
702
703        context
704            .set_config_internal(Config::LastHousekeeping, None)
705            .await?;
706        context.scheduler.interrupt_smtp().await;
707
708        Ok(())
709    }
710
711    /// Sets draft message.
712    ///
713    /// Passing `None` as message just deletes the draft
714    pub async fn set_draft(self, context: &Context, mut msg: Option<&mut Message>) -> Result<()> {
715        if self.is_special() {
716            return Ok(());
717        }
718
719        let changed = match &mut msg {
720            None => self.maybe_delete_draft(context).await?,
721            Some(msg) => self.do_set_draft(context, msg).await?,
722        };
723
724        if changed {
725            if msg.is_some() {
726                match self.get_draft_msg_id(context).await? {
727                    Some(msg_id) => context.emit_msgs_changed(self, msg_id),
728                    None => context.emit_msgs_changed_without_msg_id(self),
729                }
730            } else {
731                context.emit_msgs_changed_without_msg_id(self)
732            }
733        }
734
735        Ok(())
736    }
737
738    /// Returns ID of the draft message, if there is one.
739    async fn get_draft_msg_id(self, context: &Context) -> Result<Option<MsgId>> {
740        let msg_id: Option<MsgId> = context
741            .sql
742            .query_get_value(
743                "SELECT id FROM msgs WHERE chat_id=? AND state=?;",
744                (self, MessageState::OutDraft),
745            )
746            .await?;
747        Ok(msg_id)
748    }
749
750    /// Returns draft message, if there is one.
751    pub async fn get_draft(self, context: &Context) -> Result<Option<Message>> {
752        if self.is_special() {
753            return Ok(None);
754        }
755        match self.get_draft_msg_id(context).await? {
756            Some(draft_msg_id) => {
757                let msg = Message::load_from_db(context, draft_msg_id).await?;
758                Ok(Some(msg))
759            }
760            None => Ok(None),
761        }
762    }
763
764    /// Deletes draft message, if there is one.
765    ///
766    /// Returns `true`, if message was deleted, `false` otherwise.
767    async fn maybe_delete_draft(self, context: &Context) -> Result<bool> {
768        Ok(context
769            .sql
770            .execute(
771                "DELETE FROM msgs WHERE chat_id=? AND state=?",
772                (self, MessageState::OutDraft),
773            )
774            .await?
775            > 0)
776    }
777
778    /// Set provided message as draft message for specified chat.
779    /// Returns true if the draft was added or updated in place.
780    async fn do_set_draft(self, context: &Context, msg: &mut Message) -> Result<bool> {
781        match msg.viewtype {
782            Viewtype::Unknown => bail!("Can not set draft of unknown type."),
783            Viewtype::Text => {
784                if msg.text.is_empty() && msg.in_reply_to.is_none_or_empty() {
785                    bail!("No text and no quote in draft");
786                }
787            }
788            _ => {
789                if msg.viewtype == Viewtype::File
790                    && let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg)
791                        // We do not do an automatic conversion to other viewtypes here so that
792                        // users can send images as "files" to preserve the original quality
793                        // (usually we compress images). The remaining conversions are done by
794                        // `prepare_msg_blob()` later.
795                        .filter(|&(vt, _)| vt == Viewtype::Webxdc || vt == Viewtype::Vcard)
796                {
797                    msg.viewtype = better_type;
798                }
799                if msg.viewtype == Viewtype::Vcard {
800                    let blob = msg
801                        .param
802                        .get_file_blob(context)?
803                        .context("no file stored in params")?;
804                    msg.try_set_vcard(context, &blob.to_abs_path()).await?;
805                }
806            }
807        }
808
809        // set back draft information to allow identifying the draft later on -
810        // no matter if message object is reused or reloaded from db
811        msg.state = MessageState::OutDraft;
812        msg.chat_id = self;
813
814        // if possible, replace existing draft and keep id
815        if !msg.id.is_special()
816            && let Some(old_draft) = self.get_draft(context).await?
817            && old_draft.id == msg.id
818            && old_draft.chat_id == self
819            && old_draft.state == MessageState::OutDraft
820        {
821            let affected_rows = context
822                        .sql.execute(
823                                "UPDATE msgs
824                                SET timestamp=?1,type=?2,txt=?3,txt_normalized=?4,param=?5,mime_in_reply_to=?6
825                                WHERE id=?7
826                                AND (type <> ?2 
827                                    OR txt <> ?3 
828                                    OR txt_normalized <> ?4
829                                    OR param <> ?5
830                                    OR mime_in_reply_to <> ?6);",
831                                (
832                                    time(),
833                                    msg.viewtype,
834                                    &msg.text,
835                                    normalize_text(&msg.text),
836                                    msg.param.to_string(),
837                                    msg.in_reply_to.as_deref().unwrap_or_default(),
838                                    msg.id,
839                                ),
840                            ).await?;
841            return Ok(affected_rows > 0);
842        }
843
844        let row_id = context
845            .sql
846            .transaction(|transaction| {
847                // Delete existing draft if it exists.
848                transaction.execute(
849                    "DELETE FROM msgs WHERE chat_id=? AND state=?",
850                    (self, MessageState::OutDraft),
851                )?;
852
853                // Insert new draft.
854                transaction.execute(
855                    "INSERT INTO msgs (
856                 chat_id,
857                 rfc724_mid,
858                 from_id,
859                 timestamp,
860                 type,
861                 state,
862                 txt,
863                 txt_normalized,
864                 param,
865                 hidden,
866                 mime_in_reply_to)
867         VALUES (?,?,?,?,?,?,?,?,?,?,?);",
868                    (
869                        self,
870                        &msg.rfc724_mid,
871                        ContactId::SELF,
872                        time(),
873                        msg.viewtype,
874                        MessageState::OutDraft,
875                        &msg.text,
876                        normalize_text(&msg.text),
877                        msg.param.to_string(),
878                        1,
879                        msg.in_reply_to.as_deref().unwrap_or_default(),
880                    ),
881                )?;
882
883                Ok(transaction.last_insert_rowid())
884            })
885            .await?;
886        msg.id = MsgId::new(row_id.try_into()?);
887        Ok(true)
888    }
889
890    /// Returns number of messages in a chat.
891    pub async fn get_msg_cnt(self, context: &Context) -> Result<usize> {
892        let count = context
893            .sql
894            .count(
895                "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id=?",
896                (self,),
897            )
898            .await?;
899        Ok(count)
900    }
901
902    /// Returns the number of fresh messages in the chat.
903    pub async fn get_fresh_msg_cnt(self, context: &Context) -> Result<usize> {
904        // this function is typically used to show a badge counter beside _each_ chatlist item.
905        // to make this as fast as possible, esp. on older devices, we added an combined index over the rows used for querying.
906        // so if you alter the query here, you may want to alter the index over `(state, hidden, chat_id)` in `sql.rs`.
907        //
908        // the impact of the index is significant once the database grows:
909        // - on an older android4 with 18k messages, query-time decreased from 110ms to 2ms
910        // - on an mid-class moto-g or iphone7 with 50k messages, query-time decreased from 26ms or 6ms to 0-1ms
911        // the times are average, no matter if there are fresh messages or not -
912        // and have to be multiplied by the number of items shown at once on the chatlist,
913        // so savings up to 2 seconds are possible on older devices - newer ones will feel "snappier" :)
914        let count = if self.is_archived_link() {
915            context
916                .sql
917                .count(
918                    "SELECT COUNT(DISTINCT(m.chat_id))
919                    FROM msgs m
920                    LEFT JOIN chats c ON m.chat_id=c.id
921                    WHERE m.state=10
922                    and m.hidden=0
923                    AND m.chat_id>9
924                    AND c.blocked=0
925                    AND c.archived=1
926                    ",
927                    (),
928                )
929                .await?
930        } else {
931            context
932                .sql
933                .count(
934                    "SELECT COUNT(*)
935                FROM msgs
936                WHERE state=?
937                AND hidden=0
938                AND chat_id=?;",
939                    (MessageState::InFresh, self),
940                )
941                .await?
942        };
943        Ok(count)
944    }
945
946    pub(crate) async fn created_timestamp(self, context: &Context) -> Result<i64> {
947        Ok(context
948            .sql
949            .query_get_value("SELECT created_timestamp FROM chats WHERE id=?", (self,))
950            .await?
951            .unwrap_or(0))
952    }
953
954    /// Returns timestamp of us joining the chat if we are the member of the chat.
955    pub(crate) async fn join_timestamp(self, context: &Context) -> Result<Option<i64>> {
956        context
957            .sql
958            .query_get_value(
959                "SELECT add_timestamp FROM chats_contacts WHERE chat_id=? AND contact_id=?",
960                (self, ContactId::SELF),
961            )
962            .await
963    }
964
965    /// Returns timestamp of the latest message in the chat,
966    /// including hidden messages or a draft if there is one.
967    pub(crate) async fn get_timestamp(self, context: &Context) -> Result<Option<i64>> {
968        let timestamp = context
969            .sql
970            .query_get_value(
971                "SELECT MAX(timestamp)
972                 FROM msgs
973                 WHERE chat_id=?
974                 HAVING COUNT(*) > 0",
975                (self,),
976            )
977            .await?;
978        Ok(timestamp)
979    }
980
981    /// Returns a list of active similar chat IDs sorted by similarity metric.
982    ///
983    /// Jaccard similarity coefficient is used to estimate similarity of chat member sets.
984    ///
985    /// Chat is considered active if something was posted there within the last 42 days.
986    #[expect(clippy::arithmetic_side_effects)]
987    pub async fn get_similar_chat_ids(self, context: &Context) -> Result<Vec<(ChatId, f64)>> {
988        // Count number of common members in this and other chats.
989        let intersection = context
990            .sql
991            .query_map_vec(
992                "SELECT y.chat_id, SUM(x.contact_id = y.contact_id)
993                 FROM chats_contacts as x
994                 JOIN chats_contacts as y
995                 WHERE x.contact_id > 9
996                   AND y.contact_id > 9
997                   AND x.add_timestamp >= x.remove_timestamp
998                   AND y.add_timestamp >= y.remove_timestamp
999                   AND x.chat_id=?
1000                   AND y.chat_id<>x.chat_id
1001                   AND y.chat_id>?
1002                 GROUP BY y.chat_id",
1003                (self, DC_CHAT_ID_LAST_SPECIAL),
1004                |row| {
1005                    let chat_id: ChatId = row.get(0)?;
1006                    let intersection: f64 = row.get(1)?;
1007                    Ok((chat_id, intersection))
1008                },
1009            )
1010            .await
1011            .context("failed to calculate member set intersections")?;
1012
1013        let chat_size: HashMap<ChatId, f64> = context
1014            .sql
1015            .query_map_collect(
1016                "SELECT chat_id, count(*) AS n
1017                 FROM chats_contacts
1018                 WHERE contact_id > ? AND chat_id > ?
1019                 AND add_timestamp >= remove_timestamp
1020                 GROUP BY chat_id",
1021                (ContactId::LAST_SPECIAL, DC_CHAT_ID_LAST_SPECIAL),
1022                |row| {
1023                    let chat_id: ChatId = row.get(0)?;
1024                    let size: f64 = row.get(1)?;
1025                    Ok((chat_id, size))
1026                },
1027            )
1028            .await
1029            .context("failed to count chat member sizes")?;
1030
1031        let our_chat_size = chat_size.get(&self).copied().unwrap_or_default();
1032        let mut chats_with_metrics = Vec::new();
1033        for (chat_id, intersection_size) in intersection {
1034            if intersection_size > 0.0 {
1035                let other_chat_size = chat_size.get(&chat_id).copied().unwrap_or_default();
1036                let union_size = our_chat_size + other_chat_size - intersection_size;
1037                let metric = intersection_size / union_size;
1038                chats_with_metrics.push((chat_id, metric))
1039            }
1040        }
1041        chats_with_metrics.sort_unstable_by(|(chat_id1, metric1), (chat_id2, metric2)| {
1042            metric2
1043                .partial_cmp(metric1)
1044                .unwrap_or(chat_id2.cmp(chat_id1))
1045        });
1046
1047        // Select up to five similar active chats.
1048        let mut res = Vec::new();
1049        let now = time();
1050        for (chat_id, metric) in chats_with_metrics {
1051            if let Some(chat_timestamp) = chat_id.get_timestamp(context).await?
1052                && now > chat_timestamp + 42 * 24 * 3600
1053            {
1054                // Chat was inactive for 42 days, skip.
1055                continue;
1056            }
1057
1058            if metric < 0.1 {
1059                // Chat is unrelated.
1060                break;
1061            }
1062
1063            let chat = Chat::load_from_db(context, chat_id).await?;
1064            if chat.typ != Chattype::Group {
1065                continue;
1066            }
1067
1068            match chat.visibility {
1069                ChatVisibility::Normal | ChatVisibility::Pinned => {}
1070                ChatVisibility::Archived => continue,
1071            }
1072
1073            res.push((chat_id, metric));
1074            if res.len() >= 5 {
1075                break;
1076            }
1077        }
1078
1079        Ok(res)
1080    }
1081
1082    /// Returns similar chats as a [`Chatlist`].
1083    ///
1084    /// [`Chatlist`]: crate::chatlist::Chatlist
1085    pub async fn get_similar_chatlist(self, context: &Context) -> Result<Chatlist> {
1086        let chat_ids: Vec<ChatId> = self
1087            .get_similar_chat_ids(context)
1088            .await
1089            .context("failed to get similar chat IDs")?
1090            .into_iter()
1091            .map(|(chat_id, _metric)| chat_id)
1092            .collect();
1093        let chatlist = Chatlist::from_chat_ids(context, &chat_ids).await?;
1094        Ok(chatlist)
1095    }
1096
1097    pub(crate) async fn get_param(self, context: &Context) -> Result<Params> {
1098        let res: Option<String> = context
1099            .sql
1100            .query_get_value("SELECT param FROM chats WHERE id=?", (self,))
1101            .await?;
1102        Ok(res
1103            .map(|s| s.parse().unwrap_or_default())
1104            .unwrap_or_default())
1105    }
1106
1107    /// Returns true if the chat is not promoted.
1108    pub(crate) async fn is_unpromoted(self, context: &Context) -> Result<bool> {
1109        let param = self.get_param(context).await?;
1110        let unpromoted = param.get_bool(Param::Unpromoted).unwrap_or_default();
1111        Ok(unpromoted)
1112    }
1113
1114    /// Returns true if the chat is promoted.
1115    pub(crate) async fn is_promoted(self, context: &Context) -> Result<bool> {
1116        let promoted = !self.is_unpromoted(context).await?;
1117        Ok(promoted)
1118    }
1119
1120    /// Returns true if chat is a saved messages chat.
1121    pub async fn is_self_talk(self, context: &Context) -> Result<bool> {
1122        Ok(self.get_param(context).await?.exists(Param::Selftalk))
1123    }
1124
1125    /// Returns true if chat is a device chat.
1126    pub async fn is_device_talk(self, context: &Context) -> Result<bool> {
1127        Ok(self.get_param(context).await?.exists(Param::Devicetalk))
1128    }
1129
1130    async fn parent_query<T, F>(
1131        self,
1132        context: &Context,
1133        fields: &str,
1134        state_out_min: MessageState,
1135        f: F,
1136    ) -> Result<Option<T>>
1137    where
1138        F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
1139        T: Send + 'static,
1140    {
1141        let sql = &context.sql;
1142        let query = format!(
1143            "SELECT {fields} \
1144             FROM msgs \
1145             WHERE chat_id=? \
1146             AND ((state BETWEEN {} AND {}) OR (state >= {})) \
1147             AND NOT hidden \
1148             AND download_state={} \
1149             AND from_id != {} \
1150             ORDER BY timestamp DESC, id DESC \
1151             LIMIT 1;",
1152            MessageState::InFresh as u32,
1153            MessageState::InSeen as u32,
1154            state_out_min as u32,
1155            // Do not reply to not fully downloaded messages. Such a message could be a group chat
1156            // message that we assigned to 1:1 chat.
1157            DownloadState::Done as u32,
1158            // Do not reference info messages, they are not actually sent out
1159            // and have Message-IDs unknown to other chat members.
1160            ContactId::INFO.to_u32(),
1161        );
1162        sql.query_row_optional(&query, (self,), f).await
1163    }
1164
1165    async fn get_parent_mime_headers(
1166        self,
1167        context: &Context,
1168        state_out_min: MessageState,
1169    ) -> Result<Option<(String, String, String)>> {
1170        self.parent_query(
1171            context,
1172            "rfc724_mid, mime_in_reply_to, IFNULL(mime_references, '')",
1173            state_out_min,
1174            |row: &rusqlite::Row| {
1175                let rfc724_mid: String = row.get(0)?;
1176                let mime_in_reply_to: String = row.get(1)?;
1177                let mime_references: String = row.get(2)?;
1178                Ok((rfc724_mid, mime_in_reply_to, mime_references))
1179            },
1180        )
1181        .await
1182    }
1183
1184    /// Returns multi-line text summary of encryption preferences of all chat contacts.
1185    ///
1186    /// This can be used to find out if encryption is not available because
1187    /// keys for some users are missing or simply because the majority of the users in a group
1188    /// prefer plaintext emails.
1189    ///
1190    /// To get more verbose summary for a contact, including its key fingerprint, use [`Contact::get_encrinfo`].
1191    #[expect(clippy::arithmetic_side_effects)]
1192    pub async fn get_encryption_info(self, context: &Context) -> Result<String> {
1193        let chat = Chat::load_from_db(context, self).await?;
1194        if !chat.is_encrypted(context).await? {
1195            return Ok(stock_str::encr_none(context));
1196        }
1197
1198        let mut ret = stock_str::messages_are_e2ee(context) + "\n";
1199
1200        for &contact_id in get_chat_contacts(context, self)
1201            .await?
1202            .iter()
1203            .filter(|&contact_id| !contact_id.is_special())
1204        {
1205            let contact = Contact::get_by_id(context, contact_id).await?;
1206            let addr = contact.get_addr();
1207            logged_debug_assert!(
1208                context,
1209                contact.is_key_contact(),
1210                "get_encryption_info: contact {contact_id} is not a key-contact."
1211            );
1212            let fingerprint = contact
1213                .fingerprint()
1214                .context("Contact does not have a fingerprint in encrypted chat")?;
1215            if let Some(public_key) = contact.public_key(context).await? {
1216                if let Some(relay_addrs) = addresses_from_public_key(&public_key) {
1217                    let relays = relay_addrs.join(",");
1218                    ret += &format!("\n{addr}({relays})\n{fingerprint}\n");
1219                } else {
1220                    ret += &format!("\n{addr}\n{fingerprint}\n");
1221                }
1222            } else {
1223                ret += &format!("\n{addr}\n(key missing)\n{fingerprint}\n");
1224            }
1225        }
1226
1227        Ok(ret.trim().to_string())
1228    }
1229
1230    /// Bad evil escape hatch.
1231    ///
1232    /// Avoid using this, eventually types should be cleaned up enough
1233    /// that it is no longer necessary.
1234    pub fn to_u32(self) -> u32 {
1235        self.0
1236    }
1237
1238    pub(crate) async fn reset_gossiped_timestamp(self, context: &Context) -> Result<()> {
1239        context
1240            .sql
1241            .execute("DELETE FROM gossip_timestamp WHERE chat_id=?", (self,))
1242            .await?;
1243        Ok(())
1244    }
1245
1246    /// Returns the sort timestamp for a new message in the chat.
1247    ///
1248    /// `message_timestamp` should be either the message "sent" timestamp or a timestamp of the
1249    /// corresponding event in case of a system message (usually the current system time).
1250    /// `always_sort_to_bottom` makes this adjust the returned timestamp up so that the message goes
1251    /// to the chat bottom.
1252    pub(crate) async fn calc_sort_timestamp(
1253        self,
1254        context: &Context,
1255        message_timestamp: i64,
1256        always_sort_to_bottom: bool,
1257    ) -> Result<i64> {
1258        let mut sort_timestamp = cmp::min(message_timestamp, smeared_time(context));
1259
1260        let last_msg_time: Option<i64> = if always_sort_to_bottom {
1261            // get newest message for this chat
1262
1263            // Let hidden messages also be ordered with protection messages because hidden messages
1264            // also can be or not be verified, so let's preserve this information -- even it's not
1265            // used currently, it can be useful in the future versions.
1266            context
1267                .sql
1268                .query_get_value(
1269                    "SELECT MAX(timestamp)
1270                     FROM msgs
1271                     WHERE chat_id=? AND state!=?
1272                     HAVING COUNT(*) > 0",
1273                    (self, MessageState::OutDraft),
1274                )
1275                .await?
1276        } else {
1277            None
1278        };
1279
1280        if let Some(last_msg_time) = last_msg_time
1281            && last_msg_time > sort_timestamp
1282        {
1283            sort_timestamp = last_msg_time;
1284        }
1285
1286        if let Some(join_timestamp) = self.join_timestamp(context).await? {
1287            // If we are the member of the chat, don't add messages
1288            // before the timestamp of us joining it.
1289            // This is needed to avoid sorting "Member added"
1290            // or automatically sent bot welcome messages
1291            // above SecureJoin system messages.
1292            Ok(std::cmp::max(sort_timestamp, join_timestamp))
1293        } else {
1294            Ok(sort_timestamp)
1295        }
1296    }
1297}
1298
1299impl std::fmt::Display for ChatId {
1300    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1301        if self.is_trash() {
1302            write!(f, "Chat#Trash")
1303        } else if self.is_archived_link() {
1304            write!(f, "Chat#ArchivedLink")
1305        } else if self.is_alldone_hint() {
1306            write!(f, "Chat#AlldoneHint")
1307        } else if self.is_special() {
1308            write!(f, "Chat#Special{}", self.0)
1309        } else {
1310            write!(f, "Chat#{}", self.0)
1311        }
1312    }
1313}
1314
1315/// Allow converting [ChatId] to an SQLite type.
1316///
1317/// This allows you to directly store [ChatId] into the database as
1318/// well as query for a [ChatId].
1319impl rusqlite::types::ToSql for ChatId {
1320    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
1321        let val = rusqlite::types::Value::Integer(i64::from(self.0));
1322        let out = rusqlite::types::ToSqlOutput::Owned(val);
1323        Ok(out)
1324    }
1325}
1326
1327/// Allow converting an SQLite integer directly into [ChatId].
1328impl rusqlite::types::FromSql for ChatId {
1329    fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
1330        i64::column_result(value).and_then(|val| {
1331            if 0 <= val && val <= i64::from(u32::MAX) {
1332                Ok(ChatId::new(val as u32))
1333            } else {
1334                Err(rusqlite::types::FromSqlError::OutOfRange(val))
1335            }
1336        })
1337    }
1338}
1339
1340/// An object representing a single chat in memory.
1341/// Chat objects are created using eg. `Chat::load_from_db`
1342/// and are not updated on database changes;
1343/// if you want an update, you have to recreate the object.
1344#[derive(Debug, Clone, Deserialize, Serialize)]
1345pub struct Chat {
1346    /// Database ID.
1347    pub id: ChatId,
1348
1349    /// Chat type, e.g. 1:1 chat, group chat, mailing list.
1350    pub typ: Chattype,
1351
1352    /// Chat name.
1353    pub name: String,
1354
1355    /// Whether the chat is archived or pinned.
1356    pub visibility: ChatVisibility,
1357
1358    /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and
1359    /// ad-hoc groups.
1360    pub grpid: String,
1361
1362    /// Whether the chat is blocked, unblocked or a contact request.
1363    pub blocked: Blocked,
1364
1365    /// Additional chat parameters stored in the database.
1366    pub param: Params,
1367
1368    /// If location streaming is enabled in the chat.
1369    is_sending_locations: bool,
1370
1371    /// Duration of the chat being muted.
1372    pub mute_duration: MuteDuration,
1373}
1374
1375impl Chat {
1376    /// Loads chat from the database by its ID.
1377    pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> {
1378        let mut chat = context
1379            .sql
1380            .query_row(
1381                "SELECT c.type, c.name, c.grpid, c.param, c.archived,
1382                    c.blocked, c.locations_send_until, c.muted_until
1383             FROM chats c
1384             WHERE c.id=?;",
1385                (chat_id,),
1386                |row| {
1387                    let c = Chat {
1388                        id: chat_id,
1389                        typ: row.get(0)?,
1390                        name: row.get::<_, String>(1)?,
1391                        grpid: row.get::<_, String>(2)?,
1392                        param: row.get::<_, String>(3)?.parse().unwrap_or_default(),
1393                        visibility: row.get(4)?,
1394                        blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
1395                        is_sending_locations: row.get(6)?,
1396                        mute_duration: row.get(7)?,
1397                    };
1398                    Ok(c)
1399                },
1400            )
1401            .await
1402            .context(format!("Failed loading chat {chat_id} from database"))?;
1403
1404        if chat.id.is_archived_link() {
1405            chat.name = stock_str::archived_chats(context);
1406        } else {
1407            if chat.typ == Chattype::Single && chat.name.is_empty() {
1408                // chat.name is set to contact.display_name on changes,
1409                // however, if things went wrong somehow, we do this here explicitly.
1410                let mut chat_name = "Err [Name not found]".to_owned();
1411                match get_chat_contacts(context, chat.id).await {
1412                    Ok(contacts) => {
1413                        if let Some(contact_id) = contacts.first()
1414                            && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1415                        {
1416                            contact.get_display_name().clone_into(&mut chat_name);
1417                        }
1418                    }
1419                    Err(err) => {
1420                        error!(
1421                            context,
1422                            "Failed to load contacts for {}: {:#}.", chat.id, err
1423                        );
1424                    }
1425                }
1426                chat.name = chat_name;
1427            }
1428            if chat.param.exists(Param::Selftalk) {
1429                chat.name = stock_str::saved_messages(context);
1430            } else if chat.param.exists(Param::Devicetalk) {
1431                chat.name = stock_str::device_messages(context);
1432            }
1433        }
1434
1435        Ok(chat)
1436    }
1437
1438    /// Returns whether this is the `saved messages` chat
1439    pub fn is_self_talk(&self) -> bool {
1440        self.param.exists(Param::Selftalk)
1441    }
1442
1443    /// Returns true if chat is a device chat.
1444    pub fn is_device_talk(&self) -> bool {
1445        self.param.exists(Param::Devicetalk)
1446    }
1447
1448    /// Returns true if chat is a mailing list.
1449    pub fn is_mailing_list(&self) -> bool {
1450        self.typ == Chattype::Mailinglist
1451    }
1452
1453    /// Returns None if user can send messages to this chat.
1454    ///
1455    /// Otherwise returns a reason useful for logging.
1456    pub(crate) async fn why_cant_send(&self, context: &Context) -> Result<Option<CantSendReason>> {
1457        self.why_cant_send_ex(context, &|_| false).await
1458    }
1459
1460    pub(crate) async fn why_cant_send_ex(
1461        &self,
1462        context: &Context,
1463        skip_fn: &(dyn Send + Sync + Fn(&CantSendReason) -> bool),
1464    ) -> Result<Option<CantSendReason>> {
1465        use CantSendReason::*;
1466        // NB: Don't forget to update Chatlist::try_load() when changing this function!
1467
1468        if self.id.is_special() {
1469            let reason = SpecialChat;
1470            if !skip_fn(&reason) {
1471                return Ok(Some(reason));
1472            }
1473        }
1474        if self.is_device_talk() {
1475            let reason = DeviceChat;
1476            if !skip_fn(&reason) {
1477                return Ok(Some(reason));
1478            }
1479        }
1480        if self.is_contact_request() {
1481            let reason = ContactRequest;
1482            if !skip_fn(&reason) {
1483                return Ok(Some(reason));
1484            }
1485        }
1486        if self.is_mailing_list() && self.get_mailinglist_addr().is_none_or_empty() {
1487            let reason = ReadOnlyMailingList;
1488            if !skip_fn(&reason) {
1489                return Ok(Some(reason));
1490            }
1491        }
1492        if self.typ == Chattype::InBroadcast {
1493            let reason = InBroadcast;
1494            if !skip_fn(&reason) {
1495                return Ok(Some(reason));
1496            }
1497        }
1498
1499        // Do potentially slow checks last and after calls to `skip_fn` which should be fast.
1500        let reason = NotAMember;
1501        if !skip_fn(&reason) && !self.is_self_in_chat(context).await? {
1502            return Ok(Some(reason));
1503        }
1504
1505        let reason = MissingKey;
1506        if !skip_fn(&reason) && self.typ == Chattype::Single {
1507            let contact_ids = get_chat_contacts(context, self.id).await?;
1508            if let Some(contact_id) = contact_ids.first() {
1509                let contact = Contact::get_by_id(context, *contact_id).await?;
1510                if contact.is_key_contact() && contact.public_key(context).await?.is_none() {
1511                    return Ok(Some(reason));
1512                }
1513            }
1514        }
1515
1516        Ok(None)
1517    }
1518
1519    /// Returns true if can send to the chat.
1520    ///
1521    /// This function can be used by the UI to decide whether to display the input box.
1522    pub async fn can_send(&self, context: &Context) -> Result<bool> {
1523        Ok(self.why_cant_send(context).await?.is_none())
1524    }
1525
1526    /// Checks if the user is part of a chat
1527    /// and has basically the permissions to edit the chat therefore.
1528    /// The function does not check if the chat type allows editing of concrete elements.
1529    pub async fn is_self_in_chat(&self, context: &Context) -> Result<bool> {
1530        match self.typ {
1531            Chattype::Single | Chattype::OutBroadcast | Chattype::Mailinglist => Ok(true),
1532            Chattype::Group | Chattype::InBroadcast => {
1533                is_contact_in_chat(context, self.id, ContactId::SELF).await
1534            }
1535        }
1536    }
1537
1538    pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {
1539        context
1540            .sql
1541            .execute(
1542                "UPDATE chats SET param=? WHERE id=?",
1543                (self.param.to_string(), self.id),
1544            )
1545            .await?;
1546        Ok(())
1547    }
1548
1549    /// Returns chat ID.
1550    pub fn get_id(&self) -> ChatId {
1551        self.id
1552    }
1553
1554    /// Returns chat type.
1555    pub fn get_type(&self) -> Chattype {
1556        self.typ
1557    }
1558
1559    /// Returns chat name.
1560    pub fn get_name(&self) -> &str {
1561        &self.name
1562    }
1563
1564    /// Returns mailing list address where messages are sent to.
1565    pub fn get_mailinglist_addr(&self) -> Option<&str> {
1566        self.param.get(Param::ListPost)
1567    }
1568
1569    /// Returns profile image path for the chat.
1570    pub async fn get_profile_image(&self, context: &Context) -> Result<Option<PathBuf>> {
1571        if self.id.is_archived_link() {
1572            // This is not a real chat, but the "Archive" button
1573            // that is shown at the top of the chats list
1574            return Ok(Some(get_archive_icon(context).await?));
1575        } else if self.is_device_talk() {
1576            return Ok(Some(get_device_icon(context).await?));
1577        } else if self.is_self_talk() {
1578            return Ok(Some(get_saved_messages_icon(context).await?));
1579        } else if !self.is_encrypted(context).await? {
1580            // This is an unencrypted chat, show a special avatar that marks it as such.
1581            return Ok(Some(get_abs_path(
1582                context,
1583                Path::new(&get_unencrypted_icon(context).await?),
1584            )));
1585        } else if self.typ == Chattype::Single {
1586            // For 1:1 chats, we always use the same avatar as for the contact
1587            // This is before the `self.is_encrypted()` check, because that function
1588            // has two database calls, i.e. it's slow
1589            let contacts = get_chat_contacts(context, self.id).await?;
1590            if let Some(contact_id) = contacts.first() {
1591                let contact = Contact::get_by_id(context, *contact_id).await?;
1592                return contact.get_profile_image(context).await;
1593            }
1594        } else if let Some(image_rel) = self.param.get(Param::ProfileImage) {
1595            // Load the group avatar, or the device-chat / saved-messages icon
1596            if !image_rel.is_empty() {
1597                return Ok(Some(get_abs_path(context, Path::new(&image_rel))));
1598            }
1599        }
1600        Ok(None)
1601    }
1602
1603    /// Returns chat avatar color.
1604    ///
1605    /// For 1:1 chats, the color is calculated from the contact's address
1606    /// for address-contacts and from the OpenPGP key fingerprint for key-contacts.
1607    /// For group chats the color is calculated from the grpid, if present, or the chat name.
1608    pub async fn get_color(&self, context: &Context) -> Result<u32> {
1609        let mut color = 0;
1610
1611        if self.typ == Chattype::Single {
1612            let contacts = get_chat_contacts(context, self.id).await?;
1613            if let Some(contact_id) = contacts.first()
1614                && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1615            {
1616                color = contact.get_color();
1617            }
1618        } else if !self.grpid.is_empty() {
1619            color = str_to_color(&self.grpid);
1620        } else {
1621            color = str_to_color(&self.name);
1622        }
1623
1624        Ok(color)
1625    }
1626
1627    /// Returns a struct describing the current state of the chat.
1628    ///
1629    /// This is somewhat experimental, even more so than the rest of
1630    /// deltachat, and the data returned is still subject to change.
1631    pub async fn get_info(&self, context: &Context) -> Result<ChatInfo> {
1632        let draft = match self.id.get_draft(context).await? {
1633            Some(message) => message.text,
1634            _ => String::new(),
1635        };
1636        Ok(ChatInfo {
1637            id: self.id,
1638            type_: self.typ as u32,
1639            name: self.name.clone(),
1640            archived: self.visibility == ChatVisibility::Archived,
1641            param: self.param.to_string(),
1642            is_sending_locations: self.is_sending_locations,
1643            color: self.get_color(context).await?,
1644            profile_image: self
1645                .get_profile_image(context)
1646                .await?
1647                .unwrap_or_else(std::path::PathBuf::new),
1648            draft,
1649            is_muted: self.is_muted(),
1650            ephemeral_timer: self.id.get_ephemeral_timer(context).await?,
1651        })
1652    }
1653
1654    /// Returns chat visibilitiy, e.g. whether it is archived or pinned.
1655    pub fn get_visibility(&self) -> ChatVisibility {
1656        self.visibility
1657    }
1658
1659    /// Returns true if chat is a contact request.
1660    ///
1661    /// Messages cannot be sent to such chat and read receipts are not
1662    /// sent until the chat is manually unblocked.
1663    pub fn is_contact_request(&self) -> bool {
1664        self.blocked == Blocked::Request
1665    }
1666
1667    /// Returns true if the chat is not promoted.
1668    pub fn is_unpromoted(&self) -> bool {
1669        self.param.get_bool(Param::Unpromoted).unwrap_or_default()
1670    }
1671
1672    /// Returns true if the chat is promoted.
1673    /// This means a message has been sent to it and it _not_ only exists on the users device.
1674    pub fn is_promoted(&self) -> bool {
1675        !self.is_unpromoted()
1676    }
1677
1678    /// Returns true if the chat is encrypted.
1679    pub async fn is_encrypted(&self, context: &Context) -> Result<bool> {
1680        let is_encrypted = self.is_self_talk()
1681            || match self.typ {
1682                Chattype::Single => {
1683                    match context
1684                        .sql
1685                        .query_row_optional(
1686                            "SELECT cc.contact_id, c.fingerprint<>''
1687                             FROM chats_contacts cc LEFT JOIN contacts c
1688                                 ON c.id=cc.contact_id
1689                             WHERE cc.chat_id=?
1690                            ",
1691                            (self.id,),
1692                            |row| {
1693                                let id: ContactId = row.get(0)?;
1694                                let is_key: bool = row.get(1)?;
1695                                Ok((id, is_key))
1696                            },
1697                        )
1698                        .await?
1699                    {
1700                        Some((id, is_key)) => is_key || id == ContactId::DEVICE,
1701                        None => true,
1702                    }
1703                }
1704                Chattype::Group => {
1705                    // Do not encrypt ad-hoc groups.
1706                    !self.grpid.is_empty()
1707                }
1708                Chattype::Mailinglist => false,
1709                Chattype::OutBroadcast | Chattype::InBroadcast => true,
1710            };
1711        Ok(is_encrypted)
1712    }
1713
1714    /// Returns true if location streaming is enabled in the chat.
1715    pub fn is_sending_locations(&self) -> bool {
1716        self.is_sending_locations
1717    }
1718
1719    /// Returns true if the chat is currently muted.
1720    pub fn is_muted(&self) -> bool {
1721        match self.mute_duration {
1722            MuteDuration::NotMuted => false,
1723            MuteDuration::Forever => true,
1724            MuteDuration::Until(when) => when > SystemTime::now(),
1725        }
1726    }
1727
1728    /// Returns chat member list timestamp.
1729    pub(crate) async fn member_list_timestamp(&self, context: &Context) -> Result<i64> {
1730        if let Some(member_list_timestamp) = self.param.get_i64(Param::MemberListTimestamp) {
1731            Ok(member_list_timestamp)
1732        } else {
1733            Ok(self.id.created_timestamp(context).await?)
1734        }
1735    }
1736
1737    /// Returns true if member list is stale,
1738    /// i.e. has not been updated for 60 days.
1739    ///
1740    /// This is used primarily to detect the case
1741    /// where the user just restored an old backup.
1742    pub(crate) async fn member_list_is_stale(&self, context: &Context) -> Result<bool> {
1743        let now = time();
1744        let member_list_ts = self.member_list_timestamp(context).await?;
1745        let is_stale = now.saturating_add(TIMESTAMP_SENT_TOLERANCE)
1746            >= member_list_ts.saturating_add(60 * 24 * 3600);
1747        Ok(is_stale)
1748    }
1749
1750    /// Adds missing values to the msg object,
1751    /// writes the record to the database.
1752    ///
1753    /// If `update_msg_id` is set, that record is reused;
1754    /// if `update_msg_id` is None, a new record is created.
1755    #[expect(clippy::arithmetic_side_effects)]
1756    async fn prepare_msg_raw(
1757        &mut self,
1758        context: &Context,
1759        msg: &mut Message,
1760        update_msg_id: Option<MsgId>,
1761    ) -> Result<()> {
1762        let mut to_id = 0;
1763        let mut location_id = 0;
1764
1765        if msg.rfc724_mid.is_empty() {
1766            msg.rfc724_mid = create_outgoing_rfc724_mid();
1767        }
1768
1769        if self.typ == Chattype::Single {
1770            if let Some(id) = context
1771                .sql
1772                .query_get_value(
1773                    "SELECT contact_id FROM chats_contacts WHERE chat_id=?;",
1774                    (self.id,),
1775                )
1776                .await?
1777            {
1778                to_id = id;
1779            } else {
1780                error!(
1781                    context,
1782                    "Cannot send message, contact for {} not found.", self.id,
1783                );
1784                bail!("Cannot set message, contact for {} not found.", self.id);
1785            }
1786        } else if matches!(self.typ, Chattype::Group | Chattype::OutBroadcast)
1787            && self.param.get_int(Param::Unpromoted).unwrap_or_default() == 1
1788        {
1789            msg.param.set_int(Param::AttachChatAvatarAndDescription, 1);
1790            self.param
1791                .remove(Param::Unpromoted)
1792                .set_i64(Param::GroupNameTimestamp, msg.timestamp_sort)
1793                .set_i64(Param::GroupDescriptionTimestamp, msg.timestamp_sort);
1794            self.update_param(context).await?;
1795        }
1796
1797        let is_bot = context.get_config_bool(Config::Bot).await?;
1798        msg.param
1799            .set_optional(Param::Bot, Some("1").filter(|_| is_bot));
1800
1801        // Set "In-Reply-To:" to identify the message to which the composed message is a reply.
1802        // Set "References:" to identify the "thread" of the conversation.
1803        // Both according to [RFC 5322 3.6.4, page 25](https://www.rfc-editor.org/rfc/rfc5322#section-3.6.4).
1804        let new_references;
1805        if self.is_self_talk() {
1806            // As self-talks are mainly used to transfer data between devices,
1807            // we do not set In-Reply-To/References in this case.
1808            new_references = String::new();
1809        } else if let Some((parent_rfc724_mid, parent_in_reply_to, parent_references)) =
1810            // We don't filter `OutPending` and `OutFailed` messages because the new message for
1811            // which `parent_query()` is done may assume that it will be received in a context
1812            // affected by those messages, e.g. they could add new members to a group and the
1813            // new message will contain them in "To:". Anyway recipients must be prepared to
1814            // orphaned references.
1815            self
1816                .id
1817                .get_parent_mime_headers(context, MessageState::OutPending)
1818                .await?
1819        {
1820            // "In-Reply-To:" is not changed if it is set manually.
1821            // This does not affect "References:" header, it will contain "default parent" (the
1822            // latest message in the thread) anyway.
1823            if msg.in_reply_to.is_none() && !parent_rfc724_mid.is_empty() {
1824                msg.in_reply_to = Some(parent_rfc724_mid.clone());
1825            }
1826
1827            // Use parent `In-Reply-To` as a fallback
1828            // in case parent message has no `References` header
1829            // as specified in RFC 5322:
1830            // > If the parent message does not contain
1831            // > a "References:" field but does have an "In-Reply-To:" field
1832            // > containing a single message identifier, then the "References:" field
1833            // > will contain the contents of the parent's "In-Reply-To:" field
1834            // > followed by the contents of the parent's "Message-ID:" field (if
1835            // > any).
1836            let parent_references = if parent_references.is_empty() {
1837                parent_in_reply_to
1838            } else {
1839                parent_references
1840            };
1841
1842            // The whole list of messages referenced may be huge.
1843            // Only take 2 recent references and add third from `In-Reply-To`.
1844            let mut references_vec: Vec<&str> = parent_references.rsplit(' ').take(2).collect();
1845            references_vec.reverse();
1846
1847            if !parent_rfc724_mid.is_empty()
1848                && !references_vec.contains(&parent_rfc724_mid.as_str())
1849            {
1850                references_vec.push(&parent_rfc724_mid)
1851            }
1852
1853            if references_vec.is_empty() {
1854                // As a fallback, use our Message-ID,
1855                // same as in the case of top-level message.
1856                new_references = msg.rfc724_mid.clone();
1857            } else {
1858                new_references = references_vec.join(" ");
1859            }
1860        } else {
1861            // This is a top-level message.
1862            // Add our Message-ID as first references.
1863            // This allows us to identify replies to our message even if
1864            // email server such as Outlook changes `Message-ID:` header.
1865            // MUAs usually keep the first Message-ID in `References:` header unchanged.
1866            new_references = msg.rfc724_mid.clone();
1867        }
1868
1869        // add independent location to database
1870        if msg.param.exists(Param::SetLatitude)
1871            && let Ok(row_id) = context
1872                .sql
1873                .insert(
1874                    "INSERT INTO locations \
1875                     (timestamp,from_id,chat_id, latitude,longitude,independent)\
1876                     VALUES (?,?,?, ?,?,1);",
1877                    (
1878                        msg.timestamp_sort,
1879                        ContactId::SELF,
1880                        self.id,
1881                        msg.param.get_float(Param::SetLatitude).unwrap_or_default(),
1882                        msg.param.get_float(Param::SetLongitude).unwrap_or_default(),
1883                    ),
1884                )
1885                .await
1886        {
1887            location_id = row_id;
1888        }
1889
1890        let ephemeral_timer = if msg.param.get_cmd() == SystemMessage::EphemeralTimerChanged {
1891            EphemeralTimer::Disabled
1892        } else {
1893            self.id.get_ephemeral_timer(context).await?
1894        };
1895        let ephemeral_timestamp = match ephemeral_timer {
1896            EphemeralTimer::Disabled => 0,
1897            EphemeralTimer::Enabled { duration } => time().saturating_add(duration.into()),
1898        };
1899
1900        let (msg_text, was_truncated) = truncate_msg_text(context, msg.text.clone()).await?;
1901        let new_mime_headers = if msg.has_html() {
1902            msg.param.get(Param::SendHtml).map(|s| s.to_string())
1903        } else {
1904            None
1905        };
1906        let new_mime_headers: Option<String> = new_mime_headers.map(|s| {
1907            let html_part = MimePart::new("text/html", s);
1908            let mut buffer = Vec::new();
1909            let cursor = Cursor::new(&mut buffer);
1910            html_part.write_part(cursor).ok();
1911            String::from_utf8_lossy(&buffer).to_string()
1912        });
1913        let new_mime_headers = new_mime_headers.or_else(|| match was_truncated {
1914            // We need to add some headers so that they are stripped before formatting HTML by
1915            // `MsgId::get_html()`, not a part of the actual text. Let's add "Content-Type", it's
1916            // anyway a useful metadata about the stored text.
1917            true => Some("Content-Type: text/plain; charset=utf-8\r\n\r\n".to_string() + &msg.text),
1918            false => None,
1919        });
1920        let new_mime_headers = match new_mime_headers {
1921            Some(h) => Some(tokio::task::block_in_place(move || {
1922                buf_compress(h.as_bytes())
1923            })?),
1924            None => None,
1925        };
1926
1927        msg.chat_id = self.id;
1928        msg.from_id = ContactId::SELF;
1929
1930        // add message to the database
1931        if let Some(update_msg_id) = update_msg_id {
1932            context
1933                .sql
1934                .execute(
1935                    "UPDATE msgs
1936                     SET rfc724_mid=?, chat_id=?, from_id=?, to_id=?, timestamp=?, type=?,
1937                         state=?, txt=?, txt_normalized=?, subject=?, param=?,
1938                         hidden=?, mime_in_reply_to=?, mime_references=?, mime_modified=?,
1939                         mime_headers=?, mime_compressed=1, location_id=?, ephemeral_timer=?,
1940                         ephemeral_timestamp=?
1941                     WHERE id=?;",
1942                    params_slice![
1943                        msg.rfc724_mid,
1944                        msg.chat_id,
1945                        msg.from_id,
1946                        to_id,
1947                        msg.timestamp_sort,
1948                        msg.viewtype,
1949                        msg.state,
1950                        msg_text,
1951                        normalize_text(&msg_text),
1952                        &msg.subject,
1953                        msg.param.to_string(),
1954                        msg.hidden,
1955                        msg.in_reply_to.as_deref().unwrap_or_default(),
1956                        new_references,
1957                        new_mime_headers.is_some(),
1958                        new_mime_headers.unwrap_or_default(),
1959                        location_id as i32,
1960                        ephemeral_timer,
1961                        ephemeral_timestamp,
1962                        update_msg_id
1963                    ],
1964                )
1965                .await?;
1966            msg.id = update_msg_id;
1967        } else {
1968            let raw_id = context
1969                .sql
1970                .insert(
1971                    "INSERT INTO msgs (
1972                        rfc724_mid,
1973                        chat_id,
1974                        from_id,
1975                        to_id,
1976                        timestamp,
1977                        type,
1978                        state,
1979                        txt,
1980                        txt_normalized,
1981                        subject,
1982                        param,
1983                        hidden,
1984                        mime_in_reply_to,
1985                        mime_references,
1986                        mime_modified,
1987                        mime_headers,
1988                        mime_compressed,
1989                        location_id,
1990                        ephemeral_timer,
1991                        ephemeral_timestamp)
1992                        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?,?);",
1993                    params_slice![
1994                        msg.rfc724_mid,
1995                        msg.chat_id,
1996                        msg.from_id,
1997                        to_id,
1998                        msg.timestamp_sort,
1999                        msg.viewtype,
2000                        msg.state,
2001                        msg_text,
2002                        normalize_text(&msg_text),
2003                        &msg.subject,
2004                        msg.param.to_string(),
2005                        msg.hidden,
2006                        msg.in_reply_to.as_deref().unwrap_or_default(),
2007                        new_references,
2008                        new_mime_headers.is_some(),
2009                        new_mime_headers.unwrap_or_default(),
2010                        location_id as i32,
2011                        ephemeral_timer,
2012                        ephemeral_timestamp
2013                    ],
2014                )
2015                .await?;
2016            context.new_msgs_notify.notify_one();
2017            msg.id = MsgId::new(u32::try_from(raw_id)?);
2018
2019            maybe_set_logging_xdc(context, msg, self.id).await?;
2020            context
2021                .update_webxdc_integration_database(msg, context)
2022                .await?;
2023        }
2024        context.scheduler.interrupt_ephemeral_task().await;
2025        Ok(())
2026    }
2027
2028    /// Sends a `SyncAction` synchronising chat contacts to other devices.
2029    pub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> {
2030        if self.is_encrypted(context).await? {
2031            let self_fp = self_fingerprint(context).await?;
2032            let fingerprint_addrs = context
2033                .sql
2034                .query_map_vec(
2035                    "SELECT c.id, c.fingerprint, c.addr
2036                     FROM contacts c INNER JOIN chats_contacts cc
2037                     ON c.id=cc.contact_id
2038                     WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2039                    (self.id,),
2040                    |row| {
2041                        if row.get::<_, ContactId>(0)? == ContactId::SELF {
2042                            return Ok((self_fp.to_string(), String::new()));
2043                        }
2044                        let fingerprint = row.get(1)?;
2045                        let addr = row.get(2)?;
2046                        Ok((fingerprint, addr))
2047                    },
2048                )
2049                .await?;
2050            self.sync(context, SyncAction::SetPgpContacts(fingerprint_addrs))
2051                .await?;
2052        } else {
2053            let addrs = context
2054                .sql
2055                .query_map_vec(
2056                    "SELECT c.addr \
2057                    FROM contacts c INNER JOIN chats_contacts cc \
2058                    ON c.id=cc.contact_id \
2059                    WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp",
2060                    (self.id,),
2061                    |row| {
2062                        let addr: String = row.get(0)?;
2063                        Ok(addr)
2064                    },
2065                )
2066                .await?;
2067            self.sync(context, SyncAction::SetContacts(addrs)).await?;
2068        }
2069        Ok(())
2070    }
2071
2072    /// Returns chat id for the purpose of synchronisation across devices.
2073    async fn get_sync_id(&self, context: &Context) -> Result<Option<SyncId>> {
2074        match self.typ {
2075            Chattype::Single => {
2076                if self.is_device_talk() {
2077                    return Ok(Some(SyncId::Device));
2078                }
2079
2080                let mut r = None;
2081                for contact_id in get_chat_contacts(context, self.id).await? {
2082                    if contact_id == ContactId::SELF && !self.is_self_talk() {
2083                        continue;
2084                    }
2085                    if r.is_some() {
2086                        return Ok(None);
2087                    }
2088                    let contact = Contact::get_by_id(context, contact_id).await?;
2089                    if let Some(fingerprint) = contact.fingerprint() {
2090                        r = Some(SyncId::ContactFingerprint(fingerprint.hex()));
2091                    } else {
2092                        r = Some(SyncId::ContactAddr(contact.get_addr().to_string()));
2093                    }
2094                }
2095                Ok(r)
2096            }
2097            Chattype::OutBroadcast
2098            | Chattype::InBroadcast
2099            | Chattype::Group
2100            | Chattype::Mailinglist => {
2101                if !self.grpid.is_empty() {
2102                    return Ok(Some(SyncId::Grpid(self.grpid.clone())));
2103                }
2104
2105                let Some((parent_rfc724_mid, parent_in_reply_to, _)) = self
2106                    .id
2107                    .get_parent_mime_headers(context, MessageState::OutDelivered)
2108                    .await?
2109                else {
2110                    warn!(
2111                        context,
2112                        "Chat::get_sync_id({}): No good message identifying the chat found.",
2113                        self.id
2114                    );
2115                    return Ok(None);
2116                };
2117                Ok(Some(SyncId::Msgids(vec![
2118                    parent_in_reply_to,
2119                    parent_rfc724_mid,
2120                ])))
2121            }
2122        }
2123    }
2124
2125    /// Synchronises a chat action to other devices.
2126    pub(crate) async fn sync(&self, context: &Context, action: SyncAction) -> Result<()> {
2127        if let Some(id) = self.get_sync_id(context).await? {
2128            sync(context, id, action).await?;
2129        }
2130        Ok(())
2131    }
2132}
2133
2134pub(crate) async fn sync(context: &Context, id: SyncId, action: SyncAction) -> Result<()> {
2135    context
2136        .add_sync_item(SyncData::AlterChat { id, action })
2137        .await?;
2138    context.scheduler.interrupt_smtp().await;
2139    Ok(())
2140}
2141
2142/// Whether the chat is pinned or archived.
2143#[derive(Debug, Copy, Eq, PartialEq, Clone, Serialize, Deserialize, EnumIter, Default)]
2144#[repr(i8)]
2145pub enum ChatVisibility {
2146    /// Chat is neither archived nor pinned.
2147    #[default]
2148    Normal = 0,
2149
2150    /// Chat is archived.
2151    Archived = 1,
2152
2153    /// Chat is pinned to the top of the chatlist.
2154    Pinned = 2,
2155}
2156
2157impl rusqlite::types::ToSql for ChatVisibility {
2158    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
2159        let val = rusqlite::types::Value::Integer(*self as i64);
2160        let out = rusqlite::types::ToSqlOutput::Owned(val);
2161        Ok(out)
2162    }
2163}
2164
2165impl rusqlite::types::FromSql for ChatVisibility {
2166    fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
2167        i64::column_result(value).map(|val| {
2168            match val {
2169                2 => ChatVisibility::Pinned,
2170                1 => ChatVisibility::Archived,
2171                0 => ChatVisibility::Normal,
2172                // fallback to Normal for unknown values, may happen eg. on imports created by a newer version.
2173                _ => ChatVisibility::Normal,
2174            }
2175        })
2176    }
2177}
2178
2179/// The current state of a chat.
2180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2181#[non_exhaustive]
2182pub struct ChatInfo {
2183    /// The chat ID.
2184    pub id: ChatId,
2185
2186    /// The type of chat as a `u32` representation of [Chattype].
2187    ///
2188    /// On the C API this number is one of the
2189    /// `DC_CHAT_TYPE_UNDEFINED`, `DC_CHAT_TYPE_SINGLE`,
2190    /// or `DC_CHAT_TYPE_GROUP`
2191    /// constants.
2192    #[serde(rename = "type")]
2193    pub type_: u32,
2194
2195    /// The name of the chat.
2196    pub name: String,
2197
2198    /// Whether the chat is archived.
2199    pub archived: bool,
2200
2201    /// The "params" of the chat.
2202    ///
2203    /// This is the string-serialised version of `Params` currently.
2204    pub param: String,
2205
2206    /// Whether this chat is currently sending location-stream messages.
2207    pub is_sending_locations: bool,
2208
2209    /// Colour this chat should be represented in by the UI.
2210    ///
2211    /// Yes, spelling colour is hard.
2212    pub color: u32,
2213
2214    /// The path to the profile image.
2215    ///
2216    /// If there is no profile image set this will be an empty string
2217    /// currently.
2218    pub profile_image: std::path::PathBuf,
2219
2220    /// The draft message text.
2221    ///
2222    /// If the chat has not draft this is an empty string.
2223    ///
2224    /// TODO: This doesn't seem rich enough, it can not handle drafts
2225    ///       which contain non-text parts.  Perhaps it should be a
2226    ///       simple `has_draft` bool instead.
2227    pub draft: String,
2228
2229    /// Whether the chat is muted
2230    ///
2231    /// The exact time its muted can be found out via the `chat.mute_duration` property
2232    pub is_muted: bool,
2233
2234    /// Ephemeral message timer.
2235    pub ephemeral_timer: EphemeralTimer,
2236    // ToDo:
2237    // - [ ] summary,
2238    // - [ ] lastUpdated,
2239    // - [ ] freshMessageCounter,
2240    // - [ ] email
2241}
2242
2243async fn get_asset_icon(context: &Context, name: &str, bytes: &[u8]) -> Result<PathBuf> {
2244    ensure!(name.starts_with("icon-"));
2245    if let Some(icon) = context.sql.get_raw_config(name).await? {
2246        return Ok(get_abs_path(context, Path::new(&icon)));
2247    }
2248
2249    let blob =
2250        BlobObject::create_and_deduplicate_from_bytes(context, bytes, &format!("{name}.png"))?;
2251    let icon = blob.as_name().to_string();
2252    context.sql.set_raw_config(name, Some(&icon)).await?;
2253
2254    Ok(get_abs_path(context, Path::new(&icon)))
2255}
2256
2257pub(crate) async fn get_saved_messages_icon(context: &Context) -> Result<PathBuf> {
2258    get_asset_icon(
2259        context,
2260        "icon-saved-messages",
2261        include_bytes!("../assets/icon-saved-messages.png"),
2262    )
2263    .await
2264}
2265
2266pub(crate) async fn get_device_icon(context: &Context) -> Result<PathBuf> {
2267    get_asset_icon(
2268        context,
2269        "icon-device",
2270        include_bytes!("../assets/icon-device.png"),
2271    )
2272    .await
2273}
2274
2275pub(crate) async fn get_archive_icon(context: &Context) -> Result<PathBuf> {
2276    get_asset_icon(
2277        context,
2278        "icon-archive",
2279        include_bytes!("../assets/icon-archive.png"),
2280    )
2281    .await
2282}
2283
2284/// Returns path to the icon
2285/// indicating unencrypted chats and address-contacts.
2286pub(crate) async fn get_unencrypted_icon(context: &Context) -> Result<PathBuf> {
2287    get_asset_icon(
2288        context,
2289        "icon-unencrypted",
2290        include_bytes!("../assets/icon-unencrypted.png"),
2291    )
2292    .await
2293}
2294
2295async fn update_special_chat_name(
2296    context: &Context,
2297    contact_id: ContactId,
2298    name: String,
2299) -> Result<()> {
2300    if let Some(ChatIdBlocked { id: chat_id, .. }) =
2301        ChatIdBlocked::lookup_by_contact(context, contact_id).await?
2302    {
2303        // the `!= name` condition avoids unneeded writes
2304        context
2305            .sql
2306            .execute(
2307                "UPDATE chats SET name=?, name_normalized=? WHERE id=? AND name!=?",
2308                (&name, normalize_text(&name), chat_id, &name),
2309            )
2310            .await?;
2311    }
2312    Ok(())
2313}
2314
2315pub(crate) async fn update_special_chat_names(context: &Context) -> Result<()> {
2316    update_special_chat_name(
2317        context,
2318        ContactId::DEVICE,
2319        stock_str::device_messages(context),
2320    )
2321    .await?;
2322    update_special_chat_name(context, ContactId::SELF, stock_str::saved_messages(context)).await?;
2323    Ok(())
2324}
2325
2326/// Handle a [`ChatId`] and its [`Blocked`] status at once.
2327///
2328/// This struct is an optimisation to read a [`ChatId`] and its [`Blocked`] status at once
2329/// from the database.  It [`Deref`]s to [`ChatId`] so it can be used as an extension to
2330/// [`ChatId`].
2331///
2332/// [`Deref`]: std::ops::Deref
2333#[derive(Debug)]
2334pub(crate) struct ChatIdBlocked {
2335    /// Chat ID.
2336    pub id: ChatId,
2337
2338    /// Whether the chat is blocked, unblocked or a contact request.
2339    pub blocked: Blocked,
2340}
2341
2342impl ChatIdBlocked {
2343    /// Searches the database for the 1:1 chat with this contact.
2344    ///
2345    /// If no chat is found `None` is returned.
2346    pub async fn lookup_by_contact(
2347        context: &Context,
2348        contact_id: ContactId,
2349    ) -> Result<Option<Self>> {
2350        ensure!(context.sql.is_open().await, "Database not available");
2351        ensure!(
2352            contact_id != ContactId::UNDEFINED,
2353            "Invalid contact id requested"
2354        );
2355
2356        context
2357            .sql
2358            .query_row_optional(
2359                "SELECT c.id, c.blocked
2360                   FROM chats c
2361                  INNER JOIN chats_contacts j
2362                          ON c.id=j.chat_id
2363                  WHERE c.type=100  -- 100 = Chattype::Single
2364                    AND c.id>9      -- 9 = DC_CHAT_ID_LAST_SPECIAL
2365                    AND j.contact_id=?;",
2366                (contact_id,),
2367                |row| {
2368                    let id: ChatId = row.get(0)?;
2369                    let blocked: Blocked = row.get(1)?;
2370                    Ok(ChatIdBlocked { id, blocked })
2371                },
2372            )
2373            .await
2374    }
2375
2376    /// Returns the chat for the 1:1 chat with this contact.
2377    ///
2378    /// If the chat does not yet exist a new one is created, using the provided [`Blocked`]
2379    /// state.
2380    pub async fn get_for_contact(
2381        context: &Context,
2382        contact_id: ContactId,
2383        create_blocked: Blocked,
2384    ) -> Result<Self> {
2385        ensure!(context.sql.is_open().await, "Database not available");
2386        ensure!(
2387            contact_id != ContactId::UNDEFINED,
2388            "Invalid contact id requested"
2389        );
2390
2391        if let Some(res) = Self::lookup_by_contact(context, contact_id).await? {
2392            // Already exists, no need to create.
2393            return Ok(res);
2394        }
2395
2396        let contact = Contact::get_by_id(context, contact_id).await?;
2397        let chat_name = contact.get_display_name().to_string();
2398        let mut params = Params::new();
2399        match contact_id {
2400            ContactId::SELF => {
2401                params.set_int(Param::Selftalk, 1);
2402            }
2403            ContactId::DEVICE => {
2404                params.set_int(Param::Devicetalk, 1);
2405            }
2406            _ => (),
2407        }
2408
2409        let smeared_time = create_smeared_timestamp(context);
2410
2411        let chat_id = context
2412            .sql
2413            .transaction(move |transaction| {
2414                transaction.execute(
2415                    "INSERT INTO chats
2416                     (type, name, name_normalized, param, blocked, created_timestamp)
2417                     VALUES(?, ?, ?, ?, ?, ?)",
2418                    (
2419                        Chattype::Single,
2420                        &chat_name,
2421                        normalize_text(&chat_name),
2422                        params.to_string(),
2423                        create_blocked as u8,
2424                        smeared_time,
2425                    ),
2426                )?;
2427                let chat_id = ChatId::new(
2428                    transaction
2429                        .last_insert_rowid()
2430                        .try_into()
2431                        .context("chat table rowid overflows u32")?,
2432                );
2433
2434                transaction.execute(
2435                    "INSERT INTO chats_contacts
2436                 (chat_id, contact_id)
2437                 VALUES((SELECT last_insert_rowid()), ?)",
2438                    (contact_id,),
2439                )?;
2440
2441                Ok(chat_id)
2442            })
2443            .await?;
2444
2445        let chat = Chat::load_from_db(context, chat_id).await?;
2446        if chat.is_encrypted(context).await?
2447            && !chat.param.exists(Param::Devicetalk)
2448            && !chat.param.exists(Param::Selftalk)
2449        {
2450            chat_id.add_e2ee_notice(context, smeared_time).await?;
2451        }
2452
2453        Ok(Self {
2454            id: chat_id,
2455            blocked: create_blocked,
2456        })
2457    }
2458}
2459
2460async fn prepare_msg_blob(context: &Context, msg: &mut Message) -> Result<()> {
2461    if msg.viewtype == Viewtype::Text || msg.viewtype == Viewtype::Call {
2462        // the caller should check if the message text is empty
2463    } else if msg.viewtype.has_file() {
2464        let viewtype_orig = msg.viewtype;
2465        let mut blob = msg
2466            .param
2467            .get_file_blob(context)?
2468            .with_context(|| format!("attachment missing for message of type #{}", msg.viewtype))?;
2469        let mut maybe_image = false;
2470
2471        if msg.viewtype == Viewtype::File
2472            || msg.viewtype == Viewtype::Image
2473            || msg.viewtype == Viewtype::Sticker && !msg.param.exists(Param::ForceSticker)
2474        {
2475            // Correct the type, take care not to correct already very special
2476            // formats as GIF or VOICE.
2477            //
2478            // Typical conversions:
2479            // - from FILE to AUDIO/VIDEO/IMAGE
2480            // - from FILE/IMAGE to GIF */
2481            if let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg) {
2482                if msg.viewtype == Viewtype::Sticker {
2483                    if better_type != Viewtype::Image {
2484                        // UIs don't want conversions of `Sticker` to anything other than `Image`.
2485                        msg.param.set_int(Param::ForceSticker, 1);
2486                    }
2487                } else if better_type == Viewtype::Image {
2488                    maybe_image = true;
2489                } else if better_type != Viewtype::Webxdc
2490                    || context
2491                        .ensure_sendable_webxdc_file(&blob.to_abs_path())
2492                        .await
2493                        .is_ok()
2494                {
2495                    msg.viewtype = better_type;
2496                }
2497            }
2498        } else if msg.viewtype == Viewtype::Webxdc {
2499            context
2500                .ensure_sendable_webxdc_file(&blob.to_abs_path())
2501                .await?;
2502        }
2503
2504        if msg.viewtype == Viewtype::Vcard {
2505            msg.try_set_vcard(context, &blob.to_abs_path()).await?;
2506        }
2507        if msg.viewtype == Viewtype::File && maybe_image
2508            || msg.viewtype == Viewtype::Image
2509            || msg.viewtype == Viewtype::Sticker && !msg.param.exists(Param::ForceSticker)
2510        {
2511            let new_name = blob
2512                .check_or_recode_image(context, msg.get_filename(), &mut msg.viewtype)
2513                .await?;
2514            msg.param.set(Param::Filename, new_name);
2515            msg.param.set(Param::File, blob.as_name());
2516        }
2517
2518        if !msg.param.exists(Param::MimeType)
2519            && let Some((viewtype, mime)) = message::guess_msgtype_from_suffix(msg)
2520        {
2521            // If we unexpectedly didn't recognize the file as image, don't send it as such,
2522            // either the format is unsupported or the image is corrupted.
2523            let mime = match viewtype != Viewtype::Image
2524                || matches!(msg.viewtype, Viewtype::Image | Viewtype::Sticker)
2525            {
2526                true => mime,
2527                false => "application/octet-stream",
2528            };
2529            msg.param.set(Param::MimeType, mime);
2530        }
2531
2532        msg.try_calc_and_set_dimensions(context).await?;
2533
2534        let filename = msg.get_filename().context("msg has no file")?;
2535        let suffix = Path::new(&filename)
2536            .extension()
2537            .and_then(|e| e.to_str())
2538            .unwrap_or("dat");
2539        // Get file name to use for sending. For privacy purposes, we do not transfer the original
2540        // filenames e.g. for images; these names are normally not needed and contain timestamps,
2541        // running numbers, etc.
2542        let filename: String = match viewtype_orig {
2543            Viewtype::Voice => format!(
2544                "voice-messsage_{}.{}",
2545                chrono::Utc
2546                    .timestamp_opt(msg.timestamp_sort, 0)
2547                    .single()
2548                    .map_or_else(
2549                        || "YY-mm-dd_hh:mm:ss".to_string(),
2550                        |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2551                    ),
2552                &suffix
2553            ),
2554            Viewtype::Image | Viewtype::Gif => format!(
2555                "image_{}.{}",
2556                chrono::Utc
2557                    .timestamp_opt(msg.timestamp_sort, 0)
2558                    .single()
2559                    .map_or_else(
2560                        || "YY-mm-dd_hh:mm:ss".to_string(),
2561                        |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string(),
2562                    ),
2563                &suffix,
2564            ),
2565            Viewtype::Video => format!(
2566                "video_{}.{}",
2567                chrono::Utc
2568                    .timestamp_opt(msg.timestamp_sort, 0)
2569                    .single()
2570                    .map_or_else(
2571                        || "YY-mm-dd_hh:mm:ss".to_string(),
2572                        |ts| ts.format("%Y-%m-%d_%H-%M-%S").to_string()
2573                    ),
2574                &suffix
2575            ),
2576            _ => filename,
2577        };
2578        msg.param.set(Param::Filename, filename);
2579
2580        info!(
2581            context,
2582            "Attaching \"{}\" for message type #{}.",
2583            blob.to_abs_path().display(),
2584            msg.viewtype
2585        );
2586    } else {
2587        bail!("Cannot send messages of type #{}.", msg.viewtype);
2588    }
2589    Ok(())
2590}
2591
2592/// Returns whether a contact is in a chat or not.
2593pub async fn is_contact_in_chat(
2594    context: &Context,
2595    chat_id: ChatId,
2596    contact_id: ContactId,
2597) -> Result<bool> {
2598    // this function works for group and for normal chats, however, it is more useful
2599    // for group chats.
2600    // ContactId::SELF may be used to check whether oneself
2601    // is in a group or incoming broadcast chat
2602    // (ContactId::SELF is not added to 1:1 chats or outgoing broadcast channels)
2603
2604    let exists = context
2605        .sql
2606        .exists(
2607            "SELECT COUNT(*) FROM chats_contacts
2608             WHERE chat_id=? AND contact_id=?
2609             AND add_timestamp >= remove_timestamp",
2610            (chat_id, contact_id),
2611        )
2612        .await?;
2613    Ok(exists)
2614}
2615
2616/// Sends a message object to a chat.
2617///
2618/// Sends the event #DC_EVENT_MSGS_CHANGED on success.
2619/// However, this does not imply, the message really reached the recipient -
2620/// sending may be delayed eg. due to network problems. However, from your
2621/// view, you're done with the message. Sooner or later it will find its way.
2622pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2623    ensure!(
2624        !chat_id.is_special(),
2625        "chat_id cannot be a special chat: {chat_id}"
2626    );
2627
2628    if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {
2629        msg.param.remove(Param::GuaranteeE2ee);
2630        msg.param.remove(Param::ForcePlaintext);
2631        // create_send_msg_jobs() will update `param` in the db.
2632    }
2633
2634    // protect all system messages against RTLO attacks
2635    if msg.is_system_message() {
2636        msg.text = sanitize_bidi_characters(&msg.text);
2637    }
2638
2639    if !prepare_send_msg(context, chat_id, msg).await?.is_empty() {
2640        if !msg.hidden {
2641            context.emit_msgs_changed(msg.chat_id, msg.id);
2642        }
2643
2644        if msg.param.exists(Param::SetLatitude) {
2645            context.emit_location_changed(Some(ContactId::SELF)).await?;
2646        }
2647
2648        context.scheduler.interrupt_smtp().await;
2649    }
2650
2651    Ok(msg.id)
2652}
2653
2654/// Tries to send a message synchronously.
2655///
2656/// Creates jobs in the `smtp` table, then drectly opens an SMTP connection and sends the
2657/// message. If this fails, the jobs remain in the database for later sending.
2658pub async fn send_msg_sync(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> {
2659    let rowids = prepare_send_msg(context, chat_id, msg).await?;
2660    if rowids.is_empty() {
2661        return Ok(msg.id);
2662    }
2663    let mut smtp = crate::smtp::Smtp::new();
2664    for rowid in rowids {
2665        send_msg_to_smtp(context, &mut smtp, rowid)
2666            .await
2667            .context("failed to send message, queued for later sending")?;
2668    }
2669    context.emit_msgs_changed(msg.chat_id, msg.id);
2670    Ok(msg.id)
2671}
2672
2673/// Prepares a message to be sent out.
2674///
2675/// Returns row ids of the `smtp` table.
2676async fn prepare_send_msg(
2677    context: &Context,
2678    chat_id: ChatId,
2679    msg: &mut Message,
2680) -> Result<Vec<i64>> {
2681    let mut chat = Chat::load_from_db(context, chat_id).await?;
2682
2683    let skip_fn = |reason: &CantSendReason| match reason {
2684        CantSendReason::ContactRequest => {
2685            // Allow securejoin messages, they are supposed to repair the verification.
2686            // If the chat is a contact request, let the user accept it later.
2687            msg.param.get_cmd() == SystemMessage::SecurejoinMessage
2688        }
2689        // Allow to send "Member removed" messages so we can leave the group/broadcast.
2690        // Necessary checks should be made anyway before removing contact
2691        // from the chat.
2692        CantSendReason::NotAMember => msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup,
2693        CantSendReason::InBroadcast => {
2694            matches!(
2695                msg.param.get_cmd(),
2696                SystemMessage::MemberRemovedFromGroup | SystemMessage::SecurejoinMessage
2697            )
2698        }
2699        CantSendReason::MissingKey => msg
2700            .param
2701            .get_bool(Param::ForcePlaintext)
2702            .unwrap_or_default(),
2703        _ => false,
2704    };
2705    if let Some(reason) = chat.why_cant_send_ex(context, &skip_fn).await? {
2706        bail!("Cannot send to {chat_id}: {reason}");
2707    }
2708
2709    // Check a quote reply is not leaking data from other chats.
2710    // This is meant as a last line of defence, the UI should check that before as well.
2711    // (We allow Chattype::Single in general for "Reply Privately";
2712    // checking for exact contact_id will produce false positives when ppl just left the group)
2713    if chat.typ != Chattype::Single
2714        && !context.get_config_bool(Config::Bot).await?
2715        && let Some(quoted_message) = msg.quoted_message(context).await?
2716        && quoted_message.chat_id != chat_id
2717    {
2718        bail!(
2719            "Quote of message from {} cannot be sent to {chat_id}",
2720            quoted_message.chat_id
2721        );
2722    }
2723
2724    // check current MessageState for drafts (to keep msg_id) ...
2725    let update_msg_id = if msg.state == MessageState::OutDraft {
2726        msg.hidden = false;
2727        if !msg.id.is_special() && msg.chat_id == chat_id {
2728            Some(msg.id)
2729        } else {
2730            None
2731        }
2732    } else {
2733        None
2734    };
2735
2736    if matches!(
2737        msg.state,
2738        MessageState::Undefined | MessageState::OutPreparing
2739    )
2740        // Legacy SecureJoin "v*-request" messages are unencrypted.
2741        && msg.param.get_cmd() != SystemMessage::SecurejoinMessage
2742        && chat.is_encrypted(context).await?
2743    {
2744        msg.param.set_int(Param::GuaranteeE2ee, 1);
2745        if !msg.id.is_unset() {
2746            msg.update_param(context).await?;
2747        }
2748    }
2749    msg.state = MessageState::OutPending;
2750
2751    msg.timestamp_sort = create_smeared_timestamp(context);
2752    prepare_msg_blob(context, msg).await?;
2753    if !msg.hidden {
2754        chat_id.unarchive_if_not_muted(context, msg.state).await?;
2755    }
2756    chat.prepare_msg_raw(context, msg, update_msg_id).await?;
2757
2758    let row_ids = create_send_msg_jobs(context, msg)
2759        .await
2760        .context("Failed to create send jobs")?;
2761    if !row_ids.is_empty() {
2762        donation_request_maybe(context).await.log_err(context).ok();
2763    }
2764    Ok(row_ids)
2765}
2766
2767/// Renders the Message or splits it into Pre- and Post-Message.
2768///
2769/// Pre-Message is a small message with metadata which announces a larger Post-Message.
2770/// Post-Messages are not downloaded in the background.
2771///
2772/// If pre-message is not nessesary, this returns `None` as the 0th value.
2773async fn render_mime_message_and_pre_message(
2774    context: &Context,
2775    msg: &mut Message,
2776    mimefactory: MimeFactory,
2777) -> Result<(Option<RenderedEmail>, RenderedEmail)> {
2778    let needs_pre_message = msg.viewtype.has_file()
2779        && mimefactory.will_be_encrypted() // unencrypted is likely email, we don't want to spam by sending multiple messages
2780        && msg
2781            .get_filebytes(context)
2782            .await?
2783            .context("filebytes not available, even though message has attachment")?
2784            > PRE_MSG_ATTACHMENT_SIZE_THRESHOLD;
2785
2786    if needs_pre_message {
2787        info!(
2788            context,
2789            "Message {} is large and will be split into pre- and post-messages.", msg.id,
2790        );
2791
2792        let mut mimefactory_post_msg = mimefactory.clone();
2793        mimefactory_post_msg.set_as_post_message();
2794        let rendered_msg = Box::pin(mimefactory_post_msg.render(context))
2795            .await
2796            .context("Failed to render post-message")?;
2797
2798        let mut mimefactory_pre_msg = mimefactory;
2799        mimefactory_pre_msg.set_as_pre_message_for(&rendered_msg);
2800        let rendered_pre_msg = Box::pin(mimefactory_pre_msg.render(context))
2801            .await
2802            .context("pre-message failed to render")?;
2803
2804        if rendered_pre_msg.message.len() > PRE_MSG_SIZE_WARNING_THRESHOLD {
2805            warn!(
2806                context,
2807                "Pre-message for message {} is larger than expected: {}.",
2808                msg.id,
2809                rendered_pre_msg.message.len()
2810            );
2811        }
2812
2813        Ok((Some(rendered_pre_msg), rendered_msg))
2814    } else {
2815        Ok((None, Box::pin(mimefactory.render(context)).await?))
2816    }
2817}
2818
2819/// Constructs jobs for sending a message and inserts them into the `smtp` table.
2820///
2821/// Updates the message `GuaranteeE2ee` parameter and persists it
2822/// in the database depending on whether the message
2823/// is added to the outgoing queue as encrypted or not.
2824///
2825/// Returns row ids if `smtp` table jobs were created or an empty `Vec` otherwise.
2826///
2827/// The caller has to interrupt SMTP loop or otherwise process new rows.
2828pub(crate) async fn create_send_msg_jobs(context: &Context, msg: &mut Message) -> Result<Vec<i64>> {
2829    let cmd = msg.param.get_cmd();
2830    if cmd == SystemMessage::GroupNameChanged || cmd == SystemMessage::GroupDescriptionChanged {
2831        msg.chat_id
2832            .update_timestamp(
2833                context,
2834                if cmd == SystemMessage::GroupNameChanged {
2835                    Param::GroupNameTimestamp
2836                } else {
2837                    Param::GroupDescriptionTimestamp
2838                },
2839                msg.timestamp_sort,
2840            )
2841            .await?;
2842    }
2843
2844    let needs_encryption = msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default();
2845    let mimefactory = match MimeFactory::from_msg(context, msg.clone()).await {
2846        Ok(mf) => mf,
2847        Err(err) => {
2848            // Mark message as failed
2849            message::set_msg_failed(context, msg, &err.to_string())
2850                .await
2851                .ok();
2852            return Err(err);
2853        }
2854    };
2855    let attach_selfavatar = mimefactory.attach_selfavatar;
2856    let mut recipients = mimefactory.recipients();
2857
2858    let from = context.get_primary_self_addr().await?;
2859    let lowercase_from = from.to_lowercase();
2860
2861    recipients.retain(|x| x.to_lowercase() != lowercase_from);
2862
2863    // Default Webxdc integrations are hidden messages and must not be sent out:
2864    if (msg.param.get_int(Param::WebxdcIntegration).is_some() && msg.hidden)
2865        // This may happen eg. for groups with only SELF and bcc_self disabled:
2866        || (!context.get_config_bool(Config::BccSelf).await? && recipients.is_empty())
2867    {
2868        info!(
2869            context,
2870            "Message {} has no recipient, skipping smtp-send.", msg.id
2871        );
2872        msg.param.set_int(Param::GuaranteeE2ee, 1);
2873        msg.update_param(context).await?;
2874        msg.id.set_delivered(context).await?;
2875        msg.state = MessageState::OutDelivered;
2876        return Ok(Vec::new());
2877    }
2878
2879    let (rendered_pre_msg, rendered_msg) =
2880        match render_mime_message_and_pre_message(context, msg, mimefactory).await {
2881            Ok(res) => Ok(res),
2882            Err(err) => {
2883                message::set_msg_failed(context, msg, &err.to_string()).await?;
2884                Err(err)
2885            }
2886        }?;
2887
2888    if let (post_msg, Some(pre_msg)) = (&rendered_msg, &rendered_pre_msg) {
2889        info!(
2890            context,
2891            "Message {} sizes: pre-message: {}; post-message: {}.",
2892            msg.id,
2893            format_size(pre_msg.message.len(), BINARY),
2894            format_size(post_msg.message.len(), BINARY),
2895        );
2896        msg.pre_rfc724_mid = pre_msg.rfc724_mid.clone();
2897    } else {
2898        info!(
2899            context,
2900            "Message {} will be sent in one shot (no pre- and post-message). Size: {}.",
2901            msg.id,
2902            format_size(rendered_msg.message.len(), BINARY),
2903        );
2904    }
2905
2906    if context.get_config_bool(Config::BccSelf).await? {
2907        smtp::add_self_recipients(context, &mut recipients, rendered_msg.is_encrypted).await?;
2908    }
2909
2910    if needs_encryption && !rendered_msg.is_encrypted {
2911        /* unrecoverable */
2912        message::set_msg_failed(
2913            context,
2914            msg,
2915            "End-to-end-encryption unavailable unexpectedly.",
2916        )
2917        .await?;
2918        bail!(
2919            "e2e encryption unavailable {} - {:?}",
2920            msg.id,
2921            needs_encryption
2922        );
2923    }
2924
2925    let now = smeared_time(context);
2926
2927    if rendered_msg.last_added_location_id.is_some()
2928        && let Err(err) = location::set_kml_sent_timestamp(context, msg.chat_id, now).await
2929    {
2930        error!(context, "Failed to set kml sent_timestamp: {err:#}.");
2931    }
2932
2933    if attach_selfavatar && let Err(err) = msg.chat_id.set_selfavatar_timestamp(context, now).await
2934    {
2935        error!(context, "Failed to set selfavatar timestamp: {err:#}.");
2936    }
2937
2938    if rendered_msg.is_encrypted {
2939        msg.param.set_int(Param::GuaranteeE2ee, 1);
2940    } else {
2941        msg.param.remove(Param::GuaranteeE2ee);
2942    }
2943    msg.subject.clone_from(&rendered_msg.subject);
2944    // Sort the message to the bottom. Employ `msgs_index7` to compute `timestamp`.
2945    context
2946        .sql
2947        .execute(
2948            "
2949UPDATE msgs SET
2950    timestamp=(
2951        SELECT MAX(timestamp) FROM msgs WHERE
2952            -- From `InFresh` to `OutMdnRcvd` inclusive except `OutDraft`.
2953            state IN(10,13,16,18,20,24,26,28) AND
2954            hidden IN(0,1) AND
2955            chat_id=?
2956    ),
2957    pre_rfc724_mid=?, subject=?, param=?
2958WHERE id=?
2959            ",
2960            (
2961                msg.chat_id,
2962                &msg.pre_rfc724_mid,
2963                &msg.subject,
2964                msg.param.to_string(),
2965                msg.id,
2966            ),
2967        )
2968        .await?;
2969
2970    let chunk_size = context.get_max_smtp_rcpt_to().await?;
2971    let trans_fn = |t: &mut rusqlite::Transaction| {
2972        let mut row_ids = Vec::<i64>::new();
2973
2974        if let Some(sync_ids) = rendered_msg.sync_ids_to_delete {
2975            t.execute(
2976                &format!("DELETE FROM multi_device_sync WHERE id IN ({sync_ids})"),
2977                (),
2978            )?;
2979        }
2980        let mut stmt = t.prepare(
2981            "INSERT INTO smtp (rfc724_mid, recipients, mime, msg_id)
2982            VALUES            (?1,         ?2,         ?3,   ?4)",
2983        )?;
2984        for recipients_chunk in recipients.chunks(chunk_size) {
2985            let recipients_chunk = recipients_chunk.join(" ");
2986            if let Some(pre_msg) = &rendered_pre_msg {
2987                let row_id = stmt.execute((
2988                    &pre_msg.rfc724_mid,
2989                    &recipients_chunk,
2990                    &pre_msg.message,
2991                    msg.id,
2992                ))?;
2993                row_ids.push(row_id.try_into()?);
2994            }
2995            let row_id = stmt.execute((
2996                &rendered_msg.rfc724_mid,
2997                &recipients_chunk,
2998                &rendered_msg.message,
2999                msg.id,
3000            ))?;
3001            row_ids.push(row_id.try_into()?);
3002        }
3003        Ok(row_ids)
3004    };
3005    context.sql.transaction(trans_fn).await
3006}
3007
3008/// Sends a text message to the given chat.
3009///
3010/// Returns database ID of the sent message.
3011pub async fn send_text_msg(
3012    context: &Context,
3013    chat_id: ChatId,
3014    text_to_send: String,
3015) -> Result<MsgId> {
3016    ensure!(
3017        !chat_id.is_special(),
3018        "bad chat_id, can not be a special chat: {chat_id}"
3019    );
3020
3021    let mut msg = Message::new_text(text_to_send);
3022    send_msg(context, chat_id, &mut msg).await
3023}
3024
3025/// Sends chat members a request to edit the given message's text.
3026#[expect(clippy::arithmetic_side_effects)]
3027pub async fn send_edit_request(context: &Context, msg_id: MsgId, new_text: String) -> Result<()> {
3028    let mut original_msg = Message::load_from_db(context, msg_id).await?;
3029    ensure!(
3030        original_msg.from_id == ContactId::SELF,
3031        "Can edit only own messages"
3032    );
3033    ensure!(!original_msg.is_info(), "Cannot edit info messages");
3034    ensure!(!original_msg.has_html(), "Cannot edit HTML messages");
3035    ensure!(original_msg.viewtype != Viewtype::Call, "Cannot edit calls");
3036    ensure!(
3037        !original_msg.text.is_empty(), // avoid complexity in UI element changes. focus is typos and rewordings
3038        "Cannot add text"
3039    );
3040    ensure!(!new_text.trim().is_empty(), "Edited text cannot be empty");
3041    if original_msg.text == new_text {
3042        info!(context, "Text unchanged.");
3043        return Ok(());
3044    }
3045
3046    save_text_edit_to_db(context, &mut original_msg, &new_text).await?;
3047
3048    let mut edit_msg = Message::new_text(EDITED_PREFIX.to_owned() + &new_text); // prefix only set for nicer display in Non-Delta-MUAs
3049    edit_msg.set_quote(context, Some(&original_msg)).await?; // quote only set for nicer display in Non-Delta-MUAs
3050    if original_msg.get_showpadlock() {
3051        edit_msg.param.set_int(Param::GuaranteeE2ee, 1);
3052    }
3053    edit_msg
3054        .param
3055        .set(Param::TextEditFor, original_msg.rfc724_mid);
3056    edit_msg.hidden = true;
3057    send_msg(context, original_msg.chat_id, &mut edit_msg).await?;
3058    Ok(())
3059}
3060
3061pub(crate) async fn save_text_edit_to_db(
3062    context: &Context,
3063    original_msg: &mut Message,
3064    new_text: &str,
3065) -> Result<()> {
3066    original_msg.param.set_int(Param::IsEdited, 1);
3067    context
3068        .sql
3069        .execute(
3070            "UPDATE msgs SET txt=?, txt_normalized=?, param=? WHERE id=?",
3071            (
3072                new_text,
3073                normalize_text(new_text),
3074                original_msg.param.to_string(),
3075                original_msg.id,
3076            ),
3077        )
3078        .await?;
3079    context.emit_msgs_changed(original_msg.chat_id, original_msg.id);
3080    Ok(())
3081}
3082
3083async fn donation_request_maybe(context: &Context) -> Result<()> {
3084    let secs_between_checks = 30 * 24 * 60 * 60;
3085    let now = time();
3086    let ts = context
3087        .get_config_i64(Config::DonationRequestNextCheck)
3088        .await?;
3089    if ts > now {
3090        return Ok(());
3091    }
3092    let msg_cnt = context.sql.count(
3093        "SELECT COUNT(*) FROM msgs WHERE state>=? AND hidden=0",
3094        (MessageState::OutDelivered,),
3095    );
3096    let ts = if ts == 0 || msg_cnt.await? < 100 {
3097        now.saturating_add(secs_between_checks)
3098    } else {
3099        let mut msg = Message::new_text(stock_str::donation_request(context));
3100        add_device_msg(context, None, Some(&mut msg)).await?;
3101        i64::MAX
3102    };
3103    context
3104        .set_config_internal(Config::DonationRequestNextCheck, Some(&ts.to_string()))
3105        .await
3106}
3107
3108/// Chat message list request options.
3109#[derive(Debug)]
3110pub struct MessageListOptions {
3111    /// Return only info messages.
3112    pub info_only: bool,
3113
3114    /// Add day markers before each date regarding the local timezone.
3115    pub add_daymarker: bool,
3116}
3117
3118/// Returns all messages belonging to the chat.
3119pub async fn get_chat_msgs(context: &Context, chat_id: ChatId) -> Result<Vec<ChatItem>> {
3120    get_chat_msgs_ex(
3121        context,
3122        chat_id,
3123        MessageListOptions {
3124            info_only: false,
3125            add_daymarker: false,
3126        },
3127    )
3128    .await
3129}
3130
3131/// Returns messages belonging to the chat according to the given options.
3132#[expect(clippy::arithmetic_side_effects)]
3133pub async fn get_chat_msgs_ex(
3134    context: &Context,
3135    chat_id: ChatId,
3136    options: MessageListOptions,
3137) -> Result<Vec<ChatItem>> {
3138    let MessageListOptions {
3139        info_only,
3140        add_daymarker,
3141    } = options;
3142    let process_row = if info_only {
3143        |row: &rusqlite::Row| {
3144            // is_info logic taken from Message.is_info()
3145            let params = row.get::<_, String>("param")?;
3146            let (from_id, to_id) = (
3147                row.get::<_, ContactId>("from_id")?,
3148                row.get::<_, ContactId>("to_id")?,
3149            );
3150            let is_info_msg: bool = from_id == ContactId::INFO
3151                || to_id == ContactId::INFO
3152                || match Params::from_str(&params) {
3153                    Ok(p) => {
3154                        let cmd = p.get_cmd();
3155                        cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage
3156                    }
3157                    _ => false,
3158                };
3159
3160            Ok((
3161                row.get::<_, i64>("timestamp")?,
3162                row.get::<_, MsgId>("id")?,
3163                !is_info_msg,
3164            ))
3165        }
3166    } else {
3167        |row: &rusqlite::Row| {
3168            Ok((
3169                row.get::<_, i64>("timestamp")?,
3170                row.get::<_, MsgId>("id")?,
3171                false,
3172            ))
3173        }
3174    };
3175    let process_rows = |rows: rusqlite::AndThenRows<_>| {
3176        // It is faster to sort here rather than
3177        // let sqlite execute an ORDER BY clause.
3178        let mut sorted_rows = Vec::new();
3179        for row in rows {
3180            let (ts, curr_id, exclude_message): (i64, MsgId, bool) = row?;
3181            if !exclude_message {
3182                sorted_rows.push((ts, curr_id));
3183            }
3184        }
3185        sorted_rows.sort_unstable();
3186
3187        let mut ret = Vec::new();
3188        let mut last_day = 0;
3189        let cnv_to_local = gm2local_offset();
3190
3191        for (ts, curr_id) in sorted_rows {
3192            if add_daymarker {
3193                let curr_local_timestamp = ts + cnv_to_local;
3194                let secs_in_day = 86400;
3195                let curr_day = curr_local_timestamp / secs_in_day;
3196                if curr_day != last_day {
3197                    ret.push(ChatItem::DayMarker {
3198                        timestamp: curr_day * secs_in_day - cnv_to_local,
3199                    });
3200                    last_day = curr_day;
3201                }
3202            }
3203            ret.push(ChatItem::Message { msg_id: curr_id });
3204        }
3205        Ok(ret)
3206    };
3207
3208    let items = if info_only {
3209        context
3210            .sql
3211            .query_map(
3212        // GLOB is used here instead of LIKE because it is case-sensitive
3213                "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
3214               FROM msgs m
3215              WHERE m.chat_id=?
3216                AND m.hidden=0
3217                AND (
3218                    m.param GLOB '*\nS=*' OR param GLOB 'S=*'
3219                    OR m.from_id == ?
3220                    OR m.to_id == ?
3221                );",
3222                (chat_id, ContactId::INFO, ContactId::INFO),
3223                process_row,
3224                process_rows,
3225            )
3226            .await?
3227    } else {
3228        context
3229            .sql
3230            .query_map(
3231                "SELECT m.id AS id, m.timestamp AS timestamp
3232               FROM msgs m
3233              WHERE m.chat_id=?
3234                AND m.hidden=0;",
3235                (chat_id,),
3236                process_row,
3237                process_rows,
3238            )
3239            .await?
3240    };
3241    Ok(items)
3242}
3243
3244/// Marks all unread messages in all chats as noticed.
3245/// Ignores messages from blocked contacts, but does not ignore messages in muted chats.
3246pub async fn marknoticed_all_chats(context: &Context) -> Result<()> {
3247    // The sql statement here is similar to the one in get_fresh_msgs
3248    let list = context
3249        .sql
3250        .query_map_vec(
3251            "SELECT DISTINCT(c.id)
3252                 FROM msgs m
3253                 INNER JOIN chats c
3254                        ON m.chat_id=c.id
3255                 WHERE m.state=?
3256                   AND m.hidden=0
3257                   AND m.chat_id>9
3258                   AND c.blocked=0;",
3259            (MessageState::InFresh,),
3260            |row| {
3261                let msg_id: ChatId = row.get(0)?;
3262                Ok(msg_id)
3263            },
3264        )
3265        .await?;
3266
3267    for chat_id in list {
3268        marknoticed_chat(context, chat_id).await?;
3269    }
3270
3271    Ok(())
3272}
3273
3274/// Marks all messages in the chat as noticed.
3275/// If the given chat-id is the archive-link, marks all messages in all archived chats as noticed.
3276pub async fn marknoticed_chat(context: &Context, chat_id: ChatId) -> Result<()> {
3277    // "WHERE" below uses the index `(state, hidden, chat_id)`, see get_fresh_msg_cnt() for reasoning
3278    // the additional SELECT statement may speed up things as no write-blocking is needed.
3279    if chat_id.is_archived_link() {
3280        let chat_ids_in_archive = context
3281            .sql
3282            .query_map_vec(
3283                "SELECT DISTINCT(m.chat_id) FROM msgs m
3284                    LEFT JOIN chats c ON m.chat_id=c.id
3285                    WHERE m.state=10 AND m.hidden=0 AND m.chat_id>9 AND c.archived=1",
3286                (),
3287                |row| {
3288                    let chat_id: ChatId = row.get(0)?;
3289                    Ok(chat_id)
3290                },
3291            )
3292            .await?;
3293        if chat_ids_in_archive.is_empty() {
3294            return Ok(());
3295        }
3296
3297        context
3298            .sql
3299            .transaction(|transaction| {
3300                let mut stmt = transaction.prepare(
3301                    "UPDATE msgs SET state=13 WHERE state=10 AND hidden=0 AND chat_id = ?",
3302                )?;
3303                for chat_id_in_archive in &chat_ids_in_archive {
3304                    stmt.execute((chat_id_in_archive,))?;
3305                }
3306                Ok(())
3307            })
3308            .await?;
3309
3310        for chat_id_in_archive in chat_ids_in_archive {
3311            start_chat_ephemeral_timers(context, chat_id_in_archive).await?;
3312            context.emit_event(EventType::MsgsNoticed(chat_id_in_archive));
3313            chatlist_events::emit_chatlist_item_changed(context, chat_id_in_archive);
3314        }
3315    } else {
3316        start_chat_ephemeral_timers(context, chat_id).await?;
3317
3318        let noticed_msgs_count = context
3319            .sql
3320            .execute(
3321                "UPDATE msgs
3322            SET state=?
3323          WHERE state=?
3324            AND hidden=0
3325            AND chat_id=?;",
3326                (MessageState::InNoticed, MessageState::InFresh, chat_id),
3327            )
3328            .await?;
3329
3330        // This is to trigger emitting `MsgsNoticed` on other devices when reactions are noticed
3331        // locally (i.e. when the chat was opened locally).
3332        let hidden_messages = context
3333            .sql
3334            .query_map_vec(
3335                "SELECT id FROM msgs
3336                    WHERE state=?
3337                      AND hidden=1
3338                      AND chat_id=?
3339                    ORDER BY id LIMIT 100", // LIMIT to 100 in order to avoid blocking the UI too long, usually there will be less than 100 messages anyway
3340                (MessageState::InFresh, chat_id), // No need to check for InNoticed messages, because reactions are never InNoticed
3341                |row| {
3342                    let msg_id: MsgId = row.get(0)?;
3343                    Ok(msg_id)
3344                },
3345            )
3346            .await?;
3347        message::markseen_msgs(context, hidden_messages).await?;
3348        if noticed_msgs_count == 0 {
3349            return Ok(());
3350        }
3351    }
3352
3353    context.emit_event(EventType::MsgsNoticed(chat_id));
3354    chatlist_events::emit_chatlist_item_changed(context, chat_id);
3355    context.on_archived_chats_maybe_noticed();
3356    Ok(())
3357}
3358
3359/// Marks messages preceding outgoing messages as noticed.
3360///
3361/// In a chat, if there is an outgoing message, it can be assumed that all previous
3362/// messages were noticed. So, this function takes a Vec of messages that were
3363/// just received, and for all the outgoing messages, it marks all
3364/// previous messages as noticed.
3365pub(crate) async fn mark_old_messages_as_noticed(
3366    context: &Context,
3367    mut msgs: Vec<ReceivedMsg>,
3368) -> Result<()> {
3369    if context.get_config_bool(Config::TeamProfile).await? {
3370        return Ok(());
3371    }
3372
3373    msgs.retain(|m| m.state.is_outgoing());
3374    if msgs.is_empty() {
3375        return Ok(());
3376    }
3377
3378    let mut msgs_by_chat: HashMap<ChatId, ReceivedMsg> = HashMap::new();
3379    for msg in msgs {
3380        let chat_id = msg.chat_id;
3381        if let Some(existing_msg) = msgs_by_chat.get(&chat_id) {
3382            if msg.sort_timestamp > existing_msg.sort_timestamp {
3383                msgs_by_chat.insert(chat_id, msg);
3384            }
3385        } else {
3386            msgs_by_chat.insert(chat_id, msg);
3387        }
3388    }
3389
3390    let changed_chats = context
3391        .sql
3392        .transaction(|transaction| {
3393            let mut changed_chats = Vec::new();
3394            for (_, msg) in msgs_by_chat {
3395                let changed_rows = transaction.execute(
3396                    "UPDATE msgs
3397            SET state=?
3398          WHERE state=?
3399            AND hidden=0
3400            AND chat_id=?
3401            AND timestamp<=?;",
3402                    (
3403                        MessageState::InNoticed,
3404                        MessageState::InFresh,
3405                        msg.chat_id,
3406                        msg.sort_timestamp,
3407                    ),
3408                )?;
3409                if changed_rows > 0 {
3410                    changed_chats.push(msg.chat_id);
3411                }
3412            }
3413            Ok(changed_chats)
3414        })
3415        .await?;
3416
3417    if !changed_chats.is_empty() {
3418        info!(
3419            context,
3420            "Marking chats as noticed because there are newer outgoing messages: {changed_chats:?}."
3421        );
3422        context.on_archived_chats_maybe_noticed();
3423    }
3424
3425    for c in changed_chats {
3426        start_chat_ephemeral_timers(context, c).await?;
3427        context.emit_event(EventType::MsgsNoticed(c));
3428        chatlist_events::emit_chatlist_item_changed(context, c);
3429    }
3430
3431    Ok(())
3432}
3433
3434/// Marks last incoming message in a chat as fresh.
3435pub async fn markfresh_chat(context: &Context, chat_id: ChatId) -> Result<()> {
3436    let affected_rows = context
3437        .sql
3438        .execute(
3439            "UPDATE msgs
3440                SET state=?1
3441              WHERE id=(SELECT id
3442                          FROM msgs
3443                         WHERE state IN (?1, ?2, ?3) AND hidden=0 AND chat_id=?4
3444                      ORDER BY timestamp DESC, id DESC
3445                         LIMIT 1)
3446                AND state!=?1",
3447            (
3448                MessageState::InFresh,
3449                MessageState::InNoticed,
3450                MessageState::InSeen,
3451                chat_id,
3452            ),
3453        )
3454        .await?;
3455
3456    if affected_rows == 0 {
3457        return Ok(());
3458    }
3459
3460    context.emit_msgs_changed_without_msg_id(chat_id);
3461    chatlist_events::emit_chatlist_item_changed(context, chat_id);
3462
3463    Ok(())
3464}
3465
3466/// Returns all database message IDs of the given types.
3467///
3468/// If `chat_id` is None, return messages from any chat.
3469///
3470/// `Viewtype::Unknown` can be used for `msg_type2` and `msg_type3`
3471/// if less than 3 viewtypes are requested.
3472pub async fn get_chat_media(
3473    context: &Context,
3474    chat_id: Option<ChatId>,
3475    msg_type: Viewtype,
3476    msg_type2: Viewtype,
3477    msg_type3: Viewtype,
3478) -> Result<Vec<MsgId>> {
3479    let list = if msg_type == Viewtype::Webxdc
3480        && msg_type2 == Viewtype::Unknown
3481        && msg_type3 == Viewtype::Unknown
3482    {
3483        context
3484            .sql
3485            .query_map_vec(
3486                "SELECT id
3487               FROM msgs
3488              WHERE (1=? OR chat_id=?)
3489                AND chat_id != ?
3490                AND type = ?
3491                AND hidden=0
3492              ORDER BY max(timestamp, timestamp_rcvd), id;",
3493                (
3494                    chat_id.is_none(),
3495                    chat_id.unwrap_or_else(|| ChatId::new(0)),
3496                    DC_CHAT_ID_TRASH,
3497                    Viewtype::Webxdc,
3498                ),
3499                |row| {
3500                    let msg_id: MsgId = row.get(0)?;
3501                    Ok(msg_id)
3502                },
3503            )
3504            .await?
3505    } else {
3506        context
3507            .sql
3508            .query_map_vec(
3509                "SELECT id
3510               FROM msgs
3511              WHERE (1=? OR chat_id=?)
3512                AND chat_id != ?
3513                AND type IN (?, ?, ?)
3514                AND hidden=0
3515              ORDER BY timestamp, id;",
3516                (
3517                    chat_id.is_none(),
3518                    chat_id.unwrap_or_else(|| ChatId::new(0)),
3519                    DC_CHAT_ID_TRASH,
3520                    msg_type,
3521                    if msg_type2 != Viewtype::Unknown {
3522                        msg_type2
3523                    } else {
3524                        msg_type
3525                    },
3526                    if msg_type3 != Viewtype::Unknown {
3527                        msg_type3
3528                    } else {
3529                        msg_type
3530                    },
3531                ),
3532                |row| {
3533                    let msg_id: MsgId = row.get(0)?;
3534                    Ok(msg_id)
3535                },
3536            )
3537            .await?
3538    };
3539    Ok(list)
3540}
3541
3542/// Returns a vector of contact IDs for given chat ID.
3543pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3544    // Normal chats do not include SELF.  Group chats do (as it may happen that one is deleted from a
3545    // groupchat but the chats stays visible, moreover, this makes displaying lists easier)
3546    context
3547        .sql
3548        .query_map_vec(
3549            "SELECT cc.contact_id
3550               FROM chats_contacts cc
3551               LEFT JOIN contacts c
3552                      ON c.id=cc.contact_id
3553              WHERE cc.chat_id=? AND cc.add_timestamp >= cc.remove_timestamp
3554              ORDER BY c.id=1, c.last_seen DESC, c.id DESC;",
3555            (chat_id,),
3556            |row| {
3557                let contact_id: ContactId = row.get(0)?;
3558                Ok(contact_id)
3559            },
3560        )
3561        .await
3562}
3563
3564/// Returns a vector of contact IDs for given chat ID that are no longer part of the group.
3565///
3566/// Members that have been removed recently are in the beginning of the list.
3567pub async fn get_past_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> {
3568    let now = time();
3569    context
3570        .sql
3571        .query_map_vec(
3572            "SELECT cc.contact_id
3573             FROM chats_contacts cc
3574             LEFT JOIN contacts c
3575                  ON c.id=cc.contact_id
3576             WHERE cc.chat_id=?
3577             AND cc.add_timestamp < cc.remove_timestamp
3578             AND ? < cc.remove_timestamp
3579             ORDER BY c.id=1, cc.remove_timestamp DESC, c.id DESC",
3580            (chat_id, now.saturating_sub(60 * 24 * 3600)),
3581            |row| {
3582                let contact_id: ContactId = row.get(0)?;
3583                Ok(contact_id)
3584            },
3585        )
3586        .await
3587}
3588
3589/// Creates an encrypted group chat.
3590pub async fn create_group(context: &Context, name: &str) -> Result<ChatId> {
3591    create_group_ex(context, Sync, create_id(), name).await
3592}
3593
3594/// Creates an unencrypted group chat.
3595pub async fn create_group_unencrypted(context: &Context, name: &str) -> Result<ChatId> {
3596    create_group_ex(context, Sync, String::new(), name).await
3597}
3598
3599/// Creates a group chat.
3600///
3601/// * `sync` - Whether a multi-device synchronization message should be sent. Ignored for
3602///   unencrypted chats currently.
3603/// * `grpid` - Group ID. Iff nonempty, the chat is encrypted (with key-contacts).
3604/// * `name` - Chat name.
3605pub(crate) async fn create_group_ex(
3606    context: &Context,
3607    sync: sync::Sync,
3608    grpid: String,
3609    name: &str,
3610) -> Result<ChatId> {
3611    let mut chat_name = sanitize_single_line(name);
3612    if chat_name.is_empty() {
3613        // We can't just fail because the user would lose the work already done in the UI like
3614        // selecting members.
3615        error!(context, "Invalid chat name: {name}.");
3616        chat_name = "…".to_string();
3617    }
3618
3619    let timestamp = create_smeared_timestamp(context);
3620    let row_id = context
3621        .sql
3622        .insert(
3623            "INSERT INTO chats
3624        (type, name, name_normalized, grpid, param, created_timestamp)
3625        VALUES(?, ?, ?, ?, \'U=1\', ?)",
3626            (
3627                Chattype::Group,
3628                &chat_name,
3629                normalize_text(&chat_name),
3630                &grpid,
3631                timestamp,
3632            ),
3633        )
3634        .await?;
3635
3636    let chat_id = ChatId::new(u32::try_from(row_id)?);
3637    add_to_chat_contacts_table(context, timestamp, chat_id, &[ContactId::SELF]).await?;
3638
3639    context.emit_msgs_changed_without_ids();
3640    chatlist_events::emit_chatlist_changed(context);
3641    chatlist_events::emit_chatlist_item_changed(context, chat_id);
3642
3643    if !grpid.is_empty() {
3644        // Add "Messages are end-to-end encrypted." message.
3645        chat_id.add_e2ee_notice(context, timestamp).await?;
3646    }
3647
3648    if !context.get_config_bool(Config::Bot).await?
3649        && !context.get_config_bool(Config::SkipStartMessages).await?
3650    {
3651        let text = if !grpid.is_empty() {
3652            // Add "Others will only see this group after you sent a first message." message.
3653            stock_str::new_group_send_first_message(context)
3654        } else {
3655            // Add "Messages in this chat use classic email and are not encrypted." message.
3656            stock_str::chat_unencrypted_explanation(context)
3657        };
3658        chat_id.add_start_info_message(context, &text).await?;
3659    }
3660    if let (true, true) = (sync.into(), !grpid.is_empty()) {
3661        let id = SyncId::Grpid(grpid);
3662        let action = SyncAction::CreateGroupEncrypted(chat_name);
3663        self::sync(context, id, action).await.log_err(context).ok();
3664    }
3665    Ok(chat_id)
3666}
3667
3668/// Create a new, outgoing **broadcast channel**
3669/// (called "Channel" in the UI).
3670///
3671/// Broadcast channels are similar to groups on the sending device,
3672/// however, recipients get the messages in a read-only chat
3673/// and will not see who the other members are.
3674///
3675/// Called `broadcast` here rather than `channel`,
3676/// because the word "channel" already appears a lot in the code,
3677/// which would make it hard to grep for it.
3678///
3679/// After creation, the chat contains no recipients and is in _unpromoted_ state;
3680/// see [`create_group`] for more information on the unpromoted state.
3681///
3682/// Returns the created chat's id.
3683pub async fn create_broadcast(context: &Context, chat_name: String) -> Result<ChatId> {
3684    let grpid = create_id();
3685    let secret = create_broadcast_secret();
3686    create_out_broadcast_ex(context, Sync, grpid, chat_name, secret).await
3687}
3688
3689const SQL_INSERT_BROADCAST_SECRET: &str =
3690    "INSERT INTO broadcast_secrets (chat_id, secret) VALUES (?, ?)
3691    ON CONFLICT(chat_id) DO UPDATE SET secret=excluded.secret";
3692
3693pub(crate) async fn create_out_broadcast_ex(
3694    context: &Context,
3695    sync: sync::Sync,
3696    grpid: String,
3697    chat_name: String,
3698    secret: String,
3699) -> Result<ChatId> {
3700    let chat_name = sanitize_single_line(&chat_name);
3701    if chat_name.is_empty() {
3702        bail!("Invalid broadcast channel name: {chat_name}.");
3703    }
3704
3705    let timestamp = create_smeared_timestamp(context);
3706    let trans_fn = |t: &mut rusqlite::Transaction| -> Result<ChatId> {
3707        let cnt: u32 = t.query_row(
3708            "SELECT COUNT(*) FROM chats WHERE grpid=?",
3709            (&grpid,),
3710            |row| row.get(0),
3711        )?;
3712        ensure!(cnt == 0, "{cnt} chats exist with grpid {grpid}");
3713
3714        t.execute(
3715            "INSERT INTO chats
3716            (type, name, name_normalized, grpid, created_timestamp)
3717            VALUES(?, ?, ?, ?, ?)",
3718            (
3719                Chattype::OutBroadcast,
3720                &chat_name,
3721                normalize_text(&chat_name),
3722                &grpid,
3723                timestamp,
3724            ),
3725        )?;
3726        let chat_id = ChatId::new(t.last_insert_rowid().try_into()?);
3727
3728        t.execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, &secret))?;
3729        Ok(chat_id)
3730    };
3731    let chat_id = context.sql.transaction(trans_fn).await?;
3732    chat_id.add_e2ee_notice(context, timestamp).await?;
3733
3734    context.emit_msgs_changed_without_ids();
3735    chatlist_events::emit_chatlist_changed(context);
3736    chatlist_events::emit_chatlist_item_changed(context, chat_id);
3737
3738    if sync.into() {
3739        let id = SyncId::Grpid(grpid);
3740        let action = SyncAction::CreateOutBroadcast { chat_name, secret };
3741        self::sync(context, id, action).await.log_err(context).ok();
3742    }
3743
3744    Ok(chat_id)
3745}
3746
3747pub(crate) async fn load_broadcast_secret(
3748    context: &Context,
3749    chat_id: ChatId,
3750) -> Result<Option<String>> {
3751    context
3752        .sql
3753        .query_get_value(
3754            "SELECT secret FROM broadcast_secrets WHERE chat_id=?",
3755            (chat_id,),
3756        )
3757        .await
3758}
3759
3760pub(crate) async fn save_broadcast_secret(
3761    context: &Context,
3762    chat_id: ChatId,
3763    secret: &str,
3764) -> Result<()> {
3765    info!(context, "Saving broadcast secret for chat {chat_id}");
3766    context
3767        .sql
3768        .execute(SQL_INSERT_BROADCAST_SECRET, (chat_id, secret))
3769        .await?;
3770
3771    Ok(())
3772}
3773
3774pub(crate) async fn delete_broadcast_secret(context: &Context, chat_id: ChatId) -> Result<()> {
3775    info!(context, "Removing broadcast secret for chat {chat_id}");
3776    context
3777        .sql
3778        .execute("DELETE FROM broadcast_secrets WHERE chat_id=?", (chat_id,))
3779        .await?;
3780
3781    Ok(())
3782}
3783
3784/// Set chat contacts in the `chats_contacts` table.
3785pub(crate) async fn update_chat_contacts_table(
3786    context: &Context,
3787    timestamp: i64,
3788    id: ChatId,
3789    contacts: &BTreeSet<ContactId>,
3790) -> Result<()> {
3791    context
3792        .sql
3793        .transaction(move |transaction| {
3794            // Bump `remove_timestamp` to at least `now`
3795            // even for members from `contacts`.
3796            // We add members from `contacts` back below.
3797            transaction.execute(
3798                "UPDATE chats_contacts
3799                 SET remove_timestamp=MAX(add_timestamp+1, ?)
3800                 WHERE chat_id=?",
3801                (timestamp, id),
3802            )?;
3803
3804            if !contacts.is_empty() {
3805                let mut statement = transaction.prepare(
3806                    "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp)
3807                     VALUES                     (?1,      ?2,         ?3)
3808                     ON CONFLICT (chat_id, contact_id)
3809                     DO UPDATE SET add_timestamp=remove_timestamp",
3810                )?;
3811
3812                for contact_id in contacts {
3813                    // We bumped `add_timestamp` for existing rows above,
3814                    // so on conflict it is enough to set `add_timestamp = remove_timestamp`
3815                    // and this guarantees that `add_timestamp` is no less than `timestamp`.
3816                    statement.execute((id, contact_id, timestamp))?;
3817                }
3818            }
3819            Ok(())
3820        })
3821        .await?;
3822    Ok(())
3823}
3824
3825/// Adds contacts to the `chats_contacts` table.
3826pub(crate) async fn add_to_chat_contacts_table(
3827    context: &Context,
3828    timestamp: i64,
3829    chat_id: ChatId,
3830    contact_ids: &[ContactId],
3831) -> Result<()> {
3832    context
3833        .sql
3834        .transaction(move |transaction| {
3835            let mut add_statement = transaction.prepare(
3836                "INSERT INTO chats_contacts (chat_id, contact_id, add_timestamp) VALUES(?1, ?2, ?3)
3837                 ON CONFLICT (chat_id, contact_id)
3838                 DO UPDATE SET add_timestamp=MAX(remove_timestamp, ?3)",
3839            )?;
3840
3841            for contact_id in contact_ids {
3842                add_statement.execute((chat_id, contact_id, timestamp))?;
3843            }
3844            Ok(())
3845        })
3846        .await?;
3847
3848    Ok(())
3849}
3850
3851/// Removes a contact from the chat
3852/// by updating the `remove_timestamp`.
3853pub(crate) async fn remove_from_chat_contacts_table(
3854    context: &Context,
3855    chat_id: ChatId,
3856    contact_id: ContactId,
3857) -> Result<()> {
3858    let now = time();
3859    context
3860        .sql
3861        .execute(
3862            "UPDATE chats_contacts
3863             SET remove_timestamp=MAX(add_timestamp+1, ?)
3864             WHERE chat_id=? AND contact_id=?",
3865            (now, chat_id, contact_id),
3866        )
3867        .await?;
3868    Ok(())
3869}
3870
3871/// Removes a contact from the chat
3872/// without leaving a trace.
3873///
3874/// Note that if we call this function,
3875/// and then receive a message from another device
3876/// that doesn't know that this this member was removed
3877/// then the group membership algorithm will wrongly re-add this member.
3878pub(crate) async fn remove_from_chat_contacts_table_without_trace(
3879    context: &Context,
3880    chat_id: ChatId,
3881    contact_id: ContactId,
3882) -> Result<()> {
3883    context
3884        .sql
3885        .execute(
3886            "DELETE FROM chats_contacts
3887            WHERE chat_id=? AND contact_id=?",
3888            (chat_id, contact_id),
3889        )
3890        .await?;
3891
3892    Ok(())
3893}
3894
3895/// Adds a contact to the chat.
3896/// If the group is promoted, also sends out a system message to all group members
3897pub async fn add_contact_to_chat(
3898    context: &Context,
3899    chat_id: ChatId,
3900    contact_id: ContactId,
3901) -> Result<()> {
3902    add_contact_to_chat_ex(context, Sync, chat_id, contact_id, false).await?;
3903    Ok(())
3904}
3905
3906pub(crate) async fn add_contact_to_chat_ex(
3907    context: &Context,
3908    mut sync: sync::Sync,
3909    chat_id: ChatId,
3910    contact_id: ContactId,
3911    from_handshake: bool,
3912) -> Result<bool> {
3913    ensure!(!chat_id.is_special(), "can not add member to special chats");
3914    let contact = Contact::get_by_id(context, contact_id).await?;
3915    let mut msg = Message::new(Viewtype::default());
3916
3917    chat_id.reset_gossiped_timestamp(context).await?;
3918
3919    // this also makes sure, no contacts are added to special or normal chats
3920    let mut chat = Chat::load_from_db(context, chat_id).await?;
3921    ensure!(
3922        chat.typ == Chattype::Group || (from_handshake && chat.typ == Chattype::OutBroadcast),
3923        "{chat_id} is not a group where one can add members",
3924    );
3925    ensure!(
3926        Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF,
3927        "invalid contact_id {contact_id} for adding to group"
3928    );
3929    ensure!(
3930        chat.typ != Chattype::OutBroadcast || contact_id != ContactId::SELF,
3931        "Cannot add SELF to broadcast channel."
3932    );
3933    match chat.is_encrypted(context).await? {
3934        true => ensure!(
3935            contact.is_key_contact(),
3936            "Only key-contacts can be added to encrypted chats"
3937        ),
3938        false => ensure!(
3939            !contact.is_key_contact(),
3940            "Only address-contacts can be added to unencrypted chats"
3941        ),
3942    }
3943
3944    if !chat.is_self_in_chat(context).await? {
3945        context.emit_event(EventType::ErrorSelfNotInGroup(
3946            "Cannot add contact to group; self not in group.".into(),
3947        ));
3948        warn!(
3949            context,
3950            "Can not add contact because the account is not part of the group/broadcast."
3951        );
3952        return Ok(false);
3953    }
3954    if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {
3955        let smeared_time = smeared_time(context);
3956        chat.param
3957            .remove(Param::Unpromoted)
3958            .set_i64(Param::GroupNameTimestamp, smeared_time)
3959            .set_i64(Param::GroupDescriptionTimestamp, smeared_time);
3960        chat.update_param(context).await?;
3961    }
3962    if context.is_self_addr(contact.get_addr()).await? {
3963        // ourself is added using ContactId::SELF, do not add this address explicitly.
3964        // if SELF is not in the group, members cannot be added at all.
3965        warn!(
3966            context,
3967            "Invalid attempt to add self e-mail address to group."
3968        );
3969        return Ok(false);
3970    }
3971
3972    if is_contact_in_chat(context, chat_id, contact_id).await? {
3973        if !from_handshake {
3974            return Ok(true);
3975        }
3976    } else {
3977        // else continue and send status mail
3978        add_to_chat_contacts_table(context, time(), chat_id, &[contact_id]).await?;
3979    }
3980    if chat.is_promoted() {
3981        msg.viewtype = Viewtype::Text;
3982
3983        let contact_addr = contact.get_addr().to_lowercase();
3984        let added_by = if from_handshake && chat.typ == Chattype::OutBroadcast {
3985            // The contact was added via a QR code rather than explicit user action,
3986            // so it could be confusing to say 'You added member Alice'.
3987            // And in a broadcast, SELF is the only one who can add members,
3988            // so, no information is lost by just writing 'Member Alice added' instead.
3989            ContactId::UNDEFINED
3990        } else {
3991            ContactId::SELF
3992        };
3993        msg.text = stock_str::msg_add_member_local(context, contact.id, added_by).await;
3994        msg.param.set_cmd(SystemMessage::MemberAddedToGroup);
3995        msg.param.set(Param::Arg, contact_addr);
3996        msg.param.set_int(Param::Arg2, from_handshake.into());
3997        let fingerprint = contact.fingerprint().map(|f| f.hex());
3998        msg.param.set_optional(Param::Arg4, fingerprint);
3999        msg.param
4000            .set_int(Param::ContactAddedRemoved, contact.id.to_u32() as i32);
4001        if chat.typ == Chattype::OutBroadcast {
4002            let secret = load_broadcast_secret(context, chat_id)
4003                .await?
4004                .context("Failed to find broadcast shared secret")?;
4005            msg.param.set(PARAM_BROADCAST_SECRET, secret);
4006        }
4007        send_msg(context, chat_id, &mut msg).await?;
4008
4009        sync = Nosync;
4010    }
4011    context.emit_event(EventType::ChatModified(chat_id));
4012    if sync.into() {
4013        chat.sync_contacts(context).await.log_err(context).ok();
4014    }
4015    Ok(true)
4016}
4017
4018/// Returns true if an avatar should be attached in the given chat.
4019///
4020/// This function does not check if the avatar is set.
4021/// If avatar is not set and this function returns `true`,
4022/// a `Chat-User-Avatar: 0` header should be sent to reset the avatar.
4023#[expect(clippy::arithmetic_side_effects)]
4024pub(crate) async fn shall_attach_selfavatar(context: &Context, chat_id: ChatId) -> Result<bool> {
4025    let timestamp_some_days_ago = time() - DC_RESEND_USER_AVATAR_DAYS * 24 * 60 * 60;
4026    let needs_attach = context
4027        .sql
4028        .query_map(
4029            "SELECT c.selfavatar_sent
4030             FROM chats_contacts cc
4031             LEFT JOIN contacts c ON c.id=cc.contact_id
4032             WHERE cc.chat_id=? AND cc.contact_id!=? AND cc.add_timestamp >= cc.remove_timestamp",
4033            (chat_id, ContactId::SELF),
4034            |row| {
4035                let selfavatar_sent: i64 = row.get(0)?;
4036                Ok(selfavatar_sent)
4037            },
4038            |rows| {
4039                let mut needs_attach = false;
4040                for row in rows {
4041                    let selfavatar_sent = row?;
4042                    if selfavatar_sent < timestamp_some_days_ago {
4043                        needs_attach = true;
4044                    }
4045                }
4046                Ok(needs_attach)
4047            },
4048        )
4049        .await?;
4050    Ok(needs_attach)
4051}
4052
4053/// Chat mute duration.
4054#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
4055pub enum MuteDuration {
4056    /// Chat is not muted.
4057    NotMuted,
4058
4059    /// Chat is muted until the user unmutes the chat.
4060    Forever,
4061
4062    /// Chat is muted for a limited period of time.
4063    Until(std::time::SystemTime),
4064}
4065
4066impl rusqlite::types::ToSql for MuteDuration {
4067    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
4068        let duration: i64 = match &self {
4069            MuteDuration::NotMuted => 0,
4070            MuteDuration::Forever => -1,
4071            MuteDuration::Until(when) => {
4072                let duration = when
4073                    .duration_since(SystemTime::UNIX_EPOCH)
4074                    .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
4075                i64::try_from(duration.as_secs())
4076                    .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?
4077            }
4078        };
4079        let val = rusqlite::types::Value::Integer(duration);
4080        let out = rusqlite::types::ToSqlOutput::Owned(val);
4081        Ok(out)
4082    }
4083}
4084
4085impl rusqlite::types::FromSql for MuteDuration {
4086    fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
4087        // Negative values other than -1 should not be in the
4088        // database.  If found they'll be NotMuted.
4089        match i64::column_result(value)? {
4090            0 => Ok(MuteDuration::NotMuted),
4091            -1 => Ok(MuteDuration::Forever),
4092            n if n > 0 => match SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(n as u64)) {
4093                Some(t) => Ok(MuteDuration::Until(t)),
4094                None => Err(rusqlite::types::FromSqlError::OutOfRange(n)),
4095            },
4096            _ => Ok(MuteDuration::NotMuted),
4097        }
4098    }
4099}
4100
4101/// Mutes the chat for a given duration or unmutes it.
4102pub async fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuration) -> Result<()> {
4103    set_muted_ex(context, Sync, chat_id, duration).await
4104}
4105
4106pub(crate) async fn set_muted_ex(
4107    context: &Context,
4108    sync: sync::Sync,
4109    chat_id: ChatId,
4110    duration: MuteDuration,
4111) -> Result<()> {
4112    ensure!(!chat_id.is_special(), "Invalid chat ID");
4113    context
4114        .sql
4115        .execute(
4116            "UPDATE chats SET muted_until=? WHERE id=?;",
4117            (duration, chat_id),
4118        )
4119        .await
4120        .context(format!("Failed to set mute duration for {chat_id}"))?;
4121    context.emit_event(EventType::ChatModified(chat_id));
4122    chatlist_events::emit_chatlist_item_changed(context, chat_id);
4123    if sync.into() {
4124        let chat = Chat::load_from_db(context, chat_id).await?;
4125        chat.sync(context, SyncAction::SetMuted(duration))
4126            .await
4127            .log_err(context)
4128            .ok();
4129    }
4130    Ok(())
4131}
4132
4133/// Removes contact from the chat.
4134pub async fn remove_contact_from_chat(
4135    context: &Context,
4136    chat_id: ChatId,
4137    contact_id: ContactId,
4138) -> Result<()> {
4139    ensure!(
4140        !chat_id.is_special(),
4141        "bad chat_id, can not be special chat: {chat_id}"
4142    );
4143    ensure!(
4144        !contact_id.is_special() || contact_id == ContactId::SELF,
4145        "Cannot remove special contact"
4146    );
4147
4148    let chat = Chat::load_from_db(context, chat_id).await?;
4149    if chat.typ == Chattype::InBroadcast {
4150        ensure!(
4151            contact_id == ContactId::SELF,
4152            "Cannot remove other member from incoming broadcast channel"
4153        );
4154        delete_broadcast_secret(context, chat_id).await?;
4155    }
4156
4157    ensure!(
4158        matches!(
4159            chat.typ,
4160            Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast
4161        ),
4162        "Cannot remove members from non-group chats."
4163    );
4164
4165    if !chat.is_self_in_chat(context).await? {
4166        let err_msg =
4167            format!("Cannot remove contact {contact_id} from chat {chat_id}: self not in group.");
4168        context.emit_event(EventType::ErrorSelfNotInGroup(err_msg.clone()));
4169        bail!("{err_msg}");
4170    }
4171
4172    let mut sync = Nosync;
4173
4174    if chat.is_promoted() && chat.typ != Chattype::OutBroadcast {
4175        remove_from_chat_contacts_table(context, chat_id, contact_id).await?;
4176    } else {
4177        remove_from_chat_contacts_table_without_trace(context, chat_id, contact_id).await?;
4178    }
4179
4180    // We do not return an error if the contact does not exist in the database.
4181    // This allows to delete dangling references to deleted contacts
4182    // in case of the database becoming inconsistent due to a bug.
4183    if let Some(contact) = Contact::get_by_id_optional(context, contact_id).await? {
4184        if chat.is_promoted() {
4185            let addr = contact.get_addr();
4186            let fingerprint = contact.fingerprint().map(|f| f.hex());
4187
4188            let res =
4189                send_member_removal_msg(context, &chat, contact_id, addr, fingerprint.as_deref())
4190                    .await;
4191
4192            if contact_id == ContactId::SELF {
4193                res?;
4194            } else if let Err(e) = res {
4195                warn!(
4196                    context,
4197                    "remove_contact_from_chat({chat_id}, {contact_id}): send_msg() failed: {e:#}."
4198                );
4199            }
4200        } else {
4201            sync = Sync;
4202        }
4203    }
4204    context.emit_event(EventType::ChatModified(chat_id));
4205    if sync.into() {
4206        chat.sync_contacts(context).await.log_err(context).ok();
4207    }
4208
4209    Ok(())
4210}
4211
4212async fn send_member_removal_msg(
4213    context: &Context,
4214    chat: &Chat,
4215    contact_id: ContactId,
4216    addr: &str,
4217    fingerprint: Option<&str>,
4218) -> Result<MsgId> {
4219    let mut msg = Message::new(Viewtype::Text);
4220
4221    if contact_id == ContactId::SELF {
4222        if chat.typ == Chattype::InBroadcast {
4223            msg.text = stock_str::msg_you_left_broadcast(context);
4224        } else {
4225            msg.text = stock_str::msg_group_left_local(context, ContactId::SELF).await;
4226        }
4227    } else {
4228        msg.text = stock_str::msg_del_member_local(context, contact_id, ContactId::SELF).await;
4229    }
4230
4231    msg.param.set_cmd(SystemMessage::MemberRemovedFromGroup);
4232    msg.param.set(Param::Arg, addr.to_lowercase());
4233    msg.param.set_optional(Param::Arg4, fingerprint);
4234    msg.param
4235        .set(Param::ContactAddedRemoved, contact_id.to_u32());
4236
4237    send_msg(context, chat.id, &mut msg).await
4238}
4239
4240/// Set group or broadcast channel description.
4241///
4242/// If the group is already _promoted_ (any message was sent to the group),
4243/// or if this is a brodacast channel,
4244/// all members are informed by a special status message that is sent automatically by this function.
4245///
4246/// Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent.
4247///
4248/// See also [`get_chat_description`]
4249pub async fn set_chat_description(
4250    context: &Context,
4251    chat_id: ChatId,
4252    new_description: &str,
4253) -> Result<()> {
4254    set_chat_description_ex(context, Sync, chat_id, new_description).await
4255}
4256
4257async fn set_chat_description_ex(
4258    context: &Context,
4259    mut sync: sync::Sync,
4260    chat_id: ChatId,
4261    new_description: &str,
4262) -> Result<()> {
4263    let new_description = sanitize_bidi_characters(new_description.trim());
4264
4265    ensure!(!chat_id.is_special(), "Invalid chat ID");
4266
4267    let chat = Chat::load_from_db(context, chat_id).await?;
4268    ensure!(
4269        chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4270        "Can only set description for groups / broadcasts"
4271    );
4272    ensure!(
4273        !chat.grpid.is_empty(),
4274        "Cannot set description for ad hoc groups"
4275    );
4276    if !chat.is_self_in_chat(context).await? {
4277        context.emit_event(EventType::ErrorSelfNotInGroup(
4278            "Cannot set chat description; self not in group".into(),
4279        ));
4280        bail!("Cannot set chat description; self not in group");
4281    }
4282
4283    let old_description = get_chat_description(context, chat_id).await?;
4284    if old_description == new_description {
4285        return Ok(());
4286    }
4287
4288    context
4289        .sql
4290        .execute(
4291            "INSERT OR REPLACE INTO chats_descriptions(chat_id, description) VALUES(?, ?)",
4292            (chat_id, &new_description),
4293        )
4294        .await?;
4295
4296    if chat.is_promoted() {
4297        let mut msg = Message::new(Viewtype::Text);
4298        msg.text = stock_str::msg_chat_description_changed(context, ContactId::SELF).await;
4299        msg.param.set_cmd(SystemMessage::GroupDescriptionChanged);
4300
4301        msg.id = send_msg(context, chat_id, &mut msg).await?;
4302        context.emit_msgs_changed(chat_id, msg.id);
4303        sync = Nosync;
4304    }
4305    context.emit_event(EventType::ChatModified(chat_id));
4306
4307    if sync.into() {
4308        chat.sync(context, SyncAction::SetDescription(new_description))
4309            .await
4310            .log_err(context)
4311            .ok();
4312    }
4313
4314    Ok(())
4315}
4316
4317/// Load the chat description from the database.
4318///
4319/// UIs show this in the profile page of the chat,
4320/// it is settable by [`set_chat_description`]
4321pub async fn get_chat_description(context: &Context, chat_id: ChatId) -> Result<String> {
4322    let description = context
4323        .sql
4324        .query_get_value(
4325            "SELECT description FROM chats_descriptions WHERE chat_id=?",
4326            (chat_id,),
4327        )
4328        .await?
4329        .unwrap_or_default();
4330    Ok(description)
4331}
4332
4333/// Sets group, mailing list, or broadcast channel chat name.
4334///
4335/// If the group is already _promoted_ (any message was sent to the group),
4336/// or if this is a brodacast channel,
4337/// all members are informed by a special status message that is sent automatically by this function.
4338///
4339/// Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent.
4340pub async fn set_chat_name(context: &Context, chat_id: ChatId, new_name: &str) -> Result<()> {
4341    rename_ex(context, Sync, chat_id, new_name).await
4342}
4343
4344async fn rename_ex(
4345    context: &Context,
4346    mut sync: sync::Sync,
4347    chat_id: ChatId,
4348    new_name: &str,
4349) -> Result<()> {
4350    let new_name = sanitize_single_line(new_name);
4351    /* the function only sets the names of group chats; normal chats get their names from the contacts */
4352    let mut success = false;
4353
4354    ensure!(!new_name.is_empty(), "Invalid name");
4355    ensure!(!chat_id.is_special(), "Invalid chat ID");
4356
4357    let chat = Chat::load_from_db(context, chat_id).await?;
4358    let mut msg = Message::new(Viewtype::default());
4359
4360    if chat.typ == Chattype::Group
4361        || chat.typ == Chattype::Mailinglist
4362        || chat.typ == Chattype::OutBroadcast
4363    {
4364        if chat.name == new_name {
4365            success = true;
4366        } else if !chat.is_self_in_chat(context).await? {
4367            context.emit_event(EventType::ErrorSelfNotInGroup(
4368                "Cannot set chat name; self not in group".into(),
4369            ));
4370        } else {
4371            context
4372                .sql
4373                .execute(
4374                    "UPDATE chats SET name=?, name_normalized=? WHERE id=?",
4375                    (&new_name, normalize_text(&new_name), chat_id),
4376                )
4377                .await?;
4378            if chat.is_promoted()
4379                && !chat.is_mailing_list()
4380                && sanitize_single_line(&chat.name) != new_name
4381            {
4382                msg.viewtype = Viewtype::Text;
4383                msg.text = if chat.typ == Chattype::OutBroadcast {
4384                    stock_str::msg_broadcast_name_changed(context, &chat.name, &new_name)
4385                } else {
4386                    stock_str::msg_grp_name(context, &chat.name, &new_name, ContactId::SELF).await
4387                };
4388                msg.param.set_cmd(SystemMessage::GroupNameChanged);
4389                if !chat.name.is_empty() {
4390                    msg.param.set(Param::Arg, &chat.name);
4391                }
4392                msg.id = send_msg(context, chat_id, &mut msg).await?;
4393                context.emit_msgs_changed(chat_id, msg.id);
4394                sync = Nosync;
4395            }
4396            context.emit_event(EventType::ChatModified(chat_id));
4397            chatlist_events::emit_chatlist_item_changed(context, chat_id);
4398            success = true;
4399        }
4400    }
4401
4402    if !success {
4403        bail!("Failed to set name");
4404    }
4405    if sync.into() && chat.name != new_name {
4406        let sync_name = new_name.to_string();
4407        chat.sync(context, SyncAction::Rename(sync_name))
4408            .await
4409            .log_err(context)
4410            .ok();
4411    }
4412    Ok(())
4413}
4414
4415/// Sets a new profile image for the chat.
4416///
4417/// The profile image can only be set when you are a member of the
4418/// chat.  To remove the profile image pass an empty string for the
4419/// `new_image` parameter.
4420pub async fn set_chat_profile_image(
4421    context: &Context,
4422    chat_id: ChatId,
4423    new_image: &str, // XXX use PathBuf
4424) -> Result<()> {
4425    ensure!(!chat_id.is_special(), "Invalid chat ID");
4426    let mut chat = Chat::load_from_db(context, chat_id).await?;
4427    ensure!(
4428        chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4429        "Can only set profile image for groups / broadcasts"
4430    );
4431    ensure!(
4432        !chat.grpid.is_empty(),
4433        "Cannot set profile image for ad hoc groups"
4434    );
4435    /* we should respect this - whatever we send to the group, it gets discarded anyway! */
4436    if !chat.is_self_in_chat(context).await? {
4437        context.emit_event(EventType::ErrorSelfNotInGroup(
4438            "Cannot set chat profile image; self not in group.".into(),
4439        ));
4440        bail!("Failed to set profile image");
4441    }
4442    let mut msg = Message::new(Viewtype::Text);
4443    msg.param
4444        .set_int(Param::Cmd, SystemMessage::GroupImageChanged as i32);
4445    if new_image.is_empty() {
4446        chat.param.remove(Param::ProfileImage);
4447        msg.param.remove(Param::Arg);
4448        msg.text = if chat.typ == Chattype::OutBroadcast {
4449            stock_str::msg_broadcast_img_changed(context)
4450        } else {
4451            stock_str::msg_grp_img_deleted(context, ContactId::SELF).await
4452        };
4453    } else {
4454        let mut image_blob = BlobObject::create_and_deduplicate(
4455            context,
4456            Path::new(new_image),
4457            Path::new(new_image),
4458        )?;
4459        image_blob.recode_to_avatar_size(context).await?;
4460        chat.param.set(Param::ProfileImage, image_blob.as_name());
4461        msg.param.set(Param::Arg, image_blob.as_name());
4462        msg.text = if chat.typ == Chattype::OutBroadcast {
4463            stock_str::msg_broadcast_img_changed(context)
4464        } else {
4465            stock_str::msg_grp_img_changed(context, ContactId::SELF).await
4466        };
4467    }
4468    chat.update_param(context).await?;
4469    if chat.is_promoted() {
4470        msg.id = send_msg(context, chat_id, &mut msg).await?;
4471        context.emit_msgs_changed(chat_id, msg.id);
4472    }
4473    context.emit_event(EventType::ChatModified(chat_id));
4474    chatlist_events::emit_chatlist_item_changed(context, chat_id);
4475    Ok(())
4476}
4477
4478/// Forwards multiple messages to a chat.
4479pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) -> Result<()> {
4480    forward_msgs_2ctx(context, msg_ids, context, chat_id).await
4481}
4482
4483/// Forwards multiple messages to a chat in another context.
4484#[expect(clippy::arithmetic_side_effects)]
4485pub async fn forward_msgs_2ctx(
4486    ctx_src: &Context,
4487    msg_ids: &[MsgId],
4488    ctx_dst: &Context,
4489    chat_id: ChatId,
4490) -> Result<()> {
4491    ensure!(!msg_ids.is_empty(), "empty msgs_ids: nothing to forward");
4492    ensure!(!chat_id.is_special(), "can not forward to special chat");
4493
4494    let mut created_msgs: Vec<MsgId> = Vec::new();
4495    let mut curr_timestamp: i64;
4496
4497    chat_id
4498        .unarchive_if_not_muted(ctx_dst, MessageState::Undefined)
4499        .await?;
4500    let mut chat = Chat::load_from_db(ctx_dst, chat_id).await?;
4501    if let Some(reason) = chat.why_cant_send(ctx_dst).await? {
4502        bail!("cannot send to {chat_id}: {reason}");
4503    }
4504    curr_timestamp = create_smeared_timestamps(ctx_dst, msg_ids.len());
4505    let mut msgs = Vec::with_capacity(msg_ids.len());
4506    for id in msg_ids {
4507        let ts: i64 = ctx_src
4508            .sql
4509            .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4510            .await?
4511            .with_context(|| format!("No message {id}"))?;
4512        msgs.push((ts, *id));
4513    }
4514    msgs.sort_unstable();
4515    for (_, id) in msgs {
4516        let src_msg_id: MsgId = id;
4517        let mut msg = Message::load_from_db(ctx_src, src_msg_id).await?;
4518        if msg.state == MessageState::OutDraft {
4519            bail!("cannot forward drafts.");
4520        }
4521
4522        let mut param = msg.param;
4523        msg.param = Params::new();
4524
4525        if msg.get_viewtype() != Viewtype::Sticker {
4526            let forwarded_msg_id = match ctx_src.blobdir == ctx_dst.blobdir {
4527                true => src_msg_id,
4528                false => MsgId::new_unset(),
4529            };
4530            msg.param
4531                .set_int(Param::Forwarded, forwarded_msg_id.to_u32() as i32);
4532        }
4533
4534        if msg.get_viewtype() == Viewtype::Call {
4535            msg.viewtype = Viewtype::Text;
4536        }
4537        msg.text += &msg.additional_text;
4538
4539        let param = &mut param;
4540
4541        // When forwarding between different accounts, blob files must be physically copied
4542        // because each account has its own blob directory.
4543        if ctx_src.blobdir == ctx_dst.blobdir {
4544            msg.param.steal(param, Param::File);
4545        } else if let Some(src_path) = param.get_file_path(ctx_src)? {
4546            let new_blob = BlobObject::create_and_deduplicate(ctx_dst, &src_path, &src_path)
4547                .context("Failed to copy blob file to destination account")?;
4548            msg.param.set(Param::File, new_blob.as_name());
4549        }
4550        msg.param.steal(param, Param::Filename);
4551        msg.param.steal(param, Param::Width);
4552        msg.param.steal(param, Param::Height);
4553        msg.param.steal(param, Param::Duration);
4554        msg.param.steal(param, Param::MimeType);
4555        msg.param.steal(param, Param::ProtectQuote);
4556        msg.param.steal(param, Param::Quote);
4557        msg.param.steal(param, Param::Summary1);
4558        if msg.has_html() {
4559            msg.set_html(src_msg_id.get_html(ctx_src).await?);
4560        }
4561        msg.in_reply_to = None;
4562
4563        // do not leak data as group names; a default subject is generated by mimefactory
4564        msg.subject = "".to_string();
4565
4566        msg.state = MessageState::OutPending;
4567        msg.rfc724_mid = create_outgoing_rfc724_mid();
4568        msg.timestamp_sort = curr_timestamp;
4569        chat.prepare_msg_raw(ctx_dst, &mut msg, None).await?;
4570
4571        curr_timestamp += 1;
4572        if !create_send_msg_jobs(ctx_dst, &mut msg).await?.is_empty() {
4573            ctx_dst.scheduler.interrupt_smtp().await;
4574        }
4575        created_msgs.push(msg.id);
4576    }
4577    for msg_id in created_msgs {
4578        ctx_dst.emit_msgs_changed(chat_id, msg_id);
4579    }
4580    Ok(())
4581}
4582
4583/// Save a copy of the message in "Saved Messages"
4584/// and send a sync messages so that other devices save the message as well, unless deleted there.
4585pub async fn save_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4586    let mut msgs = Vec::with_capacity(msg_ids.len());
4587    for id in msg_ids {
4588        let ts: i64 = context
4589            .sql
4590            .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4591            .await?
4592            .with_context(|| format!("No message {id}"))?;
4593        msgs.push((ts, *id));
4594    }
4595    msgs.sort_unstable();
4596    for (_, src_msg_id) in msgs {
4597        let dest_rfc724_mid = create_outgoing_rfc724_mid();
4598        let src_rfc724_mid = save_copy_in_self_talk(context, src_msg_id, &dest_rfc724_mid).await?;
4599        context
4600            .add_sync_item(SyncData::SaveMessage {
4601                src: src_rfc724_mid,
4602                dest: dest_rfc724_mid,
4603            })
4604            .await?;
4605    }
4606    context.scheduler.interrupt_smtp().await;
4607    Ok(())
4608}
4609
4610/// Saves a copy of the given message in "Saved Messages" using the given RFC724 id.
4611/// To allow UIs to have a "show in context" button,
4612/// the copy contains a reference to the original message
4613/// as well as to the original chat in case the original message gets deleted.
4614/// Returns data needed to add a `SaveMessage` sync item.
4615#[expect(clippy::arithmetic_side_effects)]
4616pub(crate) async fn save_copy_in_self_talk(
4617    context: &Context,
4618    src_msg_id: MsgId,
4619    dest_rfc724_mid: &String,
4620) -> Result<String> {
4621    let dest_chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?;
4622    let mut msg = Message::load_from_db(context, src_msg_id).await?;
4623    msg.param.remove(Param::Cmd);
4624    msg.param.remove(Param::WebxdcDocument);
4625    msg.param.remove(Param::WebxdcDocumentTimestamp);
4626    msg.param.remove(Param::WebxdcSummary);
4627    msg.param.remove(Param::WebxdcSummaryTimestamp);
4628    msg.param.remove(Param::PostMessageFileBytes);
4629    msg.param.remove(Param::PostMessageViewtype);
4630
4631    msg.text += &msg.additional_text;
4632
4633    if !msg.original_msg_id.is_unset() {
4634        bail!("message already saved.");
4635    }
4636
4637    let copy_fields = "from_id, to_id, timestamp_rcvd, type,
4638                       mime_modified, mime_headers, mime_compressed, mime_in_reply_to, subject, msgrmsg";
4639    let row_id = context
4640        .sql
4641        .insert(
4642            &format!(
4643                "INSERT INTO msgs ({copy_fields},
4644                                   timestamp_sent,
4645                                   txt, chat_id, rfc724_mid, state, timestamp, param, starred)
4646                 SELECT            {copy_fields},
4647                                   -- Outgoing messages on originating device
4648                                   -- have timestamp_sent == 0.
4649                                   -- We copy sort timestamp instead
4650                                   -- so UIs display the same timestamp
4651                                   -- for saved and original message.
4652                                   IIF(timestamp_sent == 0, timestamp, timestamp_sent),
4653                                   ?, ?, ?, ?, ?, ?, ?
4654                 FROM msgs WHERE id=?;"
4655            ),
4656            (
4657                msg.text,
4658                dest_chat_id,
4659                dest_rfc724_mid,
4660                if msg.from_id == ContactId::SELF {
4661                    MessageState::OutDelivered
4662                } else {
4663                    MessageState::InSeen
4664                },
4665                create_smeared_timestamp(context),
4666                msg.param.to_string(),
4667                src_msg_id,
4668                src_msg_id,
4669            ),
4670        )
4671        .await?;
4672    let dest_msg_id = MsgId::new(row_id.try_into()?);
4673
4674    context.emit_msgs_changed(msg.chat_id, src_msg_id);
4675    context.emit_msgs_changed(dest_chat_id, dest_msg_id);
4676    chatlist_events::emit_chatlist_changed(context);
4677    chatlist_events::emit_chatlist_item_changed(context, dest_chat_id);
4678
4679    Ok(msg.rfc724_mid)
4680}
4681
4682/// Resends given messages with the same Message-ID.
4683///
4684/// This is primarily intended to make existing webxdcs available to new chat members.
4685pub async fn resend_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4686    let mut msgs: Vec<Message> = Vec::new();
4687    for msg_id in msg_ids {
4688        let msg = Message::load_from_db(context, *msg_id).await?;
4689        ensure!(
4690            msg.from_id == ContactId::SELF,
4691            "can resend only own messages"
4692        );
4693        ensure!(!msg.is_info(), "cannot resend info messages");
4694        msgs.push(msg)
4695    }
4696
4697    for mut msg in msgs {
4698        match msg.get_state() {
4699            // `get_state()` may return an outdated `OutPending`, so update anyway.
4700            MessageState::OutPending
4701            | MessageState::OutFailed
4702            | MessageState::OutDelivered
4703            | MessageState::OutMdnRcvd => {
4704                message::update_msg_state(context, msg.id, MessageState::OutPending).await?
4705            }
4706            msg_state => bail!("Unexpected message state {msg_state}"),
4707        }
4708        if create_send_msg_jobs(context, &mut msg).await?.is_empty() {
4709            continue;
4710        }
4711
4712        // Emit the event only after `create_send_msg_jobs`
4713        // because `create_send_msg_jobs` may change the message
4714        // encryption status and call `msg.update_param`.
4715        context.emit_event(EventType::MsgsChanged {
4716            chat_id: msg.chat_id,
4717            msg_id: msg.id,
4718        });
4719        // note(treefit): only matters if it is the last message in chat (but probably to expensive to check, debounce also solves it)
4720        chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
4721
4722        if msg.viewtype == Viewtype::Webxdc {
4723            let conn_fn = |conn: &mut rusqlite::Connection| {
4724                let range = conn.query_row(
4725                    "SELECT IFNULL(min(id), 1), IFNULL(max(id), 0) \
4726                     FROM msgs_status_updates WHERE msg_id=?",
4727                    (msg.id,),
4728                    |row| {
4729                        let min_id: StatusUpdateSerial = row.get(0)?;
4730                        let max_id: StatusUpdateSerial = row.get(1)?;
4731                        Ok((min_id, max_id))
4732                    },
4733                )?;
4734                if range.0 > range.1 {
4735                    return Ok(());
4736                };
4737                // `first_serial` must be decreased, otherwise if `Context::flush_status_updates()`
4738                // runs in parallel, it would miss the race and instead of resending just remove the
4739                // updates thinking that they have been already sent.
4740                conn.execute(
4741                    "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) \
4742                     VALUES(?, ?, ?, '') \
4743                     ON CONFLICT(msg_id) \
4744                     DO UPDATE SET first_serial=min(first_serial - 1, excluded.first_serial)",
4745                    (msg.id, range.0, range.1),
4746                )?;
4747                Ok(())
4748            };
4749            context.sql.call_write(conn_fn).await?;
4750        }
4751        context.scheduler.interrupt_smtp().await;
4752    }
4753    Ok(())
4754}
4755
4756pub(crate) async fn get_chat_cnt(context: &Context) -> Result<usize> {
4757    if context.sql.is_open().await {
4758        // no database, no chats - this is no error (needed eg. for information)
4759        let count = context
4760            .sql
4761            .count("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;", ())
4762            .await?;
4763        Ok(count)
4764    } else {
4765        Ok(0)
4766    }
4767}
4768
4769/// Returns a tuple of `(chatid, blocked)`.
4770pub(crate) async fn get_chat_id_by_grpid(
4771    context: &Context,
4772    grpid: &str,
4773) -> Result<Option<(ChatId, Blocked)>> {
4774    context
4775        .sql
4776        .query_row_optional(
4777            "SELECT id, blocked FROM chats WHERE grpid=?;",
4778            (grpid,),
4779            |row| {
4780                let chat_id = row.get::<_, ChatId>(0)?;
4781
4782                let b = row.get::<_, Option<Blocked>>(1)?.unwrap_or_default();
4783                Ok((chat_id, b))
4784            },
4785        )
4786        .await
4787}
4788
4789/// Adds a message to device chat.
4790///
4791/// Optional `label` can be provided to ensure that message is added only once.
4792/// If `important` is true, a notification will be sent.
4793#[expect(clippy::arithmetic_side_effects)]
4794pub async fn add_device_msg_with_importance(
4795    context: &Context,
4796    label: Option<&str>,
4797    msg: Option<&mut Message>,
4798    important: bool,
4799) -> Result<MsgId> {
4800    ensure!(
4801        label.is_some() || msg.is_some(),
4802        "device-messages need label, msg or both"
4803    );
4804    let mut chat_id = ChatId::new(0);
4805    let mut msg_id = MsgId::new_unset();
4806
4807    if let Some(label) = label
4808        && was_device_msg_ever_added(context, label).await?
4809    {
4810        info!(context, "Device-message {label} already added.");
4811        return Ok(msg_id);
4812    }
4813
4814    if let Some(msg) = msg {
4815        chat_id = ChatId::get_for_contact(context, ContactId::DEVICE).await?;
4816
4817        let rfc724_mid = create_outgoing_rfc724_mid();
4818        let timestamp_sent = create_smeared_timestamp(context);
4819
4820        // makes sure, the added message is the last one,
4821        // even if the date is wrong (useful esp. when warning about bad dates)
4822        msg.timestamp_sort = timestamp_sent;
4823        if let Some(last_msg_time) = chat_id.get_timestamp(context).await?
4824            && msg.timestamp_sort <= last_msg_time
4825        {
4826            msg.timestamp_sort = last_msg_time + 1;
4827        }
4828        prepare_msg_blob(context, msg).await?;
4829        let state = MessageState::InFresh;
4830        let row_id = context
4831            .sql
4832            .insert(
4833                "INSERT INTO msgs (
4834            chat_id,
4835            from_id,
4836            to_id,
4837            timestamp,
4838            timestamp_sent,
4839            timestamp_rcvd,
4840            type,state,
4841            txt,
4842            txt_normalized,
4843            param,
4844            rfc724_mid)
4845            VALUES (?,?,?,?,?,?,?,?,?,?,?,?);",
4846                (
4847                    chat_id,
4848                    ContactId::DEVICE,
4849                    ContactId::SELF,
4850                    msg.timestamp_sort,
4851                    timestamp_sent,
4852                    timestamp_sent, // timestamp_sent equals timestamp_rcvd
4853                    msg.viewtype,
4854                    state,
4855                    &msg.text,
4856                    normalize_text(&msg.text),
4857                    msg.param.to_string(),
4858                    rfc724_mid,
4859                ),
4860            )
4861            .await?;
4862        context.new_msgs_notify.notify_one();
4863
4864        msg_id = MsgId::new(u32::try_from(row_id)?);
4865        if !msg.hidden {
4866            chat_id.unarchive_if_not_muted(context, state).await?;
4867        }
4868    }
4869
4870    if let Some(label) = label {
4871        context
4872            .sql
4873            .execute("INSERT INTO devmsglabels (label) VALUES (?);", (label,))
4874            .await?;
4875    }
4876
4877    if !msg_id.is_unset() {
4878        chat_id.emit_msg_event(context, msg_id, important);
4879    }
4880
4881    Ok(msg_id)
4882}
4883
4884/// Adds a message to device chat.
4885pub async fn add_device_msg(
4886    context: &Context,
4887    label: Option<&str>,
4888    msg: Option<&mut Message>,
4889) -> Result<MsgId> {
4890    add_device_msg_with_importance(context, label, msg, false).await
4891}
4892
4893/// Returns true if device message with a given label was ever added to the device chat.
4894pub async fn was_device_msg_ever_added(context: &Context, label: &str) -> Result<bool> {
4895    ensure!(!label.is_empty(), "empty label");
4896    let exists = context
4897        .sql
4898        .exists(
4899            "SELECT COUNT(label) FROM devmsglabels WHERE label=?",
4900            (label,),
4901        )
4902        .await?;
4903
4904    Ok(exists)
4905}
4906
4907// needed on device-switches during export/import;
4908// - deletion in `msgs` with `ContactId::DEVICE` makes sure,
4909//   no wrong information are shown in the device chat
4910// - deletion in `devmsglabels` makes sure,
4911//   deleted messages are reset and useful messages can be added again
4912// - we reset the config-option `QuotaExceeding`
4913//   that is used as a helper to drive the corresponding device message.
4914pub(crate) async fn delete_and_reset_all_device_msgs(context: &Context) -> Result<()> {
4915    context
4916        .sql
4917        .execute("DELETE FROM msgs WHERE from_id=?;", (ContactId::DEVICE,))
4918        .await?;
4919    context.sql.execute("DELETE FROM devmsglabels;", ()).await?;
4920
4921    // Insert labels for welcome messages to avoid them being re-added on reconfiguration.
4922    context
4923        .sql
4924        .execute(
4925            r#"INSERT INTO devmsglabels (label) VALUES ("core-welcome-image"), ("core-welcome")"#,
4926            (),
4927        )
4928        .await?;
4929    context
4930        .set_config_internal(Config::QuotaExceeding, None)
4931        .await?;
4932    Ok(())
4933}
4934
4935/// Adds an informational message to chat.
4936///
4937/// For example, it can be a message showing that a member was added to a group.
4938/// Doesn't fail if the chat doesn't exist.
4939#[expect(clippy::too_many_arguments)]
4940pub(crate) async fn add_info_msg_with_cmd(
4941    context: &Context,
4942    chat_id: ChatId,
4943    text: &str,
4944    cmd: SystemMessage,
4945    // Timestamp where in the chat the message will be sorted.
4946    // If this is None, the message will be sorted to the bottom.
4947    timestamp_sort: Option<i64>,
4948    // Timestamp to show to the user
4949    timestamp_sent_rcvd: i64,
4950    parent: Option<&Message>,
4951    from_id: Option<ContactId>,
4952    added_removed_id: Option<ContactId>,
4953) -> Result<MsgId> {
4954    let rfc724_mid = create_outgoing_rfc724_mid();
4955    let ephemeral_timer = chat_id.get_ephemeral_timer(context).await?;
4956
4957    let mut param = Params::new();
4958    if cmd != SystemMessage::Unknown {
4959        param.set_cmd(cmd);
4960    }
4961    if let Some(contact_id) = added_removed_id {
4962        param.set(Param::ContactAddedRemoved, contact_id.to_u32().to_string());
4963    }
4964
4965    let timestamp_sort = if let Some(ts) = timestamp_sort {
4966        ts
4967    } else {
4968        let sort_to_bottom = true;
4969        chat_id
4970            .calc_sort_timestamp(context, smeared_time(context), sort_to_bottom)
4971            .await?
4972    };
4973
4974    let row_id =
4975    context.sql.insert(
4976        "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)
4977        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);",
4978        (
4979            chat_id,
4980            from_id.unwrap_or(ContactId::INFO),
4981            ContactId::INFO,
4982            timestamp_sort,
4983            timestamp_sent_rcvd,
4984            timestamp_sent_rcvd,
4985            Viewtype::Text,
4986            MessageState::InNoticed,
4987            text,
4988            normalize_text(text),
4989            rfc724_mid,
4990            ephemeral_timer,
4991            param.to_string(),
4992            parent.map(|msg|msg.rfc724_mid.clone()).unwrap_or_default()
4993        )
4994    ).await?;
4995    context.new_msgs_notify.notify_one();
4996
4997    let msg_id = MsgId::new(row_id.try_into()?);
4998    context.emit_msgs_changed(chat_id, msg_id);
4999
5000    Ok(msg_id)
5001}
5002
5003/// Adds info message with a given text and `timestamp` to the chat.
5004pub(crate) async fn add_info_msg(context: &Context, chat_id: ChatId, text: &str) -> Result<MsgId> {
5005    add_info_msg_with_cmd(
5006        context,
5007        chat_id,
5008        text,
5009        SystemMessage::Unknown,
5010        None,
5011        time(),
5012        None,
5013        None,
5014        None,
5015    )
5016    .await
5017}
5018
5019pub(crate) async fn update_msg_text_and_timestamp(
5020    context: &Context,
5021    chat_id: ChatId,
5022    msg_id: MsgId,
5023    text: &str,
5024    timestamp: i64,
5025) -> Result<()> {
5026    context
5027        .sql
5028        .execute(
5029            "UPDATE msgs SET txt=?, txt_normalized=?, timestamp=? WHERE id=?;",
5030            (text, normalize_text(text), timestamp, msg_id),
5031        )
5032        .await?;
5033    context.emit_msgs_changed(chat_id, msg_id);
5034    Ok(())
5035}
5036
5037/// Set chat contacts by their addresses creating the corresponding contacts if necessary.
5038async fn set_contacts_by_addrs(context: &Context, id: ChatId, addrs: &[String]) -> Result<()> {
5039    let chat = Chat::load_from_db(context, id).await?;
5040    ensure!(
5041        !chat.is_encrypted(context).await?,
5042        "Cannot add address-contacts to encrypted chat {id}"
5043    );
5044    ensure!(
5045        chat.typ == Chattype::OutBroadcast,
5046        "{id} is not a broadcast list",
5047    );
5048    let mut contacts = BTreeSet::new();
5049    for addr in addrs {
5050        let contact_addr = ContactAddress::new(addr)?;
5051        let contact = Contact::add_or_lookup(context, "", &contact_addr, Origin::Hidden)
5052            .await?
5053            .0;
5054        contacts.insert(contact);
5055    }
5056    let contacts_old = BTreeSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
5057    if contacts == contacts_old {
5058        return Ok(());
5059    }
5060    context
5061        .sql
5062        .transaction(move |transaction| {
5063            transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
5064
5065            // We do not care about `add_timestamp` column
5066            // because timestamps are not used for broadcast channels.
5067            let mut statement = transaction
5068                .prepare("INSERT INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)")?;
5069            for contact_id in &contacts {
5070                statement.execute((id, contact_id))?;
5071            }
5072            Ok(())
5073        })
5074        .await?;
5075    context.emit_event(EventType::ChatModified(id));
5076    Ok(())
5077}
5078
5079/// Set chat contacts by their fingerprints creating the corresponding contacts if necessary.
5080///
5081/// `fingerprint_addrs` is a list of pairs of fingerprint and address.
5082async fn set_contacts_by_fingerprints(
5083    context: &Context,
5084    id: ChatId,
5085    fingerprint_addrs: &[(String, String)],
5086) -> Result<()> {
5087    let chat = Chat::load_from_db(context, id).await?;
5088    ensure!(
5089        chat.is_encrypted(context).await?,
5090        "Cannot add key-contacts to unencrypted chat {id}"
5091    );
5092    ensure!(
5093        matches!(chat.typ, Chattype::Group | Chattype::OutBroadcast),
5094        "{id} is not a group or broadcast",
5095    );
5096    let mut contacts = BTreeSet::new();
5097    for (fingerprint, addr) in fingerprint_addrs {
5098        let contact = Contact::add_or_lookup_ex(context, "", addr, fingerprint, Origin::Hidden)
5099            .await?
5100            .0;
5101        contacts.insert(contact);
5102    }
5103    let contacts_old = BTreeSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
5104    if contacts == contacts_old {
5105        return Ok(());
5106    }
5107    let broadcast_contacts_added = context
5108        .sql
5109        .transaction(move |transaction| {
5110            // For broadcast channels, we only add members,
5111            // because we don't use the membership consistency algorithm,
5112            // and are using sync messages as a basic way to ensure consistency between devices.
5113            // For groups, we also remove members,
5114            // because the sync message is used in order to sync unpromoted groups.
5115            if chat.typ != Chattype::OutBroadcast {
5116                transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
5117            }
5118
5119            // We do not care about `add_timestamp` column
5120            // because timestamps are not used for broadcast channels.
5121            let mut statement = transaction.prepare(
5122                "INSERT OR IGNORE INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)",
5123            )?;
5124            let mut broadcast_contacts_added = Vec::new();
5125            for contact_id in &contacts {
5126                if statement.execute((id, contact_id))? > 0 && chat.typ == Chattype::OutBroadcast {
5127                    broadcast_contacts_added.push(*contact_id);
5128                }
5129            }
5130            Ok(broadcast_contacts_added)
5131        })
5132        .await?;
5133    let timestamp = smeared_time(context);
5134    for added_id in broadcast_contacts_added {
5135        let msg = stock_str::msg_add_member_local(context, added_id, ContactId::UNDEFINED).await;
5136        add_info_msg_with_cmd(
5137            context,
5138            id,
5139            &msg,
5140            SystemMessage::MemberAddedToGroup,
5141            Some(timestamp),
5142            timestamp,
5143            None,
5144            Some(ContactId::SELF),
5145            Some(added_id),
5146        )
5147        .await?;
5148    }
5149    context.emit_event(EventType::ChatModified(id));
5150    Ok(())
5151}
5152
5153/// A cross-device chat id used for synchronisation.
5154#[derive(Debug, Serialize, Deserialize, PartialEq)]
5155pub(crate) enum SyncId {
5156    /// E-mail address of the contact.
5157    ContactAddr(String),
5158
5159    /// OpenPGP key fingerprint of the contact.
5160    ContactFingerprint(String),
5161
5162    Grpid(String),
5163    /// "Message-ID"-s, from oldest to latest. Used for ad-hoc groups.
5164    Msgids(Vec<String>),
5165
5166    /// Special id for device chat.
5167    Device,
5168}
5169
5170/// An action synchronised to other devices.
5171#[derive(Debug, Serialize, Deserialize, PartialEq)]
5172pub(crate) enum SyncAction {
5173    Block,
5174    Unblock,
5175    Accept,
5176    SetVisibility(ChatVisibility),
5177    SetMuted(MuteDuration),
5178    /// Create broadcast channel with the given name.
5179    CreateOutBroadcast {
5180        chat_name: String,
5181        secret: String,
5182    },
5183    /// Create encrypted group chat with the given name.
5184    CreateGroupEncrypted(String),
5185    Rename(String),
5186    /// Set chat contacts by their addresses.
5187    SetContacts(Vec<String>),
5188    /// Set chat contacts by their fingerprints.
5189    ///
5190    /// The list is a list of pairs of fingerprint and address.
5191    SetPgpContacts(Vec<(String, String)>),
5192    SetDescription(String),
5193    Delete,
5194}
5195
5196impl Context {
5197    /// Executes [`SyncData::AlterChat`] item sent by other device.
5198    pub(crate) async fn sync_alter_chat(&self, id: &SyncId, action: &SyncAction) -> Result<()> {
5199        let chat_id = match id {
5200            SyncId::ContactAddr(addr) => {
5201                if let SyncAction::Rename(to) = action {
5202                    Contact::create_ex(self, Nosync, to, addr).await?;
5203                    return Ok(());
5204                }
5205                let addr = ContactAddress::new(addr).context("Invalid address")?;
5206                let (contact_id, _) =
5207                    Contact::add_or_lookup(self, "", &addr, Origin::Hidden).await?;
5208                match action {
5209                    SyncAction::Block => {
5210                        return contact::set_blocked(self, Nosync, contact_id, true).await;
5211                    }
5212                    SyncAction::Unblock => {
5213                        return contact::set_blocked(self, Nosync, contact_id, false).await;
5214                    }
5215                    _ => (),
5216                }
5217                // Use `Request` so that even if the program crashes, the user doesn't have to look
5218                // into the blocked contacts.
5219                ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5220                    .await?
5221                    .id
5222            }
5223            SyncId::ContactFingerprint(fingerprint) => {
5224                let name = "";
5225                let addr = "";
5226                let (contact_id, _) =
5227                    Contact::add_or_lookup_ex(self, name, addr, fingerprint, Origin::Hidden)
5228                        .await?;
5229                match action {
5230                    SyncAction::Rename(to) => {
5231                        contact_id.set_name_ex(self, Nosync, to).await?;
5232                        self.emit_event(EventType::ContactsChanged(Some(contact_id)));
5233                        return Ok(());
5234                    }
5235                    SyncAction::Block => {
5236                        return contact::set_blocked(self, Nosync, contact_id, true).await;
5237                    }
5238                    SyncAction::Unblock => {
5239                        return contact::set_blocked(self, Nosync, contact_id, false).await;
5240                    }
5241                    _ => (),
5242                }
5243                ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5244                    .await?
5245                    .id
5246            }
5247            SyncId::Grpid(grpid) => {
5248                match action {
5249                    SyncAction::CreateOutBroadcast { chat_name, secret } => {
5250                        create_out_broadcast_ex(
5251                            self,
5252                            Nosync,
5253                            grpid.to_string(),
5254                            chat_name.clone(),
5255                            secret.to_string(),
5256                        )
5257                        .await?;
5258                        return Ok(());
5259                    }
5260                    SyncAction::CreateGroupEncrypted(name) => {
5261                        create_group_ex(self, Nosync, grpid.clone(), name).await?;
5262                        return Ok(());
5263                    }
5264                    _ => {}
5265                }
5266                get_chat_id_by_grpid(self, grpid)
5267                    .await?
5268                    .with_context(|| format!("No chat for grpid '{grpid}'"))?
5269                    .0
5270            }
5271            SyncId::Msgids(msgids) => {
5272                let msg = message::get_by_rfc724_mids(self, msgids)
5273                    .await?
5274                    .with_context(|| format!("No message found for Message-IDs {msgids:?}"))?;
5275                ChatId::lookup_by_message(&msg)
5276                    .with_context(|| format!("No chat found for Message-IDs {msgids:?}"))?
5277            }
5278            SyncId::Device => ChatId::get_for_contact(self, ContactId::DEVICE).await?,
5279        };
5280        match action {
5281            SyncAction::Block => chat_id.block_ex(self, Nosync).await,
5282            SyncAction::Unblock => chat_id.unblock_ex(self, Nosync).await,
5283            SyncAction::Accept => chat_id.accept_ex(self, Nosync).await,
5284            SyncAction::SetVisibility(v) => chat_id.set_visibility_ex(self, Nosync, *v).await,
5285            SyncAction::SetMuted(duration) => set_muted_ex(self, Nosync, chat_id, *duration).await,
5286            SyncAction::CreateOutBroadcast { .. } | SyncAction::CreateGroupEncrypted(..) => {
5287                // Create action should have been handled above already.
5288                Err(anyhow!("sync_alter_chat({id:?}, {action:?}): Bad request."))
5289            }
5290            SyncAction::Rename(to) => rename_ex(self, Nosync, chat_id, to).await,
5291            SyncAction::SetDescription(to) => {
5292                set_chat_description_ex(self, Nosync, chat_id, to).await
5293            }
5294            SyncAction::SetContacts(addrs) => set_contacts_by_addrs(self, chat_id, addrs).await,
5295            SyncAction::SetPgpContacts(fingerprint_addrs) => {
5296                set_contacts_by_fingerprints(self, chat_id, fingerprint_addrs).await
5297            }
5298            SyncAction::Delete => chat_id.delete_ex(self, Nosync).await,
5299        }
5300    }
5301
5302    /// Emits the appropriate `MsgsChanged` event. Should be called if the number of unnoticed
5303    /// archived chats could decrease. In general we don't want to make an extra db query to know if
5304    /// a noticed chat is archived. Emitting events should be cheap, a false-positive `MsgsChanged`
5305    /// is ok.
5306    pub(crate) fn on_archived_chats_maybe_noticed(&self) {
5307        self.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
5308    }
5309}
5310
5311#[cfg(test)]
5312mod chat_tests;