1use std::collections::{BTreeSet, HashSet};
4use std::io::Cursor;
5
6use anyhow::{Context as _, Result, bail, ensure};
7use base64::Engine as _;
8use data_encoding::BASE32_NOPAD;
9use deltachat_contact_tools::sanitize_bidi_characters;
10use iroh_gossip::proto::TopicId;
11use mail_builder::headers::HeaderType;
12use mail_builder::headers::address::{Address, EmailAddress};
13use mail_builder::mime::MimePart;
14use tokio::fs;
15
16use crate::aheader::{Aheader, EncryptPreference};
17use crate::blob::BlobObject;
18use crate::chat::{self, Chat};
19use crate::config::Config;
20use crate::constants::ASM_SUBJECT;
21use crate::constants::{Chattype, DC_FROM_HANDSHAKE};
22use crate::contact::{Contact, ContactId, Origin};
23use crate::context::Context;
24use crate::e2ee::EncryptHelper;
25use crate::ensure_and_debug_assert;
26use crate::ephemeral::Timer as EphemeralTimer;
27use crate::headerdef::HeaderDef;
28use crate::key::{DcKey, SignedPublicKey, self_fingerprint};
29use crate::location;
30use crate::log::{info, warn};
31use crate::message::{Message, MsgId, Viewtype};
32use crate::mimeparser::{SystemMessage, is_hidden};
33use crate::param::Param;
34use crate::peer_channels::{create_iroh_header, get_iroh_topic_for_msg};
35use crate::simplify::escape_message_footer_marks;
36use crate::stock_str;
37use crate::tools::{
38 IsNoneOrEmpty, create_outgoing_rfc724_mid, create_smeared_timestamp, remove_subject_prefix,
39 time,
40};
41use crate::webxdc::StatusUpdateSerial;
42
43pub const RECOMMENDED_FILE_SIZE: u64 = 24 * 1024 * 1024 / 4 * 3;
47
48#[derive(Debug, Clone)]
49#[expect(clippy::large_enum_variant)]
50pub enum Loaded {
51 Message {
52 chat: Chat,
53 msg: Message,
54 },
55 Mdn {
56 rfc724_mid: String,
57 additional_msg_ids: Vec<String>,
58 },
59}
60
61#[derive(Debug, Clone)]
63pub struct MimeFactory {
64 from_addr: String,
65 from_displayname: String,
66
67 sender_displayname: Option<String>,
74
75 selfstatus: String,
76
77 recipients: Vec<String>,
91
92 encryption_keys: Option<Vec<(String, SignedPublicKey)>>,
98
99 to: Vec<(String, String)>,
106
107 past_members: Vec<(String, String)>,
109
110 member_fingerprints: Vec<String>,
116
117 member_timestamps: Vec<i64>,
123
124 timestamp: i64,
125 loaded: Loaded,
126 in_reply_to: String,
127
128 references: Vec<String>,
130
131 req_mdn: bool,
134
135 last_added_location_id: Option<u32>,
136
137 sync_ids_to_delete: Option<String>,
142
143 pub attach_selfavatar: bool,
145
146 webxdc_topic: Option<TopicId>,
148}
149
150#[derive(Debug, Clone)]
152pub struct RenderedEmail {
153 pub message: String,
154 pub is_encrypted: bool,
156 pub last_added_location_id: Option<u32>,
157
158 pub sync_ids_to_delete: Option<String>,
161
162 pub rfc724_mid: String,
164
165 pub subject: String,
167}
168
169fn new_address_with_name(name: &str, address: String) -> Address<'static> {
170 Address::new_address(
171 if name == address || name.is_empty() {
172 None
173 } else {
174 Some(name.to_string())
175 },
176 address,
177 )
178}
179
180impl MimeFactory {
181 pub async fn from_msg(context: &Context, msg: Message) -> Result<MimeFactory> {
182 let now = time();
183 let chat = Chat::load_from_db(context, msg.chat_id).await?;
184 let attach_profile_data = Self::should_attach_profile_data(&msg);
185 let undisclosed_recipients = chat.typ == Chattype::OutBroadcast;
186
187 let from_addr = context.get_primary_self_addr().await?;
188 let config_displayname = context
189 .get_config(Config::Displayname)
190 .await?
191 .unwrap_or_default();
192 let (from_displayname, sender_displayname) =
193 if let Some(override_name) = msg.param.get(Param::OverrideSenderDisplayname) {
194 (override_name.to_string(), Some(config_displayname))
195 } else {
196 let name = match attach_profile_data {
197 true => config_displayname,
198 false => "".to_string(),
199 };
200 (name, None)
201 };
202
203 let mut recipients = Vec::new();
204 let mut to = Vec::new();
205 let mut past_members = Vec::new();
206 let mut member_fingerprints = Vec::new();
207 let mut member_timestamps = Vec::new();
208 let mut recipient_ids = HashSet::new();
209 let mut req_mdn = false;
210
211 let encryption_keys;
212
213 let self_fingerprint = self_fingerprint(context).await?;
214
215 if chat.is_self_talk() {
216 to.push((from_displayname.to_string(), from_addr.to_string()));
217
218 encryption_keys = if msg.param.get_bool(Param::ForcePlaintext).unwrap_or(false) {
219 None
220 } else {
221 Some(Vec::new())
223 };
224 } else if chat.is_mailing_list() {
225 let list_post = chat
226 .param
227 .get(Param::ListPost)
228 .context("Can't write to mailinglist without ListPost param")?;
229 to.push(("".to_string(), list_post.to_string()));
230 recipients.push(list_post.to_string());
231
232 encryption_keys = None;
234 } else {
235 let email_to_remove = if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
236 msg.param.get(Param::Arg)
237 } else {
238 None
239 };
240
241 let is_encrypted = if msg
242 .param
243 .get_bool(Param::ForcePlaintext)
244 .unwrap_or_default()
245 {
246 false
247 } else {
248 msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
249 || chat.is_encrypted(context).await?
250 };
251
252 let mut keys = Vec::new();
253 let mut missing_key_addresses = BTreeSet::new();
254 context
255 .sql
256 .query_map(
261 "SELECT
262 c.authname,
263 c.addr,
264 c.fingerprint,
265 c.id,
266 cc.add_timestamp,
267 cc.remove_timestamp,
268 k.public_key
269 FROM chats_contacts cc
270 LEFT JOIN contacts c ON cc.contact_id=c.id
271 LEFT JOIN public_keys k ON k.fingerprint=c.fingerprint
272 WHERE cc.chat_id=?
273 AND (cc.contact_id>9 OR (cc.contact_id=1 AND ?))
274 ORDER BY cc.add_timestamp DESC",
275 (msg.chat_id, chat.typ == Chattype::Group),
276 |row| {
277 let authname: String = row.get(0)?;
278 let addr: String = row.get(1)?;
279 let fingerprint: String = row.get(2)?;
280 let id: ContactId = row.get(3)?;
281 let add_timestamp: i64 = row.get(4)?;
282 let remove_timestamp: i64 = row.get(5)?;
283 let public_key_bytes_opt: Option<Vec<u8>> = row.get(6)?;
284 Ok((authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt))
285 },
286 |rows| {
287 let mut past_member_timestamps = Vec::new();
288 let mut past_member_fingerprints = Vec::new();
289
290 for row in rows {
291 let (authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt) = row?;
292
293 let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
294 Some(SignedPublicKey::from_slice(public_key_bytes)?)
295 } else {
296 None
297 };
298
299 let addr = if id == ContactId::SELF {
300 from_addr.to_string()
301 } else {
302 addr
303 };
304 let name = match attach_profile_data {
305 true => authname,
306 false => "".to_string(),
307 };
308 if add_timestamp >= remove_timestamp {
309 if !recipients_contain_addr(&to, &addr) {
310 if id != ContactId::SELF {
311 recipients.push(addr.clone());
312 }
313 if !undisclosed_recipients {
314 to.push((name, addr.clone()));
315
316 if is_encrypted {
317 if !fingerprint.is_empty() {
318 member_fingerprints.push(fingerprint);
319 } else if id == ContactId::SELF {
320 member_fingerprints.push(self_fingerprint.to_string());
321 } else {
322 ensure_and_debug_assert!(member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
323 }
324 }
325 member_timestamps.push(add_timestamp);
326 }
327 }
328 recipient_ids.insert(id);
329
330 if let Some(public_key) = public_key_opt {
331 keys.push((addr.clone(), public_key))
332 } else if id != ContactId::SELF {
333 missing_key_addresses.insert(addr.clone());
334 if is_encrypted {
335 warn!(context, "Missing key for {addr}");
336 }
337 }
338 } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
339 if !recipients_contain_addr(&past_members, &addr) {
342 if let Some(email_to_remove) = email_to_remove {
343 if email_to_remove == addr {
344 if id != ContactId::SELF {
348 recipients.push(addr.clone());
349 }
350
351 if let Some(public_key) = public_key_opt {
352 keys.push((addr.clone(), public_key))
353 } else if id != ContactId::SELF {
354 missing_key_addresses.insert(addr.clone());
355 if is_encrypted {
356 warn!(context, "Missing key for {addr}");
357 }
358 }
359 }
360 }
361 if !undisclosed_recipients {
362 past_members.push((name, addr.clone()));
363 past_member_timestamps.push(remove_timestamp);
364
365 if is_encrypted {
366 if !fingerprint.is_empty() {
367 past_member_fingerprints.push(fingerprint);
368 } else if id == ContactId::SELF {
369 past_member_fingerprints.push(self_fingerprint.to_string());
372 } else {
373 ensure_and_debug_assert!(past_member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
374 }
375 }
376 }
377 }
378 }
379 }
380
381 ensure_and_debug_assert!(
382 member_timestamps.len() >= to.len(),
383 "member_timestamps.len() ({}) < to.len() ({})",
384 member_timestamps.len(), to.len());
385 ensure_and_debug_assert!(
386 member_fingerprints.is_empty() || member_fingerprints.len() >= to.len(),
387 "member_fingerprints.len() ({}) < to.len() ({})",
388 member_fingerprints.len(), to.len());
389
390 if to.len() > 1 {
391 if let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
392 to.remove(position);
393 member_timestamps.remove(position);
394 if is_encrypted {
395 member_fingerprints.remove(position);
396 }
397 }
398 }
399
400 member_timestamps.extend(past_member_timestamps);
401 if is_encrypted {
402 member_fingerprints.extend(past_member_fingerprints);
403 }
404 Ok(())
405 },
406 )
407 .await?;
408 let recipient_ids: Vec<_> = recipient_ids.into_iter().collect();
409 ContactId::scaleup_origin(context, &recipient_ids, Origin::OutgoingTo).await?;
410
411 if !msg.is_system_message()
412 && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
413 && context.should_request_mdns().await?
414 {
415 req_mdn = true;
416 }
417
418 encryption_keys = if !is_encrypted {
419 None
420 } else {
421 if keys.is_empty() && !recipients.is_empty() {
422 bail!(
423 "No recipient keys are available, cannot encrypt to {:?}.",
424 recipients
425 );
426 }
427
428 if !missing_key_addresses.is_empty() {
430 recipients.retain(|addr| !missing_key_addresses.contains(addr));
431 }
432
433 Some(keys)
434 };
435 }
436
437 let (in_reply_to, references) = context
438 .sql
439 .query_row(
440 "SELECT mime_in_reply_to, IFNULL(mime_references, '')
441 FROM msgs WHERE id=?",
442 (msg.id,),
443 |row| {
444 let in_reply_to: String = row.get(0)?;
445 let references: String = row.get(1)?;
446
447 Ok((in_reply_to, references))
448 },
449 )
450 .await?;
451 let references: Vec<String> = references
452 .trim()
453 .split_ascii_whitespace()
454 .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
455 .collect();
456 let selfstatus = match attach_profile_data {
457 true => context
458 .get_config(Config::Selfstatus)
459 .await?
460 .unwrap_or_default(),
461 false => "".to_string(),
462 };
463 let attach_selfavatar = Self::should_attach_selfavatar(context, &msg).await;
464
465 ensure_and_debug_assert!(
466 member_timestamps.is_empty()
467 || to.len() + past_members.len() == member_timestamps.len(),
468 "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
469 to.len(),
470 past_members.len(),
471 member_timestamps.len(),
472 );
473 let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
474 let factory = MimeFactory {
475 from_addr,
476 from_displayname,
477 sender_displayname,
478 selfstatus,
479 recipients,
480 encryption_keys,
481 to,
482 past_members,
483 member_fingerprints,
484 member_timestamps,
485 timestamp: msg.timestamp_sort,
486 loaded: Loaded::Message { msg, chat },
487 in_reply_to,
488 references,
489 req_mdn,
490 last_added_location_id: None,
491 sync_ids_to_delete: None,
492 attach_selfavatar,
493 webxdc_topic,
494 };
495 Ok(factory)
496 }
497
498 pub async fn from_mdn(
499 context: &Context,
500 from_id: ContactId,
501 rfc724_mid: String,
502 additional_msg_ids: Vec<String>,
503 ) -> Result<MimeFactory> {
504 let contact = Contact::get_by_id(context, from_id).await?;
505 let from_addr = context.get_primary_self_addr().await?;
506 let timestamp = create_smeared_timestamp(context);
507
508 let addr = contact.get_addr().to_string();
509 let encryption_keys = if contact.is_key_contact() {
510 if let Some(key) = contact.public_key(context).await? {
511 Some(vec![(addr.clone(), key)])
512 } else {
513 Some(Vec::new())
514 }
515 } else {
516 None
517 };
518
519 let res = MimeFactory {
520 from_addr,
521 from_displayname: "".to_string(),
522 sender_displayname: None,
523 selfstatus: "".to_string(),
524 recipients: vec![addr],
525 encryption_keys,
526 to: vec![("".to_string(), contact.get_addr().to_string())],
527 past_members: vec![],
528 member_fingerprints: vec![],
529 member_timestamps: vec![],
530 timestamp,
531 loaded: Loaded::Mdn {
532 rfc724_mid,
533 additional_msg_ids,
534 },
535 in_reply_to: String::default(),
536 references: Vec::new(),
537 req_mdn: false,
538 last_added_location_id: None,
539 sync_ids_to_delete: None,
540 attach_selfavatar: false,
541 webxdc_topic: None,
542 };
543
544 Ok(res)
545 }
546
547 fn should_skip_autocrypt(&self) -> bool {
548 match &self.loaded {
549 Loaded::Message { msg, .. } => {
550 msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
551 }
552 Loaded::Mdn { .. } => false,
553 }
554 }
555
556 fn should_attach_profile_data(msg: &Message) -> bool {
557 msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
558 let step = msg.param.get(Param::Arg).unwrap_or_default();
559 step == "vg-request-with-auth"
565 || step == "vc-request-with-auth"
566 || step == "vg-member-added"
567 || step == "vc-contact-confirm"
568 }
569 }
570
571 async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
572 Self::should_attach_profile_data(msg)
573 && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
574 Ok(should) => should,
575 Err(err) => {
576 warn!(
577 context,
578 "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
579 );
580 false
581 }
582 }
583 }
584
585 fn grpimage(&self) -> Option<String> {
586 match &self.loaded {
587 Loaded::Message { chat, msg } => {
588 let cmd = msg.param.get_cmd();
589
590 match cmd {
591 SystemMessage::MemberAddedToGroup => {
592 return chat.param.get(Param::ProfileImage).map(Into::into);
593 }
594 SystemMessage::GroupImageChanged => {
595 return msg.param.get(Param::Arg).map(Into::into);
596 }
597 _ => {}
598 }
599
600 if msg
601 .param
602 .get_bool(Param::AttachGroupImage)
603 .unwrap_or_default()
604 {
605 return chat.param.get(Param::ProfileImage).map(Into::into);
606 }
607
608 None
609 }
610 Loaded::Mdn { .. } => None,
611 }
612 }
613
614 async fn subject_str(&self, context: &Context) -> Result<String> {
615 let subject = match &self.loaded {
616 Loaded::Message { chat, msg } => {
617 let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
618
619 if !msg.subject.is_empty() {
620 return Ok(msg.subject.clone());
621 }
622
623 if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
624 && quoted_msg_subject.is_none_or_empty()
625 {
626 let re = if self.in_reply_to.is_empty() {
627 ""
628 } else {
629 "Re: "
630 };
631 return Ok(format!("{}{}", re, chat.name));
632 }
633
634 let parent_subject = if quoted_msg_subject.is_none_or_empty() {
635 chat.param.get(Param::LastSubject)
636 } else {
637 quoted_msg_subject.as_deref()
638 };
639 if let Some(last_subject) = parent_subject {
640 return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
641 }
642
643 let self_name = match Self::should_attach_profile_data(msg) {
644 true => context.get_config(Config::Displayname).await?,
645 false => None,
646 };
647 let self_name = &match self_name {
648 Some(name) => name,
649 None => context.get_config(Config::Addr).await?.unwrap_or_default(),
650 };
651 stock_str::subject_for_new_contact(context, self_name).await
652 }
653 Loaded::Mdn { .. } => "Receipt Notification".to_string(), };
655
656 Ok(subject)
657 }
658
659 pub fn recipients(&self) -> Vec<String> {
660 self.recipients.clone()
661 }
662
663 pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
666 let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
667
668 let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
669
670 let mut to: Vec<Address<'static>> = Vec::new();
671 for (name, addr) in &self.to {
672 to.push(Address::new_address(
673 if name.is_empty() {
674 None
675 } else {
676 Some(name.to_string())
677 },
678 addr.clone(),
679 ));
680 }
681
682 let mut past_members: Vec<Address<'static>> = Vec::new(); for (name, addr) in &self.past_members {
684 past_members.push(Address::new_address(
685 if name.is_empty() {
686 None
687 } else {
688 Some(name.to_string())
689 },
690 addr.clone(),
691 ));
692 }
693
694 ensure_and_debug_assert!(
695 self.member_timestamps.is_empty()
696 || to.len() + past_members.len() == self.member_timestamps.len(),
697 "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
698 to.len(),
699 past_members.len(),
700 self.member_timestamps.len(),
701 );
702 if to.is_empty() {
703 to.push(hidden_recipients());
704 }
705
706 headers.push(("From", from.into()));
709
710 if let Some(sender_displayname) = &self.sender_displayname {
711 let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
712 headers.push(("Sender", sender.into()));
713 }
714 headers.push((
715 "To",
716 mail_builder::headers::address::Address::new_list(to.clone()).into(),
717 ));
718 if !past_members.is_empty() {
719 headers.push((
720 "Chat-Group-Past-Members",
721 mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
722 ));
723 }
724
725 if let Loaded::Message { chat, .. } = &self.loaded {
726 if chat.typ == Chattype::Group {
727 if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await?
728 {
729 headers.push((
730 "Chat-Group-Member-Timestamps",
731 mail_builder::headers::raw::Raw::new(
732 self.member_timestamps
733 .iter()
734 .map(|ts| ts.to_string())
735 .collect::<Vec<String>>()
736 .join(" "),
737 )
738 .into(),
739 ));
740 }
741
742 if !self.member_fingerprints.is_empty() {
743 headers.push((
744 "Chat-Group-Member-Fpr",
745 mail_builder::headers::raw::Raw::new(
746 self.member_fingerprints
747 .iter()
748 .map(|fp| fp.to_string())
749 .collect::<Vec<String>>()
750 .join(" "),
751 )
752 .into(),
753 ));
754 }
755 }
756 }
757
758 let subject_str = self.subject_str(context).await?;
759 headers.push((
760 "Subject",
761 mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
762 ));
763
764 let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
765 .unwrap()
766 .to_rfc2822();
767 headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
768
769 let rfc724_mid = match &self.loaded {
770 Loaded::Message { msg, .. } => msg.rfc724_mid.clone(),
771 Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
772 };
773 headers.push((
774 "Message-ID",
775 mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
776 ));
777
778 if !self.in_reply_to.is_empty() {
780 headers.push((
781 "In-Reply-To",
782 mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
783 ));
784 }
785 if !self.references.is_empty() {
786 headers.push((
787 "References",
788 mail_builder::headers::message_id::MessageId::<'static>::new_list(
789 self.references.iter().map(|s| s.to_string()),
790 )
791 .into(),
792 ));
793 }
794
795 if let Loaded::Mdn { .. } = self.loaded {
797 headers.push((
798 "Auto-Submitted",
799 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
800 ));
801 } else if context.get_config_bool(Config::Bot).await? {
802 headers.push((
803 "Auto-Submitted",
804 mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
805 ));
806 } else if let Loaded::Message { msg, .. } = &self.loaded {
807 if msg.param.get_cmd() == SystemMessage::SecurejoinMessage {
808 let step = msg.param.get(Param::Arg).unwrap_or_default();
809 if step != "vg-request" && step != "vc-request" {
810 headers.push((
811 "Auto-Submitted",
812 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
813 ));
814 }
815 }
816 }
817
818 if let Loaded::Message { chat, .. } = &self.loaded {
819 if chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast {
820 headers.push((
821 "List-ID",
822 mail_builder::headers::text::Text::new(format!(
823 "{} <{}>",
824 chat.name, chat.grpid
825 ))
826 .into(),
827 ));
828 }
829 }
830
831 if let Loaded::Message { msg, .. } = &self.loaded {
832 if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
833 headers.push((
834 "Chat-Edit",
835 mail_builder::headers::message_id::MessageId::new(
836 original_rfc724_mid.to_string(),
837 )
838 .into(),
839 ));
840 } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
841 headers.push((
842 "Chat-Delete",
843 mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
844 .into(),
845 ));
846 }
847 }
848
849 headers.push((
851 "Chat-Version",
852 mail_builder::headers::raw::Raw::new("1.0").into(),
853 ));
854
855 if self.req_mdn {
856 headers.push((
860 "Chat-Disposition-Notification-To",
861 mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
862 ));
863 }
864
865 let grpimage = self.grpimage();
866 let skip_autocrypt = self.should_skip_autocrypt();
867 let encrypt_helper = EncryptHelper::new(context).await?;
868
869 if !skip_autocrypt {
870 let aheader = encrypt_helper.get_aheader().to_string();
872 headers.push((
873 "Autocrypt",
874 mail_builder::headers::raw::Raw::new(aheader).into(),
875 ));
876 }
877
878 let is_encrypted = self.encryption_keys.is_some();
879
880 if let Loaded::Message { msg, .. } = &self.loaded {
884 let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
885 if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
886 headers.push((
887 "Ephemeral-Timer",
888 mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
889 ));
890 }
891 }
892
893 let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
894 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
895 } else {
896 false
897 };
898
899 let message: MimePart<'static> = match &self.loaded {
900 Loaded::Message { msg, .. } => {
901 let msg = msg.clone();
902 let (main_part, mut parts) = self
903 .render_message(context, &mut headers, &grpimage, is_encrypted)
904 .await?;
905 if parts.is_empty() {
906 main_part
908 } else {
909 parts.insert(0, main_part);
910
911 if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
913 MimePart::new("multipart/report; report-type=multi-device-sync", parts)
914 } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
915 MimePart::new("multipart/report; report-type=status-update", parts)
916 } else {
917 MimePart::new("multipart/mixed", parts)
918 }
919 }
920 }
921 Loaded::Mdn { .. } => self.render_mdn()?,
922 };
923
924 let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
933
934 let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
947
948 let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
957
958 unprotected_headers.push((
960 "MIME-Version",
961 mail_builder::headers::raw::Raw::new("1.0").into(),
962 ));
963 for header @ (original_header_name, _header_value) in &headers {
964 let header_name = original_header_name.to_lowercase();
965 if header_name == "message-id" {
966 unprotected_headers.push(header.clone());
967 hidden_headers.push(header.clone());
968 } else if is_hidden(&header_name) {
969 hidden_headers.push(header.clone());
970 } else if header_name == "autocrypt"
971 && !context.get_config_bool(Config::ProtectAutocrypt).await?
972 {
973 unprotected_headers.push(header.clone());
974 } else if header_name == "from" {
975 if is_encrypted || !is_securejoin_message {
977 protected_headers.push(header.clone());
978 }
979
980 unprotected_headers.push((
981 original_header_name,
982 Address::new_address(None::<&'static str>, self.from_addr.clone()).into(),
983 ));
984 } else if header_name == "to" {
985 protected_headers.push(header.clone());
986 if is_encrypted {
987 let mut to_without_names = to
988 .clone()
989 .into_iter()
990 .filter_map(|header| match header {
991 Address::Address(mb) => Some(Address::Address(EmailAddress {
992 name: None,
993 email: mb.email,
994 })),
995 _ => None,
996 })
997 .collect::<Vec<_>>();
998 if to_without_names.is_empty() {
999 to_without_names.push(hidden_recipients());
1000 }
1001 unprotected_headers.push((
1002 original_header_name,
1003 Address::new_list(to_without_names).into(),
1004 ));
1005 } else {
1006 unprotected_headers.push(header.clone());
1007 }
1008 } else if is_encrypted {
1009 protected_headers.push(header.clone());
1010
1011 match header_name.as_str() {
1012 "subject" => {
1013 unprotected_headers.push((
1014 "Subject",
1015 mail_builder::headers::raw::Raw::new("[...]").into(),
1016 ));
1017 }
1018 "date"
1019 | "in-reply-to"
1020 | "references"
1021 | "auto-submitted"
1022 | "chat-version"
1023 | "autocrypt-setup-message" => {
1024 unprotected_headers.push(header.clone());
1025 }
1026 _ => {
1027 }
1029 }
1030 } else {
1031 protected_headers.push(header.clone());
1035 unprotected_headers.push(header.clone())
1036 }
1037 }
1038
1039 let outer_message = if let Some(encryption_keys) = self.encryption_keys {
1040 let message = protected_headers
1042 .into_iter()
1043 .fold(message, |message, (header, value)| {
1044 message.header(header, value)
1045 });
1046
1047 let mut message: MimePart<'static> = hidden_headers
1049 .into_iter()
1050 .fold(message, |message, (header, value)| {
1051 message.header(header, value)
1052 });
1053
1054 let multiple_recipients =
1056 encryption_keys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1057
1058 let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1059 let now = time();
1060
1061 match &self.loaded {
1062 Loaded::Message { chat, msg } => {
1063 if chat.typ != Chattype::OutBroadcast {
1064 for (addr, key) in &encryption_keys {
1065 let fingerprint = key.dc_fingerprint().hex();
1066 let cmd = msg.param.get_cmd();
1067 let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1068 || cmd == SystemMessage::SecurejoinMessage
1069 || multiple_recipients && {
1070 let gossiped_timestamp: Option<i64> = context
1071 .sql
1072 .query_get_value(
1073 "SELECT timestamp
1074 FROM gossip_timestamp
1075 WHERE chat_id=? AND fingerprint=?",
1076 (chat.id, &fingerprint),
1077 )
1078 .await?;
1079
1080 gossip_period == 0
1087 || gossiped_timestamp
1088 .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1089 };
1090
1091 if !should_do_gossip {
1092 continue;
1093 }
1094
1095 let header = Aheader::new(
1096 addr.clone(),
1097 key.clone(),
1098 EncryptPreference::NoPreference,
1101 )
1102 .to_string();
1103
1104 message = message.header(
1105 "Autocrypt-Gossip",
1106 mail_builder::headers::raw::Raw::new(header),
1107 );
1108
1109 context
1110 .sql
1111 .execute(
1112 "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1113 VALUES (?, ?, ?)
1114 ON CONFLICT (chat_id, fingerprint)
1115 DO UPDATE SET timestamp=excluded.timestamp",
1116 (chat.id, &fingerprint, now),
1117 )
1118 .await?;
1119 }
1120 }
1121 }
1122 Loaded::Mdn { .. } => {
1123 }
1125 }
1126
1127 for (h, v) in &mut message.headers {
1129 if h == "Content-Type" {
1130 if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1131 *ct = ct.clone().attribute("protected-headers", "v1");
1132 }
1133 }
1134 }
1135
1136 let compress = match &self.loaded {
1140 Loaded::Message { msg, .. } => {
1141 msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1142 }
1143 Loaded::Mdn { .. } => true,
1144 };
1145
1146 let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1149 encryption_keyring.extend(encryption_keys.iter().map(|(_addr, key)| (*key).clone()));
1150
1151 let encrypted = encrypt_helper
1155 .encrypt(context, encryption_keyring, message, compress)
1156 .await?
1157 + "\n";
1158
1159 MimePart::new(
1161 "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1162 vec![
1163 MimePart::new("application/pgp-encrypted", "Version: 1\r\n").header(
1165 "Content-Description",
1166 mail_builder::headers::raw::Raw::new("PGP/MIME version identification"),
1167 ),
1168 MimePart::new(
1170 "application/octet-stream; name=\"encrypted.asc\"",
1171 encrypted,
1172 )
1173 .header(
1174 "Content-Description",
1175 mail_builder::headers::raw::Raw::new("OpenPGP encrypted message"),
1176 )
1177 .header(
1178 "Content-Disposition",
1179 mail_builder::headers::raw::Raw::new("inline; filename=\"encrypted.asc\";"),
1180 ),
1181 ],
1182 )
1183 } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1184 message
1193 } else {
1194 let message = hidden_headers
1195 .into_iter()
1196 .fold(message, |message, (header, value)| {
1197 message.header(header, value)
1198 });
1199 let message = MimePart::new("multipart/mixed", vec![message]);
1200 let mut message = protected_headers
1201 .iter()
1202 .fold(message, |message, (header, value)| {
1203 message.header(*header, value.clone())
1204 });
1205
1206 if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
1207 let protected: HashSet<&str> =
1209 HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1210 unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1211
1212 message
1213 } else {
1214 for (h, v) in &mut message.headers {
1215 if h == "Content-Type" {
1216 if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1217 *ct = ct.clone().attribute("protected-headers", "v1");
1218 }
1219 }
1220 }
1221
1222 let signature = encrypt_helper.sign(context, &message).await?;
1223 MimePart::new(
1224 "multipart/signed; protocol=\"application/pgp-signature\"; protected",
1225 vec![
1226 message,
1227 MimePart::new(
1228 "application/pgp-signature; name=\"signature.asc\"",
1229 signature,
1230 )
1231 .header(
1232 "Content-Description",
1233 mail_builder::headers::raw::Raw::<'static>::new(
1234 "OpenPGP digital signature",
1235 ),
1236 )
1237 .attachment("signature"),
1238 ],
1239 )
1240 }
1241 };
1242
1243 let outer_message = unprotected_headers
1245 .into_iter()
1246 .fold(outer_message, |message, (header, value)| {
1247 message.header(header, value)
1248 });
1249
1250 let MimeFactory {
1251 last_added_location_id,
1252 ..
1253 } = self;
1254
1255 let mut buffer = Vec::new();
1256 let cursor = Cursor::new(&mut buffer);
1257 outer_message.clone().write_part(cursor).ok();
1258 let message = String::from_utf8_lossy(&buffer).to_string();
1259
1260 Ok(RenderedEmail {
1261 message,
1262 is_encrypted,
1264 last_added_location_id,
1265 sync_ids_to_delete: self.sync_ids_to_delete,
1266 rfc724_mid,
1267 subject: subject_str,
1268 })
1269 }
1270
1271 fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1273 let Loaded::Message { msg, .. } = &self.loaded else {
1274 return None;
1275 };
1276
1277 let latitude = msg.param.get_float(Param::SetLatitude)?;
1278 let longitude = msg.param.get_float(Param::SetLongitude)?;
1279
1280 let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1281 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1282 .attachment("message.kml");
1283 Some(part)
1284 }
1285
1286 async fn get_location_kml_part(
1288 &mut self,
1289 context: &Context,
1290 ) -> Result<Option<MimePart<'static>>> {
1291 let Loaded::Message { msg, .. } = &self.loaded else {
1292 return Ok(None);
1293 };
1294
1295 let Some((kml_content, last_added_location_id)) =
1296 location::get_kml(context, msg.chat_id).await?
1297 else {
1298 return Ok(None);
1299 };
1300
1301 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1302 .attachment("location.kml");
1303 if !msg.param.exists(Param::SetLatitude) {
1304 self.last_added_location_id = Some(last_added_location_id);
1306 }
1307 Ok(Some(part))
1308 }
1309
1310 async fn render_message(
1311 &mut self,
1312 context: &Context,
1313 headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1314 grpimage: &Option<String>,
1315 is_encrypted: bool,
1316 ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1317 let Loaded::Message { chat, msg } = &self.loaded else {
1318 bail!("Attempt to render MDN as a message");
1319 };
1320 let chat = chat.clone();
1321 let msg = msg.clone();
1322 let command = msg.param.get_cmd();
1323 let mut placeholdertext = None;
1324
1325 let send_verified_headers = match chat.typ {
1326 Chattype::Single => true,
1327 Chattype::Group => true,
1328 Chattype::Mailinglist => false,
1330 Chattype::OutBroadcast | Chattype::InBroadcast => false,
1331 };
1332 if chat.is_protected() && send_verified_headers {
1333 headers.push((
1334 "Chat-Verified",
1335 mail_builder::headers::raw::Raw::new("1").into(),
1336 ));
1337 }
1338
1339 if chat.typ == Chattype::Group {
1340 if !chat.grpid.is_empty() {
1342 headers.push((
1343 "Chat-Group-ID",
1344 mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1345 ));
1346 }
1347 }
1348
1349 if chat.typ == Chattype::Group
1350 || chat.typ == Chattype::OutBroadcast
1351 || chat.typ == Chattype::InBroadcast
1352 {
1353 headers.push((
1354 "Chat-Group-Name",
1355 mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1356 ));
1357 if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1358 headers.push((
1359 "Chat-Group-Name-Timestamp",
1360 mail_builder::headers::text::Text::new(ts.to_string()).into(),
1361 ));
1362 }
1363
1364 match command {
1365 SystemMessage::MemberRemovedFromGroup => {
1366 ensure!(chat.typ != Chattype::OutBroadcast);
1367 let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1368
1369 if email_to_remove
1370 == context
1371 .get_config(Config::ConfiguredAddr)
1372 .await?
1373 .unwrap_or_default()
1374 {
1375 placeholdertext = Some(stock_str::msg_group_left_remote(context).await);
1376 } else {
1377 placeholdertext =
1378 Some(stock_str::msg_del_member_remote(context, email_to_remove).await);
1379 };
1380
1381 if !email_to_remove.is_empty() {
1382 headers.push((
1383 "Chat-Group-Member-Removed",
1384 mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1385 .into(),
1386 ));
1387 }
1388 }
1389 SystemMessage::MemberAddedToGroup => {
1390 ensure!(chat.typ != Chattype::OutBroadcast);
1391 let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1394 placeholdertext =
1395 Some(stock_str::msg_add_member_remote(context, email_to_add).await);
1396
1397 if !email_to_add.is_empty() {
1398 headers.push((
1399 "Chat-Group-Member-Added",
1400 mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1401 ));
1402 }
1403 if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1404 info!(
1405 context,
1406 "Sending secure-join message {:?}.", "vg-member-added",
1407 );
1408 headers.push((
1409 "Secure-Join",
1410 mail_builder::headers::raw::Raw::new("vg-member-added".to_string())
1411 .into(),
1412 ));
1413 }
1414 }
1415 SystemMessage::GroupNameChanged => {
1416 let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1417 headers.push((
1418 "Chat-Group-Name-Changed",
1419 mail_builder::headers::text::Text::new(old_name).into(),
1420 ));
1421 }
1422 SystemMessage::GroupImageChanged => {
1423 headers.push((
1424 "Chat-Content",
1425 mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1426 ));
1427 if grpimage.is_none() {
1428 headers.push((
1429 "Chat-Group-Avatar",
1430 mail_builder::headers::raw::Raw::new("0").into(),
1431 ));
1432 }
1433 }
1434 _ => {}
1435 }
1436 }
1437
1438 match command {
1439 SystemMessage::LocationStreamingEnabled => {
1440 headers.push((
1441 "Chat-Content",
1442 mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1443 ));
1444 }
1445 SystemMessage::EphemeralTimerChanged => {
1446 headers.push((
1447 "Chat-Content",
1448 mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1449 ));
1450 }
1451 SystemMessage::LocationOnly
1452 | SystemMessage::MultiDeviceSync
1453 | SystemMessage::WebxdcStatusUpdate => {
1454 headers.push((
1463 "Auto-Submitted",
1464 mail_builder::headers::raw::Raw::new("auto-generated").into(),
1465 ));
1466 }
1467 SystemMessage::AutocryptSetupMessage => {
1468 headers.push((
1469 "Autocrypt-Setup-Message",
1470 mail_builder::headers::raw::Raw::new("v1").into(),
1471 ));
1472
1473 placeholdertext = Some(ASM_SUBJECT.to_string());
1474 }
1475 SystemMessage::SecurejoinMessage => {
1476 let step = msg.param.get(Param::Arg).unwrap_or_default();
1477 if !step.is_empty() {
1478 info!(context, "Sending secure-join message {step:?}.");
1479 headers.push((
1480 "Secure-Join",
1481 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1482 ));
1483
1484 let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1485 if !param2.is_empty() {
1486 headers.push((
1487 if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1488 "Secure-Join-Auth"
1489 } else {
1490 "Secure-Join-Invitenumber"
1491 },
1492 mail_builder::headers::text::Text::new(param2.to_string()).into(),
1493 ));
1494 }
1495
1496 let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1497 if !fingerprint.is_empty() {
1498 headers.push((
1499 "Secure-Join-Fingerprint",
1500 mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1501 ));
1502 }
1503 if let Some(id) = msg.param.get(Param::Arg4) {
1504 headers.push((
1505 "Secure-Join-Group",
1506 mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1507 ));
1508 };
1509 }
1510 }
1511 SystemMessage::ChatProtectionEnabled => {
1512 headers.push((
1513 "Chat-Content",
1514 mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1515 ));
1516 }
1517 SystemMessage::ChatProtectionDisabled => {
1518 headers.push((
1519 "Chat-Content",
1520 mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1521 ));
1522 }
1523 SystemMessage::IrohNodeAddr => {
1524 headers.push((
1525 HeaderDef::IrohNodeAddr.into(),
1526 mail_builder::headers::text::Text::new(serde_json::to_string(
1527 &context
1528 .get_or_try_init_peer_channel()
1529 .await?
1530 .get_node_addr()
1531 .await?,
1532 )?)
1533 .into(),
1534 ));
1535 }
1536 _ => {}
1537 }
1538
1539 if let Some(grpimage) = grpimage {
1540 info!(context, "setting group image '{}'", grpimage);
1541 let avatar = build_avatar_file(context, grpimage)
1542 .await
1543 .context("Cannot attach group image")?;
1544 headers.push((
1545 "Chat-Group-Avatar",
1546 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1547 ));
1548 }
1549
1550 if msg.viewtype == Viewtype::Sticker {
1551 headers.push((
1552 "Chat-Content",
1553 mail_builder::headers::raw::Raw::new("sticker").into(),
1554 ));
1555 } else if msg.viewtype == Viewtype::VideochatInvitation {
1556 headers.push((
1557 "Chat-Content",
1558 mail_builder::headers::raw::Raw::new("videochat-invitation").into(),
1559 ));
1560 headers.push((
1561 "Chat-Webrtc-Room",
1562 mail_builder::headers::raw::Raw::new(
1563 msg.param
1564 .get(Param::WebrtcRoom)
1565 .unwrap_or_default()
1566 .to_string(),
1567 )
1568 .into(),
1569 ));
1570 }
1571
1572 if msg.viewtype == Viewtype::Voice
1573 || msg.viewtype == Viewtype::Audio
1574 || msg.viewtype == Viewtype::Video
1575 {
1576 if msg.viewtype == Viewtype::Voice {
1577 headers.push((
1578 "Chat-Voice-Message",
1579 mail_builder::headers::raw::Raw::new("1").into(),
1580 ));
1581 }
1582 let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1583 if duration_ms > 0 {
1584 let dur = duration_ms.to_string();
1585 headers.push((
1586 "Chat-Duration",
1587 mail_builder::headers::raw::Raw::new(dur).into(),
1588 ));
1589 }
1590 }
1591
1592 let afwd_email = msg.param.exists(Param::Forwarded);
1598 let fwdhint = if afwd_email {
1599 Some(
1600 "---------- Forwarded message ----------\r\n\
1601 From: Delta Chat\r\n\
1602 \r\n"
1603 .to_string(),
1604 )
1605 } else {
1606 None
1607 };
1608
1609 let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1610
1611 let mut quoted_text = None;
1612 if let Some(msg_quoted_text) = msg.quoted_text() {
1613 let mut some_quoted_text = String::new();
1614 for quoted_line in msg_quoted_text.split('\n') {
1615 some_quoted_text += "> ";
1616 some_quoted_text += quoted_line;
1617 some_quoted_text += "\r\n";
1618 }
1619 some_quoted_text += "\r\n";
1620 quoted_text = Some(some_quoted_text)
1621 }
1622
1623 if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1624 quoted_text = Some("> ...\r\n\r\n".to_string());
1626 }
1627 if quoted_text.is_none() && final_text.starts_with('>') {
1628 quoted_text = Some("\r\n".to_string());
1631 }
1632
1633 let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1634
1635 let footer = if is_reaction { "" } else { &self.selfstatus };
1636
1637 let message_text = format!(
1638 "{}{}{}{}{}{}",
1639 fwdhint.unwrap_or_default(),
1640 quoted_text.unwrap_or_default(),
1641 escape_message_footer_marks(final_text),
1642 if !final_text.is_empty() && !footer.is_empty() {
1643 "\r\n\r\n"
1644 } else {
1645 ""
1646 },
1647 if !footer.is_empty() { "-- \r\n" } else { "" },
1648 footer
1649 );
1650
1651 let mut main_part = MimePart::new("text/plain", message_text);
1652 if is_reaction {
1653 main_part = main_part.header(
1654 "Content-Disposition",
1655 mail_builder::headers::raw::Raw::new("reaction"),
1656 );
1657 }
1658
1659 let mut parts = Vec::new();
1660
1661 if msg.has_html() {
1664 let html = if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded) {
1665 MsgId::new(orig_msg_id.try_into()?)
1666 .get_html(context)
1667 .await?
1668 } else {
1669 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1670 };
1671 if let Some(html) = html {
1672 main_part = MimePart::new(
1673 "multipart/alternative",
1674 vec![main_part, MimePart::new("text/html", html)],
1675 )
1676 }
1677 }
1678
1679 if msg.viewtype.has_file() {
1681 let file_part = build_body_file(context, &msg).await?;
1682 parts.push(file_part);
1683 }
1684
1685 if let Some(msg_kml_part) = self.get_message_kml_part() {
1686 parts.push(msg_kml_part);
1687 }
1688
1689 if location::is_sending_locations_to_chat(context, Some(msg.chat_id)).await? {
1690 if let Some(part) = self.get_location_kml_part(context).await? {
1691 parts.push(part);
1692 }
1693 }
1694
1695 if command == SystemMessage::MultiDeviceSync {
1698 let json = msg.param.get(Param::Arg).unwrap_or_default();
1699 let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1700 parts.push(context.build_sync_part(json.to_string()));
1701 self.sync_ids_to_delete = Some(ids.to_string());
1702 } else if command == SystemMessage::WebxdcStatusUpdate {
1703 let json = msg.param.get(Param::Arg).unwrap_or_default();
1704 parts.push(context.build_status_update_part(json));
1705 } else if msg.viewtype == Viewtype::Webxdc {
1706 let topic = self
1707 .webxdc_topic
1708 .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1709 .unwrap_or(create_iroh_header(context, msg.id).await?);
1710 headers.push((
1711 HeaderDef::IrohGossipTopic.get_headername(),
1712 mail_builder::headers::raw::Raw::new(topic).into(),
1713 ));
1714 if let (Some(json), _) = context
1715 .render_webxdc_status_update_object(
1716 msg.id,
1717 StatusUpdateSerial::MIN,
1718 StatusUpdateSerial::MAX,
1719 None,
1720 )
1721 .await?
1722 {
1723 parts.push(context.build_status_update_part(&json));
1724 }
1725 }
1726
1727 if self.attach_selfavatar {
1728 match context.get_config(Config::Selfavatar).await? {
1729 Some(path) => match build_avatar_file(context, &path).await {
1730 Ok(avatar) => headers.push((
1731 "Chat-User-Avatar",
1732 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1733 )),
1734 Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1735 },
1736 None => headers.push((
1737 "Chat-User-Avatar",
1738 mail_builder::headers::raw::Raw::new("0").into(),
1739 )),
1740 }
1741 }
1742
1743 Ok((main_part, parts))
1744 }
1745
1746 fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1748 let Loaded::Mdn {
1751 rfc724_mid,
1752 additional_msg_ids,
1753 } = &self.loaded
1754 else {
1755 bail!("Attempt to render a message as MDN");
1756 };
1757
1758 let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1762
1763 let mut message = MimePart::new(
1764 "multipart/report; report-type=disposition-notification",
1765 vec![text_part],
1766 );
1767
1768 let message_text2 = format!(
1770 "Original-Recipient: rfc822;{}\r\n\
1771 Final-Recipient: rfc822;{}\r\n\
1772 Original-Message-ID: <{}>\r\n\
1773 Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1774 self.from_addr, self.from_addr, rfc724_mid
1775 );
1776
1777 let extension_fields = if additional_msg_ids.is_empty() {
1778 "".to_string()
1779 } else {
1780 "Additional-Message-IDs: ".to_string()
1781 + &additional_msg_ids
1782 .iter()
1783 .map(|mid| render_rfc724_mid(mid))
1784 .collect::<Vec<String>>()
1785 .join(" ")
1786 + "\r\n"
1787 };
1788
1789 message.add_part(MimePart::new(
1790 "message/disposition-notification",
1791 message_text2 + &extension_fields,
1792 ));
1793
1794 Ok(message)
1795 }
1796}
1797
1798fn hidden_recipients() -> Address<'static> {
1799 Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
1800}
1801
1802async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
1803 let file_name = msg.get_filename().context("msg has no file")?;
1804 let blob = msg
1805 .param
1806 .get_file_blob(context)?
1807 .context("msg has no file")?;
1808 let mimetype = msg
1809 .param
1810 .get(Param::MimeType)
1811 .unwrap_or("application/octet-stream")
1812 .to_string();
1813 let body = fs::read(blob.to_abs_path()).await?;
1814
1815 let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
1821
1822 Ok(mail)
1823}
1824
1825async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
1826 let blob = match path.starts_with("$BLOBDIR/") {
1827 true => BlobObject::from_name(context, path)?,
1828 false => BlobObject::from_path(context, path.as_ref())?,
1829 };
1830 let body = fs::read(blob.to_abs_path()).await?;
1831 let encoded_body = base64::engine::general_purpose::STANDARD
1832 .encode(&body)
1833 .chars()
1834 .enumerate()
1835 .fold(String::new(), |mut res, (i, c)| {
1836 if i % 78 == 77 {
1837 res.push(' ')
1838 }
1839 res.push(c);
1840 res
1841 });
1842 Ok(encoded_body)
1843}
1844
1845fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
1846 let addr_lc = addr.to_lowercase();
1847 recipients
1848 .iter()
1849 .any(|(_, cur)| cur.to_lowercase() == addr_lc)
1850}
1851
1852fn render_rfc724_mid(rfc724_mid: &str) -> String {
1853 let rfc724_mid = rfc724_mid.trim().to_string();
1854
1855 if rfc724_mid.chars().next().unwrap_or_default() == '<' {
1856 rfc724_mid
1857 } else {
1858 format!("<{rfc724_mid}>")
1859 }
1860}
1861
1862#[cfg(test)]
1863mod mimefactory_tests;