//! 飞牛音乐播放缓存(容量限制 + LRU 逐出)。 //! //! 缓存目录:`{app_data}/music/cache`,文件 `guid.`(ext 缺省记 `bin`)。 //! 元数据:`index.json` → `{ "guid": { "size", "lastUsed", "file" } }`。 //! 超上限按 lastUsed 升序逐出,直到总占用低于上限。 use std::collections::HashMap; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; use serde_json::json; /// 单条缓存元数据 #[derive(Serialize, Deserialize, Clone)] pub struct CacheEntry { pub size: u64, pub last_used: u64, pub file: String, } pub struct CacheManager { root: PathBuf, index_path: PathBuf, } impl CacheManager { pub fn new(app_data_dir: &Path) -> Self { let root = app_data_dir.join("music").join("cache"); fs::create_dir_all(&root).ok(); let index_path = root.join("index.json"); Self { root, index_path } } /// 本地曲库标签缓存文件:{cache_root}/local-tags.json。 /// 记录 path -> {size, mtim, 标签},扫描时未变化的文件直接复用, /// 避免万级曲库每次都重新解析音频标签。 pub fn local_tags_path(&self) -> PathBuf { self.root.join("local-tags.json") } fn load_index(&self) -> HashMap { fs::read_to_string(&self.index_path) .ok() .and_then(|s| serde_json::from_str(&s).ok()) .unwrap_or_default() } fn save_index(&self, idx: &HashMap) { if let Ok(s) = serde_json::to_string(idx) { fs::write(&self.index_path, s).ok(); } } fn now_ms(&self) -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_millis() as u64) .unwrap_or(0) } /// 命中缓存:更新 lastUsed 并返回文件路径。 pub fn hit(&self, guid: &str) -> Option { let mut idx = self.load_index(); if let Some(e) = idx.get_mut(guid) { let path = self.root.join(&e.file); if path.exists() { e.last_used = self.now_ms(); self.save_index(&idx); return Some(path.to_string_lossy().to_string()); } idx.remove(guid); self.save_index(&idx); } None } /// 写入缓存(流式 chunk);按上限(GB)逐出。返回写入总字节数。 pub async fn put( &self, guid: &str, ext: &str, max_gb: u32, mut stream: impl futures_util::Stream> + Unpin, ) -> Result { let safe_guid = sanitize(guid); let ext = if ext.is_empty() { "bin" } else { ext }; let file = format!("{safe_guid}.{ext}"); let path = self.root.join(&file); let mut total: u64 = 0; let mut f = fs::File::create(&path).map_err(|e| format!("创建缓存文件失败: {e}"))?; while let Some(chunk) = futures_util::StreamExt::next(&mut stream).await { let chunk = chunk.map_err(|e| format!("读取流失败: {e}"))?; total += chunk.len() as u64; f.write_all(chunk.as_ref()).map_err(|e| format!("写入缓存失败: {e}"))?; } f.flush().ok(); let mut idx = self.load_index(); idx.insert( guid.to_string(), CacheEntry { size: total, last_used: self.now_ms(), file, }, ); self.save_index(&idx); self.evict(max_gb); Ok(total) } /// 按上限(GB)逐出。max_gb==0 视为全部清空。 fn evict(&self, max_gb: u32) { if max_gb == 0 { self.clear(); return; } let max_bytes = max_gb as u64 * 1024 * 1024 * 1024; let mut idx = self.load_index(); let mut total: u64 = idx.values().map(|e| e.size).sum(); let mut order: Vec<(String, u64)> = idx.iter().map(|(g, e)| (g.clone(), e.last_used)).collect(); order.sort_by_key(|(_, t)| *t); for (guid, _) in order { if total <= max_bytes { break; } if let Some(e) = idx.remove(&guid) { let _ = fs::remove_file(self.root.join(&e.file)); total = total.saturating_sub(e.size); } } self.save_index(&idx); } /// 当前占用与条目数。 pub fn status(&self) -> serde_json::Value { let idx = self.load_index(); let total: u64 = idx.values().map(|e| e.size).sum(); json!({ "count": idx.len(), "usedBytes": total, "usedMb": (total as f64 / 1024.0 / 1024.0 * 10.0).round() / 10.0, }) } pub fn clear(&self) { let idx = self.load_index(); for e in idx.values() { let _ = fs::remove_file(self.root.join(&e.file)); } fs::remove_file(&self.index_path).ok(); } } fn sanitize(s: &str) -> String { s.chars() .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) .collect() }