1
This commit is contained in:
70
src-tauri/src/audio_store.rs
Normal file
70
src-tauri/src/audio_store.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
//! 生成语音:SQLite 访问与 Tauri 状态
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::audio_db::{AudioDb, GeneratedAudioRecord};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct AudioStore {
|
||||
inner: Arc<RwLock<Option<Arc<AudioDb>>>>,
|
||||
}
|
||||
|
||||
impl AudioStore {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub async fn init(&self, db_path: PathBuf) -> Result<(), String> {
|
||||
let db = tokio::task::spawn_blocking(move || {
|
||||
AudioDb::open(db_path).map_err(|e| e.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
|
||||
let count = tokio::task::spawn_blocking({
|
||||
let db = Arc::new(db);
|
||||
let db2 = db.clone();
|
||||
move || db2.list().map(|l| (db, l.len())).map_err(|e| e.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
|
||||
let (db, n) = count;
|
||||
*self.inner.write().await = Some(db);
|
||||
log::info!(target: "audio", "语音历史数据库已初始化,共 {n} 条记录");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn with_db<F, T>(&self, f: F) -> Result<T, String>
|
||||
where
|
||||
F: FnOnce(Arc<AudioDb>) -> Result<T, String> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let db = self
|
||||
.inner
|
||||
.read()
|
||||
.await
|
||||
.clone()
|
||||
.ok_or_else(|| "语音数据库未初始化".to_string())?;
|
||||
tokio::task::spawn_blocking(move || f(db))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
|
||||
pub async fn list(&self) -> Result<Vec<GeneratedAudioRecord>, String> {
|
||||
self.with_db(|db| db.list().map_err(|e| e.to_string())).await
|
||||
}
|
||||
|
||||
pub async fn insert(&self, name: String, file_path: String) -> Result<GeneratedAudioRecord, String> {
|
||||
self.with_db(move |db| db.insert(&name, &file_path).map_err(|e| e.to_string()))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete(&self, id: i64) -> Result<bool, String> {
|
||||
self.with_db(move |db| db.delete(id).map_err(|e| e.to_string()))
|
||||
.await
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user