agentmux_srv_core/backend/google/
mod.rs1use std::future::Future;
14
15use serde_json::Value;
16
17use crate::backend::storage::google_grants::GrantLevel;
18use crate::identity::oauth_tokens::HttpReply;
19
20pub mod access;
21pub mod calendar;
22pub mod calls;
23pub mod drive;
24pub mod gmail;
25pub mod gmail_flow;
26pub mod gmail_sender;
27pub mod gmail_thread;
28pub mod gmail_write;
29
30const SCOPE_PREFIX: &str = "https://www.googleapis.com/auth/";
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Service {
35 Calendar,
36 Drive,
37 Gmail,
38}
39
40impl Service {
41 pub fn as_str(self) -> &'static str {
42 match self {
43 Service::Calendar => "calendar",
44 Service::Drive => "drive",
45 Service::Gmail => "gmail",
46 }
47 }
48
49 pub fn scopes(self, level: GrantLevel) -> Vec<String> {
51 let names: &[&str] = match (self, level) {
52 (Service::Calendar, GrantLevel::Read) => {
53 &["calendar.calendarlist.readonly", "calendar.events.readonly", "calendar.events.freebusy"]
54 }
55 (Service::Calendar, GrantLevel::Write) => &[
56 "calendar.calendarlist.readonly",
57 "calendar.events.readonly",
58 "calendar.events.freebusy",
59 "calendar.events",
60 ],
61 (Service::Drive, _) => &["drive.file"],
64 (Service::Gmail, GrantLevel::Read) => &["gmail.readonly"],
67 (Service::Gmail, GrantLevel::Write) => &["gmail.readonly", "gmail.compose", "gmail.modify"],
70 };
71 names.iter().map(|n| format!("{SCOPE_PREFIX}{n}")).collect()
72 }
73}
74
75#[derive(Debug, Clone, PartialEq)]
77pub struct GoogleRequest {
78 pub method: reqwest::Method,
79 pub url: String,
80 pub query: Vec<(&'static str, String)>,
81 pub body: Option<Value>,
82 pub text: bool,
85}
86
87pub const TEXT_CAP: usize = 200_000;
89
90pub trait GoogleHttp: Sync {
92 fn send(&self, req: &GoogleRequest, token: &str) -> impl Future<Output = Result<HttpReply, String>> + Send;
93}
94
95pub struct LiveGoogleHttp;
97
98impl GoogleHttp for LiveGoogleHttp {
99 async fn send(&self, req: &GoogleRequest, token: &str) -> Result<HttpReply, String> {
100 let mut b = crate::identity::oauth_client::http()
101 .request(req.method.clone(), &req.url)
102 .bearer_auth(token)
103 .header("Accept", if req.text { "*/*" } else { "application/json" })
104 .query(&req.query);
105 if let Some(body) = &req.body {
106 b = b.json(body);
107 }
108 let mut resp = b.send().await.map_err(|e| format!("request failed: {}", e.without_url()))?;
109 let status = resp.status().as_u16();
110 if req.text && (200..300).contains(&status) {
111 let mut buf: Vec<u8> = Vec::new();
112 let mut truncated = false;
113 while let Some(chunk) = resp.chunk().await.map_err(|e| format!("request failed: {}", e.without_url()))? {
114 let room = TEXT_CAP - buf.len();
115 if chunk.len() > room {
116 buf.extend_from_slice(&chunk[..room]);
117 truncated = true;
118 break;
119 }
120 buf.extend_from_slice(&chunk);
121 }
122 let text = String::from_utf8_lossy(&buf).into_owned();
123 return Ok(HttpReply { status, body: serde_json::json!({ "text": text, "truncated": truncated }) });
124 }
125 let body = resp.json().await.unwrap_or_else(|_| serde_json::json!({}));
126 Ok(HttpReply { status, body })
127 }
128}
129
130pub fn google_error(reply: &HttpReply) -> String {
132 let msg = reply.body.pointer("/error/message").and_then(Value::as_str).unwrap_or("").trim();
133 let reason = reply.body.pointer("/error/errors/0/reason").and_then(Value::as_str).unwrap_or("");
134 match (reply.status, msg.is_empty()) {
135 (401, _) => "Google refused the account's token; reconnect it in Connectors".to_string(),
136 (403, _) if reason.contains("insufficient") || msg.contains("insufficient") => {
137 "the account hasn't granted the permission this needs; turn the service on again in Connectors".to_string()
138 }
139 (404, _) => "Google found no such calendar, event or file (or the account can't see it)".to_string(),
140 (429, _) => "Google is rate-limiting this account; try again in a minute".to_string(),
141 (s, false) => format!("Google answered HTTP {s}: {}", msg.chars().take(300).collect::<String>()),
142 (s, true) => format!("Google answered HTTP {s}"),
143 }
144}
145
146pub(crate) fn clip(s: &str, max: usize) -> String {
148 if s.chars().count() <= max {
149 return s.to_string();
150 }
151 let mut out: String = s.chars().take(max).collect();
152 out.push('…');
153 out
154}
155
156#[cfg(test)]
157mod tests;