agentmux_srv_core/backend/google/
gmail_thread.rs1use serde_json::Value;
11
12use super::gmail::{get, header, id_arg, line, url_of};
13use super::gmail_write::DraftView;
14use super::{clip, GoogleRequest};
15
16pub const NO_PARTICIPANT: &str = "None of these recipients has taken part in that thread.";
18const UNCHECKED: &str = "This draft replies into a thread, but the thread could not be read, so its recipients were not checked against it.";
19const SHOWN_PEOPLE: usize = 5;
21const KEPT_PEOPLE: usize = 500;
22
23pub fn context_plan(thread_id: &str) -> Result<GoogleRequest, String> {
25 let id = id_arg("thread_id", Some(thread_id))?;
26 let mut q = vec![("format", "metadata".to_string())];
27 for h in ["From", "To", "Cc", "Bcc", "Subject"] {
28 q.push(("metadataHeaders", h.to_string()));
29 }
30 Ok(get(url_of(&["threads", &id])?, q))
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ThreadContext {
36 pub subject: String,
37 pub messages: usize,
38 pub people: Vec<String>,
40}
41
42pub fn context_of(thread: &Value) -> ThreadContext {
44 let sent = |m: &&Value| !m.get("labelIds").and_then(Value::as_array).is_some_and(|l| l.iter().any(|x| x.as_str() == Some("DRAFT")));
47 let all: Vec<&Value> = thread.get("messages").and_then(Value::as_array).map(|a| a.iter().filter(sent).collect()).unwrap_or_default();
48 let mut people: Vec<String> = Vec::new();
49 for m in &all {
50 let p = m.get("payload").unwrap_or(&Value::Null);
51 for name in ["From", "To", "Cc", "Bcc"] {
52 for a in addresses_in(header(p, name)) {
53 if people.len() < KEPT_PEOPLE && !people.contains(&a) {
54 people.push(a);
55 }
56 }
57 }
58 }
59 let subject = all.first().map(|m| line(header(m.get("payload").unwrap_or(&Value::Null), "Subject"), 200)).unwrap_or_default();
60 ThreadContext { subject, messages: all.len(), people }
61}
62
63pub fn addresses_in(value: &str) -> Vec<String> {
67 let (mut out, mut entry) = (Vec::new(), String::new());
68 let (mut quoted, mut escaped, mut angle) = (false, false, false);
69 for c in value.chars().chain(std::iter::once(',')) {
70 match c {
71 _ if escaped => escaped = false,
72 '\\' if quoted => escaped = true,
73 '"' => quoted = !quoted,
74 '<' if !quoted => angle = true,
75 '>' if !quoted => angle = false,
76 ',' | ';' if !quoted && !angle => {
77 out.extend(entry_address(&entry));
78 entry.clear();
79 continue;
80 }
81 _ => {}
82 }
83 entry.push(c);
84 }
85 out
86}
87
88fn entry_address(entry: &str) -> Option<String> {
89 let inner = match (entry.rfind('<'), entry.rfind('>')) {
90 (Some(open), Some(close)) if open < close => &entry[open + 1..close],
91 _ => entry,
92 };
93 let a = inner.trim().trim_matches('"').to_ascii_lowercase();
94 let (local, domain) = a.split_once('@')?;
95 (!local.is_empty() && !domain.is_empty() && !domain.contains('@') && !a.chars().any(|c| c.is_whitespace() || c.is_control())).then_some(a)
96}
97
98#[derive(Debug, Clone, Default, PartialEq, Eq)]
100pub struct ThreadNote {
101 pub warning: Option<String>,
103 pub line: Option<String>,
105 pub strangers: bool,
107}
108
109impl ThreadNote {
110 pub fn of(view: &DraftView, ctx: &ThreadContext, own: &str) -> ThreadNote {
113 if ctx.messages == 0 {
116 return ThreadNote::default();
117 }
118 let recipients: Vec<String> = [&view.to, &view.cc, &view.bcc].iter().flat_map(|r| addresses_in(r)).collect();
119 let strangers = !recipients.iter().any(|r| ctx.people.contains(r));
120 let own = own.trim().to_ascii_lowercase();
121 let others: Vec<&String> = ctx.people.iter().filter(|p| **p != own).collect();
122 let who = if others.is_empty() {
123 String::new()
124 } else {
125 let shown: Vec<&str> = others.iter().take(SHOWN_PEOPLE).map(|p| p.as_str()).collect();
126 let more = if others.len() > SHOWN_PEOPLE { format!(" and {} more", others.len() - SHOWN_PEOPLE) } else { String::new() };
127 format!(", with {}{more}", shown.join(", "))
128 };
129 let subject = if ctx.subject.is_empty() { "(no subject)" } else { &ctx.subject };
130 let line = format!("Replies in the thread: {} ({} message{}{who})", clip(subject, 120), ctx.messages, if ctx.messages == 1 { "" } else { "s" });
131 ThreadNote { warning: strangers.then(|| NO_PARTICIPANT.to_string()), line: Some(line), strangers }
132 }
133
134 pub fn unchecked() -> ThreadNote {
136 ThreadNote { warning: Some(UNCHECKED.to_string()), line: None, strangers: false }
137 }
138}
139
140#[cfg(test)]
141#[path = "gmail_thread_tests.rs"]
142mod tests;