1use std::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> {
174 let path = PathBuf::from_str(path_str)
175 .map_err(|_| ImageError::FileNotFound(PathBuf::from(path_str)))?;
176 let abs_path = if path.is_absolute() {
177 path
178 } else {
179 std::env::current_dir()
181 .unwrap_or_else(|_| PathBuf::from("."))
182 .join(&path)
183 };
184 Self::load(abs_path)
185 }
186
187 pub fn data_uri(&self) -> String {
189 format!("data:{};base64,{}", self.mime_type, self.base64_data)
190 }
191
192 pub fn display_name(&self) -> String {
194 self.path
195 .file_name()
196 .map(|n| n.to_string_lossy().to_string())
197 .unwrap_or_else(|| self.path.to_string_lossy().to_string())
198 }
199
200 pub fn size_display(&self) -> String {
202 let bytes = self.size_bytes;
203 if bytes < 1024 {
204 format!("{} B", bytes)
205 } else if bytes < 1024 * 1024 {
206 format!("{:.1} KB", bytes as f64 / 1024.0)
207 } else {
208 format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
209 }
210 }
211
212 pub fn exists_on_disk(&self) -> bool {
214 self.path.is_file()
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 #[test]
223 fn test_encode_base64() {
224 assert_eq!(encode_base64(b"f"), "Zg==");
225 assert_eq!(encode_base64(b"fo"), "Zm8=");
226 assert_eq!(encode_base64(b"foo"), "Zm9v");
227 assert_eq!(encode_base64(b"foob"), "Zm9vYg==");
228 assert_eq!(encode_base64(b"fooba"), "Zm9vYmE=");
229 assert_eq!(encode_base64(b"foobar"), "Zm9vYmFy");
230 assert_eq!(encode_base64(b""), "");
232 }
233
234 use std::io::Write;
235
236 fn make_png() -> Vec<u8> {
237 vec![
239 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,
242 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08, 0xD7, 0x63, 0xF8, 0xFF, 0xFF, 0x3F, 0x00, 0x05, 0xFE, 0x02, 0xFE, 0xDC,
244 0xCC, 0x59, 0xE7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
246 ]
247 }
248
249 #[test]
250 fn test_load_png() {
251 let dir = tempfile::tempdir().unwrap();
252 let file_path = dir.path().join("test.png");
253 let png_bytes = make_png();
254 let mut f = std::fs::File::create(&file_path).unwrap();
255 f.write_all(&png_bytes).unwrap();
256
257 let img = ImageAttachment::load(file_path.clone()).unwrap();
258 assert_eq!(img.mime_type, "image/png");
259 assert!(!img.base64_data.is_empty());
260 assert_eq!(img.size_bytes, png_bytes.len() as u64);
261 assert!(img.data_uri().starts_with("data:image/png;base64,"));
262 }
263
264 #[test]
265 fn test_load_jpeg() {
266 let dir = tempfile::tempdir().unwrap();
267 let file_path = dir.path().join("photo.jpg");
268 std::fs::write(&file_path, b"\xff\xd8\xff\xe0").unwrap();
270
271 let img = ImageAttachment::load(file_path).unwrap();
272 assert_eq!(img.mime_type, "image/jpeg");
273 }
274
275 #[test]
276 fn test_load_unsupported_extension() {
277 let dir = tempfile::tempdir().unwrap();
278 let file_path = dir.path().join("doc.pdf");
279 std::fs::write(&file_path, b"not a pdf").unwrap();
280
281 let err = ImageAttachment::load(file_path).unwrap_err();
282 match err {
283 ImageError::UnsupportedMime { .. } => {}
284 other => panic!("expected UnsupportedMime, got {:?}", other),
285 }
286 }
287
288 #[test]
289 fn test_load_nonexistent() {
290 let path = PathBuf::from("/nonexistent/image.png");
291 let err = ImageAttachment::load(path).unwrap_err();
292 match err {
293 ImageError::FileNotFound(_) => {}
294 other => panic!("expected FileNotFound, got {:?}", other),
295 }
296 }
297
298 #[test]
299 fn test_display_name() {
300 let img = ImageAttachment {
301 path: PathBuf::from("/tmp/screenshot.png"),
302 mime_type: "image/png".to_string(),
303 base64_data: "aaaa".to_string(),
304 size_bytes: 100,
305 dimensions: None,
306 };
307 assert_eq!(img.display_name(), "screenshot.png");
308 assert_eq!(img.size_display(), "100 B");
309 }
310
311 #[test]
312 fn test_size_display() {
313 let img = ImageAttachment {
314 path: PathBuf::from("/tmp/big.png"),
315 mime_type: "image/png".to_string(),
316 base64_data: "x".repeat(1024 * 1024),
317 size_bytes: 1_500_000,
318 dimensions: None,
319 };
320 assert!(img.size_display().contains("1.4 MB"));
321 }
322}