Files
yaoayanui/src-tauri/src/video_store.rs
fengchuanhn@gmail.com 0b39d7e36f 11
2026-05-18 15:14:37 +08:00

85 lines
2.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 口播视频SQLite 访问与 Tauri 状态
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;
use crate::video_db::{VideoDb, GeneratedVideoRecord};
#[derive(Debug, Default)]
pub struct VideoStore {
inner: Arc<RwLock<Option<Arc<VideoDb>>>>,
}
impl VideoStore {
pub fn new() -> Self {
Self::default()
}
pub async fn init(&self, db_path: PathBuf) -> Result<(), String> {
let db = tokio::task::spawn_blocking(move || {
VideoDb::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: "video", "口播视频历史数据库已初始化,共 {n} 条记录");
Ok(())
}
async fn with_db<F, T>(&self, f: F) -> Result<T, String>
where
F: FnOnce(Arc<VideoDb>) -> 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<GeneratedVideoRecord>, String> {
self.with_db(|db| db.list().map_err(|e| e.to_string())).await
}
pub async fn get(&self, id: i64) -> Result<Option<GeneratedVideoRecord>, String> {
self.with_db(move |db| db.get(id).map_err(|e| e.to_string()))
.await
}
pub async fn insert(
&self,
name: String,
file_path: String,
avatar_id: Option<i64>,
audio_id: Option<i64>,
) -> Result<GeneratedVideoRecord, String> {
self.with_db(move |db| {
db.insert(&name, &file_path, avatar_id, audio_id)
.map_err(|e| e.to_string())
})
.await
}
pub async fn delete(&self, id: i64) -> Result<Option<String>, String> {
self.with_db(move |db| db.delete(id).map_err(|e| e.to_string()))
.await
}
}