[core] V0.1: parse, compose, reply/forward, safe names, threading, rules + Sieve, sanitiser, search (55 tests green)
This commit is contained in:
+129
-3
@@ -1,6 +1,7 @@
|
||||
//! Parsing a raw RFC 5322 message (mail-parser) into what the app stores and shows.
|
||||
|
||||
use crate::Address;
|
||||
use crate::{Address, safe_filename};
|
||||
use mail_parser::{MessageParser, MessagePart, PartKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Larger messages are refused before parsing (Proton's own limit is 25 MB of attachments).
|
||||
@@ -81,7 +82,132 @@ impl std::fmt::Display for ParseError {
|
||||
|
||||
impl std::error::Error for ParseError {}
|
||||
|
||||
/// At most this many Message-IDs are kept from In-Reply-To and References.
|
||||
pub const MAX_REFERENCES: usize = 100;
|
||||
|
||||
pub fn parse(raw: &[u8]) -> Result<Parsed, ParseError> {
|
||||
let _ = raw;
|
||||
todo!()
|
||||
if raw.len() > MAX_MESSAGE_BYTES {
|
||||
return Err(ParseError::TooLarge);
|
||||
}
|
||||
if raw.iter().all(u8::is_ascii_whitespace) {
|
||||
return Err(ParseError::NotMail);
|
||||
}
|
||||
let message = MessageParser::new().parse(raw).ok_or(ParseError::NotMail)?;
|
||||
|
||||
let subject: String =
|
||||
message.subject().unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_SUBJECT_CHARS).collect();
|
||||
|
||||
let text = join_bodies(message.text_body().filter_map(|part| part.text()));
|
||||
// mail-parser converts a text-only message to HTML; the app renders text itself, so keep real HTML only.
|
||||
let html = join_bodies(
|
||||
message.html_body().filter(|part| matches!(part.kind(), PartKind::Html)).filter_map(|part| part.text()),
|
||||
);
|
||||
|
||||
let mut attachments = Vec::new();
|
||||
let mut dropped_attachments = 0;
|
||||
for part in message.attachments() {
|
||||
if attachments.len() >= MAX_ATTACHMENTS {
|
||||
dropped_attachments += 1;
|
||||
continue;
|
||||
}
|
||||
attachments.push(attachment(&part));
|
||||
}
|
||||
|
||||
Ok(Parsed {
|
||||
message_id: message.message_id().map(clean_id).filter(|id| !id.is_empty()),
|
||||
in_reply_to: ids(message.in_reply_to()),
|
||||
references: ids(message.references()),
|
||||
subject: subject.trim().to_string(),
|
||||
from: addresses(message.from()),
|
||||
to: addresses(message.to()),
|
||||
cc: addresses(message.cc()),
|
||||
reply_to: addresses(message.reply_to()),
|
||||
date: message.date().map(|d| d.to_timestamp()),
|
||||
date_text: message.date().map(|d| d.to_rfc822()),
|
||||
text,
|
||||
html,
|
||||
attachments,
|
||||
dropped_attachments,
|
||||
})
|
||||
}
|
||||
|
||||
fn join_bodies<'a>(parts: impl Iterator<Item = std::borrow::Cow<'a, str>>) -> Option<String> {
|
||||
let mut out = String::new();
|
||||
for part in parts {
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&part);
|
||||
}
|
||||
if out.is_empty() { None } else { Some(normalize_newlines(&out)) }
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_newlines(s: &str) -> String {
|
||||
s.replace("\r\n", "\n").replace('\r', "\n")
|
||||
}
|
||||
|
||||
fn clean_id(id: &str) -> String {
|
||||
id.trim().trim_start_matches('<').trim_end_matches('>').trim().chars().take(998).collect()
|
||||
}
|
||||
|
||||
fn ids(list: Option<mail_parser::TextList<'_>>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for id in list.iter().flat_map(|l| l.iter()) {
|
||||
let id = clean_id(id);
|
||||
if !id.is_empty() && !out.contains(&id) && out.len() < MAX_REFERENCES {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn addresses(list: Option<mail_parser::AddressList<'_>>) -> Vec<Address> {
|
||||
list.iter()
|
||||
.flat_map(|l| l.mailboxes())
|
||||
.filter_map(|m| {
|
||||
let email = m.address()?.trim();
|
||||
if email.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let name = m.name().map(|n| n.chars().filter(|c| !c.is_control()).collect::<String>());
|
||||
Some(Address::new(name.as_deref(), email))
|
||||
})
|
||||
.take(MAX_ADDRESSES)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn attachment(part: &MessagePart<'_>) -> Attachment {
|
||||
let content_type = part
|
||||
.content_type()
|
||||
.map(|ct| match ct.subtype() {
|
||||
Some(sub) => format!("{}/{}", ct.ctype(), sub),
|
||||
None => ct.ctype().to_string(),
|
||||
})
|
||||
.map(|ct| ct.to_ascii_lowercase())
|
||||
.filter(|ct| ct.len() <= 127 && ct.chars().all(|c| c.is_ascii_graphic()))
|
||||
.unwrap_or_else(|| "application/octet-stream".to_string());
|
||||
|
||||
let content_id = part.content_id().map(clean_id).filter(|id| !id.is_empty());
|
||||
let declared_attachment = part.content_disposition().is_some_and(|d| d.is_attachment());
|
||||
let inline = content_id.is_some() && !declared_attachment;
|
||||
|
||||
let (name, data) = match part.kind() {
|
||||
PartKind::Message(nested) => {
|
||||
let name = part
|
||||
.attachment_name()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("{}.eml", nested.subject().unwrap_or("message")));
|
||||
let name = if name.to_ascii_lowercase().ends_with(".eml") { name } else { format!("{name}.eml") };
|
||||
(name, part.decoded().into_owned())
|
||||
}
|
||||
_ => {
|
||||
let name = part.attachment_name().map(str::to_owned).unwrap_or_else(|| {
|
||||
let ext = content_type.rsplit('/').next().unwrap_or("bin");
|
||||
format!("attachment.{ext}")
|
||||
});
|
||||
(name, part.decoded().into_owned())
|
||||
}
|
||||
};
|
||||
|
||||
Attachment { filename: safe_filename(&name), content_type, content_id, inline, data }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user