use crate::models::{Clip, ClipSource}; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct LibraryPaths { pub clip_root: PathBuf, pub thumbs_root: PathBuf, pub sessions_root: PathBuf, pub buffer_root: PathBuf, } impl LibraryPaths { pub fn new(root: impl Into) -> Self { let root = root.into(); Self { clip_root: root.join("clips"), thumbs_root: root.join("thumbs"), sessions_root: root.join("sessions"), buffer_root: root.join("buffer"), } } /// Builds paths while honoring a user-selected clip directory. Thumbs, /// sessions, and the rolling buffer stay under the library root. pub fn with_clip_root(root: impl Into, clip_root: impl Into) -> Self { let root = root.into(); Self { clip_root: clip_root.into(), thumbs_root: root.join("thumbs"), sessions_root: root.join("sessions"), buffer_root: root.join("buffer"), } } pub fn ensure(&self) -> io::Result<()> { fs::create_dir_all(&self.clip_root)?; fs::create_dir_all(&self.thumbs_root)?; fs::create_dir_all(&self.sessions_root)?; fs::create_dir_all(&self.buffer_root)?; Ok(()) } } pub fn clip_path( paths: &LibraryPaths, game_id: &str, created_at: SystemTime, clip_id: &str, ) -> PathBuf { let month_bucket = month_bucket(created_at); paths .clip_root .join(sanitize_path_component(game_id)) .join(month_bucket) .join(format!("{}.mp4", sanitize_path_component(clip_id))) } pub fn build_test_clip( paths: &LibraryPaths, clip_id: &str, session_id: &str, game_id: &str, duration: Duration, ) -> Clip { let created_at = SystemTime::now(); Clip { id: clip_id.to_string(), title: None, session_id: session_id.to_string(), game_id: game_id.to_string(), path: clip_path(paths, game_id, created_at, clip_id), thumbnail_path: Some(paths.thumbs_root.join(format!("{clip_id}.jpg"))), created_at, duration, source: ClipSource::ManualHotkey, event_type: None, tags: Vec::new(), upload_url: None, upload_provider: None, } } pub fn sanitize_path_component(value: &str) -> String { value .chars() .map(|ch| { if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' { ch } else { '-' } }) .collect::() .trim_matches('-') .to_string() } fn month_bucket(created_at: SystemTime) -> String { let days = created_at .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_secs() / 86_400; let approx_year = 1970 + days / 365; let approx_month = ((days % 365) / 31) + 1; format!("{approx_year:04}-{approx_month:02}") } pub fn is_inside_root(root: &Path, candidate: &Path) -> bool { let Ok(root) = root.canonicalize() else { return false; }; let Ok(candidate) = candidate.canonicalize() else { return false; }; candidate.starts_with(root) } #[derive(Debug, Clone, PartialEq, Eq)] pub struct StorageCleanupReport { pub deleted_files: usize, pub deleted_bytes: u64, pub remaining_bytes: u64, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StorageLevel { Ok, Warning, Critical, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct StorageSpace { pub total_bytes: u64, pub available_bytes: u64, pub level: StorageLevel, } impl StorageSpace { pub fn free_gb(&self) -> f64 { self.available_bytes as f64 / (1024.0 * 1024.0 * 1024.0) } } pub fn check_storage_space(root: &Path) -> StorageSpace { let disks = sysinfo::Disks::new_with_refreshed_list(); let mount = disks .list() .iter() .find(|disk| path_is_on_mount(root, disk.mount_point())) .or_else(|| disks.list().first()); let valid = |disk: Option<&sysinfo::Disk>| -> Option<(u64, u64)> { disk.map(|disk| (disk.total_space(), disk.available_space())) }; let (total, available) = valid(mount).unwrap_or((0, 0)); let warning_at = bytes_for_gb(5); let critical_at = bytes_for_gb(2); let level = if available < critical_at { StorageLevel::Critical } else if available < warning_at { StorageLevel::Warning } else { StorageLevel::Ok }; StorageSpace { total_bytes: total, available_bytes: available, level, } } fn bytes_for_gb(gb: u64) -> u64 { gb * 1024 * 1024 * 1024 } fn path_is_on_mount(path: &Path, mount: &Path) -> bool { let path = path .to_str() .map(|value| value.to_ascii_lowercase()) .unwrap_or_default(); let mount = mount .to_str() .map(|value| value.to_ascii_lowercase()) .unwrap_or_default(); path == mount || path.starts_with(&mount) } pub fn cleanup_oldest_files_until_under_limit( root: &Path, max_bytes: u64, ) -> io::Result { let mut files = collect_files(root)?; let mut total_bytes: u64 = files.iter().map(|file| file.bytes).sum(); let mut deleted_files = 0; let mut deleted_bytes = 0; files.sort_by_key(|file| file.modified_at); for file in files { if total_bytes <= max_bytes { break; } fs::remove_file(&file.path)?; total_bytes = total_bytes.saturating_sub(file.bytes); deleted_files += 1; deleted_bytes += file.bytes; } Ok(StorageCleanupReport { deleted_files, deleted_bytes, remaining_bytes: total_bytes, }) } #[derive(Debug, Clone)] struct FileFact { path: PathBuf, bytes: u64, modified_at: SystemTime, } fn collect_files(root: &Path) -> io::Result> { let mut files = Vec::new(); if !root.exists() { return Ok(files); } for entry in fs::read_dir(root)? { let entry = entry?; let path = entry.path(); if path.is_dir() { files.extend(collect_files(&path)?); } else { let metadata = entry.metadata()?; files.push(FileFact { path, bytes: metadata.len(), modified_at: metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH), }); } } Ok(files) } pub fn default_library_root() -> PathBuf { dirs::document_dir() .map(|docs| docs.join("ClipForge")) .or_else(|| dirs::home_dir().map(|home| home.join("ClipForge"))) .unwrap_or_else(|| { std::env::current_dir() .unwrap_or_else(|_| PathBuf::from(".")) .join("clipforge-library") }) } #[derive(Debug, Clone)] pub struct LibraryResolution { pub root: PathBuf, pub migrated_from: Option, } pub fn resolve_library_root() -> io::Result { let target = default_library_root(); let legacy = legacy_library_in_working_dir(); if let Some(legacy) = legacy { if legacy != target && !library_has_content(&target) { migrate_library(&legacy, &target)?; return Ok(LibraryResolution { root: target, migrated_from: Some(legacy), }); } } Ok(LibraryResolution { root: target, migrated_from: None, }) } fn legacy_library_in_working_dir() -> Option { let cwd = std::env::current_dir().ok()?; let candidate = cwd.join("clipforge-library"); candidate.is_dir().then_some(candidate) } fn library_has_content(path: &Path) -> bool { if path.join("settings.json").exists() || path.join("library.sqlite").exists() { return true; } if let Ok(mut entries) = fs::read_dir(path) { return entries.next().is_some(); } false } fn migrate_library(from: &Path, to: &Path) -> io::Result<()> { if let Some(parent) = to.parent() { fs::create_dir_all(parent)?; } if fs::rename(from, to).is_ok() { return Ok(()); } copy_dir_all(from, to)?; fs::remove_dir_all(from) } fn copy_dir_all(from: &Path, to: &Path) -> io::Result<()> { fs::create_dir_all(to)?; for entry in fs::read_dir(from)? { let entry = entry?; let target = to.join(entry.file_name()); if entry.file_type()?.is_dir() { copy_dir_all(&entry.path(), &target)?; } else { fs::copy(entry.path(), &target)?; } } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::env; use std::fs; #[test] fn sanitizes_path_components() { assert_eq!( sanitize_path_component("Counter Strike 2!"), "Counter-Strike-2" ); } #[test] fn cleanup_removes_old_files_until_under_limit() { let root = env::temp_dir().join(format!( "clipforge-cleanup-{}", SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_nanos() )); fs::create_dir_all(&root).expect("test root"); fs::write(root.join("one.tmp"), vec![1_u8; 10]).expect("file one"); fs::write(root.join("two.tmp"), vec![1_u8; 10]).expect("file two"); let report = cleanup_oldest_files_until_under_limit(&root, 10).expect("cleanup"); assert_eq!(report.deleted_files, 1); assert_eq!(report.remaining_bytes, 10); let _ = fs::remove_dir_all(root); } #[test] fn storage_space_reports_metrics_for_root() { let root = env::temp_dir(); let space = check_storage_space(&root); assert!(space.total_bytes > 0); assert!(space.available_bytes <= space.total_bytes); } #[test] fn path_is_on_mount_matches_drive_prefix() { let root = if cfg!(windows) { Path::new("C:/Users/ClipForge/Clips") } else { Path::new("/home/clipforge/clips") }; let mount = if cfg!(windows) { Path::new("C:") } else { Path::new("/home") }; assert!(path_is_on_mount(root, mount)); } #[test] fn default_library_root_prefers_documents_dir() { let root = default_library_root(); let docs = dirs::document_dir().expect("documents dir"); let expected = docs.join("ClipForge"); assert_eq!(root, expected); } #[test] fn migrates_legacy_library_to_target() { let temp_ns = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_nanos(); let from = std::env::temp_dir().join(format!("clipforge-from-{temp_ns}")); let to = std::env::temp_dir().join(format!("clipforge-to-{temp_ns}")); fs::create_dir_all(&from).expect("from"); fs::write(from.join("settings.json"), "{}").expect("settings"); fs::create_dir_all(to.parent().unwrap()).expect("parent"); assert!(from.exists()); assert!(!to.exists()); migrate_library(&from, &to).expect("migrate"); assert!(!from.exists()); assert!(to.join("settings.json").exists()); assert!(library_has_content(&to)); let _ = fs::remove_dir_all(to); } #[test] fn library_has_content_reports_empty_directory() { let temp_ns = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_nanos(); let dir = std::env::temp_dir().join(format!("clipforge-hascontent-{temp_ns}")); fs::create_dir_all(&dir).expect("dir"); assert!(!library_has_content(&dir)); let _ = fs::remove_dir_all(dir); } }