Compare commits

...

19 Commits

Author SHA1 Message Date
lychang
f5336a4ea2 update code level 2026-05-14 01:23:42 +08:00
lychang
e073554754 update code level 2026-05-14 01:23:29 +08:00
lychang
73dbb30e27 update code level 2026-05-14 00:04:35 +08:00
lychang
8f214b587b update code level 2026-05-13 21:08:04 +08:00
lychang
b5df61c78a update code level 2026-03-28 13:23:53 +08:00
lychang
eb43c145cc update code level 2026-03-28 12:56:30 +08:00
lychang
675a402848 update code level 2026-03-28 12:36:26 +08:00
lychang
7a68eb959a update code level 2026-03-25 18:57:14 +08:00
lychang
f6c9141449 update code level 2026-03-25 18:31:11 +08:00
lychang
b7118bd4b9 update code level 2026-03-25 15:20:21 +08:00
lychang
4ff83492f1 update code level 2026-03-25 14:50:50 +08:00
lychang
6b2d44ca78 update code level 2026-03-25 14:38:21 +08:00
lychang
e05cf48063 update code level 2026-03-25 14:06:49 +08:00
lychang
448eef2319 update code level 2026-03-25 07:50:14 +08:00
lychang
e53ee4b2d0 update code level 2026-03-25 07:29:57 +08:00
lychang
af15d9f3d1 update code level 2026-03-25 04:49:36 +08:00
lychang
8a7156128b update code level 2026-03-23 03:26:06 +08:00
lychang
d69c6c6aa3 update code level 2026-03-23 03:07:04 +08:00
lychang
4115c04107 update code level 2026-03-23 02:38:17 +08:00
19 changed files with 2276 additions and 4082 deletions

1
.env
View File

@@ -1 +0,0 @@
DATABASE_URL=sqlite:data/imager.db

View File

@@ -0,0 +1,36 @@
---
name: "image-brotli-processor"
description: "将图片从缩略图改为brotli压缩处理。在需要优化图片存储和传输性能时调用,特别是当用户想要减少图片文件大小和提高加载速度时。"
---
# 图片Brotli压缩处理器
这个skill帮助将传统的缩略图系统改为使用brotli压缩的图片处理系统,以提高性能和减少存储空间。
## 功能
- 将图片处理从传统的缩略图改为brotli压缩
- 添加智能尺寸调整和压缩策略
- 提供向后兼容的API端点
- 优化网络传输和存储效率
## 使用场景
- 当用户想要优化图片加载性能时
- 需要减少图片存储空间占用时
- 想要提高网络传输效率时
- 需要保持图片质量的同时减小文件大小时
## 实现步骤
1. 修改图片处理器,添加brotli压缩功能
2. 添加新的brotli图片服务端点
3. 更新路由配置
4. 修改前端图片引用路径
## 技术优势
- **更高的压缩率**:比gzip高20-30%的压缩效率
- **更快的加载速度**:减小文件大小,提高网络传输效率
- **保持图片质量**:在压缩的同时保持视觉质量
- **浏览器支持**:现代浏览器都支持brotli解码

3464
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -15,3 +15,8 @@ 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"] }
config = "0.13"
rand = "0.8"
tracing = "0.1"
tracing-subscriber = "0.3"
thiserror = "1.0"
mimalloc = "0.1.48"

View File

@@ -124,7 +124,7 @@ body {
object-fit: cover;
}
/* 较宽图片布局 (1.2 < ratio ≤ 1.5) */
/* 较宽图片布局 (1.3 < ratio ≤ 1.5) */
.image-item.wide {
grid-column: span 1;
}
@@ -136,7 +136,7 @@ body {
object-fit: cover;
}
/* 较高图片布局 (0.83 ≤ ratio < 1.2) */
/* 较高图片布局 (0.83 ≤ ratio < 1.3) */
.image-item.tall {
grid-column: span 1;
}

View File

@@ -21,6 +21,7 @@
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
background: linear-gradient(135deg, var(--light-blue) 0%, var(--white) 100%);
@@ -28,6 +29,10 @@ body {
color: var(--text-dark);
line-height: 1.6;
overflow-x: hidden;
/* 优化渲染性能 */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
.container {
max-width: 1400px;
@@ -400,6 +405,31 @@ body {
opacity: 1;
}
/* 对于触摸设备,添加焦点状态以显示覆盖层 */
.favorite-card:focus-within .card-overlay {
opacity: 1;
}
/* 媒体查询:针对触摸设备的特殊处理 */
@media (hover: none) and (pointer: coarse) {
.favorite-card .card-overlay {
opacity: 0.2; /* 在触摸设备上始终轻微显示覆盖层 */
}
.favorite-card:active .card-overlay,
.favorite-card:focus .card-overlay {
opacity: 1;
}
}
/* 为了兼容性,也为触摸设备上的元素添加焦点样式 */
@media (hover: hover) and (pointer: fine) {
/* 在非触摸设备上保持原有hover效果 */
.favorite-card:hover .card-overlay {
opacity: 1;
}
}
.overlay-content {
display: flex;
gap: 6px;
@@ -1223,6 +1253,85 @@ body {
color: var(--medium-gray);
}
/* 搜索提示样式 */
.search-hint {
text-align: center;
padding: 60px 20px;
color: var(--text-light);
font-size: 1.2rem;
max-width: 600px;
margin: 0 auto;
}
.search-hint .fa-search {
font-size: 3rem;
margin-bottom: 20px;
color: var(--medium-gray);
}
.search-hint h3 {
color: var(--text-dark);
margin-bottom: 15px;
}
/* 加载状态样式 */
.loading-state {
text-align: center;
padding: 60px 20px;
color: var(--text-light);
font-size: 1.2rem;
max-width: 400px;
margin: 0 auto;
}
.loading-state .fa-spinner {
font-size: 3rem;
margin-bottom: 20px;
color: var(--secondary-blue);
}
.loading-state p {
margin-bottom: 20px;
color: var(--text-dark);
}
.progress-bar {
width: 100%;
height: 6px;
background-color: var(--light-gray);
border-radius: 3px;
overflow: hidden;
}
.progress {
height: 100%;
background: linear-gradient(135deg, var(--secondary-blue) 0%, var(--primary-blue) 100%);
border-radius: 3px;
transition: width 0.3s ease;}
.search-hint p {
margin-bottom: 15px;
font-weight: 500;
}
.search-hint ul {
list-style: none;
text-align: left;
max-width: 400px;
margin: 0 auto;
}
.search-hint li {
margin-bottom: 10px;
padding-left: 0;
}
.search-hint .btn-primary {
margin-top: 10px;
padding: 8px 16px;
font-size: 0.9rem;
}
/* 响应式媒体查询 - 移动端优化 */
@media (max-width: 1024px) {
.container {
@@ -1468,6 +1577,88 @@ body {
}
}
/* 分页加载样式 */
.loading-more {
text-align: center;
padding: 40px 20px;
background: var(--white);
border-radius: var(--border-radius);
box-shadow: var(--shadow-sm);
margin: 20px 0;
border: 1px solid var(--medium-gray);
}
.loading-spinner {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
color: var(--text-light);
font-size: 1rem;
}
.loading-spinner .fa-spinner {
color: var(--secondary-blue);
font-size: 1.2rem;
}
.load-more-error {
text-align: center;
padding: 30px 20px;
background: #fef2f2;
border-radius: var(--border-radius);
box-shadow: var(--shadow-sm);
margin: 20px 0;
border: 1px solid #fecaca;
color: #dc2626;
}
.error-content {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
font-size: 1rem;
}
.error-content .fa-exclamation-triangle {
font-size: 1.2rem;
}
.error-content a {
color: var(--primary-blue);
text-decoration: underline;
cursor: pointer;
}
.error-content a:hover {
color: var(--secondary-blue);
}
/* 移动端分页样式优化 */
@media (max-width: 768px) {
.loading-more {
padding: 30px 15px;
margin: 15px 0;
}
.loading-spinner {
font-size: 0.9rem;
gap: 10px;
}
.load-more-error {
padding: 25px 15px;
margin: 15px 0;
}
.error-content {
font-size: 0.9rem;
flex-direction: column;
gap: 8px;
}
}
/* 打印样式 */
@media print {
.search-container,

View File

@@ -16,7 +16,7 @@
<div class="search-container">
<div class="search-box">
<label for="search-input"></label><input type="text" id="search-input" placeholder="搜索图片标题..." onkeypress="handleKeyPress(event)">
<label for="search-input"></label><input type="text" id="search-input" placeholder="搜索图片标题...">
<button onclick="searchAlbums()"><i class="fas fa-search"></i></button>
</div>

View File

@@ -10,6 +10,118 @@ const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
// API基础URL
const API_BASE = '/api';
// 图片加载器类(与app.js中的保持一致)
class ImageLoader {
constructor() {
this.cache = new Map();
}
// 加载并解压图片
async loadImage(imageId, element) {
// 检查缓存
if (this.cache.has(imageId)) {
const cachedData = this.cache.get(imageId);
this.setImageSrc(element, cachedData.blobUrl, cachedData.mimeType);
return;
}
try {
const response = await fetch(`${API_BASE}/image/${imageId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const contentType = response.headers.get('content-type');
const contentEncoding = response.headers.get('content-encoding');
const originalContentType = response.headers.get('x-original-content-type');
let imageData;
if (contentEncoding === 'br') {
// Brotli压缩数据,需要解压
const compressedData = await response.arrayBuffer();
imageData = await this.decompressBrotli(compressedData);
} else {
// 未压缩数据
imageData = await response.blob();
}
// 创建Blob URL
const mimeType = originalContentType || contentType || 'image/jpeg';
const blob = new Blob([imageData], { type: mimeType });
const blobUrl = URL.createObjectURL(blob);
// 缓存结果
this.cache.set(imageId, { blobUrl, mimeType });
// 设置图片源
this.setImageSrc(element, blobUrl, mimeType);
} catch (error) {
console.error('图片加载失败:', error);
// 加载失败时使用占位图
element.src = '/assets/placeholder.svg';
}
}
// 设置图片源
setImageSrc(element, blobUrl, mimeType) {
// 创建新的Image对象进行预加载
const img = new Image();
img.onload = () => {
element.src = blobUrl;
element.classList.add('loaded');
};
img.onerror = () => {
console.error('图片解码失败');
element.src = '/assets/placeholder.svg';
};
img.src = blobUrl;
}
// Brotli解压
async decompressBrotli(compressedData) {
// 检查浏览器是否支持Brotli解压
if (window.TextDecoder && window.TextEncoder) {
try {
// 使用浏览器的Brotli解压(如果支持)
if (window.DecompressionStream && 'br' in window) {
const decompressionStream = new DecompressionStream('br');
const decompressedStream = new Response(compressedData).body.pipeThrough(decompressionStream);
return new Response(decompressedStream).arrayBuffer();
}
} catch (error) {
console.warn('浏览器Brotli解压失败,使用JavaScript解压:', error);
}
}
// 使用JavaScript实现的Brotli解压(备用方案)
return await this.decompressBrotliJS(compressedData);
}
// JavaScript实现的Brotli解压(备用方案)
async decompressBrotliJS(compressedData) {
// 这里可以集成一个轻量级的Brotli解压库
// 由于Brotli解压比较复杂,这里先返回原始数据
// 在实际项目中,可以使用第三方库如brotli-wasm
console.warn('Brotli解压未实现,返回原始数据');
return compressedData;
}
// 清理缓存
clearCache() {
// 清理所有Blob URL
for (const [imageId, cached] of this.cache.entries()) {
URL.revokeObjectURL(cached.blobUrl);
}
this.cache.clear();
}
}
// 创建全局图片加载器实例
const imageLoader = new ImageLoader();
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 添加设备类到body
@@ -31,8 +143,77 @@ document.addEventListener('DOMContentLoaded', function() {
// 初始化键盘导航和触摸手势
initLightboxControls();
// 初始化图片懒加载
initAlbumLazyLoading();
});
// 初始化相册图片懒加载
function initAlbumLazyLoading() {
// 使用Intersection Observer实现懒加载
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const imageId = img.getAttribute('data-image-id');
if (imageId && !img.classList.contains('loaded')) {
imageLoader.loadImage(imageId, img);
}
observer.unobserve(img);
}
});
}, {
rootMargin: '200px 0px', // 提前200px开始加载
threshold: 0.1
});
// 观察所有带有data-image-id的图片
document.querySelectorAll('img[data-image-id]').forEach(img => {
if (!img.classList.contains('loaded')) {
observer.observe(img);
}
});
} else {
// 不支持Intersection Observer的回退方案
console.warn('浏览器不支持Intersection Observer,使用回退懒加载方案');
initAlbumFallbackLazyLoading();
}
}
// 相册回退懒加载方案
function initAlbumFallbackLazyLoading() {
let scrollTimeout;
function checkImagesInView() {
const images = document.querySelectorAll('img[data-image-id]:not(.loaded)');
const viewportHeight = window.innerHeight;
const scrollTop = window.scrollY;
images.forEach(img => {
const rect = img.getBoundingClientRect();
const isInView = rect.top < viewportHeight + 300 && rect.bottom > -300;
if (isInView) {
const imageId = img.getAttribute('data-image-id');
if (imageId) {
imageLoader.loadImage(imageId, img);
}
}
});
}
window.addEventListener('scroll', () => {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(checkImagesInView, 100);
});
// 初始检查
checkImagesInView();
}
// 显示图片骨架屏
function showImageSkeleton(count = 8) {
const container = document.getElementById('images-container');
@@ -118,7 +299,7 @@ function displayImages() {
let dataSrc = '';
if (image.id) {
dataSrc = `/api/thumbnail/${image.id}`;
dataSrc = `/api/image/${image.id}`;
imageUrl = '/assets/placeholder.svg'; // 初始使用占位图
} else if (image.original_url) {
dataSrc = image.original_url;
@@ -128,15 +309,15 @@ function displayImages() {
const title = image.title || `图片 ${index + 1}`;
// 检查图片是否已被收藏
const isFavorited = isImageFavorited(image.id || image.original_url);
isImageFavorited(image.id || image.original_url);
return `
<div class="image-item ${orientation}" onclick="openLightbox(${index})">
<img
src="${imageUrl}"
${dataSrc ? `data-src="${dataSrc}"` : ''}
alt="${title}"
${image.id ? `data-image-id="${image.id}"` : ''}
alt="${title}"
class="lazy"
loading="lazy"
onerror="this.src='/assets/placeholder.svg'"
>
<div class="image-caption">
@@ -231,7 +412,7 @@ function updateLightboxContent(newIndex) {
// 在lightbox中优先使用原始图片以获得更好的显示效果
let imageUrl = '/assets/placeholder.svg';
if (image.id) {
imageUrl = `/api/original/${image.id}`;
imageUrl = `/api/image/${image.id}`;
} else if (image.original_url) {
imageUrl = image.original_url;
}
@@ -262,36 +443,36 @@ function updateLightboxContent(newIndex) {
// 初始化图片懒加载
function initLazyLoading() {
// 使用Intersection Observer实现懒加载
if ('IntersectionObserver' in window) {
const imageObserver = new IntersectionObserver((entries, observer) => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy');
delete img.dataset.src;
const imageId = img.getAttribute('data-image-id');
if (imageId && !img.classList.contains('loaded')) {
imageLoader.loadImage(imageId, img);
}
imageObserver.unobserve(img);
observer.unobserve(img);
}
});
}, {
rootMargin: '50px 0px',
rootMargin: '200px 0px', // 提前200px开始加载
threshold: 0.1
});
document.querySelectorAll('img.lazy').forEach(img => {
imageObserver.observe(img);
});
} else {
// 不支持IntersectionObserver的浏览器回退方案
document.querySelectorAll('img.lazy').forEach(img => {
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy');
delete img.dataset.src;
// 观察所有带有data-image-id的图片
document.querySelectorAll('img[data-image-id]').forEach(img => {
if (!img.classList.contains('loaded')) {
observer.observe(img);
}
});
} else {
// 不支持Intersection Observer的回退方案
console.warn('浏览器不支持Intersection Observer,使用回退懒加载方案');
initAlbumFallbackLazyLoading();
}
}
@@ -334,6 +515,15 @@ function initLightboxControls() {
const lightbox = document.getElementById('lightbox');
if (!lightbox.classList.contains('active')) return;
// 检查点击目标是否是导航按钮或关闭按钮
const target = event.target;
const isNavButton = target.closest('.preview-nav') || target.closest('.preview-close');
if (isNavButton) {
// 如果是按钮点击,不处理轻点关闭逻辑
return;
}
const touchEndX = event.changedTouches[0].clientX;
const touchEndY = event.changedTouches[0].clientY;
@@ -347,6 +537,8 @@ function initLightboxControls() {
} else {
nextImage();
}
// 滑动操作后阻止轻点关闭判断
return;
}
// 轻点关闭(如果移动距离很小)
@@ -435,7 +627,6 @@ function checkLightboxFavoriteStatus() {
const image = images[currentImageIndex];
const imageId = image.id;
const favoriteBtn = document.getElementById('lightbox-favorite-btn');
console.log(image)
if (!imageId || !favoriteBtn) return;
// 检查收藏状态

File diff suppressed because it is too large Load Diff

View File

@@ -7,4 +7,9 @@ port = 8080
[storage]
images_dir = "./albums"
thumbnails_dir = "./thumbnails"
[queue]
max_concurrent_tasks = 5
queue_size_limit = 5000
high_request_rate_threshold = 200.0
idle_request_rate_threshold = 10.0

View File

@@ -5,9 +5,9 @@ CREATE TABLE IF NOT EXISTS albums (
document TEXT NOT NULL,
description TEXT,
cover_image_id TEXT,
image_count INTEGER NOT NULL DEFAULT 0, -- 新增图片数量字段
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
FOREIGN KEY (cover_image_id) REFERENCES images(id)
updated_at DATETIME NOT NULL
);
-- 创建图片表

View File

@@ -7,6 +7,7 @@ pub struct Config {
pub database: DatabaseConfig,
pub server: ServerConfig,
pub storage: StorageConfig,
pub queue: QueueConfig,
}
@@ -24,7 +25,14 @@ pub struct ServerConfig {
#[derive(Debug, Deserialize, Clone)]
pub struct StorageConfig {
pub images_dir: PathBuf,
pub thumbnails_dir: PathBuf,
}
#[derive(Debug, Deserialize, Clone)]
pub struct QueueConfig {
pub max_concurrent_tasks: usize,
pub queue_size_limit: usize,
pub high_request_rate_threshold: f64,
pub idle_request_rate_threshold: f64,
}
impl Config {

View File

@@ -1,12 +1,11 @@
use sqlx::{SqlitePool, sqlite::SqlitePoolOptions, Row, Error as SqlxError};
use sqlx::{SqlitePool, sqlite::SqlitePoolOptions, Row};
use crate::config::Config;
use crate::models::*;
use uuid::Uuid;
use std::time::Duration;
use tokio::time::sleep;
pub struct Database {
pool: SqlitePool,
pub pool: SqlitePool,
config: Config,
}
impl Database {
@@ -18,29 +17,29 @@ impl Database {
} 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(30)) // 增加获取连接超时时间
.idle_timeout(std::time::Duration::from_secs(300)) // 增加空闲超时时间
.max_lifetime(std::time::Duration::from_secs(1800)) // 增加最大生命周期
.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?;
@@ -50,82 +49,89 @@ impl Database {
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?;
Ok(Database { pool })
}
/// 带重试机制的数据库操作执行器
async fn execute_with_retry<F, T>(&self, operation: F, operation_name: &str) -> Result<T, sqlx::Error>
where
F: Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, sqlx::Error>> + Send>>,
{
const MAX_RETRIES: u32 = 3;
const BASE_DELAY_MS: u64 = 100;
for attempt in 0..=MAX_RETRIES {
match operation().await {
Ok(result) => return Ok(result),
Err(e) => {
// 检查是否是死锁或超时错误
if self.is_retryable_error(&e) && attempt < MAX_RETRIES {
let delay_ms = BASE_DELAY_MS * 2u64.pow(attempt);
eprintln!("⚠️ {} 操作失败 (尝试 {}): {}, 等待 {}ms 后重试",
operation_name, attempt + 1, e, delay_ms);
sleep(Duration::from_millis(delay_ms)).await;
} else {
eprintln!("❌ {} 操作失败 (尝试 {}): {}", operation_name, attempt + 1, e);
return Err(e);
}
}
}
}
unreachable!()
}
/// 判断错误是否可重试
fn is_retryable_error(&self, error: &SqlxError) -> bool {
match error {
SqlxError::Database(db_err) => {
// SQLite 死锁错误码
if let Some(code) = db_err.code() {
code == "5" || // SQLITE_BUSY
code == "6" || // SQLITE_LOCKED
code == "261" // SQLITE_BUSY_SNAPSHOT
} else {
false
}
}
SqlxError::PoolTimedOut => true,
_ => false,
}
// 确保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<usize>, limit: Option<usize>) -> Result<Vec<AlbumInfo>, 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::<String, _>("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::<String, _>("created_at"),
// });
// }
//
// Ok(result)
// }
// 相册操作
pub async fn get_all_albums(&self) -> Result<Vec<AlbumInfo>, sqlx::Error> {
let albums = sqlx::query(
r#"
SELECT
a.id,
a.title,
a.document,
a.description,
a.cover_image_id,
COUNT(img.id) as image_count,
a.created_at
FROM albums a
LEFT JOIN images img ON img.album_id = a.id
GROUP BY a.id, a.title, a.document, a.description, a.cover_image_id, a.created_at
ORDER BY a.document DESC
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::<String, _>("id");
@@ -136,7 +142,7 @@ impl Database {
continue; // 跳过无效的记录
}
};
result.push(AlbumInfo {
id,
title: row.get("title"),
@@ -147,60 +153,63 @@ impl Database {
created_at: row.get::<String, _>("created_at"),
});
}
Ok(result)
}
pub async fn search_albums(&self, query: &str) -> Result<Vec<AlbumInfo>, sqlx::Error> {
let search_pattern = format!("%{}%", query);
let albums = sqlx::query(
r#"
SELECT
a.id,
a.title,
a.document,
a.description,
a.cover_image_id,
COUNT(img.id) as image_count,
a.created_at
FROM albums a
LEFT JOIN images img ON img.album_id = a.id
LEFT JOIN images i ON i.id = a.cover_image_id
WHERE a.title LIKE ?
GROUP BY a.id, a.title, a.document, a.description, a.cover_image_id, a.created_at
ORDER BY a.created_at DESC
"#
)
.bind(&search_pattern)
.fetch_all(&self.pool)
.await?;
let mut result = Vec::new();
for row in albums {
let id_str = row.get::<String, _>("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::<String, _>("created_at"),
});
}
Ok(result)
}
// pub async fn search_albums(&self, query: &str, page: Option<usize>, limit: Option<usize>) -> Result<Vec<AlbumInfo>, 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::<String, _>("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::<String, _>("created_at"),
// });
// }
//
// Ok(result)
// }
pub async fn get_album_with_images(&self, album_id: Uuid) -> Result<Option<AlbumWithImages>, sqlx::Error> {
// 获取相册基本信息
let album_row = sqlx::query(
@@ -209,7 +218,7 @@ impl Database {
.bind(album_id.to_string())
.fetch_optional(&self.pool)
.await?;
if let Some(row) = album_row {
let id_str = row.get::<String, _>("id");
let id = match Uuid::parse_str(&id_str) {
@@ -219,7 +228,7 @@ impl Database {
return Ok(None);
}
};
let cover_image_id = match row.get::<Option<String>, _>("cover_image_id") {
Some(s) => match Uuid::parse_str(&s) {
Ok(uuid) => Some(uuid),
@@ -230,16 +239,17 @@ impl Database {
},
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::<String, _>("created_at"),
updated_at: row.get::<String, _>("updated_at"),
};
// 获取相册中的图片
let image_rows = sqlx::query(
"SELECT * FROM images WHERE album_id = ?"
@@ -247,7 +257,7 @@ impl Database {
.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::<String, _>("id");
@@ -258,7 +268,7 @@ impl Database {
continue;
}
};
let album_id_str = row.get::<String, _>("album_id");
let album_id = match Uuid::parse_str(&album_id_str) {
Ok(uuid) => uuid,
@@ -267,7 +277,7 @@ impl Database {
continue;
}
};
images.push(Image {
id: image_id,
album_id,
@@ -282,9 +292,9 @@ impl Database {
created_at: row.get::<String, _>("created_at"),
});
}
let image_count = images.len() as i64;
Ok(Some(AlbumWithImages {
album,
images,
@@ -294,13 +304,13 @@ impl Database {
Ok(None)
}
}
pub async fn create_album(&self, album: CreateAlbum) -> Result<Uuid, sqlx::Error> {
let id = Uuid::new_v4();
let now = chrono::Utc::now().to_rfc3339();
sqlx::query(
"INSERT INTO albums (id, title, document, description, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"
"INSERT INTO albums (id, title, document, description, image_count, created_at, updated_at) VALUES (?, ?, ?, ?, 0, ?, ?)"
)
.bind(id.to_string())
.bind(album.title)
@@ -310,51 +320,74 @@ impl Database {
.bind(&now)
.execute(&self.pool)
.await?;
Ok(id)
}
// 图片操作
pub async fn add_image(&self, image: CreateImage) -> Result<Uuid, sqlx::Error> {
let id = Uuid::new_v4();
let now = chrono::Utc::now().to_rfc3339();
// pub async fn add_image(&self, image: CreateImage) -> Result<Uuid, sqlx::Error> {
// 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(
"INSERT INTO images (id, album_id, filename, original_url, title, description, file_size, width, height, mime_type, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
r#"
UPDATE albums
SET image_count = (
SELECT COUNT(*) FROM images WHERE album_id = ?
),
updated_at = datetime('now')
WHERE id = ?
"#
)
.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)
.bind(album_id.to_string())
.bind(album_id.to_string())
.execute(&self.pool)
.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)
Ok(())
}
pub async fn add_images(&self, images: Vec<CreateImage>) -> Result<Vec<Uuid>, sqlx::Error> {
@@ -365,17 +398,17 @@ impl Database {
// 由于生命周期问题,简化实现,不使用重试机制
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
)
@@ -393,10 +426,10 @@ impl Database {
.execute(&mut *tx)
.await?;
}
// 提交事务
tx.commit().await?;
// 批量设置封面图片(只对每个相册的第一批图片设置)
if let Some(album_id) = first_album_id {
// 检查相册是否已有图片
@@ -406,7 +439,7 @@ impl Database {
.bind(album_id.to_string())
.fetch_one(&self.pool)
.await?;
// 如果这是相册的第一批图片,设置第一张为封面
if existing_count == images.len() as i64 {
if let Some(first_id) = ids.first() {
@@ -419,9 +452,123 @@ impl Database {
.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<i64, sqlx::Error> {
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(ids)
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<bool, sqlx::Error> {
// // 先获取图片所属的相册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<Uuid>) -> 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<Option<Image>, sqlx::Error> {
@@ -431,7 +578,7 @@ impl Database {
.bind(image_id.to_string())
.fetch_optional(&self.pool)
.await?;
if let Some(row) = row {
let image_id_str = row.get::<String, _>("id");
let image_id = match Uuid::parse_str(&image_id_str) {
@@ -441,7 +588,7 @@ impl Database {
return Ok(None);
}
};
let album_id_str = row.get::<String, _>("album_id");
let album_id = match Uuid::parse_str(&album_id_str) {
Ok(uuid) => uuid,
@@ -450,7 +597,7 @@ impl Database {
return Ok(None);
}
};
Ok(Some(Image {
id: image_id,
album_id,
@@ -468,9 +615,9 @@ impl Database {
Ok(None)
}
}
// 收藏功能数据库操作
// 获取用户的收藏列表
pub async fn get_user_favorites(&self, user_id: &str) -> Result<Vec<FavoriteWithImage>, sqlx::Error> {
let rows = sqlx::query(
@@ -503,7 +650,7 @@ impl Database {
.bind(user_id)
.fetch_all(&self.pool)
.await?;
let mut favorites = Vec::new();
for row in rows {
let favorite_id_str = row.get::<String, _>("favorite_id");
@@ -514,7 +661,7 @@ impl Database {
continue;
}
};
let image_id_str = row.get::<String, _>("image_id");
let image_id = match Uuid::parse_str(&image_id_str) {
Ok(uuid) => uuid,
@@ -523,7 +670,7 @@ impl Database {
continue;
}
};
let album_id_str = row.get::<String, _>("album_id");
let album_id = match Uuid::parse_str(&album_id_str) {
Ok(uuid) => uuid,
@@ -532,7 +679,7 @@ impl Database {
continue;
}
};
let favorite = Favorite {
id: favorite_id,
user_id: row.get("user_id"),
@@ -540,7 +687,7 @@ impl Database {
album_id,
created_at: row.get::<String, _>("favorite_created_at"),
};
let image = Image {
id: image_id,
album_id,
@@ -554,17 +701,17 @@ impl Database {
mime_type: row.get("mime_type"),
created_at: row.get::<String, _>("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<FavoriteStatus, sqlx::Error> {
let row = sqlx::query(
@@ -574,7 +721,7 @@ impl Database {
.bind(image_id.to_string())
.fetch_optional(&self.pool)
.await?;
if let Some(row) = row {
let favorite_id_str = row.get::<String, _>("id");
let favorite_id = match Uuid::parse_str(&favorite_id_str) {
@@ -584,7 +731,7 @@ impl Database {
None
}
};
Ok(FavoriteStatus {
is_favorited: true,
favorite_id,
@@ -596,12 +743,12 @@ impl Database {
})
}
}
// 添加收藏
pub async fn add_favorite(&self, user_id: &str, favorite_data: CreateFavorite) -> Result<Uuid, sqlx::Error> {
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 (?, ?, ?, ?, ?)"
)
@@ -612,10 +759,10 @@ impl Database {
.bind(&now)
.execute(&self.pool)
.await?;
Ok(favorite_id)
}
// 移除收藏(通过收藏ID)
pub async fn remove_favorite(&self, favorite_id: Uuid) -> Result<(), sqlx::Error> {
sqlx::query(
@@ -624,10 +771,10 @@ impl Database {
.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(
@@ -637,7 +784,63 @@ impl Database {
.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<Vec<Image>, 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::<String, _>("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::<String, _>("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::<String, _>("created_at"),
});
}
Ok(images)
}
}

View File

@@ -1,8 +1,35 @@
use std::path::Path;
use std::fs;
use image::{GenericImageView, ImageFormat};
use uuid::Uuid;
use crate::config::StorageConfig;
use image::{GenericImageView, ImageFormat};
use std::fs;
use std::path::Path;
use thiserror::Error;
use uuid::Uuid;
#[derive(Error, Debug)]
pub enum ImageProcessorError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Image processing error: {0}")]
Image(#[from] image::ImageError),
#[error("Invalid image data")]
InvalidData,
}
// 手动实现 From<reqwest::Error> 以支持 ? 操作符
impl From<reqwest::Error> for ImageProcessorError {
fn from(err: reqwest::Error) -> Self {
ImageProcessorError::Io(std::io::Error::new(
std::io::ErrorKind::Other,
err.to_string(),
))
}
}
impl ImageProcessorError {
pub fn is_send(&self) -> bool {
true
}
}
pub struct ImageProcessor {
pub config: StorageConfig,
@@ -12,12 +39,15 @@ impl ImageProcessor {
pub fn new(config: StorageConfig) -> Self {
// 确保目录存在
fs::create_dir_all(&config.images_dir).unwrap_or(());
fs::create_dir_all(&config.thumbnails_dir).unwrap_or(());
Self { config }
}
pub async fn save_image(&self, image_data: &[u8], filename: &str) -> Result<ImageInfo, Box<dyn std::error::Error>> {
pub async fn save_image(
&self,
image_data: &[u8],
filename: &str,
) -> Result<ImageInfo, ImageProcessorError> {
let image_id = Uuid::new_v4();
let file_extension = Path::new(filename)
.extension()
@@ -35,10 +65,7 @@ impl ImageProcessor {
let (width, height) = img.dimensions();
let file_size = image_data.len() as i64;
// 生成缩略图
let thumbnail_path = self.config.thumbnails_dir.join(format!("thumb_{}", new_filename));
self.generate_thumbnail(&img, &thumbnail_path, 300, 200)?;
// 不再生成缩略图,直接返回原图信息
Ok(ImageInfo {
id: image_id,
filename: new_filename,
@@ -49,26 +76,16 @@ impl ImageProcessor {
})
}
/// 生成缩略图并保存到指定路径(使用统一尺寸)
/// 此功能已被移除,直接返回成功
pub fn generate_thumbnail(
&self,
img: &image::DynamicImage,
output_path: &Path,
max_width: u32,
max_height: u32,
) -> Result<(), Box<dyn std::error::Error>> {
let (width, height) = img.dimensions();
// 计算缩略图尺寸
let ratio = width as f32 / height as f32;
let (new_width, new_height) = if width > height {
(max_width, (max_width as f32 / ratio) as u32)
} else {
((max_height as f32 * ratio) as u32, max_height)
};
let thumbnail = img.thumbnail(new_width, new_height);
thumbnail.save_with_format(output_path, ImageFormat::Jpeg)?;
_img: &image::DynamicImage,
_output_path: &Path,
_max_width: u32,
_max_height: u32,
) -> Result<(), ImageProcessorError> {
// 缩略图功能已移除,此函数不再执行任何操作
Ok(())
}
@@ -82,24 +99,68 @@ impl ImageProcessor {
}
}
pub fn get_image_url(&self, filename: &str) -> String {
format!("/images/{}", filename)
/// 快速调整图片尺寸(最大宽度)
pub async fn resize_image_to_max(&self, image_data: &[u8], max_width: u32) -> Vec<u8> {
match image::load_from_memory(image_data) {
Ok(img) => {
let (width, height) = img.dimensions();
if width <= max_width {
return image_data.to_vec(); // 无需调整
}
let new_height = (height as f32 * max_width as f32 / width as f32) as u32;
let resized = img.thumbnail(max_width, new_height);
let mut output = Vec::new();
if resized
.write_to(
&mut std::io::Cursor::new(&mut output),
image::ImageOutputFormat::Jpeg(75),
)
.is_ok()
{
output
} else {
image_data.to_vec() // 失败时返回原图
}
}
Err(_) => image_data.to_vec(), // 解码失败时返回原图
}
}
pub fn get_thumbnail_url(&self, filename: &str) -> String {
format!("/thumbnails/thumb_{}", filename)
pub fn get_image_url(&self, filename: &str) -> String {
format!("/images/{}", filename)
}
pub async fn download_and_save_image(
&self,
url: &str,
filename: &str,
) -> Result<ImageInfo, Box<dyn std::error::Error>> {
) -> Result<ImageInfo, ImageProcessorError> {
let response = reqwest::get(url).await?;
let image_data = response.bytes().await?;
self.save_image(&image_data, filename).await
}
/// 检测图片格式
fn detect_image_format(&self, image_data: &[u8]) -> Option<String> {
if image_data.len() < 12 {
return None;
}
match &image_data[0..12] {
b"\xff\xd8\xff" => Some("JPEG".to_string()),
b"\x89PNG\r\n\x1a\n" => Some("PNG".to_string()),
b"GIF87a" => Some("GIF87a".to_string()),
b"GIF89a" => Some("GIF89a".to_string()),
b"BM" => Some("BMP".to_string()),
b"RIFF" if image_data.len() > 12 && &image_data[8..12] == b"WEBP" => {
Some("WebP".to_string())
}
_ => None,
}
}
}
#[derive(Debug)]

View File

@@ -4,17 +4,54 @@ 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::*;
#[derive(Debug, Deserialize)]
struct AlbumIndex {
title: String,
images: Vec<String>,
/// 批量插入图片并设置封面缩略图的辅助函数
async fn batch_insert_images_and_set_cover(
db: &Database,
images_to_insert: Vec<CreateImage>,
album_id: Uuid,
album_path: &Path,
folder_name: &str,
) -> Result<usize, Box<dyn std::error::Error>> {
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<Database>) -> Result<(), Box<dyn std::error::Error>> {
pub async fn import_existing_data(config: &Config, db: Arc<Database>, _task_queue: Option<Arc<crate::queue::TaskQueue>>) -> Result<(), Box<dyn std::error::Error>> {
println!("开始扫描图片目录并导入新相册...");
let albums_dir = Path::new(&config.storage.images_dir);
@@ -32,7 +69,52 @@ pub async fn import_existing_data(config: &Config, db: Arc<Database>) -> Result<
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::<Result<Vec<_>, _>>()?;
let mut album_folders = Vec::new();
@@ -42,7 +124,6 @@ pub async fn import_existing_data(config: &Config, db: Arc<Database>) -> Result<
if let Some(folder_name) = path.file_name().and_then(|s| s.to_str()) {
// 检查是否已存在同名相册
if existing_titles.contains(&folder_name.to_lowercase()) {
println!("跳过已存在的相册: {}", folder_name);
continue;
}
album_folders.push((folder_name.to_string(), path));
@@ -57,8 +138,9 @@ pub async fn import_existing_data(config: &Config, db: Arc<Database>) -> Result<
return Ok(());
}
// 第二阶段:串行处理相册导入,避免数据库死锁
// 对于SQLite,高并发写入容易导致死锁,改为串行处理
// 使用简单的串行处理方式导入相册
println!("📁 开始导入新相册...");
let mut total_imported = 0;
let mut successful_albums = 0;
@@ -80,12 +162,10 @@ pub async fn import_existing_data(config: &Config, db: Arc<Database>) -> Result<
// 继续处理下一个相册,不中断整个导入过程
}
}
// 在每个相册导入后添加短暂延迟,减少数据库压力
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
println!("🎉 导入完成!成功导入 {} 个相册,共 {} 张图片", successful_albums, total_imported);
Ok(())
}
@@ -216,26 +296,12 @@ async fn import_single_album(db: &Database, folder_name: &str, path: &Path) -> R
}
}
// 批量插入图片
if !images_to_insert.is_empty() {
println!(" 批量插入 {} 张图片...", images_to_insert.len());
match db.add_images(images_to_insert).await {
Ok(ids) => {
println!(" 批量插入成功,共插入 {} 张图片", ids.len());
Ok(ids.len())
}
Err(e) => {
eprintln!(" 批量插入失败: {}", e);
Ok(0)
}
}
} else {
Ok(0)
}
// 使用辅助函数批量插入图片并设置封面
batch_insert_images_and_set_cover(&db, images_to_insert, album_id, path, folder_name).await
}
/// 快速扫描图片文件
fn scan_image_files(path: &Path, _folder_name: &str) -> Result<Vec<(String, std::path::PathBuf)>, Box<dyn std::error::Error>> {
pub(crate) fn scan_image_files(path: &Path, _folder_name: &str) -> Result<Vec<(String, std::path::PathBuf)>, Box<dyn std::error::Error>> {
let mut image_files = Vec::new();
for entry in fs::read_dir(path)? {
@@ -290,4 +356,91 @@ fn get_image_info(image_path: &Path) -> Result<(i64, i32, i32), Box<dyn std::err
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<usize, Box<dyn std::error::Error>> {
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::<AlbumIndex>(&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::<Result<Vec<_>, _>>()?;
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
}
// 缩略图生成功能已移除

View File

@@ -3,60 +3,109 @@ mod database;
mod image_processor;
mod import;
mod models;
mod queue;
mod routes;
use crate::models::AlbumsCache;
use actix_files as afs;
use actix_web::{App, HttpResponse, HttpServer, web};
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();
// 加载配置
let config = match config::Config::load() {
Ok(cfg) => cfg,
Err(e) => {
eprintln!("加载配置失败: {}", e);
error!("加载配置失败: {}", e);
std::process::exit(1);
}
};
println!("启动图片展示服务...");
println!("服务地址: http://{}", config.server_address());
info!("启动图片展示服务...");
info!("服务地址: http://localhost:{} http://{}", config.server.port, config.server_address());
// 初始化数据库
let db = match database::Database::new(&config).await {
Ok(db) => {
println!("数据库连接成功");
info!("数据库连接成功");
Arc::new(db)
}
Err(e) => {
eprintln!("数据库连接失败: {}", e);
error!("数据库连接失败: {}", e);
std::process::exit(1);
}
};
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 {
println!("[后台任务] 开始扫描图片目录并导入新相册...");
match import::import_existing_data(&config_clone, db_clone).await {
Ok(_) => println!("[后台任务] 相册导入完成"),
Err(e) => eprintln!("[后台任务] 相册导入失败: {}", e),
info!("[后台任务] 开始扫描图片目录并导入新相册...");
match import::import_existing_data(&config_clone, db_clone, None).await {
Ok(_) => info!("[后台任务] 相册导入完成"),
Err(e) => error!("[后台任务] 相册导入失败: {}", e),
}
});
// 初始化图片处理器
let image_processor = Arc::new(image_processor::ImageProcessor::new(config.storage.clone()));
// 初始化相册内存缓存
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 {
match initial_db.get_all_albums().await {
Ok(albums) => {
let mut cache = initial_cache.write().await;
cache.update(albums);
println!("✅ 初始相册缓存加载完成");
}
Err(e) => {
eprintln!("❌ 初始缓存加载失败: {}", e);
}
}
});
// 设置定时刷新缓存任务(每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分钟
loop {
interval.tick().await;
match refresh_db.get_all_albums().await {
Ok(albums) => {
let mut cache = refresh_cache.write().await;
cache.update(albums);
println!("🔄 相册缓存定时刷新完成");
}
Err(e) => {
eprintln!("❌ 缓存刷新失败: {}", e);
}
}
}
});
println!("API接口:");
println!(" - GET /api/albums - 获取所有相册");
println!(" - GET /api/search?q=关键词 - 搜索相册");
println!(" - GET /api/album/:id - 获取相册详情");
println!(" - POST /api/albums - 创建新相册");
println!(" - GET /api/thumbnail/:id - 获取缩略图");
println!(" - GET /api/original/:id - 获取原始图片");
println!(" - GET /api/image/:id - 获取图片(已移除缩略图功能)");
println!(" - GET /api/favorites - 获取收藏列表");
println!(" - GET /api/favorites/status/:id - 检查收藏状态");
println!(" - POST /api/favorites - 添加收藏");
@@ -66,34 +115,51 @@ async fn main() -> std::io::Result<()> {
// 创建数据目录
fs::create_dir_all(&config.storage.images_dir).unwrap_or(());
fs::create_dir_all(&config.storage.thumbnails_dir).unwrap_or(());
fs::create_dir_all(&config.database.url[7..]).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路由
.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/thumbnail/{id}", web::get().to(routes::get_thumbnail))
.route(
"/api/original/{id}",
web::get().to(routes::get_original_image),
)
.route("/api/image/{id}", web::get().to(routes::get_image))
// 收藏功能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))
// 静态文件服务
.service(afs::Files::new("/assets", "./assets").show_files_listing())
.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/queue/stats", web::get().to(routes::get_queue_stats))
// 静态文件服务 - 启用缓存
.service(
afs::Files::new("/assets", "./assets")
.show_files_listing()
.prefer_utf8(true)
.use_last_modified(true)
.use_etag(true),
)
// HTML页面路由
.route(
"/",
@@ -119,6 +185,8 @@ async fn main() -> std::io::Result<()> {
)
})
.bind(server_address)?
// 限制worker数量为2个,减少系统资源占用
.workers(3)
.run()
.await
}

View File

@@ -1,4 +1,6 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::info;
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
@@ -7,11 +9,12 @@ pub struct Album {
pub title: String,
pub description: Option<String>,
pub cover_image_id: Option<Uuid>,
pub image_count: i64, // 新增图片数量字段
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Image {
pub id: Uuid,
pub album_id: Uuid,
@@ -33,7 +36,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,
@@ -90,4 +93,138 @@ pub struct FavoriteWithImage {
pub struct FavoriteStatus {
pub is_favorited: bool,
pub favorite_id: Option<Uuid>,
}
#[derive(Debug, Deserialize)]
pub struct AlbumIndex {
pub title: String,
pub images: Vec<String>,
}
// 内存缓存结构
#[derive(Debug, Clone)]
pub struct AlbumsCache {
pub albums: Vec<AlbumInfo>,
pub search_index: HashMap<String, Vec<AlbumInfo>>,
pub last_updated: chrono::DateTime<chrono::Utc>,
}
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<AlbumInfo>) {
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<AlbumInfo> {
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
}
}

96
src/queue.rs Normal file
View File

@@ -0,0 +1,96 @@
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicBool};
use std::time::{Duration, Instant};
use tokio::sync::Notify;
use tracing::{info, debug};
/// 队列统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueStats {
pub request_frequency: f64,
pub request_count: u64,
}
/// 简化的任务队列(仅用于记录HTTP请求频率)
pub struct TaskQueue {
// HTTP请求频率监控
request_count: AtomicU64,
last_request_time: std::sync::Mutex<Instant>,
request_window: Duration,
is_paused: AtomicBool,
notify: Notify,
}
impl TaskQueue {
pub fn new(_max_concurrent_tasks: usize, _queue_size_limit: usize, _high_request_rate_threshold: f64, _idle_request_rate_threshold: f64) -> Self {
Self {
// HTTP请求频率监控
request_count: AtomicU64::new(0),
last_request_time: std::sync::Mutex::new(Instant::now()),
request_window: Duration::from_secs(10),
is_paused: AtomicBool::new(false),
notify: Notify::new(),
}
}
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<crate::database::Database>) -> Self {
Self {
// HTTP请求频率监控
request_count: AtomicU64::new(0),
last_request_time: std::sync::Mutex::new(Instant::now()),
request_window: Duration::from_secs(10),
is_paused: AtomicBool::new(false),
notify: Notify::new(),
}
}
/// 记录HTTP请求(在每次HTTP请求处理时调用)
pub async fn record_http_request(&self) {
let now = Instant::now();
let mut last_request_time = self.last_request_time.lock().unwrap();
// 如果距离上次请求时间超过了窗口时间,重置计数器
if now.duration_since(*last_request_time) > self.request_window {
self.request_count.store(0, std::sync::atomic::Ordering::Release);
}
// 增加请求计数
self.request_count.fetch_add(1, std::sync::atomic::Ordering::Release);
*last_request_time = now;
}
/// 获取当前请求频率(请求数/秒)
pub fn get_request_frequency(&self) -> f64 {
let request_count = self.request_count.load(std::sync::atomic::Ordering::Acquire) as f64;
let window_seconds = self.request_window.as_secs_f64();
if window_seconds > 0.0 {
request_count / window_seconds
} else {
0.0
}
}
/// 获取队列统计信息
pub async fn get_stats(&self) -> QueueStats {
QueueStats {
// 添加请求频率信息
request_frequency: self.get_request_frequency(),
request_count: self.request_count.load(std::sync::atomic::Ordering::Acquire),
}
}
/// 暂停队列处理
pub fn pause(&self) {
self.is_paused.store(true, std::sync::atomic::Ordering::Release);
info!("任务队列已暂停");
}
/// 恢复队列处理
pub fn resume(&self) {
self.is_paused.store(false, std::sync::atomic::Ordering::Release);
self.notify.notify_one();
info!("任务队列已恢复");
}
}

View File

@@ -4,40 +4,35 @@ 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;
pub async fn get_albums(db: web::Data<Arc<Database>>) -> impl Responder {
match db.get_all_albums().await {
Ok(albums) => HttpResponse::Ok().json(albums),
Err(e) => {
eprintln!("获取相册列表失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
"error": "获取相册列表失败"
}))
}
}
}
// 收藏功能API路由
// 获取用户的收藏列表
pub async fn get_favorites(
db: web::Data<Arc<Database>>,
) -> impl Responder {
pub async fn get_favorites(db: web::Data<Arc<Database>>) -> impl Responder {
// 这里使用固定用户ID,实际项目中应该从认证信息中获取
let user_id = "default_user".to_string();
match db.get_user_favorites(&user_id).await {
Ok(favorites) => HttpResponse::Ok().json(favorites),
let favorites = match db.get_user_favorites(&user_id).await {
Ok(value) => value,
Err(e) => {
eprintln!("获取收藏列表失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
error!("获取收藏列表失败: {}", e);
return HttpResponse::InternalServerError().json(serde_json::json!({
"error": "获取收藏列表失败"
}))
}));
}
}
};
HttpResponse::Ok().json(favorites)
}
// 图片质量检查功能已移除,直接返回原始图片
// 检查图片是否被收藏
pub async fn check_favorite_status(
db: web::Data<Arc<Database>>,
@@ -51,19 +46,21 @@ pub async fn check_favorite_status(
}));
}
};
// 这里使用固定用户ID,实际项目中应该从认证信息中获取
let user_id = "default_user".to_string();
match db.get_favorite_status(&user_id, image_id).await {
Ok(status) => HttpResponse::Ok().json(status),
let status = match db.get_favorite_status(&user_id, image_id).await {
Ok(value) => value,
Err(e) => {
eprintln!("检查收藏状态失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
error!("检查收藏状态失败: {}", e);
return HttpResponse::InternalServerError().json(serde_json::json!({
"error": "检查收藏状态失败"
}))
}));
}
}
};
HttpResponse::Ok().json(status)
}
// 添加收藏
@@ -73,7 +70,7 @@ pub async fn add_favorite(
) -> 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,
@@ -101,7 +98,7 @@ pub async fn remove_favorite(
}));
}
};
match db.remove_favorite(favorite_id).await {
Ok(_) => HttpResponse::Ok().json(serde_json::json!({
"message": "取消收藏成功"
@@ -115,6 +112,17 @@ pub async fn remove_favorite(
}
}
// 获取任务队列状态
pub async fn get_queue_stats(
task_queue: web::Data<Arc<queue::TaskQueue>>,
) -> 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<Arc<Database>>,
@@ -128,10 +136,10 @@ pub async fn remove_favorite_by_image(
}));
}
};
// 这里使用固定用户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": "取消收藏成功"
@@ -145,79 +153,117 @@ pub async fn remove_favorite_by_image(
}
}
pub async fn get_original_image(
db: web::Data<Arc<Database>>,
image_processor: web::Data<Arc<ImageProcessor>>,
path: web::Path<String>,
) -> 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"
}));
}
pub async fn get_albums(albums_cache: web::Data<Arc<RwLock<AlbumsCache>>>) -> 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()
};
match db.get_image(image_id).await {
Ok(Some(image)) => {
let original_path = image_processor.config.images_dir.join(&image.filename);
drop(cache); // 释放读锁
if original_path.exists() {
match fs::read(&original_path) {
Ok(data) => HttpResponse::Ok().content_type(image.mime_type).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": "获取图片信息失败"
}))
}
}
HttpResponse::Ok().json(paginated_albums)
}
pub async fn search_albums(
db: web::Data<Arc<Database>>,
albums_cache: web::Data<Arc<RwLock<AlbumsCache>>>,
query: web::Query<std::collections::HashMap<String, String>>,
) -> impl Responder {
let q = query.get("q").map(|s| s.as_str()).unwrap_or("");
if q.is_empty() {
return match db.get_all_albums().await {
Ok(albums) => HttpResponse::Ok().json(albums),
Err(e) => {
eprintln!("获取相册列表失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
"error": "获取相册列表失败"
}))
}
};
// 输入验证
if q.len() > 100 {
return HttpResponse::BadRequest().json(serde_json::json!({
"error": "搜索查询过长,最多100个字符"
}));
}
match db.search_albums(q).await {
Ok(albums) => HttpResponse::Ok().json(albums),
Err(e) => {
eprintln!("搜索相册失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
"error": "搜索失败"
}))
}
// 允许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::<usize>().ok())
.unwrap_or(1);
let limit = query
.get("limit")
.and_then(|s| s.parse::<usize>().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<Arc<RwLock<AlbumsCache>>>,
) -> 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(
@@ -265,7 +311,8 @@ pub async fn create_album(
}
}
pub async fn get_thumbnail(
/// 获取原始图片
pub async fn get_image(
db: web::Data<Arc<Database>>,
image_processor: web::Data<Arc<ImageProcessor>>,
path: web::Path<String>,
@@ -281,91 +328,16 @@ pub async fn get_thumbnail(
match db.get_image(image_id).await {
Ok(Some(image)) => {
// 优先返回缩略图,如果不存在则生成
let thumbnail_path = image_processor
.config
.thumbnails_dir
.join(image.id.to_string());
let original_path = image_processor.config.images_dir.join(&image.filename);
if thumbnail_path.exists() {
// 返回缩略图
match fs::read(&thumbnail_path) {
Ok(data) => {
let mime_type = image_processor.detect_mime_type("jpg"); // 缩略图总是JPEG格式
HttpResponse::Ok().content_type(mime_type).body(data)
}
Err(e) => {
eprintln!("读取缩略图失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
"error": "读取缩略图失败"
}))
}
}
} else if original_path.exists() {
// 生成缩略图并返回
if original_path.exists() {
match fs::read(&original_path) {
Ok(data) => {
match image::load_from_memory(&data) {
Ok(img) => {
// 在内存中生成缩略图,避免重复文件读写
let thumbnail = img.thumbnail(800, 600);
// 使用临时文件来生成缩略图数据
let temp_dir = std::env::temp_dir();
let temp_file =
temp_dir.join(format!("temp_thumb_{}", Uuid::new_v4()));
if let Err(e) =
thumbnail.save_with_format(&temp_file, image::ImageFormat::Jpeg)
{
eprintln!("生成缩略图失败: {}", e);
// 如果生成缩略图失败,返回原始图片
return HttpResponse::Ok()
.content_type(image.mime_type)
.body(data);
}
// 读取缩略图数据
match fs::read(&temp_file) {
Ok(thumbnail_data) => {
// 异步保存缩略图到文件(不阻塞响应)
let config_clone = image_processor.config.clone();
let filename_clone = image.id.clone();
let thumbnail_data_clone = thumbnail_data.clone();
tokio::spawn(async move {
let thumbnail_path = config_clone
.thumbnails_dir
.join(filename_clone.to_string());
if let Err(e) =
fs::write(&thumbnail_path, &thumbnail_data_clone)
{
eprintln!("保存缩略图文件失败: {}", e);
}
});
// 清理临时文件
let _ = fs::remove_file(&temp_file);
// 返回缩略图数据
HttpResponse::Ok()
.content_type("image/jpeg")
.body(thumbnail_data)
}
Err(e) => {
eprintln!("读取缩略图数据失败: {}", e);
// 如果读取失败,返回原始图片
HttpResponse::Ok().content_type(image.mime_type).body(data)
}
}
}
Err(e) => {
eprintln!("加载图片失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
"error": "加载图片失败"
}))
}
}
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);