Skip to main content

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