1use base64::Engine as _;
17use serde::Deserialize;
18use serde_json::{json, Map, Value};
19
20use super::gmail_sender::{raw_headers, search_check, sender_check, RAW_THREAD_CHARS};
21use super::{clip, GoogleRequest, SCOPE_PREFIX};
22
23const API: &str = "https://gmail.googleapis.com/gmail/v1/users/me";
24
25pub const READ_ACTIONS: [&str; 3] = ["search_threads", "get_thread", "list_labels"];
27
28const DEFAULT_RESULTS: u32 = 10;
29const MAX_RESULTS: u32 = 25;
30pub const SUMMARIZED: usize = 10;
32const BODY_CHARS: usize = 20_000;
34const MESSAGES: usize = 30;
35const THREAD_CHARS: usize = 120_000;
36const SNIPPET_CHARS: usize = 300;
37const ADDRESS_CHARS: usize = 300;
38const ATTACHMENTS: usize = 20;
39pub const EXTERNAL_PARTS: usize = 10;
41pub const EXTERNAL_PART_CHARS: usize = 3_000_000;
42
43#[derive(Debug, Default, Clone, Deserialize)]
45pub struct GmailArgs {
46 #[serde(default)]
48 pub query: Option<String>,
49 #[serde(default)]
51 pub label_id: Option<String>,
52 #[serde(default)]
54 pub thread_id: Option<String>,
55 #[serde(default)]
57 pub headers: Option<String>,
58 #[serde(default)]
59 pub max_results: Option<u32>,
60 #[serde(default)]
61 pub page_token: Option<String>,
62 #[serde(default)]
64 pub to: Option<Vec<String>>,
65 #[serde(default)]
66 pub cc: Option<Vec<String>>,
67 #[serde(default)]
68 pub bcc: Option<Vec<String>>,
69 #[serde(default)]
70 pub subject: Option<String>,
71 #[serde(default)]
72 pub body: Option<String>,
73 #[serde(default)]
75 pub draft_id: Option<String>,
76 #[serde(default)]
78 pub add_label_ids: Option<Vec<String>>,
79 #[serde(default)]
80 pub remove_label_ids: Option<Vec<String>>,
81}
82
83pub fn needs(_action: &str) -> &'static [&'static str] {
86 &["gmail.readonly", "gmail.modify", "gmail.metadata"]
87}
88
89const FULL_MAIL: &str = "https://mail.google.com/";
92
93pub(super) fn has_scope(granted: &[String], name: &str) -> bool {
96 granted.iter().any(|g| g == FULL_MAIL || g.strip_prefix(SCOPE_PREFIX).unwrap_or(g) == name)
97}
98
99pub fn granted_for(action: &str, granted: &[String]) -> bool {
102 match action {
103 "list_labels" => needs(action).iter().any(|n| has_scope(granted, n)),
104 _ => has_scope(granted, "gmail.readonly") || has_scope(granted, "gmail.modify"),
105 }
106}
107
108pub(super) fn id_arg(name: &str, v: Option<&str>) -> Result<String, String> {
110 let id = v.map(str::trim).unwrap_or("");
111 if id.is_empty() {
112 return Err(format!("this action needs {name}: one from search_threads"));
113 }
114 if id.len() > 64 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
115 return Err(format!("\"{}\" isn't a Gmail id", clip(id, 40)));
116 }
117 Ok(id.to_string())
118}
119
120pub(super) fn url_of(tail: &[&str]) -> Result<String, String> {
121 let mut url = url::Url::parse(API).map_err(|e| e.to_string())?;
122 url.path_segments_mut().map_err(|_| "bad Gmail API URL".to_string())?.extend(tail);
123 Ok(url.to_string())
124}
125
126pub(super) fn get(url: String, query: Vec<(&'static str, String)>) -> GoogleRequest {
127 GoogleRequest { method: reqwest::Method::GET, url, query, body: None, text: false }
128}
129
130pub fn plan(action: &str, args: &GmailArgs) -> Result<GoogleRequest, String> {
132 match action {
133 "search_threads" => {
134 let mut q = vec![("maxResults", args.max_results.unwrap_or(DEFAULT_RESULTS).clamp(1, MAX_RESULTS).to_string())];
135 if let Some(text) = args.query.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
136 q.push(("q", clip(text, 500)));
137 }
138 if let Some(l) = args.label_id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
139 q.push(("labelIds", clip(l, 100)));
140 }
141 if let Some(t) = args.page_token.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
142 q.push(("pageToken", t.to_string()));
143 }
144 Ok(get(url_of(&["threads"])?, q))
145 }
146 "get_thread" => {
147 raw_headers_arg(args)?;
148 Ok(get(url_of(&["threads", &id_arg("thread_id", args.thread_id.as_deref())?])?, vec![("format", "full".to_string())]))
149 }
150 "list_labels" => Ok(get(url_of(&["labels"])?, Vec::new())),
151 other => Err(format!("Gmail has no action \"{other}\"; one of {}", READ_ACTIONS.join(", "))),
152 }
153}
154
155pub fn raw_headers_arg(args: &GmailArgs) -> Result<bool, String> {
157 match args.headers.as_deref().map(str::trim).filter(|h| !h.is_empty()) {
158 None => Ok(false),
159 Some(h) if h.eq_ignore_ascii_case("raw") => Ok(true),
160 Some(h) => Err(format!("headers can only be \"raw\", not \"{}\"", clip(h, 20))),
161 }
162}
163
164pub fn summary_plan(thread_id: &str) -> Result<GoogleRequest, String> {
167 let id = id_arg("thread_id", Some(thread_id))?;
168 let mut q = vec![("format", "metadata".to_string())];
169 for h in ["From", "Subject", "Date", "Authentication-Results", "Reply-To"] {
170 q.push(("metadataHeaders", h.to_string()));
171 }
172 Ok(get(url_of(&["threads", &id])?, q))
173}
174
175pub(super) fn s<'a>(v: &'a Value, ptr: &str) -> &'a str {
176 v.pointer(ptr).and_then(Value::as_str).unwrap_or("")
177}
178
179pub(super) fn header<'a>(payload: &'a Value, name: &str) -> &'a str {
181 payload
182 .get("headers")
183 .and_then(Value::as_array)
184 .and_then(|h| h.iter().find(|h| s(h, "/name").eq_ignore_ascii_case(name)))
185 .map(|h| s(h, "/value"))
186 .unwrap_or("")
187}
188
189pub(super) fn line(v: &str, max: usize) -> String {
191 clip(&v.split_whitespace().collect::<Vec<_>>().join(" "), max)
192}
193
194pub fn shape_search(list: &Value, summaries: &[Value]) -> Value {
197 let threads: Vec<Value> = list
198 .get("threads")
199 .and_then(Value::as_array)
200 .map(|a| {
201 a.iter()
202 .enumerate()
203 .map(|(i, t)| {
204 let mut m = Map::new();
205 m.insert("id".into(), json!(s(t, "/id")));
206 let snippet = s(t, "/snippet");
207 if !snippet.is_empty() {
208 m.insert("snippet".into(), json!(line(snippet, SNIPPET_CHARS)));
209 }
210 if let Some(sum) = summaries.get(i).filter(|v| !v.is_null()) {
211 let msgs = sum.get("messages").and_then(Value::as_array).cloned().unwrap_or_default();
212 if let Some(first) = msgs.first() {
213 let p = first.get("payload").unwrap_or(&Value::Null);
214 m.insert("subject".into(), json!(line(header(p, "Subject"), ADDRESS_CHARS)));
215 m.insert("from".into(), json!(line(header(p, "From"), ADDRESS_CHARS)));
216 }
217 if let Some(last) = msgs.last() {
218 let p = last.get("payload").unwrap_or(&Value::Null);
219 m.insert("last_date".into(), json!(line(header(p, "Date"), 60)));
220 m.insert("sender_check".into(), search_check(p, &label_ids(last)));
221 }
222 m.insert("messages".into(), json!(msgs.len()));
223 }
224 Value::Object(m)
225 })
226 .collect()
227 })
228 .unwrap_or_default();
229 let mut out = Map::new();
230 out.insert("threads".into(), json!(threads));
231 let next = s(list, "/nextPageToken");
232 if !next.is_empty() {
233 out.insert("next_page_token".into(), json!(next));
234 }
235 Value::Object(out)
236}
237
238fn is_external_text(part: &Value) -> bool {
241 part.get("filename").and_then(Value::as_str).is_none_or(str::is_empty)
242 && matches!(s(part, "/mimeType"), "text/plain" | "text/html")
243 && s(part, "/body/data").is_empty()
244 && !s(part, "/body/attachmentId").is_empty()
245}
246
247pub fn external_text_parts(thread: &Value) -> Vec<(String, String)> {
250 fn walk(part: &Value, mid: &str, out: &mut Vec<(String, String)>) {
251 if out.len() < EXTERNAL_PARTS && is_external_text(part) {
252 out.push((mid.to_string(), s(part, "/body/attachmentId").to_string()));
253 }
254 for p in part.get("parts").and_then(Value::as_array).into_iter().flatten() {
255 walk(p, mid, out);
256 }
257 }
258 let mut out = Vec::new();
259 for m in thread.get("messages").and_then(Value::as_array).into_iter().flatten() {
260 walk(m.get("payload").unwrap_or(&Value::Null), s(m, "/id"), &mut out);
261 }
262 out
263}
264
265pub fn part_plan(message_id: &str, attachment_id: &str) -> Result<GoogleRequest, String> {
267 let m = id_arg("message id", Some(message_id))?;
268 if attachment_id.is_empty() || attachment_id.len() > 2048 || !attachment_id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
270 return Err("not an attachment id".to_string());
271 }
272 Ok(get(url_of(&["messages", &m, "attachments", attachment_id])?, Vec::new()))
273}
274
275pub fn fill_external(thread: &mut Value, parts: &std::collections::HashMap<String, String>) {
278 fn walk(part: &mut Value, parts: &std::collections::HashMap<String, String>) {
279 if is_external_text(part) {
280 if let Some(data) = parts.get(s(part, "/body/attachmentId")).cloned() {
281 part["body"]["data"] = json!(data);
282 }
283 }
284 if let Some(children) = part.get_mut("parts").and_then(Value::as_array_mut) {
285 for p in children {
286 walk(p, parts);
287 }
288 }
289 }
290 for m in thread.get_mut("messages").and_then(Value::as_array_mut).into_iter().flatten() {
291 if let Some(p) = m.get_mut("payload") {
292 walk(p, parts);
293 }
294 }
295}
296
297pub(super) fn has_unloaded_text(payload: &Value) -> bool {
300 is_external_text(payload) || payload.get("parts").and_then(Value::as_array).is_some_and(|ps| ps.iter().any(has_unloaded_text))
301}
302
303fn charset_of(part: &Value) -> Option<String> {
305 let ct = header(part, "Content-Type").to_ascii_lowercase();
306 let after = ct.split("charset=").nth(1)?;
307 let name = after.split(';').next()?.trim().trim_matches('"').trim_matches('\'');
308 (!name.is_empty()).then(|| name.to_string())
309}
310
311fn decode(data: &str, charset: Option<&str>) -> String {
314 let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(data.trim_end_matches('=')) else {
315 return String::new();
316 };
317 let enc = charset.and_then(|c| encoding_rs::Encoding::for_label(c.as_bytes())).unwrap_or(encoding_rs::UTF_8);
318 enc.decode(&bytes).0.into_owned()
319}
320
321fn html_text(html: &str) -> String {
326 let lower = html.to_ascii_lowercase();
327 let mut out = String::with_capacity(html.len() / 2);
328 let mut at = 0;
329 while let Some(rel) = html[at..].find('<') {
330 let open = at + rel;
331 out.push_str(&html[at..open]);
332 let tag = &lower[open + 1..];
333 if let Some(name) = ["script", "style"].into_iter().find(|n| tag.starts_with(n)) {
334 let Some(end) = lower[open..].find(&format!("</{name}")) else {
335 return finish_text(out);
336 };
337 let closing = open + end;
338 at = html[closing..].find('>').map_or(html.len(), |i| closing + i + 1);
339 continue;
340 }
341 let block = ["br", "p", "/p", "div", "/div", "li", "tr"].iter().any(|t| tag.starts_with(t));
342 if block {
343 out.push('\n');
344 }
345 at = html[open..].find('>').map_or(html.len(), |i| open + i + 1);
346 }
347 out.push_str(&html[at..]);
348 finish_text(out)
349}
350
351fn finish_text(text: String) -> String {
352 text.replace(" ", " ").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")
353}
354
355pub(super) fn text_of_mime(payload: &Value, mime: &str) -> Vec<String> {
357 fn collect(part: &Value, mime: &str, out: &mut Vec<String>) {
358 if part.get("filename").and_then(Value::as_str).is_some_and(|f| !f.is_empty()) {
359 return;
360 }
361 if s(part, "/mimeType") == mime {
362 let data = s(part, "/body/data");
363 if !data.is_empty() {
364 out.push(decode(data, charset_of(part).as_deref()));
365 }
366 }
367 if let Some(parts) = part.get("parts").and_then(Value::as_array) {
368 for p in parts {
369 collect(p, mime, out);
370 }
371 }
372 }
373 let mut out = Vec::new();
374 collect(payload, mime, &mut out);
375 out
376}
377
378pub(super) fn body_text(payload: &Value) -> String {
380 let plain = text_of_mime(payload, "text/plain");
381 if !plain.is_empty() {
382 return plain.join("\n");
383 }
384 html_alternative(payload)
385}
386
387pub(super) fn html_alternative(payload: &Value) -> String {
389 html_text(&text_of_mime(payload, "text/html").join("\n"))
390}
391
392pub(super) fn tidy(text: &str) -> String {
394 let mut out = String::new();
395 let mut blank = 0;
396 for l in text.replace('\r', "").lines() {
397 if l.trim().is_empty() {
398 blank += 1;
399 if blank > 1 {
400 continue;
401 }
402 } else {
403 blank = 0;
404 }
405 out.push_str(l.trim_end());
406 out.push('\n');
407 }
408 out.trim().to_string()
409}
410
411pub(super) fn attachments(payload: &Value) -> Vec<Value> {
413 fn walk(part: &Value, out: &mut Vec<Value>) {
414 let name = s(part, "/filename");
415 if !name.is_empty() && out.len() < ATTACHMENTS {
416 out.push(json!({ "filename": line(name, 200), "mime_type": s(part, "/mimeType"), "size": part.pointer("/body/size").and_then(Value::as_u64).unwrap_or(0) }));
417 }
418 if let Some(parts) = part.get("parts").and_then(Value::as_array) {
419 for p in parts {
420 walk(p, out);
421 }
422 }
423 }
424 let mut out = Vec::new();
425 walk(payload, &mut out);
426 out
427}
428
429fn label_ids(m: &Value) -> Vec<&str> {
431 m.get("labelIds").and_then(Value::as_array).map(|l| l.iter().filter_map(Value::as_str).collect()).unwrap_or_default()
432}
433
434fn shape_message(m: &Value, budget: &mut usize, raw: Option<&mut usize>) -> Value {
436 let p = m.get("payload").unwrap_or(&Value::Null);
437 let mut out = Map::new();
438 out.insert("id".into(), json!(s(m, "/id")));
439 for (h, k) in [("From", "from"), ("To", "to"), ("Cc", "cc"), ("Subject", "subject"), ("Date", "date")] {
440 let v = header(p, h);
441 if !v.is_empty() {
442 out.insert(k.into(), json!(line(v, ADDRESS_CHARS)));
443 }
444 }
445 if let Some(l) = m.get("labelIds").and_then(Value::as_array) {
446 out.insert("labels".into(), json!(l.iter().filter_map(Value::as_str).collect::<Vec<_>>()));
447 }
448 out.insert("sender_check".into(), sender_check(p, &label_ids(m)));
449 if let Some(raw_budget) = raw {
450 out.insert("raw_headers".into(), raw_headers(p, raw_budget));
451 }
452 let text = tidy(&body_text(p));
453 let room = BODY_CHARS.min(*budget);
454 let shown = clip(&text, room);
455 *budget = budget.saturating_sub(shown.chars().count());
456 if text.chars().count() > room {
458 out.insert("body_cut".into(), json!(true));
459 }
460 out.insert("body".into(), json!(shown));
461 let files = attachments(p);
462 if !files.is_empty() {
463 out.insert("attachments".into(), json!(files));
464 }
465 if has_unloaded_text(p) {
466 out.insert("body_note".into(), json!("part of this mail's text is stored outside the message and was not loaded (too large, or Google did not return it)"));
467 }
468 Value::Object(out)
469}
470
471pub fn shape_thread(body: &Value, raw: bool) -> Value {
474 let mut out = Map::new();
475 let all = body.get("messages").and_then(Value::as_array).cloned().unwrap_or_default();
476 let (mut budget, mut raw_budget) = (THREAD_CHARS, RAW_THREAD_CHARS);
477 let shown: Vec<Value> = all.iter().take(MESSAGES).map(|m| shape_message(m, &mut budget, raw.then_some(&mut raw_budget))).collect();
478 out.insert("id".into(), json!(s(body, "/id")));
479 out.insert("messages".into(), json!(shown));
480 let drafts = all.iter().filter(|m| label_ids(m).contains(&"DRAFT")).count();
482 if drafts > 0 {
483 out.insert("unsent_drafts".into(), json!(drafts));
484 }
485 if all.len() > MESSAGES {
486 out.insert("messages_not_shown".into(), json!(all.len() - MESSAGES));
487 }
488 Value::Object(out)
489}
490
491pub fn shape(action: &str, body: &Value) -> Value {
493 let mut out = Map::new();
494 match action {
495 "search_threads" => return shape_search(body, &[]),
496 "get_thread" => return shape_thread(body, false),
497 "list_labels" => {
498 let labels: Vec<Value> = body
499 .get("labels")
500 .and_then(Value::as_array)
501 .map(|a| a.iter().map(|l| json!({ "id": s(l, "/id"), "name": line(s(l, "/name"), 200), "type": s(l, "/type") })).collect())
502 .unwrap_or_default();
503 out.insert("labels".into(), json!(labels));
504 }
505 _ => {}
506 }
507 Value::Object(out)
508}
509
510pub fn logged_ids(action: &str, args: &GmailArgs) -> String {
512 match action {
513 "get_thread" => args.thread_id.as_deref().map(str::trim).unwrap_or("").to_string(),
514 _ => String::new(),
515 }
516}
517
518#[cfg(test)]
519#[path = "gmail_tests.rs"]
520mod tests;