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