deltachat/
chat.rs

1//! # Chat module.
2
3use std::cmp;
4use std::collections::{HashMap, HashSet};
5use std::fmt;
6use std::io::Cursor;
7use std::marker::Sync;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10use std::time::Duration;
11
12use anyhow::{Context as _, Result, anyhow, bail, ensure};
13use chrono::TimeZone;
14use deltachat_contact_tools::{ContactAddress, sanitize_bidi_characters, sanitize_single_line};
15use 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::receive_imf::ReceivedMsg;
46use crate::smtp::{self, send_msg_to_smtp};
47use crate::stock_str;
48use crate::sync::{self, Sync::*, SyncData};
49use crate::tools::{
50    IsNoneOrEmpty, SystemTime, buf_compress, create_broadcast_secret, create_id,
51    create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path,
52    gm2local_offset, normalize_text, smeared_time, time, truncate_msg_text,
53};
54use crate::webxdc::StatusUpdateSerial;
55
56pub(crate) const PARAM_BROADCAST_SECRET: Param = Param::Arg3;
57
58/// An chat item, such as a message or a marker.
59#[derive(Debug, Copy, Clone, PartialEq, Eq)]
60pub enum ChatItem {
61    /// Chat message stored in the database.
62    Message {
63        /// Database ID of the message.
64        msg_id: MsgId,
65    },
66
67    /// Day marker, separating messages that correspond to different
68    /// days according to local time.
69    DayMarker {
70        /// Marker timestamp, for day markers
71        timestamp: i64,
72    },
73}
74
75/// The reason why messages cannot be sent to the chat.
76///
77/// The reason is mainly for logging and displaying in debug REPL, thus not translated.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub(crate) enum CantSendReason {
80    /// Special chat.
81    SpecialChat,
82
83    /// The chat is a device chat.
84    DeviceChat,
85
86    /// The chat is a contact request, it needs to be accepted before sending a message.
87    ContactRequest,
88
89    /// Mailing list without known List-Post header.
90    ReadOnlyMailingList,
91
92    /// Incoming broadcast channel where the user can't send messages.
93    InBroadcast,
94
95    /// Not a member of the chat.
96    NotAMember,
97
98    /// State for 1:1 chat with a key-contact that does not have a key.
99    MissingKey,
100}
101
102impl fmt::Display for CantSendReason {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            Self::SpecialChat => write!(f, "the chat is a special chat"),
106            Self::DeviceChat => write!(f, "the chat is a device chat"),
107            Self::ContactRequest => write!(
108                f,
109                "contact request chat should be accepted before sending messages"
110            ),
111            Self::ReadOnlyMailingList => {
112                write!(f, "mailing list does not have a know post address")
113            }
114            Self::InBroadcast => {
115                write!(f, "Broadcast channel is read-only")
116            }
117            Self::NotAMember => write!(f, "not a member of the chat"),
118            Self::MissingKey => write!(f, "key is missing"),
119        }
120    }
121}
122
123/// Chat ID, including reserved IDs.
124///
125/// Some chat IDs are reserved to identify special chat types.  This
126/// type can represent both the special as well as normal chats.
127#[derive(
128    Debug, Copy, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Hash, PartialOrd, Ord,
129)]
130pub struct ChatId(u32);
131
132impl ChatId {
133    /// Create a new [ChatId].
134    pub const fn new(id: u32) -> ChatId {
135        ChatId(id)
136    }
137
138    /// An unset ChatId
139    ///
140    /// This is transitional and should not be used in new code.
141    pub fn is_unset(self) -> bool {
142        self.0 == 0
143    }
144
145    /// Whether the chat ID signifies a special chat.
146    ///
147    /// This kind of chat ID can not be used for real chats.
148    pub fn is_special(self) -> bool {
149        (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)
150    }
151
152    /// Chat ID for messages which need to be deleted.
153    ///
154    /// Messages which should be deleted get this chat ID and are
155    /// deleted later.  Deleted messages need to stay around as long
156    /// as they are not deleted on the server so that their rfc724_mid
157    /// remains known and downloading them again can be avoided.
158    pub fn is_trash(self) -> bool {
159        self == DC_CHAT_ID_TRASH
160    }
161
162    /// Chat ID signifying there are **any** number of archived chats.
163    ///
164    /// This chat ID can be returned in a [`Chatlist`] and signals to
165    /// the UI to include a link to the archived chats.
166    ///
167    /// [`Chatlist`]: crate::chatlist::Chatlist
168    pub fn is_archived_link(self) -> bool {
169        self == DC_CHAT_ID_ARCHIVED_LINK
170    }
171
172    /// Virtual chat ID signalling there are **only** archived chats.
173    ///
174    /// This can be included in the chatlist if the
175    /// [`DC_GCL_ADD_ALLDONE_HINT`] flag is used to build the
176    /// [`Chatlist`].
177    ///
178    /// [`DC_GCL_ADD_ALLDONE_HINT`]: crate::constants::DC_GCL_ADD_ALLDONE_HINT
179    /// [`Chatlist`]: crate::chatlist::Chatlist
180    pub fn is_alldone_hint(self) -> bool {
181        self == DC_CHAT_ID_ALLDONE_HINT
182    }
183
184    /// Returns [`ChatId`] of a chat that `msg` belongs to.
185    pub(crate) fn lookup_by_message(msg: &Message) -> Option<Self> {
186        if msg.chat_id == DC_CHAT_ID_TRASH {
187            return None;
188        }
189        if msg.download_state == DownloadState::Undecipherable {
190            return None;
191        }
192        Some(msg.chat_id)
193    }
194
195    /// Returns the [`ChatId`] for the 1:1 chat with `contact_id`
196    /// if it exists and is not blocked.
197    ///
198    /// If the chat does not exist or is blocked, `None` is returned.
199    pub async fn lookup_by_contact(
200        context: &Context,
201        contact_id: ContactId,
202    ) -> Result<Option<Self>> {
203        let Some(chat_id_blocked) = ChatIdBlocked::lookup_by_contact(context, contact_id).await?
204        else {
205            return Ok(None);
206        };
207
208        let chat_id = match chat_id_blocked.blocked {
209            Blocked::Not | Blocked::Request => Some(chat_id_blocked.id),
210            Blocked::Yes => None,
211        };
212        Ok(chat_id)
213    }
214
215    /// Returns the [`ChatId`] for the 1:1 chat with `contact_id`.
216    ///
217    /// If the chat does not yet exist an unblocked chat ([`Blocked::Not`]) is created.
218    ///
219    /// This is an internal API, if **a user action** needs to get a chat
220    /// [`ChatId::create_for_contact`] should be used as this also scales up the
221    /// [`Contact`]'s origin.
222    pub(crate) async fn get_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
223        ChatIdBlocked::get_for_contact(context, contact_id, Blocked::Not)
224            .await
225            .map(|chat| chat.id)
226    }
227
228    /// Returns the unblocked 1:1 chat with `contact_id`.
229    ///
230    /// This should be used when **a user action** creates a chat 1:1, it ensures the chat
231    /// exists, is unblocked and scales the [`Contact`]'s origin.
232    pub async fn create_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> {
233        ChatId::create_for_contact_with_blocked(context, contact_id, Blocked::Not).await
234    }
235
236    /// Same as `create_for_contact()` with an additional `create_blocked` parameter
237    /// that is used in case the chat does not exist or to unblock existing chats.
238    /// `create_blocked` won't block already unblocked chats again.
239    pub(crate) async fn create_for_contact_with_blocked(
240        context: &Context,
241        contact_id: ContactId,
242        create_blocked: Blocked,
243    ) -> Result<Self> {
244        let chat_id = match ChatIdBlocked::lookup_by_contact(context, contact_id).await? {
245            Some(chat) => {
246                if create_blocked != Blocked::Not || chat.blocked == Blocked::Not {
247                    return Ok(chat.id);
248                }
249                chat.id.set_blocked(context, Blocked::Not).await?;
250                chat.id
251            }
252            None => {
253                if Contact::real_exists_by_id(context, contact_id).await?
254                    || contact_id == ContactId::SELF
255                {
256                    let chat_id =
257                        ChatIdBlocked::get_for_contact(context, contact_id, create_blocked)
258                            .await
259                            .map(|chat| chat.id)?;
260                    ContactId::scaleup_origin(context, &[contact_id], Origin::CreateChat).await?;
261                    chat_id
262                } else {
263                    warn!(
264                        context,
265                        "Cannot create chat, contact {contact_id} does not exist."
266                    );
267                    bail!("Can not create chat for non-existing contact");
268                }
269            }
270        };
271        context.emit_msgs_changed_without_ids();
272        chatlist_events::emit_chatlist_changed(context);
273        chatlist_events::emit_chatlist_item_changed(context, chat_id);
274        Ok(chat_id)
275    }
276
277    /// Create a group or mailinglist raw database record with the given parameters.
278    /// The function does not add SELF nor checks if the record already exists.
279    pub(crate) async fn create_multiuser_record(
280        context: &Context,
281        chattype: Chattype,
282        grpid: &str,
283        grpname: &str,
284        create_blocked: Blocked,
285        param: Option<String>,
286        timestamp: i64,
287    ) -> Result<Self> {
288        let grpname = sanitize_single_line(grpname);
289        let timestamp = cmp::min(timestamp, smeared_time(context));
290        let row_id =
291            context.sql.insert(
292                "INSERT INTO chats (type, name, name_normalized, grpid, blocked, created_timestamp, protected, param) VALUES(?, ?, ?, ?, ?, ?, 0, ?)",
293                (
294                    chattype,
295                    &grpname,
296                    normalize_text(&grpname),
297                    grpid,
298                    create_blocked,
299                    timestamp,
300                    param.unwrap_or_default(),
301                ),
302            ).await?;
303
304        let chat_id = ChatId::new(u32::try_from(row_id)?);
305        let chat = Chat::load_from_db(context, chat_id).await?;
306
307        if chat.is_encrypted(context).await? {
308            chat_id.add_e2ee_notice(context, timestamp).await?;
309        }
310
311        info!(
312            context,
313            "Created group/broadcast '{}' grpid={} as {}, blocked={}.",
314            &grpname,
315            grpid,
316            chat_id,
317            create_blocked,
318        );
319
320        Ok(chat_id)
321    }
322
323    async fn set_selfavatar_timestamp(self, context: &Context, timestamp: i64) -> Result<()> {
324        context
325            .sql
326            .execute(
327                "UPDATE contacts
328                 SET selfavatar_sent=?
329                 WHERE id IN(SELECT contact_id FROM chats_contacts WHERE chat_id=? AND add_timestamp >= remove_timestamp)",
330                (timestamp, self),
331            )
332            .await?;
333        Ok(())
334    }
335
336    /// Updates chat blocked status.
337    ///
338    /// Returns true if the value was modified.
339    pub(crate) async fn set_blocked(self, context: &Context, new_blocked: Blocked) -> Result<bool> {
340        if self.is_special() {
341            bail!("ignoring setting of Block-status for {self}");
342        }
343        let count = context
344            .sql
345            .execute(
346                "UPDATE chats SET blocked=?1 WHERE id=?2 AND blocked != ?1",
347                (new_blocked, self),
348            )
349            .await?;
350        Ok(count > 0)
351    }
352
353    /// Blocks the chat as a result of explicit user action.
354    pub async fn block(self, context: &Context) -> Result<()> {
355        self.block_ex(context, Sync).await
356    }
357
358    pub(crate) async fn block_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
359        let chat = Chat::load_from_db(context, self).await?;
360        let mut delete = false;
361
362        match chat.typ {
363            Chattype::OutBroadcast => {
364                bail!("Can't block chat of type {:?}", chat.typ)
365            }
366            Chattype::Single => {
367                for contact_id in get_chat_contacts(context, self).await? {
368                    if contact_id != ContactId::SELF {
369                        info!(
370                            context,
371                            "Blocking the contact {contact_id} to block 1:1 chat."
372                        );
373                        contact::set_blocked(context, Nosync, contact_id, true).await?;
374                    }
375                }
376            }
377            Chattype::Group => {
378                info!(context, "Can't block groups yet, deleting the chat.");
379                delete = true;
380            }
381            Chattype::Mailinglist | Chattype::InBroadcast => {
382                if self.set_blocked(context, Blocked::Yes).await? {
383                    context.emit_event(EventType::ChatModified(self));
384                }
385            }
386        }
387        chatlist_events::emit_chatlist_changed(context);
388
389        if sync.into() {
390            // NB: For a 1:1 chat this currently triggers `Contact::block()` on other devices.
391            chat.sync(context, SyncAction::Block)
392                .await
393                .log_err(context)
394                .ok();
395        }
396        if delete {
397            self.delete_ex(context, Nosync).await?;
398        }
399        Ok(())
400    }
401
402    /// Unblocks the chat.
403    pub async fn unblock(self, context: &Context) -> Result<()> {
404        self.unblock_ex(context, Sync).await
405    }
406
407    pub(crate) async fn unblock_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
408        self.set_blocked(context, Blocked::Not).await?;
409
410        chatlist_events::emit_chatlist_changed(context);
411
412        if sync.into() {
413            let chat = Chat::load_from_db(context, self).await?;
414            // TODO: For a 1:1 chat this currently triggers `Contact::unblock()` on other devices.
415            // Maybe we should unblock the contact locally too, this would also resolve discrepancy
416            // with `block()` which also blocks the contact.
417            chat.sync(context, SyncAction::Unblock)
418                .await
419                .log_err(context)
420                .ok();
421        }
422
423        Ok(())
424    }
425
426    /// Accept the contact request.
427    ///
428    /// Unblocks the chat and scales up origin of contacts.
429    pub async fn accept(self, context: &Context) -> Result<()> {
430        self.accept_ex(context, Sync).await
431    }
432
433    pub(crate) async fn accept_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
434        let chat = Chat::load_from_db(context, self).await?;
435
436        match chat.typ {
437            Chattype::Single | Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast => {
438                // Previously accepting a chat literally created a chat because unaccepted chats
439                // went to "contact requests" list rather than normal chatlist.
440                // But for groups we use lower origin because users don't always check all members
441                // before accepting a chat and may not want to have the group members mixed with
442                // existing contacts. `IncomingTo` fits here by its definition.
443                let origin = match chat.typ {
444                    Chattype::Group => Origin::IncomingTo,
445                    _ => Origin::CreateChat,
446                };
447                for contact_id in get_chat_contacts(context, self).await? {
448                    if contact_id != ContactId::SELF {
449                        ContactId::scaleup_origin(context, &[contact_id], origin).await?;
450                    }
451                }
452            }
453            Chattype::Mailinglist => {
454                // If the message is from a mailing list, the contacts are not counted as "known"
455            }
456        }
457
458        if self.set_blocked(context, Blocked::Not).await? {
459            context.emit_event(EventType::ChatModified(self));
460            chatlist_events::emit_chatlist_item_changed(context, self);
461        }
462
463        if sync.into() {
464            chat.sync(context, SyncAction::Accept)
465                .await
466                .log_err(context)
467                .ok();
468        }
469        Ok(())
470    }
471
472    /// Adds message "Messages are end-to-end encrypted".
473    pub(crate) async fn add_e2ee_notice(self, context: &Context, timestamp: i64) -> Result<()> {
474        let text = stock_str::messages_e2e_encrypted(context).await;
475        add_info_msg_with_cmd(
476            context,
477            self,
478            &text,
479            SystemMessage::ChatE2ee,
480            Some(timestamp),
481            timestamp,
482            None,
483            None,
484            None,
485        )
486        .await?;
487        Ok(())
488    }
489
490    /// Archives or unarchives a chat.
491    pub async fn set_visibility(self, context: &Context, visibility: ChatVisibility) -> Result<()> {
492        self.set_visibility_ex(context, Sync, visibility).await
493    }
494
495    pub(crate) async fn set_visibility_ex(
496        self,
497        context: &Context,
498        sync: sync::Sync,
499        visibility: ChatVisibility,
500    ) -> Result<()> {
501        ensure!(
502            !self.is_special(),
503            "bad chat_id, can not be special chat: {self}"
504        );
505
506        context
507            .sql
508            .transaction(move |transaction| {
509                if visibility == ChatVisibility::Archived {
510                    transaction.execute(
511                        "UPDATE msgs SET state=? WHERE chat_id=? AND state=?;",
512                        (MessageState::InNoticed, self, MessageState::InFresh),
513                    )?;
514                }
515                transaction.execute(
516                    "UPDATE chats SET archived=? WHERE id=?;",
517                    (visibility, self),
518                )?;
519                Ok(())
520            })
521            .await?;
522
523        if visibility == ChatVisibility::Archived {
524            start_chat_ephemeral_timers(context, self).await?;
525        }
526
527        context.emit_msgs_changed_without_ids();
528        chatlist_events::emit_chatlist_changed(context);
529        chatlist_events::emit_chatlist_item_changed(context, self);
530
531        if sync.into() {
532            let chat = Chat::load_from_db(context, self).await?;
533            chat.sync(context, SyncAction::SetVisibility(visibility))
534                .await
535                .log_err(context)
536                .ok();
537        }
538        Ok(())
539    }
540
541    /// Unarchives a chat that is archived and not muted.
542    /// Needed after a message is added to a chat so that the chat gets a normal visibility again.
543    /// `msg_state` is the state of the message. Matters only for incoming messages currently. For
544    /// multiple outgoing messages the function may be called once with MessageState::Undefined.
545    /// Sending an appropriate event is up to the caller.
546    /// Also emits DC_EVENT_MSGS_CHANGED for DC_CHAT_ID_ARCHIVED_LINK when the number of archived
547    /// chats with unread messages increases (which is possible if the chat is muted).
548    pub async fn unarchive_if_not_muted(
549        self,
550        context: &Context,
551        msg_state: MessageState,
552    ) -> Result<()> {
553        if msg_state != MessageState::InFresh {
554            context
555                .sql
556                .execute(
557                    "UPDATE chats SET archived=0 WHERE id=? AND archived=1 \
558                AND NOT(muted_until=-1 OR muted_until>?)",
559                    (self, time()),
560                )
561                .await?;
562            return Ok(());
563        }
564        let chat = Chat::load_from_db(context, self).await?;
565        if chat.visibility != ChatVisibility::Archived {
566            return Ok(());
567        }
568        if chat.is_muted() {
569            let unread_cnt = context
570                .sql
571                .count(
572                    "SELECT COUNT(*)
573                FROM msgs
574                WHERE state=?
575                AND hidden=0
576                AND chat_id=?",
577                    (MessageState::InFresh, self),
578                )
579                .await?;
580            if unread_cnt == 1 {
581                // Added the first unread message in the chat.
582                context.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
583            }
584            return Ok(());
585        }
586        context
587            .sql
588            .execute("UPDATE chats SET archived=0 WHERE id=?", (self,))
589            .await?;
590        Ok(())
591    }
592
593    /// Emits an appropriate event for a message. `important` is whether a notification should be
594    /// shown.
595    pub(crate) fn emit_msg_event(self, context: &Context, msg_id: MsgId, important: bool) {
596        if important {
597            debug_assert!(!msg_id.is_unset());
598
599            context.emit_incoming_msg(self, msg_id);
600        } else {
601            context.emit_msgs_changed(self, msg_id);
602        }
603    }
604
605    /// Deletes a chat.
606    ///
607    /// Messages are deleted from the device and the chat database entry is deleted.
608    /// After that, a `MsgsChanged` event is emitted.
609    /// Messages are deleted from the server in background.
610    pub async fn delete(self, context: &Context) -> Result<()> {
611        self.delete_ex(context, Sync).await
612    }
613
614    pub(crate) async fn delete_ex(self, context: &Context, sync: sync::Sync) -> Result<()> {
615        ensure!(
616            !self.is_special(),
617            "bad chat_id, can not be a special chat: {self}"
618        );
619
620        let chat = Chat::load_from_db(context, self).await?;
621        let sync_id = match sync {
622            Nosync => None,
623            Sync => chat.get_sync_id(context).await?,
624        };
625
626        context
627            .sql
628            .transaction(|transaction| {
629                transaction.execute(
630                    "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT rfc724_mid FROM msgs WHERE chat_id=? AND rfc724_mid!='')",
631                    (self,),
632                )?;
633                transaction.execute(
634                    "UPDATE imap SET target='' WHERE rfc724_mid IN (SELECT pre_rfc724_mid FROM msgs WHERE chat_id=? AND pre_rfc724_mid!='')",
635                    (self,),
636                )?;
637                transaction.execute(
638                    "DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?)",
639                    (self,),
640                )?;
641                // If you change which information is preserved here, also change `MsgId::trash()`
642                // and other places it references.
643                transaction.execute(
644                    "
645INSERT OR REPLACE INTO msgs (id, rfc724_mid, pre_rfc724_mid, timestamp, chat_id, deleted)
646SELECT id, rfc724_mid, pre_rfc724_mid, timestamp, ?, 1 FROM msgs WHERE chat_id=?
647                    ",
648                    (DC_CHAT_ID_TRASH, self),
649                )?;
650                transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (self,))?;
651                transaction.execute("DELETE FROM chats WHERE id=?", (self,))?;
652                Ok(())
653            })
654            .await?;
655
656        context.emit_event(EventType::ChatDeleted { chat_id: self });
657        context.emit_msgs_changed_without_ids();
658
659        if let Some(id) = sync_id {
660            self::sync(context, id, SyncAction::Delete)
661                .await
662                .log_err(context)
663                .ok();
664        }
665
666        if chat.is_self_talk() {
667            let mut msg = Message::new_text(stock_str::self_deleted_msg_body(context).await);
668            add_device_msg(context, None, Some(&mut msg)).await?;
669        }
670        chatlist_events::emit_chatlist_changed(context);
671
672        context
673            .set_config_internal(Config::LastHousekeeping, None)
674            .await?;
675        context.scheduler.interrupt_smtp().await;
676
677        Ok(())
678    }
679
680    /// Sets draft message.
681    ///
682    /// Passing `None` as message just deletes the draft
683    pub async fn set_draft(self, context: &Context, mut msg: Option<&mut Message>) -> Result<()> {
684        if self.is_special() {
685            return Ok(());
686        }
687
688        let changed = match &mut msg {
689            None => self.maybe_delete_draft(context).await?,
690            Some(msg) => self.do_set_draft(context, msg).await?,
691        };
692
693        if changed {
694            if msg.is_some() {
695                match self.get_draft_msg_id(context).await? {
696                    Some(msg_id) => context.emit_msgs_changed(self, msg_id),
697                    None => context.emit_msgs_changed_without_msg_id(self),
698                }
699            } else {
700                context.emit_msgs_changed_without_msg_id(self)
701            }
702        }
703
704        Ok(())
705    }
706
707    /// Returns ID of the draft message, if there is one.
708    async fn get_draft_msg_id(self, context: &Context) -> Result<Option<MsgId>> {
709        let msg_id: Option<MsgId> = context
710            .sql
711            .query_get_value(
712                "SELECT id FROM msgs WHERE chat_id=? AND state=?;",
713                (self, MessageState::OutDraft),
714            )
715            .await?;
716        Ok(msg_id)
717    }
718
719    /// Returns draft message, if there is one.
720    pub async fn get_draft(self, context: &Context) -> Result<Option<Message>> {
721        if self.is_special() {
722            return Ok(None);
723        }
724        match self.get_draft_msg_id(context).await? {
725            Some(draft_msg_id) => {
726                let msg = Message::load_from_db(context, draft_msg_id).await?;
727                Ok(Some(msg))
728            }
729            None => Ok(None),
730        }
731    }
732
733    /// Deletes draft message, if there is one.
734    ///
735    /// Returns `true`, if message was deleted, `false` otherwise.
736    async fn maybe_delete_draft(self, context: &Context) -> Result<bool> {
737        Ok(context
738            .sql
739            .execute(
740                "DELETE FROM msgs WHERE chat_id=? AND state=?",
741                (self, MessageState::OutDraft),
742            )
743            .await?
744            > 0)
745    }
746
747    /// Set provided message as draft message for specified chat.
748    /// Returns true if the draft was added or updated in place.
749    async fn do_set_draft(self, context: &Context, msg: &mut Message) -> Result<bool> {
750        match msg.viewtype {
751            Viewtype::Unknown => bail!("Can not set draft of unknown type."),
752            Viewtype::Text => {
753                if msg.text.is_empty() && msg.in_reply_to.is_none_or_empty() {
754                    bail!("No text and no quote in draft");
755                }
756            }
757            _ => {
758                if msg.viewtype == Viewtype::File
759                    && let Some((better_type, _)) = message::guess_msgtype_from_suffix(msg)
760                        // We do not do an automatic conversion to other viewtypes here so that
761                        // users can send images as "files" to preserve the original quality
762                        // (usually we compress images). The remaining conversions are done by
763                        // `prepare_msg_blob()` later.
764                        .filter(|&(vt, _)| vt == Viewtype::Webxdc || vt == Viewtype::Vcard)
765                {
766                    msg.viewtype = better_type;
767                }
768                if msg.viewtype == Viewtype::Vcard {
769                    let blob = msg
770                        .param
771                        .get_file_blob(context)?
772                        .context("no file stored in params")?;
773                    msg.try_set_vcard(context, &blob.to_abs_path()).await?;
774                }
775            }
776        }
777
778        // set back draft information to allow identifying the draft later on -
779        // no matter if message object is reused or reloaded from db
780        msg.state = MessageState::OutDraft;
781        msg.chat_id = self;
782
783        // if possible, replace existing draft and keep id
784        if !msg.id.is_special()
785            && let Some(old_draft) = self.get_draft(context).await?
786            && old_draft.id == msg.id
787            && old_draft.chat_id == self
788            && old_draft.state == MessageState::OutDraft
789        {
790            let affected_rows = context
791                        .sql.execute(
792                                "UPDATE msgs
793                                SET timestamp=?1,type=?2,txt=?3,txt_normalized=?4,param=?5,mime_in_reply_to=?6
794                                WHERE id=?7
795                                AND (type <> ?2 
796                                    OR txt <> ?3 
797                                    OR txt_normalized <> ?4
798                                    OR param <> ?5
799                                    OR mime_in_reply_to <> ?6);",
800                                (
801                                    time(),
802                                    msg.viewtype,
803                                    &msg.text,
804                                    normalize_text(&msg.text),
805                                    msg.param.to_string(),
806                                    msg.in_reply_to.as_deref().unwrap_or_default(),
807                                    msg.id,
808                                ),
809                            ).await?;
810            return Ok(affected_rows > 0);
811        }
812
813        let row_id = context
814            .sql
815            .transaction(|transaction| {
816                // Delete existing draft if it exists.
817                transaction.execute(
818                    "DELETE FROM msgs WHERE chat_id=? AND state=?",
819                    (self, MessageState::OutDraft),
820                )?;
821
822                // Insert new draft.
823                transaction.execute(
824                    "INSERT INTO msgs (
825                 chat_id,
826                 rfc724_mid,
827                 from_id,
828                 timestamp,
829                 type,
830                 state,
831                 txt,
832                 txt_normalized,
833                 param,
834                 hidden,
835                 mime_in_reply_to)
836         VALUES (?,?,?,?,?,?,?,?,?,?,?);",
837                    (
838                        self,
839                        &msg.rfc724_mid,
840                        ContactId::SELF,
841                        time(),
842                        msg.viewtype,
843                        MessageState::OutDraft,
844                        &msg.text,
845                        normalize_text(&msg.text),
846                        msg.param.to_string(),
847                        1,
848                        msg.in_reply_to.as_deref().unwrap_or_default(),
849                    ),
850                )?;
851
852                Ok(transaction.last_insert_rowid())
853            })
854            .await?;
855        msg.id = MsgId::new(row_id.try_into()?);
856        Ok(true)
857    }
858
859    /// Returns number of messages in a chat.
860    pub async fn get_msg_cnt(self, context: &Context) -> Result<usize> {
861        let count = context
862            .sql
863            .count(
864                "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id=?",
865                (self,),
866            )
867            .await?;
868        Ok(count)
869    }
870
871    /// Returns the number of fresh messages in the chat.
872    pub async fn get_fresh_msg_cnt(self, context: &Context) -> Result<usize> {
873        // this function is typically used to show a badge counter beside _each_ chatlist item.
874        // to make this as fast as possible, esp. on older devices, we added an combined index over the rows used for querying.
875        // so if you alter the query here, you may want to alter the index over `(state, hidden, chat_id)` in `sql.rs`.
876        //
877        // the impact of the index is significant once the database grows:
878        // - on an older android4 with 18k messages, query-time decreased from 110ms to 2ms
879        // - on an mid-class moto-g or iphone7 with 50k messages, query-time decreased from 26ms or 6ms to 0-1ms
880        // the times are average, no matter if there are fresh messages or not -
881        // and have to be multiplied by the number of items shown at once on the chatlist,
882        // so savings up to 2 seconds are possible on older devices - newer ones will feel "snappier" :)
883        let count = if self.is_archived_link() {
884            context
885                .sql
886                .count(
887                    "SELECT COUNT(DISTINCT(m.chat_id))
888                    FROM msgs m
889                    LEFT JOIN chats c ON m.chat_id=c.id
890                    WHERE m.state=10
891                    and m.hidden=0
892                    AND m.chat_id>9
893                    AND c.blocked=0
894                    AND c.archived=1
895                    ",
896                    (),
897                )
898                .await?
899        } else {
900            context
901                .sql
902                .count(
903                    "SELECT COUNT(*)
904                FROM msgs
905                WHERE state=?
906                AND hidden=0
907                AND chat_id=?;",
908                    (MessageState::InFresh, self),
909                )
910                .await?
911        };
912        Ok(count)
913    }
914
915    pub(crate) async fn created_timestamp(self, context: &Context) -> Result<i64> {
916        Ok(context
917            .sql
918            .query_get_value("SELECT created_timestamp FROM chats WHERE id=?", (self,))
919            .await?
920            .unwrap_or(0))
921    }
922
923    /// Returns timestamp of the latest message in the chat,
924    /// including hidden messages or a draft if there is one.
925    pub(crate) async fn get_timestamp(self, context: &Context) -> Result<Option<i64>> {
926        let timestamp = context
927            .sql
928            .query_get_value(
929                "SELECT MAX(timestamp)
930                 FROM msgs
931                 WHERE chat_id=?
932                 HAVING COUNT(*) > 0",
933                (self,),
934            )
935            .await?;
936        Ok(timestamp)
937    }
938
939    /// Returns a list of active similar chat IDs sorted by similarity metric.
940    ///
941    /// Jaccard similarity coefficient is used to estimate similarity of chat member sets.
942    ///
943    /// Chat is considered active if something was posted there within the last 42 days.
944    #[expect(clippy::arithmetic_side_effects)]
945    pub async fn get_similar_chat_ids(self, context: &Context) -> Result<Vec<(ChatId, f64)>> {
946        // Count number of common members in this and other chats.
947        let intersection = context
948            .sql
949            .query_map_vec(
950                "SELECT y.chat_id, SUM(x.contact_id = y.contact_id)
951                 FROM chats_contacts as x
952                 JOIN chats_contacts as y
953                 WHERE x.contact_id > 9
954                   AND y.contact_id > 9
955                   AND x.add_timestamp >= x.remove_timestamp
956                   AND y.add_timestamp >= y.remove_timestamp
957                   AND x.chat_id=?
958                   AND y.chat_id<>x.chat_id
959                   AND y.chat_id>?
960                 GROUP BY y.chat_id",
961                (self, DC_CHAT_ID_LAST_SPECIAL),
962                |row| {
963                    let chat_id: ChatId = row.get(0)?;
964                    let intersection: f64 = row.get(1)?;
965                    Ok((chat_id, intersection))
966                },
967            )
968            .await
969            .context("failed to calculate member set intersections")?;
970
971        let chat_size: HashMap<ChatId, f64> = context
972            .sql
973            .query_map_collect(
974                "SELECT chat_id, count(*) AS n
975                 FROM chats_contacts
976                 WHERE contact_id > ? AND chat_id > ?
977                 AND add_timestamp >= remove_timestamp
978                 GROUP BY chat_id",
979                (ContactId::LAST_SPECIAL, DC_CHAT_ID_LAST_SPECIAL),
980                |row| {
981                    let chat_id: ChatId = row.get(0)?;
982                    let size: f64 = row.get(1)?;
983                    Ok((chat_id, size))
984                },
985            )
986            .await
987            .context("failed to count chat member sizes")?;
988
989        let our_chat_size = chat_size.get(&self).copied().unwrap_or_default();
990        let mut chats_with_metrics = Vec::new();
991        for (chat_id, intersection_size) in intersection {
992            if intersection_size > 0.0 {
993                let other_chat_size = chat_size.get(&chat_id).copied().unwrap_or_default();
994                let union_size = our_chat_size + other_chat_size - intersection_size;
995                let metric = intersection_size / union_size;
996                chats_with_metrics.push((chat_id, metric))
997            }
998        }
999        chats_with_metrics.sort_unstable_by(|(chat_id1, metric1), (chat_id2, metric2)| {
1000            metric2
1001                .partial_cmp(metric1)
1002                .unwrap_or(chat_id2.cmp(chat_id1))
1003        });
1004
1005        // Select up to five similar active chats.
1006        let mut res = Vec::new();
1007        let now = time();
1008        for (chat_id, metric) in chats_with_metrics {
1009            if let Some(chat_timestamp) = chat_id.get_timestamp(context).await?
1010                && now > chat_timestamp + 42 * 24 * 3600
1011            {
1012                // Chat was inactive for 42 days, skip.
1013                continue;
1014            }
1015
1016            if metric < 0.1 {
1017                // Chat is unrelated.
1018                break;
1019            }
1020
1021            let chat = Chat::load_from_db(context, chat_id).await?;
1022            if chat.typ != Chattype::Group {
1023                continue;
1024            }
1025
1026            match chat.visibility {
1027                ChatVisibility::Normal | ChatVisibility::Pinned => {}
1028                ChatVisibility::Archived => continue,
1029            }
1030
1031            res.push((chat_id, metric));
1032            if res.len() >= 5 {
1033                break;
1034            }
1035        }
1036
1037        Ok(res)
1038    }
1039
1040    /// Returns similar chats as a [`Chatlist`].
1041    ///
1042    /// [`Chatlist`]: crate::chatlist::Chatlist
1043    pub async fn get_similar_chatlist(self, context: &Context) -> Result<Chatlist> {
1044        let chat_ids: Vec<ChatId> = self
1045            .get_similar_chat_ids(context)
1046            .await
1047            .context("failed to get similar chat IDs")?
1048            .into_iter()
1049            .map(|(chat_id, _metric)| chat_id)
1050            .collect();
1051        let chatlist = Chatlist::from_chat_ids(context, &chat_ids).await?;
1052        Ok(chatlist)
1053    }
1054
1055    pub(crate) async fn get_param(self, context: &Context) -> Result<Params> {
1056        let res: Option<String> = context
1057            .sql
1058            .query_get_value("SELECT param FROM chats WHERE id=?", (self,))
1059            .await?;
1060        Ok(res
1061            .map(|s| s.parse().unwrap_or_default())
1062            .unwrap_or_default())
1063    }
1064
1065    /// Returns true if the chat is not promoted.
1066    pub(crate) async fn is_unpromoted(self, context: &Context) -> Result<bool> {
1067        let param = self.get_param(context).await?;
1068        let unpromoted = param.get_bool(Param::Unpromoted).unwrap_or_default();
1069        Ok(unpromoted)
1070    }
1071
1072    /// Returns true if the chat is promoted.
1073    pub(crate) async fn is_promoted(self, context: &Context) -> Result<bool> {
1074        let promoted = !self.is_unpromoted(context).await?;
1075        Ok(promoted)
1076    }
1077
1078    /// Returns true if chat is a saved messages chat.
1079    pub async fn is_self_talk(self, context: &Context) -> Result<bool> {
1080        Ok(self.get_param(context).await?.exists(Param::Selftalk))
1081    }
1082
1083    /// Returns true if chat is a device chat.
1084    pub async fn is_device_talk(self, context: &Context) -> Result<bool> {
1085        Ok(self.get_param(context).await?.exists(Param::Devicetalk))
1086    }
1087
1088    async fn parent_query<T, F>(
1089        self,
1090        context: &Context,
1091        fields: &str,
1092        state_out_min: MessageState,
1093        f: F,
1094    ) -> Result<Option<T>>
1095    where
1096        F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
1097        T: Send + 'static,
1098    {
1099        let sql = &context.sql;
1100        let query = format!(
1101            "SELECT {fields} \
1102             FROM msgs \
1103             WHERE chat_id=? \
1104             AND ((state BETWEEN {} AND {}) OR (state >= {})) \
1105             AND NOT hidden \
1106             AND download_state={} \
1107             AND from_id != {} \
1108             ORDER BY timestamp DESC, id DESC \
1109             LIMIT 1;",
1110            MessageState::InFresh as u32,
1111            MessageState::InSeen as u32,
1112            state_out_min as u32,
1113            // Do not reply to not fully downloaded messages. Such a message could be a group chat
1114            // message that we assigned to 1:1 chat.
1115            DownloadState::Done as u32,
1116            // Do not reference info messages, they are not actually sent out
1117            // and have Message-IDs unknown to other chat members.
1118            ContactId::INFO.to_u32(),
1119        );
1120        sql.query_row_optional(&query, (self,), f).await
1121    }
1122
1123    async fn get_parent_mime_headers(
1124        self,
1125        context: &Context,
1126        state_out_min: MessageState,
1127    ) -> Result<Option<(String, String, String)>> {
1128        self.parent_query(
1129            context,
1130            "rfc724_mid, mime_in_reply_to, IFNULL(mime_references, '')",
1131            state_out_min,
1132            |row: &rusqlite::Row| {
1133                let rfc724_mid: String = row.get(0)?;
1134                let mime_in_reply_to: String = row.get(1)?;
1135                let mime_references: String = row.get(2)?;
1136                Ok((rfc724_mid, mime_in_reply_to, mime_references))
1137            },
1138        )
1139        .await
1140    }
1141
1142    /// Returns multi-line text summary of encryption preferences of all chat contacts.
1143    ///
1144    /// This can be used to find out if encryption is not available because
1145    /// keys for some users are missing or simply because the majority of the users in a group
1146    /// prefer plaintext emails.
1147    ///
1148    /// To get more verbose summary for a contact, including its key fingerprint, use [`Contact::get_encrinfo`].
1149    #[expect(clippy::arithmetic_side_effects)]
1150    pub async fn get_encryption_info(self, context: &Context) -> Result<String> {
1151        let chat = Chat::load_from_db(context, self).await?;
1152        if !chat.is_encrypted(context).await? {
1153            return Ok(stock_str::encr_none(context).await);
1154        }
1155
1156        let mut ret = stock_str::messages_e2e_encrypted(context).await + "\n";
1157
1158        for &contact_id in get_chat_contacts(context, self)
1159            .await?
1160            .iter()
1161            .filter(|&contact_id| !contact_id.is_special())
1162        {
1163            let contact = Contact::get_by_id(context, contact_id).await?;
1164            let addr = contact.get_addr();
1165            logged_debug_assert!(
1166                context,
1167                contact.is_key_contact(),
1168                "get_encryption_info: contact {contact_id} is not a key-contact."
1169            );
1170            let fingerprint = contact
1171                .fingerprint()
1172                .context("Contact does not have a fingerprint in encrypted chat")?;
1173            if contact.public_key(context).await?.is_some() {
1174                ret += &format!("\n{addr}\n{fingerprint}\n");
1175            } else {
1176                ret += &format!("\n{addr}\n(key missing)\n{fingerprint}\n");
1177            }
1178        }
1179
1180        Ok(ret.trim().to_string())
1181    }
1182
1183    /// Bad evil escape hatch.
1184    ///
1185    /// Avoid using this, eventually types should be cleaned up enough
1186    /// that it is no longer necessary.
1187    pub fn to_u32(self) -> u32 {
1188        self.0
1189    }
1190
1191    pub(crate) async fn reset_gossiped_timestamp(self, context: &Context) -> Result<()> {
1192        context
1193            .sql
1194            .execute("DELETE FROM gossip_timestamp WHERE chat_id=?", (self,))
1195            .await?;
1196        Ok(())
1197    }
1198
1199    /// Returns the sort timestamp for a new message in the chat.
1200    ///
1201    /// `message_timestamp` should be either the message "sent" timestamp or a timestamp of the
1202    /// corresponding event in case of a system message (usually the current system time).
1203    /// `always_sort_to_bottom` makes this adjust the returned timestamp up so that the message goes
1204    /// to the chat bottom.
1205    /// `received` -- whether the message is received. Otherwise being sent.
1206    /// `incoming` -- whether the message is incoming.
1207    pub(crate) async fn calc_sort_timestamp(
1208        self,
1209        context: &Context,
1210        message_timestamp: i64,
1211        always_sort_to_bottom: bool,
1212        received: bool,
1213        incoming: bool,
1214    ) -> Result<i64> {
1215        let mut sort_timestamp = cmp::min(message_timestamp, smeared_time(context));
1216
1217        let last_msg_time: Option<i64> = if always_sort_to_bottom {
1218            // get newest message for this chat
1219
1220            // Let hidden messages also be ordered with protection messages because hidden messages
1221            // also can be or not be verified, so let's preserve this information -- even it's not
1222            // used currently, it can be useful in the future versions.
1223            context
1224                .sql
1225                .query_get_value(
1226                    "SELECT MAX(timestamp)
1227                     FROM msgs
1228                     WHERE chat_id=? AND state!=?
1229                     HAVING COUNT(*) > 0",
1230                    (self, MessageState::OutDraft),
1231                )
1232                .await?
1233        } else if received {
1234            // Received messages shouldn't mingle with just sent ones and appear somewhere in the
1235            // middle of the chat, so we go after the newest non fresh message.
1236            //
1237            // But if a received outgoing message is older than some seen message, better sort the
1238            // received message purely by timestamp. We could place it just before that seen
1239            // message, but anyway the user may not notice it.
1240            //
1241            // NB: Received outgoing messages may break sorting of fresh incoming ones, but this
1242            // shouldn't happen frequently. Seen incoming messages don't really break sorting of
1243            // fresh ones, they rather mean that older incoming messages are actually seen as well.
1244            context
1245                .sql
1246                .query_row_optional(
1247                    "SELECT MAX(timestamp), MAX(IIF(state=?,timestamp_sent,0))
1248                     FROM msgs
1249                     WHERE chat_id=? AND hidden=0 AND state>?
1250                     HAVING COUNT(*) > 0",
1251                    (MessageState::InSeen, self, MessageState::InFresh),
1252                    |row| {
1253                        let ts: i64 = row.get(0)?;
1254                        let ts_sent_seen: i64 = row.get(1)?;
1255                        Ok((ts, ts_sent_seen))
1256                    },
1257                )
1258                .await?
1259                .and_then(|(ts, ts_sent_seen)| {
1260                    match incoming || ts_sent_seen <= message_timestamp {
1261                        true => Some(ts),
1262                        false => None,
1263                    }
1264                })
1265        } else {
1266            None
1267        };
1268
1269        if let Some(last_msg_time) = last_msg_time
1270            && last_msg_time > sort_timestamp
1271        {
1272            sort_timestamp = last_msg_time;
1273        }
1274
1275        Ok(sort_timestamp)
1276    }
1277}
1278
1279impl std::fmt::Display for ChatId {
1280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1281        if self.is_trash() {
1282            write!(f, "Chat#Trash")
1283        } else if self.is_archived_link() {
1284            write!(f, "Chat#ArchivedLink")
1285        } else if self.is_alldone_hint() {
1286            write!(f, "Chat#AlldoneHint")
1287        } else if self.is_special() {
1288            write!(f, "Chat#Special{}", self.0)
1289        } else {
1290            write!(f, "Chat#{}", self.0)
1291        }
1292    }
1293}
1294
1295/// Allow converting [ChatId] to an SQLite type.
1296///
1297/// This allows you to directly store [ChatId] into the database as
1298/// well as query for a [ChatId].
1299impl rusqlite::types::ToSql for ChatId {
1300    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
1301        let val = rusqlite::types::Value::Integer(i64::from(self.0));
1302        let out = rusqlite::types::ToSqlOutput::Owned(val);
1303        Ok(out)
1304    }
1305}
1306
1307/// Allow converting an SQLite integer directly into [ChatId].
1308impl rusqlite::types::FromSql for ChatId {
1309    fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
1310        i64::column_result(value).and_then(|val| {
1311            if 0 <= val && val <= i64::from(u32::MAX) {
1312                Ok(ChatId::new(val as u32))
1313            } else {
1314                Err(rusqlite::types::FromSqlError::OutOfRange(val))
1315            }
1316        })
1317    }
1318}
1319
1320/// An object representing a single chat in memory.
1321/// Chat objects are created using eg. `Chat::load_from_db`
1322/// and are not updated on database changes;
1323/// if you want an update, you have to recreate the object.
1324#[derive(Debug, Clone, Deserialize, Serialize)]
1325pub struct Chat {
1326    /// Database ID.
1327    pub id: ChatId,
1328
1329    /// Chat type, e.g. 1:1 chat, group chat, mailing list.
1330    pub typ: Chattype,
1331
1332    /// Chat name.
1333    pub name: String,
1334
1335    /// Whether the chat is archived or pinned.
1336    pub visibility: ChatVisibility,
1337
1338    /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and
1339    /// ad-hoc groups.
1340    pub grpid: String,
1341
1342    /// Whether the chat is blocked, unblocked or a contact request.
1343    pub blocked: Blocked,
1344
1345    /// Additional chat parameters stored in the database.
1346    pub param: Params,
1347
1348    /// If location streaming is enabled in the chat.
1349    is_sending_locations: bool,
1350
1351    /// Duration of the chat being muted.
1352    pub mute_duration: MuteDuration,
1353}
1354
1355impl Chat {
1356    /// Loads chat from the database by its ID.
1357    pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> {
1358        let mut chat = context
1359            .sql
1360            .query_row(
1361                "SELECT c.type, c.name, c.grpid, c.param, c.archived,
1362                    c.blocked, c.locations_send_until, c.muted_until
1363             FROM chats c
1364             WHERE c.id=?;",
1365                (chat_id,),
1366                |row| {
1367                    let c = Chat {
1368                        id: chat_id,
1369                        typ: row.get(0)?,
1370                        name: row.get::<_, String>(1)?,
1371                        grpid: row.get::<_, String>(2)?,
1372                        param: row.get::<_, String>(3)?.parse().unwrap_or_default(),
1373                        visibility: row.get(4)?,
1374                        blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
1375                        is_sending_locations: row.get(6)?,
1376                        mute_duration: row.get(7)?,
1377                    };
1378                    Ok(c)
1379                },
1380            )
1381            .await
1382            .context(format!("Failed loading chat {chat_id} from database"))?;
1383
1384        if chat.id.is_archived_link() {
1385            chat.name = stock_str::archived_chats(context).await;
1386        } else {
1387            if chat.typ == Chattype::Single && chat.name.is_empty() {
1388                // chat.name is set to contact.display_name on changes,
1389                // however, if things went wrong somehow, we do this here explicitly.
1390                let mut chat_name = "Err [Name not found]".to_owned();
1391                match get_chat_contacts(context, chat.id).await {
1392                    Ok(contacts) => {
1393                        if let Some(contact_id) = contacts.first()
1394                            && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1395                        {
1396                            contact.get_display_name().clone_into(&mut chat_name);
1397                        }
1398                    }
1399                    Err(err) => {
1400                        error!(
1401                            context,
1402                            "Failed to load contacts for {}: {:#}.", chat.id, err
1403                        );
1404                    }
1405                }
1406                chat.name = chat_name;
1407            }
1408            if chat.param.exists(Param::Selftalk) {
1409                chat.name = stock_str::saved_messages(context).await;
1410            } else if chat.param.exists(Param::Devicetalk) {
1411                chat.name = stock_str::device_messages(context).await;
1412            }
1413        }
1414
1415        Ok(chat)
1416    }
1417
1418    /// Returns whether this is the `saved messages` chat
1419    pub fn is_self_talk(&self) -> bool {
1420        self.param.exists(Param::Selftalk)
1421    }
1422
1423    /// Returns true if chat is a device chat.
1424    pub fn is_device_talk(&self) -> bool {
1425        self.param.exists(Param::Devicetalk)
1426    }
1427
1428    /// Returns true if chat is a mailing list.
1429    pub fn is_mailing_list(&self) -> bool {
1430        self.typ == Chattype::Mailinglist
1431    }
1432
1433    /// Returns None if user can send messages to this chat.
1434    ///
1435    /// Otherwise returns a reason useful for logging.
1436    pub(crate) async fn why_cant_send(&self, context: &Context) -> Result<Option<CantSendReason>> {
1437        self.why_cant_send_ex(context, &|_| false).await
1438    }
1439
1440    pub(crate) async fn why_cant_send_ex(
1441        &self,
1442        context: &Context,
1443        skip_fn: &(dyn Send + Sync + Fn(&CantSendReason) -> bool),
1444    ) -> Result<Option<CantSendReason>> {
1445        use CantSendReason::*;
1446        // NB: Don't forget to update Chatlist::try_load() when changing this function!
1447
1448        if self.id.is_special() {
1449            let reason = SpecialChat;
1450            if !skip_fn(&reason) {
1451                return Ok(Some(reason));
1452            }
1453        }
1454        if self.is_device_talk() {
1455            let reason = DeviceChat;
1456            if !skip_fn(&reason) {
1457                return Ok(Some(reason));
1458            }
1459        }
1460        if self.is_contact_request() {
1461            let reason = ContactRequest;
1462            if !skip_fn(&reason) {
1463                return Ok(Some(reason));
1464            }
1465        }
1466        if self.is_mailing_list() && self.get_mailinglist_addr().is_none_or_empty() {
1467            let reason = ReadOnlyMailingList;
1468            if !skip_fn(&reason) {
1469                return Ok(Some(reason));
1470            }
1471        }
1472        if self.typ == Chattype::InBroadcast {
1473            let reason = InBroadcast;
1474            if !skip_fn(&reason) {
1475                return Ok(Some(reason));
1476            }
1477        }
1478
1479        // Do potentially slow checks last and after calls to `skip_fn` which should be fast.
1480        let reason = NotAMember;
1481        if !skip_fn(&reason) && !self.is_self_in_chat(context).await? {
1482            return Ok(Some(reason));
1483        }
1484
1485        let reason = MissingKey;
1486        if !skip_fn(&reason) && self.typ == Chattype::Single {
1487            let contact_ids = get_chat_contacts(context, self.id).await?;
1488            if let Some(contact_id) = contact_ids.first() {
1489                let contact = Contact::get_by_id(context, *contact_id).await?;
1490                if contact.is_key_contact() && contact.public_key(context).await?.is_none() {
1491                    return Ok(Some(reason));
1492                }
1493            }
1494        }
1495
1496        Ok(None)
1497    }
1498
1499    /// Returns true if can send to the chat.
1500    ///
1501    /// This function can be used by the UI to decide whether to display the input box.
1502    pub async fn can_send(&self, context: &Context) -> Result<bool> {
1503        Ok(self.why_cant_send(context).await?.is_none())
1504    }
1505
1506    /// Checks if the user is part of a chat
1507    /// and has basically the permissions to edit the chat therefore.
1508    /// The function does not check if the chat type allows editing of concrete elements.
1509    pub async fn is_self_in_chat(&self, context: &Context) -> Result<bool> {
1510        match self.typ {
1511            Chattype::Single | Chattype::OutBroadcast | Chattype::Mailinglist => Ok(true),
1512            Chattype::Group | Chattype::InBroadcast => {
1513                is_contact_in_chat(context, self.id, ContactId::SELF).await
1514            }
1515        }
1516    }
1517
1518    pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {
1519        context
1520            .sql
1521            .execute(
1522                "UPDATE chats SET param=? WHERE id=?",
1523                (self.param.to_string(), self.id),
1524            )
1525            .await?;
1526        Ok(())
1527    }
1528
1529    /// Returns chat ID.
1530    pub fn get_id(&self) -> ChatId {
1531        self.id
1532    }
1533
1534    /// Returns chat type.
1535    pub fn get_type(&self) -> Chattype {
1536        self.typ
1537    }
1538
1539    /// Returns chat name.
1540    pub fn get_name(&self) -> &str {
1541        &self.name
1542    }
1543
1544    /// Returns mailing list address where messages are sent to.
1545    pub fn get_mailinglist_addr(&self) -> Option<&str> {
1546        self.param.get(Param::ListPost)
1547    }
1548
1549    /// Returns profile image path for the chat.
1550    pub async fn get_profile_image(&self, context: &Context) -> Result<Option<PathBuf>> {
1551        if self.id.is_archived_link() {
1552            // This is not a real chat, but the "Archive" button
1553            // that is shown at the top of the chats list
1554            return Ok(Some(get_archive_icon(context).await?));
1555        } else if self.is_device_talk() {
1556            return Ok(Some(get_device_icon(context).await?));
1557        } else if self.is_self_talk() {
1558            return Ok(Some(get_saved_messages_icon(context).await?));
1559        } else if !self.is_encrypted(context).await? {
1560            // This is an unencrypted chat, show a special avatar that marks it as such.
1561            return Ok(Some(get_abs_path(
1562                context,
1563                Path::new(&get_unencrypted_icon(context).await?),
1564            )));
1565        } else if self.typ == Chattype::Single {
1566            // For 1:1 chats, we always use the same avatar as for the contact
1567            // This is before the `self.is_encrypted()` check, because that function
1568            // has two database calls, i.e. it's slow
1569            let contacts = get_chat_contacts(context, self.id).await?;
1570            if let Some(contact_id) = contacts.first() {
1571                let contact = Contact::get_by_id(context, *contact_id).await?;
1572                return contact.get_profile_image(context).await;
1573            }
1574        } else if let Some(image_rel) = self.param.get(Param::ProfileImage) {
1575            // Load the group avatar, or the device-chat / saved-messages icon
1576            if !image_rel.is_empty() {
1577                return Ok(Some(get_abs_path(context, Path::new(&image_rel))));
1578            }
1579        }
1580        Ok(None)
1581    }
1582
1583    /// Returns chat avatar color.
1584    ///
1585    /// For 1:1 chats, the color is calculated from the contact's address
1586    /// for address-contacts and from the OpenPGP key fingerprint for key-contacts.
1587    /// For group chats the color is calculated from the grpid, if present, or the chat name.
1588    pub async fn get_color(&self, context: &Context) -> Result<u32> {
1589        let mut color = 0;
1590
1591        if self.typ == Chattype::Single {
1592            let contacts = get_chat_contacts(context, self.id).await?;
1593            if let Some(contact_id) = contacts.first()
1594                && let Ok(contact) = Contact::get_by_id(context, *contact_id).await
1595            {
1596                color = contact.get_color();
1597            }
1598        } else if !self.grpid.is_empty() {
1599            color = str_to_color(&self.grpid);
1600        } else {
1601            color = str_to_color(&self.name);
1602        }
1603
1604        Ok(color)
1605    }
1606
1607    /// Returns a struct describing the current state of the chat.
1608    ///
1609    /// This is somewhat experimental, even more so than the rest of
1610    /// deltachat, and the data returned is still subject to change.
1611    pub async fn get_info(&self, context: &Context) -> Result<ChatInfo> {
1612        let draft = match self.id.get_draft(context).await? {
1613            Some(message) => message.text,
1614            _ => String::new(),
1615        };
1616        Ok(ChatInfo {
1617            id: self.id,
1618            type_: self.typ as u32,
1619            name: self.name.clone(),
1620            archived: self.visibility == ChatVisibility::Archived,
1621            param: self.param.to_string(),
1622            is_sending_locations: self.is_sending_locations,
1623            color: self.get_color(context).await?,
1624            profile_image: self
1625                .get_profile_image(context)
1626                .await?
1627                .unwrap_or_else(std::path::PathBuf::new),
1628            draft,
1629            is_muted: self.is_muted(),
1630            ephemeral_timer: self.id.get_ephemeral_timer(context).await?,
1631        })
1632    }
1633
1634    /// Returns chat visibilitiy, e.g. whether it is archived or pinned.
1635    pub fn get_visibility(&self) -> ChatVisibility {
1636        self.visibility
1637    }
1638
1639    /// Returns true if chat is a contact request.
1640    ///
1641    /// Messages cannot be sent to such chat and read receipts are not
1642    /// sent until the chat is manually unblocked.
1643    pub fn is_contact_request(&self) -> bool {
1644        self.blocked == Blocked::Request
1645    }
1646
1647    /// Returns true if the chat is not promoted.
1648    pub fn is_unpromoted(&self) -> bool {
1649        self.param.get_bool(Param::Unpromoted).unwrap_or_default()
1650    }
1651
1652    /// Returns true if the chat is promoted.
1653    /// This means a message has been sent to it and it _not_ only exists on the users device.
1654    pub fn is_promoted(&self) -> bool {
1655        !self.is_unpromoted()
1656    }
1657
1658    /// Returns true if the chat is encrypted.
1659    pub async fn is_encrypted(&self, context: &Context) -> Result<bool> {
1660        let is_encrypted = self.is_self_talk()
1661            || match self.typ {
1662                Chattype::Single => {
1663                    match context
1664                        .sql
1665                        .query_row_optional(
1666                            "SELECT cc.contact_id, c.fingerprint<>''
1667                             FROM chats_contacts cc LEFT JOIN contacts c
1668                                 ON c.id=cc.contact_id
1669                             WHERE cc.chat_id=?
1670                            ",
1671                            (self.id,),
1672                            |row| {
1673                                let id: ContactId = row.get(0)?;
1674                                let is_key: bool = row.get(1)?;
1675                                Ok((id, is_key))
1676                            },
1677                        )
1678                        .await?
1679                    {
1680                        Some((id, is_key)) => is_key || id == ContactId::DEVICE,
1681                        None => true,
1682                    }
1683                }
1684                Chattype::Group => {
1685                    // Do not encrypt ad-hoc groups.
1686                    !self.grpid.is_empty()
1687                }
1688                Chattype::Mailinglist => false,
1689                Chattype::OutBroadcast | Chattype::InBroadcast => true,
1690            };
1691        Ok(is_encrypted)
1692    }
1693
1694    /// Returns true if location streaming is enabled in the chat.
1695    pub fn is_sending_locations(&self) -> bool {
1696        self.is_sending_locations
1697    }
1698
1699    /// Returns true if the chat is currently muted.
1700    pub fn is_muted(&self) -> bool {
1701        match self.mute_duration {
1702            MuteDuration::NotMuted => false,
1703            MuteDuration::Forever => true,
1704            MuteDuration::Until(when) => when > SystemTime::now(),
1705        }
1706    }
1707
1708    /// Returns chat member list timestamp.
1709    pub(crate) async fn member_list_timestamp(&self, context: &Context) -> Result<i64> {
1710        if let Some(member_list_timestamp) = self.param.get_i64(Param::MemberListTimestamp) {
1711            Ok(member_list_timestamp)
1712        } else {
1713            Ok(self.id.created_timestamp(context).await?)
1714        }
1715    }
1716
1717    /// Returns true if member list is stale,
1718    /// i.e. has not been updated for 60 days.
1719    ///
1720    /// This is used primarily to detect the case
1721    /// where the user just restored an old backup.
1722    pub(crate) async fn member_list_is_stale(&self, context: &Context) -> Result<bool> {
1723        let now = time();
1724        let member_list_ts = self.member_list_timestamp(context).await?;
1725        let is_stale = now.saturating_add(TIMESTAMP_SENT_TOLERANCE)
1726            >= member_list_ts.saturating_add(60 * 24 * 3600);
1727        Ok(is_stale)
1728    }
1729
1730    /// Adds missing values to the msg object,
1731    /// writes the record to the database.
1732    ///
1733    /// If `update_msg_id` is set, that record is reused;
1734    /// if `update_msg_id` is None, a new record is created.
1735    #[expect(clippy::arithmetic_side_effects)]
1736    async fn prepare_msg_raw(
1737        &mut self,
1738        context: &Context,
1739        msg: &mut Message,
1740        update_msg_id: Option<MsgId>,
1741    ) -> Result<()> {
1742        let mut to_id = 0;
1743        let mut location_id = 0;
1744
1745        if msg.rfc724_mid.is_empty() {
1746            msg.rfc724_mid = create_outgoing_rfc724_mid();
1747        }
1748
1749        if self.typ == Chattype::Single {
1750            if let Some(id) = context
1751                .sql
1752                .query_get_value(
1753                    "SELECT contact_id FROM chats_contacts WHERE chat_id=?;",
1754                    (self.id,),
1755                )
1756                .await?
1757            {
1758                to_id = id;
1759            } else {
1760                error!(
1761                    context,
1762                    "Cannot send message, contact for {} not found.", self.id,
1763                );
1764                bail!("Cannot set message, contact for {} not found.", self.id);
1765            }
1766        } else if matches!(self.typ, Chattype::Group | Chattype::OutBroadcast)
1767            && self.param.get_int(Param::Unpromoted).unwrap_or_default() == 1
1768        {
1769            msg.param.set_int(Param::AttachChatAvatarAndDescription, 1);
1770            self.param
1771                .remove(Param::Unpromoted)
1772                .set_i64(Param::GroupNameTimestamp, msg.timestamp_sort)
1773                .set_i64(Param::GroupDescriptionTimestamp, msg.timestamp_sort);
1774            self.update_param(context).await?;
1775            // TODO: Remove this compat code needed because Core <= v1.143:
1776            // - doesn't accept synchronization of QR code tokens for unpromoted groups, so we also
1777            //   send them when the group is promoted.
1778            // - doesn't sync QR code tokens for unpromoted groups and the group might be created
1779            //   before an upgrade.
1780            context
1781                .sync_qr_code_tokens(Some(self.grpid.as_str()))
1782                .await
1783                .log_err(context)
1784                .ok();
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
3898    let sync_qr_code_tokens;
3899    if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {
3900        let smeared_time = smeared_time(context);
3901        chat.param
3902            .remove(Param::Unpromoted)
3903            .set_i64(Param::GroupNameTimestamp, smeared_time)
3904            .set_i64(Param::GroupDescriptionTimestamp, smeared_time);
3905        chat.update_param(context).await?;
3906        sync_qr_code_tokens = true;
3907    } else {
3908        sync_qr_code_tokens = false;
3909    }
3910
3911    if context.is_self_addr(contact.get_addr()).await? {
3912        // ourself is added using ContactId::SELF, do not add this address explicitly.
3913        // if SELF is not in the group, members cannot be added at all.
3914        warn!(
3915            context,
3916            "Invalid attempt to add self e-mail address to group."
3917        );
3918        return Ok(false);
3919    }
3920
3921    if is_contact_in_chat(context, chat_id, contact_id).await? {
3922        if !from_handshake {
3923            return Ok(true);
3924        }
3925    } else {
3926        // else continue and send status mail
3927        add_to_chat_contacts_table(context, time(), chat_id, &[contact_id]).await?;
3928    }
3929    if chat.is_promoted() {
3930        msg.viewtype = Viewtype::Text;
3931
3932        let contact_addr = contact.get_addr().to_lowercase();
3933        let added_by = if from_handshake && chat.typ == Chattype::OutBroadcast {
3934            // The contact was added via a QR code rather than explicit user action,
3935            // so it could be confusing to say 'You added member Alice'.
3936            // And in a broadcast, SELF is the only one who can add members,
3937            // so, no information is lost by just writing 'Member Alice added' instead.
3938            ContactId::UNDEFINED
3939        } else {
3940            ContactId::SELF
3941        };
3942        msg.text = stock_str::msg_add_member_local(context, contact.id, added_by).await;
3943        msg.param.set_cmd(SystemMessage::MemberAddedToGroup);
3944        msg.param.set(Param::Arg, contact_addr);
3945        msg.param.set_int(Param::Arg2, from_handshake.into());
3946        let fingerprint = contact.fingerprint().map(|f| f.hex());
3947        msg.param.set_optional(Param::Arg4, fingerprint);
3948        msg.param
3949            .set_int(Param::ContactAddedRemoved, contact.id.to_u32() as i32);
3950        if chat.typ == Chattype::OutBroadcast {
3951            let secret = load_broadcast_secret(context, chat_id)
3952                .await?
3953                .context("Failed to find broadcast shared secret")?;
3954            msg.param.set(PARAM_BROADCAST_SECRET, secret);
3955        }
3956        send_msg(context, chat_id, &mut msg).await?;
3957
3958        sync = Nosync;
3959        // TODO: Remove this compat code needed because Core <= v1.143:
3960        // - doesn't accept synchronization of QR code tokens for unpromoted groups, so we also send
3961        //   them when the group is promoted.
3962        // - doesn't sync QR code tokens for unpromoted groups and the group might be created before
3963        //   an upgrade.
3964        if sync_qr_code_tokens
3965            && context
3966                .sync_qr_code_tokens(Some(chat.grpid.as_str()))
3967                .await
3968                .log_err(context)
3969                .is_ok()
3970        {
3971            context.scheduler.interrupt_smtp().await;
3972        }
3973    }
3974    context.emit_event(EventType::ChatModified(chat_id));
3975    if sync.into() {
3976        chat.sync_contacts(context).await.log_err(context).ok();
3977    }
3978    Ok(true)
3979}
3980
3981/// Returns true if an avatar should be attached in the given chat.
3982///
3983/// This function does not check if the avatar is set.
3984/// If avatar is not set and this function returns `true`,
3985/// a `Chat-User-Avatar: 0` header should be sent to reset the avatar.
3986#[expect(clippy::arithmetic_side_effects)]
3987pub(crate) async fn shall_attach_selfavatar(context: &Context, chat_id: ChatId) -> Result<bool> {
3988    let timestamp_some_days_ago = time() - DC_RESEND_USER_AVATAR_DAYS * 24 * 60 * 60;
3989    let needs_attach = context
3990        .sql
3991        .query_map(
3992            "SELECT c.selfavatar_sent
3993             FROM chats_contacts cc
3994             LEFT JOIN contacts c ON c.id=cc.contact_id
3995             WHERE cc.chat_id=? AND cc.contact_id!=? AND cc.add_timestamp >= cc.remove_timestamp",
3996            (chat_id, ContactId::SELF),
3997            |row| {
3998                let selfavatar_sent: i64 = row.get(0)?;
3999                Ok(selfavatar_sent)
4000            },
4001            |rows| {
4002                let mut needs_attach = false;
4003                for row in rows {
4004                    let selfavatar_sent = row?;
4005                    if selfavatar_sent < timestamp_some_days_ago {
4006                        needs_attach = true;
4007                    }
4008                }
4009                Ok(needs_attach)
4010            },
4011        )
4012        .await?;
4013    Ok(needs_attach)
4014}
4015
4016/// Chat mute duration.
4017#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
4018pub enum MuteDuration {
4019    /// Chat is not muted.
4020    NotMuted,
4021
4022    /// Chat is muted until the user unmutes the chat.
4023    Forever,
4024
4025    /// Chat is muted for a limited period of time.
4026    Until(std::time::SystemTime),
4027}
4028
4029impl rusqlite::types::ToSql for MuteDuration {
4030    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
4031        let duration: i64 = match &self {
4032            MuteDuration::NotMuted => 0,
4033            MuteDuration::Forever => -1,
4034            MuteDuration::Until(when) => {
4035                let duration = when
4036                    .duration_since(SystemTime::UNIX_EPOCH)
4037                    .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
4038                i64::try_from(duration.as_secs())
4039                    .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?
4040            }
4041        };
4042        let val = rusqlite::types::Value::Integer(duration);
4043        let out = rusqlite::types::ToSqlOutput::Owned(val);
4044        Ok(out)
4045    }
4046}
4047
4048impl rusqlite::types::FromSql for MuteDuration {
4049    fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
4050        // Negative values other than -1 should not be in the
4051        // database.  If found they'll be NotMuted.
4052        match i64::column_result(value)? {
4053            0 => Ok(MuteDuration::NotMuted),
4054            -1 => Ok(MuteDuration::Forever),
4055            n if n > 0 => match SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(n as u64)) {
4056                Some(t) => Ok(MuteDuration::Until(t)),
4057                None => Err(rusqlite::types::FromSqlError::OutOfRange(n)),
4058            },
4059            _ => Ok(MuteDuration::NotMuted),
4060        }
4061    }
4062}
4063
4064/// Mutes the chat for a given duration or unmutes it.
4065pub async fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuration) -> Result<()> {
4066    set_muted_ex(context, Sync, chat_id, duration).await
4067}
4068
4069pub(crate) async fn set_muted_ex(
4070    context: &Context,
4071    sync: sync::Sync,
4072    chat_id: ChatId,
4073    duration: MuteDuration,
4074) -> Result<()> {
4075    ensure!(!chat_id.is_special(), "Invalid chat ID");
4076    context
4077        .sql
4078        .execute(
4079            "UPDATE chats SET muted_until=? WHERE id=?;",
4080            (duration, chat_id),
4081        )
4082        .await
4083        .context(format!("Failed to set mute duration for {chat_id}"))?;
4084    context.emit_event(EventType::ChatModified(chat_id));
4085    chatlist_events::emit_chatlist_item_changed(context, chat_id);
4086    if sync.into() {
4087        let chat = Chat::load_from_db(context, chat_id).await?;
4088        chat.sync(context, SyncAction::SetMuted(duration))
4089            .await
4090            .log_err(context)
4091            .ok();
4092    }
4093    Ok(())
4094}
4095
4096/// Removes contact from the chat.
4097pub async fn remove_contact_from_chat(
4098    context: &Context,
4099    chat_id: ChatId,
4100    contact_id: ContactId,
4101) -> Result<()> {
4102    ensure!(
4103        !chat_id.is_special(),
4104        "bad chat_id, can not be special chat: {chat_id}"
4105    );
4106    ensure!(
4107        !contact_id.is_special() || contact_id == ContactId::SELF,
4108        "Cannot remove special contact"
4109    );
4110
4111    let chat = Chat::load_from_db(context, chat_id).await?;
4112    if chat.typ == Chattype::InBroadcast {
4113        ensure!(
4114            contact_id == ContactId::SELF,
4115            "Cannot remove other member from incoming broadcast channel"
4116        );
4117        delete_broadcast_secret(context, chat_id).await?;
4118    }
4119
4120    if matches!(
4121        chat.typ,
4122        Chattype::Group | Chattype::OutBroadcast | Chattype::InBroadcast
4123    ) {
4124        if !chat.is_self_in_chat(context).await? {
4125            let err_msg = format!(
4126                "Cannot remove contact {contact_id} from chat {chat_id}: self not in group."
4127            );
4128            context.emit_event(EventType::ErrorSelfNotInGroup(err_msg.clone()));
4129            bail!("{err_msg}");
4130        } else {
4131            let mut sync = Nosync;
4132
4133            if chat.is_promoted() && chat.typ != Chattype::OutBroadcast {
4134                remove_from_chat_contacts_table(context, chat_id, contact_id).await?;
4135            } else {
4136                remove_from_chat_contacts_table_without_trace(context, chat_id, contact_id).await?;
4137            }
4138
4139            // We do not return an error if the contact does not exist in the database.
4140            // This allows to delete dangling references to deleted contacts
4141            // in case of the database becoming inconsistent due to a bug.
4142            if let Some(contact) = Contact::get_by_id_optional(context, contact_id).await? {
4143                if chat.is_promoted() {
4144                    let addr = contact.get_addr();
4145                    let fingerprint = contact.fingerprint().map(|f| f.hex());
4146
4147                    let res = send_member_removal_msg(
4148                        context,
4149                        &chat,
4150                        contact_id,
4151                        addr,
4152                        fingerprint.as_deref(),
4153                    )
4154                    .await;
4155
4156                    if contact_id == ContactId::SELF {
4157                        res?;
4158                    } else if let Err(e) = res {
4159                        warn!(
4160                            context,
4161                            "remove_contact_from_chat({chat_id}, {contact_id}): send_msg() failed: {e:#}."
4162                        );
4163                    }
4164                } else {
4165                    sync = Sync;
4166                }
4167            }
4168            context.emit_event(EventType::ChatModified(chat_id));
4169            if sync.into() {
4170                chat.sync_contacts(context).await.log_err(context).ok();
4171            }
4172        }
4173    } else {
4174        bail!("Cannot remove members from non-group chats.");
4175    }
4176
4177    Ok(())
4178}
4179
4180async fn send_member_removal_msg(
4181    context: &Context,
4182    chat: &Chat,
4183    contact_id: ContactId,
4184    addr: &str,
4185    fingerprint: Option<&str>,
4186) -> Result<MsgId> {
4187    let mut msg = Message::new(Viewtype::Text);
4188
4189    if contact_id == ContactId::SELF {
4190        if chat.typ == Chattype::InBroadcast {
4191            msg.text = stock_str::msg_you_left_broadcast(context).await;
4192        } else {
4193            msg.text = stock_str::msg_group_left_local(context, ContactId::SELF).await;
4194        }
4195    } else {
4196        msg.text = stock_str::msg_del_member_local(context, contact_id, ContactId::SELF).await;
4197    }
4198
4199    msg.param.set_cmd(SystemMessage::MemberRemovedFromGroup);
4200    msg.param.set(Param::Arg, addr.to_lowercase());
4201    msg.param.set_optional(Param::Arg4, fingerprint);
4202    msg.param
4203        .set(Param::ContactAddedRemoved, contact_id.to_u32());
4204
4205    send_msg(context, chat.id, &mut msg).await
4206}
4207
4208/// Set group or broadcast channel description.
4209///
4210/// If the group is already _promoted_ (any message was sent to the group),
4211/// or if this is a brodacast channel,
4212/// all members are informed by a special status message that is sent automatically by this function.
4213///
4214/// Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent.
4215///
4216/// See also [`get_chat_description`]
4217pub async fn set_chat_description(
4218    context: &Context,
4219    chat_id: ChatId,
4220    new_description: &str,
4221) -> Result<()> {
4222    set_chat_description_ex(context, Sync, chat_id, new_description).await
4223}
4224
4225async fn set_chat_description_ex(
4226    context: &Context,
4227    mut sync: sync::Sync,
4228    chat_id: ChatId,
4229    new_description: &str,
4230) -> Result<()> {
4231    let new_description = sanitize_bidi_characters(new_description.trim());
4232
4233    ensure!(!chat_id.is_special(), "Invalid chat ID");
4234
4235    let chat = Chat::load_from_db(context, chat_id).await?;
4236    ensure!(
4237        chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4238        "Can only set description for groups / broadcasts"
4239    );
4240    ensure!(
4241        !chat.grpid.is_empty(),
4242        "Cannot set description for ad hoc groups"
4243    );
4244    if !chat.is_self_in_chat(context).await? {
4245        context.emit_event(EventType::ErrorSelfNotInGroup(
4246            "Cannot set chat description; self not in group".into(),
4247        ));
4248        bail!("Cannot set chat description; self not in group");
4249    }
4250
4251    let affected_rows = context
4252        .sql
4253        .execute(
4254            "INSERT INTO chats_descriptions(chat_id, description) VALUES(?, ?)
4255            ON CONFLICT(chat_id) DO UPDATE
4256            SET description=excluded.description WHERE description<>excluded.description",
4257            (chat_id, &new_description),
4258        )
4259        .await?;
4260
4261    if affected_rows == 0 {
4262        return Ok(());
4263    }
4264
4265    if chat.is_promoted() {
4266        let mut msg = Message::new(Viewtype::Text);
4267        msg.text = stock_str::msg_chat_description_changed(context, ContactId::SELF).await;
4268        msg.param.set_cmd(SystemMessage::GroupDescriptionChanged);
4269
4270        msg.id = send_msg(context, chat_id, &mut msg).await?;
4271        context.emit_msgs_changed(chat_id, msg.id);
4272        sync = Nosync;
4273    }
4274    context.emit_event(EventType::ChatModified(chat_id));
4275
4276    if sync.into() {
4277        chat.sync(context, SyncAction::SetDescription(new_description))
4278            .await
4279            .log_err(context)
4280            .ok();
4281    }
4282
4283    Ok(())
4284}
4285
4286/// Load the chat description from the database.
4287///
4288/// UIs show this in the profile page of the chat,
4289/// it is settable by [`set_chat_description`]
4290pub async fn get_chat_description(context: &Context, chat_id: ChatId) -> Result<String> {
4291    let description = context
4292        .sql
4293        .query_get_value(
4294            "SELECT description FROM chats_descriptions WHERE chat_id=?",
4295            (chat_id,),
4296        )
4297        .await?
4298        .unwrap_or_default();
4299    Ok(description)
4300}
4301
4302/// Sets group, mailing list, or broadcast channel chat name.
4303///
4304/// If the group is already _promoted_ (any message was sent to the group),
4305/// or if this is a brodacast channel,
4306/// all members are informed by a special status message that is sent automatically by this function.
4307///
4308/// Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent.
4309pub async fn set_chat_name(context: &Context, chat_id: ChatId, new_name: &str) -> Result<()> {
4310    rename_ex(context, Sync, chat_id, new_name).await
4311}
4312
4313async fn rename_ex(
4314    context: &Context,
4315    mut sync: sync::Sync,
4316    chat_id: ChatId,
4317    new_name: &str,
4318) -> Result<()> {
4319    let new_name = sanitize_single_line(new_name);
4320    /* the function only sets the names of group chats; normal chats get their names from the contacts */
4321    let mut success = false;
4322
4323    ensure!(!new_name.is_empty(), "Invalid name");
4324    ensure!(!chat_id.is_special(), "Invalid chat ID");
4325
4326    let chat = Chat::load_from_db(context, chat_id).await?;
4327    let mut msg = Message::new(Viewtype::default());
4328
4329    if chat.typ == Chattype::Group
4330        || chat.typ == Chattype::Mailinglist
4331        || chat.typ == Chattype::OutBroadcast
4332    {
4333        if chat.name == new_name {
4334            success = true;
4335        } else if !chat.is_self_in_chat(context).await? {
4336            context.emit_event(EventType::ErrorSelfNotInGroup(
4337                "Cannot set chat name; self not in group".into(),
4338            ));
4339        } else {
4340            context
4341                .sql
4342                .execute(
4343                    "UPDATE chats SET name=?, name_normalized=? WHERE id=?",
4344                    (&new_name, normalize_text(&new_name), chat_id),
4345                )
4346                .await?;
4347            if chat.is_promoted()
4348                && !chat.is_mailing_list()
4349                && sanitize_single_line(&chat.name) != new_name
4350            {
4351                msg.viewtype = Viewtype::Text;
4352                msg.text =
4353                    stock_str::msg_grp_name(context, &chat.name, &new_name, ContactId::SELF).await;
4354                msg.param.set_cmd(SystemMessage::GroupNameChanged);
4355                if !chat.name.is_empty() {
4356                    msg.param.set(Param::Arg, &chat.name);
4357                }
4358                msg.id = send_msg(context, chat_id, &mut msg).await?;
4359                context.emit_msgs_changed(chat_id, msg.id);
4360                sync = Nosync;
4361            }
4362            context.emit_event(EventType::ChatModified(chat_id));
4363            chatlist_events::emit_chatlist_item_changed(context, chat_id);
4364            success = true;
4365        }
4366    }
4367
4368    if !success {
4369        bail!("Failed to set name");
4370    }
4371    if sync.into() && chat.name != new_name {
4372        let sync_name = new_name.to_string();
4373        chat.sync(context, SyncAction::Rename(sync_name))
4374            .await
4375            .log_err(context)
4376            .ok();
4377    }
4378    Ok(())
4379}
4380
4381/// Sets a new profile image for the chat.
4382///
4383/// The profile image can only be set when you are a member of the
4384/// chat.  To remove the profile image pass an empty string for the
4385/// `new_image` parameter.
4386pub async fn set_chat_profile_image(
4387    context: &Context,
4388    chat_id: ChatId,
4389    new_image: &str, // XXX use PathBuf
4390) -> Result<()> {
4391    ensure!(!chat_id.is_special(), "Invalid chat ID");
4392    let mut chat = Chat::load_from_db(context, chat_id).await?;
4393    ensure!(
4394        chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast,
4395        "Can only set profile image for groups / broadcasts"
4396    );
4397    ensure!(
4398        !chat.grpid.is_empty(),
4399        "Cannot set profile image for ad hoc groups"
4400    );
4401    /* we should respect this - whatever we send to the group, it gets discarded anyway! */
4402    if !chat.is_self_in_chat(context).await? {
4403        context.emit_event(EventType::ErrorSelfNotInGroup(
4404            "Cannot set chat profile image; self not in group.".into(),
4405        ));
4406        bail!("Failed to set profile image");
4407    }
4408    let mut msg = Message::new(Viewtype::Text);
4409    msg.param
4410        .set_int(Param::Cmd, SystemMessage::GroupImageChanged as i32);
4411    if new_image.is_empty() {
4412        chat.param.remove(Param::ProfileImage);
4413        msg.param.remove(Param::Arg);
4414        msg.text = stock_str::msg_grp_img_deleted(context, ContactId::SELF).await;
4415    } else {
4416        let mut image_blob = BlobObject::create_and_deduplicate(
4417            context,
4418            Path::new(new_image),
4419            Path::new(new_image),
4420        )?;
4421        image_blob.recode_to_avatar_size(context).await?;
4422        chat.param.set(Param::ProfileImage, image_blob.as_name());
4423        msg.param.set(Param::Arg, image_blob.as_name());
4424        msg.text = stock_str::msg_grp_img_changed(context, ContactId::SELF).await;
4425    }
4426    chat.update_param(context).await?;
4427    if chat.is_promoted() {
4428        msg.id = send_msg(context, chat_id, &mut msg).await?;
4429        context.emit_msgs_changed(chat_id, msg.id);
4430    }
4431    context.emit_event(EventType::ChatModified(chat_id));
4432    chatlist_events::emit_chatlist_item_changed(context, chat_id);
4433    Ok(())
4434}
4435
4436/// Forwards multiple messages to a chat.
4437pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) -> Result<()> {
4438    forward_msgs_2ctx(context, msg_ids, context, chat_id).await
4439}
4440
4441/// Forwards multiple messages to a chat in another context.
4442#[expect(clippy::arithmetic_side_effects)]
4443pub async fn forward_msgs_2ctx(
4444    ctx_src: &Context,
4445    msg_ids: &[MsgId],
4446    ctx_dst: &Context,
4447    chat_id: ChatId,
4448) -> Result<()> {
4449    ensure!(!msg_ids.is_empty(), "empty msgs_ids: nothing to forward");
4450    ensure!(!chat_id.is_special(), "can not forward to special chat");
4451
4452    let mut created_msgs: Vec<MsgId> = Vec::new();
4453    let mut curr_timestamp: i64;
4454
4455    chat_id
4456        .unarchive_if_not_muted(ctx_dst, MessageState::Undefined)
4457        .await?;
4458    let mut chat = Chat::load_from_db(ctx_dst, chat_id).await?;
4459    if let Some(reason) = chat.why_cant_send(ctx_dst).await? {
4460        bail!("cannot send to {chat_id}: {reason}");
4461    }
4462    curr_timestamp = create_smeared_timestamps(ctx_dst, msg_ids.len());
4463    let mut msgs = Vec::with_capacity(msg_ids.len());
4464    for id in msg_ids {
4465        let ts: i64 = ctx_src
4466            .sql
4467            .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4468            .await?
4469            .with_context(|| format!("No message {id}"))?;
4470        msgs.push((ts, *id));
4471    }
4472    msgs.sort_unstable();
4473    for (_, id) in msgs {
4474        let src_msg_id: MsgId = id;
4475        let mut msg = Message::load_from_db(ctx_src, src_msg_id).await?;
4476        if msg.state == MessageState::OutDraft {
4477            bail!("cannot forward drafts.");
4478        }
4479
4480        let mut param = msg.param;
4481        msg.param = Params::new();
4482
4483        if msg.get_viewtype() != Viewtype::Sticker {
4484            let forwarded_msg_id = match ctx_src.blobdir == ctx_dst.blobdir {
4485                true => src_msg_id,
4486                false => MsgId::new_unset(),
4487            };
4488            msg.param
4489                .set_int(Param::Forwarded, forwarded_msg_id.to_u32() as i32);
4490        }
4491
4492        if msg.get_viewtype() == Viewtype::Call {
4493            msg.viewtype = Viewtype::Text;
4494        }
4495        msg.text += &msg.additional_text;
4496
4497        let param = &mut param;
4498
4499        // When forwarding between different accounts, blob files must be physically copied
4500        // because each account has its own blob directory.
4501        if ctx_src.blobdir == ctx_dst.blobdir {
4502            msg.param.steal(param, Param::File);
4503        } else if let Some(src_path) = param.get_file_path(ctx_src)? {
4504            let new_blob = BlobObject::create_and_deduplicate(ctx_dst, &src_path, &src_path)
4505                .context("Failed to copy blob file to destination account")?;
4506            msg.param.set(Param::File, new_blob.as_name());
4507        }
4508        msg.param.steal(param, Param::Filename);
4509        msg.param.steal(param, Param::Width);
4510        msg.param.steal(param, Param::Height);
4511        msg.param.steal(param, Param::Duration);
4512        msg.param.steal(param, Param::MimeType);
4513        msg.param.steal(param, Param::ProtectQuote);
4514        msg.param.steal(param, Param::Quote);
4515        msg.param.steal(param, Param::Summary1);
4516        if msg.has_html() {
4517            msg.set_html(src_msg_id.get_html(ctx_src).await?);
4518        }
4519        msg.in_reply_to = None;
4520
4521        // do not leak data as group names; a default subject is generated by mimefactory
4522        msg.subject = "".to_string();
4523
4524        msg.state = MessageState::OutPending;
4525        msg.rfc724_mid = create_outgoing_rfc724_mid();
4526        msg.timestamp_sort = curr_timestamp;
4527        chat.prepare_msg_raw(ctx_dst, &mut msg, None).await?;
4528
4529        curr_timestamp += 1;
4530        if !create_send_msg_jobs(ctx_dst, &mut msg).await?.is_empty() {
4531            ctx_dst.scheduler.interrupt_smtp().await;
4532        }
4533        created_msgs.push(msg.id);
4534    }
4535    for msg_id in created_msgs {
4536        ctx_dst.emit_msgs_changed(chat_id, msg_id);
4537    }
4538    Ok(())
4539}
4540
4541/// Save a copy of the message in "Saved Messages"
4542/// and send a sync messages so that other devices save the message as well, unless deleted there.
4543pub async fn save_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4544    let mut msgs = Vec::with_capacity(msg_ids.len());
4545    for id in msg_ids {
4546        let ts: i64 = context
4547            .sql
4548            .query_get_value("SELECT timestamp FROM msgs WHERE id=?", (id,))
4549            .await?
4550            .with_context(|| format!("No message {id}"))?;
4551        msgs.push((ts, *id));
4552    }
4553    msgs.sort_unstable();
4554    for (_, src_msg_id) in msgs {
4555        let dest_rfc724_mid = create_outgoing_rfc724_mid();
4556        let src_rfc724_mid = save_copy_in_self_talk(context, src_msg_id, &dest_rfc724_mid).await?;
4557        context
4558            .add_sync_item(SyncData::SaveMessage {
4559                src: src_rfc724_mid,
4560                dest: dest_rfc724_mid,
4561            })
4562            .await?;
4563    }
4564    context.scheduler.interrupt_smtp().await;
4565    Ok(())
4566}
4567
4568/// Saves a copy of the given message in "Saved Messages" using the given RFC724 id.
4569/// To allow UIs to have a "show in context" button,
4570/// the copy contains a reference to the original message
4571/// as well as to the original chat in case the original message gets deleted.
4572/// Returns data needed to add a `SaveMessage` sync item.
4573#[expect(clippy::arithmetic_side_effects)]
4574pub(crate) async fn save_copy_in_self_talk(
4575    context: &Context,
4576    src_msg_id: MsgId,
4577    dest_rfc724_mid: &String,
4578) -> Result<String> {
4579    let dest_chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?;
4580    let mut msg = Message::load_from_db(context, src_msg_id).await?;
4581    msg.param.remove(Param::Cmd);
4582    msg.param.remove(Param::WebxdcDocument);
4583    msg.param.remove(Param::WebxdcDocumentTimestamp);
4584    msg.param.remove(Param::WebxdcSummary);
4585    msg.param.remove(Param::WebxdcSummaryTimestamp);
4586    msg.param.remove(Param::PostMessageFileBytes);
4587    msg.param.remove(Param::PostMessageViewtype);
4588
4589    msg.text += &msg.additional_text;
4590
4591    if !msg.original_msg_id.is_unset() {
4592        bail!("message already saved.");
4593    }
4594
4595    let copy_fields = "from_id, to_id, timestamp_rcvd, type,
4596                       mime_modified, mime_headers, mime_compressed, mime_in_reply_to, subject, msgrmsg";
4597    let row_id = context
4598        .sql
4599        .insert(
4600            &format!(
4601                "INSERT INTO msgs ({copy_fields},
4602                                   timestamp_sent,
4603                                   txt, chat_id, rfc724_mid, state, timestamp, param, starred)
4604                 SELECT            {copy_fields},
4605                                   -- Outgoing messages on originating device
4606                                   -- have timestamp_sent == 0.
4607                                   -- We copy sort timestamp instead
4608                                   -- so UIs display the same timestamp
4609                                   -- for saved and original message.
4610                                   IIF(timestamp_sent == 0, timestamp, timestamp_sent),
4611                                   ?, ?, ?, ?, ?, ?, ?
4612                 FROM msgs WHERE id=?;"
4613            ),
4614            (
4615                msg.text,
4616                dest_chat_id,
4617                dest_rfc724_mid,
4618                if msg.from_id == ContactId::SELF {
4619                    MessageState::OutDelivered
4620                } else {
4621                    MessageState::InSeen
4622                },
4623                create_smeared_timestamp(context),
4624                msg.param.to_string(),
4625                src_msg_id,
4626                src_msg_id,
4627            ),
4628        )
4629        .await?;
4630    let dest_msg_id = MsgId::new(row_id.try_into()?);
4631
4632    context.emit_msgs_changed(msg.chat_id, src_msg_id);
4633    context.emit_msgs_changed(dest_chat_id, dest_msg_id);
4634    chatlist_events::emit_chatlist_changed(context);
4635    chatlist_events::emit_chatlist_item_changed(context, dest_chat_id);
4636
4637    Ok(msg.rfc724_mid)
4638}
4639
4640/// Resends given messages with the same Message-ID.
4641///
4642/// This is primarily intended to make existing webxdcs available to new chat members.
4643pub async fn resend_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
4644    let mut msgs: Vec<Message> = Vec::new();
4645    for msg_id in msg_ids {
4646        let msg = Message::load_from_db(context, *msg_id).await?;
4647        ensure!(
4648            msg.from_id == ContactId::SELF,
4649            "can resend only own messages"
4650        );
4651        ensure!(!msg.is_info(), "cannot resend info messages");
4652        msgs.push(msg)
4653    }
4654
4655    for mut msg in msgs {
4656        match msg.get_state() {
4657            // `get_state()` may return an outdated `OutPending`, so update anyway.
4658            MessageState::OutPending
4659            | MessageState::OutFailed
4660            | MessageState::OutDelivered
4661            | MessageState::OutMdnRcvd => {
4662                message::update_msg_state(context, msg.id, MessageState::OutPending).await?
4663            }
4664            msg_state => bail!("Unexpected message state {msg_state}"),
4665        }
4666        msg.timestamp_sort = create_smeared_timestamp(context);
4667        if create_send_msg_jobs(context, &mut msg).await?.is_empty() {
4668            continue;
4669        }
4670
4671        // Emit the event only after `create_send_msg_jobs`
4672        // because `create_send_msg_jobs` may change the message
4673        // encryption status and call `msg.update_param`.
4674        context.emit_event(EventType::MsgsChanged {
4675            chat_id: msg.chat_id,
4676            msg_id: msg.id,
4677        });
4678        // note(treefit): only matters if it is the last message in chat (but probably to expensive to check, debounce also solves it)
4679        chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
4680
4681        if msg.viewtype == Viewtype::Webxdc {
4682            let conn_fn = |conn: &mut rusqlite::Connection| {
4683                let range = conn.query_row(
4684                    "SELECT IFNULL(min(id), 1), IFNULL(max(id), 0) \
4685                     FROM msgs_status_updates WHERE msg_id=?",
4686                    (msg.id,),
4687                    |row| {
4688                        let min_id: StatusUpdateSerial = row.get(0)?;
4689                        let max_id: StatusUpdateSerial = row.get(1)?;
4690                        Ok((min_id, max_id))
4691                    },
4692                )?;
4693                if range.0 > range.1 {
4694                    return Ok(());
4695                };
4696                // `first_serial` must be decreased, otherwise if `Context::flush_status_updates()`
4697                // runs in parallel, it would miss the race and instead of resending just remove the
4698                // updates thinking that they have been already sent.
4699                conn.execute(
4700                    "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) \
4701                     VALUES(?, ?, ?, '') \
4702                     ON CONFLICT(msg_id) \
4703                     DO UPDATE SET first_serial=min(first_serial - 1, excluded.first_serial)",
4704                    (msg.id, range.0, range.1),
4705                )?;
4706                Ok(())
4707            };
4708            context.sql.call_write(conn_fn).await?;
4709        }
4710        context.scheduler.interrupt_smtp().await;
4711    }
4712    Ok(())
4713}
4714
4715pub(crate) async fn get_chat_cnt(context: &Context) -> Result<usize> {
4716    if context.sql.is_open().await {
4717        // no database, no chats - this is no error (needed eg. for information)
4718        let count = context
4719            .sql
4720            .count("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;", ())
4721            .await?;
4722        Ok(count)
4723    } else {
4724        Ok(0)
4725    }
4726}
4727
4728/// Returns a tuple of `(chatid, blocked)`.
4729pub(crate) async fn get_chat_id_by_grpid(
4730    context: &Context,
4731    grpid: &str,
4732) -> Result<Option<(ChatId, Blocked)>> {
4733    context
4734        .sql
4735        .query_row_optional(
4736            "SELECT id, blocked FROM chats WHERE grpid=?;",
4737            (grpid,),
4738            |row| {
4739                let chat_id = row.get::<_, ChatId>(0)?;
4740
4741                let b = row.get::<_, Option<Blocked>>(1)?.unwrap_or_default();
4742                Ok((chat_id, b))
4743            },
4744        )
4745        .await
4746}
4747
4748/// Adds a message to device chat.
4749///
4750/// Optional `label` can be provided to ensure that message is added only once.
4751/// If `important` is true, a notification will be sent.
4752#[expect(clippy::arithmetic_side_effects)]
4753pub async fn add_device_msg_with_importance(
4754    context: &Context,
4755    label: Option<&str>,
4756    msg: Option<&mut Message>,
4757    important: bool,
4758) -> Result<MsgId> {
4759    ensure!(
4760        label.is_some() || msg.is_some(),
4761        "device-messages need label, msg or both"
4762    );
4763    let mut chat_id = ChatId::new(0);
4764    let mut msg_id = MsgId::new_unset();
4765
4766    if let Some(label) = label
4767        && was_device_msg_ever_added(context, label).await?
4768    {
4769        info!(context, "Device-message {label} already added.");
4770        return Ok(msg_id);
4771    }
4772
4773    if let Some(msg) = msg {
4774        chat_id = ChatId::get_for_contact(context, ContactId::DEVICE).await?;
4775
4776        let rfc724_mid = create_outgoing_rfc724_mid();
4777        let timestamp_sent = create_smeared_timestamp(context);
4778
4779        // makes sure, the added message is the last one,
4780        // even if the date is wrong (useful esp. when warning about bad dates)
4781        msg.timestamp_sort = timestamp_sent;
4782        if let Some(last_msg_time) = chat_id.get_timestamp(context).await?
4783            && msg.timestamp_sort <= last_msg_time
4784        {
4785            msg.timestamp_sort = last_msg_time + 1;
4786        }
4787        prepare_msg_blob(context, msg).await?;
4788        let state = MessageState::InFresh;
4789        let row_id = context
4790            .sql
4791            .insert(
4792                "INSERT INTO msgs (
4793            chat_id,
4794            from_id,
4795            to_id,
4796            timestamp,
4797            timestamp_sent,
4798            timestamp_rcvd,
4799            type,state,
4800            txt,
4801            txt_normalized,
4802            param,
4803            rfc724_mid)
4804            VALUES (?,?,?,?,?,?,?,?,?,?,?,?);",
4805                (
4806                    chat_id,
4807                    ContactId::DEVICE,
4808                    ContactId::SELF,
4809                    msg.timestamp_sort,
4810                    timestamp_sent,
4811                    timestamp_sent, // timestamp_sent equals timestamp_rcvd
4812                    msg.viewtype,
4813                    state,
4814                    &msg.text,
4815                    normalize_text(&msg.text),
4816                    msg.param.to_string(),
4817                    rfc724_mid,
4818                ),
4819            )
4820            .await?;
4821        context.new_msgs_notify.notify_one();
4822
4823        msg_id = MsgId::new(u32::try_from(row_id)?);
4824        if !msg.hidden {
4825            chat_id.unarchive_if_not_muted(context, state).await?;
4826        }
4827    }
4828
4829    if let Some(label) = label {
4830        context
4831            .sql
4832            .execute("INSERT INTO devmsglabels (label) VALUES (?);", (label,))
4833            .await?;
4834    }
4835
4836    if !msg_id.is_unset() {
4837        chat_id.emit_msg_event(context, msg_id, important);
4838    }
4839
4840    Ok(msg_id)
4841}
4842
4843/// Adds a message to device chat.
4844pub async fn add_device_msg(
4845    context: &Context,
4846    label: Option<&str>,
4847    msg: Option<&mut Message>,
4848) -> Result<MsgId> {
4849    add_device_msg_with_importance(context, label, msg, false).await
4850}
4851
4852/// Returns true if device message with a given label was ever added to the device chat.
4853pub async fn was_device_msg_ever_added(context: &Context, label: &str) -> Result<bool> {
4854    ensure!(!label.is_empty(), "empty label");
4855    let exists = context
4856        .sql
4857        .exists(
4858            "SELECT COUNT(label) FROM devmsglabels WHERE label=?",
4859            (label,),
4860        )
4861        .await?;
4862
4863    Ok(exists)
4864}
4865
4866// needed on device-switches during export/import;
4867// - deletion in `msgs` with `ContactId::DEVICE` makes sure,
4868//   no wrong information are shown in the device chat
4869// - deletion in `devmsglabels` makes sure,
4870//   deleted messages are reset and useful messages can be added again
4871// - we reset the config-option `QuotaExceeding`
4872//   that is used as a helper to drive the corresponding device message.
4873pub(crate) async fn delete_and_reset_all_device_msgs(context: &Context) -> Result<()> {
4874    context
4875        .sql
4876        .execute("DELETE FROM msgs WHERE from_id=?;", (ContactId::DEVICE,))
4877        .await?;
4878    context.sql.execute("DELETE FROM devmsglabels;", ()).await?;
4879
4880    // Insert labels for welcome messages to avoid them being re-added on reconfiguration.
4881    context
4882        .sql
4883        .execute(
4884            r#"INSERT INTO devmsglabels (label) VALUES ("core-welcome-image"), ("core-welcome")"#,
4885            (),
4886        )
4887        .await?;
4888    context
4889        .set_config_internal(Config::QuotaExceeding, None)
4890        .await?;
4891    Ok(())
4892}
4893
4894/// Adds an informational message to chat.
4895///
4896/// For example, it can be a message showing that a member was added to a group.
4897/// Doesn't fail if the chat doesn't exist.
4898#[expect(clippy::too_many_arguments)]
4899pub(crate) async fn add_info_msg_with_cmd(
4900    context: &Context,
4901    chat_id: ChatId,
4902    text: &str,
4903    cmd: SystemMessage,
4904    // Timestamp where in the chat the message will be sorted.
4905    // If this is None, the message will be sorted to the bottom.
4906    timestamp_sort: Option<i64>,
4907    // Timestamp to show to the user
4908    timestamp_sent_rcvd: i64,
4909    parent: Option<&Message>,
4910    from_id: Option<ContactId>,
4911    added_removed_id: Option<ContactId>,
4912) -> Result<MsgId> {
4913    let rfc724_mid = create_outgoing_rfc724_mid();
4914    let ephemeral_timer = chat_id.get_ephemeral_timer(context).await?;
4915
4916    let mut param = Params::new();
4917    if cmd != SystemMessage::Unknown {
4918        param.set_cmd(cmd);
4919    }
4920    if let Some(contact_id) = added_removed_id {
4921        param.set(Param::ContactAddedRemoved, contact_id.to_u32().to_string());
4922    }
4923
4924    let timestamp_sort = if let Some(ts) = timestamp_sort {
4925        ts
4926    } else {
4927        let sort_to_bottom = true;
4928        let (received, incoming) = (false, false);
4929        chat_id
4930            .calc_sort_timestamp(
4931                context,
4932                smeared_time(context),
4933                sort_to_bottom,
4934                received,
4935                incoming,
4936            )
4937            .await?
4938    };
4939
4940    let row_id =
4941    context.sql.insert(
4942        "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)
4943        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);",
4944        (
4945            chat_id,
4946            from_id.unwrap_or(ContactId::INFO),
4947            ContactId::INFO,
4948            timestamp_sort,
4949            timestamp_sent_rcvd,
4950            timestamp_sent_rcvd,
4951            Viewtype::Text,
4952            MessageState::InNoticed,
4953            text,
4954            normalize_text(text),
4955            rfc724_mid,
4956            ephemeral_timer,
4957            param.to_string(),
4958            parent.map(|msg|msg.rfc724_mid.clone()).unwrap_or_default()
4959        )
4960    ).await?;
4961    context.new_msgs_notify.notify_one();
4962
4963    let msg_id = MsgId::new(row_id.try_into()?);
4964    context.emit_msgs_changed(chat_id, msg_id);
4965
4966    Ok(msg_id)
4967}
4968
4969/// Adds info message with a given text and `timestamp` to the chat.
4970pub(crate) async fn add_info_msg(context: &Context, chat_id: ChatId, text: &str) -> Result<MsgId> {
4971    add_info_msg_with_cmd(
4972        context,
4973        chat_id,
4974        text,
4975        SystemMessage::Unknown,
4976        None,
4977        time(),
4978        None,
4979        None,
4980        None,
4981    )
4982    .await
4983}
4984
4985pub(crate) async fn update_msg_text_and_timestamp(
4986    context: &Context,
4987    chat_id: ChatId,
4988    msg_id: MsgId,
4989    text: &str,
4990    timestamp: i64,
4991) -> Result<()> {
4992    context
4993        .sql
4994        .execute(
4995            "UPDATE msgs SET txt=?, txt_normalized=?, timestamp=? WHERE id=?;",
4996            (text, normalize_text(text), timestamp, msg_id),
4997        )
4998        .await?;
4999    context.emit_msgs_changed(chat_id, msg_id);
5000    Ok(())
5001}
5002
5003/// Set chat contacts by their addresses creating the corresponding contacts if necessary.
5004async fn set_contacts_by_addrs(context: &Context, id: ChatId, addrs: &[String]) -> Result<()> {
5005    let chat = Chat::load_from_db(context, id).await?;
5006    ensure!(
5007        !chat.is_encrypted(context).await?,
5008        "Cannot add address-contacts to encrypted chat {id}"
5009    );
5010    ensure!(
5011        chat.typ == Chattype::OutBroadcast,
5012        "{id} is not a broadcast list",
5013    );
5014    let mut contacts = HashSet::new();
5015    for addr in addrs {
5016        let contact_addr = ContactAddress::new(addr)?;
5017        let contact = Contact::add_or_lookup(context, "", &contact_addr, Origin::Hidden)
5018            .await?
5019            .0;
5020        contacts.insert(contact);
5021    }
5022    let contacts_old = HashSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
5023    if contacts == contacts_old {
5024        return Ok(());
5025    }
5026    context
5027        .sql
5028        .transaction(move |transaction| {
5029            transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
5030
5031            // We do not care about `add_timestamp` column
5032            // because timestamps are not used for broadcast channels.
5033            let mut statement = transaction
5034                .prepare("INSERT INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)")?;
5035            for contact_id in &contacts {
5036                statement.execute((id, contact_id))?;
5037            }
5038            Ok(())
5039        })
5040        .await?;
5041    context.emit_event(EventType::ChatModified(id));
5042    Ok(())
5043}
5044
5045/// Set chat contacts by their fingerprints creating the corresponding contacts if necessary.
5046///
5047/// `fingerprint_addrs` is a list of pairs of fingerprint and address.
5048async fn set_contacts_by_fingerprints(
5049    context: &Context,
5050    id: ChatId,
5051    fingerprint_addrs: &[(String, String)],
5052) -> Result<()> {
5053    let chat = Chat::load_from_db(context, id).await?;
5054    ensure!(
5055        chat.is_encrypted(context).await?,
5056        "Cannot add key-contacts to unencrypted chat {id}"
5057    );
5058    ensure!(
5059        matches!(chat.typ, Chattype::Group | Chattype::OutBroadcast),
5060        "{id} is not a group or broadcast",
5061    );
5062    let mut contacts = HashSet::new();
5063    for (fingerprint, addr) in fingerprint_addrs {
5064        let contact = Contact::add_or_lookup_ex(context, "", addr, fingerprint, Origin::Hidden)
5065            .await?
5066            .0;
5067        contacts.insert(contact);
5068    }
5069    let contacts_old = HashSet::<ContactId>::from_iter(get_chat_contacts(context, id).await?);
5070    if contacts == contacts_old {
5071        return Ok(());
5072    }
5073    context
5074        .sql
5075        .transaction(move |transaction| {
5076            // For broadcast channels, we only add members,
5077            // because we don't use the membership consistency algorithm,
5078            // and are using sync messages as a basic way to ensure consistency between devices.
5079            // For groups, we also remove members,
5080            // because the sync message is used in order to sync unpromoted groups.
5081            if chat.typ != Chattype::OutBroadcast {
5082                transaction.execute("DELETE FROM chats_contacts WHERE chat_id=?", (id,))?;
5083            }
5084
5085            // We do not care about `add_timestamp` column
5086            // because timestamps are not used for broadcast channels.
5087            let mut statement = transaction.prepare(
5088                "INSERT OR IGNORE INTO chats_contacts (chat_id, contact_id) VALUES (?, ?)",
5089            )?;
5090            for contact_id in &contacts {
5091                statement.execute((id, contact_id))?;
5092            }
5093            Ok(())
5094        })
5095        .await?;
5096    context.emit_event(EventType::ChatModified(id));
5097    Ok(())
5098}
5099
5100/// A cross-device chat id used for synchronisation.
5101#[derive(Debug, Serialize, Deserialize, PartialEq)]
5102pub(crate) enum SyncId {
5103    /// E-mail address of the contact.
5104    ContactAddr(String),
5105
5106    /// OpenPGP key fingerprint of the contact.
5107    ContactFingerprint(String),
5108
5109    Grpid(String),
5110    /// "Message-ID"-s, from oldest to latest. Used for ad-hoc groups.
5111    Msgids(Vec<String>),
5112
5113    /// Special id for device chat.
5114    Device,
5115}
5116
5117/// An action synchronised to other devices.
5118#[derive(Debug, Serialize, Deserialize, PartialEq)]
5119pub(crate) enum SyncAction {
5120    Block,
5121    Unblock,
5122    Accept,
5123    SetVisibility(ChatVisibility),
5124    SetMuted(MuteDuration),
5125    /// Create broadcast channel with the given name.
5126    CreateOutBroadcast {
5127        chat_name: String,
5128        secret: String,
5129    },
5130    /// Create encrypted group chat with the given name.
5131    CreateGroupEncrypted(String),
5132    Rename(String),
5133    /// Set chat contacts by their addresses.
5134    SetContacts(Vec<String>),
5135    /// Set chat contacts by their fingerprints.
5136    ///
5137    /// The list is a list of pairs of fingerprint and address.
5138    SetPgpContacts(Vec<(String, String)>),
5139    SetDescription(String),
5140    Delete,
5141}
5142
5143impl Context {
5144    /// Executes [`SyncData::AlterChat`] item sent by other device.
5145    pub(crate) async fn sync_alter_chat(&self, id: &SyncId, action: &SyncAction) -> Result<()> {
5146        let chat_id = match id {
5147            SyncId::ContactAddr(addr) => {
5148                if let SyncAction::Rename(to) = action {
5149                    Contact::create_ex(self, Nosync, to, addr).await?;
5150                    return Ok(());
5151                }
5152                let addr = ContactAddress::new(addr).context("Invalid address")?;
5153                let (contact_id, _) =
5154                    Contact::add_or_lookup(self, "", &addr, Origin::Hidden).await?;
5155                match action {
5156                    SyncAction::Block => {
5157                        return contact::set_blocked(self, Nosync, contact_id, true).await;
5158                    }
5159                    SyncAction::Unblock => {
5160                        return contact::set_blocked(self, Nosync, contact_id, false).await;
5161                    }
5162                    _ => (),
5163                }
5164                // Use `Request` so that even if the program crashes, the user doesn't have to look
5165                // into the blocked contacts.
5166                ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5167                    .await?
5168                    .id
5169            }
5170            SyncId::ContactFingerprint(fingerprint) => {
5171                let name = "";
5172                let addr = "";
5173                let (contact_id, _) =
5174                    Contact::add_or_lookup_ex(self, name, addr, fingerprint, Origin::Hidden)
5175                        .await?;
5176                match action {
5177                    SyncAction::Rename(to) => {
5178                        contact_id.set_name_ex(self, Nosync, to).await?;
5179                        self.emit_event(EventType::ContactsChanged(Some(contact_id)));
5180                        return Ok(());
5181                    }
5182                    SyncAction::Block => {
5183                        return contact::set_blocked(self, Nosync, contact_id, true).await;
5184                    }
5185                    SyncAction::Unblock => {
5186                        return contact::set_blocked(self, Nosync, contact_id, false).await;
5187                    }
5188                    _ => (),
5189                }
5190                ChatIdBlocked::get_for_contact(self, contact_id, Blocked::Request)
5191                    .await?
5192                    .id
5193            }
5194            SyncId::Grpid(grpid) => {
5195                match action {
5196                    SyncAction::CreateOutBroadcast { chat_name, secret } => {
5197                        create_out_broadcast_ex(
5198                            self,
5199                            Nosync,
5200                            grpid.to_string(),
5201                            chat_name.clone(),
5202                            secret.to_string(),
5203                        )
5204                        .await?;
5205                        return Ok(());
5206                    }
5207                    SyncAction::CreateGroupEncrypted(name) => {
5208                        create_group_ex(self, Nosync, grpid.clone(), name).await?;
5209                        return Ok(());
5210                    }
5211                    _ => {}
5212                }
5213                get_chat_id_by_grpid(self, grpid)
5214                    .await?
5215                    .with_context(|| format!("No chat for grpid '{grpid}'"))?
5216                    .0
5217            }
5218            SyncId::Msgids(msgids) => {
5219                let msg = message::get_by_rfc724_mids(self, msgids)
5220                    .await?
5221                    .with_context(|| format!("No message found for Message-IDs {msgids:?}"))?;
5222                ChatId::lookup_by_message(&msg)
5223                    .with_context(|| format!("No chat found for Message-IDs {msgids:?}"))?
5224            }
5225            SyncId::Device => ChatId::get_for_contact(self, ContactId::DEVICE).await?,
5226        };
5227        match action {
5228            SyncAction::Block => chat_id.block_ex(self, Nosync).await,
5229            SyncAction::Unblock => chat_id.unblock_ex(self, Nosync).await,
5230            SyncAction::Accept => chat_id.accept_ex(self, Nosync).await,
5231            SyncAction::SetVisibility(v) => chat_id.set_visibility_ex(self, Nosync, *v).await,
5232            SyncAction::SetMuted(duration) => set_muted_ex(self, Nosync, chat_id, *duration).await,
5233            SyncAction::CreateOutBroadcast { .. } | SyncAction::CreateGroupEncrypted(..) => {
5234                // Create action should have been handled above already.
5235                Err(anyhow!("sync_alter_chat({id:?}, {action:?}): Bad request."))
5236            }
5237            SyncAction::Rename(to) => rename_ex(self, Nosync, chat_id, to).await,
5238            SyncAction::SetDescription(to) => {
5239                set_chat_description_ex(self, Nosync, chat_id, to).await
5240            }
5241            SyncAction::SetContacts(addrs) => set_contacts_by_addrs(self, chat_id, addrs).await,
5242            SyncAction::SetPgpContacts(fingerprint_addrs) => {
5243                set_contacts_by_fingerprints(self, chat_id, fingerprint_addrs).await
5244            }
5245            SyncAction::Delete => chat_id.delete_ex(self, Nosync).await,
5246        }
5247    }
5248
5249    /// Emits the appropriate `MsgsChanged` event. Should be called if the number of unnoticed
5250    /// archived chats could decrease. In general we don't want to make an extra db query to know if
5251    /// a noticed chat is archived. Emitting events should be cheap, a false-positive `MsgsChanged`
5252    /// is ok.
5253    pub(crate) fn on_archived_chats_maybe_noticed(&self) {
5254        self.emit_msgs_changed_without_msg_id(DC_CHAT_ID_ARCHIVED_LINK);
5255    }
5256}
5257
5258#[cfg(test)]
5259mod chat_tests;