Nacre/src/net/fetch.rs
astar76 2d8323a3e0 Nacre on Servo: first complete, reviewed, not yet built version
Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess):
tabs and windows, address bar with suggestions, history, bookmarks and
reading list, downloads with resume and external download managers,
encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists),
VPN through Tor or a proxy and secure DNS via a local bridge proxy,
picture in picture, Discord Rich Presence, media player and visualizer,
spell check, site apps, user scripts and styles, import from other
browsers, gamepads, Web Bluetooth, and every setting of the original Nacre
in a plain egui interface.

Not compiled yet; docs/HANDOFF.md has the first build checklist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 06:08:36 -06:00

94 lines
3.6 KiB
Rust

//! Nacre's own HTTP requests (filter lists, updates, suggestions, favicons for apps, downloads).
//! They go through the bridge like the pages do, so the VPN covers them too.
use std::sync::{Arc, OnceLock, RwLock};
use std::time::Duration;
/// Proxy URL of the bridge, set once at start. Empty = direct (bridge off).
static PROXY: OnceLock<RwLock<String>> = OnceLock::new();
static USER_AGENT: OnceLock<RwLock<String>> = OnceLock::new();
pub fn set_proxy(url: &str) {
let lock = PROXY.get_or_init(|| RwLock::new(String::new()));
if let Ok(mut current) = lock.write() {
*current = url.to_owned();
}
}
pub fn set_user_agent(ua: &str) {
let lock = USER_AGENT.get_or_init(|| RwLock::new(String::new()));
if let Ok(mut current) = lock.write() {
*current = ua.to_owned();
}
}
pub fn user_agent() -> String {
USER_AGENT.get().and_then(|l| l.read().ok().map(|s| s.clone())).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Nacre/{}", env!("CARGO_PKG_VERSION")))
}
/// An agent for requests to the internet. `timeout` covers the whole request.
pub fn agent(timeout: Option<Duration>) -> ureq::Agent {
let proxy = PROXY.get().and_then(|l| l.read().ok().map(|s| s.clone())).unwrap_or_default();
let proxy = if proxy.is_empty() { None } else { ureq::Proxy::new(&proxy).ok() };
let config = ureq::Agent::config_builder()
.timeout_global(timeout)
.timeout_connect(Some(Duration::from_secs(20)))
.proxy(proxy)
.user_agent(user_agent())
.http_status_as_error(false)
.max_redirects(10)
.build();
config.into()
}
/// An agent for local services (download managers): never through the bridge or VPN.
pub fn local_agent(timeout: Duration) -> ureq::Agent {
let config = ureq::Agent::config_builder().timeout_global(Some(timeout)).proxy(None).http_status_as_error(false).user_agent("Nacre").build();
config.into()
}
#[derive(Debug)]
pub struct Fetched {
pub status: u16,
pub body: Vec<u8>,
pub content_type: String,
}
impl Fetched {
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
}
/// GET a URL and read up to `limit` bytes of the body.
pub fn get(url: &str, headers: &[(&str, &str)], limit: u64, timeout: Duration) -> Result<Fetched, String> {
let mut request = agent(Some(timeout)).get(url);
for (k, v) in headers {
request = request.header(*k, *v);
}
let mut response = request.call().map_err(|e| e.to_string())?;
let status = response.status().as_u16();
let content_type = response.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("").to_owned();
let body = response.body_mut().with_config().limit(limit).read_to_vec().map_err(|e| e.to_string())?;
Ok(Fetched { status, body, content_type })
}
pub fn get_json(url: &str, timeout: Duration) -> Result<serde_json::Value, String> {
let fetched = get(url, &[("accept", "application/json")], 8 * 1024 * 1024, timeout)?;
if !fetched.ok() {
return Err(format!("the server answered {}", fetched.status));
}
serde_json::from_slice(&fetched.body).map_err(|e| e.to_string())
}
/// Run `job` on a worker thread and hand the result to `done` through the app's queue.
pub fn spawn<T: Send + 'static>(name: &str, job: impl FnOnce() -> T + Send + 'static, done: impl FnOnce(T) + Send + 'static) {
let _ = std::thread::Builder::new().name(format!("nacre-{name}")).spawn(move || done(job()));
}
/// A value filled in later by a worker thread.
pub type Slot<T> = Arc<std::sync::Mutex<Option<T>>>;