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