1use std::collections::BTreeMap;
15
16use axum::http::StatusCode;
17use axum::response::{IntoResponse, Response};
18use axum::Json;
19use serde_json::{json, Value};
20use zeroize::Zeroizing;
21
22use agentmux_common::api_types::{CaptureFrom, CaptureInto, CaptureRule};
23
24use super::browser_actions::{note, How, Kind};
25use super::browser_capture::{captured_note, take_read, CaptureAs, CaptureRequest, HOST_WAIT};
26use super::ui_handlers::{err_response, proxy_value, target_block_id};
27use super::AppState;
28use crate::backend::vault::capture::{self, Target};
29
30pub(super) fn card_rule(refs: &BTreeMap<String, String>, given: Option<&CaptureAs>) -> Result<CaptureRule, String> {
33 let Some(given) = given else {
34 return Err("say where the card goes: as {kind: \"card\", label}".into());
35 };
36 if given.kind.as_deref().is_some_and(|k| k.trim() != "card") {
37 return Err("card is for a card: leave kind out, or give \"card\"".into());
38 }
39 if let Some((key, _)) = refs.iter().find(|(_, r)| r.trim().is_empty()) {
40 return Err(format!("card.{key} needs the ref of the element that shows it"));
41 }
42 let from = CaptureFrom::Parts(refs.keys().map(|k| (k.clone(), CaptureFrom::Stdout("all".into()))).collect());
43 Ok(CaptureRule { into: CaptureInto { kind: Some("card".into()), label: Some(given.label.clone()), ..Default::default() }, from })
44}
45
46pub(super) fn gathered(reads: Vec<(String, Zeroizing<String>, String)>) -> Result<(BTreeMap<String, Zeroizing<String>>, String), String> {
48 let mut origin = String::new();
49 let mut values = BTreeMap::new();
50 for (key, value, from) in reads {
51 if from.is_empty() {
52 return Err("AgentMux can't tell which site this page is, so nothing was saved".into());
53 }
54 if origin.is_empty() {
55 origin = from;
56 } else if origin != from {
57 return Err(format!("the card's parts are on more than one site ({origin} and {from}), so nothing was saved: capture a card whose parts are on one site"));
58 }
59 values.insert(key, value);
60 }
61 Ok((values, origin))
62}
63
64pub(super) async fn capture_card(state: AppState, caller: Option<axum::Extension<crate::server::caller::Caller>>, req: CaptureRequest) -> Response {
65 let Some(refs) = req.card.clone() else {
66 return err_response(StatusCode::BAD_REQUEST, "card names the elements that show the card's parts".into());
67 };
68 if req.entry.is_some() || req.download || req.ref_.is_some() {
69 return err_response(StatusCode::BAD_REQUEST, "a card is saved whole as a new entry: give card and as, not ref, entry or download".into());
70 }
71 let reason = match crate::backend::vault::history::require_reason(req.reason.as_deref()) {
72 Ok(r) => r,
73 Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
74 };
75 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
76 Ok(b) => b,
77 Err((code, e)) => return err_response(code, e),
78 };
79 let agent: String = req.auth.agent_id.chars().take(64).collect();
80 let rule = match card_rule(&refs, req.into.as_ref()) {
81 Ok(r) => r,
82 Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
83 };
84 let (store, a) = (state.identity_store.clone(), agent.clone());
85 let mut plan = match tokio::task::spawn_blocking(move || capture::plan(&store, &[rule], &a, "")).await {
86 Ok(Ok(p)) => p,
87 Ok(Err(e)) => return err_response(StatusCode::BAD_REQUEST, e),
88 Err(e) => return err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
89 };
90 plan.reason = reason;
91
92 let mut reads = Vec::with_capacity(refs.len());
93 for (key, r) in &refs {
94 let read = proxy_value(&state, "capture_value", json!({ "block_id": block_id, "ref": r, "whole": true }), HOST_WAIT).await;
95 let read = match read {
96 Ok(v) => v,
97 Err((code, e)) => return err_response(code, format!("card.{key}: {e}; nothing was saved")),
98 };
99 match take_read(read) {
100 Ok((value, origin)) => reads.push((key.clone(), value, origin)),
101 Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
102 }
103 }
104 let (values, origin) = match gathered(reads) {
105 Ok(g) => g,
106 Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
107 };
108 let parts: Vec<String> = values.keys().cloned().collect();
109
110 let (store, given, from) = (state.identity_store.clone(), req.into, origin.clone());
111 let stored = tokio::task::spawn_blocking(move || store_card(&store, plan, values, &from, given.as_ref())).await;
112 super::vault_handlers::publish(&state);
113 let mut marked = 0;
115 if matches!(stored, Ok(Ok(_))) {
116 for r in refs.values() {
117 match proxy_value(&state, "capture_mark", json!({ "block_id": block_id, "ref": r }), HOST_WAIT).await {
118 Ok(_) => marked += 1,
119 Err((_, e)) => tracing::warn!(error = %e, "[vault] a captured card element couldn't be marked"),
120 }
121 }
122 }
123 let log = note(&block_id, &agent, Kind::Capture).target(&format!("card, {} parts", parts.len()));
124 match &stored {
125 Ok(Ok((_, label))) => log.detail(&format!("{label} (a card), captured from {origin}")).how(How::Allowed).record(&state),
126 Ok(Err(e)) => log.how(How::Refused(e.chars().take(160).collect())).record(&state),
127 Err(_) => {}
128 }
129 match stored {
130 Ok(Ok((id, label))) => {
131 let out = json!({ "ok": true, "id": id, "label": label, "captured_from": origin, "parts": parts, "marked": marked == refs.len(), "note": captured_note(marked == refs.len()) });
132 (StatusCode::OK, Json(out)).into_response()
133 }
134 Ok(Err(e)) => err_response(StatusCode::BAD_REQUEST, format!("nothing was saved: {e}")),
135 Err(e) => err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
136 }
137}
138
139pub(super) fn store_card(
141 store: &crate::backend::storage::store::Store,
142 mut plan: capture::Capture,
143 values: BTreeMap<String, Zeroizing<String>>,
144 origin: &str,
145 given: Option<&CaptureAs>,
146) -> Result<(String, String), String> {
147 plan.cmd = format!("from {origin}");
148 if let (Target::New { fields, .. }, Some(given)) = (&mut plan.rules[0].into, given) {
149 fields.extend(given.fields.clone());
150 if let Some(date) = given.expires.as_ref().filter(|d| !d.trim().is_empty()) {
151 fields.insert("expires".into(), date.clone());
152 }
153 }
154 let found = capture::card_found(values)?;
155 let ids = plan.store(store, &[found])?;
156 let Target::New { label, .. } = &plan.rules[0].into else {
157 return Err("a card is a new entry".into());
158 };
159 Ok((ids.into_iter().next().unwrap_or_default(), label.clone()))
160}
161
162#[cfg(test)]
163#[path = "browser_capture_card_tests.rs"]
164mod tests;