eoka 0.17.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
use super::{
    dispatch_coordinated_key_event, dispatch_coordinated_mouse_event, held_key_from_combo,
    key_event, HeldInputState, MouseButton, MouseEventType, Session,
};
use crate::action::dispatch::Dispatch;
use crate::error::Result;
use serde_json::json;
use std::ops::Range;
use std::time::Duration;
use tokio::sync::OwnedMutexGuard;

/// Pause between the pointer moves of a drag.
const DRAG_STEP_PAUSE: Duration = Duration::from_millis(8);

/// Sleep a uniformly random number of milliseconds in `range`.
async fn pause_ms(range: Range<u64>) {
    tokio::time::sleep(Duration::from_millis(fastrand::u64(range))).await;
}

pub(crate) struct ActionInput {
    session: Session,
    state: OwnedMutexGuard<HeldInputState>,
}

impl ActionInput {
    pub(crate) fn has_held_input(&self) -> bool {
        !self.state.keys.is_empty() || !self.state.mouse_buttons.is_empty()
    }

    pub(crate) fn discard_unsent_reservations(&mut self) {
        self.state.keys.clear();
        self.state.mouse_buttons.clear();
    }

    pub(crate) async fn acquire(session: &Session) -> Result<Self> {
        let state = std::sync::Arc::clone(session.held_input())
            .lock_owned()
            .await;
        if !state.mouse_buttons.is_empty() || !state.keys.is_empty() {
            return Err(crate::Error::input_state(
                "Release held input before a high-level action",
            ));
        }
        Ok(Self {
            session: session.clone(),
            state,
        })
    }

    pub(crate) async fn move_to(&mut self, dispatch: &Dispatch, x: f64, y: f64) -> Result<()> {
        dispatch
            .send(
                &self.session,
                "Input.dispatchMouseEvent",
                json!({"type":"mouseMoved","x":x,"y":y,"buttons":0,"force":0.0}),
                true,
            )
            .await?;
        self.state.pointer = Some((x, y));
        Ok(())
    }

    /// Record a pointer position dispatched outside this helper.
    pub(crate) fn record_pointer(&mut self, x: f64, y: f64) {
        self.state.pointer = Some((x, y));
    }

    pub(crate) async fn human_move(&mut self, dispatch: &Dispatch, x: f64, y: f64) -> Result<()> {
        // Start where the pointer really is; only an untouched page has no
        // position, and then the path comes in from a nearby point.
        let start = self.state.pointer.unwrap_or_else(|| {
            (
                (x + fastrand::f64() * 400.0 - 200.0).max(0.0),
                (y + fastrand::f64() * 200.0 - 100.0).max(0.0),
            )
        });
        for (px, py) in crate::stealth::human::bezier_curve(start, (x, y), 24) {
            self.move_to(dispatch, px, py).await?;
            pause_ms(5..13).await;
        }
        Ok(())
    }

    pub(crate) async fn click(
        &mut self,
        dispatch: &Dispatch,
        x: f64,
        y: f64,
        count: i32,
        human: bool,
    ) -> Result<()> {
        let buttons = self
            .state
            .reserve_mouse_down(MouseButton::Left, (x, y))
            .map_err(crate::Error::input_state)?;
        dispatch.send(&self.session, "Input.dispatchMouseEvent", json!({"type":"mousePressed","x":x,"y":y,"button":"left","buttons":buttons,"clickCount":count,"force":0.5}), false).await?;
        self.state.pointer = Some((x, y));
        if human {
            pause_ms(50..120).await;
        }
        dispatch.send(&self.session, "Input.dispatchMouseEvent", json!({"type":"mouseReleased","x":x,"y":y,"button":"left","buttons":0,"clickCount":count,"force":0.0}), false).await?;
        self.state.finish_mouse_up(MouseButton::Left);
        Ok(())
    }

    pub(crate) async fn key(&mut self, dispatch: &Dispatch, key: &str) -> Result<()> {
        let (id, held) = held_key_from_combo(key);
        let modifiers = self
            .state
            .reserve_key_down(id.clone(), held.clone())
            .map_err(crate::Error::input_state)?
            | held.combo_modifiers;
        dispatch
            .send(
                &self.session,
                "Input.dispatchKeyEvent",
                serde_json::to_value(key_event(
                    &held,
                    crate::cdp::KeyEventType::KeyDown,
                    modifiers,
                ))?,
                false,
            )
            .await?;
        dispatch
            .send(
                &self.session,
                "Input.dispatchKeyEvent",
                serde_json::to_value(key_event(&held, crate::cdp::KeyEventType::KeyUp, modifiers))?,
                false,
            )
            .await?;
        self.state.finish_key_up(&id);
        Ok(())
    }

    pub(crate) async fn text<F: std::future::Future<Output = Result<()>>>(
        &mut self,
        dispatch: &Dispatch,
        text: &str,
        mode: crate::InputMode,
        mut before_insert: impl FnMut() -> F,
    ) -> Result<()> {
        if mode == crate::InputMode::Human && !text.is_empty() {
            for ch in text.chars() {
                before_insert().await?;
                // A newline is the Enter key, which Chrome only inserts as "\r".
                let (key, typed) = if ch == '\n' {
                    ("Enter".to_string(), "\r".to_string())
                } else {
                    (ch.to_string(), ch.to_string())
                };
                let (code, virtual_key, shift) = crate::keyboard::char_key(ch);
                let mut event = json!({"type":"keyDown","key":key,"code":code,"text":typed,"unmodifiedText":typed,
                    "windowsVirtualKeyCode":virtual_key,"nativeVirtualKeyCode":virtual_key,"modifiers":if shift { 8 } else { 0 }});
                dispatch
                    .send(
                        &self.session,
                        "Input.dispatchKeyEvent",
                        event.clone(),
                        false,
                    )
                    .await?;
                pause_ms(15..45).await;
                event["type"] = json!("keyUp");
                if let Some(fields) = event.as_object_mut() {
                    fields.remove("text");
                    fields.remove("unmodifiedText");
                }
                dispatch
                    .send(&self.session, "Input.dispatchKeyEvent", event, false)
                    .await?;
                pause_ms(if ch == ' ' || ch.is_ascii_punctuation() {
                    90..220
                } else {
                    50..150
                })
                .await;
            }
        } else if mode == crate::InputMode::Sequential && !text.is_empty() {
            for ch in text.chars() {
                before_insert().await?;
                dispatch
                    .send(
                        &self.session,
                        "Input.insertText",
                        json!({"text":ch.to_string()}),
                        false,
                    )
                    .await?;
            }
        } else {
            before_insert().await?;
            dispatch
                .send(
                    &self.session,
                    "Input.insertText",
                    json!({"text":text}),
                    false,
                )
                .await?;
        }
        Ok(())
    }

    pub(crate) async fn drag(
        &mut self,
        dispatch: &Dispatch,
        x: f64,
        y: f64,
        dx: f64,
        dy: f64,
    ) -> Result<()> {
        self.move_to(dispatch, x, y).await?;
        self.state
            .reserve_mouse_down(MouseButton::Left, (x, y))
            .map_err(crate::Error::input_state)?;
        dispatch.send(&self.session,"Input.dispatchMouseEvent",json!({"type":"mousePressed","x":x,"y":y,"button":"left","buttons":1,"clickCount":1,"force":0.5}),false).await?;
        for step in 1..=24 {
            let t = f64::from(step) / 24.0;
            let shifted = t - 1.0;
            let t = 1.0 + 2.70158 * shifted.powi(3) + 1.70158 * shifted.powi(2);
            let (px, py) = (x + dx * t, y + dy * t);
            self.state.mouse_buttons.insert(MouseButton::Left, (px, py));
            dispatch
                .send(
                    &self.session,
                    "Input.dispatchMouseEvent",
                    json!({"type":"mouseMoved","x":px,"y":py,"buttons":1,"force":0.5}),
                    false,
                )
                .await?;
            self.state.pointer = Some((px, py));
            tokio::time::sleep(DRAG_STEP_PAUSE).await;
        }
        dispatch.send(&self.session,"Input.dispatchMouseEvent",json!({"type":"mouseReleased","x":x+dx,"y":y+dy,"button":"left","buttons":0,"clickCount":1,"force":0.0}),false).await?;
        self.state.finish_mouse_up(MouseButton::Left);
        self.state.pointer = Some((x + dx, y + dy));
        Ok(())
    }

    pub(crate) async fn cleanup(&mut self) -> Result<()> {
        while let Some(id) = self.state.keys.keys().next().cloned() {
            let (key, modifiers) = self
                .state
                .key_up_event(&id)
                .map_err(crate::Error::input_state)?;
            dispatch_coordinated_key_event(
                &self.session,
                &key,
                crate::cdp::KeyEventType::KeyUp,
                modifiers,
            )
            .await?;
            self.state.finish_key_up(&id);
        }
        while let Some((&button, &(x, y))) = self.state.mouse_buttons.iter().next() {
            let buttons = self
                .state
                .mouse_up_mask(button)
                .map_err(crate::Error::input_state)?;
            dispatch_coordinated_mouse_event(
                &self.session,
                MouseEventType::MouseReleased,
                x,
                y,
                Some(button),
                Some(1),
                buttons,
            )
            .await?;
            self.state.finish_mouse_up(button);
        }
        Ok(())
    }
}