deltachat/
chat.rs

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