use std::sync::Arc;
use crate::net::{CookieJar, HttpClient, RobotsCache};
pub struct BrowserContext {
pub id: String,
pub cookie_jar: Arc<CookieJar>,
pub http_client: Arc<HttpClient>,
pub user_agent: String,
pub proxy_url: Option<String>,
pub robots_cache: Arc<RobotsCache>,
pub obey_robots: bool,
pub stealth: bool,
pub allow_file_access: bool,
}
impl BrowserContext {
pub fn new(id: String) -> Self {
let cookie_jar = Arc::new(CookieJar::new());
let http_client = Arc::new(HttpClient::with_cookie_jar(cookie_jar.clone()));
BrowserContext {
id,
cookie_jar,
http_client,
user_agent:
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
.to_string(),
proxy_url: None,
robots_cache: Arc::new(RobotsCache::new()),
obey_robots: false,
stealth: false,
allow_file_access: false,
}
}
pub fn with_options(id: String, proxy_url: Option<String>, stealth: bool) -> Self {
Self::with_full_options(id, proxy_url, stealth, None)
}
pub fn with_full_options(id: String, proxy_url: Option<String>, stealth: bool, user_agent: Option<String>) -> Self {
let cookie_jar = Arc::new(CookieJar::new());
let client = HttpClient::with_options(cookie_jar.clone(), proxy_url.as_deref());
let resolved_ua = user_agent.unwrap_or_else(|| {
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
.to_string()
});
if let Ok(mut guard) = client.user_agent.try_write() {
*guard = resolved_ua.clone();
}
let http_client = Arc::new(client);
BrowserContext {
id,
cookie_jar,
http_client,
user_agent: resolved_ua,
proxy_url,
robots_cache: Arc::new(RobotsCache::new()),
obey_robots: false,
stealth,
allow_file_access: false,
}
}
pub fn with_proxy(id: String, proxy_url: Option<String>) -> Self {
Self::with_options(id, proxy_url, false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn with_full_options_propagates_user_agent_to_http_client() {
let ctx = BrowserContext::with_full_options("test".to_string(), None, false, Some("Custom-UA/1.0".to_string()));
assert_eq!(ctx.user_agent, "Custom-UA/1.0");
let client_ua = ctx.http_client.user_agent.read().await.clone();
assert_eq!(client_ua, "Custom-UA/1.0");
}
#[tokio::test(flavor = "current_thread")]
async fn with_full_options_falls_back_to_chrome_default() {
let ctx = BrowserContext::with_full_options("test".to_string(), None, false, None);
assert!(ctx.user_agent.contains("Chrome"));
let client_ua = ctx.http_client.user_agent.read().await.clone();
assert!(client_ua.contains("Chrome"));
assert_eq!(ctx.user_agent, client_ua);
}
#[tokio::test(flavor = "current_thread")]
async fn with_options_keeps_default_user_agent() {
let ctx = BrowserContext::with_options("test".to_string(), None, false);
assert!(ctx.user_agent.contains("Chrome"));
}
}