From b915e69222263742c87b4d3d10fe4315d1d23589 Mon Sep 17 00:00:00 2001 From: lychang Date: Sun, 19 Jul 2026 15:03:13 +0800 Subject: [PATCH] update --- .gitignore | 1 + Cargo.toml | 6 +- assets/album.html | 3 +- assets/css/album.css | 79 +++- assets/css/style.css | 48 +-- assets/index.html | 2 +- assets/js/album.js | 95 ++++- assets/js/app.js | 44 ++- src/config.rs | 23 +- src/database.rs | 846 ----------------------------------------- src/image_processor.rs | 2 +- src/import.rs | 446 ---------------------- src/main.rs | 170 +++++---- src/models.rs | 230 ----------- src/queue.rs | 4 +- src/routes.rs | 365 ------------------ 16 files changed, 332 insertions(+), 2032 deletions(-) delete mode 100644 src/database.rs delete mode 100644 src/import.rs delete mode 100644 src/models.rs delete mode 100644 src/routes.rs diff --git a/.gitignore b/.gitignore index ea8c4bf..8bac997 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +/albmums \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 1dbb2d0..bd724e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,12 @@ sqlx = { version = "0.7", features = ["sqlite", "runtime-tokio", "migrate"] } chrono = { version = "0.4", features = ["serde"] } uuid = { version = "1.0", features = ["v4", "serde"] } image = { version = "0.24", default-features = false, features = ["jpeg", "png", "gif", "webp"] } -reqwest = { version = "0.11", default-features = false, features = ["blocking","rustls-tls"] } +reqwest = { version = "0.11", default-features = false, features = ["rustls-tls", "json"] } config = "0.13" rand = "0.8" tracing = "0.1" tracing-subscriber = "0.3" thiserror = "1.0" -mimalloc = "0.1.48" \ No newline at end of file +mimalloc = "0.1.48" +regex = "1" +lazy_static = "1.4" \ No newline at end of file diff --git a/assets/album.html b/assets/album.html index 30e33f4..0ab87bd 100644 --- a/assets/album.html +++ b/assets/album.html @@ -18,6 +18,7 @@
正在加载...
+
@@ -78,6 +79,6 @@
- + \ No newline at end of file diff --git a/assets/css/album.css b/assets/css/album.css index f8a8db8..820dfc4 100644 --- a/assets/css/album.css +++ b/assets/css/album.css @@ -72,7 +72,7 @@ body { text-align: center; color: var(--text-light); font-size: 1.2rem; - margin-bottom: 40px; + margin-bottom: 20px; background: var(--white); padding: 20px; border-radius: var(--border-radius); @@ -83,6 +83,57 @@ body { margin-right: auto; } +/* 相册元数据标签(人名 + 标签) */ +.album-meta-tags { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 10px; + margin: 0 auto 40px; + max-width: 800px; +} + +.meta-chip { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 6px 14px; + border-radius: 20px; + font-size: 0.85rem; + cursor: pointer; + transition: all 0.2s ease; + user-select: none; + border: 1px solid transparent; +} + +.meta-chip i { + font-size: 0.75rem; +} + +.meta-chip-person { + background: #dbeafe; + color: #1e40af; + border-color: #bfdbfe; +} + +.meta-chip-person:hover { + background: #bfdbfe; + transform: translateY(-1px); + box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2); +} + +.meta-chip-tag { + background: #f0fdf4; + color: #166534; + border-color: #bbf7d0; +} + +.meta-chip-tag:hover { + background: #dcfce7; + transform: translateY(-1px); + box-shadow: 0 2px 8px rgba(22, 163, 74, 0.2); +} + /* 智能图片网格布局 - 自适应瀑布流效果 */ .images-grid { display: grid; @@ -392,6 +443,10 @@ body { .album-info { font-size: 1.1rem; padding: 18px; + margin-bottom: 18px; + } + + .album-meta-tags { margin-bottom: 35px; } @@ -441,7 +496,18 @@ body { .album-info { font-size: 1rem; padding: 15px; + margin-bottom: 15px; + } + + .album-meta-tags { + gap: 8px; margin-bottom: 30px; + padding: 0 10px; + } + + .meta-chip { + padding: 5px 12px; + font-size: 0.8rem; } .images-grid { @@ -523,7 +589,18 @@ body { .album-info { font-size: 0.9rem; padding: 12px; + margin-bottom: 12px; + } + + .album-meta-tags { + gap: 6px; margin-bottom: 25px; + padding: 0 8px; + } + + .meta-chip { + padding: 4px 10px; + font-size: 0.75rem; } .images-grid { diff --git a/assets/css/style.css b/assets/css/style.css index a377197..e3bc870 100644 --- a/assets/css/style.css +++ b/assets/css/style.css @@ -1168,6 +1168,7 @@ body { transition: all 0.3s ease; position: relative; border: 1px solid var(--medium-gray); + cursor: pointer; } .album-card:hover { transform: translateY(-8px); @@ -1196,7 +1197,7 @@ body { .album-info { padding: 25px; } -.album-info h2 { +.album-info h3 { font-size: 1.4rem; margin-bottom: 12px; color: var(--text-dark); @@ -1211,7 +1212,6 @@ body { display: flex; justify-content: space-between; align-items: center; - margin-bottom: 20px; color: var(--text-light); font-size: 0.9rem; } @@ -1220,25 +1220,6 @@ body { align-items: center; gap: 6px; } -.view-button { - display: block; - text-align: center; - padding: 14px; - background: linear-gradient(135deg, var(--secondary-blue) 0%, var(--primary-blue) 100%); - color: var(--white); - text-decoration: none; - border-radius: 10px; - font-weight: 600; - transition: all 0.3s ease; - border: none; - cursor: pointer; - font-size: 1rem; -} -.view-button:hover { - transform: translateY(-2px); - box-shadow: 0 8px 20px rgba(59, 130, 246, 0.3); - background: linear-gradient(135deg, var(--primary-blue) 0%, var(--secondary-blue) 100%); -} .no-results { text-align: center; @@ -1431,7 +1412,7 @@ body { padding: 20px; } - .album-info h2 { + .album-info h3 { font-size: 1.2rem; } @@ -1440,11 +1421,6 @@ body { align-items: flex-start; gap: 8px; } - - .view-button { - padding: 12px; - font-size: 0.9rem; - } } @media (max-width: 480px) { @@ -1516,7 +1492,7 @@ body { padding: 15px; } - .album-info h2 { + .album-info h3 { font-size: 1.1rem; } @@ -1524,11 +1500,6 @@ body { font-size: 0.8rem; } - .view-button { - padding: 10px; - font-size: 0.85rem; - } - .loading { padding: 40px 15px; font-size: 1rem; @@ -1559,14 +1530,6 @@ body { transform: scale(0.98); box-shadow: var(--shadow-md); } - - .view-button:hover { - transform: none; - } - - .view-button:active { - transform: scale(0.95); - } } /* 高分辨率屏幕优化 */ @@ -1661,8 +1624,7 @@ body { /* 打印样式 */ @media print { - .search-container, - .view-button { + .search-container { display: none; } diff --git a/assets/index.html b/assets/index.html index 6168052..9dd48e5 100644 --- a/assets/index.html +++ b/assets/index.html @@ -41,6 +41,6 @@ - + \ No newline at end of file diff --git a/assets/js/album.js b/assets/js/album.js index 763a2d6..fa82e20 100644 --- a/assets/js/album.js +++ b/assets/js/album.js @@ -261,11 +261,89 @@ async function loadAlbum(albumId) { // 更新相册信息 function updateAlbumInfo() { document.getElementById('album-title').textContent = currentAlbum.title; - document.getElementById('album-info').innerHTML = - ` 共 ${images.length} 张图片`; + + let infoHtml = ` 共 ${images.length} 张图片`; + document.getElementById('album-info').innerHTML = infoHtml; + + // 显示相册元数据(人名 + 标签) + updateAlbumMeta(); + document.title = `${currentAlbum.title} - 图片展示服务`; } +// 更新相册元数据(人名 + 标签)点击可搜索 +function updateAlbumMeta() { + const metaContainer = document.getElementById('album-meta-tags'); + if (!metaContainer) return; + + let chips = []; + + // 添加人名标签 + if (currentAlbum.person_name_cleaned) { + chips.push({ + text: currentAlbum.person_name_cleaned, + type: 'person', + query: currentAlbum.person_name_cleaned + }); + } + + // 添加标签 + if (currentAlbum.tags) { + try { + const tags = JSON.parse(currentAlbum.tags); + if (Array.isArray(tags)) { + tags.forEach(tag => { + chips.push({ + text: tag, + type: 'tag', + query: tag + }); + }); + } + } catch (e) { + // 非JSON格式,当作逗号分隔 + currentAlbum.tags.split(',').forEach(tag => { + const t = tag.trim(); + if (t) { + chips.push({ + text: t, + type: 'tag', + query: t + }); + } + }); + } + } + + if (chips.length === 0) { + metaContainer.style.display = 'none'; + return; + } + + metaContainer.style.display = 'flex'; + metaContainer.innerHTML = chips.map(chip => { + const icon = chip.type === 'person' ? 'fa-user' : 'fa-tag'; + return ` + ${chip.text} + `; + }).join(''); +} + +// 事件委托:点击元数据标签 +document.addEventListener('click', function(e) { + const chip = e.target.closest('.meta-chip'); + if (!chip) return; + const query = chip.dataset.metaQuery; + if (query) { + searchByMeta(query); + } +}); + +// 点击元数据标签搜索 +function searchByMeta(encodedQuery) { + window.location.href = `/?search=${encodedQuery}`; +} + // 智能判断图片方向 - 更精确的判断逻辑 function getImageOrientation(width, height) { if (!width || !height) return 'square'; @@ -708,8 +786,12 @@ function toggleFavorite(event, imageIndex) { return; } + // 找到按钮元素(event.target 可能是 i 图标) + const btn = event.target.closest('.favorite-btn'); + if (!btn) return; + // 检查当前收藏状态 - const isFavorited = event.target.classList.contains('favorited'); + const isFavorited = btn.classList.contains('favorited'); if (isFavorited) { // 取消收藏 @@ -723,7 +805,7 @@ function toggleFavorite(event, imageIndex) { return response.json(); }) .then(() => { - event.target.classList.remove('favorited'); + btn.classList.remove('favorited'); showFavoriteToast('已取消收藏', false); }) .catch(error => { @@ -750,7 +832,7 @@ function toggleFavorite(event, imageIndex) { return response.json(); }) .then(() => { - event.target.classList.add('favorited'); + btn.classList.add('favorited'); showFavoriteToast('已添加到收藏夹', true); }) .catch(error => { @@ -835,4 +917,5 @@ window.openLightbox = openLightbox; window.closeLightbox = closeLightbox; window.prevImage = prevImage; window.nextImage = nextImage; -window.toggleFavorite = toggleFavorite; \ No newline at end of file +window.toggleFavorite = toggleFavorite; +window.addToFavoritesFromLightbox = addToFavoritesFromLightbox; \ No newline at end of file diff --git a/assets/js/app.js b/assets/js/app.js index ad010c2..3709235 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -99,10 +99,21 @@ document.addEventListener('DOMContentLoaded', function () { document.body.classList.add('touch-device'); } - loadAlbums(); initSearch(); initInfiniteScroll(); initLazyLoading(); // 初始化图片懒加载 + + // 检查URL中是否有search参数 + const urlParams = new URLSearchParams(window.location.search); + const searchQuery = urlParams.get('search'); + if (searchQuery) { + const searchInput = document.getElementById('search-input'); + searchInput.value = searchQuery; + // 直接搜索,不先加载全部相册 + searchAlbums(); + } else { + loadAlbums(); + } }); // 初始化搜索功能 @@ -355,7 +366,7 @@ function appendAlbums(albums) { const createdDate = new Date(album.created_at).toLocaleDateString('zh-CN'); return ` -
+
${album.image_count} 张图片 ${createdDate}
- - 查看相册 -
`; @@ -555,7 +563,7 @@ function displayAlbums(albums) { const createdDate = new Date(album.created_at).toLocaleDateString('zh-CN'); return ` -
+
${album.image_count} 张图片 ${createdDate}
- - 查看相册 -
`; @@ -759,6 +764,11 @@ preloadCriticalResources(); // 优化滚动性能 optimizeScrollPerformance(); +// 打开相册详情 +function openAlbum(albumId) { + window.location.href = `/album?id=${albumId}`; +} + // 随机打开相册 function openRandomAlbum() { // 添加随机动画效果 @@ -818,12 +828,7 @@ function showFavorites() { return response.json(); }) .then(favoriteImages => { - if (favoriteImages.length === 0) { - alert('收藏夹为空,快去收藏一些喜欢的图片吧!'); - return; - } - - // 创建收藏夹页面或跳转到收藏夹视图 + // 始终显示收藏夹视图(包括空状态) displayFavorites(favoriteImages); }) .catch(error => { @@ -1197,4 +1202,11 @@ function openFavoriteImage(favoriteId) { // 导出函数供全局使用 window.searchAlbums = searchAlbums; window.openRandomAlbum = openRandomAlbum; -window.showFavorites = showFavorites; \ No newline at end of file +window.showFavorites = showFavorites; +window.openAlbum = openAlbum; +window.backToHome = backToHome; +window.loadAlbums = loadAlbums; +window.removeFavorite = removeFavorite; +window.previewFavorite = previewFavorite; +window.openFavoriteImage = openFavoriteImage; +window.removeFavoriteFromPreview = removeFavoriteFromPreview; \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 3154a55..809ff69 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,6 +8,9 @@ pub struct Config { pub server: ServerConfig, pub storage: StorageConfig, pub queue: QueueConfig, + pub api_server: Option, + #[serde(default)] + pub old_db: Option, } @@ -35,15 +38,31 @@ pub struct QueueConfig { pub idle_request_rate_threshold: f64, } +#[derive(Debug, Deserialize, Clone)] +pub struct ApiServerConfig { + pub url: String, +} + +#[derive(Debug, Deserialize, Clone)] +pub struct OldDbConfig { + pub path: String, + #[serde(default = "default_auto_migrate")] + pub auto_migrate: bool, +} + +fn default_auto_migrate() -> bool { + false +} + impl Config { pub fn load() -> Result { let config = config::Config::builder() .add_source(config::File::with_name("config")) .build()?; - + config.try_deserialize() } - + pub fn server_address(&self) -> String { format!("{}:{}", self.server.host, self.server.port) } diff --git a/src/database.rs b/src/database.rs deleted file mode 100644 index 80dd2b4..0000000 --- a/src/database.rs +++ /dev/null @@ -1,846 +0,0 @@ -use sqlx::{SqlitePool, sqlite::SqlitePoolOptions, Row}; -use crate::config::Config; -use crate::models::*; -use uuid::Uuid; - -pub struct Database { - pub pool: SqlitePool, - config: Config, -} - -impl Database { - pub async fn new(config: &Config) -> Result { - // 从URL中提取文件路径 - let url = &config.database.url; - let file_path = if url.starts_with("sqlite:") { - &url[7..] // 移除 "sqlite:" 前缀 - } else { - url - }; - - // 确保数据目录存在 - if let Some(parent) = std::path::Path::new(file_path).parent() { - if !parent.exists() { - std::fs::create_dir_all(parent)?; - } - } - - // 如果数据库文件不存在,创建一个空文件 - if !std::path::Path::new(file_path).exists() { - std::fs::File::create(file_path)?; - println!("创建新的数据库文件: {}", file_path); - } - - let pool = SqlitePoolOptions::new() - .max_connections(10) // 优化:减少最大连接数,避免资源浪费 - .min_connections(2) // 优化:减少最小连接数 - .acquire_timeout(std::time::Duration::from_secs(5)) // 优化:减少获取连接超时时间 - .idle_timeout(std::time::Duration::from_secs(300)) // 优化:减少空闲超时时间 - .max_lifetime(std::time::Duration::from_secs(1800)) // 优化:减少最大生命周期 - .connect(url) - .await?; - - // 在迁移之前设置SQLite性能优化参数 - // 这些PRAGMA语句必须在事务外执行 - sqlx::query("PRAGMA journal_mode=WAL;").execute(&pool).await?; - sqlx::query("PRAGMA wal_autocheckpoint=4000;").execute(&pool).await?; - sqlx::query("PRAGMA synchronous=NORMAL;").execute(&pool).await?; - sqlx::query("PRAGMA cache_size=-64000;").execute(&pool).await?; - sqlx::query("PRAGMA mmap_size=268435456;").execute(&pool).await?; - sqlx::query("PRAGMA temp_store=MEMORY;").execute(&pool).await?; - sqlx::query("PRAGMA foreign_keys=ON;").execute(&pool).await?; - - // 创建表 - sqlx::migrate!("./migrations").run(&pool).await?; - - // 确保image_count字段存在并正确初始化 - let db = Database { - pool, - config: config.clone(), // 保存配置副本 - }; - db.ensure_image_count_field().await?; - - Ok(db) - } - - // pub async fn get_albums(&self, page: Option, limit: Option) -> Result, sqlx::Error> { - // let page = page.unwrap_or(1); - // let limit = limit.unwrap_or(50); // 减少默认加载数量,提高响应速度 - // let offset = (page - 1) * limit; - // - // let albums = sqlx::query( - // r#" - // SELECT - // id, - // title, - // document, - // description, - // cover_image_id, - // image_count, - // created_at - // FROM albums - // ORDER BY created_at DESC - // LIMIT ? OFFSET ? - // "# - // ) - // .bind(limit as i64) - // .bind(offset as i64) - // .fetch_all(&self.pool) - // .await?; - // - // let mut result = Vec::new(); - // for row in albums { - // let id_str = row.get::("id"); - // let id = match Uuid::parse_str(&id_str) { - // Ok(uuid) => uuid, - // Err(e) => { - // eprintln!("无效的UUID格式: {} - 错误: {}", id_str, e); - // continue; // 跳过无效的记录 - // } - // }; - // - // result.push(AlbumInfo { - // id, - // title: row.get("title"), - // document: row.get("document"), - // description: row.get("description"), - // cover_image_id: row.get("cover_image_id"), - // image_count: row.get("image_count"), - // created_at: row.get::("created_at"), - // }); - // } - // - // Ok(result) - // } - // 相册操作 - pub async fn get_all_albums(&self) -> Result, sqlx::Error> { - - let albums = sqlx::query( - r#" - SELECT - id, - title, - document, - description, - cover_image_id, - image_count, - created_at - FROM albums - ORDER BY created_at DESC - "# - ) - .fetch_all(&self.pool) - .await?; - - let mut result = Vec::new(); - for row in albums { - let id_str = row.get::("id"); - let id = match Uuid::parse_str(&id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的UUID格式: {} - 错误: {}", id_str, e); - continue; // 跳过无效的记录 - } - }; - - result.push(AlbumInfo { - id, - title: row.get("title"), - document: row.get("document"), - description: row.get("description"), - cover_image_id: row.get("cover_image_id"), - image_count: row.get("image_count"), - created_at: row.get::("created_at"), - }); - } - - Ok(result) - } - - // pub async fn search_albums(&self, query: &str, page: Option, limit: Option) -> Result, sqlx::Error> { - // let search_pattern = format!("%{}%", query); - // let page = page.unwrap_or(1); - // let limit = limit.unwrap_or(50); // 减少默认加载数量,提高响应速度 - // let offset = (page - 1) * limit; - // - // let albums = sqlx::query( - // r#" - // SELECT - // id, - // title, - // document, - // description, - // cover_image_id, - // image_count, - // created_at - // FROM albums - // WHERE title LIKE ? - // ORDER BY created_at DESC - // LIMIT ? OFFSET ? - // "# - // ) - // .bind(&search_pattern) - // .bind(limit as i64) - // .bind(offset as i64) - // .fetch_all(&self.pool) - // .await?; - // - // let mut result = Vec::new(); - // for row in albums { - // let id_str = row.get::("id"); - // let id = match Uuid::parse_str(&id_str) { - // Ok(uuid) => uuid, - // Err(e) => { - // eprintln!("无效的UUID格式: {} - 错误: {}", id_str, e); - // continue; // 跳过无效的记录 - // } - // }; - // - // result.push(AlbumInfo { - // id, - // title: row.get("title"), - // document: row.get("document"), - // description: row.get("description"), - // cover_image_id: row.get("cover_image_id"), - // image_count: row.get("image_count"), - // created_at: row.get::("created_at"), - // }); - // } - // - // Ok(result) - // } - - pub async fn get_album_with_images(&self, album_id: Uuid) -> Result, sqlx::Error> { - // 获取相册基本信息 - let album_row = sqlx::query( - "SELECT * FROM albums WHERE id = ?" - ) - .bind(album_id.to_string()) - .fetch_optional(&self.pool) - .await?; - - if let Some(row) = album_row { - let id_str = row.get::("id"); - let id = match Uuid::parse_str(&id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的相册UUID格式: {} - 错误: {}", id_str, e); - return Ok(None); - } - }; - - let cover_image_id = match row.get::, _>("cover_image_id") { - Some(s) => match Uuid::parse_str(&s) { - Ok(uuid) => Some(uuid), - Err(e) => { - eprintln!("无效的封面图片UUID格式: {} - 错误: {}", s, e); - None - } - }, - None => None - }; - - let album = Album { - id, - title: row.get("title"), - description: row.get("description"), - cover_image_id, - image_count: row.get("image_count"), - created_at: row.get::("created_at"), - updated_at: row.get::("updated_at"), - }; - - // 获取相册中的图片 - let image_rows = sqlx::query( - "SELECT * FROM images WHERE album_id = ?" - ) - .bind(album_id.to_string()) - .fetch_all(&self.pool) - .await?; - - let mut images = Vec::new(); - for row in image_rows { - let image_id_str = row.get::("id"); - let image_id = match Uuid::parse_str(&image_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的图片UUID格式: {} - 错误: {}", image_id_str, e); - continue; - } - }; - - let album_id_str = row.get::("album_id"); - let album_id = match Uuid::parse_str(&album_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的相册UUID格式: {} - 错误: {}", album_id_str, e); - continue; - } - }; - - images.push(Image { - id: image_id, - album_id, - filename: row.get("filename"), - original_url: row.get("original_url"), - title: row.get("title"), - description: row.get("description"), - file_size: row.get("file_size"), - width: row.get("width"), - height: row.get("height"), - mime_type: row.get("mime_type"), - created_at: row.get::("created_at"), - }); - } - - let image_count = images.len() as i64; - - Ok(Some(AlbumWithImages { - album, - images, - image_count, - })) - } else { - Ok(None) - } - } - - pub async fn create_album(&self, album: CreateAlbum) -> Result { - let id = Uuid::new_v4(); - let now = chrono::Utc::now().to_rfc3339(); - - sqlx::query( - "INSERT INTO albums (id, title, document, description, image_count, created_at, updated_at) VALUES (?, ?, ?, ?, 0, ?, ?)" - ) - .bind(id.to_string()) - .bind(album.title) - .bind(album.document) - .bind(album.description) - .bind(&now) - .bind(&now) - .execute(&self.pool) - .await?; - - Ok(id) - } - - // 图片操作 - // pub async fn add_image(&self, image: CreateImage) -> Result { - // let id = Uuid::new_v4(); - // let now = chrono::Utc::now().to_rfc3339(); - // - // sqlx::query( - // "INSERT INTO images (id, album_id, filename, original_url, title, description, file_size, width, height, mime_type, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" - // ) - // .bind(id.to_string()) - // .bind(image.album_id.to_string()) - // .bind(image.filename) - // .bind(image.original_url) - // .bind(image.title) - // .bind(image.description) - // .bind(image.file_size) - // .bind(image.width) - // .bind(image.height) - // .bind(image.mime_type) - // .bind(&now) - // .execute(&self.pool) - // .await?; - // - // // 更新相册的图片数量 - // self.update_album_image_count(image.album_id).await?; - // - // // 如果这是相册的第一张图片,设置为封面 - // let image_count = sqlx::query_scalar::<_, i64>( - // "SELECT COUNT(*) FROM images WHERE album_id = ?" - // ) - // .bind(image.album_id.to_string()) - // .fetch_one(&self.pool) - // .await?; - // - // if image_count == 1 { - // sqlx::query( - // "UPDATE albums SET cover_image_id = ? WHERE id = ?" - // ) - // .bind(id.to_string()) - // .bind(image.album_id.to_string()) - // .execute(&self.pool) - // .await?; - // } - // - // Ok(id) - // } - - /// 更新相册的图片数量 - pub async fn update_album_image_count(&self, album_id: Uuid) -> Result<(), sqlx::Error> { - sqlx::query( - r#" - UPDATE albums - SET image_count = ( - SELECT COUNT(*) FROM images WHERE album_id = ? - ), - updated_at = datetime('now') - WHERE id = ? - "# - ) - .bind(album_id.to_string()) - .bind(album_id.to_string()) - .execute(&self.pool) - .await?; - - Ok(()) - } - - pub async fn add_images(&self, images: Vec) -> Result, sqlx::Error> { - if images.is_empty() { - return Ok(Vec::new()); - } - - // 由于生命周期问题,简化实现,不使用重试机制 - let now = chrono::Utc::now().to_rfc3339(); - let mut ids = Vec::new(); - - // 保存第一个相册ID用于封面设置 - let first_album_id = images.first().map(|img| img.album_id); - - // 使用事务确保批量插入的原子性 - let mut tx = self.pool.begin().await?; - - for image in &images { - let id = Uuid::new_v4(); - ids.push(id); - - sqlx::query( - "INSERT INTO images (id, album_id, filename, original_url, title, description, file_size, width, height, mime_type, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" - ) - .bind(id.to_string()) - .bind(image.album_id.to_string()) - .bind(&image.filename) - .bind(&image.original_url) - .bind(&image.title) - .bind(&image.description) - .bind(image.file_size) - .bind(image.width) - .bind(image.height) - .bind(&image.mime_type) - .bind(&now) - .execute(&mut *tx) - .await?; - } - - // 提交事务 - tx.commit().await?; - - // 批量设置封面图片(只对每个相册的第一批图片设置) - if let Some(album_id) = first_album_id { - // 检查相册是否已有图片 - let existing_count = sqlx::query_scalar::<_, i64>( - "SELECT COUNT(*) FROM images WHERE album_id = ?" - ) - .bind(album_id.to_string()) - .fetch_one(&self.pool) - .await?; - - // 如果这是相册的第一批图片,设置第一张为封面 - if existing_count == images.len() as i64 { - if let Some(first_id) = ids.first() { - sqlx::query( - "UPDATE albums SET cover_image_id = ? WHERE id = ?" - ) - .bind(first_id.to_string()) - .bind(album_id.to_string()) - .execute(&self.pool) - .await?; - } - } - - // 更新相册的图片数量 - self.update_album_image_count(album_id).await?; - } - - Ok(ids) - } - - /// 获取相册中的图片数量(直接从image_count字段读取) - pub async fn get_album_image_count(&self, album_id: Uuid) -> Result { - let count = sqlx::query_scalar::<_, i64>( - "SELECT COUNT(*) FROM images WHERE album_id = ?" - ) - .bind(album_id.to_string()) - .fetch_one(&self.pool) - .await?; - - Ok(count) - } - - /// 确保image_count字段存在并正确初始化 - pub async fn ensure_image_count_field(&self) -> Result<(), sqlx::Error> { - // 检查字段是否存在 - let exists: i64 = sqlx::query_scalar( - "SELECT COUNT(*) FROM pragma_table_info('albums') WHERE name = 'image_count'" - ) - .fetch_one(&self.pool) - .await?; - - if exists == 0 { - // 字段不存在,添加字段 - sqlx::query("ALTER TABLE albums ADD COLUMN image_count INTEGER NOT NULL DEFAULT 0") - .execute(&self.pool) - .await?; - - // 更新现有数据的image_count - sqlx::query( - "UPDATE albums SET image_count = ( - SELECT COUNT(*) FROM images WHERE images.album_id = albums.id - )" - ) - .execute(&self.pool) - .await?; - - println!("✅ image_count字段已成功添加并初始化"); - } else { - println!("ℹ️ image_count字段已存在,跳过初始化"); - } - - Ok(()) - } - - /// 删除相册及其关联的图片 - pub async fn delete_album(&self, album_id: Uuid) -> Result<(), sqlx::Error> { - let mut tx = self.pool.begin().await?; - - // 删除相册关联的图片 - sqlx::query("DELETE FROM images WHERE album_id = ?") - .bind(album_id.to_string()) - .execute(&mut *tx) - .await?; - - // 删除相册 - sqlx::query("DELETE FROM albums WHERE id = ?") - .bind(album_id.to_string()) - .execute(&mut *tx) - .await?; - - tx.commit().await?; - Ok(()) - } - - // pub async fn delete_image(&self, image_id: Uuid) -> Result { - // // 先获取图片所属的相册ID - // let album_id_result = sqlx::query_scalar::<_, String>( - // r#" - // SELECT album_id FROM images WHERE id = ? - // "# - // ) - // .bind(image_id.to_string()) - // .fetch_optional(&self.pool) - // .await?; - // - // let result = sqlx::query( - // r#" - // DELETE FROM images - // WHERE id = ? - // "# - // ) - // .bind(image_id.to_string()) - // .execute(&self.pool) - // .await?; - // - // // 如果删除成功且找到了相册ID,更新相册图片数量 - // if result.rows_affected() > 0 { - // if let Some(album_id_str) = album_id_result { - // if let Ok(album_id) = Uuid::parse_str(&album_id_str) { - // self.update_album_image_count(album_id).await?; - // } - // } - // } - // - // Ok(result.rows_affected() > 0) - // } - - pub async fn update_album_cover(&self, album_id: Uuid, cover_image_id: Option) -> Result<(), sqlx::Error> { - let cover_id_str = cover_image_id.map(|id| id.to_string()); - - sqlx::query( - "UPDATE albums SET cover_image_id = ?, updated_at = datetime('now') WHERE id = ?" - ) - .bind(cover_id_str) - .bind(album_id.to_string()) - .execute(&self.pool) - .await?; - - Ok(()) - } - - pub async fn get_image(&self, image_id: Uuid) -> Result, sqlx::Error> { - let row = sqlx::query( - "SELECT * FROM images WHERE id = ?" - ) - .bind(image_id.to_string()) - .fetch_optional(&self.pool) - .await?; - - if let Some(row) = row { - let image_id_str = row.get::("id"); - let image_id = match Uuid::parse_str(&image_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的图片UUID格式: {} - 错误: {}", image_id_str, e); - return Ok(None); - } - }; - - let album_id_str = row.get::("album_id"); - let album_id = match Uuid::parse_str(&album_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的相册UUID格式: {} - 错误: {}", album_id_str, e); - return Ok(None); - } - }; - - Ok(Some(Image { - id: image_id, - album_id, - filename: row.get("filename"), - original_url: row.get("original_url"), - title: row.get("title"), - description: row.get("description"), - file_size: row.get("file_size"), - width: row.get("width"), - height: row.get("height"), - mime_type: row.get("mime_type"), - created_at: row.get::("created_at"), - })) - } else { - Ok(None) - } - } - - // 收藏功能数据库操作 - - // 获取用户的收藏列表 - pub async fn get_user_favorites(&self, user_id: &str) -> Result, sqlx::Error> { - let rows = sqlx::query( - r#" - SELECT - f.id as favorite_id, - f.user_id, - f.image_id, - f.album_id, - f.created_at as favorite_created_at, - i.id as image_id, - i.album_id, - i.filename, - i.original_url, - i.title, - i.description, - i.file_size, - i.width, - i.height, - i.mime_type, - i.created_at as image_created_at, - a.title as album_title - FROM favorites f - JOIN images i ON f.image_id = i.id - JOIN albums a ON f.album_id = a.id - WHERE f.user_id = ? - ORDER BY f.created_at DESC - "# - ) - .bind(user_id) - .fetch_all(&self.pool) - .await?; - - let mut favorites = Vec::new(); - for row in rows { - let favorite_id_str = row.get::("favorite_id"); - let favorite_id = match Uuid::parse_str(&favorite_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的收藏UUID格式: {} - 错误: {}", favorite_id_str, e); - continue; - } - }; - - let image_id_str = row.get::("image_id"); - let image_id = match Uuid::parse_str(&image_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的图片UUID格式: {} - 错误: {}", image_id_str, e); - continue; - } - }; - - let album_id_str = row.get::("album_id"); - let album_id = match Uuid::parse_str(&album_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的相册UUID格式: {} - 错误: {}", album_id_str, e); - continue; - } - }; - - let favorite = Favorite { - id: favorite_id, - user_id: row.get("user_id"), - image_id, - album_id, - created_at: row.get::("favorite_created_at"), - }; - - let image = Image { - id: image_id, - album_id, - filename: row.get("filename"), - original_url: row.get("original_url"), - title: row.get("title"), - description: row.get("description"), - file_size: row.get("file_size"), - width: row.get("width"), - height: row.get("height"), - mime_type: row.get("mime_type"), - created_at: row.get::("image_created_at"), - }; - - favorites.push(FavoriteWithImage { - favorite, - image, - album_title: row.get("album_title"), - }); - } - - Ok(favorites) - } - - // 检查图片是否被用户收藏 - pub async fn get_favorite_status(&self, user_id: &str, image_id: Uuid) -> Result { - let row = sqlx::query( - "SELECT id FROM favorites WHERE user_id = ? AND image_id = ?" - ) - .bind(user_id) - .bind(image_id.to_string()) - .fetch_optional(&self.pool) - .await?; - - if let Some(row) = row { - let favorite_id_str = row.get::("id"); - let favorite_id = match Uuid::parse_str(&favorite_id_str) { - Ok(uuid) => Some(uuid), - Err(e) => { - eprintln!("无效的收藏UUID格式: {} - 错误: {}", favorite_id_str, e); - None - } - }; - - Ok(FavoriteStatus { - is_favorited: true, - favorite_id, - }) - } else { - Ok(FavoriteStatus { - is_favorited: false, - favorite_id: None, - }) - } - } - - // 添加收藏 - pub async fn add_favorite(&self, user_id: &str, favorite_data: CreateFavorite) -> Result { - let favorite_id = Uuid::new_v4(); - let now = chrono::Utc::now().to_rfc3339(); - - sqlx::query( - "INSERT INTO favorites (id, user_id, image_id, album_id, created_at) VALUES (?, ?, ?, ?, ?)" - ) - .bind(favorite_id.to_string()) - .bind(user_id) - .bind(favorite_data.image_id.to_string()) - .bind(favorite_data.album_id.to_string()) - .bind(&now) - .execute(&self.pool) - .await?; - - Ok(favorite_id) - } - - // 移除收藏(通过收藏ID) - pub async fn remove_favorite(&self, favorite_id: Uuid) -> Result<(), sqlx::Error> { - sqlx::query( - "DELETE FROM favorites WHERE id = ?" - ) - .bind(favorite_id.to_string()) - .execute(&self.pool) - .await?; - - Ok(()) - } - - // 移除收藏(通过用户ID和图片ID) - pub async fn remove_favorite_by_image(&self, user_id: &str, image_id: Uuid) -> Result<(), sqlx::Error> { - sqlx::query( - "DELETE FROM favorites WHERE user_id = ? AND image_id = ?" - ) - .bind(user_id) - .bind(image_id.to_string()) - .execute(&self.pool) - .await?; - - Ok(()) - } - - /// 获取配置 - pub fn get_config(&self) -> &Config { - &self.config - } - - /// 获取未处理的图片(即缩略图可能不存在的图片) - pub async fn get_unprocessed_images(&self, limit: i64) -> Result, sqlx::Error> { - let rows = sqlx::query( - r#" - SELECT * FROM images - ORDER BY created_at DESC - LIMIT ? - "# - ) - .bind(limit) - .fetch_all(&self.pool) - .await?; - - let mut images = Vec::new(); - for row in rows { - let image_id_str = row.get::("id"); - let image_id = match Uuid::parse_str(&image_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的图片UUID格式: {} - 错误: {}", image_id_str, e); - continue; - } - }; - - let album_id_str = row.get::("album_id"); - let album_id = match Uuid::parse_str(&album_id_str) { - Ok(uuid) => uuid, - Err(e) => { - eprintln!("无效的相册UUID格式: {} - 错误: {}", album_id_str, e); - continue; - } - }; - - images.push(Image { - id: image_id, - album_id, - filename: row.get("filename"), - original_url: row.get("original_url"), - title: row.get("title"), - description: row.get("description"), - file_size: row.get("file_size"), - width: row.get("width"), - height: row.get("height"), - mime_type: row.get("mime_type"), - created_at: row.get::("created_at"), - }); - } - - Ok(images) - } -} \ No newline at end of file diff --git a/src/image_processor.rs b/src/image_processor.rs index a82c6d1..360bb7e 100644 --- a/src/image_processor.rs +++ b/src/image_processor.rs @@ -1,5 +1,5 @@ use crate::config::StorageConfig; -use image::{GenericImageView, ImageFormat}; +use image::GenericImageView; use std::fs; use std::path::Path; use thiserror::Error; diff --git a/src/import.rs b/src/import.rs deleted file mode 100644 index c09a9e3..0000000 --- a/src/import.rs +++ /dev/null @@ -1,446 +0,0 @@ -use std::fs; -use std::path::Path; -use std::sync::Arc; -use image::GenericImageView; -use serde::Deserialize; -use tokio::task; -use uuid::Uuid; -use crate::config::Config; -use crate::database::Database; -use crate::models::*; - -/// 批量插入图片并设置封面缩略图的辅助函数 -async fn batch_insert_images_and_set_cover( - db: &Database, - images_to_insert: Vec, - album_id: Uuid, - album_path: &Path, - folder_name: &str, -) -> Result> { - if images_to_insert.is_empty() { - return Ok(0); - } - - println!(" 批量插入 {} 张图片...", images_to_insert.len()); - match db.add_images(images_to_insert).await { - Ok(ids) => { - println!(" 批量插入成功,共插入 {} 张图片", ids.len()); - - // 设置第一张图片为封面图片并生成缩略图 - if let Some(first_image_id) = ids.first() { - println!(" 设置第一张图片为封面图片 (ID: {})...", first_image_id); - - // 更新相册的封面图片ID - if let Err(e) = db.update_album_cover(album_id, Some(*first_image_id)).await { - eprintln!(" 更新相册封面失败: {}", e); - } - - // 获取第一张图片的信息 - if let Ok(Some(first_image)) = db.get_image(*first_image_id).await { - println!(" 封面图片已设置: {}", first_image.filename); - } - } - - Ok(ids.len()) - } - Err(e) => { - eprintln!(" 批量插入失败: {}", e); - Ok(0) - } - } -} - - -pub async fn import_existing_data(config: &Config, db: Arc, _task_queue: Option>) -> Result<(), Box> { - println!("开始扫描图片目录并导入新相册..."); - - let albums_dir = Path::new(&config.storage.images_dir); - - if !albums_dir.exists() { - println!("albums目录不存在,跳过导入"); - return Ok(()); - } - - // 获取数据库中现有的相册列表 - let existing_albums = db.get_all_albums().await?; - let existing_titles: Vec = existing_albums.iter() - .map(|album| album.document.to_lowercase()) - .collect(); - - println!("数据库中现有相册数量: {}", existing_albums.len()); - - // 第一阶段:检查并重新导入失败的相册 - println!("🔍 检查需要重新导入的相册..."); - let mut reimported_count = 0; - let mut deleted_count = 0; - - for album in &existing_albums { - let album_folder_path = albums_dir.join(&album.document); - - // 检查相册文件夹是否存在 - if !album_folder_path.exists() { - // 文件夹不存在,删除数据库中的相册记录 - println!("🗑️ 相册文件夹不存在,删除相册: {}", album.document); - if let Err(e) = db.delete_album(album.id).await { - eprintln!("❌ 删除相册失败: {}", e); - } else { - deleted_count += 1; - } - continue; - } - - // 检查相册是否有图片 - let image_count = db.get_album_image_count(album.id).await.unwrap_or(0); - if image_count == 0 { - // 相册存在但没有图片,尝试重新导入 - println!("🔄 重新导入相册: {} (图片数量: 0)", album.document); - match reimport_single_album(&db, &album.document, &album_folder_path, album.id).await { - Ok(count) => { - if count > 0 { - reimported_count += 1; - println!("✅ 相册 {} 重新导入成功,导入 {} 张图片", album.document, count); - } else { - println!("⚠️ 相册 {} 重新导入但没有找到图片", album.document); - } - } - Err(e) => { - eprintln!("❌ 相册 {} 重新导入失败: {}", album.document, e); - } - } - } - } - - if reimported_count > 0 || deleted_count > 0 { - println!("🎯 重新导入完成: 重新导入 {} 个相册,删除 {} 个相册", reimported_count, deleted_count); - } - - // 第二阶段:快速扫描所有相册文件夹,导入新相册 - let entries: Vec<_> = fs::read_dir(albums_dir)?.collect::, _>>()?; - let mut album_folders = Vec::new(); - - for entry in entries { - let path = entry.path(); - if path.is_dir() { - if let Some(folder_name) = path.file_name().and_then(|s| s.to_str()) { - // 检查是否已存在同名相册 - if existing_titles.contains(&folder_name.to_lowercase()) { - continue; - } - album_folders.push((folder_name.to_string(), path)); - } - } - } - - println!("发现 {} 个新相册需要导入", album_folders.len()); - - if album_folders.is_empty() { - println!("没有新相册需要导入"); - return Ok(()); - } - - // 使用简单的串行处理方式导入相册 - println!("📁 开始导入新相册..."); - - let mut total_imported = 0; - let mut successful_albums = 0; - - for (folder_name, path) in album_folders { - println!("📁 开始导入相册: {}", folder_name); - - match import_single_album(&db, &folder_name, &path).await { - Ok(count) => { - if count > 0 { - successful_albums += 1; - total_imported += count; - println!("✅ 相册 {} 导入完成,共导入 {} 张图片", folder_name, count); - } else { - println!("⚠️ 相册 {} 没有图片需要导入", folder_name); - } - } - Err(e) => { - eprintln!("❌ 相册 {} 导入失败: {}", folder_name, e); - // 继续处理下一个相册,不中断整个导入过程 - } - } - } - - println!("🎉 导入完成!成功导入 {} 个相册,共 {} 张图片", successful_albums, total_imported); - - Ok(()) -} - -/// 导入单个相册的辅助函数 -async fn import_single_album(db: &Database, folder_name: &str, path: &Path) -> Result> { - println!("📁 开始导入相册: {}", folder_name); - - // 读取index.json文件 - let index_file_path = path.join("index.json"); - let album_title = if index_file_path.exists() { - match fs::read_to_string(&index_file_path) { - Ok(content) => { - match serde_json::from_str::(&content) { - Ok(index) => { - println!(" 从index.json读取相册标题: {}", index.title); - index.title - } - Err(e) => { - println!(" 解析index.json失败: {}, 使用文件夹名作为标题", e); - folder_name.to_string() - } - } - } - Err(e) => { - println!(" 读取index.json失败: {}, 使用文件夹名作为标题", e); - folder_name.to_string() - } - } - } else { - println!(" index.json不存在,使用文件夹名作为标题"); - folder_name.to_string() - }; - - // 创建新相册 - let new_album = CreateAlbum { - title: album_title.clone(), - document: folder_name.to_string(), - description: Some(format!("从文件夹 {} 自动导入的相册", folder_name)), - }; - - let album_id = db.create_album(new_album).await?; - println!(" 创建相册: {} (ID: {})", album_title, album_id); - - // 读取图片URL列表(如果有index.json) - let image_urls = if index_file_path.exists() { - match fs::read_to_string(&index_file_path) { - Ok(content) => { - match serde_json::from_str::(&content) { - Ok(index) => { - println!(" 从index.json读取到 {} 个图片URL", index.images.len()); - Some(index.images) - } - Err(_) => None - } - } - Err(_) => None - } - } else { - None - }; - - // 快速扫描图片文件 - let image_files = scan_image_files(path, folder_name)?; - - if image_files.is_empty() { - println!(" 相册 {} 中没有找到图片文件", folder_name); - return Ok(0); - } - - println!(" 发现 {} 张图片,开始处理...", image_files.len()); - - // 并行处理图片信息获取 - let mut image_tasks = Vec::new(); - - for (index, (filename, image_path)) in image_files.iter().enumerate() { - let image_url = image_urls.as_ref().and_then(|urls| { - if urls.len() > index { - Some(urls[index].clone()) - } else { - None - } - }); - - let filename_clone = filename.clone(); - let image_path_clone = image_path.clone(); - let album_id_clone = album_id; - let folder_name_clone = folder_name.to_string(); - - let task = task::spawn_blocking(move || { - // 在阻塞线程中处理图片信息 - let (file_size, width, height) = match get_image_info(&image_path_clone) { - Ok(info) => info, - Err(e) => { - eprintln!("获取图片信息失败: {} - {}", image_path_clone.display(), e); - (0, 0, 0) - } - }; - - CreateImage { - album_id: album_id_clone, - filename: format!("{}/{}", folder_name_clone, filename_clone), - original_url: image_url, - title: Some(format!("图片 {}", index + 1)), - description: Some(format!("从文件夹 {} 导入的图片", folder_name_clone)), - file_size, - width, - height, - mime_type: match image_path_clone.extension().and_then(|s| s.to_str()).unwrap_or("jpg").to_lowercase().as_str() { - "jpg" | "jpeg" => "image/jpeg".to_string(), - "png" => "image/png".to_string(), - "gif" => "image/gif".to_string(), - "webp" => "image/webp".to_string(), - "bmp" => "image/bmp".to_string(), - _ => "image/jpeg".to_string(), - }, - } - }); - - image_tasks.push(task); - } - - // 收集所有图片信息 - let mut images_to_insert = Vec::new(); - for task in image_tasks { - match task.await { - Ok(image) => images_to_insert.push(image), - Err(e) => eprintln!("图片处理任务失败: {}", e), - } - } - - // 使用辅助函数批量插入图片并设置封面 - batch_insert_images_and_set_cover(&db, images_to_insert, album_id, path, folder_name).await -} - -/// 快速扫描图片文件 -pub(crate) fn scan_image_files(path: &Path, _folder_name: &str) -> Result, Box> { - let mut image_files = Vec::new(); - - for entry in fs::read_dir(path)? { - let entry = entry?; - let image_path = entry.path(); - - if image_path.is_file() { - if let Some(extension) = image_path.extension().and_then(|s| s.to_str()) { - let valid_extensions = ["jpg", "jpeg", "png", "gif", "webp", "bmp"]; - - if valid_extensions.contains(&extension.to_lowercase().as_str()) { - let filename = image_path.file_name() - .and_then(|s| s.to_str()) - .unwrap_or("unknown.jpg") - .to_string(); - - image_files.push((filename, image_path)); - } - } - } - } - - // 按数字顺序排序文件名 - image_files.sort_by(|a, b| { - // 提取文件名中的数字部分进行排序 - let num_a = a.0.chars() - .take_while(|c| c.is_ascii_digit()) - .collect::() - .parse::() - .unwrap_or(0); - - let num_b = b.0.chars() - .take_while(|c| c.is_ascii_digit()) - .collect::() - .parse::() - .unwrap_or(0); - - num_a.cmp(&num_b) - }); - - Ok(image_files) -} - -/// 获取图片的实际信息(文件大小、宽度、高度) -fn get_image_info(image_path: &Path) -> Result<(i64, i32, i32), Box> { - // 获取文件大小 - let metadata = fs::metadata(image_path)?; - let file_size = metadata.len() as i64; - - // 使用image库获取图片尺寸 - let img = image::open(image_path)?; - let (width, height) = img.dimensions(); - - Ok((file_size, width as i32, height as i32)) -} - -/// 重新导入单个相册(使用现有的相册ID) -async fn reimport_single_album( - db: &Database, - folder_name: &str, - path: &Path, - album_id: Uuid, -) -> Result> { - println!("📁 重新导入相册: {} (ID: {})", folder_name, album_id); - - // 读取index.json文件 - let index_file_path = path.join("index.json"); - let album_title = if index_file_path.exists() { - match fs::read_to_string(&index_file_path) { - Ok(content) => { - match serde_json::from_str::(&content) { - Ok(index) => index.title, - Err(_) => folder_name.to_string(), - } - } - Err(_) => folder_name.to_string(), - } - } else { - folder_name.to_string() - }; - - println!(" 相册标题: {}", album_title); - - // 扫描图片文件 - let mut images_to_insert = Vec::new(); - let image_extensions = ["jpg", "jpeg", "png", "gif", "webp", "bmp"]; - - let entries: Vec<_> = fs::read_dir(path)?.collect::, _>>()?; - - for entry in entries { - let file_path = entry.path(); - if file_path.is_file() { - if let Some(extension) = file_path.extension().and_then(|ext| ext.to_str()) { - if image_extensions.contains(&extension.to_lowercase().as_str()) { - if let Some(filename) = file_path.file_name().and_then(|s| s.to_str()) { - // 跳过index.json文件 - if filename == "index.json" { - continue; - } - - // 获取图片信息 - let (file_size, width, height) = match get_image_info(&file_path) { - Ok(info) => info, - Err(e) => { - eprintln!(" 获取图片信息失败 {}: {}", filename, e); - continue; - } - }; - - let image = CreateImage { - album_id, - filename: format!("{}/{}", folder_name, filename), - original_url: Some(format!("/images/{}/{}", folder_name, filename)), - title: Some(filename.to_string()), - description: Some(String::new()), - file_size, - width, - height, - mime_type: match extension.to_lowercase().as_str() { - "jpg" | "jpeg" => "image/jpeg".to_string(), - "png" => "image/png".to_string(), - "gif" => "image/gif".to_string(), - "webp" => "image/webp".to_string(), - "bmp" => "image/bmp".to_string(), - _ => "application/octet-stream".to_string(), - }, - }; - - images_to_insert.push(image); - } - } - } - } - } - - println!(" 发现 {} 张图片需要导入", images_to_insert.len()); - - // 使用辅助函数批量插入图片并设置封面 - batch_insert_images_and_set_cover(&db, images_to_insert, album_id, path, folder_name).await -} - -// 缩略图生成功能已移除 \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 500d9f8..a26aca6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,23 +1,26 @@ mod config; -mod database; -mod image_processor; -mod import; mod models; -mod queue; +mod db; +mod engine; +mod cache; mod routes; +mod services; +mod image_processor; +mod queue; -use crate::models::AlbumsCache; +use crate::cache::AlbumsCache; use actix_files as afs; use actix_web::{App, HttpResponse, HttpServer, middleware, web}; use std::fs; use std::sync::Arc; use tokio::time::{Duration, interval}; use tracing::{error, info}; + #[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; + #[actix_web::main] async fn main() -> std::io::Result<()> { - // 初始化结构化日志 tracing_subscriber::fmt::init(); // 加载配置 @@ -29,11 +32,11 @@ async fn main() -> std::io::Result<()> { } }; - info!("启动图片展示服务..."); - info!("服务地址: http://localhost:{} http://{}", config.server.port, config.server_address()); + info!("启动图片展示服务 v2.0..."); + info!("服务地址: http://{}", config.server_address()); // 初始化数据库 - let db = match database::Database::new(&config).await { + let db = match db::Database::new(&config).await { Ok(db) => { info!("数据库连接成功"); Arc::new(db) @@ -44,23 +47,34 @@ async fn main() -> std::io::Result<()> { } }; + // 自动迁移老数据库 + if let Some(ref old_db_cfg) = config.old_db { + if old_db_cfg.auto_migrate { + info!("[迁移] 检测到 old_db 配置,自动迁移: {}", old_db_cfg.path); + match db.migrate_from_old_db(&old_db_cfg.path).await { + Ok(stats) => info!("[迁移] {}", db.migration_summary(&stats)), + Err(e) => error!("[迁移] 失败: {}", e), + } + } + } + let image_processor = Arc::new(image_processor::ImageProcessor::new(config.storage.clone())); - // 在后台线程中自动导入新相册(不阻塞HTTP服务启动) + // 后台导入本地相册 let config_clone = config.clone(); let db_clone = Arc::clone(&db); tokio::spawn(async move { info!("[后台任务] 开始扫描图片目录并导入新相册..."); - match import::import_existing_data(&config_clone, db_clone, None).await { + match services::import::import_existing_data(&config_clone, db_clone, None).await { Ok(_) => info!("[后台任务] 相册导入完成"), Err(e) => error!("[后台任务] 相册导入失败: {}", e), } }); - // 初始化相册内存缓存 + // 相册内存缓存 let albums_cache = Arc::new(tokio::sync::RwLock::new(AlbumsCache::new())); - // 初始加载相册数据到缓存 + // 初始加载缓存 let initial_cache = Arc::clone(&albums_cache); let initial_db = Arc::clone(&db); tokio::spawn(async move { @@ -76,15 +90,13 @@ async fn main() -> std::io::Result<()> { } }); - // 设置定时刷新缓存任务(每30分钟) + // 定时刷新缓存(每30分钟) let refresh_cache = Arc::clone(&albums_cache); let refresh_db = Arc::clone(&db); tokio::spawn(async move { - let mut interval = interval(Duration::from_secs(30 * 60)); // 30分钟 - + let mut interval = interval(Duration::from_secs(30 * 60)); loop { interval.tick().await; - match refresh_db.get_all_albums().await { Ok(albums) => { let mut cache = refresh_cache.write().await; @@ -98,61 +110,88 @@ async fn main() -> std::io::Result<()> { } }); - + // 任务队列 + let task_queue = Arc::new(queue::TaskQueue::new( + config.queue.max_concurrent_tasks, + config.queue.queue_size_limit, + config.queue.high_request_rate_threshold, + config.queue.idle_request_rate_threshold, + )); println!("API接口:"); println!(" - GET /api/albums - 获取所有相册"); println!(" - GET /api/search?q=关键词 - 搜索相册"); + println!(" - GET /api/album/random - 随机相册"); println!(" - GET /api/album/:id - 获取相册详情"); println!(" - POST /api/albums - 创建新相册"); - println!(" - GET /api/image/:id - 获取图片(已移除缩略图功能)"); - println!(" - GET /api/favorites - 获取收藏列表"); - println!(" - GET /api/favorites/status/:id - 检查收藏状态"); + println!(" - GET /api/image/:id - 获取图片"); + println!(" - GET /api/favorites - 收藏列表"); println!(" - POST /api/favorites - 添加收藏"); println!(" - DELETE /api/favorites/:id - 取消收藏"); - println!(" - DELETE /api/favorites/image/:id - 通过图片ID取消收藏"); + println!("元数据接口:"); + println!(" - GET /api/people - 人员列表"); + println!(" - GET /api/people/search?q=关键词 - 搜索人员"); + println!(" - GET /api/people/{{name}} - 人员详情"); + println!(" - GET /api/people/{{id}}/aliases - 人员别名"); + println!(" - GET /api/metadata/stats - 元数据统计"); + println!(" - GET /api/tags/search?tag=标签 - 按标签搜索"); + println!(" - GET /api/tags/popular?limit=50 - 热门标签"); + println!("推荐接口:"); + println!(" - GET /api/recommend/tags?q=xxx - 标签推荐"); + println!(" - GET /api/recommend/persons?q=xxx - 人物推荐"); + println!(" - GET /api/recommend/related?context=xxx - 关联推荐"); + println!(" - GET /api/recommend/popular-persons - 热门人物"); + println!("迁移接口:"); + println!(" - GET /api/migration/stats - 迁移状态"); + println!(" - POST /api/migration/run?path=persons.db - 执行迁移"); + println!(" - GET /api/queue/stats - 队列状态"); println!("按 Ctrl+C 停止服务"); - // 创建数据目录 fs::create_dir_all(&config.storage.images_dir).unwrap_or(()); - // 在闭包外提取需要的路径 - let server_address = config.server_address(); - HttpServer::new(move || { App::new() - // 启用压缩中间件 .wrap(middleware::Compress::default()) - // 启用日志中间件 .wrap(middleware::Logger::default()) .app_data(web::Data::new(Arc::clone(&db))) .app_data(web::Data::new(Arc::clone(&image_processor))) .app_data(web::Data::new(Arc::clone(&albums_cache))) - // API路由 + .app_data(web::Data::new(Arc::clone(&task_queue))) + // 相册 API .route("/api/albums", web::get().to(routes::get_albums)) .route("/api/search", web::get().to(routes::search_albums)) .route("/api/album/random", web::get().to(routes::get_random_album)) .route("/api/album/{id}", web::get().to(routes::get_album_detail)) .route("/api/albums", web::post().to(routes::create_album)) .route("/api/image/{id}", web::get().to(routes::get_image)) - // 收藏功能API路由 + // 收藏 API .route("/api/favorites", web::get().to(routes::get_favorites)) - .route( - "/api/favorites/status/{id}", - web::get().to(routes::check_favorite_status), - ) + .route("/api/favorites/status/{id}", web::get().to(routes::check_favorite_status)) .route("/api/favorites", web::post().to(routes::add_favorite)) - .route( - "/api/favorites/{id}", - web::delete().to(routes::remove_favorite), - ) - .route( - "/api/favorites/image/{id}", - web::delete().to(routes::remove_favorite_by_image), - ) - // 队列状态API路由 + .route("/api/favorites/{id}", web::delete().to(routes::remove_favorite)) + .route("/api/favorites/image/{id}", web::delete().to(routes::remove_favorite_by_image)) + // 人员 API + .route("/api/people", web::get().to(routes::get_people)) + .route("/api/people/search", web::get().to(routes::search_people)) + .route("/api/people/{name}", web::get().to(routes::get_person_detail)) + .route("/api/people/{id}/aliases", web::get().to(routes::get_person_aliases)) + // 标签 API + .route("/api/metadata/stats", web::get().to(routes::get_metadata_stats)) + .route("/api/tags/search", web::get().to(routes::search_by_tag)) + .route("/api/tags/popular", web::get().to(routes::get_popular_tags)) + // 推荐 API + .route("/api/recommend/tags", web::get().to(routes::recommend_tags)) + .route("/api/recommend/persons", web::get().to(routes::recommend_persons)) + .route("/api/recommend/related", web::get().to(routes::recommend_related)) + .route("/api/recommend/popular-persons", web::get().to(routes::popular_persons)) + // 迁移 API + .route("/api/migration/stats", web::get().to(routes::migration_stats)) + .route("/api/migration/run", web::post().to(routes::migration_run)) + // 管线 API + .route("/api/pipeline/run", web::post().to(routes::pipeline_run)) + // 队列 API .route("/api/queue/stats", web::get().to(routes::get_queue_stats)) - // 静态文件服务 - 启用缓存 + // 静态文件 .service( afs::Files::new("/assets", "./assets") .show_files_listing() @@ -160,33 +199,24 @@ async fn main() -> std::io::Result<()> { .use_last_modified(true) .use_etag(true), ) - // HTML页面路由 - .route( - "/", - web::get().to(|| async { - match fs::read_to_string("./assets/index.html") { - Ok(content) => HttpResponse::Ok() - .content_type("text/html; charset=utf-8") - .body(content), - Err(_) => HttpResponse::NotFound().body("首页文件不存在"), - } - }), - ) - .route( - "/album", - web::get().to(|| async { - match fs::read_to_string("./assets/album.html") { - Ok(content) => HttpResponse::Ok() - .content_type("text/html; charset=utf-8") - .body(content), - Err(_) => HttpResponse::NotFound().body("相册页面文件不存在"), - } - }), - ) + .route("/", web::get().to(|| async { + match fs::read_to_string("./assets/index.html") { + Ok(content) => HttpResponse::Ok() + .content_type("text/html; charset=utf-8") + .body(content), + Err(_) => HttpResponse::NotFound().body("首页文件不存在"), + } + })) + .route("/album", web::get().to(|| async { + match fs::read_to_string("./assets/album.html") { + Ok(content) => HttpResponse::Ok() + .content_type("text/html; charset=utf-8") + .body(content), + Err(_) => HttpResponse::NotFound().body("相册页面不存在"), + } + })) }) - .bind(server_address)? - // 限制worker数量为2个,减少系统资源占用 - .workers(3) + .bind(config.server_address())? .run() .await } \ No newline at end of file diff --git a/src/models.rs b/src/models.rs deleted file mode 100644 index b69cbd6..0000000 --- a/src/models.rs +++ /dev/null @@ -1,230 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use tracing::info; -use uuid::Uuid; - -#[derive(Debug, Serialize, Deserialize)] -pub struct Album { - pub id: Uuid, - pub title: String, - pub description: Option, - pub cover_image_id: Option, - pub image_count: i64, // 新增图片数量字段 - pub created_at: String, - pub updated_at: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Image { - pub id: Uuid, - pub album_id: Uuid, - pub filename: String, - pub original_url: Option, - pub title: Option, - pub description: Option, - pub file_size: i64, - pub width: i32, - pub height: i32, - pub mime_type: String, - pub created_at: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct AlbumWithImages { - pub album: Album, - pub images: Vec, - pub image_count: i64, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct AlbumInfo { - pub id: Uuid, - pub title: String, - pub document: String, - pub description: Option, - pub cover_image_id: Option, - pub image_count: i64, - pub created_at: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct CreateAlbum { - pub title: String, - pub document: String, - pub description: Option, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct CreateImage { - pub album_id: Uuid, - pub filename: String, - pub original_url: Option, - pub title: Option, - pub description: Option, - pub file_size: i64, - pub width: i32, - pub height: i32, - pub mime_type: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct Favorite { - pub id: Uuid, - pub user_id: String, - pub image_id: Uuid, - pub album_id: Uuid, - pub created_at: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct CreateFavorite { - pub image_id: Uuid, - pub album_id: Uuid, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct FavoriteWithImage { - pub favorite: Favorite, - pub image: Image, - pub album_title: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct FavoriteStatus { - pub is_favorited: bool, - pub favorite_id: Option, -} -#[derive(Debug, Deserialize)] -pub struct AlbumIndex { - pub title: String, - pub images: Vec, -} -// 内存缓存结构 -#[derive(Debug, Clone)] -pub struct AlbumsCache { - pub albums: Vec, - pub search_index: HashMap>, - pub last_updated: chrono::DateTime, -} - -impl AlbumsCache { - pub fn new() -> Self { - Self { - albums: Vec::new(), - search_index: 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) { - self.albums = albums; // 不再克隆整个向量,而是移动所有权 - 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) - .or_insert_with(Vec::new) - .push(album.clone()); // 这里仍需要克隆单个元素 - } - - info!( - "相册缓存已更新,共 {} 个相册,{} 个搜索索引项", - self.albums.len(), - self.search_index.len() - ); - } - - pub fn search(&self, query: &str) -> Vec { - let query_lower = query.to_lowercase().trim().to_string(); - - if query_lower.is_empty() { - return Vec::new(); - } - - let mut results = Vec::new(); - let mut seen_ids = std::collections::HashSet::new(); - - // 1. 搜索完整匹配(最高优先级) - if let Some(matches) = self.search_index.get(&query_lower) { - for album in matches { - if seen_ids.insert(album.id) { - results.push(album.clone()); - } - } - } - - // 2. 搜索单词匹配 - for word in query_lower.split_whitespace() { - if word.len() >= 2 { - // 只搜索长度>=2的单词 - if let Some(matches) = self.search_index.get(word) { - for album in matches { - if seen_ids.insert(album.id) { - results.push(album.clone()); - } - } - } - } - } - - // 3. 模糊搜索:在相册标题和描述中搜索包含查询词的结果 - if results.is_empty() { - for album in &self.albums { - let title_lower = album.title.to_lowercase(); - let description_lower = album - .description - .as_ref() - .map(|d| d.to_lowercase()) - .unwrap_or_default(); - - // 检查标题或描述是否包含搜索词 - if title_lower.contains(&query_lower) || description_lower.contains(&query_lower) { - if seen_ids.insert(album.id) { - results.push(album.clone()); - } - } - } - } - - // 4. 如果还没有结果,尝试部分匹配(更宽松的搜索) - if results.is_empty() && query_lower.len() >= 2 { - for album in &self.albums { - let title_lower = album.title.to_lowercase(); - - // 检查标题是否包含搜索词的任何部分 - if query_lower - .split_whitespace() - .any(|word| word.len() >= 2 && title_lower.contains(word)) - { - if seen_ids.insert(album.id) { - results.push(album.clone()); - } - } - } - } - - results - } -} \ No newline at end of file diff --git a/src/queue.rs b/src/queue.rs index 8797b7b..8e13a30 100644 --- a/src/queue.rs +++ b/src/queue.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, AtomicBool}; use std::time::{Duration, Instant}; use tokio::sync::Notify; -use tracing::{info, debug}; +use tracing::info; /// 队列统计信息 #[derive(Debug, Clone, Serialize, Deserialize)] @@ -34,7 +34,7 @@ impl TaskQueue { } } - pub fn new_with_db(_max_concurrent_tasks: usize, _queue_size_limit: usize, _high_request_rate_threshold: f64, _idle_request_rate_threshold: f64, _db: Arc) -> Self { + pub fn new_with_db(_max_concurrent_tasks: usize, _queue_size_limit: usize, _high_request_rate_threshold: f64, _idle_request_rate_threshold: f64, _db: Arc) -> Self { Self { // HTTP请求频率监控 request_count: AtomicU64::new(0), diff --git a/src/routes.rs b/src/routes.rs deleted file mode 100644 index 1305d7a..0000000 --- a/src/routes.rs +++ /dev/null @@ -1,365 +0,0 @@ -use crate::database::Database; -use crate::image_processor::ImageProcessor; -use crate::models::*; -use actix_web::{HttpResponse, Responder, web}; -use std::fs; -use std::sync::Arc; -use tokio::sync::RwLock; -use tracing::error; -use uuid::Uuid; -use crate::queue; - - - -// 收藏功能API路由 - -// 获取用户的收藏列表 -pub async fn get_favorites(db: web::Data>) -> impl Responder { - // 这里使用固定用户ID,实际项目中应该从认证信息中获取 - let user_id = "default_user".to_string(); - - let favorites = match db.get_user_favorites(&user_id).await { - Ok(value) => value, - Err(e) => { - error!("获取收藏列表失败: {}", e); - return HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "获取收藏列表失败" - })); - } - }; - - HttpResponse::Ok().json(favorites) -} - -// 图片质量检查功能已移除,直接返回原始图片 - -// 检查图片是否被收藏 -pub async fn check_favorite_status( - db: web::Data>, - path: web::Path, -) -> impl Responder { - let image_id = match Uuid::parse_str(&path.into_inner()) { - Ok(id) => id, - Err(_) => { - return HttpResponse::BadRequest().json(serde_json::json!({ - "error": "无效的图片ID" - })); - } - }; - - // 这里使用固定用户ID,实际项目中应该从认证信息中获取 - let user_id = "default_user".to_string(); - - let status = match db.get_favorite_status(&user_id, image_id).await { - Ok(value) => value, - Err(e) => { - error!("检查收藏状态失败: {}", e); - return HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "检查收藏状态失败" - })); - } - }; - - HttpResponse::Ok().json(status) -} - -// 添加收藏 -pub async fn add_favorite( - db: web::Data>, - favorite_data: web::Json, -) -> impl Responder { - // 这里使用固定用户ID,实际项目中应该从认证信息中获取 - let user_id = "default_user".to_string(); - - match db.add_favorite(&user_id, favorite_data.into_inner()).await { - Ok(favorite_id) => HttpResponse::Created().json(serde_json::json!({ - "id": favorite_id, - "message": "收藏成功" - })), - Err(e) => { - eprintln!("添加收藏失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "添加收藏失败" - })) - } - } -} - -// 取消收藏 -pub async fn remove_favorite( - db: web::Data>, - path: web::Path, -) -> impl Responder { - let favorite_id = match Uuid::parse_str(&path.into_inner()) { - Ok(id) => id, - Err(_) => { - return HttpResponse::BadRequest().json(serde_json::json!({ - "error": "无效的收藏ID" - })); - } - }; - - match db.remove_favorite(favorite_id).await { - Ok(_) => HttpResponse::Ok().json(serde_json::json!({ - "message": "取消收藏成功" - })), - Err(e) => { - eprintln!("取消收藏失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "取消收藏失败" - })) - } - } -} - -// 获取任务队列状态 -pub async fn get_queue_stats( - task_queue: web::Data>, -) -> impl Responder { - // 记录HTTP请求频率 - task_queue.record_http_request().await; - - let stats = task_queue.get_stats().await; - HttpResponse::Ok().json(stats) -} - -// 通过图片ID取消收藏 -pub async fn remove_favorite_by_image( - db: web::Data>, - path: web::Path, -) -> impl Responder { - let image_id = match Uuid::parse_str(&path.into_inner()) { - Ok(id) => id, - Err(_) => { - return HttpResponse::BadRequest().json(serde_json::json!({ - "error": "无效的图片ID" - })); - } - }; - - // 这里使用固定用户ID,实际项目中应该从认证信息中获取 - let user_id = "default_user".to_string(); - - match db.remove_favorite_by_image(&user_id, image_id).await { - Ok(_) => HttpResponse::Ok().json(serde_json::json!({ - "message": "取消收藏成功" - })), - Err(e) => { - eprintln!("取消收藏失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "取消收藏失败" - })) - } - } -} - - - -pub async fn get_albums(albums_cache: web::Data>>) -> impl Responder { - // 从内存缓存获取数据 - let cache = albums_cache.read().await; - let total_albums = cache.albums.len(); - - // 应用分页 - let start = 0; - let end = total_albums; - let paginated_albums = if start < end { - cache.albums[start..end].to_vec() - } else { - Vec::new() - }; - - drop(cache); // 释放读锁 - - HttpResponse::Ok().json(paginated_albums) -} - -pub async fn search_albums( - albums_cache: web::Data>>, - query: web::Query>, -) -> impl Responder { - let q = query.get("q").map(|s| s.as_str()).unwrap_or(""); - - // 输入验证 - if q.len() > 100 { - return HttpResponse::BadRequest().json(serde_json::json!({ - "error": "搜索查询过长,最多100个字符" - })); - } - - // 允许Unicode字符(包括中文)、ASCII图形字符和空白字符 - // 只阻止控制字符和其他潜在危险字符 - if q.chars().any(|c| c.is_control() || c == '\0') { - return HttpResponse::BadRequest().json(serde_json::json!({ - "error": "搜索查询包含无效字符" - })); - } - - let page = query - .get("page") - .and_then(|s| s.parse::().ok()) - .unwrap_or(1); - let limit = query - .get("limit") - .and_then(|s| s.parse::().ok()) - .unwrap_or(50); - let offset = (page - 1) * limit; - - if q.is_empty() { - // 如果没有搜索词,返回所有相册(带分页) - let cache = albums_cache.read().await; - let total_albums = cache.albums.len(); - - // 应用分页 - let start = offset.min(total_albums); - let end = (offset + limit).min(total_albums); - let paginated_albums = if start < end { - cache.albums[start..end].to_vec() - } else { - Vec::new() - }; - - drop(cache); - return HttpResponse::Ok().json(paginated_albums); - } - - // 从内存缓存搜索 - let cache = albums_cache.read().await; - let mut search_results = cache.search(q); - - // 应用分页到搜索结果 - let total_results = search_results.len(); - let start = offset.min(total_results); - let end = (offset + limit).min(total_results); - let paginated_results = if start < end { - search_results.drain(start..end).collect() - } else { - Vec::new() - }; - - drop(cache); - - HttpResponse::Ok().json(paginated_results) -} - -pub async fn get_random_album( - albums_cache: web::Data>>, -) -> impl Responder { - // 从内存缓存获取数据 - let cache = albums_cache.read().await; - - if cache.albums.is_empty() { - drop(cache); - return HttpResponse::NotFound().json(serde_json::json!({ - "error": "没有可用的相册" - })); - } - - // 使用随机数生成器选择一个随机相册 - use rand::Rng; - let mut rng = rand::thread_rng(); - let random_index = rng.gen_range(0..cache.albums.len()); - let random_album = cache.albums[random_index].clone(); - - drop(cache); - - HttpResponse::Ok().json(random_album) -} - -pub async fn get_album_detail( - db: web::Data>, - path: web::Path, -) -> impl Responder { - let album_id = match Uuid::parse_str(&path.into_inner()) { - Ok(id) => id, - Err(_) => { - return HttpResponse::BadRequest().json(serde_json::json!({ - "error": "无效的相册ID" - })); - } - }; - - match db.get_album_with_images(album_id).await { - Ok(Some(album)) => HttpResponse::Ok().json(album), - Ok(None) => HttpResponse::NotFound().json(serde_json::json!({ - "error": "相册不存在" - })), - Err(e) => { - eprintln!("获取相册详情失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "获取相册详情失败" - })) - } - } -} - -pub async fn create_album( - db: web::Data>, - album_data: web::Json, -) -> impl Responder { - match db.create_album(album_data.into_inner()).await { - Ok(album_id) => HttpResponse::Created().json(serde_json::json!({ - "id": album_id, - "message": "相册创建成功" - })), - Err(e) => { - eprintln!("创建相册失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "创建相册失败" - })) - } - } -} - -/// 获取原始图片 -pub async fn get_image( - db: web::Data>, - image_processor: web::Data>, - path: web::Path, -) -> impl Responder { - let image_id = match Uuid::parse_str(&path.into_inner()) { - Ok(id) => id, - Err(_) => { - return HttpResponse::BadRequest().json(serde_json::json!({ - "error": "无效的图片ID" - })); - } - }; - - match db.get_image(image_id).await { - Ok(Some(image)) => { - let original_path = image_processor.config.images_dir.join(&image.filename); - - if original_path.exists() { - match fs::read(&original_path) { - Ok(data) => { - HttpResponse::Ok() - .content_type(image.mime_type.clone()) - .insert_header(("Cache-Control", "public, max-age=31536000")) - .insert_header(("ETag", format!("\"{}\"", image_id))) - .body(data) - } - Err(e) => { - eprintln!("读取原始图片失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "读取图片失败" - })) - } - } - } else { - HttpResponse::NotFound().json(serde_json::json!({ - "error": "图片文件不存在" - })) - } - } - Ok(None) => HttpResponse::NotFound().json(serde_json::json!({ - "error": "图片不存在" - })), - Err(e) => { - eprintln!("获取图片信息失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "获取图片信息失败" - })) - } - } -} \ No newline at end of file