browser_automation_cli/native/
cookies.rs1#![allow(missing_docs)]
2use serde::{Deserialize, Serialize};
3use serde_json::{json, Value};
4
5use super::cdp::client::CdpClient;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8#[serde(rename_all = "camelCase")]
9pub struct Cookie {
10 pub name: String,
11 pub value: String,
12 pub domain: String,
13 pub path: String,
14 #[serde(default)]
15 pub expires: f64,
16 #[serde(default)]
17 pub size: i64,
18 #[serde(default)]
19 pub http_only: bool,
20 #[serde(default)]
21 pub secure: bool,
22 #[serde(default)]
23 pub session: bool,
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub same_site: Option<String>,
26}
27
28pub async fn get_all_cookies(client: &CdpClient, session_id: &str) -> Result<Vec<Cookie>, String> {
29 let result = client
30 .send_command_no_params("Network.getAllCookies", Some(session_id))
31 .await?;
32
33 let cookies: Vec<Cookie> = result
34 .get("cookies")
35 .and_then(|v| serde_json::from_value(v.clone()).ok())
36 .unwrap_or_default();
37
38 Ok(cookies)
39}
40
41pub async fn get_cookies(
42 client: &CdpClient,
43 session_id: &str,
44 urls: Option<Vec<String>>,
45) -> Result<Vec<Cookie>, String> {
46 let params = match urls {
47 Some(ref u) if !u.is_empty() => json!({ "urls": u }),
48 _ => json!({}),
49 };
50
51 let result = client
52 .send_command("Network.getCookies", Some(params), Some(session_id))
53 .await?;
54
55 let cookies: Vec<Cookie> = result
56 .get("cookies")
57 .and_then(|v| serde_json::from_value(v.clone()).ok())
58 .unwrap_or_default();
59
60 Ok(cookies)
61}
62
63pub async fn set_cookies(
64 client: &CdpClient,
65 session_id: &str,
66 cookies: Vec<Value>,
67 current_url: Option<&str>,
68) -> Result<(), String> {
69 let cookies: Vec<Value> = cookies
70 .into_iter()
71 .map(|mut c| {
72 if c.get("url").is_none() && c.get("domain").is_none() {
74 if let Some(url) = current_url {
75 if let Some(m) = c.as_object_mut() {
76 m.insert("url".to_string(), Value::String(url.to_string()));
77 }
78 }
79 }
80 c
81 })
82 .collect();
83
84 client
85 .send_command(
86 "Network.setCookies",
87 Some(json!({ "cookies": cookies })),
88 Some(session_id),
89 )
90 .await?;
91
92 Ok(())
93}
94
95pub async fn clear_cookies(client: &CdpClient, session_id: &str) -> Result<(), String> {
96 client
97 .send_command_no_params("Network.clearBrowserCookies", Some(session_id))
98 .await?;
99 Ok(())
100}