1use base64::Engine as _;
17use serde_json::{json, Value};
18use sha2::{Digest, Sha256};
19
20use super::gmail::{attachments, body_text, get, header, html_alternative, id_arg, line, s, tidy, url_of, GmailArgs};
21use super::gmail_thread::ThreadNote;
22use super::{clip, GoogleRequest};
23
24pub const WRITE_ACTIONS: [&str; 5] = ["create_draft", "update_draft", "send_draft", "label_thread", "trash_thread"];
26
27pub fn always_asks(action: &str) -> bool {
29 matches!(action, "send_draft" | "trash_thread")
30}
31
32const RECIPIENTS: usize = 50;
34const SUBJECT_CHARS: usize = 300;
35const BODY_CHARS: usize = 100_000;
36const LABELS: usize = 10;
38const SHOWN_BODY_CHARS: usize = 3000;
40
41pub fn needs(action: &str) -> &'static [&'static str] {
44 match action {
45 "label_thread" | "trash_thread" => &["gmail.modify"],
46 _ => &["gmail.compose", "gmail.modify"],
47 }
48}
49
50pub fn granted_for(action: &str, granted: &[String]) -> bool {
52 needs(action).iter().any(|n| super::gmail::has_scope(granted, n))
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Outgoing {
58 pub to: Vec<String>,
59 pub cc: Vec<String>,
60 pub bcc: Vec<String>,
61 pub subject: String,
62 pub body: String,
63 pub in_reply_to: Option<String>,
66 pub references: Option<String>,
67}
68
69fn address(raw: &str) -> Result<String, String> {
72 let a = raw.trim();
73 let bad = || format!("\"{}\" isn't an address I can send to; write it as name@example.com", clip(&line(a, 80), 60));
74 if a.is_empty() || a.len() > 320 || a.chars().any(|c| c.is_control()) {
75 return Err(bad());
76 }
77 let (name, email) = match (a.rfind('<'), a.ends_with('>')) {
78 (Some(open), true) => (a[..open].trim(), &a[open + 1..a.len() - 1]),
79 _ => ("", a),
80 };
81 let plain_name = name.chars().all(|c| c.is_ascii_alphanumeric() || " .'-_".contains(c));
82 let (local, domain) = email.split_once('@').ok_or_else(bad)?;
83 let part_ok = |p: &str, extra: &str| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c));
84 if !plain_name || !part_ok(local, ".+-_") || !part_ok(domain, ".-") || !domain.contains('.') || domain.starts_with('.') || domain.ends_with('.') || email.len() > 254 {
85 return Err(bad());
86 }
87 Ok(if name.is_empty() { email.to_string() } else { format!("{name} <{email}>") })
88}
89
90fn addresses(list: &Option<Vec<String>>) -> Result<Vec<String>, String> {
91 list.iter().flatten().filter(|s| !s.trim().is_empty()).map(|a| address(a)).collect()
92}
93
94pub fn outgoing(args: &GmailArgs) -> Result<Outgoing, String> {
97 let (to, cc, bcc) = (addresses(&args.to)?, addresses(&args.cc)?, addresses(&args.bcc)?);
98 if to.len() + cc.len() + bcc.len() > RECIPIENTS {
99 return Err(format!("a mail goes to at most {RECIPIENTS} people"));
100 }
101 let subject = args.subject.as_deref().unwrap_or("").trim().to_string();
102 if subject.chars().any(|c| c.is_control()) {
103 return Err("the subject is a single line".to_string());
104 }
105 if subject.chars().count() > SUBJECT_CHARS {
106 return Err(format!("the subject is at most {SUBJECT_CHARS} characters"));
107 }
108 let body = args.body.as_deref().unwrap_or("").to_string();
109 if body.chars().count() > BODY_CHARS {
110 return Err(format!("the body is at most {BODY_CHARS} characters"));
111 }
112 if subject.is_empty() && body.trim().is_empty() && to.is_empty() {
113 return Err("a draft needs at least a recipient (to), a subject or a body".to_string());
114 }
115 Ok(Outgoing { to, cc, bcc, subject, body, in_reply_to: None, references: None })
116}
117
118fn b64_lines(bytes: &[u8]) -> String {
119 let all = base64::engine::general_purpose::STANDARD.encode(bytes);
120 all.as_bytes().chunks(76).map(|c| String::from_utf8_lossy(c).into_owned()).collect::<Vec<_>>().join("\r\n")
121}
122
123fn subject_header(subject: &str) -> String {
125 if subject.is_ascii() {
126 return subject.to_string();
127 }
128 let mut words = Vec::new();
129 let mut chunk = String::new();
130 for c in subject.chars() {
131 if chunk.len() + c.len_utf8() > 36 {
132 words.push(std::mem::take(&mut chunk));
133 }
134 chunk.push(c);
135 }
136 if !chunk.is_empty() {
137 words.push(chunk);
138 }
139 words.iter().map(|w| format!("=?UTF-8?B?{}?=", base64::engine::general_purpose::STANDARD.encode(w))).collect::<Vec<_>>().join("\r\n ")
140}
141
142pub fn rfc822(o: &Outgoing) -> String {
145 let mut out = String::from("MIME-Version: 1.0\r\n");
146 for (name, list) in [("To", &o.to), ("Cc", &o.cc), ("Bcc", &o.bcc)] {
147 if !list.is_empty() {
148 out.push_str(&format!("{name}: {}\r\n", list.join(", ")));
149 }
150 }
151 out.push_str(&format!("Subject: {}\r\n", subject_header(&o.subject)));
152 if let Some(id) = &o.in_reply_to {
153 out.push_str(&format!("In-Reply-To: {id}\r\n"));
154 }
155 if let Some(refs) = &o.references {
156 out.push_str(&format!("References: {refs}\r\n"));
157 }
158 out.push_str("Content-Type: text/plain; charset=\"UTF-8\"\r\nContent-Transfer-Encoding: base64\r\n\r\n");
159 out.push_str(&b64_lines(o.body.as_bytes()));
160 out.push_str("\r\n");
161 out
162}
163
164fn draft_body(o: &Outgoing, thread_id: Option<&str>) -> Value {
165 let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(rfc822(o));
166 let mut message = json!({ "raw": raw });
167 if let Some(t) = thread_id {
168 message["threadId"] = json!(t);
169 }
170 json!({ "message": message })
171}
172
173fn post(url: String, body: Value) -> GoogleRequest {
174 GoogleRequest { method: reqwest::Method::POST, url, query: Vec::new(), body: Some(body), text: false }
175}
176
177#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Reply {
180 pub in_reply_to: String,
181 pub references: String,
182 pub subject: String,
183}
184
185pub fn reply_fetch_plan(thread_id: &str) -> Result<GoogleRequest, String> {
187 let id = id_arg("thread_id", Some(thread_id))?;
188 let mut q = vec![("format", "metadata".to_string())];
189 for h in ["Message-ID", "References", "Subject"] {
190 q.push(("metadataHeaders", h.to_string()));
191 }
192 Ok(get(url_of(&["threads", &id])?, q))
193}
194
195fn message_id(v: &str) -> Option<String> {
197 let v = v.trim();
198 (v.len() >= 3 && v.len() <= 998 && v.starts_with('<') && v.ends_with('>') && !v.chars().any(|c| c.is_control() || c.is_whitespace())).then(|| v.to_string())
199}
200
201pub fn reply_of(thread: &Value) -> Option<Reply> {
204 let last = thread.get("messages").and_then(Value::as_array)?.last()?;
205 let p = last.get("payload")?;
206 let id = message_id(header(p, "Message-ID"))?;
207 let mut refs: Vec<String> = header(p, "References").split_whitespace().filter_map(message_id).collect();
209 refs.push(id.clone());
210 let keep = refs.len().saturating_sub(10);
211 let subject = line(header(p, "Subject"), SUBJECT_CHARS);
212 Some(Reply { in_reply_to: id, references: refs[keep..].join(" "), subject })
213}
214
215pub fn with_reply(o: &mut Outgoing, r: &Reply) {
217 o.in_reply_to = Some(r.in_reply_to.clone());
218 o.references = Some(r.references.clone());
219 if o.subject.is_empty() && !r.subject.is_empty() {
220 o.subject = if r.subject.to_ascii_lowercase().starts_with("re:") { r.subject.clone() } else { format!("Re: {}", r.subject) };
221 }
222}
223
224pub fn draft_plan(action: &str, args: &GmailArgs, reply: Option<&Reply>) -> Result<GoogleRequest, String> {
228 let mut o = outgoing(args)?;
229 if let Some(r) = reply {
230 with_reply(&mut o, r);
231 }
232 let thread = match args.thread_id.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
233 Some(t) => Some(id_arg("thread_id", Some(t))?),
234 None => None,
235 };
236 let body = draft_body(&o, thread.as_deref());
237 match action {
238 "create_draft" => Ok(post(url_of(&["drafts"])?, body)),
239 "update_draft" => {
240 let id = id_arg("draft_id", args.draft_id.as_deref())?;
241 Ok(GoogleRequest { method: reqwest::Method::PUT, url: url_of(&["drafts", &id])?, query: Vec::new(), body: Some(body), text: false })
242 }
243 other => Err(format!("{other} doesn't write a draft")),
244 }
245}
246
247pub fn draft_fetch_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
249 let id = id_arg("draft_id", args.draft_id.as_deref())?;
250 Ok(get(url_of(&["drafts", &id])?, vec![("format", "full".to_string())]))
251}
252
253pub fn draft_raw_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
255 let id = id_arg("draft_id", args.draft_id.as_deref())?;
256 Ok(get(url_of(&["drafts", &id])?, vec![("format", "raw".to_string())]))
257}
258
259pub fn send_plan(id: &str, raw: &str, thread_id: Option<&str>) -> Result<GoogleRequest, String> {
262 let id = id_arg("draft_id", Some(id))?;
263 let mut message = json!({ "raw": raw });
264 if let Some(t) = thread_id.filter(|t| !t.is_empty()) {
265 message["threadId"] = json!(t);
266 }
267 Ok(post(url_of(&["drafts", "send"])?, json!({ "id": id, "message": message })))
268}
269
270pub fn trash_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
272 let id = id_arg("thread_id", args.thread_id.as_deref())?;
273 Ok(post(url_of(&["threads", &id, "trash"])?, json!({})))
274}
275
276fn label_ids(name: &str, list: &Option<Vec<String>>) -> Result<Vec<String>, String> {
277 let ids: Vec<String> = list.iter().flatten().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect();
278 if ids.len() > LABELS {
279 return Err(format!("{name} takes at most {LABELS} label ids"));
280 }
281 for id in &ids {
282 id_arg(name, Some(id)).map_err(|_| format!("\"{}\" isn't a label id; list_labels has them", clip(id, 40)))?;
283 }
284 Ok(ids)
285}
286
287pub fn label_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
290 let thread = id_arg("thread_id", args.thread_id.as_deref())?;
291 let add = label_ids("add_label_ids", &args.add_label_ids)?;
292 let remove = label_ids("remove_label_ids", &args.remove_label_ids)?;
293 if add.is_empty() && remove.is_empty() {
294 return Err("label_thread needs add_label_ids or remove_label_ids (ids from list_labels)".to_string());
295 }
296 if add.iter().any(|l| l == "TRASH") {
297 return Err("a thread goes to the trash with trash_thread, which asks the person first".to_string());
298 }
299 Ok(post(url_of(&["threads", &thread, "modify"])?, json!({ "addLabelIds": add, "removeLabelIds": remove })))
300}
301
302#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct DraftView {
305 pub id: String,
306 pub to: String,
307 pub cc: String,
308 pub bcc: String,
309 pub subject: String,
310 pub body: String,
311 pub html: String,
314 pub attachments: Vec<String>,
316 pub thread_id: String,
319 version: String,
322}
323
324fn normalized(s: &str) -> String {
325 s.split_whitespace().collect::<Vec<_>>().join(" ")
326}
327
328fn without_attachment_ids(v: &Value) -> Value {
330 match v {
331 Value::Object(m) => Value::Object(m.iter().filter(|(k, _)| k.as_str() != "attachmentId").map(|(k, v)| (k.clone(), without_attachment_ids(v))).collect()),
332 Value::Array(a) => Value::Array(a.iter().map(without_attachment_ids).collect()),
333 other => other.clone(),
334 }
335}
336
337impl DraftView {
338 pub fn of(draft: &Value) -> DraftView {
341 let msg = draft.get("message").unwrap_or(&Value::Null);
342 let p = msg.get("payload").unwrap_or(&Value::Null);
343 let h = |name: &str| header(p, name).split_whitespace().collect::<Vec<_>>().join(" ");
344 let body = tidy(&body_text(p));
345 let html = tidy(&html_alternative(p));
346 let html = if html.is_empty() || normalized(&html) == normalized(&body) { String::new() } else { html };
347 let attachments = attachments(p)
348 .iter()
349 .map(|a| format!("{} ({} bytes)", s(a, "/filename"), a.get("size").and_then(Value::as_u64).unwrap_or(0)))
350 .collect();
351 let mut hash = Sha256::new();
352 hash.update(without_attachment_ids(p).to_string().as_bytes());
353 let version = format!("{}:{}", s(msg, "/id"), hash.finalize().iter().map(|b| format!("{b:02x}")).collect::<String>());
354 DraftView { id: s(draft, "/id").to_string(), to: h("To"), cc: h("Cc"), bcc: h("Bcc"), subject: h("Subject"), body, html, attachments, thread_id: s(msg, "/threadId").to_string(), version }
355 }
356
357 pub fn digest(&self) -> String {
360 let mut h = Sha256::new();
361 for part in [&self.to, &self.cc, &self.bcc, &self.subject, &self.body, &self.html, &self.attachments.join("\n"), &self.version] {
362 h.update((part.len() as u64).to_le_bytes());
363 h.update(part.as_bytes());
364 }
365 h.finalize().iter().map(|b| format!("{b:02x}")).collect()
366 }
367
368 pub fn has_recipient(&self) -> bool {
370 [&self.to, &self.cc, &self.bcc].iter().any(|r| !r.trim().is_empty())
371 }
372}
373
374pub fn send_question(agent: &str, account: &str, view: &DraftView) -> (String, String) {
376 send_question_in(agent, account, view, &ThreadNote::default())
377}
378
379pub fn send_question_in(agent: &str, account: &str, view: &DraftView, note: &ThreadNote) -> (String, String) {
382 let room = if view.html.is_empty() { SHOWN_BODY_CHARS } else { SHOWN_BODY_CHARS / 2 };
384 let field = |name: &str, v: &str| if v.is_empty() { String::new() } else { format!("{name}: {v}\n") };
385 let files = if view.attachments.is_empty() { String::new() } else { format!("Attached: {}\n", view.attachments.join(", ")) };
386 let html = if view.html.is_empty() {
387 String::new()
388 } else {
389 format!("\n\nThis mail also has an HTML version, which most people's mail programs show instead of the text above. It reads:\n\n{}", clip(&view.html, room))
390 };
391 let warning = note.warning.as_ref().map(|w| format!("{w}\n\n")).unwrap_or_default();
392 let thread = note.line.as_ref().map(|l| format!("{l}\n")).unwrap_or_default();
393 let message = format!(
394 "{warning}{agent} wants to send this email from {account}. It can't be taken back once it is sent.\n\n{}{}{}{thread}{files}Subject: {}\n\n{}{html}",
395 field("To", &view.to),
396 field("Cc", &view.cc),
397 field("Bcc", &view.bcc),
398 if view.subject.is_empty() { "(none)" } else { &view.subject },
399 clip(&view.body, room),
400 );
401 (format!("{} wants to send an email", clip(&line(agent, 60), 60)), message)
402}
403
404pub fn trash_question(agent: &str, account: &str, summary: &Value) -> (String, String) {
407 let first = summary.get("messages").and_then(Value::as_array).and_then(|m| m.first());
408 let p = first.and_then(|m| m.get("payload")).unwrap_or(&Value::Null);
409 let count = summary.get("messages").and_then(Value::as_array).map_or(0, Vec::len);
410 let message = format!(
411 "{agent} wants to move this email thread in {account} to the trash (Gmail keeps it there for 30 days).\n\nSubject: {}\nFrom: {}\nMessages: {count}",
412 clip(&line(header(p, "Subject"), 200), 200),
413 clip(&line(header(p, "From"), 200), 200),
414 );
415 (format!("{} wants to trash an email", clip(&line(agent, 60), 60)), message)
416}
417
418#[cfg(test)]
419#[path = "gmail_write_tests.rs"]
420mod tests;