1use std::io::Cursor;
2use std::time::Duration;
3
4use image::imageops::FilterType;
5use image::{DynamicImage, ImageReader};
6use sha2::{Digest, Sha256};
7
8const MAX_DOWNLOAD_BYTES: u64 = 5 * 1024 * 1024;
10
11const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15);
13
14const THUMB_WIDTH: u32 = 256;
16const THUMB_HEIGHT: u32 = 256;
17
18const MAX_OUTPUT_BYTES: usize = 50 * 1024;
20
21const KEY_HEX_LEN: usize = 32;
23
24#[derive(Debug, Clone)]
26pub struct ThumbnailResult {
27 pub key: String,
29 pub data: Vec<u8>,
31}
32
33#[derive(Debug)]
35pub enum Error {
36 Download(String),
37 TooLarge(u64),
38 Decode(String),
39 Encode(String),
40}
41
42impl std::fmt::Display for Error {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 match self {
45 Self::Download(msg) => write!(f, "download failed: {msg}"),
46 Self::TooLarge(size) => write!(
47 f,
48 "source too large: {size} bytes (max {MAX_DOWNLOAD_BYTES})"
49 ),
50 Self::Decode(msg) => write!(f, "image decode failed: {msg}"),
51 Self::Encode(msg) => write!(f, "webp encode failed: {msg}"),
52 }
53 }
54}
55
56impl std::error::Error for Error {}
57
58#[must_use]
62pub fn thumbnail_key(source_url: &str) -> String {
63 let mut hasher = Sha256::new();
64 hasher.update(source_url.as_bytes());
65 let hash = hasher.finalize();
66 let hex = hex_encode(&hash);
67 format!("thumbnails/{}.webp", &hex[..KEY_HEX_LEN])
68}
69
70pub fn download(url: &str) -> Result<Vec<u8>, Error> {
79 let rt = tokio::runtime::Builder::new_current_thread()
80 .enable_all()
81 .build()
82 .map_err(|e| Error::Download(e.to_string()))?;
83
84 rt.block_on(download_async(url))
85}
86
87async fn download_async(url: &str) -> Result<Vec<u8>, Error> {
88 let client = reqwest::Client::builder()
89 .timeout(DOWNLOAD_TIMEOUT)
90 .build()
91 .map_err(|e| Error::Download(e.to_string()))?;
92
93 let response = client
94 .get(url)
95 .send()
96 .await
97 .map_err(|e| Error::Download(e.to_string()))?;
98
99 if !response.status().is_success() {
100 return Err(Error::Download(format!("HTTP {}", response.status())));
101 }
102
103 if let Some(len) = response.content_length()
104 && len > MAX_DOWNLOAD_BYTES
105 {
106 return Err(Error::TooLarge(len));
107 }
108
109 let bytes = response
110 .bytes()
111 .await
112 .map_err(|e| Error::Download(e.to_string()))?;
113
114 if bytes.len() as u64 > MAX_DOWNLOAD_BYTES {
115 return Err(Error::TooLarge(bytes.len() as u64));
116 }
117
118 Ok(bytes.to_vec())
119}
120
121pub fn resize_to_webp(bytes: &[u8]) -> Result<Vec<u8>, Error> {
128 let img = decode_image(bytes)?;
129 let thumb = cover_crop(&img, THUMB_WIDTH, THUMB_HEIGHT);
130 encode_webp(&thumb)
131}
132
133pub fn process_thumbnail(url: &str) -> Result<ThumbnailResult, Error> {
139 let key = thumbnail_key(url);
140 let bytes = download(url)?;
141 let data = resize_to_webp(&bytes)?;
142 Ok(ThumbnailResult { key, data })
143}
144
145fn decode_image(bytes: &[u8]) -> Result<DynamicImage, Error> {
146 let cursor = Cursor::new(bytes);
147 let reader = ImageReader::new(cursor)
148 .with_guessed_format()
149 .map_err(|e| Error::Decode(e.to_string()))?;
150 reader.decode().map_err(|e| Error::Decode(e.to_string()))
151}
152
153fn cover_crop(img: &DynamicImage, width: u32, height: u32) -> DynamicImage {
155 let (iw, ih) = (img.width(), img.height());
156 let target_ratio = f64::from(width) / f64::from(height);
157 let source_ratio = f64::from(iw) / f64::from(ih);
158
159 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
160 let cropped = if source_ratio > target_ratio {
161 let new_w = (f64::from(ih) * target_ratio) as u32;
162 let x = (iw - new_w) / 2;
163 img.crop_imm(x, 0, new_w, ih)
164 } else {
165 let new_h = (f64::from(iw) / target_ratio) as u32;
166 let y = (ih - new_h) / 2;
167 img.crop_imm(0, y, iw, new_h)
168 };
169
170 cropped.resize_exact(width, height, FilterType::Lanczos3)
171}
172
173fn encode_webp(img: &DynamicImage) -> Result<Vec<u8>, Error> {
174 let mut buf = Cursor::new(Vec::new());
175 img.write_with_encoder(image::codecs::webp::WebPEncoder::new_lossless(&mut buf))
176 .map_err(|e| Error::Encode(e.to_string()))?;
177
178 let data = buf.into_inner();
179 if data.len() > MAX_OUTPUT_BYTES {
180 return Err(Error::Encode(format!(
181 "output too large: {} bytes (max {MAX_OUTPUT_BYTES})",
182 data.len()
183 )));
184 }
185
186 Ok(data)
187}
188
189fn hex_encode(bytes: &[u8]) -> String {
190 bytes
191 .iter()
192 .fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
193 use std::fmt::Write;
194 let _ = write!(s, "{b:02x}");
195 s
196 })
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202 use image::ImageFormat;
203
204 #[test]
205 fn thumbnail_key_is_deterministic() {
206 let key1 = thumbnail_key("https://example.com/photo.jpg");
207 let key2 = thumbnail_key("https://example.com/photo.jpg");
208 assert_eq!(key1, key2);
209 }
210
211 #[test]
212 fn thumbnail_key_different_urls_differ() {
213 let key1 = thumbnail_key("https://example.com/a.jpg");
214 let key2 = thumbnail_key("https://example.com/b.jpg");
215 assert_ne!(key1, key2);
216 }
217
218 #[test]
219 fn thumbnail_key_format() {
220 let key = thumbnail_key("https://example.com/photo.jpg");
221 assert!(key.starts_with("thumbnails/"));
222 assert!(
223 std::path::Path::new(&key)
224 .extension()
225 .is_some_and(|ext| ext.eq_ignore_ascii_case("webp"))
226 );
227 let hex_part = &key["thumbnails/".len()..key.len() - ".webp".len()];
228 assert_eq!(hex_part.len(), KEY_HEX_LEN);
229 assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
230 }
231
232 #[test]
233 fn resize_to_webp_produces_valid_output() {
234 let img = DynamicImage::new_rgb8(800, 600);
235 let mut png_bytes = Vec::new();
236 img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
237 .ok();
238
239 let webp = resize_to_webp(&png_bytes);
240 assert!(webp.is_ok());
241 let data = webp.ok();
242 assert!(data.is_some());
243 let data = data.unwrap_or_default();
244 assert!(!data.is_empty());
245 assert!(data.len() <= MAX_OUTPUT_BYTES);
246 }
247
248 #[test]
249 fn resize_to_webp_is_256x256() {
250 let img = DynamicImage::new_rgb8(1024, 768);
251 let mut png_bytes = Vec::new();
252 img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
253 .ok();
254
255 let webp = resize_to_webp(&png_bytes);
256 assert!(webp.is_ok());
257 let data = webp.unwrap_or_default();
258
259 let decoded = ImageReader::new(Cursor::new(&data))
260 .with_guessed_format()
261 .ok()
262 .and_then(|r| r.decode().ok());
263 assert!(decoded.is_some());
264 let decoded = decoded.unwrap_or_else(|| DynamicImage::new_rgb8(0, 0));
265 assert_eq!(decoded.width(), THUMB_WIDTH);
266 assert_eq!(decoded.height(), THUMB_HEIGHT);
267 }
268
269 #[test]
270 fn resize_to_webp_portrait_image() {
271 let img = DynamicImage::new_rgb8(400, 1200);
272 let mut png_bytes = Vec::new();
273 img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
274 .ok();
275
276 let webp = resize_to_webp(&png_bytes);
277 assert!(webp.is_ok());
278 }
279
280 #[test]
281 fn resize_to_webp_square_image() {
282 let img = DynamicImage::new_rgb8(500, 500);
283 let mut png_bytes = Vec::new();
284 img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
285 .ok();
286
287 let webp = resize_to_webp(&png_bytes);
288 assert!(webp.is_ok());
289 }
290
291 #[test]
292 fn resize_to_webp_tiny_image() {
293 let img = DynamicImage::new_rgb8(16, 16);
294 let mut png_bytes = Vec::new();
295 img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
296 .ok();
297
298 let webp = resize_to_webp(&png_bytes);
299 assert!(webp.is_ok());
300 }
301
302 #[test]
303 fn resize_to_webp_invalid_bytes_fails() {
304 let result = resize_to_webp(b"not an image");
305 assert!(result.is_err());
306 }
307
308 #[test]
309 fn download_invalid_url_fails() {
310 let result = download("not-a-url");
311 assert!(result.is_err());
312 }
313
314 #[test]
315 fn hex_encode_works() {
316 assert_eq!(hex_encode(&[0x00, 0xff, 0xab]), "00ffab");
317 }
318}