From 2529ef17fd8db7890d085d1dce591bd5d65e5160 Mon Sep 17 00:00:00 2001 From: SimonShiki Date: Mon, 6 Jan 2025 13:34:35 +0800 Subject: [PATCH] :fire: chore: remove cache manager Signed-off-by: SimonShiki --- src-tauri/src/cache_manager.rs | 162 --------------------------------- src-tauri/src/error.rs | 2 - src-tauri/src/lib.rs | 10 +- src/pages/settings.tsx | 34 ------- src/utils/cache.ts | 9 -- 5 files changed, 1 insertion(+), 216 deletions(-) delete mode 100644 src-tauri/src/cache_manager.rs delete mode 100644 src/utils/cache.ts diff --git a/src-tauri/src/cache_manager.rs b/src-tauri/src/cache_manager.rs deleted file mode 100644 index bc49513..0000000 --- a/src-tauri/src/cache_manager.rs +++ /dev/null @@ -1,162 +0,0 @@ -use std::collections::HashMap; -use std::fs; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; -use tauri::State; - -pub struct CacheManagerState(pub Arc); - -pub struct CacheManager { - cache_dir: PathBuf, - max_cache_size: u64, - current_cache_size: Mutex, - cache_items: Mutex>, -} - -struct CacheItem { - path: PathBuf, - size: u64, - last_accessed: std::time::SystemTime, -} - -impl CacheManager { - pub fn new(cache_dir: PathBuf, max_cache_size: u64) -> Self { - let cm = CacheManager { - cache_dir, - max_cache_size, - current_cache_size: Mutex::new(0), - cache_items: Mutex::new(HashMap::new()), - }; - cm.init(); - cm - } - - fn init(&self) { - if !self.cache_dir.exists() { - fs::create_dir_all(&self.cache_dir).expect("Failed to create cache directory"); - } - self.load_cache_info(); - } - - fn load_cache_info(&self) { - let mut current_size = 0; - let mut items = HashMap::new(); - - if let Ok(entries) = fs::read_dir(&self.cache_dir) { - for entry in entries.flatten() { - if let Ok(metadata) = entry.metadata() { - if metadata.is_file() { - let id = entry - .file_name() - .to_str() - .and_then(|s| s.split('.').next()) - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - - let item = CacheItem { - path: entry.path(), - size: metadata.len(), - last_accessed: metadata - .modified() - .unwrap_or_else(|_| std::time::SystemTime::now()), - }; - - current_size += item.size; - items.insert(id, item); - } - } - } - } - - *self.current_cache_size.lock().unwrap() = current_size; - *self.cache_items.lock().unwrap() = items; - } - - pub fn get_cached_song(&self, id: u64) -> Option> { - let mut items = self.cache_items.lock().unwrap(); - if let Some(item) = items.get_mut(&id) { - item.last_accessed = std::time::SystemTime::now(); - fs::read(&item.path).ok() - } else { - None - } - } - - pub fn cache_song(&self, id: u64, data: &[u8]) -> Result<(), String> { - let file_path = self.cache_dir.join(format!("{}.mp3", id)); - self.ensure_space_available(data.len() as u64)?; - - fs::write(&file_path, data).map_err(|e| e.to_string())?; - - let mut items = self.cache_items.lock().unwrap(); - let mut current_size = self.current_cache_size.lock().unwrap(); - - items.insert( - id, - CacheItem { - path: file_path, - size: data.len() as u64, - last_accessed: std::time::SystemTime::now(), - }, - ); - *current_size += data.len() as u64; - - Ok(()) - } - - fn ensure_space_available(&self, required_space: u64) -> Result<(), String> { - let mut current_size = self.current_cache_size.lock().unwrap(); - let mut items = self.cache_items.lock().unwrap(); - - while *current_size + required_space > self.max_cache_size && !items.is_empty() { - let oldest_id = items - .iter() - .min_by_key(|(_, item)| item.last_accessed) - .map(|(id, _)| *id) - .ok_or_else(|| "No items to remove".to_string())?; - - if let Some(item) = items.remove(&oldest_id) { - fs::remove_file(&item.path).map_err(|e| e.to_string())?; - *current_size -= item.size; - } - } - - Ok(()) - } - - pub fn get_cache_size(&self) -> u64 { - *self.current_cache_size.lock().unwrap() - } - - pub fn clear_cache(&self) -> Result<(), String> { - let mut items = self.cache_items.lock().unwrap(); - let mut current_size = self.current_cache_size.lock().unwrap(); - - for (_, item) in items.drain() { - fs::remove_file(&item.path).map_err(|e| e.to_string())?; - } - - *current_size = 0; - Ok(()) - } -} - -#[tauri::command] -pub fn get_cached_song(id: u64, state: State) -> Option> { - state.0.get_cached_song(id) -} - -#[tauri::command] -pub fn cache_song(id: u64, data: Vec, state: State) -> Result<(), String> { - state.0.cache_song(id, &data) -} - -#[tauri::command] -pub fn get_cache_size(state: State) -> u64 { - state.0.get_cache_size() -} - -#[tauri::command] -pub fn clear_cache(state: State) -> Result<(), String> { - state.0.clear_cache() -} diff --git a/src-tauri/src/error.rs b/src-tauri/src/error.rs index 6e69311..1e8179c 100644 --- a/src-tauri/src/error.rs +++ b/src-tauri/src/error.rs @@ -8,7 +8,6 @@ pub enum AppError { FileNotFound(String), FileOpenError(String), DecodeError(String), - SinkCreationError(String), InvalidOperation(String), SeekError(String), NetworkError(String), @@ -24,7 +23,6 @@ impl Display for AppError { AppError::FileNotFound(path) => write!(f, "File not found: {}", path), AppError::FileOpenError(err) => write!(f, "Failed to open file: {}", err), AppError::DecodeError(err) => write!(f, "Failed to decode audio: {}", err), - AppError::SinkCreationError(err) => write!(f, "Failed to create audio sink: {}", err), AppError::InvalidOperation(err) => write!(f, "Invalid operation: {}", err), AppError::SeekError(err) => write!(f, "Failed to seek: {}", err), AppError::NetworkError(err) => write!(f, "Network error: {}", err), diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 35424a4..6a115e9 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,11 +1,9 @@ mod audio; -mod cache_manager; mod error; mod local_scanner; mod media_control; use audio::AudioState; -use cache_manager::{CacheManager, CacheManagerState}; use media_control::MediaControlState; use rodio::OutputStreamBuilder; use std::sync::atomic::AtomicBool; @@ -49,10 +47,6 @@ pub async fn run() { .manage(audio_state) .manage(media_control_state) .setup(|app| { - let cache_dir = app.path().app_cache_dir().unwrap(); - let cache_manager = Arc::new(CacheManager::new(cache_dir, 1024 * 1024 * 1024)); // 1GB cache limit - app.manage(CacheManagerState(cache_manager)); - let show = MenuItemBuilder::with_id("show", "Show").build(app)?; let pause_resume = MenuItemBuilder::with_id("pause_resume", "Pause/Resume").build(app)?; @@ -120,9 +114,7 @@ pub async fn run() { media_control::update_media_metadata, media_control::update_playback_status, local_scanner::get_song_buffer, - local_scanner::scan_folder, - cache_manager::get_cache_size, - cache_manager::clear_cache, + local_scanner::scan_folder ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src/pages/settings.tsx b/src/pages/settings.tsx index 072de6b..30515c8 100644 --- a/src/pages/settings.tsx +++ b/src/pages/settings.tsx @@ -16,7 +16,6 @@ import type { NCMConfig, NCMQuality } from '../storages/ncm'; import Spinner from '../components/base/spinner'; import { FormattedMessage, useIntl } from 'react-intl'; import { langMap } from '../../locales'; -import { clearCache, getCacheSize } from '../utils/cache'; import { nowPlayingBarJotai } from '../jotais/play'; const localStorageConfigJotai = focusAtom(storagesConfigJotai, (optic) => optic.prop('local')) as unknown as WritableAtom], void>; @@ -41,8 +40,6 @@ export default function Settings () { const [ncmAuthModalOpen, setNcmAuthModalOpen] = useState(false); const [qr, setQr] = useState(false); const [qrUrl, setQrUrl] = useState(''); - const [cacheSize, setCacheSize] = useState(-1); - const [clearingCache, setClearingCache] = useState(false); const {instance: localStorage} = useAtomValue(localStorageJotai); const ncmConfig = useAtomValue(ncmStorageConfigJotai); const localScanned = useAtomValue(localScannedJotai); @@ -72,19 +69,6 @@ export default function Settings () { { value: 'jymaster', label: intl.formatMessage({ defaultMessage: 'Ultra HD Mastering' }) } ]; - useEffect(() => { - if (cacheSize > 0) return; - getCacheSize().then(setCacheSize); - }, [cacheSize]); - - useEffect(() => { - if (!clearingCache) return; - clearCache().then(() => { - setCacheSize(-1); - setClearingCache(false); - }); - }, [clearingCache]); - useEffect(() => { if (!qr) { setQrUrl(''); @@ -178,24 +162,6 @@ export default function Settings () { - -
- - - - - {cacheSize < 0 ? ( - - ) : ( - - )} - -
-
diff --git a/src/utils/cache.ts b/src/utils/cache.ts deleted file mode 100644 index 445e25c..0000000 --- a/src/utils/cache.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { invoke } from '@tauri-apps/api/core'; - -export async function getCacheSize () { - return await invoke('get_cache_size'); -} - -export async function clearCache () { - await invoke('clear_cache'); -}