use std::io::Read; use std::net::{IpAddr, ToSocketAddrs}; use std::time::Duration; use ureq::http::{Uri, header::LOCATION}; use ureq::{Agent, Body, ResponseExt}; const MAX_LINKS: usize = 3; const MAX_REDIRECTS: usize = 5; const MAX_IMAGE: u64 = 5 * 1024 * 1024; const MAX_HTML: u64 = 512 * 1024; const MAX_TITLE: usize = 256; const MAX_DESCRIPTION: usize = 512; #[derive(Debug, Clone, PartialEq, Eq)] pub enum EmbedKind { Page, Image, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Embed { pub url: String, pub kind: EmbedKind, pub site: Option, pub title: Option, pub description: Option, pub image: Option>, } #[derive(Debug, PartialEq, Eq)] struct Meta { title: Option, description: Option, image: Option, site: Option, } pub fn urls(text: &str) -> Vec { let mut out: Vec = Vec::new(); let mut rest = text; while out.len() < MAX_LINKS { let Some(start) = find_scheme(rest) else { break; }; let tail = &rest[start..]; let end = tail .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"')) .unwrap_or(tail.len()); rest = &tail[end..]; let link = trim_link(&tail[..end]); let has_host = link.find("://").is_some_and(|i| link.len() > i + 3); if has_host && !out.iter().any(|u| u == link) { out.push(link.to_owned()); } } out } fn find_scheme(s: &str) -> Option { s.find("http://") .into_iter() .chain(s.find("https://")) .min() } fn trim_link(s: &str) -> &str { let mut s = s; loop { let t = s.trim_end_matches(['.', ',', ';', ':', '!', '?']); let t = if t.ends_with(')') && t.matches(')').count() > t.matches('(').count() { &t[..t.len() - 1] } else { t }; if t.len() == s.len() { return s; } s = t; } } pub fn fetch(url: &str) -> Option { let agent = Agent::new_with_config( Agent::config_builder() .timeout_global(Some(Duration::from_secs(5))) .max_redirects(0) .user_agent("yumush") .http_status_as_error(true) .build(), ); let mut resp = get(&agent, url)?; let final_url = resp.get_uri().to_string(); let mime = mime_of(&resp)?; if is_image(&mime) { let image = read_image(&mut resp)?; return Some(Embed { url: url.to_owned(), kind: EmbedKind::Image, site: None, title: last_segment(&final_url), description: None, image: Some(image), }); } if mime != "text/html" { return None; } let mut bytes = Vec::new(); resp.body_mut() .as_reader() .take(MAX_HTML) .read_to_end(&mut bytes) .ok()?; let meta = parse_meta(&String::from_utf8_lossy(&bytes)); let image = meta .image .and_then(|src| resolve(&final_url, &src)) .and_then(|img| fetch_image(&agent, &img)); if meta.title.is_none() && image.is_none() { return None; } let host = final_url .parse::() .ok() .and_then(|u| u.host().map(str::to_owned)); Some(Embed { url: url.to_owned(), kind: EmbedKind::Page, site: meta.site.or(host), title: meta.title, description: meta.description, image, }) } fn get(agent: &Agent, url: &str) -> Option> { let mut url = url.to_owned(); for _ in 0..=MAX_REDIRECTS { if !public(&url) { return None; } let resp = agent.get(&url).call().ok()?; if !resp.status().is_redirection() { return Some(resp); } let location = resp.headers().get(LOCATION)?.to_str().ok()?; url = resolve(&url, location)?; } None } fn public(url: &str) -> bool { let Ok(uri) = url.parse::() else { return false; }; let default_port = match uri.scheme_str() { Some("http") => 80, Some("https") => 443, _ => return false, }; let Some(host) = uri.host() else { return false; }; let host = host.trim_start_matches('[').trim_end_matches(']'); let Ok(addrs) = (host, uri.port_u16().unwrap_or(default_port)).to_socket_addrs() else { return false; }; let addrs: Vec<_> = addrs.collect(); !addrs.is_empty() && addrs.iter().all(|addr| routable(addr.ip())) } fn routable(ip: IpAddr) -> bool { match ip { IpAddr::V4(ip) => { let [a, b, ..] = ip.octets(); let shared = a == 100 && (b & 0xc0) == 64; !(a == 0 || shared || ip.is_private() || ip.is_loopback() || ip.is_link_local() || ip.is_broadcast() || ip.is_unspecified() || ip.is_multicast() || ip.is_documentation()) } IpAddr::V6(ip) => { if let Some(mapped) = ip.to_ipv4_mapped() { return routable(IpAddr::V4(mapped)); } let first = ip.segments()[0]; let unique_local = (first & 0xfe00) == 0xfc00; let link_local = (first & 0xffc0) == 0xfe80; !(ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() || unique_local || link_local) } } } fn mime_of(resp: &ureq::http::Response) -> Option { let mime = resp.body().mime_type()?; Some(mime.trim().to_ascii_lowercase()) } fn is_image(mime: &str) -> bool { matches!( mime, "image/png" | "image/jpeg" | "image/gif" | "image/webp" ) } fn read_image(resp: &mut ureq::http::Response) -> Option> { resp.body_mut() .with_config() .limit(MAX_IMAGE) .read_to_vec() .ok() } fn fetch_image(agent: &Agent, url: &str) -> Option> { let mut resp = get(agent, url)?; if !is_image(&mime_of(&resp)?) { return None; } read_image(&mut resp) } fn last_segment(url: &str) -> Option { let path = url.parse::().ok()?.path().to_owned(); path.rsplit('/').find(|s| !s.is_empty()).map(str::to_owned) } fn resolve(base: &str, src: &str) -> Option { let src = src.trim(); if src.starts_with("http://") || src.starts_with("https://") { return Some(src.to_owned()); } let base = base.parse::().ok()?; let scheme = base.scheme_str()?; let authority = base.authority()?.as_str(); if let Some(rest) = src.strip_prefix("//") { return Some(format!("{scheme}://{rest}")); } if src.starts_with('/') { return Some(format!("{scheme}://{authority}{src}")); } let path = base.path(); let dir = match path.rfind('/') { Some(i) => &path[..=i], None => "/", }; Some(format!("{scheme}://{authority}{dir}{src}")) } fn parse_meta(html: &str) -> Meta { let lower = html.to_ascii_lowercase(); let mut tags: Vec<(String, String)> = Vec::new(); for (pos, _) in lower.match_indices(" key = Some(value), "content" => content = Some(value), _ => {} } } if let (Some(k), Some(c)) = (key, content) { tags.push((k.to_ascii_lowercase(), c)); } } let found = |names: &[&str]| -> Option { names.iter().find_map(|n| { tags.iter() .find(|(k, _)| k.as_str() == *n) .map(|(_, v)| v.clone()) }) }; let title = found(&["og:title", "twitter:title"]) .or_else(|| tag_text(html, &lower, " Option { let start = lower.find(open)?; let body = start + lower[start..].find('>')? + 1; let end = body + lower[body..].find(close)?; Some(html[body..end].to_owned()) } fn attributes(tag: &str) -> Vec<(String, String)> { let mut out = Vec::new(); let mut rest = tag; loop { rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == '/'); if rest.is_empty() || rest.starts_with('>') { break; } let end = rest .find(|c: char| c.is_whitespace() || c == '=' || c == '>') .unwrap_or(rest.len()); let name = rest[..end].to_ascii_lowercase(); rest = rest[end..].trim_start(); let mut value = String::new(); if let Some(after) = rest.strip_prefix('=') { let after = after.trim_start(); match after.chars().next() { Some(q @ ('"' | '\'')) => { let body = &after[1..]; let close = body.find(q).unwrap_or(body.len()); value = body[..close].to_owned(); rest = &body[(close + 1).min(body.len())..]; } _ => { let close = after .find(|c: char| c.is_whitespace() || c == '>') .unwrap_or(after.len()); value = after[..close].to_owned(); rest = &after[close..]; } } } out.push((name, value)); } out } fn clean(s: &str, max: usize) -> String { decode(s) .split_whitespace() .collect::>() .join(" ") .chars() .take(max) .collect() } fn decode(s: &str) -> String { let mut out = String::new(); let mut rest = s; while let Some(i) = rest.find('&') { out.push_str(&rest[..i]); rest = &rest[i..]; if let Some(semi) = rest.find(';').filter(|&j| j <= 10) && let Some(c) = entity(&rest[1..semi]) { out.push(c); rest = &rest[semi + 1..]; continue; } out.push('&'); rest = &rest[1..]; } out.push_str(rest); out } fn entity(e: &str) -> Option { match e { "amp" => Some('&'), "lt" => Some('<'), "gt" => Some('>'), "quot" => Some('"'), _ => numeric(e), } } fn numeric(e: &str) -> Option { match e.strip_prefix("#x") { Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?), None => char::from_u32(e.strip_prefix('#')?.parse().ok()?), } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_meta_reads_mixed_attributes_and_entities() { let html = r#"Ignored"#; let meta = parse_meta(html); assert_eq!(meta.title.as_deref(), Some("Og \"Title\"")); assert_eq!(meta.description.as_deref(), Some("It's 'here'")); assert_eq!(meta.image.as_deref(), Some("https://img.test/a.png")); assert_eq!(meta.site.as_deref(), Some("Site")); assert_eq!( parse_meta(" A\n B & C ") .title .as_deref(), Some("A B & C") ); } #[test] fn urls_trims_punctuation_and_dedups() { let text = "see (https://a.com/x), https://b.com/y. and ! https://a.com/x http://d.com/w?q=1 https://e.com"; assert_eq!( urls(text), ["https://a.com/x", "https://b.com/y", "https://c.com/z"] ); assert_eq!(urls("https://w.org/a_(b)"), ["https://w.org/a_(b)"]); } }