This commit is contained in:
lychang
2026-07-19 15:03:13 +08:00
parent f5336a4ea2
commit b915e69222
16 changed files with 332 additions and 2032 deletions

View File

@@ -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
}