deltachat/
chat.rs

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