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