//! Loading pages and pictures. Every address, including each redirect, is //! checked against the filter before anything is requested. //! //! On computers and phones Clearwake talks to sites directly. In a web //! browser it can't (sites don't allow other pages to read them), so the web //! version asks clearwake.ai/fetch, which applies the same filter. use clearwake_core::{Filter, Url}; use std::sync::{Arc, Mutex}; #[allow(dead_code)] pub const MAX_PAGE: u64 = 12 * 1024 * 1024; #[allow(dead_code)] pub const MAX_IMAGE: u64 = 8 * 1024 * 1024; #[allow(dead_code)] pub const USER_AGENT: &str = "Mozilla/5.0 (compatible; Clearwake/0.1; +https://clearwake.ai)"; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Kind { Page, Image, } #[derive(Clone, Debug)] pub struct Job { pub generation: u64, pub kind: Kind, pub url: String, } pub enum Body { /// A page or text, with its final address after redirects. Page { url: String, content_type: String, bytes: Vec }, /// A decoded picture, RGBA. Image { width: usize, height: usize, rgba: Vec }, } pub struct Done { pub job: Job, pub result: Result, } pub type Inbox = Arc>>; /// Decode a picture and shrink it to at most `max` pixels wide. pub fn decode_image(bytes: &[u8], max: u32) -> Result { let img = image::load_from_memory(bytes).map_err(|_| String::from("This picture could not be read."))?; let img = if img.width() > max { let h = (img.height() as u64 * max as u64 / img.width() as u64).max(1) as u32; img.resize_exact(max, h, image::imageops::FilterType::Triangle) } else { img }; let mut rgba = img.to_rgba8(); lay_on_paper(&mut rgba); Ok(Body::Image { width: rgba.width() as usize, height: rgba.height() as usize, rgba: rgba.into_raw() }) } /// Web pictures with see-through parts (logos, diagrams) are drawn for a white page. On /// Clearwake's dark page their dark lines would vanish, so pictures bigger than an icon get /// a white backing, the way every page author expects them to be seen. fn lay_on_paper(rgba: &mut image::RgbaImage) { if rgba.width() <= 32 || rgba.height() <= 32 || rgba.pixels().all(|p| p[3] == 255) { return; } for p in rgba.pixels_mut() { let a = p[3] as u32; for c in 0..3 { p[c] = ((p[c] as u32 * a + 255 * (255 - a)) / 255) as u8; } p[3] = 255; } } fn blocked_message() -> String { String::from("Clearwake blocked this address because it serves ads or tracking.") } #[cfg(not(target_arch = "wasm32"))] mod native { use super::*; use std::collections::VecDeque; use std::io::Read; use std::sync::Condvar; pub struct Loader { queue: Arc<(Mutex>, Condvar)>, } impl Loader { pub fn new(inbox: Inbox, ctx: egui::Context, filter: Arc) -> Loader { let queue: Arc<(Mutex>, Condvar)> = Arc::new((Mutex::new(VecDeque::new()), Condvar::new())); #[allow(unused_mut)] let mut config = ureq::Agent::config_builder(); #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))] { // Trust the same certificates the computer itself trusts. config = config.tls_config(ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build()); } let agent: ureq::Agent = config .max_redirects(0) .http_status_as_error(false) .timeout_global(Some(std::time::Duration::from_secs(30))) .user_agent(USER_AGENT) .build() .into(); for _ in 0..6 { let queue = queue.clone(); let inbox = inbox.clone(); let ctx = ctx.clone(); let filter = filter.clone(); let agent = agent.clone(); std::thread::spawn(move || loop { let job = { let (lock, cv) = &*queue; let mut q = lock.lock().unwrap(); loop { if let Some(j) = q.pop_front() { break j; } q = cv.wait(q).unwrap(); } }; let result = fetch(&agent, &filter, &job); inbox.lock().unwrap().push(Done { job, result }); ctx.request_repaint(); }); } Loader { queue } } pub fn load(&self, job: Job) { let (lock, cv) = &*self.queue; let mut q = lock.lock().unwrap(); if job.kind == Kind::Page { // A new page makes every queued job for older pages pointless. q.retain(|j| j.generation >= job.generation); q.push_front(job); } else { q.push_back(job); } cv.notify_one(); } } fn fetch(agent: &ureq::Agent, filter: &Filter, job: &Job) -> Result { let mut url = Url::parse(&job.url).ok_or_else(|| String::from("That address doesn't look right."))?; for _ in 0..10 { if filter.blocks(&url) { return Err(blocked_message()); } let accept = match job.kind { Kind::Page => "text/html,application/xhtml+xml,text/plain;q=0.9,image/*;q=0.8", Kind::Image => "image/png,image/jpeg,image/gif,image/webp,image/*;q=0.8", }; let mut resp = agent .get(url.to_string()) .header("Accept", accept) .header("Accept-Language", "en-US,en;q=0.8") .call() .map_err(|e| friendly(&e.to_string()))?; let status = resp.status().as_u16(); if (300..400).contains(&status) { let loc = resp.headers().get("location").and_then(|v| v.to_str().ok()).unwrap_or(""); url = url.join(loc).ok_or_else(|| String::from("The site sent Clearwake somewhere it won't go."))?; continue; } if status >= 400 { return Err(format!("The site answered with an error ({status}).")); } let content_type = resp.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("").to_string(); let limit = if job.kind == Kind::Page { MAX_PAGE } else { MAX_IMAGE }; let mut bytes = Vec::new(); resp.body_mut() .as_reader() .take(limit) .read_to_end(&mut bytes) .map_err(|e| friendly(&e.to_string()))?; return match job.kind { Kind::Image => decode_image(&bytes, 1600), Kind::Page => Ok(Body::Page { url: url.to_string(), content_type, bytes }), }; } Err(String::from("The site redirected too many times.")) } fn friendly(e: &str) -> String { let l = e.to_ascii_lowercase(); if l.contains("dns") || l.contains("resolve") || l.contains("lookup") { String::from("Clearwake couldn't find that site. Check the address and your connection.") } else if l.contains("timed out") || l.contains("timeout") { String::from("The site took too long to answer.") } else if l.contains("certificate") || l.contains("tls") { String::from("This site's security certificate isn't valid, so Clearwake won't open it.") } else { format!("The page couldn't be loaded. ({e})") } } } #[cfg(not(target_arch = "wasm32"))] pub use native::Loader; #[cfg(target_arch = "wasm32")] mod web { use super::*; pub struct Loader { inbox: Inbox, ctx: egui::Context, filter: Arc, } impl Loader { pub fn new(inbox: Inbox, ctx: egui::Context, filter: Arc) -> Loader { Loader { inbox, ctx, filter } } pub fn load(&self, job: Job) { let inbox = self.inbox.clone(); let ctx = self.ctx.clone(); if let Some(u) = Url::parse(&job.url) { if self.filter.blocks(&u) { inbox.lock().unwrap().push(Done { job, result: Err(blocked_message()) }); ctx.request_repaint(); return; } } let proxied = format!("/fetch?url={}", clearwake_core::url::encode_component(&job.url)); let req = ehttp::Request::get(proxied); ehttp::fetch(req, move |res| { let result = match res { Err(e) => Err(format!("The page couldn't be loaded. ({e})")), Ok(r) if !r.ok => { let msg = String::from_utf8_lossy(&r.bytes).to_string(); Err(if msg.trim().is_empty() || msg.len() > 300 { format!("The site answered with an error ({}).", r.status) } else { msg }) } Ok(r) => match job.kind { Kind::Image => decode_image(&r.bytes, 1200), Kind::Page => Ok(Body::Page { url: r.headers.get("x-clearwake-url").map(|s| s.to_string()).unwrap_or_else(|| job.url.clone()), content_type: r.headers.get("content-type").unwrap_or("").to_string(), bytes: r.bytes, }), }, }; inbox.lock().unwrap().push(Done { job, result }); ctx.request_repaint(); }); } } } #[cfg(target_arch = "wasm32")] pub use web::Loader;