1
//! A minimal W3C WebDriver client for chromedriver.
2

            
3
use anyhow::{Context, Result, anyhow, bail};
4
use base64::Engine;
5
use bytes::Bytes;
6
use http_body_util::{BodyExt, Full};
7
use hyper::{Method, Request};
8
use hyper_util::client::legacy::{Client, connect::HttpConnector};
9
use hyper_util::rt::TokioExecutor;
10
use serde_json::{Value, json};
11
use std::time::{Duration, Instant};
12

            
13
use super::harness::READY_DEADLINE;
14

            
15
const NO_SUCH_ELEMENT: &str = "no such element";
16
const FIND_POLL: Duration = Duration::from_millis(100);
17
const ELEMENT: &str = "element-6066-11e4-a52e-4f735466cecf";
18

            
19
/// Keys of the WebDriver key table.
20
pub const ARROW_DOWN: &str = "\u{E015}";
21
pub const ENTER: &str = "\u{E007}";
22
pub const TAB: &str = "\u{E004}";
23
pub const SHIFT_TAB: &str = "\u{E008}\u{E004}\u{E000}";
24
pub const BACKSPACE: &str = "\u{E003}";
25

            
26
#[derive(Clone)]
27
pub struct Element(String);
28

            
29
pub struct Driver {
30
    client: Client<HttpConnector, Full<Bytes>>,
31
    session: String,
32
}
33

            
34
4093
async fn call(
35
4093
    client: &Client<HttpConnector, Full<Bytes>>,
36
4093
    method: Method,
37
4093
    url: &str,
38
4093
    body: Option<Value>,
39
4093
) -> Result<Value> {
40
4093
    let payload = body.map_or_else(String::new, |body| body.to_string());
41
4093
    let request = Request::builder()
42
4093
        .method(method)
43
4093
        .uri(url)
44
4093
        .header("content-type", "application/json")
45
4093
        .body(Full::new(Bytes::from(payload)))?;
46
4093
    let response = client.request(request).await?;
47
4093
    let status = response.status();
48
4093
    let bytes = response.into_body().collect().await?.to_bytes();
49
4093
    let reply: Value = serde_json::from_slice(&bytes)
50
        .with_context(|| format!("{url}: {}", String::from_utf8_lossy(&bytes)))?;
51
4093
    if !status.is_success() {
52
        bail!("{url} answered {status}: {}", reply["value"]);
53
4093
    }
54
4093
    Ok(reply["value"].clone())
55
4093
}
56

            
57
impl Driver {
58
    /// A headless Chrome session through the chromedriver at `endpoint`.
59
59
    pub async fn connect(endpoint: &str) -> Result<Self> {
60
59
        let client = Client::builder(TokioExecutor::new()).build_http();
61
59
        let capabilities = json!({
62
59
            "capabilities": {"alwaysMatch": {
63
59
                "browserName": "chrome",
64
59
                "goog:loggingPrefs": {"browser": "ALL"},
65
59
                "goog:chromeOptions": {"args": [
66
59
                    "--headless=new", "--no-sandbox", "--disable-gpu",
67
59
                    "--disable-dev-shm-usage", "--window-size=1280,900",
68
                ]}
69
            }}
70
        });
71
59
        let reply = call(
72
59
            &client,
73
59
            Method::POST,
74
59
            &format!("{endpoint}/session"),
75
59
            Some(capabilities),
76
59
        )
77
59
        .await?;
78
59
        let id = reply["sessionId"]
79
59
            .as_str()
80
            .ok_or_else(|| anyhow!("no session id in {reply}"))?;
81
59
        Ok(Self {
82
59
            client,
83
59
            session: format!("{endpoint}/session/{id}"),
84
59
        })
85
59
    }
86

            
87
3663
    async fn post(&self, path: &str, body: Value) -> Result<Value> {
88
3663
        let url = format!("{}{path}", self.session);
89
3663
        call(&self.client, Method::POST, &url, Some(body)).await
90
3663
    }
91

            
92
314
    async fn get(&self, path: &str) -> Result<Value> {
93
314
        let url = format!("{}{path}", self.session);
94
314
        call(&self.client, Method::GET, &url, None).await
95
314
    }
96

            
97
57
    pub async fn quit(&self) -> Result<()> {
98
57
        call(&self.client, Method::DELETE, &self.session, None)
99
57
            .await
100
57
            .map(drop)
101
57
    }
102

            
103
141
    pub async fn goto(&self, url: &str) -> Result<()> {
104
141
        self.post("/url", json!({ "url": url })).await.map(drop)
105
141
    }
106

            
107
83
    pub async fn set_size(&self, width: u32, height: u32) -> Result<()> {
108
83
        self.post("/window/rect", json!({ "width": width, "height": height }))
109
83
            .await
110
83
            .map(drop)
111
83
    }
112

            
113
1011
    fn element(value: &Value) -> Result<Element> {
114
1011
        value[ELEMENT]
115
1011
            .as_str()
116
1011
            .map(|id| Element(id.to_string()))
117
            .ok_or_else(|| anyhow!("not an element: {value}"))
118
1011
    }
119

            
120
    /// The element that has the focus.
121
244
    pub async fn active(&self) -> Result<Element> {
122
244
        Self::element(&self.get("/element/active").await?)
123
244
    }
124

            
125
184
    pub async fn find_all(&self, css: &str) -> Result<Vec<Element>> {
126
184
        let found = self
127
184
            .post(
128
184
                "/elements",
129
184
                json!({ "using": "css selector", "value": css }),
130
184
            )
131
184
            .await?;
132
184
        found
133
184
            .as_array()
134
184
            .map(|list| list.iter().map(Self::element).collect())
135
            .unwrap_or_else(|| Ok(Vec::new()))
136
184
    }
137

            
138
    /// Polls `path` while the element is absent; any other failure is final.
139
567
    async fn find_waiting(&self, path: &str, css: &str, what: &str) -> Result<Element> {
140
567
        let deadline = Instant::now() + READY_DEADLINE;
141
        loop {
142
567
            let found = self
143
567
                .post(path, json!({ "using": "css selector", "value": css }))
144
567
                .await;
145
567
            match found {
146
567
                Ok(value) => return Self::element(&value),
147
                Err(error) if !format!("{error:#}").contains(NO_SUCH_ELEMENT) => {
148
                    return Err(error).with_context(|| what.to_string());
149
                }
150
                Err(error) if Instant::now() > deadline => {
151
                    return Err(error).with_context(|| what.to_string());
152
                }
153
                Err(_) => tokio::time::sleep(FIND_POLL).await,
154
            }
155
        }
156
567
    }
157

            
158
553
    pub async fn find(&self, css: &str) -> Result<Element> {
159
553
        self.find_waiting("/element", css, &format!("find {css}"))
160
553
            .await
161
553
    }
162

            
163
14
    pub async fn find_in(&self, parent: &Element, css: &str) -> Result<Element> {
164
14
        self.find_waiting(
165
14
            &format!("/element/{}/element", parent.0),
166
14
            css,
167
14
            &format!("find {css} in an element"),
168
14
        )
169
14
        .await
170
14
    }
171

            
172
533
    pub async fn click(&self, element: &Element) -> Result<()> {
173
533
        self.post(&format!("/element/{}/click", element.0), json!({}))
174
533
            .await
175
533
            .map(drop)
176
533
    }
177

            
178
266
    pub async fn clear(&self, element: &Element) -> Result<()> {
179
266
        self.post(&format!("/element/{}/clear", element.0), json!({}))
180
266
            .await
181
266
            .map(drop)
182
266
    }
183

            
184
644
    pub async fn type_into(&self, element: &Element, text: &str) -> Result<()> {
185
644
        self.post(
186
644
            &format!("/element/{}/value", element.0),
187
644
            json!({ "text": text }),
188
644
        )
189
644
        .await
190
644
        .map(drop)
191
644
    }
192

            
193
    /// Runs `script` with `args` (elements pass as themselves) and returns
194
    /// its result.
195
1172
    pub async fn run(&self, script: &str, args: Vec<Value>) -> Result<Value> {
196
1172
        self.post("/execute/sync", json!({ "script": script, "args": args }))
197
1172
            .await
198
1172
    }
199

            
200
    /// Runs `script` with `args`; it returns by calling its last argument.
201
3
    pub async fn run_async(&self, script: &str, args: Vec<Value>) -> Result<Value> {
202
3
        self.post("/execute/async", json!({ "script": script, "args": args }))
203
3
            .await
204
3
    }
205

            
206
70
    pub async fn screenshot(&self) -> Result<Vec<u8>> {
207
70
        let shot = self.get("/screenshot").await?;
208
70
        let text = shot.as_str().ok_or_else(|| anyhow!("no screenshot"))?;
209
70
        Ok(base64::engine::general_purpose::STANDARD.decode(text)?)
210
70
    }
211

            
212
    /// The browser log entries since the last call.
213
70
    pub async fn log(&self) -> Result<Vec<Value>> {
214
70
        let entries = self.post("/se/log", json!({ "type": "browser" })).await?;
215
70
        Ok(entries.as_array().cloned().unwrap_or_default())
216
70
    }
217
}