agentmux_srv_core/backend/
task_media.rs1use std::io::Read;
17use std::path::{Path, PathBuf};
18use std::time::{Duration, SystemTime};
19
20use image::ImageFormat;
21
22use super::attachments::process::{self, Sniffed};
23use super::storage::work_media::media_kind;
24
25pub const MAX_IMAGE_BYTES: u64 = 25 * 1024 * 1024;
27pub const MAX_RECORDING_BYTES: u64 = 100 * 1024 * 1024;
28pub const MAX_FILES_PER_CALL: usize = 10;
30const THUMB_EDGE: u32 = 256;
32const INCOMING_MAX_AGE: Duration = Duration::from_secs(60 * 60);
34const ORPHAN_MAX_AGE: Duration = Duration::from_secs(60 * 60);
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Sniff {
40 pub kind: &'static str,
41 pub mime: &'static str,
42 pub ext: &'static str,
43}
44
45pub fn sniff(head: &[u8]) -> Option<Sniff> {
48 let image = |mime, ext| Some(Sniff { kind: media_kind::IMAGE, mime, ext });
49 let recording = |mime, ext| Some(Sniff { kind: media_kind::RECORDING, mime, ext });
50 match process::sniff(head) {
51 Sniffed::Image(ImageFormat::Png) => return image("image/png", "png"),
52 Sniffed::Image(ImageFormat::Jpeg) => return image("image/jpeg", "jpg"),
53 Sniffed::Image(ImageFormat::Gif) => return image("image/gif", "gif"),
54 Sniffed::Image(ImageFormat::WebP) => return image("image/webp", "webp"),
55 Sniffed::Svg => return image("image/svg+xml", "svg"),
56 Sniffed::Image(_) | Sniffed::Heic | Sniffed::Avif => return None,
58 Sniffed::NotImage => {}
59 }
60 if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) {
61 return recording("video/webm", "webm");
62 }
63 if head.len() >= 12 && &head[4..8] == b"ftyp" {
64 return match &head[8..12] {
65 b"qt " => recording("video/quicktime", "mov"),
66 b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"mif1" | b"msf1" | b"avif" | b"avis" => None,
67 _ => recording("video/mp4", "mp4"),
68 };
69 }
70 None
71}
72
73pub fn max_bytes(kind: &str) -> u64 {
75 if kind == media_kind::RECORDING {
76 MAX_RECORDING_BYTES
77 } else {
78 MAX_IMAGE_BYTES
79 }
80}
81
82pub fn ext_of_mime(mime: &str) -> &'static str {
84 match mime {
85 "image/png" => "png",
86 "image/jpeg" => "jpg",
87 "image/gif" => "gif",
88 "image/webp" => "webp",
89 "image/svg+xml" => "svg",
90 "video/webm" => "webm",
91 "video/quicktime" => "mov",
92 _ => "mp4",
93 }
94}
95
96pub fn root_beside(isolated_work_store: Option<PathBuf>, shared_dir: Option<PathBuf>) -> Option<PathBuf> {
100 match isolated_work_store {
101 Some(store) => store.parent().map(|dir| dir.join("task-media")),
102 None => shared_dir.map(|dir| dir.join("task-media")),
103 }
104}
105
106#[cfg(not(any(test, feature = "test-support")))]
108pub fn default_root() -> Option<PathBuf> {
109 root_beside(
110 crate::registry::resolve_isolated_work_store_path(&super::base::get_mux_db_dir()),
111 crate::registry::shared_guard::shared_dir(),
112 )
113}
114
115#[cfg(any(test, feature = "test-support"))]
117pub fn default_root() -> Option<PathBuf> {
118 static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
119 Some(DIR.get_or_init(|| tempfile::tempdir().unwrap()).path().join("task-media"))
120}
121
122fn valid_sha(sha: &str) -> bool {
123 sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
124}
125
126pub fn blob_path(root: &Path, sha: &str, mime: &str) -> Option<PathBuf> {
129 valid_sha(sha).then(|| root.join(&sha[..2]).join(format!("{sha}.{}", ext_of_mime(mime))))
130}
131
132pub fn thumb_path(root: &Path, sha: &str) -> Option<PathBuf> {
134 valid_sha(sha).then(|| root.join(&sha[..2]).join(format!("{sha}.thumb.png")))
135}
136
137pub fn new_incoming_path(root: &Path) -> PathBuf {
139 root.join("incoming").join(format!("{}.part", uuid::Uuid::new_v4()))
140}
141
142pub fn read_head(path: &Path) -> std::io::Result<Vec<u8>> {
144 let mut f = std::fs::File::open(path)?;
145 let mut buf = vec![0u8; 1024];
146 let mut n = 0;
147 while n < buf.len() {
148 let got = f.read(&mut buf[n..])?;
149 if got == 0 {
150 break;
151 }
152 n += got;
153 }
154 buf.truncate(n);
155 Ok(buf)
156}
157
158pub fn commit(root: &Path, tmp: &Path, sha: &str, found: &Sniff) -> std::io::Result<PathBuf> {
161 let dest = blob_path(root, sha, found.mime).ok_or_else(|| std::io::Error::other("not a content hash"))?;
162 if let Some(dir) = dest.parent() {
163 std::fs::create_dir_all(dir)?;
164 }
165 if dest.exists() {
166 let _ = std::fs::remove_file(tmp);
167 } else if std::fs::rename(tmp, &dest).is_err() {
168 std::fs::copy(tmp, &dest)?;
169 let _ = std::fs::remove_file(tmp);
170 }
171 if found.kind == media_kind::IMAGE && found.mime != "image/svg+xml" {
172 if let Some(thumb) = thumb_path(root, sha).filter(|t| !t.exists()) {
173 let _ = make_thumb(&dest, &thumb);
174 }
175 }
176 Ok(dest)
177}
178
179fn make_thumb(src: &Path, dest: &Path) -> Result<(), String> {
180 process::header_dimensions(src).map_err(|e| e.to_string())?;
181 let mut reader = image::ImageReader::open(src).map_err(|e| e.to_string())?.with_guessed_format().map_err(|e| e.to_string())?;
182 let mut limits = image::Limits::default();
183 limits.max_image_width = Some(process::MAX_SIDE);
184 limits.max_image_height = Some(process::MAX_SIDE);
185 limits.max_alloc = Some(process::MAX_PIXELS * 4 + 64 * 1024 * 1024);
186 reader.limits(limits);
187 let img = reader.decode().map_err(|e| e.to_string())?;
188 img.thumbnail(THUMB_EDGE, THUMB_EDGE).save_with_format(dest, ImageFormat::Png).map_err(|e| e.to_string())
189}
190
191pub fn remove_content(root: &Path, sha: &str, mime: &str) -> bool {
193 let mut gone = false;
194 if let Some(p) = blob_path(root, sha, mime) {
195 gone = std::fs::remove_file(p).is_ok();
196 }
197 if let Some(p) = thumb_path(root, sha) {
198 let _ = std::fs::remove_file(p);
199 }
200 gone
201}
202
203pub fn sweep(root: &Path, named: impl Fn(&str) -> bool) -> usize {
207 let mut removed = 0;
208 let old = |meta: &std::fs::Metadata, age: Duration| {
209 meta.modified().ok().and_then(|m| SystemTime::now().duration_since(m).ok()).is_some_and(|a| a > age)
210 };
211 if let Ok(dir) = std::fs::read_dir(root.join("incoming")) {
212 for e in dir.flatten() {
213 if e.metadata().is_ok_and(|m| old(&m, INCOMING_MAX_AGE)) && std::fs::remove_file(e.path()).is_ok() {
214 removed += 1;
215 }
216 }
217 }
218 let Ok(shards) = std::fs::read_dir(root) else { return removed };
219 for shard in shards.flatten() {
220 if shard.file_name() == "incoming" || !shard.path().is_dir() {
221 continue;
222 }
223 let Ok(files) = std::fs::read_dir(shard.path()) else { continue };
224 for f in files.flatten() {
225 let name = f.file_name().to_string_lossy().into_owned();
226 let sha = name.split('.').next().unwrap_or("");
227 if !valid_sha(sha) || named(sha) {
228 continue;
229 }
230 if f.metadata().is_ok_and(|m| old(&m, ORPHAN_MAX_AGE)) && std::fs::remove_file(f.path()).is_ok() {
231 removed += 1;
232 }
233 }
234 }
235 removed
236}
237
238#[cfg(test)]
239#[path = "task_media_tests.rs"]
240mod tests;