1use 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#[derive(
48 Debug, Copy, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
49)]
50pub struct MsgId(u32);
51
52impl MsgId {
53 pub fn new(id: u32) -> MsgId {
55 MsgId(id)
56 }
57
58 pub fn new_unset() -> MsgId {
60 MsgId(0)
61 }
62
63 pub fn is_special(self) -> bool {
67 self.0 <= DC_MSG_ID_LAST_SPECIAL
68 }
69
70 pub fn is_unset(self) -> bool {
80 self.0 == 0
81 }
82
83 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 pub(crate) async fn trash(self, context: &Context, on_server: bool) -> Result<()> {
126 context
127 .sql
128 .execute(
129 "
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 pub fn to_u32(self) -> u32 {
164 self.0
165 }
166
167 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 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 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 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 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
343impl 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
364impl rusqlite::types::FromSql for MsgId {
366 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
367 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 Reply = 2,
399}
400
401#[derive(Debug, Clone, Default, Serialize, Deserialize)]
405pub struct Message {
406 pub(crate) id: MsgId,
408
409 pub(crate) from_id: ContactId,
411
412 pub(crate) to_id: ContactId,
414
415 pub(crate) chat_id: ChatId,
417
418 pub(crate) viewtype: Viewtype,
420
421 pub(crate) state: MessageState,
423 pub(crate) download_state: DownloadState,
424
425 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 pub(crate) additional_text: String,
437
438 pub(crate) subject: String,
442
443 pub(crate) rfc724_mid: String,
445 pub(crate) pre_rfc724_mid: String,
447
448 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 pub fn new(viewtype: Viewtype) -> Self {
463 Message {
464 viewtype,
465 rfc724_mid: create_outgoing_rfc724_mid(),
466 ..Default::default()
467 }
468 }
469
470 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 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 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 -- DC_CHAT_ID_TRASH
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 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 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 return Some("application/octet-stream".to_string());
654 }
655 None
657 }
658
659 pub fn get_file(&self, context: &Context) -> Option<PathBuf> {
661 self.param.get_file_path(context).unwrap_or(None)
662 }
663
664 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 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 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 pub fn has_location(&self) -> bool {
734 self.location_id != 0
735 }
736
737 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 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 pub fn get_id(&self) -> MsgId {
774 self.id
775 }
776
777 pub fn rfc724_mid(&self) -> &str {
780 &self.rfc724_mid
781 }
782
783 pub fn get_from_id(&self) -> ContactId {
785 self.from_id
786 }
787
788 pub fn get_chat_id(&self) -> ChatId {
790 self.chat_id
791 }
792
793 pub fn get_viewtype(&self) -> Viewtype {
795 self.viewtype
796 }
797
798 pub fn get_state(&self) -> MessageState {
800 self.state
801 }
802
803 pub fn get_received_timestamp(&self) -> i64 {
805 self.timestamp_rcvd
806 }
807
808 pub fn get_sort_timestamp(&self) -> i64 {
810 if self.timestamp_sort != 0 {
811 self.timestamp_sort
812 } else {
813 self.timestamp_sent
814 }
815 }
816
817 pub fn get_text(&self) -> String {
822 self.text.clone() + &self.additional_text
823 }
824
825 pub fn get_subject(&self) -> &str {
827 &self.subject
828 }
829
830 pub fn get_filename(&self) -> Option<String> {
834 if let Some(name) = self.param.get(Param::Filename) {
835 return Some(sanitize_filename(name));
836 }
837 self.param
838 .get(Param::File)
839 .and_then(|file| Path::new(file).file_name())
840 .map(|name| sanitize_filename(&name.to_string_lossy()))
841 }
842
843 pub async fn get_filebytes(&self, context: &Context) -> Result<Option<u64>> {
846 if self.download_state != DownloadState::Done
847 && let Some(file_size) = self
848 .param
849 .get(Param::PostMessageFileBytes)
850 .and_then(|s| s.parse().ok())
851 {
852 return Ok(Some(file_size));
853 }
854 if let Some(path) = self.param.get_file_path(context)? {
855 Ok(Some(get_filebytes(context, &path).await.with_context(
856 || format!("failed to get {} size in bytes", path.display()),
857 )?))
858 } else {
859 Ok(None)
860 }
861 }
862
863 #[cfg(test)]
866 pub(crate) fn get_post_message_viewtype(&self) -> Option<Viewtype> {
867 if self.download_state != DownloadState::Done {
868 return self
869 .param
870 .get_i64(Param::PostMessageViewtype)
871 .and_then(Viewtype::from_i64);
872 }
873 None
874 }
875
876 pub fn get_width(&self) -> i32 {
878 self.param.get_int(Param::Width).unwrap_or_default()
879 }
880
881 pub fn get_height(&self) -> i32 {
883 self.param.get_int(Param::Height).unwrap_or_default()
884 }
885
886 pub fn get_duration(&self) -> i32 {
888 self.param.get_int(Param::Duration).unwrap_or_default()
889 }
890
891 pub fn get_showpadlock(&self) -> bool {
893 self.param.get_int(Param::GuaranteeE2ee).unwrap_or_default() != 0
894 || self.from_id == ContactId::DEVICE
895 }
896
897 pub fn is_bot(&self) -> bool {
899 self.param.get_bool(Param::Bot).unwrap_or_default()
900 }
901
902 pub fn get_ephemeral_timer(&self) -> EphemeralTimer {
904 self.ephemeral_timer
905 }
906
907 pub fn get_ephemeral_timestamp(&self) -> i64 {
909 self.ephemeral_timestamp
910 }
911
912 pub async fn get_summary(&self, context: &Context, chat: Option<&Chat>) -> Result<Summary> {
914 let chat_loaded: Chat;
915 let chat = if let Some(chat) = chat {
916 chat
917 } else {
918 let chat = Chat::load_from_db(context, self.chat_id).await?;
919 chat_loaded = chat;
920 &chat_loaded
921 };
922
923 let contact = if self.from_id != ContactId::SELF {
924 match chat.typ {
925 Chattype::Group | Chattype::Mailinglist => {
926 Some(Contact::get_by_id(context, self.from_id).await?)
927 }
928 Chattype::Single | Chattype::OutBroadcast | Chattype::InBroadcast => None,
929 }
930 } else {
931 None
932 };
933
934 Summary::new(context, self, chat, contact.as_ref()).await
935 }
936
937 pub fn get_override_sender_name(&self) -> Option<String> {
947 self.param
948 .get(Param::OverrideSenderDisplayname)
949 .map(|name| name.to_string())
950 }
951
952 pub(crate) fn get_sender_name(&self, contact: &Contact) -> String {
955 self.get_override_sender_name()
956 .unwrap_or_else(|| contact.get_display_name().to_string())
957 }
958
959 #[expect(clippy::arithmetic_side_effects)]
964 pub fn has_deviating_timestamp(&self) -> bool {
965 let cnv_to_local = gm2local_offset();
966 let sort_timestamp = self.get_sort_timestamp() + cnv_to_local;
967 let send_timestamp = self.get_timestamp() + cnv_to_local;
968
969 sort_timestamp / 86400 != send_timestamp / 86400
970 }
971
972 pub fn is_sent(&self) -> bool {
975 self.state >= MessageState::OutDelivered
976 }
977
978 pub fn is_forwarded(&self) -> bool {
980 self.param.get_int(Param::Forwarded).is_some()
981 }
982
983 pub fn is_edited(&self) -> bool {
985 self.param.get_bool(Param::IsEdited).unwrap_or_default()
986 }
987
988 pub fn is_info(&self) -> bool {
990 let cmd = self.param.get_cmd();
991 self.from_id == ContactId::INFO
992 || self.to_id == ContactId::INFO
993 || cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage
994 }
995
996 pub fn get_info_type(&self) -> SystemMessage {
998 self.param.get_cmd()
999 }
1000
1001 pub async fn get_info_contact_id(&self, context: &Context) -> Result<Option<ContactId>> {
1003 match self.param.get_cmd() {
1004 SystemMessage::GroupNameChanged
1005 | SystemMessage::GroupDescriptionChanged
1006 | SystemMessage::GroupImageChanged
1007 | SystemMessage::EphemeralTimerChanged => {
1008 if self.from_id != ContactId::INFO {
1009 Ok(Some(self.from_id))
1010 } else {
1011 Ok(None)
1012 }
1013 }
1014
1015 SystemMessage::MemberAddedToGroup | SystemMessage::MemberRemovedFromGroup => {
1016 if let Some(contact_i32) = self.param.get_int(Param::ContactAddedRemoved) {
1017 let contact_id = ContactId::new(contact_i32.try_into()?);
1018 if contact_id == ContactId::SELF
1019 || Contact::real_exists_by_id(context, contact_id).await?
1020 {
1021 Ok(Some(contact_id))
1022 } else {
1023 Ok(None)
1024 }
1025 } else {
1026 Ok(None)
1027 }
1028 }
1029
1030 SystemMessage::AutocryptSetupMessage
1031 | SystemMessage::SecurejoinMessage
1032 | SystemMessage::LocationStreamingEnabled
1033 | SystemMessage::LocationOnly
1034 | SystemMessage::ChatE2ee
1035 | SystemMessage::ChatProtectionEnabled
1036 | SystemMessage::ChatProtectionDisabled
1037 | SystemMessage::InvalidUnencryptedMail
1038 | SystemMessage::SecurejoinWait
1039 | SystemMessage::SecurejoinWaitTimeout
1040 | SystemMessage::MultiDeviceSync
1041 | SystemMessage::WebxdcStatusUpdate
1042 | SystemMessage::WebxdcInfoMessage
1043 | SystemMessage::IrohNodeAddr
1044 | SystemMessage::CallAccepted
1045 | SystemMessage::CallEnded
1046 | SystemMessage::Unknown => Ok(None),
1047 }
1048 }
1049
1050 pub fn is_system_message(&self) -> bool {
1052 let cmd = self.param.get_cmd();
1053 cmd != SystemMessage::Unknown
1054 }
1055
1056 pub fn set_text(&mut self, text: String) {
1058 self.text = text;
1059 }
1060
1061 pub fn set_subject(&mut self, subject: String) {
1064 self.subject = subject;
1065 }
1066
1067 pub fn set_file_and_deduplicate(
1082 &mut self,
1083 context: &Context,
1084 file: &Path,
1085 name: Option<&str>,
1086 filemime: Option<&str>,
1087 ) -> Result<()> {
1088 let name = if let Some(name) = name {
1089 name.to_string()
1090 } else {
1091 file.file_name()
1092 .map(|s| s.to_string_lossy().to_string())
1093 .unwrap_or_else(|| "unknown_file".to_string())
1094 };
1095
1096 let blob = BlobObject::create_and_deduplicate(context, file, Path::new(&name))?;
1097 self.param.set(Param::File, blob.as_name());
1098
1099 self.param.set(Param::Filename, name);
1100 self.param.set_optional(Param::MimeType, filemime);
1101
1102 Ok(())
1103 }
1104
1105 pub fn set_file_from_bytes(
1112 &mut self,
1113 context: &Context,
1114 name: &str,
1115 data: &[u8],
1116 filemime: Option<&str>,
1117 ) -> Result<()> {
1118 let blob = BlobObject::create_and_deduplicate_from_bytes(context, data, name)?;
1119 self.param.set(Param::Filename, name);
1120 self.param.set(Param::File, blob.as_name());
1121 self.param.set_optional(Param::MimeType, filemime);
1122
1123 Ok(())
1124 }
1125
1126 pub async fn make_vcard(&mut self, context: &Context, contacts: &[ContactId]) -> Result<()> {
1128 ensure!(
1129 matches!(self.viewtype, Viewtype::File | Viewtype::Vcard),
1130 "Wrong viewtype for vCard: {}",
1131 self.viewtype,
1132 );
1133 let vcard = contact::make_vcard(context, contacts).await?;
1134 self.set_file_from_bytes(context, "vcard.vcf", vcard.as_bytes(), None)
1135 }
1136
1137 pub(crate) async fn try_set_vcard(&mut self, context: &Context, path: &Path) -> Result<()> {
1139 let vcard = fs::read(path)
1140 .await
1141 .with_context(|| format!("Could not read {path:?}"))?;
1142 if let Some(summary) = get_vcard_summary(&vcard) {
1143 self.param.set(Param::Summary1, summary);
1144 } else {
1145 warn!(context, "try_set_vcard: Not a valid DeltaChat vCard.");
1146 self.viewtype = Viewtype::File;
1147 }
1148 Ok(())
1149 }
1150
1151 pub fn set_override_sender_name(&mut self, name: Option<String>) {
1154 self.param
1155 .set_optional(Param::OverrideSenderDisplayname, name);
1156 }
1157
1158 pub fn set_dimension(&mut self, width: i32, height: i32) {
1160 self.param.set_int(Param::Width, width);
1161 self.param.set_int(Param::Height, height);
1162 }
1163
1164 pub fn set_duration(&mut self, duration: i32) {
1166 self.param.set_int(Param::Duration, duration);
1167 }
1168
1169 pub(crate) fn set_reaction(&mut self) {
1171 self.param.set_int(Param::Reaction, 1);
1172 }
1173
1174 pub async fn latefiling_mediasize(
1177 &mut self,
1178 context: &Context,
1179 width: i32,
1180 height: i32,
1181 duration: i32,
1182 ) -> Result<()> {
1183 if width > 0 && height > 0 {
1184 self.param.set_int(Param::Width, width);
1185 self.param.set_int(Param::Height, height);
1186 }
1187 if duration > 0 {
1188 self.param.set_int(Param::Duration, duration);
1189 }
1190 self.update_param(context).await?;
1191 Ok(())
1192 }
1193
1194 pub fn set_quote_text(&mut self, text: Option<(String, bool)>) {
1200 let Some((text, protect)) = text else {
1201 self.param.remove(Param::Quote);
1202 self.param.remove(Param::ProtectQuote);
1203 return;
1204 };
1205 self.param.set(Param::Quote, text);
1206 self.param.set_optional(
1207 Param::ProtectQuote,
1208 match protect {
1209 true => Some("1"),
1210 false => None,
1211 },
1212 );
1213 }
1214
1215 pub async fn set_quote(&mut self, context: &Context, quote: Option<&Message>) -> Result<()> {
1224 if let Some(quote) = quote {
1225 ensure!(
1226 !quote.rfc724_mid.is_empty(),
1227 "Message without Message-Id cannot be quoted"
1228 );
1229 self.in_reply_to = Some(quote.rfc724_mid.clone());
1230
1231 let text = quote.get_text();
1232 let text = if text.is_empty() {
1233 quote
1235 .get_summary(context, None)
1236 .await?
1237 .truncated_text(500)
1238 .to_string()
1239 } else {
1240 text
1241 };
1242 self.set_quote_text(Some((
1243 text,
1244 quote
1245 .param
1246 .get_bool(Param::GuaranteeE2ee)
1247 .unwrap_or_default(),
1248 )));
1249 } else {
1250 self.in_reply_to = None;
1251 self.set_quote_text(None);
1252 }
1253
1254 Ok(())
1255 }
1256
1257 pub fn quoted_text(&self) -> Option<String> {
1259 self.param.get(Param::Quote).map(|s| s.to_string())
1260 }
1261
1262 pub async fn quoted_message(&self, context: &Context) -> Result<Option<Message>> {
1264 if self.param.get(Param::Quote).is_some() && !self.is_forwarded() {
1265 return self.parent(context).await;
1266 }
1267 Ok(None)
1268 }
1269
1270 pub async fn parent(&self, context: &Context) -> Result<Option<Message>> {
1275 if let Some(in_reply_to) = &self.in_reply_to
1276 && let Some(msg_id) = rfc724_mid_exists(context, in_reply_to).await?
1277 {
1278 let msg = Message::load_from_db_optional(context, msg_id).await?;
1279 return Ok(msg);
1280 }
1281 Ok(None)
1282 }
1283
1284 pub async fn get_original_msg_id(&self, context: &Context) -> Result<Option<MsgId>> {
1286 if !self.original_msg_id.is_special()
1287 && let Some(msg) = Message::load_from_db_optional(context, self.original_msg_id).await?
1288 {
1289 return if msg.chat_id.is_trash() {
1290 Ok(None)
1291 } else {
1292 Ok(Some(msg.id))
1293 };
1294 }
1295 Ok(None)
1296 }
1297
1298 pub async fn get_saved_msg_id(&self, context: &Context) -> Result<Option<MsgId>> {
1302 let res: Option<MsgId> = context
1303 .sql
1304 .query_get_value(
1305 "SELECT id FROM msgs WHERE starred=? AND chat_id!=?",
1306 (self.id, DC_CHAT_ID_TRASH),
1307 )
1308 .await?;
1309 Ok(res)
1310 }
1311
1312 pub(crate) fn force_plaintext(&mut self) {
1314 self.param.set_int(Param::ForcePlaintext, 1);
1315 }
1316
1317 pub async fn update_param(&self, context: &Context) -> Result<()> {
1319 context
1320 .sql
1321 .execute(
1322 "UPDATE msgs SET param=? WHERE id=?;",
1323 (self.param.to_string(), self.id),
1324 )
1325 .await?;
1326 Ok(())
1327 }
1328
1329 pub fn error(&self) -> Option<String> {
1342 self.error.clone()
1343 }
1344}
1345
1346#[derive(
1350 Debug,
1351 Default,
1352 Clone,
1353 Copy,
1354 PartialEq,
1355 Eq,
1356 PartialOrd,
1357 Ord,
1358 FromPrimitive,
1359 ToPrimitive,
1360 ToSql,
1361 FromSql,
1362 Serialize,
1363 Deserialize,
1364)]
1365#[repr(u32)]
1366pub enum MessageState {
1367 #[default]
1369 Undefined = 0,
1370
1371 InFresh = 10,
1374
1375 InNoticed = 13,
1379
1380 InSeen = 16,
1383
1384 OutPreparing = 18,
1390
1391 OutDraft = 19,
1393
1394 OutPending = 20,
1398
1399 OutFailed = 24,
1402
1403 OutDelivered = 26,
1407
1408 OutMdnRcvd = 28,
1411}
1412
1413impl std::fmt::Display for MessageState {
1414 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1415 write!(
1416 f,
1417 "{}",
1418 match self {
1419 Self::Undefined => "Undefined",
1420 Self::InFresh => "Fresh",
1421 Self::InNoticed => "Noticed",
1422 Self::InSeen => "Seen",
1423 Self::OutPreparing => "Preparing",
1424 Self::OutDraft => "Draft",
1425 Self::OutPending => "Pending",
1426 Self::OutFailed => "Failed",
1427 Self::OutDelivered => "Delivered",
1428 Self::OutMdnRcvd => "Read",
1429 }
1430 )
1431 }
1432}
1433
1434impl MessageState {
1435 pub fn can_fail(self) -> bool {
1437 use MessageState::*;
1438 matches!(
1439 self,
1440 OutPreparing | OutPending | OutDelivered | OutMdnRcvd )
1442 }
1443
1444 pub fn is_outgoing(self) -> bool {
1446 use MessageState::*;
1447 matches!(
1448 self,
1449 OutPreparing | OutDraft | OutPending | OutFailed | OutDelivered | OutMdnRcvd
1450 )
1451 }
1452
1453 pub(crate) fn with_mdns(self, has_mdns: bool) -> Self {
1455 if self == MessageState::OutDelivered && has_mdns {
1456 return MessageState::OutMdnRcvd;
1457 }
1458 self
1459 }
1460}
1461
1462pub async fn get_msg_read_receipts(
1464 context: &Context,
1465 msg_id: MsgId,
1466) -> Result<Vec<(ContactId, i64)>> {
1467 context
1468 .sql
1469 .query_map_vec(
1470 "SELECT contact_id, timestamp_sent FROM msgs_mdns WHERE msg_id=?",
1471 (msg_id,),
1472 |row| {
1473 let contact_id: ContactId = row.get(0)?;
1474 let ts: i64 = row.get(1)?;
1475 Ok((contact_id, ts))
1476 },
1477 )
1478 .await
1479}
1480
1481pub async fn get_msg_read_receipt_count(context: &Context, msg_id: MsgId) -> Result<usize> {
1485 context
1486 .sql
1487 .count("SELECT COUNT(*) FROM msgs_mdns WHERE msg_id=?", (msg_id,))
1488 .await
1489}
1490
1491pub(crate) fn guess_msgtype_from_suffix(msg: &Message) -> Option<(Viewtype, &'static str)> {
1492 msg.param
1493 .get(Param::Filename)
1494 .or_else(|| msg.param.get(Param::File))
1495 .and_then(|file| guess_msgtype_from_path_suffix(Path::new(file)))
1496}
1497
1498pub(crate) fn guess_msgtype_from_path_suffix(path: &Path) -> Option<(Viewtype, &'static str)> {
1499 let extension: &str = &path.extension()?.to_str()?.to_lowercase();
1500 let info = match extension {
1501 "3gp" => (Viewtype::Video, "video/3gpp"),
1514 "aac" => (Viewtype::Audio, "audio/aac"),
1515 "avi" => (Viewtype::Video, "video/x-msvideo"),
1516 "avif" => (Viewtype::File, "image/avif"), "doc" => (Viewtype::File, "application/msword"),
1518 "docx" => (
1519 Viewtype::File,
1520 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1521 ),
1522 "epub" => (Viewtype::File, "application/epub+zip"),
1523 "flac" => (Viewtype::Audio, "audio/flac"),
1524 "gif" => (Viewtype::Gif, "image/gif"),
1525 "heic" => (Viewtype::File, "image/heic"), "heif" => (Viewtype::File, "image/heif"), "html" => (Viewtype::File, "text/html"),
1528 "htm" => (Viewtype::File, "text/html"),
1529 "ico" => (Viewtype::File, "image/vnd.microsoft.icon"),
1530 "jar" => (Viewtype::File, "application/java-archive"),
1531 "jpeg" => (Viewtype::Image, "image/jpeg"),
1532 "jpe" => (Viewtype::Image, "image/jpeg"),
1533 "jpg" => (Viewtype::Image, "image/jpeg"),
1534 "json" => (Viewtype::File, "application/json"),
1535 "mov" => (Viewtype::Video, "video/quicktime"),
1536 "m4a" => (Viewtype::Audio, "audio/m4a"),
1537 "mp3" => (Viewtype::Audio, "audio/mpeg"),
1538 "mp4" => (Viewtype::Video, "video/mp4"),
1539 "odp" => (
1540 Viewtype::File,
1541 "application/vnd.oasis.opendocument.presentation",
1542 ),
1543 "ods" => (
1544 Viewtype::File,
1545 "application/vnd.oasis.opendocument.spreadsheet",
1546 ),
1547 "odt" => (Viewtype::File, "application/vnd.oasis.opendocument.text"),
1548 "oga" => (Viewtype::Audio, "audio/ogg"),
1549 "ogg" => (Viewtype::Audio, "audio/ogg"),
1550 "ogv" => (Viewtype::File, "video/ogg"),
1551 "opus" => (Viewtype::File, "audio/ogg"), "otf" => (Viewtype::File, "font/otf"),
1553 "pdf" => (Viewtype::File, "application/pdf"),
1554 "png" => (Viewtype::Image, "image/png"),
1555 "ppt" => (Viewtype::File, "application/vnd.ms-powerpoint"),
1556 "pptx" => (
1557 Viewtype::File,
1558 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1559 ),
1560 "rar" => (Viewtype::File, "application/vnd.rar"),
1561 "rtf" => (Viewtype::File, "application/rtf"),
1562 "spx" => (Viewtype::File, "audio/ogg"), "svg" => (Viewtype::File, "image/svg+xml"),
1564 "tgs" => (Viewtype::File, "application/x-tgsticker"),
1565 "tiff" => (Viewtype::File, "image/tiff"),
1566 "tif" => (Viewtype::File, "image/tiff"),
1567 "ttf" => (Viewtype::File, "font/ttf"),
1568 "txt" => (Viewtype::File, "text/plain"),
1569 "vcard" => (Viewtype::Vcard, "text/vcard"),
1570 "vcf" => (Viewtype::Vcard, "text/vcard"),
1571 "wav" => (Viewtype::Audio, "audio/wav"),
1572 "weba" => (Viewtype::File, "audio/webm"),
1573 "webm" => (Viewtype::File, "video/webm"), "webp" => (Viewtype::Image, "image/webp"), "wmv" => (Viewtype::Video, "video/x-ms-wmv"),
1576 "xdc" => (Viewtype::Webxdc, "application/webxdc+zip"),
1577 "xhtml" => (Viewtype::File, "application/xhtml+xml"),
1578 "xls" => (Viewtype::File, "application/vnd.ms-excel"),
1579 "xlsx" => (
1580 Viewtype::File,
1581 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1582 ),
1583 "xml" => (Viewtype::File, "application/xml"),
1584 "zip" => (Viewtype::File, "application/zip"),
1585 _ => {
1586 return None;
1587 }
1588 };
1589 Some(info)
1590}
1591
1592pub(crate) async fn get_mime_headers(context: &Context, msg_id: MsgId) -> Result<Vec<u8>> {
1599 let (headers, compressed) = context
1600 .sql
1601 .query_row(
1602 "SELECT mime_headers, mime_compressed FROM msgs WHERE id=?",
1603 (msg_id,),
1604 |row| {
1605 let headers = sql::row_get_vec(row, 0)?;
1606 let compressed: bool = row.get(1)?;
1607 Ok((headers, compressed))
1608 },
1609 )
1610 .await?;
1611 if compressed {
1612 return buf_decompress(&headers);
1613 }
1614
1615 let headers2 = headers.clone();
1616 let compressed = match tokio::task::block_in_place(move || buf_compress(&headers2)) {
1617 Err(e) => {
1618 warn!(context, "get_mime_headers: buf_compress() failed: {}", e);
1619 return Ok(headers);
1620 }
1621 Ok(o) => o,
1622 };
1623 let update = |conn: &mut rusqlite::Connection| {
1624 match conn.execute(
1625 "\
1626 UPDATE msgs SET mime_headers=?, mime_compressed=1 \
1627 WHERE id=? AND mime_headers!='' AND mime_compressed=0",
1628 (compressed, msg_id),
1629 ) {
1630 Ok(rows_updated) => ensure!(rows_updated <= 1),
1631 Err(e) => {
1632 warn!(context, "get_mime_headers: UPDATE failed: {}", e);
1633 return Err(e.into());
1634 }
1635 }
1636 Ok(())
1637 };
1638 if let Err(e) = context.sql.call_write(update).await {
1639 warn!(
1640 context,
1641 "get_mime_headers: failed to update mime_headers: {}", e
1642 );
1643 }
1644
1645 Ok(headers)
1646}
1647
1648pub(crate) async fn delete_msg_locally(context: &Context, msg: &Message) -> Result<()> {
1651 if msg.location_id > 0 {
1652 delete_poi_location(context, msg.location_id).await?;
1653 }
1654 let on_server = true;
1655 msg.id
1656 .trash(context, on_server)
1657 .await
1658 .with_context(|| format!("Unable to trash message {}", msg.id))?;
1659
1660 context.emit_event(EventType::MsgDeleted {
1661 chat_id: msg.chat_id,
1662 msg_id: msg.id,
1663 });
1664
1665 if msg.viewtype == Viewtype::Webxdc {
1666 context.emit_event(EventType::WebxdcInstanceDeleted { msg_id: msg.id });
1667 }
1668
1669 let logging_xdc_id = context
1670 .debug_logging
1671 .read()
1672 .expect("RwLock is poisoned")
1673 .as_ref()
1674 .map(|dl| dl.msg_id);
1675 if let Some(id) = logging_xdc_id
1676 && id == msg.id
1677 {
1678 set_debug_logging_xdc(context, None).await?;
1679 }
1680
1681 Ok(())
1682}
1683
1684pub(crate) async fn delete_msgs_locally_done(
1687 context: &Context,
1688 msg_ids: &[MsgId],
1689 modified_chat_ids: BTreeSet<ChatId>,
1690) -> Result<()> {
1691 for modified_chat_id in modified_chat_ids {
1692 context.emit_msgs_changed_without_msg_id(modified_chat_id);
1693 chatlist_events::emit_chatlist_item_changed(context, modified_chat_id);
1694 }
1695 if !msg_ids.is_empty() {
1696 context.emit_msgs_changed_without_ids();
1697 chatlist_events::emit_chatlist_changed(context);
1698 context
1700 .set_config_internal(Config::LastHousekeeping, None)
1701 .await?;
1702 }
1703 Ok(())
1704}
1705
1706pub async fn delete_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
1708 delete_msgs_ex(context, msg_ids, false).await
1709}
1710
1711pub async fn delete_msgs_ex(
1715 context: &Context,
1716 msg_ids: &[MsgId],
1717 delete_for_all: bool,
1718) -> Result<()> {
1719 let mut modified_chat_ids = BTreeSet::new();
1720 let mut deleted_rfc724_mid = Vec::new();
1721 let mut res = Ok(());
1722
1723 for &msg_id in msg_ids {
1724 let msg = Message::load_from_db(context, msg_id).await?;
1725 ensure!(
1726 !delete_for_all || msg.from_id == ContactId::SELF,
1727 "Can delete only own messages for others"
1728 );
1729 ensure!(
1730 !delete_for_all || msg.get_showpadlock(),
1731 "Cannot request deletion of unencrypted message for others"
1732 );
1733
1734 modified_chat_ids.insert(msg.chat_id);
1735 deleted_rfc724_mid.push(msg.rfc724_mid.clone());
1736
1737 let update_db = |trans: &mut rusqlite::Transaction| {
1738 let mut stmt = trans.prepare("UPDATE imap SET target='' WHERE rfc724_mid=?")?;
1739 stmt.execute((&msg.rfc724_mid,))?;
1740 if !msg.pre_rfc724_mid.is_empty() {
1741 stmt.execute((&msg.pre_rfc724_mid,))?;
1742 }
1743 trans.execute("DELETE FROM smtp WHERE msg_id=?", (msg_id,))?;
1744 trans.execute(
1745 "DELETE FROM download WHERE rfc724_mid=?",
1746 (&msg.rfc724_mid,),
1747 )?;
1748 trans.execute(
1749 "DELETE FROM available_post_msgs WHERE rfc724_mid=?",
1750 (&msg.rfc724_mid,),
1751 )?;
1752 Ok(())
1753 };
1754 if let Err(e) = context.sql.transaction(update_db).await {
1755 error!(context, "delete_msgs: failed to update db: {e:#}.");
1756 res = Err(e);
1757 continue;
1758 }
1759 }
1760 res?;
1761
1762 if delete_for_all {
1763 ensure!(
1764 modified_chat_ids.len() == 1,
1765 "Can delete only from same chat."
1766 );
1767 if let Some(chat_id) = modified_chat_ids.iter().next() {
1768 let mut msg = Message::new_text("🚮".to_owned());
1769 msg.param.set_int(Param::GuaranteeE2ee, 1);
1774 msg.param
1775 .set(Param::DeleteRequestFor, deleted_rfc724_mid.join(" "));
1776 msg.hidden = true;
1777 send_msg(context, *chat_id, &mut msg).await?;
1778 }
1779 } else {
1780 context
1781 .add_sync_item(SyncData::DeleteMessages {
1782 msgs: deleted_rfc724_mid,
1783 })
1784 .await?;
1785 context.scheduler.interrupt_smtp().await;
1786 }
1787
1788 for &msg_id in msg_ids {
1789 let msg = Message::load_from_db(context, msg_id).await?;
1790 delete_msg_locally(context, &msg).await?;
1791 }
1792 delete_msgs_locally_done(context, msg_ids, modified_chat_ids).await?;
1793
1794 context.scheduler.interrupt_inbox().await;
1796
1797 Ok(())
1798}
1799
1800pub async fn markseen_msgs(context: &Context, msg_ids: Vec<MsgId>) -> Result<()> {
1802 if msg_ids.is_empty() {
1803 return Ok(());
1804 }
1805
1806 let old_last_msg_id = MsgId::new(context.get_config_u32(Config::LastMsgId).await?);
1807 let last_msg_id = msg_ids.iter().fold(&old_last_msg_id, std::cmp::max);
1808 context
1809 .set_config_internal(Config::LastMsgId, Some(&last_msg_id.to_u32().to_string()))
1810 .await?;
1811
1812 let mut msgs = Vec::with_capacity(msg_ids.len());
1813 for &id in &msg_ids {
1814 if let Some(msg) = context
1815 .sql
1816 .query_row_optional(
1817 "SELECT
1818 m.chat_id AS chat_id,
1819 m.state AS state,
1820 m.ephemeral_timer AS ephemeral_timer,
1821 m.param AS param,
1822 m.from_id AS from_id,
1823 m.rfc724_mid AS rfc724_mid,
1824 m.hidden AS hidden,
1825 c.archived AS archived,
1826 c.blocked AS blocked
1827 FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id
1828 WHERE m.id=? AND m.chat_id>9",
1829 (id,),
1830 |row| {
1831 let chat_id: ChatId = row.get("chat_id")?;
1832 let state: MessageState = row.get("state")?;
1833 let param: Params = row.get::<_, String>("param")?.parse().unwrap_or_default();
1834 let from_id: ContactId = row.get("from_id")?;
1835 let rfc724_mid: String = row.get("rfc724_mid")?;
1836 let hidden: bool = row.get("hidden")?;
1837 let visibility: ChatVisibility = row.get("archived")?;
1838 let blocked: Option<Blocked> = row.get("blocked")?;
1839 let ephemeral_timer: EphemeralTimer = row.get("ephemeral_timer")?;
1840 Ok((
1841 (
1842 id,
1843 chat_id,
1844 state,
1845 param,
1846 from_id,
1847 rfc724_mid,
1848 hidden,
1849 visibility,
1850 blocked.unwrap_or_default(),
1851 ),
1852 ephemeral_timer,
1853 ))
1854 },
1855 )
1856 .await?
1857 {
1858 msgs.push(msg);
1859 }
1860 }
1861
1862 if msgs
1863 .iter()
1864 .any(|(_, ephemeral_timer)| *ephemeral_timer != EphemeralTimer::Disabled)
1865 {
1866 start_ephemeral_timers_msgids(context, &msg_ids)
1867 .await
1868 .context("failed to start ephemeral timers")?;
1869 }
1870
1871 let mut updated_chat_ids = BTreeSet::new();
1872 let mut archived_chats_maybe_noticed = false;
1873 for (
1874 (
1875 id,
1876 curr_chat_id,
1877 curr_state,
1878 curr_param,
1879 curr_from_id,
1880 curr_rfc724_mid,
1881 curr_hidden,
1882 curr_visibility,
1883 curr_blocked,
1884 ),
1885 _curr_ephemeral_timer,
1886 ) in msgs
1887 {
1888 if curr_state == MessageState::InFresh || curr_state == MessageState::InNoticed {
1889 update_msg_state(context, id, MessageState::InSeen).await?;
1890 info!(context, "Seen message {}.", id);
1891
1892 markseen_on_imap_table(context, &curr_rfc724_mid).await?;
1893
1894 let to_id = if curr_blocked == Blocked::Not
1905 && !curr_hidden
1906 && curr_param.get_bool(Param::WantsMdn).unwrap_or_default()
1907 && curr_param.get_cmd() == SystemMessage::Unknown
1908 && context.should_send_mdns().await?
1909 {
1910 context
1914 .sql
1915 .execute(
1916 "UPDATE msgs SET param=? WHERE id=?",
1917 (curr_param.clone().remove(Param::WantsMdn).to_string(), id),
1918 )
1919 .await
1920 .context("failed to clear WantsMdn")?;
1921 Some(curr_from_id)
1922 } else if context.get_config_bool(Config::BccSelf).await? {
1923 Some(ContactId::SELF)
1924 } else {
1925 None
1926 };
1927 if let Some(to_id) = to_id {
1928 context
1929 .sql
1930 .execute(
1931 "INSERT INTO smtp_mdns (msg_id, from_id, rfc724_mid) VALUES(?, ?, ?)",
1932 (id, to_id, curr_rfc724_mid),
1933 )
1934 .await
1935 .context("failed to insert into smtp_mdns")?;
1936 context.scheduler.interrupt_smtp().await;
1937 }
1938
1939 if !curr_hidden {
1940 updated_chat_ids.insert(curr_chat_id);
1941 }
1942 }
1943 archived_chats_maybe_noticed |= curr_state == MessageState::InFresh
1944 && !curr_hidden
1945 && curr_visibility == ChatVisibility::Archived;
1946 }
1947
1948 for updated_chat_id in updated_chat_ids {
1949 context.emit_event(EventType::MsgsNoticed(updated_chat_id));
1950 chatlist_events::emit_chatlist_item_changed(context, updated_chat_id);
1951 }
1952 if archived_chats_maybe_noticed {
1953 context.on_archived_chats_maybe_noticed();
1954 }
1955
1956 Ok(())
1957}
1958
1959pub async fn get_existing_msg_ids(context: &Context, ids: &[MsgId]) -> Result<Vec<MsgId>> {
1963 let query_only = true;
1964 let res = context
1965 .sql
1966 .transaction_ex(query_only, |transaction| {
1967 let mut res: Vec<MsgId> = Vec::new();
1968 for id in ids {
1969 if transaction.query_one(
1970 "SELECT COUNT(*) > 0 FROM msgs WHERE id=? AND chat_id!=3",
1971 (id,),
1972 |row| {
1973 let exists: bool = row.get(0)?;
1974 Ok(exists)
1975 },
1976 )? {
1977 res.push(*id);
1978 }
1979 }
1980 Ok(res)
1981 })
1982 .await?;
1983 Ok(res)
1984}
1985
1986pub(crate) async fn update_msg_state(
1987 context: &Context,
1988 msg_id: MsgId,
1989 state: MessageState,
1990) -> Result<()> {
1991 ensure!(
1992 state != MessageState::OutMdnRcvd,
1993 "Update msgs_mdns table instead!"
1994 );
1995 ensure!(state != MessageState::OutFailed, "use set_msg_failed()!");
1996 let error_subst = match state >= MessageState::OutPending {
1997 true => ", error=''",
1998 false => "",
1999 };
2000 context
2001 .sql
2002 .execute(
2003 &format!("UPDATE msgs SET state=? {error_subst} WHERE id=?"),
2004 (state, msg_id),
2005 )
2006 .await?;
2007 Ok(())
2008}
2009
2010pub(crate) async fn set_msg_failed(
2018 context: &Context,
2019 msg: &mut Message,
2020 error: &str,
2021) -> Result<()> {
2022 if msg.state.can_fail() {
2023 msg.state = MessageState::OutFailed;
2024 warn!(context, "{} failed: {}", msg.id, error);
2025 } else {
2026 warn!(
2027 context,
2028 "{} seems to have failed ({}), but state is {}", msg.id, error, msg.state
2029 )
2030 }
2031 msg.error = Some(error.to_string());
2032
2033 let exists = context
2034 .sql
2035 .execute(
2036 "UPDATE msgs SET state=?, error=? WHERE id=?;",
2037 (msg.state, error, msg.id),
2038 )
2039 .await?
2040 > 0;
2041 context.emit_event(EventType::MsgFailed {
2042 chat_id: msg.chat_id,
2043 msg_id: msg.id,
2044 });
2045 if exists {
2046 chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
2047 }
2048 Ok(())
2049}
2050
2051pub(crate) async fn insert_tombstone(context: &Context, rfc724_mid: &str) -> Result<MsgId> {
2056 let row_id = context
2057 .sql
2058 .insert(
2059 "INSERT INTO msgs(rfc724_mid, chat_id) VALUES (?,?)",
2060 (rfc724_mid, DC_CHAT_ID_TRASH),
2061 )
2062 .await?;
2063 let msg_id = MsgId::new(u32::try_from(row_id)?);
2064 Ok(msg_id)
2065}
2066
2067pub async fn get_unblocked_msg_cnt(context: &Context) -> usize {
2069 match context
2070 .sql
2071 .count(
2072 "SELECT COUNT(*) \
2073 FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id \
2074 WHERE m.id>9 AND m.chat_id>9 AND c.blocked=0;",
2075 (),
2076 )
2077 .await
2078 {
2079 Ok(res) => res,
2080 Err(err) => {
2081 error!(context, "get_unblocked_msg_cnt() failed. {:#}", err);
2082 0
2083 }
2084 }
2085}
2086
2087pub async fn get_request_msg_cnt(context: &Context) -> usize {
2089 match context
2090 .sql
2091 .count(
2092 "SELECT COUNT(*) \
2093 FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id \
2094 WHERE c.blocked=2;",
2095 (),
2096 )
2097 .await
2098 {
2099 Ok(res) => res,
2100 Err(err) => {
2101 error!(context, "get_request_msg_cnt() failed. {:#}", err);
2102 0
2103 }
2104 }
2105}
2106
2107#[expect(clippy::arithmetic_side_effects)]
2122pub async fn estimate_deletion_cnt(
2123 context: &Context,
2124 from_server: bool,
2125 seconds: i64,
2126) -> Result<usize> {
2127 let self_chat_id = ChatIdBlocked::lookup_by_contact(context, ContactId::SELF)
2128 .await?
2129 .map(|c| c.id)
2130 .unwrap_or_default();
2131 let threshold_timestamp = time() - seconds;
2132
2133 let cnt = if from_server {
2134 context
2135 .sql
2136 .count(
2137 "SELECT COUNT(*)
2138 FROM msgs m
2139 WHERE m.id > ?
2140 AND timestamp < ?
2141 AND chat_id != ?
2142 AND EXISTS (SELECT * FROM imap WHERE rfc724_mid=m.rfc724_mid);",
2143 (DC_MSG_ID_LAST_SPECIAL, threshold_timestamp, self_chat_id),
2144 )
2145 .await?
2146 } else {
2147 context
2148 .sql
2149 .count(
2150 "SELECT COUNT(*)
2151 FROM msgs m
2152 WHERE m.id > ?
2153 AND timestamp < ?
2154 AND chat_id != ?
2155 AND chat_id != ? AND hidden = 0;",
2156 (
2157 DC_MSG_ID_LAST_SPECIAL,
2158 threshold_timestamp,
2159 self_chat_id,
2160 DC_CHAT_ID_TRASH,
2161 ),
2162 )
2163 .await?
2164 };
2165 Ok(cnt)
2166}
2167
2168pub(crate) async fn rfc724_mid_exists(
2170 context: &Context,
2171 rfc724_mid: &str,
2172) -> Result<Option<MsgId>> {
2173 Ok(rfc724_mid_exists_ex(context, rfc724_mid, "1")
2174 .await?
2175 .map(|(id, _)| id))
2176}
2177
2178pub(crate) async fn rfc724_mid_exists_ex(
2184 context: &Context,
2185 rfc724_mid: &str,
2186 expr: &str,
2187) -> Result<Option<(MsgId, bool)>> {
2188 let rfc724_mid = rfc724_mid.trim_start_matches('<').trim_end_matches('>');
2189 if rfc724_mid.is_empty() {
2190 warn!(context, "Empty rfc724_mid passed to rfc724_mid_exists");
2191 return Ok(None);
2192 }
2193
2194 let res = context
2195 .sql
2196 .query_row_optional(
2197 &("SELECT id, timestamp_sent, MIN(".to_string()
2198 + expr
2199 + ") FROM msgs WHERE rfc724_mid=?1 OR pre_rfc724_mid=?1
2200 HAVING COUNT(*) > 0 -- Prevent MIN(expr) from returning NULL when there are no rows.
2201 ORDER BY timestamp_sent DESC"),
2202 (rfc724_mid,),
2203 |row| {
2204 let msg_id: MsgId = row.get(0)?;
2205 let expr_res: bool = row.get(2)?;
2206 Ok((msg_id, expr_res))
2207 },
2208 )
2209 .await?;
2210
2211 Ok(res)
2212}
2213
2214pub(crate) async fn rfc724_mid_download_tried(context: &Context, rfc724_mid: &str) -> Result<bool> {
2219 let rfc724_mid = rfc724_mid.trim_start_matches('<').trim_end_matches('>');
2220 if rfc724_mid.is_empty() {
2221 warn!(
2222 context,
2223 "Empty rfc724_mid passed to rfc724_mid_download_tried"
2224 );
2225 return Ok(false);
2226 }
2227
2228 let res = context
2229 .sql
2230 .exists(
2231 "SELECT COUNT(*) FROM msgs
2232 WHERE rfc724_mid=? AND download_state<>?",
2233 (rfc724_mid, DownloadState::Available),
2234 )
2235 .await?;
2236
2237 Ok(res)
2238}
2239
2240pub(crate) async fn get_by_rfc724_mids(
2247 context: &Context,
2248 mids: &[String],
2249) -> Result<Option<Message>> {
2250 let mut latest = None;
2251 for id in mids.iter().rev() {
2252 let Some(msg_id) = rfc724_mid_exists(context, id).await? else {
2253 continue;
2254 };
2255 let Some(msg) = Message::load_from_db_optional(context, msg_id).await? else {
2256 continue;
2257 };
2258 if msg.download_state == DownloadState::Done {
2259 return Ok(Some(msg));
2260 }
2261 latest.get_or_insert(msg);
2262 }
2263 Ok(latest)
2264}
2265
2266pub(crate) fn get_vcard_summary(vcard: &[u8]) -> Option<String> {
2268 let vcard = str::from_utf8(vcard).ok()?;
2269 let contacts = deltachat_contact_tools::parse_vcard(vcard);
2270 let [c] = &contacts[..] else {
2271 return None;
2272 };
2273 if !deltachat_contact_tools::may_be_valid_addr(&c.addr) {
2274 return None;
2275 }
2276 Some(c.display_name().to_string())
2277}
2278
2279#[derive(
2281 Debug,
2282 Default,
2283 Display,
2284 Clone,
2285 Copy,
2286 PartialEq,
2287 Eq,
2288 FromPrimitive,
2289 ToPrimitive,
2290 FromSql,
2291 ToSql,
2292 Serialize,
2293 Deserialize,
2294)]
2295#[repr(u32)]
2296pub enum Viewtype {
2297 #[default]
2299 Unknown = 0,
2300
2301 Text = 10,
2304
2305 Image = 20,
2311
2312 Gif = 21,
2316
2317 Sticker = 23,
2322
2323 Audio = 40,
2327
2328 Voice = 41,
2333
2334 Video = 50,
2341
2342 File = 60,
2346
2347 Call = 71,
2349
2350 Webxdc = 80,
2352
2353 Vcard = 90,
2357}
2358
2359impl Viewtype {
2360 pub fn has_file(&self) -> bool {
2362 match self {
2363 Viewtype::Unknown => false,
2364 Viewtype::Text => false,
2365 Viewtype::Image => true,
2366 Viewtype::Gif => true,
2367 Viewtype::Sticker => true,
2368 Viewtype::Audio => true,
2369 Viewtype::Voice => true,
2370 Viewtype::Video => true,
2371 Viewtype::File => true,
2372 Viewtype::Call => false,
2373 Viewtype::Webxdc => true,
2374 Viewtype::Vcard => true,
2375 }
2376 }
2377}
2378
2379#[cfg(test)]
2380mod message_tests;