//! A mail's designed page and its attachments, brought when he opens the mail on a phone (MAIL.md "All mail on the//! phone": "Attachments and the designed page are fetched when he opens a message"; coordinator, Mac 9).//!//! The import keeps a mail's words and its attachments' names, never the page as the sender designed it nor the//! files. When the phone asks (`mail_page`, [`super::acts`]), the Mac fetches the message whole once (BODY.PEEK[],//! nothing marked read) and lands, sealed like every file of a sealed table (`ObjectSink::put_sealed_file`)://!//! - the HTML part as one page, its inline pictures (`cid:`) carried inside it as data, so the page needs nothing//! more from the sender to look as designed. Pictures it names on the web stay links: the phone decides whether//! to load them;//! - each attachment up to [`ATTACHMENT_MAX`], in the order the import named them (`mail_parser`'s attachments, the//! same parser), so `attachments[i]` takes its own file.use std::collections::HashMap;use base64::Engine;use mail_parser::{MessageParser, MimeHeaders};/// The largest message fetched whole.pubconst MESSAGE_MAX: u64 = 60 * 1024 * 1024;/// The largest page kept, its inline pictures inside.pubconst PAGE_MAX: usize = 10 * 1024 * 1024;/// The largest inline picture carried inside the page.pubconst INLINE_MAX: usize = 2 * 1024 * 1024;/// The largest attachment kept.pubconst ATTACHMENT_MAX: usize = 25 * 1024 * 1024;/// One attachment, by its place in the row's `attachments`.#[derive(Debug, Clone, PartialEq, Eq)]pubstructPart {pub index: usize,pub name: String,pub mime: String,/// Empty when it is over [`ATTACHMENT_MAX`] (it stays in the mailbox).pub bytes: Vec<u8>,}/// What a whole message gives.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructOpened {/// The page as designed; `None` for a mail written as plain text (its words are already the mail).pub html: Option<String>,pub attachments: Vec<Part>,}fn mime_of(part: &mail_parser::MessagePart<'_>) -> String { part.content_type() .map(|ct| match ct.subtype() {Some(sub) => format!("{}/{sub}", ct.ctype()),None => ct.ctype().to_string(), }) .unwrap_or_else(|| "application/octet-stream".to_string())}/// The message's page and attachments; `None` when it cannot be read.pubfn open(raw: &[u8]) -> Option<Opened> {let message = MessageParser::default().parse(raw)?;let designed = message.html_body.first().and_then(|&i| message.part(i)).is_some_and(|part| part.is_text_html());let html = if designed { message.body_html(0).map(|h| h.into_owned()) } else { None };let html = html.map(|html| {// Inline pictures, by Content-ID, carried in the page.letmut inline: HashMap<String, String> = HashMap::new();for part in message.parts.iter() {letSome(cid) = part.content_id() else { continue };let mime = mime_of(part);let bytes = part.contents();if !mime.starts_with("image/") || bytes.is_empty() || bytes.len() > INLINE_MAX {continue; }let cid = cid.trim().trim_start_matches('<').trim_end_matches('>').to_string(); inline.insert(cid, format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))); }letmut page = html.clone();for (cid, data) in &inline {for prefix in ["cid:", "CID:", "Cid:"] { page = page.replace(&format!("{prefix}{cid}"), data); } }if page.len() > PAGE_MAX { page = html; }if !page.to_ascii_lowercase().contains("<meta charset") { page = format!("<!doctype html><meta charset=\"utf-8\">{page}"); } page });let html = html.filter(|page| page.len() <= PAGE_MAX);let attachments = message .attachments() .enumerate() .map(|(index, part)| {let bytes = part.contents();Part { index, name: part.attachment_name().unwrap_or("attachment").to_string(), mime: mime_of(part), bytes: if bytes.len() <= ATTACHMENT_MAX { bytes.to_vec() } else { Vec::new() }, } }) .collect();Some(Opened { html, attachments })}#[cfg(test)]mod tests {usesuper::*;const DESIGNED: &[u8] = b"From: Shop <deals@shop.invented>\r\nTo: owner@mail.invented\r\nSubject: Sale\r\nMessage-ID: <s1@shop.invented>\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"M\"\r\n\r\n--M\r\nContent-Type: multipart/related; boundary=\"R\"\r\n\r\n--R\r\nContent-Type: multipart/alternative; boundary=\"A\"\r\n\r\n--A\r\nContent-Type: text/plain\r\n\r\nSale today\r\n--A\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Sale</h1><img src=\"cid:logo@shop\"><img src=\"https://shop.invented/x.png\"></body></html>\r\n--A--\r\n--R\r\nContent-Type: image/png\r\nContent-ID: <logo@shop>\r\nContent-Transfer-Encoding: base64\r\n\r\niVBORw0KGgo=\r\n--R--\r\n--M\r\nContent-Type: application/pdf; name=\"menu.pdf\"\r\nContent-Disposition: attachment; filename=\"menu.pdf\"\r\nContent-Transfer-Encoding: base64\r\n\r\nJVBERi0xLjQK\r\n--M--\r\n"; #[test]fn a_designed_mail_opens_as_its_page_with_pictures_inside_and_its_files() {let opened = open(DESIGNED).unwrap();let page = opened.html.unwrap(); assert!(page.contains("<h1>Sale</h1>")); assert!(page.contains("data:image/png;base64,iVBORw0KGgo="), "the inline picture travels inside: {page}"); assert!(!page.contains("cid:"), "no reference left to a part"); assert!(page.contains("https://shop.invented/x.png"), "a picture on the web stays a link for the phone to decide"); assert!(page.starts_with("<!doctype html><meta charset=\"utf-8\">"));// The parser counts the inline picture among the attachments, as the import (the same parser) named them on// the row: each keeps its place, so `attachments[1]` is the PDF on the row too.let names: Vec<&str> = opened.attachments.iter().map(|a| a.name.as_str()).collect(); assert_eq!(names, ["attachment", "menu.pdf"]); assert_eq!((opened.attachments[1].index, opened.attachments[1].mime.as_str()), (1, "application/pdf")); assert_eq!(opened.attachments[1].bytes, b"%PDF-1.4\n"); } #[test]fn a_plain_mail_has_no_page() {let plain = b"From: a@friend.invented\r\nSubject: hi\r\nContent-Type: text/plain\r\n\r\nSee you at six.\r\n";let opened = open(plain).unwrap(); assert_eq!(opened.html, None); assert!(opened.attachments.is_empty()); }}