Skip to main content

cdp_driver/
agent.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{json, Value};
3use tokio::sync::broadcast;
4
5use crate::client::CdpClient;
6use crate::config::Config;
7use crate::error::{CdpError, Result};
8use crate::types::ConsoleMessage;
9
10fn quote(s: &str) -> String {
11    serde_json::to_string(s).unwrap_or_else(|_| format!("\"{}\"", s.replace('"', "\\\"")))
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub enum BrowserAction {
16    Navigate {
17        url: String,
18    },
19    GoBack,
20    GoForward,
21    Reload,
22
23    Click {
24        selector: Option<String>,
25        x: Option<f64>,
26        y: Option<f64>,
27    },
28    Type {
29        text: String,
30        selector: Option<String>,
31    },
32    Fill {
33        selector: String,
34        value: String,
35    },
36    Submit {
37        selector: Option<String>,
38    },
39    PressKey {
40        key: String,
41    },
42
43    GetTitle,
44    GetUrl,
45    GetText,
46    GetContent {
47        selector: Option<String>,
48    },
49    GetLinks,
50    GetAttributes {
51        selector: String,
52    },
53    Exists {
54        selector: String,
55    },
56
57    Screenshot {
58        path: Option<String>,
59    },
60    Evaluate {
61        expression: String,
62    },
63
64    Wait {
65        ms: u64,
66    },
67    WaitForSelector {
68        selector: String,
69        timeout_ms: u64,
70    },
71
72    Scroll {
73        x: f64,
74        y: f64,
75    },
76    SetViewport {
77        width: i32,
78        height: i32,
79        mobile: bool,
80    },
81    GetMetrics,
82}
83
84#[derive(Debug, Clone)]
85pub struct ActionResult {
86    pub success: bool,
87    pub value: Option<Value>,
88    pub error: Option<String>,
89}
90
91impl ActionResult {
92    pub fn is_success(&self) -> bool {
93        self.success
94    }
95}
96
97impl std::fmt::Display for ActionResult {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        if self.success {
100            write!(f, "Ok({:?})", self.value)
101        } else {
102            write!(f, "Err({})", self.error.as_deref().unwrap_or("unknown"))
103        }
104    }
105}
106
107pub struct BrowserAgent {
108    client: CdpClient,
109}
110
111impl BrowserAgent {
112    pub async fn connect(host: &str, port: u16) -> Result<Self> {
113        let client = CdpClient::connect_to_page(host, port).await?;
114        for domain in ["Page", "Runtime", "DOM", "Network"] {
115            client.enable_domain(domain).await?;
116        }
117        Ok(BrowserAgent { client })
118    }
119
120    pub async fn connect_with_config(config: &Config) -> Result<Self> {
121        let agent = Self::connect(&config.host, config.port).await?;
122        agent
123            .client
124            .set_viewport(config.viewport_width, config.viewport_height, false)
125            .await?;
126        Ok(agent)
127    }
128
129    /// Wrap an already-connected client (domains are the caller's responsibility).
130    pub fn from_client(client: CdpClient) -> Self {
131        BrowserAgent { client }
132    }
133
134    /// Close the underlying tab.
135    pub async fn close(&self) -> Result<()> {
136        self.client.close().await
137    }
138
139    pub fn capture_console(&self) -> broadcast::Receiver<ConsoleMessage> {
140        let (tx, rx) = broadcast::channel(64);
141        let mut events = self.client.subscribe_events();
142        tokio::spawn(async move {
143            while let Ok((method, params)) = events.recv().await {
144                if method != "Runtime.consoleAPICalled" {
145                    continue;
146                }
147                let level = params["type"].as_str().unwrap_or("log").to_string();
148                let text = params["args"]
149                    .as_array()
150                    .and_then(|args| args.first())
151                    .and_then(|a| a["value"].as_str())
152                    .unwrap_or("")
153                    .to_string();
154                let url = params["stackTrace"]["callFrames"][0]["url"]
155                    .as_str()
156                    .map(str::to_owned);
157                let line = params["stackTrace"]["callFrames"][0]["lineNumber"].as_u64();
158                let _ = tx.send(ConsoleMessage {
159                    level,
160                    text,
161                    url,
162                    line,
163                });
164            }
165        });
166        rx
167    }
168
169    pub async fn execute(&self, action: BrowserAction) -> ActionResult {
170        match self.dispatch(action).await {
171            Ok(value) => ActionResult {
172                success: true,
173                value: Some(value),
174                error: None,
175            },
176            Err(e) => ActionResult {
177                success: false,
178                value: None,
179                error: Some(e.to_string()),
180            },
181        }
182    }
183
184    pub async fn execute_many(&self, actions: Vec<BrowserAction>) -> Vec<ActionResult> {
185        let mut results = Vec::with_capacity(actions.len());
186        for action in actions {
187            results.push(self.execute(action).await);
188        }
189        results
190    }
191
192    pub async fn execute_json(&self, json_str: &str) -> ActionResult {
193        match parse_action(json_str) {
194            Ok(action) => self.execute(action).await,
195            Err(e) => ActionResult {
196                success: false,
197                value: None,
198                error: Some(e.to_string()),
199            },
200        }
201    }
202
203    async fn dispatch(&self, action: BrowserAction) -> Result<Value> {
204        match action {
205            BrowserAction::Navigate { url } => {
206                let nav = self.client.navigate(&url).await?;
207                Ok(json!({ "frameId": nav.frame_id }))
208            }
209            BrowserAction::GoBack => self.client.send_command("Page.goBack", json!({})).await,
210            BrowserAction::GoForward => self.client.send_command("Page.goForward", json!({})).await,
211            BrowserAction::Reload => self.client.send_command("Page.reload", json!({})).await,
212
213            BrowserAction::Click { selector, x, y } => {
214                if let Some(sel) = selector {
215                    self.client
216                        .eval(&format!("document.querySelector({})?.click()", quote(&sel)))
217                        .await?;
218                } else if let (Some(cx), Some(cy)) = (x, y) {
219                    for event_type in ["mousePressed", "mouseReleased"] {
220                        self.client
221                            .send_command(
222                                "Input.dispatchMouseEvent",
223                                json!({
224                                    "type": event_type, "x": cx, "y": cy,
225                                    "button": "left", "clickCount": 1,
226                                }),
227                            )
228                            .await?;
229                    }
230                } else {
231                    return Err(CdpError::Protocol("click: need selector or (x, y)".into()));
232                }
233                Ok(json!(null))
234            }
235
236            BrowserAction::Type { text, selector } => {
237                if let Some(sel) = selector {
238                    self.client
239                        .eval(&format!("document.querySelector({})?.focus()", quote(&sel)))
240                        .await?;
241                }
242                self.client
243                    .send_command("Input.insertText", json!({ "text": text }))
244                    .await?;
245                Ok(json!(null))
246            }
247
248            BrowserAction::Fill { selector, value } => {
249                self.client
250                    .eval(&format!(
251                        "(sel => {{ \
252                        let el = document.querySelector(sel); \
253                        if (!el) return; \
254                        el.focus(); \
255                        el.value = {}; \
256                        el.dispatchEvent(new Event('input', {{bubbles:true}})); \
257                        el.dispatchEvent(new Event('change', {{bubbles:true}})); \
258                    }})({})",
259                        quote(&value),
260                        quote(&selector),
261                    ))
262                    .await?;
263                Ok(json!(null))
264            }
265
266            BrowserAction::Submit { selector } => {
267                let sel = selector.as_deref().unwrap_or("form");
268                self.client
269                    .eval(&format!("document.querySelector({})?.submit()", quote(sel)))
270                    .await?;
271                Ok(json!(null))
272            }
273
274            BrowserAction::PressKey { key } => {
275                let (code, vk) = key_info(&key);
276                self.client
277                    .send_command(
278                        "Input.dispatchKeyEvent",
279                        json!({
280                            "type": "keyDown", "key": key, "code": code,
281                            "windowsVirtualKeyCode": vk,
282                        }),
283                    )
284                    .await?;
285                self.client
286                    .send_command(
287                        "Input.dispatchKeyEvent",
288                        json!({
289                            "type": "keyUp", "key": key, "code": code,
290                        }),
291                    )
292                    .await?;
293                Ok(json!(null))
294            }
295
296            BrowserAction::GetTitle => Ok(json!(self.client.eval("document.title").await?)),
297            BrowserAction::GetUrl => Ok(json!(self.client.eval("window.location.href").await?)),
298            BrowserAction::GetText => Ok(json!(self.client.eval("document.body.innerText").await?)),
299
300            BrowserAction::GetContent { selector } => {
301                let expr = match selector {
302                    Some(sel) => format!("document.querySelector({})?.innerHTML", quote(&sel)),
303                    None => "document.documentElement.outerHTML".into(),
304                };
305                Ok(json!(self.client.eval(&expr).await?))
306            }
307
308            BrowserAction::GetLinks => {
309                let ev = self
310                    .client
311                    .evaluate(
312                        "Array.from(document.querySelectorAll('a'))\
313                     .map(a => ({ href: a.href, text: a.innerText.trim() }))",
314                    )
315                    .await?;
316                Ok(ev.result.value.unwrap_or(json!([])))
317            }
318
319            BrowserAction::GetAttributes { selector } => {
320                let ev = self
321                    .client
322                    .evaluate(&format!(
323                        "(sel => {{ \
324                        let el = document.querySelector(sel); \
325                        if (!el) return null; \
326                        let attrs = {{}}; \
327                        for (let a of el.attributes) attrs[a.name] = a.value; \
328                        return attrs; \
329                    }})({})",
330                        quote(&selector)
331                    ))
332                    .await?;
333                Ok(ev.result.value.unwrap_or(json!(null)))
334            }
335
336            BrowserAction::Exists { selector } => {
337                let ev = self
338                    .client
339                    .evaluate(&format!("!!document.querySelector({})", quote(&selector)))
340                    .await?;
341                Ok(ev.result.value.unwrap_or(json!(false)))
342            }
343
344            BrowserAction::Screenshot { path } => match path {
345                Some(p) => {
346                    self.client.full_page_screenshot_to_file(&p).await?;
347                    Ok(json!(p))
348                }
349                None => Ok(json!(self.client.full_page_screenshot().await?.len())),
350            },
351
352            BrowserAction::Evaluate { expression } => {
353                let ev = self.client.evaluate(&expression).await?;
354                Ok(ev.result.value.unwrap_or(json!(null)))
355            }
356
357            BrowserAction::Wait { ms } => {
358                tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
359                Ok(json!(null))
360            }
361
362            BrowserAction::WaitForSelector {
363                selector,
364                timeout_ms,
365            } => {
366                let deadline =
367                    std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
368                let expr = format!("!!document.querySelector({})", quote(&selector));
369                loop {
370                    let ev = self.client.evaluate(&expr).await?;
371                    if ev.result.value == Some(json!(true)) {
372                        return Ok(json!(true));
373                    }
374                    if std::time::Instant::now() >= deadline {
375                        return Err(CdpError::Timeout);
376                    }
377                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
378                }
379            }
380
381            BrowserAction::Scroll { x, y } => {
382                self.client
383                    .eval(&format!("window.scrollTo({x}, {y})"))
384                    .await?;
385                Ok(json!(null))
386            }
387
388            BrowserAction::SetViewport {
389                width,
390                height,
391                mobile,
392            } => {
393                self.client.set_viewport(width, height, mobile).await?;
394                Ok(json!(null))
395            }
396
397            BrowserAction::GetMetrics => {
398                self.client
399                    .send_command("Performance.getMetrics", json!({}))
400                    .await
401            }
402        }
403    }
404}
405
406fn key_info(key: &str) -> (&str, u32) {
407    match key {
408        "Enter" => ("Enter", 13),
409        "Tab" => ("Tab", 9),
410        "Backspace" => ("Backspace", 8),
411        "Delete" => ("Delete", 46),
412        "Escape" => ("Escape", 27),
413        " " | "Space" => ("Space", 32),
414        "ArrowLeft" => ("ArrowLeft", 37),
415        "ArrowUp" => ("ArrowUp", 38),
416        "ArrowRight" => ("ArrowRight", 39),
417        "ArrowDown" => ("ArrowDown", 40),
418        _ => (key, 0),
419    }
420}
421
422#[derive(Debug, Deserialize)]
423struct RawAction {
424    action: String,
425    url: Option<String>,
426    selector: Option<String>,
427    value: Option<String>,
428    text: Option<String>,
429    key: Option<String>,
430    path: Option<String>,
431    ms: Option<u64>,
432    x: Option<f64>,
433    y: Option<f64>,
434    expression: Option<String>,
435    width: Option<i32>,
436    height: Option<i32>,
437    mobile: Option<bool>,
438    timeout_ms: Option<u64>,
439}
440
441fn parse_action(json_str: &str) -> Result<BrowserAction> {
442    let a: RawAction = serde_json::from_str(json_str)?;
443
444    macro_rules! need {
445        ($field:expr, $name:literal) => {
446            $field.ok_or_else(|| CdpError::Protocol(concat!($name, " is required").into()))?
447        };
448    }
449
450    Ok(match a.action.as_str() {
451        "navigate" => BrowserAction::Navigate {
452            url: need!(a.url, "url"),
453        },
454        "back" | "go_back" => BrowserAction::GoBack,
455        "forward" | "go_forward" => BrowserAction::GoForward,
456        "reload" => BrowserAction::Reload,
457        "click" => BrowserAction::Click {
458            selector: a.selector,
459            x: a.x,
460            y: a.y,
461        },
462        "type" => BrowserAction::Type {
463            text: need!(a.text, "text"),
464            selector: a.selector,
465        },
466        "fill" => BrowserAction::Fill {
467            selector: need!(a.selector, "selector"),
468            value: need!(a.value, "value"),
469        },
470        "submit" => BrowserAction::Submit {
471            selector: a.selector,
472        },
473        "press_key" | "key" => BrowserAction::PressKey {
474            key: need!(a.key, "key"),
475        },
476        "get_title" | "title" => BrowserAction::GetTitle,
477        "get_url" | "url" => BrowserAction::GetUrl,
478        "get_text" | "text" => BrowserAction::GetText,
479        "get_content" | "content" => BrowserAction::GetContent {
480            selector: a.selector,
481        },
482        "get_links" | "links" => BrowserAction::GetLinks,
483        "get_attributes" | "attributes" => BrowserAction::GetAttributes {
484            selector: need!(a.selector, "selector"),
485        },
486        "exists" => BrowserAction::Exists {
487            selector: need!(a.selector, "selector"),
488        },
489        "screenshot" => BrowserAction::Screenshot { path: a.path },
490        "evaluate" | "eval" => BrowserAction::Evaluate {
491            expression: need!(a.expression, "expression"),
492        },
493        "wait" => BrowserAction::Wait {
494            ms: need!(a.ms, "ms"),
495        },
496        "wait_for_selector" => BrowserAction::WaitForSelector {
497            selector: need!(a.selector, "selector"),
498            timeout_ms: a.timeout_ms.unwrap_or(5000),
499        },
500        "scroll" => BrowserAction::Scroll {
501            x: a.x.unwrap_or(0.0),
502            y: a.y.unwrap_or(0.0),
503        },
504        "set_viewport" => BrowserAction::SetViewport {
505            width: need!(a.width, "width"),
506            height: need!(a.height, "height"),
507            mobile: a.mobile.unwrap_or(false),
508        },
509        "get_metrics" | "metrics" => BrowserAction::GetMetrics,
510        other => return Err(CdpError::Protocol(format!("unknown action: {other}"))),
511    })
512}
513
514pub struct ActionBuilder {
515    actions: Vec<BrowserAction>,
516}
517
518impl ActionBuilder {
519    pub fn new() -> Self {
520        ActionBuilder {
521            actions: Vec::new(),
522        }
523    }
524
525    pub fn navigate(mut self, url: &str) -> Self {
526        self.actions
527            .push(BrowserAction::Navigate { url: url.into() });
528        self
529    }
530
531    pub fn wait(mut self, ms: u64) -> Self {
532        self.actions.push(BrowserAction::Wait { ms });
533        self
534    }
535
536    pub fn click(mut self, selector: &str) -> Self {
537        self.actions.push(BrowserAction::Click {
538            selector: Some(selector.into()),
539            x: None,
540            y: None,
541        });
542        self
543    }
544
545    pub fn fill(mut self, selector: &str, value: &str) -> Self {
546        self.actions.push(BrowserAction::Fill {
547            selector: selector.into(),
548            value: value.into(),
549        });
550        self
551    }
552
553    pub fn press_key(mut self, key: &str) -> Self {
554        self.actions
555            .push(BrowserAction::PressKey { key: key.into() });
556        self
557    }
558
559    pub fn screenshot(mut self, path: Option<&str>) -> Self {
560        self.actions.push(BrowserAction::Screenshot {
561            path: path.map(Into::into),
562        });
563        self
564    }
565
566    pub fn evaluate(mut self, expr: &str) -> Self {
567        self.actions.push(BrowserAction::Evaluate {
568            expression: expr.into(),
569        });
570        self
571    }
572
573    pub fn scroll(mut self, x: f64, y: f64) -> Self {
574        self.actions.push(BrowserAction::Scroll { x, y });
575        self
576    }
577
578    pub fn get_title(mut self) -> Self {
579        self.actions.push(BrowserAction::GetTitle);
580        self
581    }
582
583    pub fn build(self) -> Vec<BrowserAction> {
584        self.actions
585    }
586}
587
588impl Default for ActionBuilder {
589    fn default() -> Self {
590        Self::new()
591    }
592}