Skip to main content

macfly_core/
html.rs

1use std::sync::LazyLock;
2
3use regex::Regex;
4
5use crate::model::FidelityInfo;
6
7static BLOCK_BREAK_RE: LazyLock<Regex> = LazyLock::new(|| {
8    Regex::new(r"(?i)</?(?:div|p|br|h[1-6]|tr|section|article)\b[^>]*>").expect("block break regex")
9});
10static LI_OPEN_RE: LazyLock<Regex> =
11    LazyLock::new(|| Regex::new(r"(?i)<li\b[^>]*>").expect("li open regex"));
12static TAG_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<[^>]+>").expect("tag regex"));
13static MULTI_NL_RE: LazyLock<Regex> =
14    LazyLock::new(|| Regex::new(r"\n{3,}").expect("multi newline regex"));
15
16pub fn analyze_note_fidelity(html: &str, attachment_count: usize) -> FidelityInfo {
17    let lower = html.to_ascii_lowercase();
18    let has_attachments = attachment_count > 0 || lower.contains("<object");
19    let has_tables = lower.contains("<table");
20    let has_images = lower.contains("<img");
21    let has_internal_links = lower.contains("applenotes://");
22    let has_checklists = lower.contains("type=\"checkbox\"")
23        || lower.contains("apple-checklist")
24        || lower.contains("☐")
25        || lower.contains("☑");
26
27    let is_rich =
28        has_attachments || has_tables || has_images || has_internal_links || has_checklists;
29
30    let (safe_mutations, blocked_mutations) = if is_rich {
31        (
32            vec!["append".to_string(), "move".to_string()],
33            vec!["replace_body".to_string()],
34        )
35    } else {
36        (
37            vec![
38                "append".to_string(),
39                "move".to_string(),
40                "replace_body".to_string(),
41            ],
42            vec![],
43        )
44    };
45
46    FidelityInfo {
47        has_attachments,
48        has_tables,
49        has_checklists,
50        has_internal_links,
51        has_images,
52        safe_mutations,
53        blocked_mutations,
54    }
55}
56
57pub fn html_to_clean_text(html: &str) -> String {
58    let with_bullets = LI_OPEN_RE.replace_all(html, "\n- ");
59    let with_breaks = BLOCK_BREAK_RE.replace_all(&with_bullets, "\n");
60    let stripped = TAG_RE.replace_all(&with_breaks, "");
61    let decoded = decode_basic_entities(&stripped);
62
63    let normalized_lines: Vec<String> = decoded
64        .lines()
65        .map(|l| l.trim_end().to_string())
66        .collect();
67    let joined = normalized_lines.join("\n");
68    MULTI_NL_RE
69        .replace_all(joined.trim(), "\n\n")
70        .into_owned()
71}
72
73/// Bereinigt E-Mail-Text: entfernt überlange Zitatketten (`> ...`) und klassische Reply-Trenner,
74/// damit KI-Agenten weniger Tokens verbrauchen und fokussiert auf die aktuelle Nachricht bleiben.
75pub fn clean_mail_body(raw: &str) -> String {
76    let mut out = Vec::new();
77    let mut quote_lines_skipped = 0usize;
78
79    for line in raw.lines() {
80        let trimmed = line.trim();
81        // Klassische Zitat-Blöcke am Ende kompakter halten
82        if trimmed.starts_with('>') {
83            quote_lines_skipped += 1;
84            continue;
85        }
86        if quote_lines_skipped > 0 {
87            out.push(format!("[… {quote_lines_skipped} zitierte Zeilen ausgeblendet]"));
88            quote_lines_skipped = 0;
89        }
90        out.push(line.trim_end().to_string());
91    }
92    if quote_lines_skipped > 0 {
93        out.push(format!("[… {quote_lines_skipped} zitierte Zeilen ausgeblendet]"));
94    }
95
96    let joined = out.join("\n");
97    MULTI_NL_RE
98        .replace_all(joined.trim(), "\n\n")
99        .into_owned()
100}
101
102fn decode_basic_entities(s: &str) -> String {
103    s.replace("&nbsp;", " ")
104        .replace("&amp;", "&")
105        .replace("&lt;", "<")
106        .replace("&gt;", ">")
107        .replace("&quot;", "\"")
108        .replace("&#39;", "'")
109        .replace("&apos;", "'")
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn converts_apple_notes_html_cleanly() {
118        let html = "<div><h1>Projekt Alpha</h1></div><div><br></div><ul><li>Punkt 1</li><li>Punkt 2 &amp; mehr</li></ul>";
119        let clean = html_to_clean_text(html);
120        assert!(clean.contains("Projekt Alpha"));
121        assert!(clean.contains("- Punkt 1"));
122        assert!(clean.contains("- Punkt 2 & mehr"));
123    }
124
125    #[test]
126    fn protects_rich_notes_from_replace() {
127        let html = "<div>Text</div><table><tr><td>A</td></tr></table>";
128        let f = analyze_note_fidelity(html, 0);
129        assert!(f.has_tables);
130        assert!(f.blocked_mutations.iter().any(|m| m == "replace_body"));
131        assert!(f.safe_mutations.iter().any(|m| m == "append"));
132    }
133}