1use std::path::{Path, PathBuf};
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5
6pub const MAX_IMAGE_BYTES: u64 = 20 * 1024 * 1024;
9
10pub const SUPPORTED_MIME_TYPES: &[&str] = &[
12 "image/png",
13 "image/jpeg",
14 "image/jpg",
15 "image/webp",
16 "image/gif",
17 "image/bmp",
18];
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ImageAttachment {
26 pub path: PathBuf,
28 pub mime_type: String,
30 pub base64_data: String,
32 pub size_bytes: u64,
34 #[serde(skip_serializing_if = "Option::is_none", default)]
37 pub dimensions: Option<(u32, u32)>,
38}
39
40#[derive(Debug)]
42pub enum ImageError {
43 FileNotFound(PathBuf),
44 IoError(std::io::Error),
45 TooLarge { path: PathBuf, size: u64, max: u64 },
46 UnsupportedMime { path: PathBuf, mime: String },
47 EncodeError(String),
48}
49
50impl std::fmt::Display for ImageError {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 match self {
53 ImageError::FileNotFound(p) => write!(f, "File not found: {}", p.display()),
54 ImageError::IoError(e) => write!(f, "I/O error: {}", e),
55 ImageError::TooLarge { path, size, max } => {
56 write!(
57 f,
58 "Image too large: {} ({} bytes, max {} bytes)",
59 path.display(),
60 size,
61 max
62 )
63 }
64 ImageError::UnsupportedMime { path, mime } => {
65 write!(
66 f,
67 "Unsupported image format '{}' for {}",
68 mime,
69 path.display()
70 )
71 }
72 ImageError::EncodeError(msg) => write!(f, "{}", msg),
73 }
74 }
75}
76
77impl std::error::Error for ImageError {}
78
79fn guess_mime(ext: &str) -> Option<&'static str> {
81 match ext.to_lowercase().as_str() {
82 "png" => Some("image/png"),
83 "jpg" | "jpeg" => Some("image/jpeg"),
84 "webp" => Some("image/webp"),
85 "gif" => Some("image/gif"),
86 "bmp" => Some("image/bmp"),
87 "svg" => Some("image/svg+xml"),
88 _ => None,
89 }
90}
91
92const BASE64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
94
95fn encode_base64(bytes: &[u8]) -> String {
97 let mut result = String::with_capacity(bytes.len().div_ceil(3) * 4);
98
99 for chunk in bytes.chunks(3) {
100 let b0 = chunk[0];
101 let b1 = chunk.get(1).copied().unwrap_or(0);
102 let b2 = chunk.get(2).copied().unwrap_or(0);
103
104 let i0 = (b0 >> 2) as usize;
105 let i1 = (((b0 & 0x03) << 4) | (b1 >> 4)) as usize;
106 let i2 = if chunk.len() > 1 {
107 (((b1 & 0x0f) << 2) | (b2 >> 6)) as usize
108 } else {
109 64
110 };
111 let i3 = if chunk.len() > 2 {
112 (b2 & 0x3f) as usize
113 } else {
114 64
115 };
116
117 result.push(BASE64_CHARS[i0] as char);
118 result.push(BASE64_CHARS[i1] as char);
119 result.push(if i2 < 64 { BASE64_CHARS[i2] } else { b'=' } as char);
120 result.push(if i3 < 64 { BASE64_CHARS[i3] } else { b'=' } as char);
121 }
122
123 result
124}
125
126impl ImageAttachment {
127 pub fn load(path: PathBuf) -> Result<Self, ImageError> {
132 let bytes = std::fs::read(&path).map_err(|e| {
134 if e.kind() == std::io::ErrorKind::NotFound {
135 ImageError::FileNotFound(path.clone())
136 } else {
137 ImageError::IoError(e)
138 }
139 })?;
140
141 let size = bytes.len() as u64;
142
143 if size > MAX_IMAGE_BYTES {
145 return Err(ImageError::TooLarge {
146 path: path.clone(),
147 size,
148 max: MAX_IMAGE_BYTES,
149 });
150 }
151
152 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
154 let mime = guess_mime(ext).ok_or_else(|| ImageError::UnsupportedMime {
155 path: path.clone(),
156 mime: ext.to_string(),
157 })?;
158
159 let base64_data = encode_base64(&bytes);
161
162 Ok(ImageAttachment {
163 path,
164 mime_type: mime.to_string(),
165 base64_data,
166 size_bytes: size,
167 dimensions: None,
168 })
169 }
170
171 pub fn load_from_str(path_str: &str) -> Result<Self, ImageError> {
178 let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
179 Self::load_from_str_in(&base, path_str)
180 }
181
182 pub fn load_from_str_in(base_dir: &Path, path_str: &str) -> Result<Self, ImageError> {
184 let path = PathBuf::from_str(path_str)
185 .map_err(|_| ImageError::FileNotFound(PathBuf::from(path_str)))?;
186 let abs_path = if path.is_absolute() {
187 path
188 } else {
189 base_dir.join(&path)
190 };
191 Self::load(abs_path)
192 }
193
194 pub fn data_uri(&self) -> String {
196 format!("data:{};base64,{}", self.mime_type, self.base64_data)
197 }
198
199 pub fn display_name(&self) -> String {
201 self.path
202 .file_name()
203 .map(|n| n.to_string_lossy().to_string())
204 .unwrap_or_else(|| self.path.to_string_lossy().to_string())
205 }
206
207 pub fn size_display(&self) -> String {
209 let bytes = self.size_bytes;
210 if bytes < 1024 {
211 format!("{} B", bytes)
212 } else if bytes < 1024 * 1024 {
213 format!("{:.1} KB", bytes as f64 / 1024.0)
214 } else {
215 format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
216 }
217 }
218
219 pub fn exists_on_disk(&self) -> bool {
221 self.path.is_file()
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 #[test]
230 fn test_encode_base64() {
231 assert_eq!(encode_base64(b"f"), "Zg==");
232 assert_eq!(encode_base64(b"fo"), "Zm8=");
233 assert_eq!(encode_base64(b"foo"), "Zm9v");
234 assert_eq!(encode_base64(b"foob"), "Zm9vYg==");
235 assert_eq!(encode_base64(b"fooba"), "Zm9vYmE=");
236 assert_eq!(encode_base64(b"foobar"), "Zm9vYmFy");
237 assert_eq!(encode_base64(b""), "");
239 }
240
241 use std::io::Write;
242
243 fn make_png() -> Vec<u8> {
244 vec![
246 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
249 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08, 0xD7, 0x63, 0xF8, 0xFF, 0xFF, 0x3F, 0x00, 0x05, 0xFE, 0x02, 0xFE, 0xDC,
251 0xCC, 0x59, 0xE7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
253 ]
254 }
255
256 #[test]
257 fn test_load_png() {
258 let dir = tempfile::tempdir().unwrap();
259 let file_path = dir.path().join("test.png");
260 let png_bytes = make_png();
261 let mut f = std::fs::File::create(&file_path).unwrap();
262 f.write_all(&png_bytes).unwrap();
263
264 let img = ImageAttachment::load(file_path.clone()).unwrap();
265 assert_eq!(img.mime_type, "image/png");
266 assert!(!img.base64_data.is_empty());
267 assert_eq!(img.size_bytes, png_bytes.len() as u64);
268 assert!(img.data_uri().starts_with("data:image/png;base64,"));
269 }
270
271 #[test]
272 fn test_load_jpeg() {
273 let dir = tempfile::tempdir().unwrap();
274 let file_path = dir.path().join("photo.jpg");
275 std::fs::write(&file_path, b"\xff\xd8\xff\xe0").unwrap();
277
278 let img = ImageAttachment::load(file_path).unwrap();
279 assert_eq!(img.mime_type, "image/jpeg");
280 }
281
282 #[test]
283 fn test_load_unsupported_extension() {
284 let dir = tempfile::tempdir().unwrap();
285 let file_path = dir.path().join("doc.pdf");
286 std::fs::write(&file_path, b"not a pdf").unwrap();
287
288 let err = ImageAttachment::load(file_path).unwrap_err();
289 match err {
290 ImageError::UnsupportedMime { .. } => {}
291 other => panic!("expected UnsupportedMime, got {:?}", other),
292 }
293 }
294
295 #[test]
296 fn test_load_nonexistent() {
297 let path = PathBuf::from("/nonexistent/image.png");
298 let err = ImageAttachment::load(path).unwrap_err();
299 match err {
300 ImageError::FileNotFound(_) => {}
301 other => panic!("expected FileNotFound, got {:?}", other),
302 }
303 }
304
305 #[test]
306 fn test_display_name() {
307 let img = ImageAttachment {
308 path: PathBuf::from("/tmp/screenshot.png"),
309 mime_type: "image/png".to_string(),
310 base64_data: "aaaa".to_string(),
311 size_bytes: 100,
312 dimensions: None,
313 };
314 assert_eq!(img.display_name(), "screenshot.png");
315 assert_eq!(img.size_display(), "100 B");
316 }
317
318 #[test]
319 fn test_size_display() {
320 let img = ImageAttachment {
321 path: PathBuf::from("/tmp/big.png"),
322 mime_type: "image/png".to_string(),
323 base64_data: "x".repeat(1024 * 1024),
324 size_bytes: 1_500_000,
325 dimensions: None,
326 };
327 assert!(img.size_display().contains("1.4 MB"));
328 }
329}