agent_hub_runtime/core/preview/cookies/
mod.rs1mod apply;
3pub use apply::ImportResult;
4pub mod policy;
5pub mod sources;
6use super::{super::error::AppError, browser::Browsers};
7use policy::{Cookie, Skipped};
8use serde::Serialize;
9use serde_json::Value;
10use std::{
11 collections::{BTreeMap, HashMap},
12 sync::{Arc, Mutex},
13 time::{Duration, Instant},
14};
15#[derive(Clone, Serialize)]
16pub struct Target {
17 pub id: String,
18 pub profile: String,
19 pub profile_name: String,
20 pub revision: String,
21 pub title: String,
22 pub url: String,
23}
24#[derive(Serialize)]
25pub struct Summary {
26 pub id: String,
27 pub target: Target,
28 pub domains: BTreeMap<String, usize>,
29 pub total: usize,
30 pub importable: usize,
31 pub skipped: Skipped,
32}
33struct Batch {
34 target: Target,
35 cookies: Vec<Cookie>,
36 created: Instant,
37}
38#[derive(Default)]
39pub struct Imports {
40 batches: Mutex<HashMap<String, Batch>>,
41}
42impl Imports {
43 pub fn shared() -> Arc<Self> {
44 let imports = Arc::new(Self::default());
45 let weak = Arc::downgrade(&imports);
46 std::thread::spawn(move || {
47 while let Some(imports) = weak.upgrade() {
48 if let Ok(mut batches) = imports.batches.lock() {
49 batches.retain(|_, batch| batch.created.elapsed() < Duration::from_secs(300));
50 }
51 drop(imports);
52 std::thread::sleep(Duration::from_secs(1));
53 }
54 });
55 imports
56 }
57 pub fn prepare(
58 &self,
59 browsers: &Browsers,
60 id: &str,
61 revision: &str,
62 value: Value,
63 ) -> Result<Summary, AppError> {
64 let target = target(browsers, id, revision)?;
65 self.prepare_target(target, value)
66 }
67 pub fn prepare_target(&self, target: Target, value: Value) -> Result<Summary, AppError> {
69 let normalized = policy::normalize(value)?;
70 let mut domains = BTreeMap::new();
71 for cookie in &normalized.cookies {
72 *domains.entry(cookie.domain.clone()).or_default() += 1;
73 }
74 let summary = Summary {
75 id: uuid::Uuid::new_v4().to_string(),
76 target: target.clone(),
77 domains,
78 total: normalized.total,
79 importable: normalized.cookies.len(),
80 skipped: normalized.skipped,
81 };
82 let mut batches = self
83 .batches
84 .lock()
85 .map_err(|_| AppError::internal("Cookie imports unavailable"))?;
86 batches.retain(|_, batch| batch.created.elapsed() < Duration::from_secs(300));
87 if batches.len() >= 4 {
88 return Err(AppError::invalid_input(
89 "Close an existing cookie import preview before opening another",
90 ));
91 }
92 batches.insert(
93 summary.id.clone(),
94 Batch {
95 target,
96 cookies: normalized.cookies,
97 created: Instant::now(),
98 },
99 );
100 Ok(summary)
101 }
102 pub fn cancel(&self, id: &str) {
103 if let Ok(mut batches) = self.batches.lock() {
104 batches.remove(id);
105 }
106 }
107 pub fn clear(&self) {
108 if let Ok(mut batches) = self.batches.lock() {
109 batches.clear();
110 }
111 }
112 pub fn apply(
113 &self,
114 browsers: &Browsers,
115 id: &str,
116 domains: Vec<String>,
117 replace: bool,
118 ) -> Result<ImportResult, AppError> {
119 let (target, cookies) = self.take(id, domains)?;
120 browsers.apply_cookies(&target, cookies, replace)
121 }
122 pub fn take(&self, id: &str, domains: Vec<String>) -> Result<(Target, Vec<Cookie>), AppError> {
124 let batch = self
125 .batches
126 .lock()
127 .map_err(|_| AppError::internal("Cookie imports unavailable"))?
128 .remove(id)
129 .ok_or_else(|| {
130 AppError::cancelled("Cookie import preview expired; inspect the source again")
131 })?;
132 if batch.created.elapsed() >= Duration::from_secs(300) {
133 return Err(AppError::cancelled(
134 "Cookie import preview expired; inspect the source again",
135 ));
136 }
137 let allowed = batch
138 .cookies
139 .iter()
140 .map(|cookie| cookie.domain.clone())
141 .collect::<std::collections::HashSet<_>>();
142 if domains.is_empty() || domains.iter().any(|domain| !allowed.contains(domain)) {
143 return Err(AppError::invalid_input(
144 "Select domains from this import preview",
145 ));
146 }
147 let cookies = batch
148 .cookies
149 .into_iter()
150 .filter(|cookie| domains.contains(&cookie.domain))
151 .collect::<Vec<_>>();
152 Ok((batch.target, cookies))
153 }
154}
155pub(super) fn target(browsers: &Browsers, id: &str, revision: &str) -> Result<Target, AppError> {
156 let page = browsers.page(id)?;
157 let mut page = page
158 .lock()
159 .map_err(|_| AppError::internal("Browser page unavailable"))?;
160 let (current, url) = page.identity()?;
161 if current != revision {
162 return Err(AppError::cancelled(
163 "Page changed; inspect the cookie source again",
164 ));
165 }
166 let metadata = page
167 .metadata
168 .lock()
169 .map_err(|_| AppError::internal("Browser metadata unavailable"))?;
170 Ok(Target {
171 id: id.into(),
172 profile: metadata.profile.clone(),
173 profile_name: browsers
174 .profiles()?
175 .iter()
176 .find(|profile| profile.id == metadata.profile)
177 .map(|profile| profile.name.clone())
178 .unwrap_or_else(|| metadata.profile.clone()),
179 title: metadata.title.clone(),
180 url,
181 revision: current,
182 })
183}
184
185#[cfg(test)]
186#[path = "tests/policy.rs"]
187mod policy_tests;
188
189#[cfg(test)]
190#[path = "tests/browser.rs"]
191mod browser_tests;