deltachat/
chat.rs

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