1use serde_json::{json, Value};
4use tokio::sync::broadcast;
5
6use crate::action_parse::parse_action;
7use crate::client::CdpClient;
8use crate::config::Config;
9use crate::error::{CdpError, Result};
10use crate::keys::key_info;
11use crate::types::ConsoleMessage;
12
13pub use crate::action::BrowserAction;
16pub use crate::action_builder::ActionBuilder;
17
18const SELECTOR_POLL_MS: u64 = 100;
20
21const CONSOLE_BACKLOG: usize = 64;
23
24fn quote(s: &str) -> String {
27 serde_json::to_string(s).unwrap_or_else(|_| format!("\"{}\"", s.replace('"', "\\\"")))
28}
29
30#[derive(Debug, Clone)]
34pub struct ActionResult {
35 pub success: bool,
37 pub value: Option<Value>,
39 pub error: Option<String>,
41}
42
43impl ActionResult {
44 pub fn is_success(&self) -> bool {
46 self.success
47 }
48
49 fn failed(error: impl std::fmt::Display) -> Self {
51 ActionResult {
52 success: false,
53 value: None,
54 error: Some(error.to_string()),
55 }
56 }
57}
58
59impl std::fmt::Display for ActionResult {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 if self.success {
62 write!(f, "Ok({:?})", self.value)
63 } else {
64 write!(f, "Err({})", self.error.as_deref().unwrap_or("unknown"))
65 }
66 }
67}
68
69pub struct BrowserAgent {
72 client: CdpClient,
73}
74
75impl BrowserAgent {
76 pub async fn connect(host: &str, port: u16) -> Result<Self> {
79 let client = CdpClient::connect_to_page(host, port).await?;
80 for domain in ["Page", "Runtime", "DOM", "Network"] {
81 client.enable_domain(domain).await?;
82 }
83 Ok(BrowserAgent { client })
84 }
85
86 pub async fn connect_with_config(config: &Config) -> Result<Self> {
89 let agent = Self::connect(&config.host, config.port).await?;
90 agent
91 .client
92 .set_viewport(config.viewport_width, config.viewport_height, false)
93 .await?;
94 Ok(agent)
95 }
96
97 pub fn from_client(client: CdpClient) -> Self {
99 BrowserAgent { client }
100 }
101
102 pub async fn close(&self) -> Result<()> {
104 self.client.close().await
105 }
106
107 pub fn capture_console(&self) -> broadcast::Receiver<ConsoleMessage> {
111 let (tx, rx) = broadcast::channel(CONSOLE_BACKLOG);
112 let mut events = self.client.subscribe_events();
113 tokio::spawn(async move {
114 while let Ok((method, params)) = events.recv().await {
115 if method != "Runtime.consoleAPICalled" {
116 continue;
117 }
118 let level = params["type"].as_str().unwrap_or("log").to_string();
119 let text = params["args"]
120 .as_array()
121 .and_then(|args| args.first())
122 .and_then(|a| a["value"].as_str())
123 .unwrap_or("")
124 .to_string();
125 let url = params["stackTrace"]["callFrames"][0]["url"]
126 .as_str()
127 .map(str::to_owned);
128 let line = params["stackTrace"]["callFrames"][0]["lineNumber"].as_u64();
129 let _ = tx.send(ConsoleMessage {
130 level,
131 text,
132 url,
133 line,
134 });
135 }
136 });
137 rx
138 }
139
140 pub async fn execute(&self, action: BrowserAction) -> ActionResult {
143 match self.dispatch(action).await {
144 Ok(value) => ActionResult {
145 success: true,
146 value: Some(value),
147 error: None,
148 },
149 Err(e) => ActionResult::failed(e),
150 }
151 }
152
153 pub async fn execute_many(&self, actions: Vec<BrowserAction>) -> Vec<ActionResult> {
155 let mut results = Vec::with_capacity(actions.len());
156 for action in actions {
157 results.push(self.execute(action).await);
158 }
159 results
160 }
161
162 pub async fn execute_json(&self, json_str: &str) -> ActionResult {
165 match parse_action(json_str) {
166 Ok(action) => self.execute(action).await,
167 Err(e) => ActionResult::failed(e),
168 }
169 }
170
171 async fn dispatch(&self, action: BrowserAction) -> Result<Value> {
172 match action {
173 BrowserAction::Navigate { url } => {
174 let nav = self.client.navigate(&url).await?;
175 Ok(json!({ "frameId": nav.frame_id }))
176 }
177 BrowserAction::GoBack => self.client.send_command("Page.goBack", json!({})).await,
178 BrowserAction::GoForward => self.client.send_command("Page.goForward", json!({})).await,
179 BrowserAction::Reload => self.client.send_command("Page.reload", json!({})).await,
180
181 BrowserAction::Click { selector, x, y } => {
182 if let Some(sel) = selector {
183 self.client
184 .eval(&format!("document.querySelector({})?.click()", quote(&sel)))
185 .await?;
186 } else if let (Some(cx), Some(cy)) = (x, y) {
187 for event_type in ["mousePressed", "mouseReleased"] {
188 self.client
189 .send_command(
190 "Input.dispatchMouseEvent",
191 json!({
192 "type": event_type, "x": cx, "y": cy,
193 "button": "left", "clickCount": 1,
194 }),
195 )
196 .await?;
197 }
198 } else {
199 return Err(CdpError::Protocol("click: need selector or (x, y)".into()));
200 }
201 Ok(json!(null))
202 }
203
204 BrowserAction::Type { text, selector } => {
205 if let Some(sel) = selector {
206 self.client
207 .eval(&format!("document.querySelector({})?.focus()", quote(&sel)))
208 .await?;
209 }
210 self.client
211 .send_command("Input.insertText", json!({ "text": text }))
212 .await?;
213 Ok(json!(null))
214 }
215
216 BrowserAction::Fill { selector, value } => {
217 self.client
218 .eval(&format!(
219 "(sel => {{ \
220 let el = document.querySelector(sel); \
221 if (!el) return; \
222 el.focus(); \
223 el.value = {}; \
224 el.dispatchEvent(new Event('input', {{bubbles:true}})); \
225 el.dispatchEvent(new Event('change', {{bubbles:true}})); \
226 }})({})",
227 quote(&value),
228 quote(&selector),
229 ))
230 .await?;
231 Ok(json!(null))
232 }
233
234 BrowserAction::Submit { selector } => {
235 let sel = selector.as_deref().unwrap_or("form");
236 self.client
237 .eval(&format!("document.querySelector({})?.submit()", quote(sel)))
238 .await?;
239 Ok(json!(null))
240 }
241
242 BrowserAction::PressKey { key } => {
243 let (code, vk) = key_info(&key);
244 self.client
245 .send_command(
246 "Input.dispatchKeyEvent",
247 json!({
248 "type": "keyDown", "key": key, "code": code,
249 "windowsVirtualKeyCode": vk,
250 }),
251 )
252 .await?;
253 self.client
254 .send_command(
255 "Input.dispatchKeyEvent",
256 json!({
257 "type": "keyUp", "key": key, "code": code,
258 }),
259 )
260 .await?;
261 Ok(json!(null))
262 }
263
264 BrowserAction::GetTitle => Ok(json!(self.client.eval("document.title").await?)),
265 BrowserAction::GetUrl => Ok(json!(self.client.eval("window.location.href").await?)),
266 BrowserAction::GetText => Ok(json!(self.client.eval("document.body.innerText").await?)),
267
268 BrowserAction::GetContent { selector } => {
269 let expr = match selector {
270 Some(sel) => format!("document.querySelector({})?.innerHTML", quote(&sel)),
271 None => "document.documentElement.outerHTML".into(),
272 };
273 Ok(json!(self.client.eval(&expr).await?))
274 }
275
276 BrowserAction::GetLinks => {
277 let ev = self
278 .client
279 .evaluate(
280 "Array.from(document.querySelectorAll('a'))\
281 .map(a => ({ href: a.href, text: a.innerText.trim() }))",
282 )
283 .await?;
284 Ok(ev.result.value.unwrap_or(json!([])))
285 }
286
287 BrowserAction::GetAttributes { selector } => {
288 let ev = self
289 .client
290 .evaluate(&format!(
291 "(sel => {{ \
292 let el = document.querySelector(sel); \
293 if (!el) return null; \
294 let attrs = {{}}; \
295 for (let a of el.attributes) attrs[a.name] = a.value; \
296 return attrs; \
297 }})({})",
298 quote(&selector)
299 ))
300 .await?;
301 Ok(ev.result.value.unwrap_or(json!(null)))
302 }
303
304 BrowserAction::Exists { selector } => {
305 let ev = self
306 .client
307 .evaluate(&format!("!!document.querySelector({})", quote(&selector)))
308 .await?;
309 Ok(ev.result.value.unwrap_or(json!(false)))
310 }
311
312 BrowserAction::Screenshot { path } => match path {
313 Some(p) => {
314 self.client.full_page_screenshot_to_file(&p).await?;
315 Ok(json!(p))
316 }
317 None => Ok(json!(self.client.full_page_screenshot().await?.len())),
318 },
319
320 BrowserAction::Evaluate { expression } => {
321 let ev = self.client.evaluate(&expression).await?;
322 Ok(ev.result.value.unwrap_or(json!(null)))
323 }
324
325 BrowserAction::Wait { ms } => {
326 tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
327 Ok(json!(null))
328 }
329
330 BrowserAction::WaitForSelector {
331 selector,
332 timeout_ms,
333 } => {
334 let deadline =
335 std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
336 let expr = format!("!!document.querySelector({})", quote(&selector));
337 loop {
338 let ev = self.client.evaluate(&expr).await?;
339 if ev.result.value == Some(json!(true)) {
340 return Ok(json!(true));
341 }
342 if std::time::Instant::now() >= deadline {
343 return Err(CdpError::Timeout);
344 }
345 tokio::time::sleep(std::time::Duration::from_millis(SELECTOR_POLL_MS)).await;
346 }
347 }
348
349 BrowserAction::Scroll { x, y } => {
350 self.client
351 .eval(&format!("window.scrollTo({x}, {y})"))
352 .await?;
353 Ok(json!(null))
354 }
355
356 BrowserAction::SetViewport {
357 width,
358 height,
359 mobile,
360 } => {
361 self.client.set_viewport(width, height, mobile).await?;
362 Ok(json!(null))
363 }
364
365 BrowserAction::GetMetrics => {
366 self.client
367 .send_command("Performance.getMetrics", json!({}))
368 .await
369 }
370 }
371 }
372}