yumush
Clone
https://git.tahinli.com/Tahinli/yumush.git
0 watching·0 forks·Rust·AGPL-3.0·6.8 MiB·27ceb05·Tahinli·8 hours ago·399 commits
| 1 | use std::io::Read; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use ureq::http::Uri; |
| 5 | use ureq::{Agent, Body, ResponseExt}; |
| 6 | |
| 7 | const MAX_LINKS: usize = 3; |
| 8 | const MAX_IMAGE: u64 = 5 * 1024 * 1024; |
| 9 | const MAX_HTML: u64 = 512 * 1024; |
| 10 | const MAX_TITLE: usize = 256; |
| 11 | const MAX_DESCRIPTION: usize = 512; |
| 12 | |
| 13 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 14 | pub enum EmbedKind { |
| 15 | Page, |
| 16 | Image, |
| 17 | } |
| 18 | |
| 19 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 20 | pub struct Embed { |
| 21 | pub url: String, |
| 22 | pub kind: EmbedKind, |
| 23 | pub site: Option<String>, |
| 24 | pub title: Option<String>, |
| 25 | pub description: Option<String>, |
| 26 | pub image: Option<Vec<u8>>, |
| 27 | } |
| 28 | |
| 29 | #[derive(Debug, PartialEq, Eq)] |
| 30 | struct Meta { |
| 31 | title: Option<String>, |
| 32 | description: Option<String>, |
| 33 | image: Option<String>, |
| 34 | site: Option<String>, |
| 35 | } |
| 36 | |
| 37 | pub fn urls(text: &str) -> Vec<String> { |
| 38 | let mut out: Vec<String> = Vec::new(); |
| 39 | let mut rest = text; |
| 40 | while out.len() < MAX_LINKS { |
| 41 | let Some(start) = find_scheme(rest) else { |
| 42 | break; |
| 43 | }; |
| 44 | let tail = &rest[start..]; |
| 45 | let end = tail |
| 46 | .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"')) |
| 47 | .unwrap_or(tail.len()); |
| 48 | rest = &tail[end..]; |
| 49 | let link = trim_link(&tail[..end]); |
| 50 | let has_host = link.find("://").is_some_and(|i| link.len() > i + 3); |
| 51 | if has_host && !out.iter().any(|u| u == link) { |
| 52 | out.push(link.to_owned()); |
| 53 | } |
| 54 | } |
| 55 | out |
| 56 | } |
| 57 | |
| 58 | fn find_scheme(s: &str) -> Option<usize> { |
| 59 | match (s.find("http://"), s.find("https://")) { |
| 60 | (Some(a), Some(b)) => Some(a.min(b)), |
| 61 | (a, b) => a.or(b), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn trim_link(s: &str) -> &str { |
| 66 | let mut s = s; |
| 67 | loop { |
| 68 | let t = s.trim_end_matches(['.', ',', ';', ':', '!', '?']); |
| 69 | let t = if t.ends_with(')') && t.matches(')').count() > t.matches('(').count() { |
| 70 | &t[..t.len() - 1] |
| 71 | } else { |
| 72 | t |
| 73 | }; |
| 74 | if t.len() == s.len() { |
| 75 | return s; |
| 76 | } |
| 77 | s = t; |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | pub fn fetch(url: &str) -> Option<Embed> { |
| 82 | if !is_web(url) { |
| 83 | return None; |
| 84 | } |
| 85 | let agent = Agent::new_with_config( |
| 86 | Agent::config_builder() |
| 87 | .timeout_global(Some(Duration::from_secs(5))) |
| 88 | .max_redirects(5) |
| 89 | .user_agent("yumush") |
| 90 | .http_status_as_error(true) |
| 91 | .build(), |
| 92 | ); |
| 93 | let mut resp = agent.get(url).call().ok()?; |
| 94 | let final_url = resp.get_uri().to_string(); |
| 95 | let mime = mime_of(&resp)?; |
| 96 | |
| 97 | if is_image(&mime) { |
| 98 | let image = read_image(&mut resp)?; |
| 99 | return Some(Embed { |
| 100 | url: url.to_owned(), |
| 101 | kind: EmbedKind::Image, |
| 102 | site: None, |
| 103 | title: last_segment(&final_url), |
| 104 | description: None, |
| 105 | image: Some(image), |
| 106 | }); |
| 107 | } |
| 108 | if mime != "text/html" { |
| 109 | return None; |
| 110 | } |
| 111 | |
| 112 | let mut bytes = Vec::new(); |
| 113 | resp.body_mut() |
| 114 | .as_reader() |
| 115 | .take(MAX_HTML) |
| 116 | .read_to_end(&mut bytes) |
| 117 | .ok()?; |
| 118 | let meta = parse_meta(&String::from_utf8_lossy(&bytes)); |
| 119 | |
| 120 | let image = meta |
| 121 | .image |
| 122 | .and_then(|src| resolve(&final_url, &src)) |
| 123 | .and_then(|img| fetch_image(&agent, &img)); |
| 124 | if meta.title.is_none() && image.is_none() { |
| 125 | return None; |
| 126 | } |
| 127 | |
| 128 | let host = final_url |
| 129 | .parse::<Uri>() |
| 130 | .ok() |
| 131 | .and_then(|u| u.host().map(str::to_owned)); |
| 132 | Some(Embed { |
| 133 | url: url.to_owned(), |
| 134 | kind: EmbedKind::Page, |
| 135 | site: meta.site.or(host), |
| 136 | title: meta.title, |
| 137 | description: meta.description, |
| 138 | image, |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | fn is_web(url: &str) -> bool { |
| 143 | url.parse::<Uri>() |
| 144 | .is_ok_and(|u| matches!(u.scheme_str(), Some("http" | "https"))) |
| 145 | } |
| 146 | |
| 147 | fn mime_of(resp: &ureq::http::Response<Body>) -> Option<String> { |
| 148 | let mime = resp.body().mime_type()?; |
| 149 | Some(mime.trim().to_ascii_lowercase()) |
| 150 | } |
| 151 | |
| 152 | fn is_image(mime: &str) -> bool { |
| 153 | matches!( |
| 154 | mime, |
| 155 | "image/png" | "image/jpeg" | "image/gif" | "image/webp" |
| 156 | ) |
| 157 | } |
| 158 | |
| 159 | fn read_image(resp: &mut ureq::http::Response<Body>) -> Option<Vec<u8>> { |
| 160 | resp.body_mut() |
| 161 | .with_config() |
| 162 | .limit(MAX_IMAGE) |
| 163 | .read_to_vec() |
| 164 | .ok() |
| 165 | } |
| 166 | |
| 167 | fn fetch_image(agent: &Agent, url: &str) -> Option<Vec<u8>> { |
| 168 | if !is_web(url) { |
| 169 | return None; |
| 170 | } |
| 171 | let mut resp = agent.get(url).call().ok()?; |
| 172 | if !is_image(&mime_of(&resp)?) { |
| 173 | return None; |
| 174 | } |
| 175 | read_image(&mut resp) |
| 176 | } |
| 177 | |
| 178 | fn last_segment(url: &str) -> Option<String> { |
| 179 | let path = url.parse::<Uri>().ok()?.path().to_owned(); |
| 180 | path.rsplit('/').find(|s| !s.is_empty()).map(str::to_owned) |
| 181 | } |
| 182 | |
| 183 | fn resolve(base: &str, src: &str) -> Option<String> { |
| 184 | let src = src.trim(); |
| 185 | if src.starts_with("http://") || src.starts_with("https://") { |
| 186 | return Some(src.to_owned()); |
| 187 | } |
| 188 | let base = base.parse::<Uri>().ok()?; |
| 189 | let scheme = base.scheme_str()?; |
| 190 | let authority = base.authority()?.as_str(); |
| 191 | if let Some(rest) = src.strip_prefix("//") { |
| 192 | return Some(format!("{scheme}://{rest}")); |
| 193 | } |
| 194 | if src.starts_with('/') { |
| 195 | return Some(format!("{scheme}://{authority}{src}")); |
| 196 | } |
| 197 | let path = base.path(); |
| 198 | let dir = match path.rfind('/') { |
| 199 | Some(i) => &path[..=i], |
| 200 | None => "/", |
| 201 | }; |
| 202 | Some(format!("{scheme}://{authority}{dir}{src}")) |
| 203 | } |
| 204 | |
| 205 | fn parse_meta(html: &str) -> Meta { |
| 206 | let lower = html.to_ascii_lowercase(); |
| 207 | let mut tags: Vec<(String, String)> = Vec::new(); |
| 208 | for (pos, _) in lower.match_indices("<meta") { |
| 209 | let mut key = None; |
| 210 | let mut content = None; |
| 211 | for (name, value) in attributes(&html[pos + 5..]) { |
| 212 | match name.as_str() { |
| 213 | "property" | "name" => key = Some(value), |
| 214 | "content" => content = Some(value), |
| 215 | _ => {} |
| 216 | } |
| 217 | } |
| 218 | if let (Some(k), Some(c)) = (key, content) { |
| 219 | tags.push((k.to_ascii_lowercase(), c)); |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | let found = |names: &[&str]| -> Option<String> { |
| 224 | names.iter().find_map(|n| { |
| 225 | tags.iter() |
| 226 | .find(|(k, _)| k.as_str() == *n) |
| 227 | .map(|(_, v)| v.clone()) |
| 228 | }) |
| 229 | }; |
| 230 | |
| 231 | let title = found(&["og:title", "twitter:title"]) |
| 232 | .or_else(|| tag_text(html, &lower, "<title", "</title")); |
| 233 | |
| 234 | Meta { |
| 235 | title: title |
| 236 | .map(|t| clean(&t, MAX_TITLE)) |
| 237 | .filter(|t| !t.is_empty()), |
| 238 | description: found(&["og:description", "twitter:description", "description"]) |
| 239 | .map(|d| clean(&d, MAX_DESCRIPTION)) |
| 240 | .filter(|d| !d.is_empty()), |
| 241 | image: found(&["og:image", "twitter:image"]).map(|i| i.trim().to_owned()), |
| 242 | site: found(&["og:site_name"]) |
| 243 | .map(|s| clean(&s, MAX_TITLE)) |
| 244 | .filter(|s| !s.is_empty()), |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | fn tag_text(html: &str, lower: &str, open: &str, close: &str) -> Option<String> { |
| 249 | let start = lower.find(open)?; |
| 250 | let body = start + lower[start..].find('>')? + 1; |
| 251 | let end = body + lower[body..].find(close)?; |
| 252 | Some(html[body..end].to_owned()) |
| 253 | } |
| 254 | |
| 255 | fn attributes(tag: &str) -> Vec<(String, String)> { |
| 256 | let mut out = Vec::new(); |
| 257 | let mut rest = tag; |
| 258 | loop { |
| 259 | rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == '/'); |
| 260 | if rest.is_empty() || rest.starts_with('>') { |
| 261 | break; |
| 262 | } |
| 263 | let end = rest |
| 264 | .find(|c: char| c.is_whitespace() || c == '=' || c == '>') |
| 265 | .unwrap_or(rest.len()); |
| 266 | let name = rest[..end].to_ascii_lowercase(); |
| 267 | rest = rest[end..].trim_start(); |
| 268 | let mut value = String::new(); |
| 269 | if let Some(after) = rest.strip_prefix('=') { |
| 270 | let after = after.trim_start(); |
| 271 | match after.chars().next() { |
| 272 | Some(q @ ('"' | '\'')) => { |
| 273 | let body = &after[1..]; |
| 274 | let close = body.find(q).unwrap_or(body.len()); |
| 275 | value = body[..close].to_owned(); |
| 276 | rest = &body[(close + 1).min(body.len())..]; |
| 277 | } |
| 278 | _ => { |
| 279 | let close = after |
| 280 | .find(|c: char| c.is_whitespace() || c == '>') |
| 281 | .unwrap_or(after.len()); |
| 282 | value = after[..close].to_owned(); |
| 283 | rest = &after[close..]; |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | out.push((name, value)); |
| 288 | } |
| 289 | out |
| 290 | } |
| 291 | |
| 292 | fn clean(s: &str, max: usize) -> String { |
| 293 | decode(s) |
| 294 | .split_whitespace() |
| 295 | .collect::<Vec<_>>() |
| 296 | .join(" ") |
| 297 | .chars() |
| 298 | .take(max) |
| 299 | .collect() |
| 300 | } |
| 301 | |
| 302 | fn decode(s: &str) -> String { |
| 303 | let mut out = String::new(); |
| 304 | let mut rest = s; |
| 305 | while let Some(i) = rest.find('&') { |
| 306 | out.push_str(&rest[..i]); |
| 307 | rest = &rest[i..]; |
| 308 | if let Some(semi) = rest.find(';').filter(|&j| j <= 10) |
| 309 | && let Some(c) = entity(&rest[1..semi]) |
| 310 | { |
| 311 | out.push(c); |
| 312 | rest = &rest[semi + 1..]; |
| 313 | continue; |
| 314 | } |
| 315 | out.push('&'); |
| 316 | rest = &rest[1..]; |
| 317 | } |
| 318 | out.push_str(rest); |
| 319 | out |
| 320 | } |
| 321 | |
| 322 | fn entity(e: &str) -> Option<char> { |
| 323 | match e { |
| 324 | "amp" => Some('&'), |
| 325 | "lt" => Some('<'), |
| 326 | "gt" => Some('>'), |
| 327 | "quot" => Some('"'), |
| 328 | _ => numeric(e), |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | fn numeric(e: &str) -> Option<char> { |
| 333 | match e.strip_prefix("#x") { |
| 334 | Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?), |
| 335 | None => char::from_u32(e.strip_prefix('#')?.parse().ok()?), |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | #[cfg(test)] |
| 340 | mod tests { |
| 341 | use super::*; |
| 342 | |
| 343 | #[test] |
| 344 | fn parse_meta_reads_mixed_attributes_and_entities() { |
| 345 | let html = r#"<title>Ignored</title><META content="Og "Title"" property="og:title"><meta name='description' content='It's 'here''><meta content="https://img.test/a.png" property="og:image"><meta property="og:site_name" content='Site'>"#; |
| 346 | let meta = parse_meta(html); |
| 347 | assert_eq!(meta.title.as_deref(), Some("Og \"Title\"")); |
| 348 | assert_eq!(meta.description.as_deref(), Some("It's 'here'")); |
| 349 | assert_eq!(meta.image.as_deref(), Some("https://img.test/a.png")); |
| 350 | assert_eq!(meta.site.as_deref(), Some("Site")); |
| 351 | assert_eq!( |
| 352 | parse_meta("<title> A\n B & C </title>") |
| 353 | .title |
| 354 | .as_deref(), |
| 355 | Some("A B & C") |
| 356 | ); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn urls_trims_punctuation_and_dedups() { |
| 361 | let text = "see (https://a.com/x), https://b.com/y. and <https://c.com/z>! https://a.com/x http://d.com/w?q=1 https://e.com"; |
| 362 | assert_eq!( |
| 363 | urls(text), |
| 364 | ["https://a.com/x", "https://b.com/y", "https://c.com/z"] |
| 365 | ); |
| 366 | assert_eq!(urls("https://w.org/a_(b)"), ["https://w.org/a_(b)"]); |
| 367 | } |
| 368 | } |