cosmic_applet_avestruz/
http.rs1use std::time::Duration;
16
17const FETCH_TIMEOUT: Duration = Duration::from_secs(20);
19
20pub fn client() -> reqwest::Client {
23 reqwest::Client::builder()
24 .https_only(true)
25 .timeout(FETCH_TIMEOUT)
26 .user_agent(concat!("avestruz/", env!("CARGO_PKG_VERSION")))
27 .build()
28 .unwrap_or_default()
29}
30
31pub async fn get(http: &reqwest::Client, url: &str, max_bytes: usize) -> Result<Vec<u8>, String> {
34 let response = http.get(url).send().await.map_err(|e| e.to_string())?;
35 read(response, max_bytes).await
36}
37
38pub async fn get_in_place(http: &reqwest::Client, url: &str, max_bytes: usize) -> Result<Vec<u8>, String> {
41 let response = http.get(url).send().await.map_err(|e| e.to_string())?;
42 if response.url().as_str() != url {
43 return Err("redirected".to_string());
44 }
45 read(response, max_bytes).await
46}
47
48async fn read(response: reqwest::Response, max_bytes: usize) -> Result<Vec<u8>, String> {
51 let mut response = response.error_for_status().map_err(|e| e.to_string())?;
52 if response.content_length().is_some_and(|length| length > max_bytes as u64) {
53 return Err(format!("larger than {max_bytes} bytes"));
54 }
55
56 let mut bytes = Vec::new();
59 while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
60 if bytes.len() + chunk.len() > max_bytes {
61 return Err(format!("larger than {max_bytes} bytes"));
62 }
63 bytes.extend_from_slice(&chunk);
64 }
65 Ok(bytes)
66}
67
68pub async fn get_as(http: &reqwest::Client, url: &str, accept: &str, max_bytes: usize) -> Result<Vec<u8>, String> {
72 let response = http.get(url).header(reqwest::header::ACCEPT, accept).send().await.map_err(|e| e.to_string())?;
73 let response = response.error_for_status().map_err(|e| e.to_string())?;
74 read(response, max_bytes).await
75}
76
77pub struct PageHead {
80 pub url: reqwest::Url,
81 pub bytes: Vec<u8>,
82}
83
84pub enum Linked {
86 Page(PageHead),
88 Video,
90}
91
92fn media_type(content_type: &str) -> &str {
95 content_type.split(';').next().unwrap_or_default().trim()
96}
97
98fn is_html(content_type: &str) -> bool {
100 let kind = media_type(content_type);
101 kind.eq_ignore_ascii_case("text/html") || kind.eq_ignore_ascii_case("application/xhtml+xml")
102}
103
104pub fn is_video(content_type: &str) -> bool {
106 media_type(content_type).get(.."video/".len()).is_some_and(|start| start.eq_ignore_ascii_case("video/"))
107}
108
109fn head_end(bytes: &[u8], from: usize) -> Option<usize> {
112 const ENDS: [&[u8]; 2] = [b"</head", b"<body"];
113 (from..bytes.len())
114 .find(|&at| ENDS.iter().any(|end| bytes.get(at..at + end.len()).is_some_and(|tag| tag.eq_ignore_ascii_case(end))))
115}
116
117pub async fn get_page_head(http: &reqwest::Client, url: &str, max_bytes: usize) -> Result<Linked, String> {
123 let response = http.get(url).header(reqwest::header::ACCEPT, "text/html").send().await.map_err(|e| e.to_string())?;
124 let mut response = response.error_for_status().map_err(|e| e.to_string())?;
125 let content_type = response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|value| value.to_str().ok());
126 if content_type.is_some_and(is_video) {
127 return Ok(Linked::Video);
128 }
129 if !content_type.is_some_and(is_html) {
130 return Err(format!("not a web page: {}", content_type.unwrap_or("of no kind it names")));
131 }
132
133 let url = response.url().clone();
134 let mut bytes = Vec::new();
135 while bytes.len() < max_bytes {
136 let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? else {
137 break;
138 };
139 let from = bytes.len().saturating_sub(8);
142 let room = max_bytes - bytes.len();
143 bytes.extend(chunk.iter().take(room));
144 if let Some(end) = head_end(&bytes, from) {
145 bytes.truncate(end);
146 break;
147 }
148 }
149 Ok(Linked::Page(PageHead { url, bytes }))
150}
151
152#[cfg(test)]
153mod tests {
154 use super::{head_end, is_html, is_video};
155
156 #[test]
157 fn a_web_page_is_what_the_server_calls_one() {
158 assert!(is_html("text/html"));
159 assert!(is_html("Text/HTML; charset=utf-8"));
160 assert!(is_html("application/xhtml+xml"));
161 for other in ["application/pdf", "video/mp4", "text/plain", "application/json", ""] {
162 assert!(!is_html(other), "{other}");
163 }
164 }
165
166 #[test]
167 fn a_video_is_what_the_server_calls_one() {
168 for video in ["video/mp4", "Video/WebM; codecs=vp9", " video/quicktime "] {
169 assert!(is_video(video), "{video}");
170 }
171 for other in ["text/html", "application/octet-stream", "audio/mpeg", "image/gif", "video", ""] {
172 assert!(!is_video(other), "{other}");
173 }
174 }
175
176 #[test]
177 fn the_head_of_a_page_ends_where_it_closes_or_the_body_opens() {
178 let page = b"<html><head><title>a</title></HEAD><body>text</body>";
179 assert_eq!(head_end(page, 0), Some(28));
180 assert_eq!(head_end(b"<title>a</title><BODY class=x>", 0), Some(16), "a head that is never closed");
181 assert_eq!(head_end(b"<html><head><title>a</title><meta", 0), None, "not there yet");
182 assert_eq!(head_end(page, 28), Some(28));
184 assert_eq!(head_end(page, 29), Some(35), "the body, having missed the end of the head");
185 }
186
187 #[test]
188 fn one_tls_provider_is_compiled_in() {
189 let _ = rustls::ClientConfig::builder();
194 let _ = super::client();
195 }
196}