deltachat/
chat.rs

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