1use std::collections::HashMap;
2
3use serde_json::json;
4
5use crate::client::CdpClient;
6use crate::error::Result;
7
8impl CdpClient {
9 pub async fn set_cookie(
10 &self,
11 name: &str,
12 value: &str,
13 url: Option<&str>,
14 domain: Option<&str>,
15 path: Option<&str>,
16 ) -> Result<()> {
17 let mut params = json!({ "name": name, "value": value });
18 if let Some(u) = url {
19 params["url"] = json!(u);
20 }
21 if let Some(d) = domain {
22 params["domain"] = json!(d);
23 }
24 if let Some(p) = path {
25 params["path"] = json!(p);
26 }
27 self.send_command("Network.setCookie", params).await?;
28 Ok(())
29 }
30
31 pub async fn delete_cookies(&self, name: &str, url: Option<&str>) -> Result<()> {
32 let mut params = json!({ "name": name });
33 if let Some(u) = url {
34 params["url"] = json!(u);
35 }
36 self.send_command("Network.deleteCookies", params).await?;
37 Ok(())
38 }
39
40 pub async fn set_extra_headers(&self, headers: &HashMap<String, String>) -> Result<()> {
41 self.send_command("Network.setExtraHTTPHeaders", json!({ "headers": headers }))
42 .await?;
43 Ok(())
44 }
45
46 pub async fn block_urls(&self, patterns: &[&str]) -> Result<()> {
47 self.send_command("Network.setBlockedURLs", json!({ "urls": patterns }))
48 .await?;
49 Ok(())
50 }
51
52 pub async fn get_response_body(&self, request_id: &str) -> Result<String> {
53 let result = self
54 .send_command(
55 "Network.getResponseBody",
56 json!({ "requestId": request_id }),
57 )
58 .await?;
59 let body = result["body"].as_str().unwrap_or("").to_string();
60 let encoded = result["base64Encoded"].as_bool().unwrap_or(false);
61 if encoded {
62 use base64::Engine;
63 let bytes = base64::engine::general_purpose::STANDARD
64 .decode(&body)
65 .unwrap_or_default();
66 Ok(String::from_utf8_lossy(&bytes).into_owned())
67 } else {
68 Ok(body)
69 }
70 }
71
72 pub async fn intercept_requests(&self, url_patterns: &[&str]) -> Result<()> {
73 self.enable_domain("Fetch").await?;
74 let patterns: Vec<_> = url_patterns
75 .iter()
76 .map(|p| json!({ "urlPattern": p, "requestStage": "Request" }))
77 .collect();
78 self.send_command("Fetch.enable", json!({ "patterns": patterns }))
79 .await?;
80 Ok(())
81 }
82
83 pub async fn continue_request(&self, request_id: &str) -> Result<()> {
84 self.send_command("Fetch.continueRequest", json!({ "requestId": request_id }))
85 .await?;
86 Ok(())
87 }
88
89 pub async fn fulfill_request(
90 &self,
91 request_id: &str,
92 status: u16,
93 body: &str,
94 content_type: &str,
95 ) -> Result<()> {
96 use base64::Engine;
97 let body_b64 = base64::engine::general_purpose::STANDARD.encode(body);
98 self.send_command(
99 "Fetch.fulfillRequest",
100 json!({
101 "requestId": request_id,
102 "responseCode": status,
103 "body": body_b64,
104 "responseHeaders": [{ "name": "content-type", "value": content_type }],
105 }),
106 )
107 .await?;
108 Ok(())
109 }
110}