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