1use std::path::{Path, PathBuf};
27use std::process::Stdio;
28
29pub const WIRE_LIMIT_BYTES: usize = 2 * 1024 * 1024;
31
32pub const COPY_TARGET_BYTES: usize = 3 * 1024 * 1024 / 2;
35
36pub const MAX_EDGE: u32 = 2048;
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Stored {
43 pub original: PathBuf,
45 pub working: PathBuf,
47 pub bytes: usize,
49 pub working_bytes: usize,
51 pub size: Option<(u32, u32)>,
53 pub resized: bool,
55}
56
57impl Stored {
58 pub fn note(&self, name: &str) -> String {
61 let size = match self.size {
62 Some((w, h)) => format!("{w}×{h}"),
63 None => "unknown size".to_string(),
64 };
65 if self.resized {
66 let edge = self.size.map(|(w, h)| w.max(h)).unwrap_or(MAX_EDGE);
67 format!(
68 "[attached: {name} — the original is at {} ({} KB, {size}). You are looking at a \
69 {} px copy; use the original's path with `read_file` or a tool if you need the \
70 full resolution.]",
71 self.original.display(),
72 self.bytes / 1024,
73 edge.min(MAX_EDGE),
74 )
75 } else {
76 format!(
77 "[attached: {name} — {} KB, {size}, stored at {}. This is the original.]",
78 self.bytes / 1024,
79 self.original.display(),
80 )
81 }
82 }
83}
84
85#[derive(Debug, Clone)]
87pub struct Store {
88 root: PathBuf,
89 max_total_bytes: u64,
90 helper: Option<Helper>,
92}
93
94impl Store {
95 pub fn new(root: PathBuf, max_total_bytes: u64) -> Self {
97 Self {
98 root,
99 max_total_bytes,
100 helper: Helper::probe(),
101 }
102 }
103
104 pub fn with_helper(mut self, helper: Option<Helper>) -> Self {
107 self.helper = helper;
108 self
109 }
110
111 pub fn root(&self) -> &Path {
112 &self.root
113 }
114
115 pub fn keep(
120 &self,
121 session: &str,
122 name: &str,
123 mime: &str,
124 bytes: &[u8],
125 ) -> Result<Stored, String> {
126 if bytes.is_empty() {
127 return Err("the picture carries no bytes".to_string());
128 }
129 let (_, ext) = kind(mime, bytes)?;
130 let name = sanitise(name, ext);
131 let digest = hex16(bytes);
132 let dir = self.root.join(sanitise_segment(session));
133 let original = dir.join(format!("{digest}-{name}"));
134 std::fs::create_dir_all(&dir)
135 .map_err(|e| format!("could not make {}: {e}", dir.display()))?;
136 restrict(&dir, 0o700);
137 if !original.exists() {
138 let need = bytes.len() as u64;
139 let total = self.total_bytes();
140 if total + need > self.max_total_bytes {
141 let freed = self.prune(need)?;
142 if self.total_bytes() + need > self.max_total_bytes {
143 return Err(format!(
144 "the pictures on disk already hold {} MB of the {} MB budget{}; \
145 `/attachments clear` or a bigger `[attachments] max_total_bytes` makes \
146 room",
147 (self.total_bytes() - freed) / (1024 * 1024),
148 self.max_total_bytes / (1024 * 1024),
149 if freed > 0 {
150 format!(
151 ", and pruning {} MB of the oldest was not enough",
152 freed / (1024 * 1024)
153 )
154 } else {
155 String::new()
156 }
157 ));
158 }
159 }
160 write_private(&original, bytes)?;
161 } else {
162 touch(&original);
163 }
164 let size = dimensions(bytes);
165 if bytes.len() <= COPY_TARGET_BYTES {
167 return Ok(Stored {
168 working: original.clone(),
169 original,
170 bytes: bytes.len(),
171 working_bytes: bytes.len(),
172 size,
173 resized: false,
174 });
175 }
176 let Some(helper) = self.helper.clone() else {
177 return Err(format!(
178 "this picture is {} KB and has to be shrunk to {} KB for the request, and no \
179 helper was found to do it: install ImageMagick (`magick`), Python Pillow \
180 (`python3 -m pip install pillow`) or `ffmpeg`. The original is kept at {} — pass \
181 that path instead, and the agent can work on it at full size",
182 bytes.len() / 1024,
183 COPY_TARGET_BYTES / 1024,
184 original.display()
185 ));
186 };
187 let stem = original
188 .file_stem()
189 .map(|s| s.to_string_lossy().to_string())
190 .unwrap_or_else(|| digest.clone());
191 let out_name = format!("{stem}-{MAX_EDGE}.{ext}");
192 let working = dir.join(out_name);
193 if !working.exists() {
194 shrink(helper, &original, &working, ext)?;
195 }
196 let working_bytes = std::fs::metadata(&working)
197 .map(|m| m.len() as usize)
198 .unwrap_or(0);
199 if working_bytes == 0 || working_bytes > WIRE_LIMIT_BYTES {
200 return Err(format!(
201 "the copy at {} is {} KB, still over the {} KB a request may carry — the original \
202 is kept at {}",
203 working.display(),
204 working_bytes / 1024,
205 WIRE_LIMIT_BYTES / 1024,
206 original.display()
207 ));
208 }
209 Ok(Stored {
210 working,
211 original,
212 bytes: bytes.len(),
213 working_bytes,
214 size,
215 resized: true,
216 })
217 }
218
219 fn by_age(&self) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
221 let mut out = Vec::new();
222 let Ok(sessions) = std::fs::read_dir(&self.root) else {
223 return out;
224 };
225 for session in sessions.flatten() {
226 let Ok(files) = std::fs::read_dir(session.path()) else {
227 continue;
228 };
229 for file in files.flatten() {
230 let Ok(meta) = file.metadata() else {
231 continue;
232 };
233 if !meta.is_file() {
234 continue;
235 }
236 let when = meta
237 .modified()
238 .or_else(|_| meta.accessed())
239 .unwrap_or(std::time::UNIX_EPOCH);
240 out.push((file.path(), meta.len(), when));
241 }
242 }
243 out.sort_by_key(|(_, _, when)| *when);
244 out
245 }
246
247 pub fn total_bytes(&self) -> u64 {
249 self.by_age().iter().map(|(_, len, _)| *len).sum()
250 }
251
252 pub fn prune(&self, need: u64) -> Result<u64, String> {
257 let mut freed = 0;
258 for (path, len, _) in self.by_age() {
259 if freed >= need {
260 break;
261 }
262 match std::fs::remove_file(&path) {
263 Ok(()) => freed += len,
264 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
265 Err(e) => return Err(format!("could not remove {}: {e}", path.display())),
266 }
267 }
268 Ok(freed)
271 }
272
273 pub fn forget(&self, session: &str) -> Result<(), String> {
275 let dir = self.root.join(sanitise_segment(session));
276 match std::fs::remove_dir_all(&dir) {
277 Ok(()) => Ok(()),
278 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
279 Err(e) => Err(format!("could not remove {}: {e}", dir.display())),
280 }
281 }
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
286pub enum Helper {
287 Magick(PathBuf),
289 Pillow(PathBuf),
291 Ffmpeg(PathBuf),
292}
293
294impl Helper {
295 pub fn probe() -> Option<Self> {
297 for candidate in ["magick", "convert"] {
298 if let Some(path) = which(candidate) {
299 if works(&path, &["-version"]) {
300 return Some(Self::Magick(path));
301 }
302 }
303 }
304 if let Some(path) = which("python3") {
305 if works(
306 &path,
307 &[
308 "-c",
309 "import PIL.Image, sys; sys.exit(0 if PIL.Image.__version__ else 1)",
310 ],
311 ) {
312 return Some(Self::Pillow(path));
313 }
314 }
315 which("ffmpeg")
316 .filter(|path| works(path, &["-version"]))
317 .map(Self::Ffmpeg)
318 }
319
320 pub fn name(&self) -> String {
322 match self {
323 Self::Magick(p) => format!("ImageMagick ({})", p.display()),
324 Self::Pillow(p) => format!("Pillow via {}", p.display()),
325 Self::Ffmpeg(p) => format!("ffmpeg ({})", p.display()),
326 }
327 }
328}
329
330fn shrink(helper: Helper, from: &Path, to: &Path, ext: &str) -> Result<(), String> {
335 let jpeg = ext.eq_ignore_ascii_case("jpg") || ext.eq_ignore_ascii_case("jpeg");
336 let steps = if jpeg {
337 vec![(MAX_EDGE, 88), (MAX_EDGE, 78), (1536, 82), (1024, 80)]
338 } else {
339 vec![(MAX_EDGE, 0), (1536, 0), (1024, 0), (768, 0)]
341 };
342 let mut last = String::new();
343 for (edge, quality) in steps {
344 match run(helper.clone(), from, to, edge, quality) {
345 Ok(()) => {
346 let len = std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0);
347 if len > 0 && len <= COPY_TARGET_BYTES {
348 return Ok(());
349 }
350 last = format!("{} KB at {edge} px", len / 1024);
351 }
352 Err(e) => last = e,
353 }
354 }
355 if to.exists() && std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0) > 0 {
358 return Ok(());
359 }
360 Err(format!("could not shrink the picture ({last})"))
361}
362
363fn run(helper: Helper, from: &Path, to: &Path, edge: u32, quality: u32) -> Result<(), String> {
364 let (program, args) = match helper {
365 Helper::Magick(bin) => {
366 let mut args: Vec<String> = vec![
367 from.display().to_string(),
368 "-resize".into(),
369 format!("{edge}x{edge}>"),
370 "-strip".into(),
371 ];
372 if quality > 0 {
373 args.push("-quality".into());
374 args.push(quality.to_string());
375 }
376 args.push(to.display().to_string());
377 (bin, args)
378 }
379 Helper::Pillow(bin) => {
380 let script = "import sys\n\
383 from PIL import Image\n\
384 src, dst, edge, quality = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])\n\
385 im = Image.open(src)\n\
386 im.thumbnail((edge, edge))\n\
387 if quality:\n\
388 \x20 im.save(dst, quality=quality, optimize=True)\n\
389 else:\n\
390 \x20 im.save(dst, optimize=True)\n";
391 (
392 bin,
393 vec![
394 "-c".into(),
395 script.into(),
396 from.display().to_string(),
397 to.display().to_string(),
398 edge.to_string(),
399 quality.to_string(),
400 ],
401 )
402 }
403 Helper::Ffmpeg(bin) => {
404 let mut args: Vec<String> = vec![
405 "-y".into(),
406 "-loglevel".into(),
407 "error".into(),
408 "-i".into(),
409 from.display().to_string(),
410 "-vf".into(),
411 format!(
412 "scale='min({edge},iw)':'min({edge},ih)':force_original_aspect_ratio=decrease"
413 ),
414 ];
415 if quality > 0 {
416 args.push("-q:v".into());
417 args.push((31u32.saturating_sub(quality / 4)).clamp(2, 31).to_string());
419 }
420 args.push(to.display().to_string());
421 (bin, args)
422 }
423 };
424 let out = std::process::Command::new(&program)
425 .args(&args)
426 .stdin(Stdio::null())
427 .stdout(Stdio::null())
428 .stderr(Stdio::piped())
429 .output()
430 .map_err(|e| format!("{} could not run: {e}", program.display()))?;
431 if !out.status.success() {
432 let err = String::from_utf8_lossy(&out.stderr);
433 return Err(format!(
434 "{} failed on {}: {}",
435 program.display(),
436 from.display(),
437 err.lines().next().unwrap_or("no message")
438 ));
439 }
440 Ok(())
441}
442
443fn which(bin: &str) -> Option<PathBuf> {
444 let path = std::env::var_os("PATH")?;
445 std::env::split_paths(&path)
446 .map(|dir| dir.join(bin))
447 .find(|p| p.is_file())
448}
449
450fn works(bin: &Path, args: &[&str]) -> bool {
451 std::process::Command::new(bin)
452 .args(args)
453 .stdin(Stdio::null())
454 .stdout(Stdio::null())
455 .stderr(Stdio::null())
456 .status()
457 .map(|s| s.success())
458 .unwrap_or(false)
459}
460
461fn kind(mime: &str, bytes: &[u8]) -> Result<(&'static str, &'static str), String> {
464 let found = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
465 ("image/png", "png")
466 } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
467 ("image/jpeg", "jpg")
468 } else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
469 ("image/webp", "webp")
470 } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
471 ("image/gif", "gif")
472 } else {
473 return Err(format!(
474 "the bytes are not a picture this build can carry ({mime}); a picture has to be PNG, \
475 JPEG, WebP or GIF"
476 ));
477 };
478 Ok(found)
479}
480
481pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
486 if bytes.len() > 24 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") && &bytes[12..16] == b"IHDR" {
487 let w = u32::from_be_bytes(bytes[16..20].try_into().ok()?);
488 let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?);
489 return Some((w, h));
490 }
491 if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
492 if bytes.len() < 10 {
493 return None;
494 }
495 let w = u16::from_le_bytes([bytes[6], bytes[7]]) as u32;
496 let h = u16::from_le_bytes([bytes[8], bytes[9]]) as u32;
497 return Some((w, h));
498 }
499 if bytes.len() > 30 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
500 return webp_size(bytes);
501 }
502 if bytes.starts_with(&[0xFF, 0xD8]) {
503 return jpeg_size(bytes);
504 }
505 None
506}
507
508fn jpeg_size(bytes: &[u8]) -> Option<(u32, u32)> {
510 let mut i = 2;
511 while i + 9 < bytes.len() {
512 if bytes[i] != 0xFF {
513 i += 1;
514 continue;
515 }
516 let marker = bytes[i + 1];
517 if (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
519 i += 2;
520 continue;
521 }
522 let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
523 if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
525 let h = u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]) as u32;
526 let w = u16::from_be_bytes([bytes[i + 7], bytes[i + 8]]) as u32;
527 return Some((w, h));
528 }
529 i += 2 + len;
530 }
531 None
532}
533
534fn webp_size(bytes: &[u8]) -> Option<(u32, u32)> {
535 let chunk = &bytes[12..16];
536 match chunk {
537 b"VP8X" if bytes.len() >= 30 => {
538 let w = 1 + u32::from_le_bytes([bytes[24], bytes[25], bytes[26], 0]);
539 let h = 1 + u32::from_le_bytes([bytes[27], bytes[28], bytes[29], 0]);
540 Some((w, h))
541 }
542 b"VP8 " if bytes.len() >= 30 => {
543 let w = u16::from_le_bytes([bytes[26], bytes[27]]) as u32 & 0x3FFF;
544 let h = u16::from_le_bytes([bytes[28], bytes[29]]) as u32 & 0x3FFF;
545 Some((w, h))
546 }
547 b"VP8L" if bytes.len() >= 25 => {
548 let bits = u32::from_le_bytes([bytes[21], bytes[22], bytes[23], bytes[24]]);
549 let w = (bits & 0x3FFF) + 1;
550 let h = ((bits >> 14) & 0x3FFF) + 1;
551 Some((w, h))
552 }
553 _ => None,
554 }
555}
556
557fn hex16(bytes: &[u8]) -> String {
559 let digest = ring::digest::digest(&ring::digest::SHA256, bytes);
560 digest.as_ref()[..8]
561 .iter()
562 .map(|b| format!("{b:02x}"))
563 .collect()
564}
565
566fn sanitise(name: &str, ext: &str) -> String {
568 let stem = name
569 .rsplit('/')
570 .next()
571 .unwrap_or("picture")
572 .rsplit_once('.')
573 .map(|(stem, _)| stem)
574 .unwrap_or(name);
575 let cleaned: String = stem
576 .chars()
577 .map(|c| {
578 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
579 c
580 } else {
581 '-'
582 }
583 })
584 .collect();
585 let cleaned = cleaned.trim_matches('-');
586 let stem = if cleaned.is_empty() {
587 "picture"
588 } else {
589 cleaned
590 };
591 format!("{}.{ext}", stem.chars().take(40).collect::<String>())
592}
593
594fn sanitise_segment(session: &str) -> String {
595 let cleaned: String = session
596 .chars()
597 .map(|c| {
598 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
599 c
600 } else {
601 '-'
602 }
603 })
604 .collect();
605 if cleaned.is_empty() {
606 "unknown".to_string()
607 } else {
608 cleaned
609 }
610}
611
612fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
613 use std::io::Write;
614 let mut file = std::fs::OpenOptions::new()
615 .write(true)
616 .create_new(true)
617 .open(path)
618 .map_err(|e| format!("could not create {}: {e}", path.display()))?;
619 file.write_all(bytes)
620 .map_err(|e| format!("could not write {}: {e}", path.display()))?;
621 restrict(path, 0o600);
622 Ok(())
623}
624
625#[cfg(unix)]
626fn restrict(path: &Path, mode: u32) {
627 use std::os::unix::fs::PermissionsExt;
628 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
629}
630
631#[cfg(not(unix))]
632fn restrict(_path: &Path, _mode: u32) {}
633
634fn touch(path: &Path) {
635 if let Ok(file) = std::fs::OpenOptions::new().read(true).open(path) {
638 let _ = file.set_modified(std::time::SystemTime::now());
639 }
640}
641
642#[cfg(test)]
643mod tests {
644 use super::*;
645
646 pub fn png(width: u32, height: u32, rgb: [u8; 3]) -> Vec<u8> {
652 let mut raw = Vec::with_capacity((height * (1 + width * 3)) as usize);
653 for y in 0..height {
654 raw.push(0); for x in 0..width {
656 raw.extend_from_slice(&[
659 rgb[0].wrapping_add((x % 251) as u8),
660 rgb[1].wrapping_add((y % 241) as u8),
661 rgb[2],
662 ]);
663 }
664 }
665 let zlib = stored_zlib(&raw);
666 let mut png = Vec::new();
667 png.extend_from_slice(b"\x89PNG\r\n\x1a\n");
668 let mut ihdr = Vec::new();
669 ihdr.extend_from_slice(&width.to_be_bytes());
670 ihdr.extend_from_slice(&height.to_be_bytes());
671 ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); chunk(&mut png, b"IHDR", &ihdr);
673 chunk(&mut png, b"IDAT", &zlib);
674 chunk(&mut png, b"IEND", &[]);
675 png
676 }
677
678 fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
679 out.extend_from_slice(&(data.len() as u32).to_be_bytes());
680 out.extend_from_slice(kind);
681 out.extend_from_slice(data);
682 let mut crc_input = kind.to_vec();
683 crc_input.extend_from_slice(data);
684 out.extend_from_slice(&crc(&crc_input).to_be_bytes());
685 }
686
687 fn crc(data: &[u8]) -> u32 {
688 let mut crc = 0xFFFF_FFFFu32;
689 for byte in data {
690 crc ^= *byte as u32;
691 for _ in 0..8 {
692 let mask = (crc & 1).wrapping_neg();
693 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
694 }
695 }
696 !crc
697 }
698
699 fn stored_zlib(raw: &[u8]) -> Vec<u8> {
700 let mut out = vec![0x78, 0x01];
701 let mut rest = raw;
702 loop {
703 let take = rest.len().min(65535);
704 let last = take == rest.len();
705 out.push(if last { 1 } else { 0 });
706 out.extend_from_slice(&(take as u16).to_le_bytes());
707 out.extend_from_slice(&(!(take as u16)).to_le_bytes());
708 out.extend_from_slice(&rest[..take]);
709 rest = &rest[take..];
710 if last {
711 break;
712 }
713 }
714 let mut a: u32 = 1;
715 let mut b: u32 = 0;
716 for byte in raw {
717 a = (a + *byte as u32) % 65521;
718 b = (b + a) % 65521;
719 }
720 out.extend_from_slice(&((b << 16) | a).to_be_bytes());
721 out
722 }
723
724 fn store_with_helper() -> Option<(tempfile::TempDir, Store)> {
730 let helper = Helper::probe()?;
731 let dir = tempfile::tempdir().unwrap();
732 let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024)
733 .with_helper(Some(helper));
734 Some((dir, store))
735 }
736
737 fn store() -> (tempfile::TempDir, Store) {
738 let dir = tempfile::tempdir().unwrap();
739 let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024);
740 (dir, store)
741 }
742
743 #[test]
744 fn the_header_reads_the_size_without_decoding_anything() {
745 let picture = png(37, 19, [10, 20, 30]);
746 assert_eq!(dimensions(&picture), Some((37, 19)));
747 let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
749 jpeg.extend_from_slice(&[0u8; 14]);
750 jpeg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08]);
751 jpeg.extend_from_slice(&[0x01, 0x2C]); jpeg.extend_from_slice(&[0x01, 0xF4]); jpeg.extend_from_slice(&[0u8; 12]);
754 assert_eq!(dimensions(&jpeg), Some((500, 300)));
755 assert_eq!(dimensions(b"not a picture"), None);
756 }
757
758 #[test]
759 fn a_small_picture_is_its_own_working_copy_and_is_written_once() {
760 let (_dir, store) = store();
761 let picture = png(64, 64, [1, 2, 3]);
762 let first = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
763 assert!(!first.resized);
764 assert_eq!(first.working, first.original);
765 assert_eq!(std::fs::read(&first.original).unwrap(), picture);
766 let again = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
768 assert_eq!(again.original, first.original);
769 assert!(again.note("shot.png").contains("This is the original"));
770 }
771
772 #[test]
773 fn the_original_is_byte_identical_and_the_directory_is_private() {
774 use std::os::unix::fs::PermissionsExt;
775 let (_dir, store) = store();
776 let picture = png(64, 64, [9, 9, 9]);
777 let kept = store
778 .keep("s1", "../../etc/passwd.png", "image/png", &picture)
779 .unwrap();
780 assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
781 assert!(
782 kept.original.starts_with(store.root()),
783 "a name cannot escape the store: {}",
784 kept.original.display()
785 );
786 let mode = std::fs::metadata(&kept.original)
787 .unwrap()
788 .permissions()
789 .mode()
790 & 0o777;
791 assert_eq!(mode, 0o600);
792 let dir_mode = std::fs::metadata(kept.original.parent().unwrap())
793 .unwrap()
794 .permissions()
795 .mode()
796 & 0o777;
797 assert_eq!(dir_mode, 0o700);
798 }
799
800 #[test]
801 fn a_bigger_picture_is_kept_whole_and_shrunk_for_the_wire() {
802 let Some((_dir, store)) = store_with_helper() else {
803 return;
804 };
805 let picture = png(1200, 1200, [200, 30, 40]);
806 assert!(
807 picture.len() > COPY_TARGET_BYTES,
808 "the fixture has to be over the target: {} bytes",
809 picture.len()
810 );
811 let kept = store
812 .keep("s1", "photo.png", "image/png", &picture)
813 .unwrap_or_else(|why| panic!("{why}"));
814 assert!(kept.resized, "a picture over the target gets a copy");
815 assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
816 assert_ne!(kept.working, kept.original);
817 assert!(
818 kept.working_bytes <= COPY_TARGET_BYTES,
819 "the copy is {} bytes",
820 kept.working_bytes
821 );
822 let copy = std::fs::read(&kept.working).unwrap();
823 let (w, h) = dimensions(©).expect("the copy is a picture");
824 assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
825 let note = kept.note("photo.png");
826 assert!(note.contains("copy"), "{note}");
827 assert!(
828 note.contains(&kept.original.display().to_string()),
829 "{note}"
830 );
831 }
832
833 #[test]
834 fn the_original_keeps_its_pixels_while_the_copy_is_smaller() {
835 let Some((_dir, store)) = store_with_helper() else {
837 return;
838 };
839 let picture = png(3000, 2000, [90, 120, 150]);
840 assert!(picture.len() > 8 * 1024 * 1024, "{} bytes", picture.len());
841 let kept = store
842 .keep("s1", "camera.png", "image/png", &picture)
843 .unwrap_or_else(|why| panic!("{why}"));
844 assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
847 assert_eq!(dimensions(&picture), Some((3000, 2000)));
848 assert_eq!(kept.size, Some((3000, 2000)));
849 assert!(
851 kept.working_bytes <= COPY_TARGET_BYTES,
852 "{}",
853 kept.working_bytes
854 );
855 assert!(kept.working_bytes < kept.bytes);
856 let note = kept.note("camera.png");
858 assert!(note.contains("3000×2000"), "{note}");
859 assert!(note.contains("copy"), "{note}");
860 assert!(
861 note.contains(&kept.original.display().to_string()),
862 "{note}"
863 );
864 assert!(kept.working.exists());
866 assert_ne!(kept.working, kept.original);
867 }
868
869 #[test]
870 fn with_no_helper_the_original_is_still_kept_and_the_refusal_says_so() {
871 let (_dir, store) = store();
872 let store = store.with_helper(None);
873 let picture = png(1200, 1200, [5, 6, 7]);
874 let why = store
875 .keep("s1", "photo.png", "image/png", &picture)
876 .expect_err("no helper, no copy");
877 assert!(why.contains("ImageMagick"), "{why}");
878 assert!(why.contains("ffmpeg"), "{why}");
879 assert!(why.contains("original is kept"), "{why}");
880 }
881
882 #[test]
883 fn the_pillow_branch_shrinks_a_picture_on_its_own() {
884 let Some(pillow) = which("python3").filter(|p| works(p, &["-c", "import PIL.Image"]))
885 else {
886 return; };
888 let (_dir, store) = store();
889 let store = store.with_helper(Some(Helper::Pillow(pillow)));
890 let picture = png(1500, 900, [12, 200, 12]);
891 let kept = store.keep("s1", "wide.png", "image/png", &picture).unwrap();
892 assert!(kept.resized);
893 let copy = std::fs::read(&kept.working).unwrap();
894 let (w, h) = dimensions(©).expect("still a picture");
895 assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
896 assert!(
897 copy.len() < picture.len(),
898 "{} vs {}",
899 copy.len(),
900 picture.len()
901 );
902 }
903
904 #[test]
905 fn the_budget_prunes_the_oldest_first_and_then_refuses() {
906 let dir = tempfile::tempdir().unwrap();
907 let picture = png(1200, 1200, [1, 1, 1]);
908 let one = picture.len() as u64;
909 let Some(helper) = Helper::probe() else {
910 return;
911 };
912 let store = Store::new(dir.path().join("a"), one * 2).with_helper(Some(helper));
913 store.keep("old", "a.png", "image/png", &picture).unwrap();
914 std::thread::sleep(std::time::Duration::from_millis(20));
915 store.keep("new", "b.png", "image/png", &picture).unwrap();
916 std::thread::sleep(std::time::Duration::from_millis(20));
919 let third = png(1200, 1200, [2, 2, 2]);
920 store.keep("newer", "c.png", "image/png", &third).unwrap();
921 assert!(
922 std::fs::read_dir(store.root().join("old"))
923 .map(|mut d| d.next().is_none())
924 .unwrap_or(true),
925 "the oldest session was pruned"
926 );
927 assert!(
928 std::fs::read_dir(store.root().join("newer"))
929 .unwrap()
930 .count()
931 > 0
932 );
933 }
934
935 #[test]
936 fn a_budget_too_small_for_one_picture_names_the_budget() {
937 let dir = tempfile::tempdir().unwrap();
938 let picture = png(1200, 1200, [3, 3, 3]);
939 let store = Store::new(dir.path().join("a"), 1024);
940 let why = store
941 .keep("s1", "big.png", "image/png", &picture)
942 .expect_err("over budget");
943 assert!(why.contains("budget"), "{why}");
944 assert!(why.contains("max_total_bytes"), "{why}");
945 }
946
947 #[test]
948 fn forgetting_a_session_removes_its_pictures() {
949 let (_dir, store) = store();
950 let picture = png(32, 32, [0, 0, 0]);
951 let kept = store.keep("s1", "a.png", "image/png", &picture).unwrap();
952 store.forget("s1").unwrap();
953 assert!(!kept.original.exists());
954 store.forget("s1").unwrap(); }
956
957 #[test]
958 fn bytes_that_are_not_a_picture_are_refused_by_their_content_not_their_name() {
959 let (_dir, store) = store();
960 let why = store
961 .keep("s1", "notes.png", "image/png", b"plain text")
962 .expect_err("not a picture");
963 assert!(why.contains("not a picture"), "{why}");
964 }
965
966 #[test]
967 fn a_name_with_nothing_usable_in_it_still_lands_somewhere_sane() {
968 assert_eq!(sanitise("", "png"), "picture.png");
969 assert_eq!(sanitise("../../", "png"), "picture.png");
970 assert_eq!(sanitise("my shot.PNG", "png"), "my-shot.png");
971 }
972}