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