1use std::collections::BTreeSet;
4use std::collections::HashSet;
5use std::path::{Path, PathBuf};
6use std::str;
7
8use anyhow::{Context as _, Result, ensure, format_err};
9use deltachat_contact_tools::{VcardContact, parse_vcard};
10use deltachat_derive::{FromSql, ToSql};
11use serde::{Deserialize, Serialize};
12use tokio::{fs, io};
13
14use crate::blob::BlobObject;
15use crate::chat::{Chat, ChatId, ChatIdBlocked, ChatVisibility, send_msg};
16use crate::chatlist_events;
17use crate::config::Config;
18use crate::constants::{
19 Blocked, Chattype, DC_CHAT_ID_TRASH, DC_MSG_ID_LAST_SPECIAL, VideochatType,
20};
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::{error, info, warn};
30use crate::mimeparser::{SystemMessage, parse_message_id};
31use crate::param::{Param, Params};
32use crate::pgp::split_armored_data;
33use crate::reaction::get_msg_reactions;
34use crate::sql;
35use crate::summary::Summary;
36use crate::sync::SyncData;
37use crate::tools::create_outgoing_rfc724_mid;
38use crate::tools::{
39 buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file,
40 sanitize_filename, time, timestamp_to_str,
41};
42
43#[derive(
49 Debug, Copy, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
50)]
51pub struct MsgId(u32);
52
53impl MsgId {
54 pub fn new(id: u32) -> MsgId {
56 MsgId(id)
57 }
58
59 pub fn new_unset() -> MsgId {
61 MsgId(0)
62 }
63
64 pub fn is_special(self) -> bool {
68 self.0 <= DC_MSG_ID_LAST_SPECIAL
69 }
70
71 pub fn is_unset(self) -> bool {
81 self.0 == 0
82 }
83
84 pub async fn get_state(self, context: &Context) -> Result<MessageState> {
86 let result = context
87 .sql
88 .query_row_optional(
89 concat!(
90 "SELECT m.state, mdns.msg_id",
91 " FROM msgs m LEFT JOIN msgs_mdns mdns ON mdns.msg_id=m.id",
92 " WHERE id=?",
93 " LIMIT 1",
94 ),
95 (self,),
96 |row| {
97 let state: MessageState = row.get(0)?;
98 let mdn_msg_id: Option<MsgId> = row.get(1)?;
99 Ok(state.with_mdns(mdn_msg_id.is_some()))
100 },
101 )
102 .await?
103 .unwrap_or_default();
104 Ok(result)
105 }
106
107 pub(crate) async fn get_param(self, context: &Context) -> Result<Params> {
108 let res: Option<String> = context
109 .sql
110 .query_get_value("SELECT param FROM msgs WHERE id=?", (self,))
111 .await?;
112 Ok(res
113 .map(|s| s.parse().unwrap_or_default())
114 .unwrap_or_default())
115 }
116
117 pub(crate) async fn trash(self, context: &Context, on_server: bool) -> Result<()> {
129 context
130 .sql
131 .execute(
132 "INSERT OR REPLACE INTO msgs (id, rfc724_mid, timestamp, chat_id, deleted)
136 SELECT ?1, rfc724_mid, timestamp, ?, ? FROM msgs WHERE id=?1",
137 (self, DC_CHAT_ID_TRASH, on_server),
138 )
139 .await?;
140
141 Ok(())
142 }
143
144 pub(crate) async fn set_delivered(self, context: &Context) -> Result<()> {
145 update_msg_state(context, self, MessageState::OutDelivered).await?;
146 let chat_id: Option<ChatId> = context
147 .sql
148 .query_get_value("SELECT chat_id FROM msgs WHERE id=?", (self,))
149 .await?;
150 context.emit_event(EventType::MsgDelivered {
151 chat_id: chat_id.unwrap_or_default(),
152 msg_id: self,
153 });
154 if let Some(chat_id) = chat_id {
155 chatlist_events::emit_chatlist_item_changed(context, chat_id);
156 }
157 Ok(())
158 }
159
160 pub fn to_u32(self) -> u32 {
165 self.0
166 }
167
168 pub async fn get_info_server_urls(
170 context: &Context,
171 rfc724_mid: String,
172 ) -> Result<Vec<String>> {
173 context
174 .sql
175 .query_map(
176 "SELECT folder, uid FROM imap WHERE rfc724_mid=?",
177 (rfc724_mid,),
178 |row| {
179 let folder: String = row.get("folder")?;
180 let uid: u32 = row.get("uid")?;
181 Ok(format!("</{folder}/;UID={uid}>"))
182 },
183 |rows| {
184 rows.collect::<std::result::Result<Vec<_>, _>>()
185 .map_err(Into::into)
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_name_n_addr();
212 if let Some(override_sender_name) = msg.get_override_sender_name() {
213 let addr = from_contact.get_addr();
214 ret += &format!(" by ~{override_sender_name} ({addr})");
215 } else {
216 ret += &format!(" by {name}");
217 }
218 ret += "\n";
219
220 if msg.from_id != ContactId::SELF {
221 let s = timestamp_to_str(if 0 != msg.timestamp_rcvd {
222 msg.timestamp_rcvd
223 } else {
224 msg.timestamp_sort
225 });
226 ret += &format!("Received: {}", &s);
227 ret += "\n";
228 }
229
230 if let EphemeralTimer::Enabled { duration } = msg.ephemeral_timer {
231 ret += &format!("Ephemeral timer: {duration}\n");
232 }
233
234 if msg.ephemeral_timestamp != 0 {
235 ret += &format!("Expires: {}\n", timestamp_to_str(msg.ephemeral_timestamp));
236 }
237
238 if msg.from_id == ContactId::INFO || msg.to_id == ContactId::INFO {
239 return Ok(ret);
241 }
242
243 if let Ok(rows) = context
244 .sql
245 .query_map(
246 "SELECT contact_id, timestamp_sent FROM msgs_mdns WHERE msg_id=?",
247 (self,),
248 |row| {
249 let contact_id: ContactId = row.get(0)?;
250 let ts: i64 = row.get(1)?;
251 Ok((contact_id, ts))
252 },
253 |rows| rows.collect::<Result<Vec<_>, _>>().map_err(Into::into),
254 )
255 .await
256 {
257 for (contact_id, ts) in rows {
258 let fts = timestamp_to_str(ts);
259 ret += &format!("Read: {fts}");
260
261 let name = Contact::get_by_id(context, contact_id)
262 .await
263 .map(|contact| contact.get_name_n_addr())
264 .unwrap_or_default();
265
266 ret += &format!(" by {name}");
267 ret += "\n";
268 }
269 }
270
271 ret += &format!("State: {}", msg.state);
272
273 if msg.has_location() {
274 ret += ", Location sent";
275 }
276
277 if 0 != msg.param.get_int(Param::GuaranteeE2ee).unwrap_or_default() {
278 ret += ", Encrypted";
279 }
280
281 ret += "\n";
282
283 let reactions = get_msg_reactions(context, self).await?;
284 if !reactions.is_empty() {
285 ret += &format!("Reactions: {reactions}\n");
286 }
287
288 if let Some(error) = msg.error.as_ref() {
289 ret += &format!("Error: {error}");
290 }
291
292 if let Some(path) = msg.get_file(context) {
293 let bytes = get_filebytes(context, &path).await?;
294 ret += &format!(
295 "\nFile: {}, name: {}, {} bytes\n",
296 path.display(),
297 msg.get_filename().unwrap_or_default(),
298 bytes
299 );
300 }
301
302 if msg.viewtype != Viewtype::Text {
303 ret += "Type: ";
304 ret += &format!("{}", msg.viewtype);
305 ret += "\n";
306 ret += &format!("Mimetype: {}\n", &msg.get_filemime().unwrap_or_default());
307 }
308 let w = msg.param.get_int(Param::Width).unwrap_or_default();
309 let h = msg.param.get_int(Param::Height).unwrap_or_default();
310 if w != 0 || h != 0 {
311 ret += &format!("Dimension: {w} x {h}\n",);
312 }
313 let duration = msg.param.get_int(Param::Duration).unwrap_or_default();
314 if duration != 0 {
315 ret += &format!("Duration: {duration} ms\n",);
316 }
317 if !msg.rfc724_mid.is_empty() {
318 ret += &format!("\nMessage-ID: {}", msg.rfc724_mid);
319
320 let server_urls = Self::get_info_server_urls(context, msg.rfc724_mid).await?;
321 for server_url in server_urls {
322 ret += &format!("\nServer-URL: {server_url}");
324 }
325 }
326 let hop_info = self.hop_info(context).await?;
327
328 ret += "\n\n";
329 if hop_info.is_empty() {
330 ret += "No Hop Info";
331 } else {
332 ret += &hop_info;
333 }
334
335 Ok(ret)
336 }
337}
338
339impl std::fmt::Display for MsgId {
340 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341 write!(f, "Msg#{}", self.0)
342 }
343}
344
345impl rusqlite::types::ToSql for MsgId {
354 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
355 if self.0 <= DC_MSG_ID_LAST_SPECIAL {
356 return Err(rusqlite::Error::ToSqlConversionFailure(
357 format_err!("Invalid MsgId {}", self.0).into(),
358 ));
359 }
360 let val = rusqlite::types::Value::Integer(i64::from(self.0));
361 let out = rusqlite::types::ToSqlOutput::Owned(val);
362 Ok(out)
363 }
364}
365
366impl rusqlite::types::FromSql for MsgId {
368 fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
369 i64::column_result(value).and_then(|val| {
371 if 0 <= val && val <= i64::from(u32::MAX) {
372 Ok(MsgId::new(val as u32))
373 } else {
374 Err(rusqlite::types::FromSqlError::OutOfRange(val))
375 }
376 })
377 }
378}
379
380#[derive(
381 Debug,
382 Copy,
383 Clone,
384 PartialEq,
385 FromPrimitive,
386 ToPrimitive,
387 FromSql,
388 ToSql,
389 Serialize,
390 Deserialize,
391)]
392#[repr(u8)]
393pub(crate) enum MessengerMessage {
394 No = 0,
395 Yes = 1,
396
397 Reply = 2,
399}
400
401impl Default for MessengerMessage {
402 fn default() -> Self {
403 Self::No
404 }
405}
406
407#[derive(Debug, Clone, Default, Serialize, Deserialize)]
411pub struct Message {
412 pub(crate) id: MsgId,
414
415 pub(crate) from_id: ContactId,
417
418 pub(crate) to_id: ContactId,
420
421 pub(crate) chat_id: ChatId,
423
424 pub(crate) viewtype: Viewtype,
426
427 pub(crate) state: MessageState,
429 pub(crate) download_state: DownloadState,
430
431 pub(crate) hidden: bool,
433 pub(crate) timestamp_sort: i64,
434 pub(crate) timestamp_sent: i64,
435 pub(crate) timestamp_rcvd: i64,
436 pub(crate) ephemeral_timer: EphemeralTimer,
437 pub(crate) ephemeral_timestamp: i64,
438 pub(crate) text: String,
439
440 pub(crate) subject: String,
444
445 pub(crate) 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_blocked: Blocked,
454 pub(crate) location_id: u32,
455 pub(crate) error: Option<String>,
456 pub(crate) param: Params,
457}
458
459impl Message {
460 pub fn new(viewtype: Viewtype) -> Self {
462 Message {
463 viewtype,
464 rfc724_mid: create_outgoing_rfc724_mid(),
465 ..Default::default()
466 }
467 }
468
469 pub fn new_text(text: String) -> Self {
471 Message {
472 viewtype: Viewtype::Text,
473 text,
474 rfc724_mid: create_outgoing_rfc724_mid(),
475 ..Default::default()
476 }
477 }
478
479 pub async fn load_from_db(context: &Context, id: MsgId) -> Result<Message> {
483 let message = Self::load_from_db_optional(context, id)
484 .await?
485 .with_context(|| format!("Message {id} does not exist"))?;
486 Ok(message)
487 }
488
489 pub async fn load_from_db_optional(context: &Context, id: MsgId) -> Result<Option<Message>> {
493 ensure!(
494 !id.is_special(),
495 "Can not load special message ID {} from DB",
496 id
497 );
498 let msg = context
499 .sql
500 .query_row_optional(
501 concat!(
502 "SELECT",
503 " m.id AS id,",
504 " rfc724_mid AS 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.blocked AS blocked",
528 " FROM msgs m",
529 " LEFT JOIN chats c ON c.id=m.chat_id",
530 " LEFT JOIN msgs_mdns mdns ON mdns.msg_id=m.id",
531 " WHERE m.id=? AND chat_id!=3",
532 " LIMIT 1",
533 ),
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 in_reply_to: row
561 .get::<_, Option<String>>("mime_in_reply_to")?
562 .and_then(|in_reply_to| parse_message_id(&in_reply_to).ok()),
563 chat_id: row.get("chat_id")?,
564 from_id: row.get("from_id")?,
565 to_id: row.get("to_id")?,
566 timestamp_sort: row.get("timestamp")?,
567 timestamp_sent: row.get("timestamp_sent")?,
568 timestamp_rcvd: row.get("timestamp_rcvd")?,
569 ephemeral_timer: row.get("ephemeral_timer")?,
570 ephemeral_timestamp: row.get("ephemeral_timestamp")?,
571 viewtype: row.get("type")?,
572 state: state.with_mdns(mdn_msg_id.is_some()),
573 download_state: row.get("download_state")?,
574 error: Some(row.get::<_, String>("error")?)
575 .filter(|error| !error.is_empty()),
576 is_dc_message: row.get("msgrmsg")?,
577 original_msg_id: row.get("original_msg_id")?,
578 mime_modified: row.get("mime_modified")?,
579 text,
580 subject: row.get("subject")?,
581 param: row.get::<_, String>("param")?.parse().unwrap_or_default(),
582 hidden: row.get("hidden")?,
583 location_id: row.get("location")?,
584 chat_blocked: row
585 .get::<_, Option<Blocked>>("blocked")?
586 .unwrap_or_default(),
587 };
588 Ok(msg)
589 },
590 )
591 .await
592 .with_context(|| format!("failed to load message {id} from the database"))?;
593
594 Ok(msg)
595 }
596
597 pub fn get_filemime(&self) -> Option<String> {
604 if let Some(m) = self.param.get(Param::MimeType) {
605 return Some(m.to_string());
606 } else if self.param.exists(Param::File) {
607 if let Some((_, mime)) = guess_msgtype_from_suffix(self) {
608 return Some(mime.to_string());
609 }
610 return Some("application/octet-stream".to_string());
612 }
613 None
615 }
616
617 pub fn get_file(&self, context: &Context) -> Option<PathBuf> {
619 self.param.get_file_path(context).unwrap_or(None)
620 }
621
622 pub async fn vcard_contacts(&self, context: &Context) -> Result<Vec<VcardContact>> {
624 if self.viewtype != Viewtype::Vcard {
625 return Ok(Vec::new());
626 }
627
628 let path = self
629 .get_file(context)
630 .context("vCard message does not have an attachment")?;
631 let bytes = tokio::fs::read(path).await?;
632 let vcard_contents = std::str::from_utf8(&bytes).context("vCard is not a valid UTF-8")?;
633 Ok(parse_vcard(vcard_contents))
634 }
635
636 pub async fn save_file(&self, context: &Context, path: &Path) -> Result<()> {
638 let path_src = self.get_file(context).context("No file")?;
639 let mut src = fs::OpenOptions::new().read(true).open(path_src).await?;
640 let mut dst = fs::OpenOptions::new()
641 .write(true)
642 .create_new(true)
643 .open(path)
644 .await?;
645 io::copy(&mut src, &mut dst).await?;
646 Ok(())
647 }
648
649 pub(crate) async fn try_calc_and_set_dimensions(&mut self, context: &Context) -> Result<()> {
651 if self.viewtype.has_file() {
652 let file_param = self.param.get_file_path(context)?;
653 if let Some(path_and_filename) = file_param {
654 if (self.viewtype == Viewtype::Image || self.viewtype == Viewtype::Gif)
655 && !self.param.exists(Param::Width)
656 {
657 let buf = read_file(context, &path_and_filename).await?;
658
659 match get_filemeta(&buf) {
660 Ok((width, height)) => {
661 self.param.set_int(Param::Width, width as i32);
662 self.param.set_int(Param::Height, height as i32);
663 }
664 Err(err) => {
665 self.param.set_int(Param::Width, 0);
666 self.param.set_int(Param::Height, 0);
667 warn!(
668 context,
669 "Failed to get width and height for {}: {err:#}.",
670 path_and_filename.display()
671 );
672 }
673 }
674
675 if !self.id.is_unset() {
676 self.update_param(context).await?;
677 }
678 }
679 }
680 }
681 Ok(())
682 }
683
684 pub fn has_location(&self) -> bool {
690 self.location_id != 0
691 }
692
693 pub fn set_location(&mut self, latitude: f64, longitude: f64) {
710 if latitude == 0.0 && longitude == 0.0 {
711 return;
712 }
713
714 self.param.set_float(Param::SetLatitude, latitude);
715 self.param.set_float(Param::SetLongitude, longitude);
716 }
717
718 pub fn get_timestamp(&self) -> i64 {
721 if 0 != self.timestamp_sent {
722 self.timestamp_sent
723 } else {
724 self.timestamp_sort
725 }
726 }
727
728 pub fn get_id(&self) -> MsgId {
730 self.id
731 }
732
733 pub fn rfc724_mid(&self) -> &str {
736 &self.rfc724_mid
737 }
738
739 pub fn get_from_id(&self) -> ContactId {
741 self.from_id
742 }
743
744 pub fn get_chat_id(&self) -> ChatId {
746 self.chat_id
747 }
748
749 pub fn get_viewtype(&self) -> Viewtype {
751 self.viewtype
752 }
753
754 pub fn force_sticker(&mut self) {
757 self.param.set_int(Param::ForceSticker, 1);
758 }
759
760 pub fn get_state(&self) -> MessageState {
762 self.state
763 }
764
765 pub fn get_received_timestamp(&self) -> i64 {
767 self.timestamp_rcvd
768 }
769
770 pub fn get_sort_timestamp(&self) -> i64 {
772 self.timestamp_sort
773 }
774
775 pub fn get_text(&self) -> String {
777 self.text.clone()
778 }
779
780 pub fn get_subject(&self) -> &str {
782 &self.subject
783 }
784
785 pub fn get_filename(&self) -> Option<String> {
789 if let Some(name) = self.param.get(Param::Filename) {
790 return Some(sanitize_filename(name));
791 }
792 self.param
793 .get(Param::File)
794 .and_then(|file| Path::new(file).file_name())
795 .map(|name| sanitize_filename(&name.to_string_lossy()))
796 }
797
798 pub async fn get_filebytes(&self, context: &Context) -> Result<Option<u64>> {
800 if let Some(path) = self.param.get_file_path(context)? {
801 Ok(Some(get_filebytes(context, &path).await.with_context(
802 || format!("failed to get {} size in bytes", path.display()),
803 )?))
804 } else {
805 Ok(None)
806 }
807 }
808
809 pub fn get_width(&self) -> i32 {
811 self.param.get_int(Param::Width).unwrap_or_default()
812 }
813
814 pub fn get_height(&self) -> i32 {
816 self.param.get_int(Param::Height).unwrap_or_default()
817 }
818
819 pub fn get_duration(&self) -> i32 {
821 self.param.get_int(Param::Duration).unwrap_or_default()
822 }
823
824 pub fn get_showpadlock(&self) -> bool {
826 self.param.get_int(Param::GuaranteeE2ee).unwrap_or_default() != 0
827 || self.from_id == ContactId::DEVICE
828 }
829
830 pub fn is_bot(&self) -> bool {
832 self.param.get_bool(Param::Bot).unwrap_or_default()
833 }
834
835 pub fn get_ephemeral_timer(&self) -> EphemeralTimer {
837 self.ephemeral_timer
838 }
839
840 pub fn get_ephemeral_timestamp(&self) -> i64 {
842 self.ephemeral_timestamp
843 }
844
845 pub async fn get_summary(&self, context: &Context, chat: Option<&Chat>) -> Result<Summary> {
847 let chat_loaded: Chat;
848 let chat = if let Some(chat) = chat {
849 chat
850 } else {
851 let chat = Chat::load_from_db(context, self.chat_id).await?;
852 chat_loaded = chat;
853 &chat_loaded
854 };
855
856 let contact = if self.from_id != ContactId::SELF {
857 match chat.typ {
858 Chattype::Group
859 | Chattype::OutBroadcast
860 | Chattype::InBroadcast
861 | Chattype::Mailinglist => Some(Contact::get_by_id(context, self.from_id).await?),
862 Chattype::Single => None,
863 }
864 } else {
865 None
866 };
867
868 Summary::new(context, self, chat, contact.as_ref()).await
869 }
870
871 pub fn get_override_sender_name(&self) -> Option<String> {
881 self.param
882 .get(Param::OverrideSenderDisplayname)
883 .map(|name| name.to_string())
884 }
885
886 pub(crate) fn get_sender_name(&self, contact: &Contact) -> String {
889 self.get_override_sender_name()
890 .unwrap_or_else(|| contact.get_display_name().to_string())
891 }
892
893 pub fn has_deviating_timestamp(&self) -> bool {
898 let cnv_to_local = gm2local_offset();
899 let sort_timestamp = self.get_sort_timestamp() + cnv_to_local;
900 let send_timestamp = self.get_timestamp() + cnv_to_local;
901
902 sort_timestamp / 86400 != send_timestamp / 86400
903 }
904
905 pub fn is_sent(&self) -> bool {
908 self.state >= MessageState::OutDelivered
909 }
910
911 pub fn is_forwarded(&self) -> bool {
913 0 != self.param.get_int(Param::Forwarded).unwrap_or_default()
914 }
915
916 pub fn is_edited(&self) -> bool {
918 self.param.get_bool(Param::IsEdited).unwrap_or_default()
919 }
920
921 pub fn is_info(&self) -> bool {
923 let cmd = self.param.get_cmd();
924 self.from_id == ContactId::INFO
925 || self.to_id == ContactId::INFO
926 || cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage
927 }
928
929 pub fn get_info_type(&self) -> SystemMessage {
931 self.param.get_cmd()
932 }
933
934 pub async fn get_info_contact_id(&self, context: &Context) -> Result<Option<ContactId>> {
936 match self.param.get_cmd() {
937 SystemMessage::GroupNameChanged
938 | SystemMessage::GroupImageChanged
939 | SystemMessage::EphemeralTimerChanged => {
940 if self.from_id != ContactId::INFO {
941 Ok(Some(self.from_id))
942 } else {
943 Ok(None)
944 }
945 }
946
947 SystemMessage::MemberAddedToGroup | SystemMessage::MemberRemovedFromGroup => {
948 if let Some(contact_i32) = self.param.get_int(Param::ContactAddedRemoved) {
949 let contact_id = ContactId::new(contact_i32.try_into()?);
950 if contact_id == ContactId::SELF
951 || Contact::real_exists_by_id(context, contact_id).await?
952 {
953 Ok(Some(contact_id))
954 } else {
955 Ok(None)
956 }
957 } else {
958 Ok(None)
959 }
960 }
961
962 SystemMessage::AutocryptSetupMessage
963 | SystemMessage::SecurejoinMessage
964 | SystemMessage::LocationStreamingEnabled
965 | SystemMessage::LocationOnly
966 | SystemMessage::ChatE2ee
967 | SystemMessage::ChatProtectionEnabled
968 | SystemMessage::ChatProtectionDisabled
969 | SystemMessage::InvalidUnencryptedMail
970 | SystemMessage::SecurejoinWait
971 | SystemMessage::SecurejoinWaitTimeout
972 | SystemMessage::MultiDeviceSync
973 | SystemMessage::WebxdcStatusUpdate
974 | SystemMessage::WebxdcInfoMessage
975 | SystemMessage::IrohNodeAddr
976 | SystemMessage::Unknown => Ok(None),
977 }
978 }
979
980 pub fn is_system_message(&self) -> bool {
982 let cmd = self.param.get_cmd();
983 cmd != SystemMessage::Unknown
984 }
985
986 pub fn is_setupmessage(&self) -> bool {
988 if self.viewtype != Viewtype::File {
989 return false;
990 }
991
992 self.param.get_cmd() == SystemMessage::AutocryptSetupMessage
993 }
994
995 pub async fn get_setupcodebegin(&self, context: &Context) -> Option<String> {
999 if !self.is_setupmessage() {
1000 return None;
1001 }
1002
1003 if let Some(filename) = self.get_file(context) {
1004 if let Ok(ref buf) = read_file(context, &filename).await {
1005 if let Ok((typ, headers, _)) = split_armored_data(buf) {
1006 if typ == pgp::armor::BlockType::Message {
1007 return headers.get(crate::pgp::HEADER_SETUPCODE).cloned();
1008 }
1009 }
1010 }
1011 }
1012
1013 None
1014 }
1015
1016 pub(crate) fn create_webrtc_instance(instance: &str, room: &str) -> String {
1019 let (videochat_type, mut url) = Message::parse_webrtc_instance(instance);
1020
1021 if !url.contains(':') {
1023 url = format!("https://{url}");
1024 }
1025
1026 let url = if url.contains("$ROOM") {
1028 url.replace("$ROOM", room)
1029 } else if url.contains("$NOROOM") {
1030 url.replace("$NOROOM", "")
1036 } else {
1037 let maybe_slash = if url.ends_with('/')
1040 || url.ends_with('?')
1041 || url.ends_with('#')
1042 || url.ends_with('=')
1043 {
1044 ""
1045 } else {
1046 "/"
1047 };
1048 format!("{url}{maybe_slash}{room}")
1049 };
1050
1051 match videochat_type {
1053 VideochatType::BasicWebrtc => format!("basicwebrtc:{url}"),
1054 VideochatType::Jitsi => format!("jitsi:{url}"),
1055 VideochatType::Unknown => url,
1056 }
1057 }
1058
1059 pub fn parse_webrtc_instance(instance: &str) -> (VideochatType, String) {
1061 let instance: String = instance.split_whitespace().collect();
1062 let mut split = instance.splitn(2, ':');
1063 let type_str = split.next().unwrap_or_default().to_lowercase();
1064 let url = split.next();
1065 match type_str.as_str() {
1066 "basicwebrtc" => (
1067 VideochatType::BasicWebrtc,
1068 url.unwrap_or_default().to_string(),
1069 ),
1070 "jitsi" => (VideochatType::Jitsi, url.unwrap_or_default().to_string()),
1071 _ => (VideochatType::Unknown, instance.to_string()),
1072 }
1073 }
1074
1075 pub fn get_videochat_url(&self) -> Option<String> {
1077 if self.viewtype == Viewtype::VideochatInvitation {
1078 if let Some(instance) = self.param.get(Param::WebrtcRoom) {
1079 return Some(Message::parse_webrtc_instance(instance).1);
1080 }
1081 }
1082 None
1083 }
1084
1085 pub fn get_videochat_type(&self) -> Option<VideochatType> {
1087 if self.viewtype == Viewtype::VideochatInvitation {
1088 if let Some(instance) = self.param.get(Param::WebrtcRoom) {
1089 return Some(Message::parse_webrtc_instance(instance).0);
1090 }
1091 }
1092 None
1093 }
1094
1095 pub fn set_text(&mut self, text: String) {
1097 self.text = text;
1098 }
1099
1100 pub fn set_subject(&mut self, subject: String) {
1103 self.subject = subject;
1104 }
1105
1106 pub fn set_file_and_deduplicate(
1121 &mut self,
1122 context: &Context,
1123 file: &Path,
1124 name: Option<&str>,
1125 filemime: Option<&str>,
1126 ) -> Result<()> {
1127 let name = if let Some(name) = name {
1128 name.to_string()
1129 } else {
1130 file.file_name()
1131 .map(|s| s.to_string_lossy().to_string())
1132 .unwrap_or_else(|| "unknown_file".to_string())
1133 };
1134
1135 let blob = BlobObject::create_and_deduplicate(context, file, Path::new(&name))?;
1136 self.param.set(Param::File, blob.as_name());
1137
1138 self.param.set(Param::Filename, name);
1139 self.param.set_optional(Param::MimeType, filemime);
1140
1141 Ok(())
1142 }
1143
1144 pub fn set_file_from_bytes(
1151 &mut self,
1152 context: &Context,
1153 name: &str,
1154 data: &[u8],
1155 filemime: Option<&str>,
1156 ) -> Result<()> {
1157 let blob = BlobObject::create_and_deduplicate_from_bytes(context, data, name)?;
1158 self.param.set(Param::Filename, name);
1159 self.param.set(Param::File, blob.as_name());
1160 self.param.set_optional(Param::MimeType, filemime);
1161
1162 Ok(())
1163 }
1164
1165 pub async fn make_vcard(&mut self, context: &Context, contacts: &[ContactId]) -> Result<()> {
1167 ensure!(
1168 matches!(self.viewtype, Viewtype::File | Viewtype::Vcard),
1169 "Wrong viewtype for vCard: {}",
1170 self.viewtype,
1171 );
1172 let vcard = contact::make_vcard(context, contacts).await?;
1173 self.set_file_from_bytes(context, "vcard.vcf", vcard.as_bytes(), None)
1174 }
1175
1176 pub(crate) async fn try_set_vcard(&mut self, context: &Context, path: &Path) -> Result<()> {
1178 let vcard = fs::read(path)
1179 .await
1180 .with_context(|| format!("Could not read {path:?}"))?;
1181 if let Some(summary) = get_vcard_summary(&vcard) {
1182 self.param.set(Param::Summary1, summary);
1183 } else {
1184 warn!(context, "try_set_vcard: Not a valid DeltaChat vCard.");
1185 self.viewtype = Viewtype::File;
1186 }
1187 Ok(())
1188 }
1189
1190 pub fn set_override_sender_name(&mut self, name: Option<String>) {
1193 self.param
1194 .set_optional(Param::OverrideSenderDisplayname, name);
1195 }
1196
1197 pub fn set_dimension(&mut self, width: i32, height: i32) {
1199 self.param.set_int(Param::Width, width);
1200 self.param.set_int(Param::Height, height);
1201 }
1202
1203 pub fn set_duration(&mut self, duration: i32) {
1205 self.param.set_int(Param::Duration, duration);
1206 }
1207
1208 pub(crate) fn set_reaction(&mut self) {
1210 self.param.set_int(Param::Reaction, 1);
1211 }
1212
1213 pub async fn latefiling_mediasize(
1216 &mut self,
1217 context: &Context,
1218 width: i32,
1219 height: i32,
1220 duration: i32,
1221 ) -> Result<()> {
1222 if width > 0 && height > 0 {
1223 self.param.set_int(Param::Width, width);
1224 self.param.set_int(Param::Height, height);
1225 }
1226 if duration > 0 {
1227 self.param.set_int(Param::Duration, duration);
1228 }
1229 self.update_param(context).await?;
1230 Ok(())
1231 }
1232
1233 pub fn set_quote_text(&mut self, text: Option<(String, bool)>) {
1239 let Some((text, protect)) = text else {
1240 self.param.remove(Param::Quote);
1241 self.param.remove(Param::ProtectQuote);
1242 return;
1243 };
1244 self.param.set(Param::Quote, text);
1245 self.param.set_optional(
1246 Param::ProtectQuote,
1247 match protect {
1248 true => Some("1"),
1249 false => None,
1250 },
1251 );
1252 }
1253
1254 pub async fn set_quote(&mut self, context: &Context, quote: Option<&Message>) -> Result<()> {
1263 if let Some(quote) = quote {
1264 ensure!(
1265 !quote.rfc724_mid.is_empty(),
1266 "Message without Message-Id cannot be quoted"
1267 );
1268 self.in_reply_to = Some(quote.rfc724_mid.clone());
1269
1270 let text = quote.get_text();
1271 let text = if text.is_empty() {
1272 quote
1274 .get_summary(context, None)
1275 .await?
1276 .truncated_text(500)
1277 .to_string()
1278 } else {
1279 text
1280 };
1281 self.set_quote_text(Some((
1282 text,
1283 quote
1284 .param
1285 .get_bool(Param::GuaranteeE2ee)
1286 .unwrap_or_default(),
1287 )));
1288 } else {
1289 self.in_reply_to = None;
1290 self.set_quote_text(None);
1291 }
1292
1293 Ok(())
1294 }
1295
1296 pub fn quoted_text(&self) -> Option<String> {
1298 self.param.get(Param::Quote).map(|s| s.to_string())
1299 }
1300
1301 pub async fn quoted_message(&self, context: &Context) -> Result<Option<Message>> {
1303 if self.param.get(Param::Quote).is_some() && !self.is_forwarded() {
1304 return self.parent(context).await;
1305 }
1306 Ok(None)
1307 }
1308
1309 pub async fn parent(&self, context: &Context) -> Result<Option<Message>> {
1314 if let Some(in_reply_to) = &self.in_reply_to {
1315 if let Some((msg_id, _ts_sent)) = rfc724_mid_exists(context, in_reply_to).await? {
1316 let msg = Message::load_from_db_optional(context, msg_id).await?;
1317 return Ok(msg);
1318 }
1319 }
1320 Ok(None)
1321 }
1322
1323 pub async fn get_original_msg_id(&self, context: &Context) -> Result<Option<MsgId>> {
1325 if !self.original_msg_id.is_special() {
1326 if let Some(msg) = Message::load_from_db_optional(context, self.original_msg_id).await?
1327 {
1328 return if msg.chat_id.is_trash() {
1329 Ok(None)
1330 } else {
1331 Ok(Some(msg.id))
1332 };
1333 }
1334 }
1335 Ok(None)
1336 }
1337
1338 pub async fn get_saved_msg_id(&self, context: &Context) -> Result<Option<MsgId>> {
1342 let res: Option<MsgId> = context
1343 .sql
1344 .query_get_value(
1345 "SELECT id FROM msgs WHERE starred=? AND chat_id!=?",
1346 (self.id, DC_CHAT_ID_TRASH),
1347 )
1348 .await?;
1349 Ok(res)
1350 }
1351
1352 pub fn force_plaintext(&mut self) {
1354 self.param.set_int(Param::ForcePlaintext, 1);
1355 }
1356
1357 pub async fn update_param(&self, context: &Context) -> Result<()> {
1359 context
1360 .sql
1361 .execute(
1362 "UPDATE msgs SET param=? WHERE id=?;",
1363 (self.param.to_string(), self.id),
1364 )
1365 .await?;
1366 Ok(())
1367 }
1368
1369 pub fn error(&self) -> Option<String> {
1382 self.error.clone()
1383 }
1384}
1385
1386#[derive(
1390 Debug,
1391 Default,
1392 Clone,
1393 Copy,
1394 PartialEq,
1395 Eq,
1396 PartialOrd,
1397 Ord,
1398 FromPrimitive,
1399 ToPrimitive,
1400 ToSql,
1401 FromSql,
1402 Serialize,
1403 Deserialize,
1404)]
1405#[repr(u32)]
1406pub enum MessageState {
1407 #[default]
1409 Undefined = 0,
1410
1411 InFresh = 10,
1414
1415 InNoticed = 13,
1419
1420 InSeen = 16,
1423
1424 OutPreparing = 18,
1428
1429 OutDraft = 19,
1431
1432 OutPending = 20,
1436
1437 OutFailed = 24,
1440
1441 OutDelivered = 26,
1445
1446 OutMdnRcvd = 28,
1449}
1450
1451impl std::fmt::Display for MessageState {
1452 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1453 write!(
1454 f,
1455 "{}",
1456 match self {
1457 Self::Undefined => "Undefined",
1458 Self::InFresh => "Fresh",
1459 Self::InNoticed => "Noticed",
1460 Self::InSeen => "Seen",
1461 Self::OutPreparing => "Preparing",
1462 Self::OutDraft => "Draft",
1463 Self::OutPending => "Pending",
1464 Self::OutFailed => "Failed",
1465 Self::OutDelivered => "Delivered",
1466 Self::OutMdnRcvd => "Read",
1467 }
1468 )
1469 }
1470}
1471
1472impl MessageState {
1473 pub fn can_fail(self) -> bool {
1475 use MessageState::*;
1476 matches!(
1477 self,
1478 OutPreparing | OutPending | OutDelivered | OutMdnRcvd )
1480 }
1481
1482 pub fn is_outgoing(self) -> bool {
1484 use MessageState::*;
1485 matches!(
1486 self,
1487 OutPreparing | OutDraft | OutPending | OutFailed | OutDelivered | OutMdnRcvd
1488 )
1489 }
1490
1491 pub(crate) fn with_mdns(self, has_mdns: bool) -> Self {
1493 if self == MessageState::OutDelivered && has_mdns {
1494 return MessageState::OutMdnRcvd;
1495 }
1496 self
1497 }
1498}
1499
1500pub async fn get_msg_read_receipts(
1502 context: &Context,
1503 msg_id: MsgId,
1504) -> Result<Vec<(ContactId, i64)>> {
1505 context
1506 .sql
1507 .query_map(
1508 "SELECT contact_id, timestamp_sent FROM msgs_mdns WHERE msg_id=?",
1509 (msg_id,),
1510 |row| {
1511 let contact_id: ContactId = row.get(0)?;
1512 let ts: i64 = row.get(1)?;
1513 Ok((contact_id, ts))
1514 },
1515 |rows| rows.collect::<Result<Vec<_>, _>>().map_err(Into::into),
1516 )
1517 .await
1518}
1519
1520pub(crate) fn guess_msgtype_from_suffix(msg: &Message) -> Option<(Viewtype, &'static str)> {
1521 msg.param
1522 .get(Param::Filename)
1523 .or_else(|| msg.param.get(Param::File))
1524 .and_then(|file| guess_msgtype_from_path_suffix(Path::new(file)))
1525}
1526
1527pub(crate) fn guess_msgtype_from_path_suffix(path: &Path) -> Option<(Viewtype, &'static str)> {
1528 let extension: &str = &path.extension()?.to_str()?.to_lowercase();
1529 let info = match extension {
1530 "3gp" => (Viewtype::Video, "video/3gpp"),
1535 "aac" => (Viewtype::Audio, "audio/aac"),
1536 "avi" => (Viewtype::Video, "video/x-msvideo"),
1537 "avif" => (Viewtype::File, "image/avif"), "doc" => (Viewtype::File, "application/msword"),
1539 "docx" => (
1540 Viewtype::File,
1541 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1542 ),
1543 "epub" => (Viewtype::File, "application/epub+zip"),
1544 "flac" => (Viewtype::Audio, "audio/flac"),
1545 "gif" => (Viewtype::Gif, "image/gif"),
1546 "heic" => (Viewtype::File, "image/heic"), "heif" => (Viewtype::File, "image/heif"), "html" => (Viewtype::File, "text/html"),
1549 "htm" => (Viewtype::File, "text/html"),
1550 "ico" => (Viewtype::File, "image/vnd.microsoft.icon"),
1551 "jar" => (Viewtype::File, "application/java-archive"),
1552 "jpeg" => (Viewtype::Image, "image/jpeg"),
1553 "jpe" => (Viewtype::Image, "image/jpeg"),
1554 "jpg" => (Viewtype::Image, "image/jpeg"),
1555 "json" => (Viewtype::File, "application/json"),
1556 "mov" => (Viewtype::Video, "video/quicktime"),
1557 "m4a" => (Viewtype::Audio, "audio/m4a"),
1558 "mp3" => (Viewtype::Audio, "audio/mpeg"),
1559 "mp4" => (Viewtype::Video, "video/mp4"),
1560 "odp" => (
1561 Viewtype::File,
1562 "application/vnd.oasis.opendocument.presentation",
1563 ),
1564 "ods" => (
1565 Viewtype::File,
1566 "application/vnd.oasis.opendocument.spreadsheet",
1567 ),
1568 "odt" => (Viewtype::File, "application/vnd.oasis.opendocument.text"),
1569 "oga" => (Viewtype::Audio, "audio/ogg"),
1570 "ogg" => (Viewtype::Audio, "audio/ogg"),
1571 "ogv" => (Viewtype::File, "video/ogg"),
1572 "opus" => (Viewtype::File, "audio/ogg"), "otf" => (Viewtype::File, "font/otf"),
1574 "pdf" => (Viewtype::File, "application/pdf"),
1575 "png" => (Viewtype::Image, "image/png"),
1576 "ppt" => (Viewtype::File, "application/vnd.ms-powerpoint"),
1577 "pptx" => (
1578 Viewtype::File,
1579 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1580 ),
1581 "rar" => (Viewtype::File, "application/vnd.rar"),
1582 "rtf" => (Viewtype::File, "application/rtf"),
1583 "spx" => (Viewtype::File, "audio/ogg"), "svg" => (Viewtype::File, "image/svg+xml"),
1585 "tgs" => (Viewtype::File, "application/x-tgsticker"),
1586 "tiff" => (Viewtype::File, "image/tiff"),
1587 "tif" => (Viewtype::File, "image/tiff"),
1588 "ttf" => (Viewtype::File, "font/ttf"),
1589 "txt" => (Viewtype::File, "text/plain"),
1590 "vcard" => (Viewtype::Vcard, "text/vcard"),
1591 "vcf" => (Viewtype::Vcard, "text/vcard"),
1592 "wav" => (Viewtype::Audio, "audio/wav"),
1593 "weba" => (Viewtype::File, "audio/webm"),
1594 "webm" => (Viewtype::Video, "video/webm"),
1595 "webp" => (Viewtype::Image, "image/webp"), "wmv" => (Viewtype::Video, "video/x-ms-wmv"),
1597 "xdc" => (Viewtype::Webxdc, "application/webxdc+zip"),
1598 "xhtml" => (Viewtype::File, "application/xhtml+xml"),
1599 "xls" => (Viewtype::File, "application/vnd.ms-excel"),
1600 "xlsx" => (
1601 Viewtype::File,
1602 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1603 ),
1604 "xml" => (Viewtype::File, "application/xml"),
1605 "zip" => (Viewtype::File, "application/zip"),
1606 _ => {
1607 return None;
1608 }
1609 };
1610 Some(info)
1611}
1612
1613pub(crate) async fn get_mime_headers(context: &Context, msg_id: MsgId) -> Result<Vec<u8>> {
1620 let (headers, compressed) = context
1621 .sql
1622 .query_row(
1623 "SELECT mime_headers, mime_compressed FROM msgs WHERE id=?",
1624 (msg_id,),
1625 |row| {
1626 let headers = sql::row_get_vec(row, 0)?;
1627 let compressed: bool = row.get(1)?;
1628 Ok((headers, compressed))
1629 },
1630 )
1631 .await?;
1632 if compressed {
1633 return buf_decompress(&headers);
1634 }
1635
1636 let headers2 = headers.clone();
1637 let compressed = match tokio::task::block_in_place(move || buf_compress(&headers2)) {
1638 Err(e) => {
1639 warn!(context, "get_mime_headers: buf_compress() failed: {}", e);
1640 return Ok(headers);
1641 }
1642 Ok(o) => o,
1643 };
1644 let update = |conn: &mut rusqlite::Connection| {
1645 match conn.execute(
1646 "\
1647 UPDATE msgs SET mime_headers=?, mime_compressed=1 \
1648 WHERE id=? AND mime_headers!='' AND mime_compressed=0",
1649 (compressed, msg_id),
1650 ) {
1651 Ok(rows_updated) => ensure!(rows_updated <= 1),
1652 Err(e) => {
1653 warn!(context, "get_mime_headers: UPDATE failed: {}", e);
1654 return Err(e.into());
1655 }
1656 }
1657 Ok(())
1658 };
1659 if let Err(e) = context.sql.call_write(update).await {
1660 warn!(
1661 context,
1662 "get_mime_headers: failed to update mime_headers: {}", e
1663 );
1664 }
1665
1666 Ok(headers)
1667}
1668
1669pub(crate) async fn delete_msg_locally(context: &Context, msg: &Message) -> Result<()> {
1672 if msg.location_id > 0 {
1673 delete_poi_location(context, msg.location_id).await?;
1674 }
1675 let on_server = true;
1676 msg.id
1677 .trash(context, on_server)
1678 .await
1679 .with_context(|| format!("Unable to trash message {}", msg.id))?;
1680
1681 context.emit_event(EventType::MsgDeleted {
1682 chat_id: msg.chat_id,
1683 msg_id: msg.id,
1684 });
1685
1686 if msg.viewtype == Viewtype::Webxdc {
1687 context.emit_event(EventType::WebxdcInstanceDeleted { msg_id: msg.id });
1688 }
1689
1690 let logging_xdc_id = context
1691 .debug_logging
1692 .read()
1693 .expect("RwLock is poisoned")
1694 .as_ref()
1695 .map(|dl| dl.msg_id);
1696 if let Some(id) = logging_xdc_id {
1697 if id == msg.id {
1698 set_debug_logging_xdc(context, None).await?;
1699 }
1700 }
1701
1702 Ok(())
1703}
1704
1705pub(crate) async fn delete_msgs_locally_done(
1708 context: &Context,
1709 msg_ids: &[MsgId],
1710 modified_chat_ids: HashSet<ChatId>,
1711) -> Result<()> {
1712 for modified_chat_id in modified_chat_ids {
1713 context.emit_msgs_changed_without_msg_id(modified_chat_id);
1714 chatlist_events::emit_chatlist_item_changed(context, modified_chat_id);
1715 }
1716 if !msg_ids.is_empty() {
1717 context.emit_msgs_changed_without_ids();
1718 chatlist_events::emit_chatlist_changed(context);
1719 context
1721 .set_config_internal(Config::LastHousekeeping, None)
1722 .await?;
1723 }
1724 Ok(())
1725}
1726
1727pub async fn delete_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
1729 delete_msgs_ex(context, msg_ids, false).await
1730}
1731
1732pub async fn delete_msgs_ex(
1736 context: &Context,
1737 msg_ids: &[MsgId],
1738 delete_for_all: bool,
1739) -> Result<()> {
1740 let mut modified_chat_ids = HashSet::new();
1741 let mut deleted_rfc724_mid = Vec::new();
1742 let mut res = Ok(());
1743
1744 for &msg_id in msg_ids {
1745 let msg = Message::load_from_db(context, msg_id).await?;
1746 ensure!(
1747 !delete_for_all || msg.from_id == ContactId::SELF,
1748 "Can delete only own messages for others"
1749 );
1750 ensure!(
1751 !delete_for_all || msg.get_showpadlock(),
1752 "Cannot request deletion of unencrypted message for others"
1753 );
1754
1755 modified_chat_ids.insert(msg.chat_id);
1756 deleted_rfc724_mid.push(msg.rfc724_mid.clone());
1757
1758 let target = context.get_delete_msgs_target().await?;
1759 let update_db = |trans: &mut rusqlite::Transaction| {
1760 trans.execute(
1761 "UPDATE imap SET target=? WHERE rfc724_mid=?",
1762 (target, msg.rfc724_mid),
1763 )?;
1764 trans.execute("DELETE FROM smtp WHERE msg_id=?", (msg_id,))?;
1765 Ok(())
1766 };
1767 if let Err(e) = context.sql.transaction(update_db).await {
1768 error!(context, "delete_msgs: failed to update db: {e:#}.");
1769 res = Err(e);
1770 continue;
1771 }
1772 }
1773 res?;
1774
1775 if delete_for_all {
1776 ensure!(
1777 modified_chat_ids.len() == 1,
1778 "Can delete only from same chat."
1779 );
1780 if let Some(chat_id) = modified_chat_ids.iter().next() {
1781 let mut msg = Message::new_text("🚮".to_owned());
1782 msg.param.set_int(Param::GuaranteeE2ee, 1);
1787 msg.param
1788 .set(Param::DeleteRequestFor, deleted_rfc724_mid.join(" "));
1789 msg.hidden = true;
1790 send_msg(context, *chat_id, &mut msg).await?;
1791 }
1792 } else {
1793 context
1794 .add_sync_item(SyncData::DeleteMessages {
1795 msgs: deleted_rfc724_mid,
1796 })
1797 .await?;
1798 }
1799
1800 for &msg_id in msg_ids {
1801 let msg = Message::load_from_db(context, msg_id).await?;
1802 delete_msg_locally(context, &msg).await?;
1803 }
1804 delete_msgs_locally_done(context, msg_ids, modified_chat_ids).await?;
1805
1806 context.scheduler.interrupt_inbox().await;
1808
1809 Ok(())
1810}
1811
1812pub async fn markseen_msgs(context: &Context, msg_ids: Vec<MsgId>) -> Result<()> {
1814 if msg_ids.is_empty() {
1815 return Ok(());
1816 }
1817
1818 let old_last_msg_id = MsgId::new(context.get_config_u32(Config::LastMsgId).await?);
1819 let last_msg_id = msg_ids.iter().fold(&old_last_msg_id, std::cmp::max);
1820 context
1821 .set_config_internal(Config::LastMsgId, Some(&last_msg_id.to_u32().to_string()))
1822 .await?;
1823
1824 let mut msgs = Vec::with_capacity(msg_ids.len());
1825 for &id in &msg_ids {
1826 if let Some(msg) = context
1827 .sql
1828 .query_row_optional(
1829 "SELECT
1830 m.chat_id AS chat_id,
1831 m.state AS state,
1832 m.download_state as download_state,
1833 m.ephemeral_timer AS ephemeral_timer,
1834 m.param AS param,
1835 m.from_id AS from_id,
1836 m.rfc724_mid AS rfc724_mid,
1837 c.archived AS archived,
1838 c.blocked AS blocked
1839 FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id
1840 WHERE m.id=? AND m.chat_id>9",
1841 (id,),
1842 |row| {
1843 let chat_id: ChatId = row.get("chat_id")?;
1844 let state: MessageState = row.get("state")?;
1845 let download_state: DownloadState = row.get("download_state")?;
1846 let param: Params = row.get::<_, String>("param")?.parse().unwrap_or_default();
1847 let from_id: ContactId = row.get("from_id")?;
1848 let rfc724_mid: String = row.get("rfc724_mid")?;
1849 let visibility: ChatVisibility = row.get("archived")?;
1850 let blocked: Option<Blocked> = row.get("blocked")?;
1851 let ephemeral_timer: EphemeralTimer = row.get("ephemeral_timer")?;
1852 Ok((
1853 (
1854 id,
1855 chat_id,
1856 state,
1857 download_state,
1858 param,
1859 from_id,
1860 rfc724_mid,
1861 visibility,
1862 blocked.unwrap_or_default(),
1863 ),
1864 ephemeral_timer,
1865 ))
1866 },
1867 )
1868 .await?
1869 {
1870 msgs.push(msg);
1871 }
1872 }
1873
1874 if msgs
1875 .iter()
1876 .any(|(_, ephemeral_timer)| *ephemeral_timer != EphemeralTimer::Disabled)
1877 {
1878 start_ephemeral_timers_msgids(context, &msg_ids)
1879 .await
1880 .context("failed to start ephemeral timers")?;
1881 }
1882
1883 let mut updated_chat_ids = BTreeSet::new();
1884 let mut archived_chats_maybe_noticed = false;
1885 for (
1886 (
1887 id,
1888 curr_chat_id,
1889 curr_state,
1890 curr_download_state,
1891 curr_param,
1892 curr_from_id,
1893 curr_rfc724_mid,
1894 curr_visibility,
1895 curr_blocked,
1896 ),
1897 _curr_ephemeral_timer,
1898 ) in msgs
1899 {
1900 if curr_download_state != DownloadState::Done {
1901 if curr_state == MessageState::InFresh {
1902 update_msg_state(context, id, MessageState::InNoticed).await?;
1905 updated_chat_ids.insert(curr_chat_id);
1906 }
1907 } else if curr_state == MessageState::InFresh || curr_state == MessageState::InNoticed {
1908 update_msg_state(context, id, MessageState::InSeen).await?;
1909 info!(context, "Seen message {}.", id);
1910
1911 markseen_on_imap_table(context, &curr_rfc724_mid).await?;
1912
1913 if curr_blocked == Blocked::Not
1923 && curr_param.get_bool(Param::WantsMdn).unwrap_or_default()
1924 && curr_param.get_cmd() == SystemMessage::Unknown
1925 && context.should_send_mdns().await?
1926 {
1927 context
1928 .sql
1929 .execute(
1930 "INSERT INTO smtp_mdns (msg_id, from_id, rfc724_mid) VALUES(?, ?, ?)",
1931 (id, curr_from_id, curr_rfc724_mid),
1932 )
1933 .await
1934 .context("failed to insert into smtp_mdns")?;
1935 context.scheduler.interrupt_smtp().await;
1936 }
1937 updated_chat_ids.insert(curr_chat_id);
1938 }
1939 archived_chats_maybe_noticed |=
1940 curr_state == MessageState::InFresh && curr_visibility == ChatVisibility::Archived;
1941 }
1942
1943 for updated_chat_id in updated_chat_ids {
1944 context.emit_event(EventType::MsgsNoticed(updated_chat_id));
1945 chatlist_events::emit_chatlist_item_changed(context, updated_chat_id);
1946 }
1947 if archived_chats_maybe_noticed {
1948 context.on_archived_chats_maybe_noticed();
1949 }
1950
1951 Ok(())
1952}
1953
1954pub(crate) async fn update_msg_state(
1955 context: &Context,
1956 msg_id: MsgId,
1957 state: MessageState,
1958) -> Result<()> {
1959 ensure!(
1960 state != MessageState::OutMdnRcvd,
1961 "Update msgs_mdns table instead!"
1962 );
1963 ensure!(state != MessageState::OutFailed, "use set_msg_failed()!");
1964 let error_subst = match state >= MessageState::OutPending {
1965 true => ", error=''",
1966 false => "",
1967 };
1968 context
1969 .sql
1970 .execute(
1971 &format!("UPDATE msgs SET state=? {error_subst} WHERE id=?"),
1972 (state, msg_id),
1973 )
1974 .await?;
1975 Ok(())
1976}
1977
1978pub(crate) async fn set_msg_failed(
1986 context: &Context,
1987 msg: &mut Message,
1988 error: &str,
1989) -> Result<()> {
1990 if msg.state.can_fail() {
1991 msg.state = MessageState::OutFailed;
1992 warn!(context, "{} failed: {}", msg.id, error);
1993 } else {
1994 warn!(
1995 context,
1996 "{} seems to have failed ({}), but state is {}", msg.id, error, msg.state
1997 )
1998 }
1999 msg.error = Some(error.to_string());
2000
2001 let exists = context
2002 .sql
2003 .execute(
2004 "UPDATE msgs SET state=?, error=? WHERE id=?;",
2005 (msg.state, error, msg.id),
2006 )
2007 .await?
2008 > 0;
2009 context.emit_event(EventType::MsgFailed {
2010 chat_id: msg.chat_id,
2011 msg_id: msg.id,
2012 });
2013 if exists {
2014 chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
2015 }
2016 Ok(())
2017}
2018
2019pub async fn get_unblocked_msg_cnt(context: &Context) -> usize {
2021 match context
2022 .sql
2023 .count(
2024 "SELECT COUNT(*) \
2025 FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id \
2026 WHERE m.id>9 AND m.chat_id>9 AND c.blocked=0;",
2027 (),
2028 )
2029 .await
2030 {
2031 Ok(res) => res,
2032 Err(err) => {
2033 error!(context, "get_unblocked_msg_cnt() failed. {:#}", err);
2034 0
2035 }
2036 }
2037}
2038
2039pub async fn get_request_msg_cnt(context: &Context) -> usize {
2041 match context
2042 .sql
2043 .count(
2044 "SELECT COUNT(*) \
2045 FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id \
2046 WHERE c.blocked=2;",
2047 (),
2048 )
2049 .await
2050 {
2051 Ok(res) => res,
2052 Err(err) => {
2053 error!(context, "get_request_msg_cnt() failed. {:#}", err);
2054 0
2055 }
2056 }
2057}
2058
2059pub async fn estimate_deletion_cnt(
2075 context: &Context,
2076 from_server: bool,
2077 seconds: i64,
2078) -> Result<usize> {
2079 let self_chat_id = ChatIdBlocked::lookup_by_contact(context, ContactId::SELF)
2080 .await?
2081 .map(|c| c.id)
2082 .unwrap_or_default();
2083 let threshold_timestamp = time() - seconds;
2084
2085 let cnt = if from_server {
2086 context
2087 .sql
2088 .count(
2089 "SELECT COUNT(*)
2090 FROM msgs m
2091 WHERE m.id > ?
2092 AND timestamp < ?
2093 AND chat_id != ?
2094 AND EXISTS (SELECT * FROM imap WHERE rfc724_mid=m.rfc724_mid);",
2095 (DC_MSG_ID_LAST_SPECIAL, threshold_timestamp, self_chat_id),
2096 )
2097 .await?
2098 } else {
2099 context
2100 .sql
2101 .count(
2102 "SELECT COUNT(*)
2103 FROM msgs m
2104 WHERE m.id > ?
2105 AND timestamp < ?
2106 AND chat_id != ?
2107 AND chat_id != ? AND hidden = 0;",
2108 (
2109 DC_MSG_ID_LAST_SPECIAL,
2110 threshold_timestamp,
2111 self_chat_id,
2112 DC_CHAT_ID_TRASH,
2113 ),
2114 )
2115 .await?
2116 };
2117 Ok(cnt)
2118}
2119
2120pub(crate) async fn rfc724_mid_exists(
2122 context: &Context,
2123 rfc724_mid: &str,
2124) -> Result<Option<(MsgId, i64)>> {
2125 Ok(rfc724_mid_exists_ex(context, rfc724_mid, "1")
2126 .await?
2127 .map(|(id, ts_sent, _)| (id, ts_sent)))
2128}
2129
2130pub(crate) async fn rfc724_mid_exists_ex(
2136 context: &Context,
2137 rfc724_mid: &str,
2138 expr: &str,
2139) -> Result<Option<(MsgId, i64, bool)>> {
2140 let rfc724_mid = rfc724_mid.trim_start_matches('<').trim_end_matches('>');
2141 if rfc724_mid.is_empty() {
2142 warn!(context, "Empty rfc724_mid passed to rfc724_mid_exists");
2143 return Ok(None);
2144 }
2145
2146 let res = context
2147 .sql
2148 .query_row_optional(
2149 &("SELECT id, timestamp_sent, MIN(".to_string()
2150 + expr
2151 + ") FROM msgs WHERE rfc724_mid=?
2152 HAVING COUNT(*) > 0 -- Prevent MIN(expr) from returning NULL when there are no rows.
2153 ORDER BY timestamp_sent DESC"),
2154 (rfc724_mid,),
2155 |row| {
2156 let msg_id: MsgId = row.get(0)?;
2157 let timestamp_sent: i64 = row.get(1)?;
2158 let expr_res: bool = row.get(2)?;
2159 Ok((msg_id, timestamp_sent, expr_res))
2160 },
2161 )
2162 .await?;
2163
2164 Ok(res)
2165}
2166
2167pub(crate) async fn get_by_rfc724_mids(
2174 context: &Context,
2175 mids: &[String],
2176) -> Result<Option<Message>> {
2177 let mut latest = None;
2178 for id in mids.iter().rev() {
2179 let Some((msg_id, _)) = rfc724_mid_exists(context, id).await? else {
2180 continue;
2181 };
2182 let Some(msg) = Message::load_from_db_optional(context, msg_id).await? else {
2183 continue;
2184 };
2185 if msg.download_state == DownloadState::Done {
2186 return Ok(Some(msg));
2187 }
2188 latest.get_or_insert(msg);
2189 }
2190 Ok(latest)
2191}
2192
2193pub(crate) fn get_vcard_summary(vcard: &[u8]) -> Option<String> {
2195 let vcard = str::from_utf8(vcard).ok()?;
2196 let contacts = deltachat_contact_tools::parse_vcard(vcard);
2197 let [c] = &contacts[..] else {
2198 return None;
2199 };
2200 if !deltachat_contact_tools::may_be_valid_addr(&c.addr) {
2201 return None;
2202 }
2203 Some(c.display_name().to_string())
2204}
2205
2206#[derive(
2208 Debug,
2209 Default,
2210 Display,
2211 Clone,
2212 Copy,
2213 PartialEq,
2214 Eq,
2215 FromPrimitive,
2216 ToPrimitive,
2217 FromSql,
2218 ToSql,
2219 Serialize,
2220 Deserialize,
2221)]
2222#[repr(u32)]
2223pub enum Viewtype {
2224 #[default]
2226 Unknown = 0,
2227
2228 Text = 10,
2231
2232 Image = 20,
2238
2239 Gif = 21,
2243
2244 Sticker = 23,
2251
2252 Audio = 40,
2256
2257 Voice = 41,
2262
2263 Video = 50,
2270
2271 File = 60,
2275
2276 VideochatInvitation = 70,
2278
2279 Webxdc = 80,
2281
2282 Vcard = 90,
2286}
2287
2288impl Viewtype {
2289 pub fn has_file(&self) -> bool {
2291 match self {
2292 Viewtype::Unknown => false,
2293 Viewtype::Text => false,
2294 Viewtype::Image => true,
2295 Viewtype::Gif => true,
2296 Viewtype::Sticker => true,
2297 Viewtype::Audio => true,
2298 Viewtype::Voice => true,
2299 Viewtype::Video => true,
2300 Viewtype::File => true,
2301 Viewtype::VideochatInvitation => false,
2302 Viewtype::Webxdc => true,
2303 Viewtype::Vcard => true,
2304 }
2305 }
2306}
2307
2308pub(crate) fn normalize_text(text: &str) -> Option<String> {
2311 if text.is_ascii() {
2312 return None;
2313 };
2314 Some(text.to_lowercase()).filter(|t| t != text)
2315}
2316
2317#[cfg(test)]
2318mod message_tests;