update code level

This commit is contained in:
lychang
2026-03-25 07:29:57 +08:00
parent af15d9f3d1
commit e53ee4b2d0
7 changed files with 397 additions and 94 deletions

View File

@@ -34,7 +34,7 @@ pub struct AlbumWithImages {
pub image_count: i64,
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AlbumInfo {
pub id: Uuid,
pub title: String,
@@ -91,4 +91,86 @@ pub struct FavoriteWithImage {
pub struct FavoriteStatus {
pub is_favorited: bool,
pub favorite_id: Option<Uuid>,
}
// 内存缓存结构
#[derive(Debug, Clone)]
pub struct AlbumsCache {
pub albums: Vec<AlbumInfo>,
pub search_index: std::collections::HashMap<String, Vec<AlbumInfo>>,
pub last_updated: chrono::DateTime<chrono::Utc>,
}
impl AlbumsCache {
pub fn new() -> Self {
Self {
albums: Vec::new(),
search_index: std::collections::HashMap::new(),
last_updated: chrono::Utc::now(),
}
}
pub fn is_expired(&self) -> bool {
let now = chrono::Utc::now();
let duration = now - self.last_updated;
duration.num_minutes() >= 30 // 30分钟过期
}
pub fn update(&mut self, albums: Vec<AlbumInfo>) {
self.albums = albums.clone();
self.last_updated = chrono::Utc::now();
// 构建搜索索引
self.search_index.clear();
for album in &self.albums {
let title_lower = album.title.to_lowercase();
// 为每个单词创建索引
for word in title_lower.split_whitespace() {
if word.len() >= 2 { // 只索引长度>=2的单词
self.search_index
.entry(word.to_string())
.or_insert_with(Vec::new)
.push(album.clone());
}
}
// 为完整标题创建索引
self.search_index
.entry(title_lower.clone())
.or_insert_with(Vec::new)
.push(album.clone());
}
println!("✅ 相册缓存已更新,共 {} 个相册,{} 个搜索索引项",
self.albums.len(), self.search_index.len());
}
pub fn search(&self, query: &str) -> Vec<AlbumInfo> {
let query_lower = query.to_lowercase();
let mut results = Vec::new();
let mut seen_ids = std::collections::HashSet::new();
// 搜索完整匹配
if let Some(matches) = self.search_index.get(&query_lower) {
for album in matches {
if seen_ids.insert(album.id) {
results.push(album.clone());
}
}
}
// 搜索单词匹配
for word in query_lower.split_whitespace() {
if let Some(matches) = self.search_index.get(word) {
for album in matches {
if seen_ids.insert(album.id) {
results.push(album.clone());
}
}
}
}
results
}
}