deltachat/
message.rs

1//! # Messages and their identifiers.
2
3use std::collections::BTreeSet;
4use std::path::{Path, PathBuf};
5use std::str;
6
7use anyhow::{Context as _, Result, ensure, format_err};
8use deltachat_contact_tools::{VcardContact, parse_vcard};
9use deltachat_derive::{FromSql, ToSql};
10use humansize::BINARY;
11use humansize::format_size;
12use num_traits::FromPrimitive;
13use serde::{Deserialize, Serialize};
14use tokio::{fs, io};
15
16use crate::blob::BlobObject;
17use crate::chat::{Chat, ChatId, ChatIdBlocked, ChatVisibility, send_msg};
18use crate::chatlist_events;
19use crate::config::Config;
20use crate::constants::{Blocked, Chattype, DC_CHAT_ID_TRASH, DC_MSG_ID_LAST_SPECIAL};
21use crate::contact::{self, Contact, ContactId};
22use crate::context::Context;
23use crate::debug_logging::set_debug_logging_xdc;
24use crate::download::DownloadState;
25use crate::ephemeral::{Timer as EphemeralTimer, start_ephemeral_timers_msgids};
26use crate::events::EventType;
27use crate::imap::markseen_on_imap_table;
28use crate::location::delete_poi_location;
29use crate::log::warn;
30use crate::mimeparser::{SystemMessage, parse_message_id};
31use crate::param::{Param, Params};
32use crate::reaction::get_msg_reactions;
33use crate::sql;
34use crate::summary::Summary;
35use crate::sync::SyncData;
36use crate::tools::create_outgoing_rfc724_mid;
37use crate::tools::{
38    buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file,
39    sanitize_filename, time, timestamp_to_str,
40};
41
42/// Message ID, including reserved IDs.
43///
44/// Some message IDs are reserved to identify special message types.
45/// This type can represent both the special as well as normal
46/// messages.
47#[derive(
48    Debug, Copy, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
49)]
50pub struct MsgId(u32);
51
52impl MsgId {
53    /// Create a new [MsgId].
54    pub fn new(id: u32) -> MsgId {
55        MsgId(id)
56    }
57
58    /// Create a new unset [MsgId].
59    pub fn new_unset() -> MsgId {
60        MsgId(0)
61    }
62
63    /// Whether the message ID signifies a special message.
64    ///
65    /// This kind of message ID can not be used for real messages.
66    pub fn is_special(self) -> bool {
67        self.0 <= DC_MSG_ID_LAST_SPECIAL
68    }
69
70    /// Whether the message ID is unset.
71    ///
72    /// When a message is created it initially has a ID of `0`, which
73    /// is filled in by a real message ID once the message is saved in
74    /// the database.  This returns true while the message has not
75    /// been saved and thus not yet been given an actual message ID.
76    ///
77    /// When this is `true`, [MsgId::is_special] will also always be
78    /// `true`.
79    pub fn is_unset(self) -> bool {
80        self.0 == 0
81    }
82
83    /// Returns message state.
84    pub async fn get_state(self, context: &Context) -> Result<MessageState> {
85        let result = context
86            .sql
87            .query_row_optional(
88                "SELECT m.state, mdns.msg_id
89                  FROM msgs m LEFT JOIN msgs_mdns mdns ON mdns.msg_id=m.id
90                  WHERE id=?
91                  LIMIT 1",
92                (self,),
93                |row| {
94                    let state: MessageState = row.get(0)?;
95                    let mdn_msg_id: Option<MsgId> = row.get(1)?;
96                    Ok(state.with_mdns(mdn_msg_id.is_some()))
97                },
98            )
99            .await?
100            .unwrap_or_default();
101        Ok(result)
102    }
103
104    pub(crate) async fn get_param(self, context: &Context) -> Result<Params> {
105        let res: Option<String> = context
106            .sql
107            .query_get_value("SELECT param FROM msgs WHERE id=?", (self,))
108            .await?;
109        Ok(res
110            .map(|s| s.parse().unwrap_or_default())
111            .unwrap_or_default())
112    }
113
114    /// Put message into trash chat and delete message text.
115    ///
116    /// It means the message is deleted locally, but not on the server.
117    /// We keep some infos to
118    /// 1. not download the same message again
119    /// 2. be able to delete the message on the server if we want to
120    ///
121    /// * `on_server`: Delete the message on the server also if it is seen on IMAP later, but only
122    ///   if all parts of the message are trashed with this flag. `true` if the user explicitly
123    ///   deletes the message. As for trashing a partially downloaded message when replacing it with
124    ///   a fully downloaded one, see `receive_imf::add_parts()`.
125    pub(crate) async fn trash(self, context: &Context, on_server: bool) -> Result<()> {
126        context
127            .sql
128            .execute(
129                // If you change which information is preserved here, also change
130                // `ChatId::delete_ex()`, `delete_expired_messages()` and which information
131                // `receive_imf::add_parts()` still adds to the db if chat_id is TRASH.
132                "
133INSERT OR REPLACE INTO msgs (id, rfc724_mid, pre_rfc724_mid, timestamp, chat_id, deleted)
134SELECT ?1, rfc724_mid, pre_rfc724_mid, timestamp, ?, ? FROM msgs WHERE id=?1
135                ",
136                (self, DC_CHAT_ID_TRASH, on_server),
137            )
138            .await?;
139
140        Ok(())
141    }
142
143    pub(crate) async fn set_delivered(self, context: &Context) -> Result<()> {
144        update_msg_state(context, self, MessageState::OutDelivered).await?;
145        let chat_id: Option<ChatId> = context
146            .sql
147            .query_get_value("SELECT chat_id FROM msgs WHERE id=?", (self,))
148            .await?;
149        context.emit_event(EventType::MsgDelivered {
150            chat_id: chat_id.unwrap_or_default(),
151            msg_id: self,
152        });
153        if let Some(chat_id) = chat_id {
154            chatlist_events::emit_chatlist_item_changed(context, chat_id);
155        }
156        Ok(())
157    }
158
159    /// Bad evil escape hatch.
160    ///
161    /// Avoid using this, eventually types should be cleaned up enough
162    /// that it is no longer necessary.
163    pub fn to_u32(self) -> u32 {
164        self.0
165    }
166
167    /// Returns server foldernames and UIDs of a message, used for message info
168    pub async fn get_info_server_urls(
169        context: &Context,
170        rfc724_mid: String,
171    ) -> Result<Vec<String>> {
172        context
173            .sql
174            .query_map_vec(
175                "SELECT transports.addr, imap.folder, imap.uid
176                 FROM imap
177                 LEFT JOIN transports
178                 ON transports.id = imap.transport_id
179                 WHERE imap.rfc724_mid=?",
180                (rfc724_mid,),
181                |row| {
182                    let addr: String = row.get(0)?;
183                    let folder: String = row.get(1)?;
184                    let uid: u32 = row.get(2)?;
185                    Ok(format!("<{addr}/{folder}/;UID={uid}>"))
186                },
187            )
188            .await
189    }
190
191    /// Returns information about hops of a message, used for message info
192    pub async fn hop_info(self, context: &Context) -> Result<String> {
193        let hop_info = context
194            .sql
195            .query_get_value("SELECT IFNULL(hop_info, '') FROM msgs WHERE id=?", (self,))
196            .await?
197            .with_context(|| format!("Message {self} not found"))?;
198        Ok(hop_info)
199    }
200
201    /// Returns detailed message information in a multi-line text form.
202    pub async fn get_info(self, context: &Context) -> Result<String> {
203        let msg = Message::load_from_db(context, self).await?;
204
205        let mut ret = String::new();
206
207        let fts = timestamp_to_str(msg.get_timestamp());
208        ret += &format!("Sent: {fts}");
209
210        let from_contact = Contact::get_by_id(context, msg.from_id).await?;
211        let name = from_contact.get_display_name();
212        if let Some(override_sender_name) = msg.get_override_sender_name() {
213            ret += &format!(" by ~{override_sender_name}");
214        } else {
215            ret += &format!(" by {name}");
216        }
217        ret += "\n";
218
219        if msg.from_id != ContactId::SELF {
220            let s = timestamp_to_str(if 0 != msg.timestamp_rcvd {
221                msg.timestamp_rcvd
222            } else {
223                msg.timestamp_sort
224            });
225            ret += &format!("Received: {}", &s);
226            ret += "\n";
227        }
228
229        if let EphemeralTimer::Enabled { duration } = msg.ephemeral_timer {
230            ret += &format!("Ephemeral timer: {duration}\n");
231        }
232
233        if msg.ephemeral_timestamp != 0 {
234            ret += &format!("Expires: {}\n", timestamp_to_str(msg.ephemeral_timestamp));
235        }
236
237        if msg.from_id == ContactId::INFO || msg.to_id == ContactId::INFO {
238            // device-internal message, no further details needed
239            return Ok(ret);
240        }
241
242        if let Ok(rows) = context
243            .sql
244            .query_map_vec(
245                "SELECT contact_id, timestamp_sent FROM msgs_mdns WHERE msg_id=?",
246                (self,),
247                |row| {
248                    let contact_id: ContactId = row.get(0)?;
249                    let ts: i64 = row.get(1)?;
250                    Ok((contact_id, ts))
251                },
252            )
253            .await
254        {
255            for (contact_id, ts) in rows {
256                let fts = timestamp_to_str(ts);
257                ret += &format!("Read: {fts}");
258
259                let name = Contact::get_by_id(context, contact_id)
260                    .await
261                    .map(|contact| contact.get_display_name().to_owned())
262                    .unwrap_or_default();
263
264                ret += &format!(" by {name}");
265                ret += "\n";
266            }
267        }
268
269        ret += &format!("State: {}", msg.state);
270
271        if msg.has_location() {
272            ret += ", Location sent";
273        }
274
275        if 0 != msg.param.get_int(Param::GuaranteeE2ee).unwrap_or_default() {
276            ret += ", Encrypted";
277        }
278
279        ret += "\n";
280
281        let reactions = get_msg_reactions(context, self).await?;
282        if !reactions.is_empty() {
283            ret += &format!("Reactions: {reactions}\n");
284        }
285
286        if let Some(error) = msg.error.as_ref() {
287            ret += &format!("Error: {error}");
288        }
289
290        if let Some(path) = msg.get_file(context) {
291            let bytes = get_filebytes(context, &path).await?;
292            ret += &format!(
293                "\nFile: {}, name: {}, {} bytes\n",
294                path.display(),
295                msg.get_filename().unwrap_or_default(),
296                bytes
297            );
298        }
299
300        if msg.viewtype != Viewtype::Text {
301            ret += "Type: ";
302            ret += &format!("{}", msg.viewtype);
303            ret += "\n";
304            ret += &format!("Mimetype: {}\n", &msg.get_filemime().unwrap_or_default());
305        }
306        let w = msg.param.get_int(Param::Width).unwrap_or_default();
307        let h = msg.param.get_int(Param::Height).unwrap_or_default();
308        if w != 0 || h != 0 {
309            ret += &format!("Dimension: {w} x {h}\n",);
310        }
311        let duration = msg.param.get_int(Param::Duration).unwrap_or_default();
312        if duration != 0 {
313            ret += &format!("Duration: {duration} ms\n",);
314        }
315        if !msg.rfc724_mid.is_empty() {
316            ret += &format!("\nMessage-ID: {}", msg.rfc724_mid);
317
318            let server_urls = Self::get_info_server_urls(context, msg.rfc724_mid).await?;
319            for server_url in server_urls {
320                // Format as RFC 5092 relative IMAP URL.
321                ret += &format!("\nServer-URL: {server_url}");
322            }
323        }
324        let hop_info = self.hop_info(context).await?;
325
326        ret += "\n\n";
327        if hop_info.is_empty() {
328            ret += "No Hop Info";
329        } else {
330            ret += &hop_info;
331        }
332
333        Ok(ret)
334    }
335}
336
337impl std::fmt::Display for MsgId {
338    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339        write!(f, "Msg#{}", self.0)
340    }
341}
342
343/// Allow converting [MsgId] to an SQLite type.
344///
345/// This allows you to directly store [MsgId] into the database.
346///
347/// # Errors
348///
349/// This **does** ensure that no special message IDs are written into
350/// the database and the conversion will fail if this is not the case.
351impl rusqlite::types::ToSql for MsgId {
352    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
353        if self.0 <= DC_MSG_ID_LAST_SPECIAL {
354            return Err(rusqlite::Error::ToSqlConversionFailure(
355                format_err!("Invalid MsgId {}", self.0).into(),
356            ));
357        }
358        let val = rusqlite::types::Value::Integer(i64::from(self.0));
359        let out = rusqlite::types::ToSqlOutput::Owned(val);
360        Ok(out)
361    }
362}
363
364/// Allow converting an SQLite integer directly into [MsgId].
365impl rusqlite::types::FromSql for MsgId {
366    fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
367        // Would be nice if we could use match here, but alas.
368        i64::column_result(value).and_then(|val| {
369            if 0 <= val && val <= i64::from(u32::MAX) {
370                Ok(MsgId::new(val as u32))
371            } else {
372                Err(rusqlite::types::FromSqlError::OutOfRange(val))
373            }
374        })
375    }
376}
377
378#[derive(
379    Debug,
380    Copy,
381    Clone,
382    PartialEq,
383    FromPrimitive,
384    ToPrimitive,
385    FromSql,
386    ToSql,
387    Serialize,
388    Deserialize,
389    Default,
390)]
391#[repr(u8)]
392pub(crate) enum MessengerMessage {
393    #[default]
394    No = 0,
395    Yes = 1,
396
397    /// No, but reply to messenger message.
398    Reply = 2,
399}
400
401/// An object representing a single message in memory.
402/// The message object is not updated.
403/// If you want an update, you have to recreate the object.
404#[derive(Debug, Clone, Default, Serialize, Deserialize)]
405pub struct Message {
406    /// Message ID.
407    pub(crate) id: MsgId,
408
409    /// `From:` contact ID.
410    pub(crate) from_id: ContactId,
411
412    /// ID of the first contact in the `To:` header.
413    pub(crate) to_id: ContactId,
414
415    /// ID of the chat message belongs to.
416    pub(crate) chat_id: ChatId,
417
418    /// Type of the message.
419    pub(crate) viewtype: Viewtype,
420
421    /// State of the message.
422    pub(crate) state: MessageState,
423    pub(crate) download_state: DownloadState,
424
425    /// Whether the message is hidden.
426    pub(crate) hidden: bool,
427    pub(crate) timestamp_sort: i64,
428    pub(crate) timestamp_sent: i64,
429    pub(crate) timestamp_rcvd: i64,
430    pub(crate) ephemeral_timer: EphemeralTimer,
431    pub(crate) ephemeral_timestamp: i64,
432    pub(crate) text: String,
433    /// Text that is added to the end of Message.text
434    ///
435    /// Currently used for adding the download information on pre-messages
436    pub(crate) additional_text: String,
437
438    /// Message subject.
439    ///
440    /// If empty, a default subject will be generated when sending.
441    pub(crate) subject: String,
442
443    /// `Message-ID` header value.
444    pub(crate) rfc724_mid: String,
445    /// `Message-ID` header value of the pre-message, if any.
446    pub(crate) pre_rfc724_mid: String,
447
448    /// `In-Reply-To` header value.
449    pub(crate) in_reply_to: Option<String>,
450    pub(crate) is_dc_message: MessengerMessage,
451    pub(crate) original_msg_id: MsgId,
452    pub(crate) mime_modified: bool,
453    pub(crate) chat_visibility: ChatVisibility,
454    pub(crate) chat_blocked: Blocked,
455    pub(crate) location_id: u32,
456    pub(crate) error: Option<String>,
457    pub(crate) param: Params,
458}
459
460impl Message {
461    /// Creates a new message with given view type.
462    pub fn new(viewtype: Viewtype) -> Self {
463        Message {
464            viewtype,
465            rfc724_mid: create_outgoing_rfc724_mid(),
466            ..Default::default()
467        }
468    }
469
470    /// Creates a new message with Viewtype::Text.
471    pub fn new_text(text: String) -> Self {
472        Message {
473            viewtype: Viewtype::Text,
474            text,
475            rfc724_mid: create_outgoing_rfc724_mid(),
476            ..Default::default()
477        }
478    }
479
480    /// Loads message with given ID from the database.
481    ///
482    /// Returns an error if the message does not exist.
483    pub async fn load_from_db(context: &Context, id: MsgId) -> Result<Message> {
484        let message = Self::load_from_db_optional(context, id)
485            .await?
486            .with_context(|| format!("Message {id} does not exist"))?;
487        Ok(message)
488    }
489
490    /// Loads message with given ID from the database.
491    ///
492    /// Returns `None` if the message does not exist.
493    pub async fn load_from_db_optional(context: &Context, id: MsgId) -> Result<Option<Message>> {
494        ensure!(
495            !id.is_special(),
496            "Can not load special message ID {id} from DB"
497        );
498        let mut msg = context
499            .sql
500            .query_row_optional(
501                "SELECT
502                    m.id AS id,
503                    rfc724_mid AS rfc724mid,
504                    pre_rfc724_mid AS pre_rfc724mid,
505                    m.mime_in_reply_to AS mime_in_reply_to,
506                    m.chat_id AS chat_id,
507                    m.from_id AS from_id,
508                    m.to_id AS to_id,
509                    m.timestamp AS timestamp,
510                    m.timestamp_sent AS timestamp_sent,
511                    m.timestamp_rcvd AS timestamp_rcvd,
512                    m.ephemeral_timer AS ephemeral_timer,
513                    m.ephemeral_timestamp AS ephemeral_timestamp,
514                    m.type AS type,
515                    m.state AS state,
516                    mdns.msg_id AS mdn_msg_id,
517                    m.download_state AS download_state,
518                    m.error AS error,
519                    m.msgrmsg AS msgrmsg,
520                    m.starred AS original_msg_id,
521                    m.mime_modified AS mime_modified,
522                    m.txt AS txt,
523                    m.subject AS subject,
524                    m.param AS param,
525                    m.hidden AS hidden,
526                    m.location_id AS location,
527                    c.archived AS visibility,
528                    c.blocked AS blocked
529                 FROM msgs m
530                 LEFT JOIN chats c ON c.id=m.chat_id
531                 LEFT JOIN msgs_mdns mdns ON mdns.msg_id=m.id
532                 WHERE m.id=? AND chat_id!=3
533                 LIMIT 1",
534                (id,),
535                |row| {
536                    let state: MessageState = row.get("state")?;
537                    let mdn_msg_id: Option<MsgId> = row.get("mdn_msg_id")?;
538                    let text = match row.get_ref("txt")? {
539                        rusqlite::types::ValueRef::Text(buf) => {
540                            match String::from_utf8(buf.to_vec()) {
541                                Ok(t) => t,
542                                Err(_) => {
543                                    warn!(
544                                        context,
545                                        concat!(
546                                            "dc_msg_load_from_db: could not get ",
547                                            "text column as non-lossy utf8 id {}"
548                                        ),
549                                        id
550                                    );
551                                    String::from_utf8_lossy(buf).into_owned()
552                                }
553                            }
554                        }
555                        _ => String::new(),
556                    };
557                    let msg = Message {
558                        id: row.get("id")?,
559                        rfc724_mid: row.get::<_, String>("rfc724mid")?,
560                        pre_rfc724_mid: row.get::<_, String>("pre_rfc724mid")?,
561                        in_reply_to: row
562                            .get::<_, Option<String>>("mime_in_reply_to")?
563                            .and_then(|in_reply_to| parse_message_id(&in_reply_to).ok()),
564                        chat_id: row.get("chat_id")?,
565                        from_id: row.get("from_id")?,
566                        to_id: row.get("to_id")?,
567                        timestamp_sort: row.get("timestamp")?,
568                        timestamp_sent: row.get("timestamp_sent")?,
569                        timestamp_rcvd: row.get("timestamp_rcvd")?,
570                        ephemeral_timer: row.get("ephemeral_timer")?,
571                        ephemeral_timestamp: row.get("ephemeral_timestamp")?,
572                        viewtype: row.get("type").unwrap_or_default(),
573                        state: state.with_mdns(mdn_msg_id.is_some()),
574                        download_state: row.get("download_state")?,
575                        error: Some(row.get::<_, String>("error")?)
576                            .filter(|error| !error.is_empty()),
577                        is_dc_message: row.get("msgrmsg")?,
578                        original_msg_id: row.get("original_msg_id")?,
579                        mime_modified: row.get("mime_modified")?,
580                        text,
581                        additional_text: String::new(),
582                        subject: row.get("subject")?,
583                        param: row.get::<_, String>("param")?.parse().unwrap_or_default(),
584                        hidden: row.get("hidden")?,
585                        location_id: row.get("location")?,
586                        chat_visibility: row.get::<_, Option<_>>("visibility")?.unwrap_or_default(),
587                        chat_blocked: row
588                            .get::<_, Option<Blocked>>("blocked")?
589                            .unwrap_or_default(),
590                    };
591                    Ok(msg)
592                },
593            )
594            .await
595            .with_context(|| format!("failed to load message {id} from the database"))?;
596
597        if let Some(msg) = &mut msg {
598            msg.additional_text =
599                Self::get_additional_text(context, msg.download_state, &msg.param)?;
600        }
601
602        Ok(msg)
603    }
604
605    /// Returns additional text which is appended to the message's text field
606    /// when it is loaded from the database.
607    /// Currently this is used to add infomation to pre-messages of what the download will be and how large it is
608    fn get_additional_text(
609        context: &Context,
610        download_state: DownloadState,
611        param: &Params,
612    ) -> Result<String> {
613        if download_state != DownloadState::Done {
614            let file_size = param
615                .get(Param::PostMessageFileBytes)
616                .and_then(|s| s.parse().ok())
617                .map(|file_size: usize| format_size(file_size, BINARY))
618                .unwrap_or("?".to_owned());
619            let viewtype = param
620                .get_i64(Param::PostMessageViewtype)
621                .and_then(Viewtype::from_i64)
622                .unwrap_or(Viewtype::Unknown);
623            let file_name = param
624                .get(Param::Filename)
625                .map(sanitize_filename)
626                .unwrap_or("?".to_owned());
627
628            return match viewtype {
629                Viewtype::File => Ok(format!(" [{file_name} – {file_size}]")),
630                _ => {
631                    let translated_viewtype = viewtype.to_locale_string(context);
632                    Ok(format!(" [{translated_viewtype} – {file_size}]"))
633                }
634            };
635        }
636        Ok(String::new())
637    }
638
639    /// Returns the MIME type of an attached file if it exists.
640    ///
641    /// If the MIME type is not known, the function guesses the MIME type
642    /// from the extension. `application/octet-stream` is used as a fallback
643    /// if MIME type is not known, but `None` is only returned if no file
644    /// is attached.
645    pub fn get_filemime(&self) -> Option<String> {
646        if let Some(m) = self.param.get(Param::MimeType) {
647            return Some(m.to_string());
648        } else if self.param.exists(Param::File) {
649            if let Some((_, mime)) = guess_msgtype_from_suffix(self) {
650                return Some(mime.to_string());
651            }
652            // we have a file but no mimetype, let's use a generic one
653            return Some("application/octet-stream".to_string());
654        }
655        // no mimetype and no file
656        None
657    }
658
659    /// Returns the full path to the file associated with a message.
660    pub fn get_file(&self, context: &Context) -> Option<PathBuf> {
661        self.param.get_file_path(context).unwrap_or(None)
662    }
663
664    /// Returns vector of vcards if the file has a vCard attachment.
665    pub async fn vcard_contacts(&self, context: &Context) -> Result<Vec<VcardContact>> {
666        if self.viewtype != Viewtype::Vcard {
667            return Ok(Vec::new());
668        }
669
670        let path = self
671            .get_file(context)
672            .context("vCard message does not have an attachment")?;
673        let bytes = tokio::fs::read(path).await?;
674        let vcard_contents = std::str::from_utf8(&bytes).context("vCard is not a valid UTF-8")?;
675        Ok(parse_vcard(vcard_contents))
676    }
677
678    /// Save file copy at the user-provided path.
679    pub async fn save_file(&self, context: &Context, path: &Path) -> Result<()> {
680        let path_src = self.get_file(context).context("No file")?;
681        let mut src = fs::OpenOptions::new().read(true).open(path_src).await?;
682        let mut dst = fs::OpenOptions::new()
683            .write(true)
684            .create_new(true)
685            .open(path)
686            .await?;
687        io::copy(&mut src, &mut dst).await?;
688        Ok(())
689    }
690
691    /// If message is an image or gif, set Param::Width and Param::Height
692    pub(crate) async fn try_calc_and_set_dimensions(&mut self, context: &Context) -> Result<()> {
693        if self.viewtype.has_file() {
694            let file_param = self.param.get_file_path(context)?;
695            if let Some(path_and_filename) = file_param
696                && matches!(
697                    self.viewtype,
698                    Viewtype::Image | Viewtype::Gif | Viewtype::Sticker
699                )
700                && !self.param.exists(Param::Width)
701            {
702                let buf = read_file(context, &path_and_filename).await?;
703
704                match get_filemeta(&buf) {
705                    Ok((width, height)) => {
706                        self.param.set_int(Param::Width, width as i32);
707                        self.param.set_int(Param::Height, height as i32);
708                    }
709                    Err(err) => {
710                        self.param.set_int(Param::Width, 0);
711                        self.param.set_int(Param::Height, 0);
712                        warn!(
713                            context,
714                            "Failed to get width and height for {}: {err:#}.",
715                            path_and_filename.display()
716                        );
717                    }
718                }
719
720                if !self.id.is_unset() {
721                    self.update_param(context).await?;
722                }
723            }
724        }
725        Ok(())
726    }
727
728    /// Check if a message has a POI location bound to it.
729    /// These locations are also returned by [`location::get_range()`].
730    /// The UI may decide to display a special icon beside such messages.
731    ///
732    /// [`location::get_range()`]: crate::location::get_range
733    pub fn has_location(&self) -> bool {
734        self.location_id != 0
735    }
736
737    /// Set any location that should be bound to the message object.
738    /// The function is useful to add a marker to the map
739    /// at a position different from the self-location.
740    /// You should not call this function
741    /// if you want to bind the current self-location to a message;
742    /// this is done by [`location::set()`] and [`send_locations_to_chat()`].
743    ///
744    /// Typically results in the event [`LocationChanged`] with
745    /// `contact_id` set to [`ContactId::SELF`].
746    ///
747    /// `latitude` is the North-south position of the location.
748    /// `longitude` is the East-west position of the location.
749    ///
750    /// [`location::set()`]: crate::location::set
751    /// [`send_locations_to_chat()`]: crate::location::send_locations_to_chat
752    /// [`LocationChanged`]: crate::events::EventType::LocationChanged
753    pub fn set_location(&mut self, latitude: f64, longitude: f64) {
754        if latitude == 0.0 && longitude == 0.0 {
755            return;
756        }
757
758        self.param.set_float(Param::SetLatitude, latitude);
759        self.param.set_float(Param::SetLongitude, longitude);
760    }
761
762    /// Returns the message timestamp for display in the UI
763    /// as a unix timestamp in seconds.
764    pub fn get_timestamp(&self) -> i64 {
765        if 0 != self.timestamp_sent {
766            self.timestamp_sent
767        } else {
768            self.timestamp_sort
769        }
770    }
771
772    /// Returns the message ID.
773    pub fn get_id(&self) -> MsgId {
774        self.id
775    }
776
777    /// Returns the rfc724 message ID
778    /// May be empty
779    pub fn rfc724_mid(&self) -> &str {
780        &self.rfc724_mid
781    }
782
783    /// Returns the ID of the contact who wrote the message.
784    pub fn get_from_id(&self) -> ContactId {
785        self.from_id
786    }
787
788    /// Returns the chat ID.
789    pub fn get_chat_id(&self) -> ChatId {
790        self.chat_id
791    }
792
793    /// Returns the type of the message.
794    pub fn get_viewtype(&self) -> Viewtype {
795        self.viewtype
796    }
797
798    /// Forces the message to **keep** [Viewtype::Sticker]
799    /// e.g the message will not be converted to a [Viewtype::Image].
800    pub fn force_sticker(&mut self) {
801        self.param.set_int(Param::ForceSticker, 1);
802    }
803
804    /// Returns the state of the message.
805    pub fn get_state(&self) -> MessageState {
806        self.state
807    }
808
809    /// Returns the message receive time as a unix timestamp in seconds.
810    pub fn get_received_timestamp(&self) -> i64 {
811        self.timestamp_rcvd
812    }
813
814    /// Returns the timestamp of the message for sorting.
815    pub fn get_sort_timestamp(&self) -> i64 {
816        if self.timestamp_sort != 0 {
817            self.timestamp_sort
818        } else {
819            self.timestamp_sent
820        }
821    }
822
823    /// Returns the text of the message.
824    ///
825    /// Currently this includes `additional_text`, but this may change in future, when the UIs show
826    /// the necessary info themselves.
827    pub fn get_text(&self) -> String {
828        self.text.clone() + &self.additional_text
829    }
830
831    /// Returns message subject.
832    pub fn get_subject(&self) -> &str {
833        &self.subject
834    }
835
836    /// Returns original filename (as shown in chat).
837    ///
838    /// To get the full path, use [`Self::get_file()`].
839    pub fn get_filename(&self) -> Option<String> {
840        if let Some(name) = self.param.get(Param::Filename) {
841            return Some(sanitize_filename(name));
842        }
843        self.param
844            .get(Param::File)
845            .and_then(|file| Path::new(file).file_name())
846            .map(|name| sanitize_filename(&name.to_string_lossy()))
847    }
848
849    /// Returns the size of the file in bytes, if applicable.
850    /// If message is a pre-message, then this returns the size of the file to be downloaded.
851    pub async fn get_filebytes(&self, context: &Context) -> Result<Option<u64>> {
852        if self.download_state != DownloadState::Done
853            && let Some(file_size) = self
854                .param
855                .get(Param::PostMessageFileBytes)
856                .and_then(|s| s.parse().ok())
857        {
858            return Ok(Some(file_size));
859        }
860        if let Some(path) = self.param.get_file_path(context)? {
861            Ok(Some(get_filebytes(context, &path).await.with_context(
862                || format!("failed to get {} size in bytes", path.display()),
863            )?))
864        } else {
865            Ok(None)
866        }
867    }
868
869    /// If message is a Pre-Message,
870    /// then this returns the viewtype it will have when it is downloaded.
871    #[cfg(test)]
872    pub(crate) fn get_post_message_viewtype(&self) -> Option<Viewtype> {
873        if self.download_state != DownloadState::Done {
874            return self
875                .param
876                .get_i64(Param::PostMessageViewtype)
877                .and_then(Viewtype::from_i64);
878        }
879        None
880    }
881
882    /// Returns width of associated image or video file.
883    pub fn get_width(&self) -> i32 {
884        self.param.get_int(Param::Width).unwrap_or_default()
885    }
886
887    /// Returns height of associated image or video file.
888    pub fn get_height(&self) -> i32 {
889        self.param.get_int(Param::Height).unwrap_or_default()
890    }
891
892    /// Returns duration of associated audio or video file.
893    pub fn get_duration(&self) -> i32 {
894        self.param.get_int(Param::Duration).unwrap_or_default()
895    }
896
897    /// Returns true if padlock indicating message encryption should be displayed in the UI.
898    pub fn get_showpadlock(&self) -> bool {
899        self.param.get_int(Param::GuaranteeE2ee).unwrap_or_default() != 0
900            || self.from_id == ContactId::DEVICE
901    }
902
903    /// Returns true if message is auto-generated.
904    pub fn is_bot(&self) -> bool {
905        self.param.get_bool(Param::Bot).unwrap_or_default()
906    }
907
908    /// Return the ephemeral timer duration for a message.
909    pub fn get_ephemeral_timer(&self) -> EphemeralTimer {
910        self.ephemeral_timer
911    }
912
913    /// Returns the timestamp of the epehemeral message removal.
914    pub fn get_ephemeral_timestamp(&self) -> i64 {
915        self.ephemeral_timestamp
916    }
917
918    /// Returns message summary for display in the search results.
919    pub async fn get_summary(&self, context: &Context, chat: Option<&Chat>) -> Result<Summary> {
920        let chat_loaded: Chat;
921        let chat = if let Some(chat) = chat {
922            chat
923        } else {
924            let chat = Chat::load_from_db(context, self.chat_id).await?;
925            chat_loaded = chat;
926            &chat_loaded
927        };
928
929        let contact = if self.from_id != ContactId::SELF {
930            match chat.typ {
931                Chattype::Group | Chattype::Mailinglist => {
932                    Some(Contact::get_by_id(context, self.from_id).await?)
933                }
934                Chattype::Single | Chattype::OutBroadcast | Chattype::InBroadcast => None,
935            }
936        } else {
937            None
938        };
939
940        Summary::new(context, self, chat, contact.as_ref()).await
941    }
942
943    // It's a little unfortunate that the UI has to first call `dc_msg_get_override_sender_name` and then if it was `NULL`, call
944    // `dc_contact_get_display_name` but this was the best solution:
945    // - We could load a Contact struct from the db here to call `dc_get_display_name` instead of returning `None`, but then we had a db
946    //   call every time (and this fn is called a lot while the user is scrolling through a group), so performance would be bad
947    // - We could pass both a Contact struct and a Message struct in the FFI, but at least on Android we would need to handle raw
948    //   C-data in the Java code (i.e. a `long` storing a C pointer)
949    // - We can't make a param `SenderDisplayname` for messages as sometimes the display name of a contact changes, and we want to show
950    //   the same display name over all messages from the same sender.
951    /// Returns the name that should be shown over the message instead of the contact display ame.
952    pub fn get_override_sender_name(&self) -> Option<String> {
953        self.param
954            .get(Param::OverrideSenderDisplayname)
955            .map(|name| name.to_string())
956    }
957
958    // Exposing this function over the ffi instead of get_override_sender_name() would mean that at least Android Java code has
959    // to handle raw C-data (as it is done for msg_get_summary())
960    pub(crate) fn get_sender_name(&self, contact: &Contact) -> String {
961        self.get_override_sender_name()
962            .unwrap_or_else(|| contact.get_display_name().to_string())
963    }
964
965    /// Returns true if a message has a deviating timestamp.
966    ///
967    /// A message has a deviating timestamp when it is sent on
968    /// another day as received/sorted by.
969    #[expect(clippy::arithmetic_side_effects)]
970    pub fn has_deviating_timestamp(&self) -> bool {
971        let cnv_to_local = gm2local_offset();
972        let sort_timestamp = self.get_sort_timestamp() + cnv_to_local;
973        let send_timestamp = self.get_timestamp() + cnv_to_local;
974
975        sort_timestamp / 86400 != send_timestamp / 86400
976    }
977
978    /// Returns true if the message was successfully delivered to the outgoing server or even
979    /// received a read receipt.
980    pub fn is_sent(&self) -> bool {
981        self.state >= MessageState::OutDelivered
982    }
983
984    /// Returns true if the message is a forwarded message.
985    pub fn is_forwarded(&self) -> bool {
986        self.param.get_int(Param::Forwarded).is_some()
987    }
988
989    /// Returns true if the message is edited.
990    pub fn is_edited(&self) -> bool {
991        self.param.get_bool(Param::IsEdited).unwrap_or_default()
992    }
993
994    /// Returns true if the message is an informational message.
995    pub fn is_info(&self) -> bool {
996        let cmd = self.param.get_cmd();
997        self.from_id == ContactId::INFO
998            || self.to_id == ContactId::INFO
999            || cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage
1000    }
1001
1002    /// Returns the type of an informational message.
1003    pub fn get_info_type(&self) -> SystemMessage {
1004        self.param.get_cmd()
1005    }
1006
1007    /// Return the contact ID of the profile to open when tapping the info message.
1008    pub async fn get_info_contact_id(&self, context: &Context) -> Result<Option<ContactId>> {
1009        match self.param.get_cmd() {
1010            SystemMessage::GroupNameChanged
1011            | SystemMessage::GroupDescriptionChanged
1012            | SystemMessage::GroupImageChanged
1013            | SystemMessage::EphemeralTimerChanged => {
1014                if self.from_id != ContactId::INFO {
1015                    Ok(Some(self.from_id))
1016                } else {
1017                    Ok(None)
1018                }
1019            }
1020
1021            SystemMessage::MemberAddedToGroup | SystemMessage::MemberRemovedFromGroup => {
1022                if let Some(contact_i32) = self.param.get_int(Param::ContactAddedRemoved) {
1023                    let contact_id = ContactId::new(contact_i32.try_into()?);
1024                    if contact_id == ContactId::SELF
1025                        || Contact::real_exists_by_id(context, contact_id).await?
1026                    {
1027                        Ok(Some(contact_id))
1028                    } else {
1029                        Ok(None)
1030                    }
1031                } else {
1032                    Ok(None)
1033                }
1034            }
1035
1036            SystemMessage::AutocryptSetupMessage
1037            | SystemMessage::SecurejoinMessage
1038            | SystemMessage::LocationStreamingEnabled
1039            | SystemMessage::LocationOnly
1040            | SystemMessage::ChatE2ee
1041            | SystemMessage::ChatProtectionEnabled
1042            | SystemMessage::ChatProtectionDisabled
1043            | SystemMessage::InvalidUnencryptedMail
1044            | SystemMessage::SecurejoinWait
1045            | SystemMessage::SecurejoinWaitTimeout
1046            | SystemMessage::MultiDeviceSync
1047            | SystemMessage::WebxdcStatusUpdate
1048            | SystemMessage::WebxdcInfoMessage
1049            | SystemMessage::IrohNodeAddr
1050            | SystemMessage::CallAccepted
1051            | SystemMessage::CallEnded
1052            | SystemMessage::Unknown => Ok(None),
1053        }
1054    }
1055
1056    /// Returns true if the message is a system message.
1057    pub fn is_system_message(&self) -> bool {
1058        let cmd = self.param.get_cmd();
1059        cmd != SystemMessage::Unknown
1060    }
1061
1062    /// Sets or unsets message text.
1063    pub fn set_text(&mut self, text: String) {
1064        self.text = text;
1065    }
1066
1067    /// Sets the email's subject. If it's empty, a default subject
1068    /// will be used (e.g. `Message from Alice` or `Re: <last subject>`).
1069    pub fn set_subject(&mut self, subject: String) {
1070        self.subject = subject;
1071    }
1072
1073    /// Sets the file associated with a message, deduplicating files with the same name.
1074    ///
1075    /// If `name` is Some, it is used as the file name
1076    /// and the actual current name of the file is ignored.
1077    ///
1078    /// If the source file is already in the blobdir, it will be renamed,
1079    /// otherwise it will be copied to the blobdir first.
1080    ///
1081    /// In order to deduplicate files that contain the same data,
1082    /// the file will be named `<hash>.<extension>`, e.g. `ce940175885d7b78f7b7e9f1396611f.jpg`.
1083    ///
1084    /// NOTE:
1085    /// - This function will rename the file. To get the new file path, call `get_file()`.
1086    /// - The file must not be modified after this function was called.
1087    pub fn set_file_and_deduplicate(
1088        &mut self,
1089        context: &Context,
1090        file: &Path,
1091        name: Option<&str>,
1092        filemime: Option<&str>,
1093    ) -> Result<()> {
1094        let name = if let Some(name) = name {
1095            name.to_string()
1096        } else {
1097            file.file_name()
1098                .map(|s| s.to_string_lossy().to_string())
1099                .unwrap_or_else(|| "unknown_file".to_string())
1100        };
1101
1102        let blob = BlobObject::create_and_deduplicate(context, file, Path::new(&name))?;
1103        self.param.set(Param::File, blob.as_name());
1104
1105        self.param.set(Param::Filename, name);
1106        self.param.set_optional(Param::MimeType, filemime);
1107
1108        Ok(())
1109    }
1110
1111    /// Creates a new blob and sets it as a file associated with a message.
1112    ///
1113    /// In order to deduplicate files that contain the same data,
1114    /// the file will be named `<hash>.<extension>`, e.g. `ce940175885d7b78f7b7e9f1396611f.jpg`.
1115    ///
1116    /// NOTE: The file must not be modified after this function was called.
1117    pub fn set_file_from_bytes(
1118        &mut self,
1119        context: &Context,
1120        name: &str,
1121        data: &[u8],
1122        filemime: Option<&str>,
1123    ) -> Result<()> {
1124        let blob = BlobObject::create_and_deduplicate_from_bytes(context, data, name)?;
1125        self.param.set(Param::Filename, name);
1126        self.param.set(Param::File, blob.as_name());
1127        self.param.set_optional(Param::MimeType, filemime);
1128
1129        Ok(())
1130    }
1131
1132    /// Makes message a vCard-containing message using the specified contacts.
1133    pub async fn make_vcard(&mut self, context: &Context, contacts: &[ContactId]) -> Result<()> {
1134        ensure!(
1135            matches!(self.viewtype, Viewtype::File | Viewtype::Vcard),
1136            "Wrong viewtype for vCard: {}",
1137            self.viewtype,
1138        );
1139        let vcard = contact::make_vcard(context, contacts).await?;
1140        self.set_file_from_bytes(context, "vcard.vcf", vcard.as_bytes(), None)
1141    }
1142
1143    /// Updates message state from the vCard attachment.
1144    pub(crate) async fn try_set_vcard(&mut self, context: &Context, path: &Path) -> Result<()> {
1145        let vcard = fs::read(path)
1146            .await
1147            .with_context(|| format!("Could not read {path:?}"))?;
1148        if let Some(summary) = get_vcard_summary(&vcard) {
1149            self.param.set(Param::Summary1, summary);
1150        } else {
1151            warn!(context, "try_set_vcard: Not a valid DeltaChat vCard.");
1152            self.viewtype = Viewtype::File;
1153        }
1154        Ok(())
1155    }
1156
1157    /// Set different sender name for a message.
1158    /// This overrides the name set by the `set_config()`-option `displayname`.
1159    pub fn set_override_sender_name(&mut self, name: Option<String>) {
1160        self.param
1161            .set_optional(Param::OverrideSenderDisplayname, name);
1162    }
1163
1164    /// Sets the dimensions of associated image or video file.
1165    pub fn set_dimension(&mut self, width: i32, height: i32) {
1166        self.param.set_int(Param::Width, width);
1167        self.param.set_int(Param::Height, height);
1168    }
1169
1170    /// Sets the duration of associated audio or video file.
1171    pub fn set_duration(&mut self, duration: i32) {
1172        self.param.set_int(Param::Duration, duration);
1173    }
1174
1175    /// Marks the message as reaction.
1176    pub(crate) fn set_reaction(&mut self) {
1177        self.param.set_int(Param::Reaction, 1);
1178    }
1179
1180    /// Changes the message width, height or duration,
1181    /// and stores it into the database.
1182    pub async fn latefiling_mediasize(
1183        &mut self,
1184        context: &Context,
1185        width: i32,
1186        height: i32,
1187        duration: i32,
1188    ) -> Result<()> {
1189        if width > 0 && height > 0 {
1190            self.param.set_int(Param::Width, width);
1191            self.param.set_int(Param::Height, height);
1192        }
1193        if duration > 0 {
1194            self.param.set_int(Param::Duration, duration);
1195        }
1196        self.update_param(context).await?;
1197        Ok(())
1198    }
1199
1200    /// Sets message quote text.
1201    ///
1202    /// If `text` is `Some((text_str, protect))`, `protect` specifies whether `text_str` should only
1203    /// be sent encrypted. If it should, but the message is unencrypted, `text_str` is replaced with
1204    /// "...".
1205    pub fn set_quote_text(&mut self, text: Option<(String, bool)>) {
1206        let Some((text, protect)) = text else {
1207            self.param.remove(Param::Quote);
1208            self.param.remove(Param::ProtectQuote);
1209            return;
1210        };
1211        self.param.set(Param::Quote, text);
1212        self.param.set_optional(
1213            Param::ProtectQuote,
1214            match protect {
1215                true => Some("1"),
1216                false => None,
1217            },
1218        );
1219    }
1220
1221    /// Sets message quote.
1222    ///
1223    /// Message-Id is used to set Reply-To field, message text is used for quote.
1224    ///
1225    /// Encryption is required if quoted message was encrypted.
1226    ///
1227    /// The message itself is not required to exist in the database,
1228    /// it may even be deleted from the database by the time the message is prepared.
1229    pub async fn set_quote(&mut self, context: &Context, quote: Option<&Message>) -> Result<()> {
1230        if let Some(quote) = quote {
1231            ensure!(
1232                !quote.rfc724_mid.is_empty(),
1233                "Message without Message-Id cannot be quoted"
1234            );
1235            self.in_reply_to = Some(quote.rfc724_mid.clone());
1236
1237            let text = quote.get_text();
1238            let text = if text.is_empty() {
1239                // Use summary, similar to "Image" to avoid sending empty quote.
1240                quote
1241                    .get_summary(context, None)
1242                    .await?
1243                    .truncated_text(500)
1244                    .to_string()
1245            } else {
1246                text
1247            };
1248            self.set_quote_text(Some((
1249                text,
1250                quote
1251                    .param
1252                    .get_bool(Param::GuaranteeE2ee)
1253                    .unwrap_or_default(),
1254            )));
1255        } else {
1256            self.in_reply_to = None;
1257            self.set_quote_text(None);
1258        }
1259
1260        Ok(())
1261    }
1262
1263    /// Returns quoted message text, if any.
1264    pub fn quoted_text(&self) -> Option<String> {
1265        self.param.get(Param::Quote).map(|s| s.to_string())
1266    }
1267
1268    /// Returns quoted message, if any.
1269    pub async fn quoted_message(&self, context: &Context) -> Result<Option<Message>> {
1270        if self.param.get(Param::Quote).is_some() && !self.is_forwarded() {
1271            return self.parent(context).await;
1272        }
1273        Ok(None)
1274    }
1275
1276    /// Returns parent message according to the `In-Reply-To` header
1277    /// if it exists in the database and is not trashed.
1278    ///
1279    /// `References` header is not taken into account.
1280    pub async fn parent(&self, context: &Context) -> Result<Option<Message>> {
1281        if let Some(in_reply_to) = &self.in_reply_to
1282            && let Some(msg_id) = rfc724_mid_exists(context, in_reply_to).await?
1283        {
1284            let msg = Message::load_from_db_optional(context, msg_id).await?;
1285            return Ok(msg);
1286        }
1287        Ok(None)
1288    }
1289
1290    /// Returns original message ID for message from "Saved Messages".
1291    pub async fn get_original_msg_id(&self, context: &Context) -> Result<Option<MsgId>> {
1292        if !self.original_msg_id.is_special()
1293            && let Some(msg) = Message::load_from_db_optional(context, self.original_msg_id).await?
1294        {
1295            return if msg.chat_id.is_trash() {
1296                Ok(None)
1297            } else {
1298                Ok(Some(msg.id))
1299            };
1300        }
1301        Ok(None)
1302    }
1303
1304    /// Check if the message was saved and returns the corresponding message inside "Saved Messages".
1305    /// UI can use this to show a symbol beside the message, indicating it was saved.
1306    /// The message can be un-saved by deleting the returned message.
1307    pub async fn get_saved_msg_id(&self, context: &Context) -> Result<Option<MsgId>> {
1308        let res: Option<MsgId> = context
1309            .sql
1310            .query_get_value(
1311                "SELECT id FROM msgs WHERE starred=? AND chat_id!=?",
1312                (self.id, DC_CHAT_ID_TRASH),
1313            )
1314            .await?;
1315        Ok(res)
1316    }
1317
1318    /// Force the message to be sent in plain text.
1319    pub(crate) fn force_plaintext(&mut self) {
1320        self.param.set_int(Param::ForcePlaintext, 1);
1321    }
1322
1323    /// Updates `param` column of the message in the database without changing other columns.
1324    pub async fn update_param(&self, context: &Context) -> Result<()> {
1325        context
1326            .sql
1327            .execute(
1328                "UPDATE msgs SET param=? WHERE id=?;",
1329                (self.param.to_string(), self.id),
1330            )
1331            .await?;
1332        Ok(())
1333    }
1334
1335    /// Gets the error status of the message.
1336    ///
1337    /// A message can have an associated error status if something went wrong when sending or
1338    /// receiving message itself.  The error status is free-form text and should not be further parsed,
1339    /// rather it's presence is meant to indicate *something* went wrong with the message and the
1340    /// text of the error is detailed information on what.
1341    ///
1342    /// Some common reasons error can be associated with messages are:
1343    /// * Lack of valid signature on an e2ee message, usually for received messages.
1344    /// * Failure to decrypt an e2ee message, usually for received messages.
1345    /// * When a message could not be delivered to one or more recipients the non-delivery
1346    ///   notification text can be stored in the error status.
1347    pub fn error(&self) -> Option<String> {
1348        self.error.clone()
1349    }
1350}
1351
1352/// State of the message.
1353/// For incoming messages, stores the information on whether the message was read or not.
1354/// For outgoing message, the message could be pending, already delivered or confirmed.
1355#[derive(
1356    Debug,
1357    Default,
1358    Clone,
1359    Copy,
1360    PartialEq,
1361    Eq,
1362    PartialOrd,
1363    Ord,
1364    FromPrimitive,
1365    ToPrimitive,
1366    ToSql,
1367    FromSql,
1368    Serialize,
1369    Deserialize,
1370)]
1371#[repr(u32)]
1372pub enum MessageState {
1373    /// Undefined message state.
1374    #[default]
1375    Undefined = 0,
1376
1377    /// Incoming *fresh* message. Fresh messages are neither noticed
1378    /// nor seen and are typically shown in notifications.
1379    InFresh = 10,
1380
1381    /// Incoming *noticed* message. E.g. chat opened but message not
1382    /// yet read - noticed messages are not counted as unread but did
1383    /// not marked as read nor resulted in MDNs.
1384    InNoticed = 13,
1385
1386    /// Incoming message, really *seen* by the user. Marked as read on
1387    /// IMAP and MDN may be sent.
1388    InSeen = 16,
1389
1390    /// For files which need time to be prepared before they can be
1391    /// sent, the message enters this state before
1392    /// OutPending.
1393    ///
1394    /// Deprecated 2024-12-07.
1395    OutPreparing = 18,
1396
1397    /// Message saved as draft.
1398    OutDraft = 19,
1399
1400    /// The user has pressed the "send" button but the message is not
1401    /// yet sent and is pending in some way. Maybe we're offline (no
1402    /// checkmark).
1403    OutPending = 20,
1404
1405    /// *Unrecoverable* error (*recoverable* errors result in pending
1406    /// messages).
1407    OutFailed = 24,
1408
1409    /// Outgoing message successfully delivered to server (one
1410    /// checkmark). Note, that already delivered messages may get into
1411    /// the OutFailed state if we get such a hint from the server.
1412    OutDelivered = 26,
1413
1414    /// Outgoing message read by the recipient (two checkmarks; this
1415    /// requires goodwill on the receiver's side). Not used in the db for new messages.
1416    OutMdnRcvd = 28,
1417}
1418
1419impl std::fmt::Display for MessageState {
1420    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1421        write!(
1422            f,
1423            "{}",
1424            match self {
1425                Self::Undefined => "Undefined",
1426                Self::InFresh => "Fresh",
1427                Self::InNoticed => "Noticed",
1428                Self::InSeen => "Seen",
1429                Self::OutPreparing => "Preparing",
1430                Self::OutDraft => "Draft",
1431                Self::OutPending => "Pending",
1432                Self::OutFailed => "Failed",
1433                Self::OutDelivered => "Delivered",
1434                Self::OutMdnRcvd => "Read",
1435            }
1436        )
1437    }
1438}
1439
1440impl MessageState {
1441    /// Returns true if the message can transition to `OutFailed` state from the current state.
1442    pub fn can_fail(self) -> bool {
1443        use MessageState::*;
1444        matches!(
1445            self,
1446            OutPreparing | OutPending | OutDelivered | OutMdnRcvd // OutMdnRcvd can still fail because it could be a group message and only some recipients failed.
1447        )
1448    }
1449
1450    /// Returns true for any outgoing message states.
1451    pub fn is_outgoing(self) -> bool {
1452        use MessageState::*;
1453        matches!(
1454            self,
1455            OutPreparing | OutDraft | OutPending | OutFailed | OutDelivered | OutMdnRcvd
1456        )
1457    }
1458
1459    /// Returns adjusted message state if the message has MDNs.
1460    pub(crate) fn with_mdns(self, has_mdns: bool) -> Self {
1461        if self == MessageState::OutDelivered && has_mdns {
1462            return MessageState::OutMdnRcvd;
1463        }
1464        self
1465    }
1466}
1467
1468/// Returns contacts that sent read receipts and the time of reading.
1469pub async fn get_msg_read_receipts(
1470    context: &Context,
1471    msg_id: MsgId,
1472) -> Result<Vec<(ContactId, i64)>> {
1473    context
1474        .sql
1475        .query_map_vec(
1476            "SELECT contact_id, timestamp_sent FROM msgs_mdns WHERE msg_id=?",
1477            (msg_id,),
1478            |row| {
1479                let contact_id: ContactId = row.get(0)?;
1480                let ts: i64 = row.get(1)?;
1481                Ok((contact_id, ts))
1482            },
1483        )
1484        .await
1485}
1486
1487/// Returns count of read receipts on message.
1488///
1489/// This view count is meant as a feedback measure for the channel owner only.
1490pub async fn get_msg_read_receipt_count(context: &Context, msg_id: MsgId) -> Result<usize> {
1491    context
1492        .sql
1493        .count("SELECT COUNT(*) FROM msgs_mdns WHERE msg_id=?", (msg_id,))
1494        .await
1495}
1496
1497pub(crate) fn guess_msgtype_from_suffix(msg: &Message) -> Option<(Viewtype, &'static str)> {
1498    msg.param
1499        .get(Param::Filename)
1500        .or_else(|| msg.param.get(Param::File))
1501        .and_then(|file| guess_msgtype_from_path_suffix(Path::new(file)))
1502}
1503
1504pub(crate) fn guess_msgtype_from_path_suffix(path: &Path) -> Option<(Viewtype, &'static str)> {
1505    let extension: &str = &path.extension()?.to_str()?.to_lowercase();
1506    let info = match extension {
1507        // before using viewtype other than Viewtype::File,
1508        // make sure, all target UIs support that type.
1509        //
1510        // it is a non-goal to support as many formats as possible in-app.
1511        // additional parser come at security and maintainance costs and
1512        // should only be added when strictly neccessary,
1513        // eg. when a format comes from the camera app on a significant number of devices.
1514        // it is okay, when eg. dragging some video from a browser results in a "File"
1515        // for everyone, sender as well as all receivers.
1516        //
1517        // if in doubt, it is better to default to Viewtype::File that passes handing to an external app.
1518        // (cmp. <https://developer.android.com/guide/topics/media/media-formats>)
1519        "3gp" => (Viewtype::Video, "video/3gpp"),
1520        "aac" => (Viewtype::Audio, "audio/aac"),
1521        "avi" => (Viewtype::Video, "video/x-msvideo"),
1522        "avif" => (Viewtype::File, "image/avif"), // supported since Android 12 / iOS 16
1523        "doc" => (Viewtype::File, "application/msword"),
1524        "docx" => (
1525            Viewtype::File,
1526            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1527        ),
1528        "epub" => (Viewtype::File, "application/epub+zip"),
1529        "flac" => (Viewtype::Audio, "audio/flac"),
1530        "gif" => (Viewtype::Gif, "image/gif"),
1531        "heic" => (Viewtype::File, "image/heic"), // supported since Android 10 / iOS 11
1532        "heif" => (Viewtype::File, "image/heif"), // supported since Android 10 / iOS 11
1533        "html" => (Viewtype::File, "text/html"),
1534        "htm" => (Viewtype::File, "text/html"),
1535        "ico" => (Viewtype::File, "image/vnd.microsoft.icon"),
1536        "jar" => (Viewtype::File, "application/java-archive"),
1537        "jpeg" => (Viewtype::Image, "image/jpeg"),
1538        "jpe" => (Viewtype::Image, "image/jpeg"),
1539        "jpg" => (Viewtype::Image, "image/jpeg"),
1540        "json" => (Viewtype::File, "application/json"),
1541        "mov" => (Viewtype::Video, "video/quicktime"),
1542        "m4a" => (Viewtype::Audio, "audio/m4a"),
1543        "mp3" => (Viewtype::Audio, "audio/mpeg"),
1544        "mp4" => (Viewtype::Video, "video/mp4"),
1545        "odp" => (
1546            Viewtype::File,
1547            "application/vnd.oasis.opendocument.presentation",
1548        ),
1549        "ods" => (
1550            Viewtype::File,
1551            "application/vnd.oasis.opendocument.spreadsheet",
1552        ),
1553        "odt" => (Viewtype::File, "application/vnd.oasis.opendocument.text"),
1554        "oga" => (Viewtype::Audio, "audio/ogg"),
1555        "ogg" => (Viewtype::Audio, "audio/ogg"),
1556        "ogv" => (Viewtype::File, "video/ogg"),
1557        "opus" => (Viewtype::File, "audio/ogg"), // supported since Android 10
1558        "otf" => (Viewtype::File, "font/otf"),
1559        "pdf" => (Viewtype::File, "application/pdf"),
1560        "png" => (Viewtype::Image, "image/png"),
1561        "ppt" => (Viewtype::File, "application/vnd.ms-powerpoint"),
1562        "pptx" => (
1563            Viewtype::File,
1564            "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1565        ),
1566        "rar" => (Viewtype::File, "application/vnd.rar"),
1567        "rtf" => (Viewtype::File, "application/rtf"),
1568        "spx" => (Viewtype::File, "audio/ogg"), // Ogg Speex Profile
1569        "svg" => (Viewtype::File, "image/svg+xml"),
1570        "tgs" => (Viewtype::File, "application/x-tgsticker"),
1571        "tiff" => (Viewtype::File, "image/tiff"),
1572        "tif" => (Viewtype::File, "image/tiff"),
1573        "ttf" => (Viewtype::File, "font/ttf"),
1574        "txt" => (Viewtype::File, "text/plain"),
1575        "vcard" => (Viewtype::Vcard, "text/vcard"),
1576        "vcf" => (Viewtype::Vcard, "text/vcard"),
1577        "wav" => (Viewtype::Audio, "audio/wav"),
1578        "weba" => (Viewtype::File, "audio/webm"),
1579        "webm" => (Viewtype::File, "video/webm"), // not supported natively by iOS nor by SDWebImage
1580        "webp" => (Viewtype::Image, "image/webp"), // iOS via SDWebImage, Android since 4.0
1581        "wmv" => (Viewtype::Video, "video/x-ms-wmv"),
1582        "xdc" => (Viewtype::Webxdc, "application/webxdc+zip"),
1583        "xhtml" => (Viewtype::File, "application/xhtml+xml"),
1584        "xls" => (Viewtype::File, "application/vnd.ms-excel"),
1585        "xlsx" => (
1586            Viewtype::File,
1587            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1588        ),
1589        "xml" => (Viewtype::File, "application/xml"),
1590        "zip" => (Viewtype::File, "application/zip"),
1591        _ => {
1592            return None;
1593        }
1594    };
1595    Some(info)
1596}
1597
1598/// Get the raw mime-headers of the given message.
1599/// Raw headers are saved for large messages
1600/// that need a "Show full message..."
1601/// to see HTML part.
1602///
1603/// Returns an empty vector if there are no headers saved for the given message.
1604pub(crate) async fn get_mime_headers(context: &Context, msg_id: MsgId) -> Result<Vec<u8>> {
1605    let (headers, compressed) = context
1606        .sql
1607        .query_row(
1608            "SELECT mime_headers, mime_compressed FROM msgs WHERE id=?",
1609            (msg_id,),
1610            |row| {
1611                let headers = sql::row_get_vec(row, 0)?;
1612                let compressed: bool = row.get(1)?;
1613                Ok((headers, compressed))
1614            },
1615        )
1616        .await?;
1617    if compressed {
1618        return buf_decompress(&headers);
1619    }
1620
1621    let headers2 = headers.clone();
1622    let compressed = match tokio::task::block_in_place(move || buf_compress(&headers2)) {
1623        Err(e) => {
1624            warn!(context, "get_mime_headers: buf_compress() failed: {}", e);
1625            return Ok(headers);
1626        }
1627        Ok(o) => o,
1628    };
1629    let update = |conn: &mut rusqlite::Connection| {
1630        match conn.execute(
1631            "\
1632            UPDATE msgs SET mime_headers=?, mime_compressed=1 \
1633            WHERE id=? AND mime_headers!='' AND mime_compressed=0",
1634            (compressed, msg_id),
1635        ) {
1636            Ok(rows_updated) => ensure!(rows_updated <= 1),
1637            Err(e) => {
1638                warn!(context, "get_mime_headers: UPDATE failed: {}", e);
1639                return Err(e.into());
1640            }
1641        }
1642        Ok(())
1643    };
1644    if let Err(e) = context.sql.call_write(update).await {
1645        warn!(
1646            context,
1647            "get_mime_headers: failed to update mime_headers: {}", e
1648        );
1649    }
1650
1651    Ok(headers)
1652}
1653
1654/// Delete a single message from the database, including references in other tables.
1655/// This may be called in batches; the final events are emitted in delete_msgs_locally_done() then.
1656pub(crate) async fn delete_msg_locally(context: &Context, msg: &Message) -> Result<()> {
1657    if msg.location_id > 0 {
1658        delete_poi_location(context, msg.location_id).await?;
1659    }
1660    let on_server = true;
1661    msg.id
1662        .trash(context, on_server)
1663        .await
1664        .with_context(|| format!("Unable to trash message {}", msg.id))?;
1665
1666    context.emit_event(EventType::MsgDeleted {
1667        chat_id: msg.chat_id,
1668        msg_id: msg.id,
1669    });
1670
1671    if msg.viewtype == Viewtype::Webxdc {
1672        context.emit_event(EventType::WebxdcInstanceDeleted { msg_id: msg.id });
1673    }
1674
1675    let logging_xdc_id = context
1676        .debug_logging
1677        .read()
1678        .expect("RwLock is poisoned")
1679        .as_ref()
1680        .map(|dl| dl.msg_id);
1681    if let Some(id) = logging_xdc_id
1682        && id == msg.id
1683    {
1684        set_debug_logging_xdc(context, None).await?;
1685    }
1686
1687    Ok(())
1688}
1689
1690/// Do final events and jobs after batch deletion using calls to delete_msg_locally().
1691/// To avoid additional database queries, collecting data is up to the caller.
1692pub(crate) async fn delete_msgs_locally_done(
1693    context: &Context,
1694    msg_ids: &[MsgId],
1695    modified_chat_ids: BTreeSet<ChatId>,
1696) -> Result<()> {
1697    for modified_chat_id in modified_chat_ids {
1698        context.emit_msgs_changed_without_msg_id(modified_chat_id);
1699        chatlist_events::emit_chatlist_item_changed(context, modified_chat_id);
1700    }
1701    if !msg_ids.is_empty() {
1702        context.emit_msgs_changed_without_ids();
1703        chatlist_events::emit_chatlist_changed(context);
1704        // Run housekeeping to delete unused blobs.
1705        context
1706            .set_config_internal(Config::LastHousekeeping, None)
1707            .await?;
1708    }
1709    Ok(())
1710}
1711
1712/// Delete messages on all devices and on IMAP.
1713pub async fn delete_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
1714    delete_msgs_ex(context, msg_ids, false).await
1715}
1716
1717/// Delete messages on all devices, on IMAP and optionally for all chat members.
1718/// Deleted messages are moved to the trash chat and scheduling for deletion on IMAP.
1719/// When deleting messages for others, all messages must be self-sent and in the same chat.
1720pub async fn delete_msgs_ex(
1721    context: &Context,
1722    msg_ids: &[MsgId],
1723    delete_for_all: bool,
1724) -> Result<()> {
1725    let mut modified_chat_ids = BTreeSet::new();
1726    let mut deleted_rfc724_mid = Vec::new();
1727    let mut res = Ok(());
1728
1729    for &msg_id in msg_ids {
1730        let msg = Message::load_from_db(context, msg_id).await?;
1731        ensure!(
1732            !delete_for_all || msg.from_id == ContactId::SELF,
1733            "Can delete only own messages for others"
1734        );
1735        ensure!(
1736            !delete_for_all || msg.get_showpadlock(),
1737            "Cannot request deletion of unencrypted message for others"
1738        );
1739
1740        modified_chat_ids.insert(msg.chat_id);
1741        deleted_rfc724_mid.push(msg.rfc724_mid.clone());
1742
1743        let update_db = |trans: &mut rusqlite::Transaction| {
1744            let mut stmt = trans.prepare("UPDATE imap SET target='' WHERE rfc724_mid=?")?;
1745            stmt.execute((&msg.rfc724_mid,))?;
1746            if !msg.pre_rfc724_mid.is_empty() {
1747                stmt.execute((&msg.pre_rfc724_mid,))?;
1748            }
1749            trans.execute("DELETE FROM smtp WHERE msg_id=?", (msg_id,))?;
1750            trans.execute(
1751                "DELETE FROM download WHERE rfc724_mid=?",
1752                (&msg.rfc724_mid,),
1753            )?;
1754            trans.execute(
1755                "DELETE FROM available_post_msgs WHERE rfc724_mid=?",
1756                (&msg.rfc724_mid,),
1757            )?;
1758            Ok(())
1759        };
1760        if let Err(e) = context.sql.transaction(update_db).await {
1761            error!(context, "delete_msgs: failed to update db: {e:#}.");
1762            res = Err(e);
1763            continue;
1764        }
1765    }
1766    res?;
1767
1768    if delete_for_all {
1769        ensure!(
1770            modified_chat_ids.len() == 1,
1771            "Can delete only from same chat."
1772        );
1773        if let Some(chat_id) = modified_chat_ids.iter().next() {
1774            let mut msg = Message::new_text("🚮".to_owned());
1775            // We don't want to send deletion requests in chats w/o encryption:
1776            // - These are usually chats with non-DC clients who won't respect deletion requests
1777            //   anyway and display a weird trash bin message instead.
1778            // - Deletion of world-visible unencrypted messages seems not very useful.
1779            msg.param.set_int(Param::GuaranteeE2ee, 1);
1780            msg.param
1781                .set(Param::DeleteRequestFor, deleted_rfc724_mid.join(" "));
1782            msg.hidden = true;
1783            send_msg(context, *chat_id, &mut msg).await?;
1784        }
1785    } else {
1786        context
1787            .add_sync_item(SyncData::DeleteMessages {
1788                msgs: deleted_rfc724_mid,
1789            })
1790            .await?;
1791        context.scheduler.interrupt_smtp().await;
1792    }
1793
1794    for &msg_id in msg_ids {
1795        let msg = Message::load_from_db(context, msg_id).await?;
1796        delete_msg_locally(context, &msg).await?;
1797    }
1798    delete_msgs_locally_done(context, msg_ids, modified_chat_ids).await?;
1799
1800    // Interrupt Inbox loop to start message deletion, run housekeeping and call send_sync_msg().
1801    context.scheduler.interrupt_inbox().await;
1802
1803    Ok(())
1804}
1805
1806/// Marks requested messages as seen.
1807pub async fn markseen_msgs(context: &Context, msg_ids: Vec<MsgId>) -> Result<()> {
1808    if msg_ids.is_empty() {
1809        return Ok(());
1810    }
1811
1812    let old_last_msg_id = MsgId::new(context.get_config_u32(Config::LastMsgId).await?);
1813    let last_msg_id = msg_ids.iter().fold(&old_last_msg_id, std::cmp::max);
1814    context
1815        .set_config_internal(Config::LastMsgId, Some(&last_msg_id.to_u32().to_string()))
1816        .await?;
1817
1818    let mut msgs = Vec::with_capacity(msg_ids.len());
1819    for &id in &msg_ids {
1820        if let Some(msg) = context
1821            .sql
1822            .query_row_optional(
1823                "SELECT
1824                    m.chat_id AS chat_id,
1825                    m.state AS state,
1826                    m.ephemeral_timer AS ephemeral_timer,
1827                    m.param AS param,
1828                    m.from_id AS from_id,
1829                    m.rfc724_mid AS rfc724_mid,
1830                    m.hidden AS hidden,
1831                    c.archived AS archived,
1832                    c.blocked AS blocked
1833                 FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id
1834                 WHERE m.id=? AND m.chat_id>9",
1835                (id,),
1836                |row| {
1837                    let chat_id: ChatId = row.get("chat_id")?;
1838                    let state: MessageState = row.get("state")?;
1839                    let param: Params = row.get::<_, String>("param")?.parse().unwrap_or_default();
1840                    let from_id: ContactId = row.get("from_id")?;
1841                    let rfc724_mid: String = row.get("rfc724_mid")?;
1842                    let hidden: bool = row.get("hidden")?;
1843                    let visibility: ChatVisibility = row.get("archived")?;
1844                    let blocked: Option<Blocked> = row.get("blocked")?;
1845                    let ephemeral_timer: EphemeralTimer = row.get("ephemeral_timer")?;
1846                    Ok((
1847                        (
1848                            id,
1849                            chat_id,
1850                            state,
1851                            param,
1852                            from_id,
1853                            rfc724_mid,
1854                            hidden,
1855                            visibility,
1856                            blocked.unwrap_or_default(),
1857                        ),
1858                        ephemeral_timer,
1859                    ))
1860                },
1861            )
1862            .await?
1863        {
1864            msgs.push(msg);
1865        }
1866    }
1867
1868    if msgs
1869        .iter()
1870        .any(|(_, ephemeral_timer)| *ephemeral_timer != EphemeralTimer::Disabled)
1871    {
1872        start_ephemeral_timers_msgids(context, &msg_ids)
1873            .await
1874            .context("failed to start ephemeral timers")?;
1875    }
1876
1877    let mut updated_chat_ids = BTreeSet::new();
1878    let mut archived_chats_maybe_noticed = false;
1879    for (
1880        (
1881            id,
1882            curr_chat_id,
1883            curr_state,
1884            curr_param,
1885            curr_from_id,
1886            curr_rfc724_mid,
1887            curr_hidden,
1888            curr_visibility,
1889            curr_blocked,
1890        ),
1891        _curr_ephemeral_timer,
1892    ) in msgs
1893    {
1894        if curr_state == MessageState::InFresh || curr_state == MessageState::InNoticed {
1895            update_msg_state(context, id, MessageState::InSeen).await?;
1896            info!(context, "Seen message {}.", id);
1897
1898            markseen_on_imap_table(context, &curr_rfc724_mid).await?;
1899
1900            // Read receipts for system messages are never sent to contacts.
1901            // These messages have no place to display received read receipt
1902            // anyway. And since their text is locally generated,
1903            // quoting them is dangerous as it may contain contact names. E.g., for original message
1904            // "Group left by me", a read receipt will quote "Group left by <name>", and the name can
1905            // be a display name stored in address book rather than the name sent in the From field by
1906            // the user.
1907            //
1908            // We also don't send read receipts for contact requests.
1909            // Read receipts will not be sent even after accepting the chat.
1910            let to_id = if curr_blocked == Blocked::Not
1911                && !curr_hidden
1912                && curr_param.get_bool(Param::WantsMdn).unwrap_or_default()
1913                && curr_param.get_cmd() == SystemMessage::Unknown
1914                && context.should_send_mdns().await?
1915            {
1916                // Clear WantsMdn to not handle a MDN twice
1917                // if the state later is InFresh again as markfresh_chat() was called.
1918                // BccSelf MDN messages in the next branch may be sent twice for syncing.
1919                context
1920                    .sql
1921                    .execute(
1922                        "UPDATE msgs SET param=? WHERE id=?",
1923                        (curr_param.clone().remove(Param::WantsMdn).to_string(), id),
1924                    )
1925                    .await
1926                    .context("failed to clear WantsMdn")?;
1927                Some(curr_from_id)
1928            } else if context.get_config_bool(Config::BccSelf).await? {
1929                Some(ContactId::SELF)
1930            } else {
1931                None
1932            };
1933            if let Some(to_id) = to_id {
1934                context
1935                    .sql
1936                    .execute(
1937                        "INSERT INTO smtp_mdns (msg_id, from_id, rfc724_mid) VALUES(?, ?, ?)",
1938                        (id, to_id, curr_rfc724_mid),
1939                    )
1940                    .await
1941                    .context("failed to insert into smtp_mdns")?;
1942                context.scheduler.interrupt_smtp().await;
1943            }
1944
1945            if !curr_hidden {
1946                updated_chat_ids.insert(curr_chat_id);
1947            }
1948        }
1949        archived_chats_maybe_noticed |= curr_state == MessageState::InFresh
1950            && !curr_hidden
1951            && curr_visibility == ChatVisibility::Archived;
1952    }
1953
1954    for updated_chat_id in updated_chat_ids {
1955        context.emit_event(EventType::MsgsNoticed(updated_chat_id));
1956        chatlist_events::emit_chatlist_item_changed(context, updated_chat_id);
1957    }
1958    if archived_chats_maybe_noticed {
1959        context.on_archived_chats_maybe_noticed();
1960    }
1961
1962    Ok(())
1963}
1964
1965/// Checks if the messages with given IDs exist.
1966///
1967/// Returns IDs of existing messages.
1968pub async fn get_existing_msg_ids(context: &Context, ids: &[MsgId]) -> Result<Vec<MsgId>> {
1969    let query_only = true;
1970    let res = context
1971        .sql
1972        .transaction_ex(query_only, |transaction| {
1973            let mut res: Vec<MsgId> = Vec::new();
1974            for id in ids {
1975                if transaction.query_one(
1976                    "SELECT COUNT(*) > 0 FROM msgs WHERE id=? AND chat_id!=3",
1977                    (id,),
1978                    |row| {
1979                        let exists: bool = row.get(0)?;
1980                        Ok(exists)
1981                    },
1982                )? {
1983                    res.push(*id);
1984                }
1985            }
1986            Ok(res)
1987        })
1988        .await?;
1989    Ok(res)
1990}
1991
1992pub(crate) async fn update_msg_state(
1993    context: &Context,
1994    msg_id: MsgId,
1995    state: MessageState,
1996) -> Result<()> {
1997    ensure!(
1998        state != MessageState::OutMdnRcvd,
1999        "Update msgs_mdns table instead!"
2000    );
2001    ensure!(state != MessageState::OutFailed, "use set_msg_failed()!");
2002    let error_subst = match state >= MessageState::OutPending {
2003        true => ", error=''",
2004        false => "",
2005    };
2006    context
2007        .sql
2008        .execute(
2009            &format!("UPDATE msgs SET state=? {error_subst} WHERE id=?"),
2010            (state, msg_id),
2011        )
2012        .await?;
2013    Ok(())
2014}
2015
2016// as we do not cut inside words, this results in about 32-42 characters.
2017// Do not use too long subjects - we add a tag after the subject which gets truncated by the clients otherwise.
2018// It should also be very clear, the subject is _not_ the whole message.
2019// The value is also used for CC:-summaries
2020
2021// Context functions to work with messages
2022
2023pub(crate) async fn set_msg_failed(
2024    context: &Context,
2025    msg: &mut Message,
2026    error: &str,
2027) -> Result<()> {
2028    if msg.state.can_fail() {
2029        msg.state = MessageState::OutFailed;
2030        warn!(context, "{} failed: {}", msg.id, error);
2031    } else {
2032        warn!(
2033            context,
2034            "{} seems to have failed ({}), but state is {}", msg.id, error, msg.state
2035        )
2036    }
2037    msg.error = Some(error.to_string());
2038
2039    let exists = context
2040        .sql
2041        .execute(
2042            "UPDATE msgs SET state=?, error=? WHERE id=?;",
2043            (msg.state, error, msg.id),
2044        )
2045        .await?
2046        > 0;
2047    context.emit_event(EventType::MsgFailed {
2048        chat_id: msg.chat_id,
2049        msg_id: msg.id,
2050    });
2051    if exists {
2052        chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
2053    }
2054    Ok(())
2055}
2056
2057/// Inserts a tombstone into `msgs` table
2058/// to prevent downloading the same message in the future.
2059///
2060/// Returns tombstone database row ID.
2061pub(crate) async fn insert_tombstone(context: &Context, rfc724_mid: &str) -> Result<MsgId> {
2062    let row_id = context
2063        .sql
2064        .insert(
2065            "INSERT INTO msgs(rfc724_mid, chat_id) VALUES (?,?)",
2066            (rfc724_mid, DC_CHAT_ID_TRASH),
2067        )
2068        .await?;
2069    let msg_id = MsgId::new(u32::try_from(row_id)?);
2070    Ok(msg_id)
2071}
2072
2073/// The number of messages assigned to unblocked chats
2074pub async fn get_unblocked_msg_cnt(context: &Context) -> usize {
2075    match context
2076        .sql
2077        .count(
2078            "SELECT COUNT(*) \
2079         FROM msgs m  LEFT JOIN chats c ON c.id=m.chat_id \
2080         WHERE m.id>9 AND m.chat_id>9 AND c.blocked=0;",
2081            (),
2082        )
2083        .await
2084    {
2085        Ok(res) => res,
2086        Err(err) => {
2087            error!(context, "get_unblocked_msg_cnt() failed. {:#}", err);
2088            0
2089        }
2090    }
2091}
2092
2093/// Returns the number of messages in contact request chats.
2094pub async fn get_request_msg_cnt(context: &Context) -> usize {
2095    match context
2096        .sql
2097        .count(
2098            "SELECT COUNT(*) \
2099         FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id \
2100         WHERE c.blocked=2;",
2101            (),
2102        )
2103        .await
2104    {
2105        Ok(res) => res,
2106        Err(err) => {
2107            error!(context, "get_request_msg_cnt() failed. {:#}", err);
2108            0
2109        }
2110    }
2111}
2112
2113/// Estimates the number of messages that will be deleted
2114/// by the options `delete_device_after` or `delete_server_after`.
2115///
2116/// This is typically used to show the estimated impact to the user
2117/// before actually enabling deletion of old messages.
2118///
2119/// If `from_server` is true,
2120/// estimate deletion count for server,
2121/// otherwise estimate deletion count for device.
2122///
2123/// Count messages older than the given number of `seconds`.
2124///
2125/// Returns the number of messages that are older than the given number of seconds.
2126/// This includes e-mails downloaded due to the `show_emails` option.
2127/// Messages in the "saved messages" folder are not counted as they will not be deleted automatically.
2128#[expect(clippy::arithmetic_side_effects)]
2129pub async fn estimate_deletion_cnt(
2130    context: &Context,
2131    from_server: bool,
2132    seconds: i64,
2133) -> Result<usize> {
2134    let self_chat_id = ChatIdBlocked::lookup_by_contact(context, ContactId::SELF)
2135        .await?
2136        .map(|c| c.id)
2137        .unwrap_or_default();
2138    let threshold_timestamp = time() - seconds;
2139
2140    let cnt = if from_server {
2141        context
2142            .sql
2143            .count(
2144                "SELECT COUNT(*)
2145             FROM msgs m
2146             WHERE m.id > ?
2147               AND timestamp < ?
2148               AND chat_id != ?
2149               AND EXISTS (SELECT * FROM imap WHERE rfc724_mid=m.rfc724_mid);",
2150                (DC_MSG_ID_LAST_SPECIAL, threshold_timestamp, self_chat_id),
2151            )
2152            .await?
2153    } else {
2154        context
2155            .sql
2156            .count(
2157                "SELECT COUNT(*)
2158             FROM msgs m
2159             WHERE m.id > ?
2160               AND timestamp < ?
2161               AND chat_id != ?
2162               AND chat_id != ? AND hidden = 0;",
2163                (
2164                    DC_MSG_ID_LAST_SPECIAL,
2165                    threshold_timestamp,
2166                    self_chat_id,
2167                    DC_CHAT_ID_TRASH,
2168                ),
2169            )
2170            .await?
2171    };
2172    Ok(cnt)
2173}
2174
2175/// See [`rfc724_mid_exists_ex()`].
2176pub(crate) async fn rfc724_mid_exists(
2177    context: &Context,
2178    rfc724_mid: &str,
2179) -> Result<Option<MsgId>> {
2180    Ok(rfc724_mid_exists_ex(context, rfc724_mid, "1")
2181        .await?
2182        .map(|(id, _)| id))
2183}
2184
2185/// Returns [MsgId] of the most recent message with given `rfc724_mid`
2186/// (Message-ID header) and bool `expr` result if such messages exists in the db.
2187///
2188/// * `expr`: SQL expression additionally passed into `SELECT`. Evaluated to `true` iff it is true
2189///   for all messages with the given `rfc724_mid`.
2190pub(crate) async fn rfc724_mid_exists_ex(
2191    context: &Context,
2192    rfc724_mid: &str,
2193    expr: &str,
2194) -> Result<Option<(MsgId, bool)>> {
2195    let rfc724_mid = rfc724_mid.trim_start_matches('<').trim_end_matches('>');
2196    if rfc724_mid.is_empty() {
2197        warn!(context, "Empty rfc724_mid passed to rfc724_mid_exists");
2198        return Ok(None);
2199    }
2200
2201    let res = context
2202        .sql
2203        .query_row_optional(
2204            &("SELECT id, timestamp_sent, MIN(".to_string()
2205                + expr
2206                + ") FROM msgs WHERE rfc724_mid=?1 OR pre_rfc724_mid=?1
2207              HAVING COUNT(*) > 0 -- Prevent MIN(expr) from returning NULL when there are no rows.
2208              ORDER BY timestamp_sent DESC"),
2209            (rfc724_mid,),
2210            |row| {
2211                let msg_id: MsgId = row.get(0)?;
2212                let expr_res: bool = row.get(2)?;
2213                Ok((msg_id, expr_res))
2214            },
2215        )
2216        .await?;
2217
2218    Ok(res)
2219}
2220
2221/// Returns `true` iff there is a message
2222/// with the given `rfc724_mid`
2223/// and a download state other than `DownloadState::Available`,
2224/// i.e. it was already tried to download the message or it's sent locally.
2225pub(crate) async fn rfc724_mid_download_tried(context: &Context, rfc724_mid: &str) -> Result<bool> {
2226    let rfc724_mid = rfc724_mid.trim_start_matches('<').trim_end_matches('>');
2227    if rfc724_mid.is_empty() {
2228        warn!(
2229            context,
2230            "Empty rfc724_mid passed to rfc724_mid_download_tried"
2231        );
2232        return Ok(false);
2233    }
2234
2235    let res = context
2236        .sql
2237        .exists(
2238            "SELECT COUNT(*) FROM msgs
2239             WHERE rfc724_mid=? AND download_state<>?",
2240            (rfc724_mid, DownloadState::Available),
2241        )
2242        .await?;
2243
2244    Ok(res)
2245}
2246
2247/// Given a list of Message-IDs, returns the most relevant message found in the database.
2248///
2249/// Relevance here is `(download_state == Done, index)`, where `index` is an index of Message-ID in
2250/// `mids`. This means Message-IDs should be ordered from the least late to the latest one (like in
2251/// the References header).
2252/// Only messages that are not in the trash chat are considered.
2253pub(crate) async fn get_by_rfc724_mids(
2254    context: &Context,
2255    mids: &[String],
2256) -> Result<Option<Message>> {
2257    let mut latest = None;
2258    for id in mids.iter().rev() {
2259        let Some(msg_id) = rfc724_mid_exists(context, id).await? else {
2260            continue;
2261        };
2262        let Some(msg) = Message::load_from_db_optional(context, msg_id).await? else {
2263            continue;
2264        };
2265        if msg.download_state == DownloadState::Done {
2266            return Ok(Some(msg));
2267        }
2268        latest.get_or_insert(msg);
2269    }
2270    Ok(latest)
2271}
2272
2273/// Returns the 1st part of summary text (i.e. before the dash if any) for a valid DeltaChat vCard.
2274pub(crate) fn get_vcard_summary(vcard: &[u8]) -> Option<String> {
2275    let vcard = str::from_utf8(vcard).ok()?;
2276    let contacts = deltachat_contact_tools::parse_vcard(vcard);
2277    let [c] = &contacts[..] else {
2278        return None;
2279    };
2280    if !deltachat_contact_tools::may_be_valid_addr(&c.addr) {
2281        return None;
2282    }
2283    Some(c.display_name().to_string())
2284}
2285
2286/// How a message is primarily displayed.
2287#[derive(
2288    Debug,
2289    Default,
2290    Display,
2291    Clone,
2292    Copy,
2293    PartialEq,
2294    Eq,
2295    FromPrimitive,
2296    ToPrimitive,
2297    FromSql,
2298    ToSql,
2299    Serialize,
2300    Deserialize,
2301)]
2302#[repr(u32)]
2303pub enum Viewtype {
2304    /// Unknown message type.
2305    #[default]
2306    Unknown = 0,
2307
2308    /// Text message.
2309    /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().
2310    Text = 10,
2311
2312    /// Image message.
2313    /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to
2314    /// `Gif` when sending the message.
2315    /// File, width and height are set via dc_msg_set_file_and_deduplicate(), dc_msg_set_dimension()
2316    /// and retrieved via dc_msg_get_file(), dc_msg_get_height(), dc_msg_get_width().
2317    Image = 20,
2318
2319    /// Animated GIF message.
2320    /// File, width and height are set via dc_msg_set_file_and_deduplicate(), dc_msg_set_dimension()
2321    /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().
2322    Gif = 21,
2323
2324    /// Message containing a sticker, similar to image.
2325    /// NB: When sending, the message viewtype may be changed to `Image` by some heuristics like
2326    /// checking for transparent pixels. Use `Message::force_sticker()` to disable them.
2327    ///
2328    /// If possible, the ui should display the image without borders in a transparent way.
2329    /// A click on a sticker will offer to install the sticker set in some future.
2330    Sticker = 23,
2331
2332    /// Message containing an Audio file.
2333    /// File and duration are set via dc_msg_set_file_and_deduplicate(), dc_msg_set_duration()
2334    /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().
2335    Audio = 40,
2336
2337    /// A voice message that was directly recorded by the user.
2338    /// For all other audio messages, the type #DC_MSG_AUDIO should be used.
2339    /// File and duration are set via dc_msg_set_file_and_deduplicate(), dc_msg_set_duration()
2340    /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()
2341    Voice = 41,
2342
2343    /// Video messages.
2344    /// File, width, height and durarion
2345    /// are set via dc_msg_set_file_and_deduplicate(), dc_msg_set_dimension(), dc_msg_set_duration()
2346    /// and retrieved via
2347    /// dc_msg_get_file(), dc_msg_get_width(),
2348    /// dc_msg_get_height(), dc_msg_get_duration().
2349    Video = 50,
2350
2351    /// Message containing any file, eg. a PDF.
2352    /// The file is set via dc_msg_set_file_and_deduplicate()
2353    /// and retrieved via dc_msg_get_file().
2354    File = 60,
2355
2356    /// Message is an incoming or outgoing call.
2357    Call = 71,
2358
2359    /// Message is an webxdc instance.
2360    Webxdc = 80,
2361
2362    /// Message containing shared contacts represented as a vCard (virtual contact file)
2363    /// with email addresses and possibly other fields.
2364    /// Use `parse_vcard()` to retrieve them.
2365    Vcard = 90,
2366}
2367
2368impl Viewtype {
2369    /// Whether a message with this [`Viewtype`] should have a file attachment.
2370    pub fn has_file(&self) -> bool {
2371        match self {
2372            Viewtype::Unknown => false,
2373            Viewtype::Text => false,
2374            Viewtype::Image => true,
2375            Viewtype::Gif => true,
2376            Viewtype::Sticker => true,
2377            Viewtype::Audio => true,
2378            Viewtype::Voice => true,
2379            Viewtype::Video => true,
2380            Viewtype::File => true,
2381            Viewtype::Call => false,
2382            Viewtype::Webxdc => true,
2383            Viewtype::Vcard => true,
2384        }
2385    }
2386}
2387
2388#[cfg(test)]
2389mod message_tests;