update code level

This commit is contained in:
lychang
2026-03-28 12:56:30 +08:00
parent 675a402848
commit eb43c145cc
6 changed files with 446 additions and 33 deletions

View File

@@ -386,7 +386,7 @@ impl TaskQueue {
false
}
/// 启动定期清理过期任务
pub async fn start_periodic_cleanup(self: Arc<Self>, interval_duration: Duration) {
let queue = Arc::clone(&self);
@@ -790,24 +790,6 @@ impl AlbumImportWorker {
pub struct TaskFactory;
impl TaskFactory {
/// 创建缩略图生成任务
pub fn create_thumbnail_task(
image_id: Uuid,
original_data: Vec<u8>,
priority: TaskPriority,
) -> Task {
Task {
id: Uuid::new_v4(),
task_type: TaskType::ThumbnailGeneration,
priority,
created_at: Instant::now(),
data: TaskData::ThumbnailGeneration {
image_id,
original_data,
},
}
}
/// 创建相册导入任务
pub fn create_album_import_task(album_path: String, album_data: Option<Vec<u8>>) -> Task {
Task {

View File

@@ -384,7 +384,7 @@ pub async fn create_album(
}
}
/// 获取原始图片(已移除缩略图功能)
/// 获取压缩图片(后端压缩,前端解压)
pub async fn get_image(
db: web::Data<Arc<Database>>,
image_processor: web::Data<Arc<ImageProcessor>>,
@@ -406,11 +406,39 @@ pub async fn get_image(
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")) // 1年缓存
.insert_header(("ETag", format!("\"{}\"", image_id)))
.body(data)
// 检查是否支持压缩(仅对JPEG/PNG图片进行压缩)
let should_compress = image.mime_type == "image/jpeg" || image.mime_type == "image/png";
if should_compress {
// 使用Brotli压缩图片数据
match compress_image_data(&data) {
Ok(compressed_data) => {
HttpResponse::Ok()
.content_type("application/octet-stream") // 压缩数据使用二进制格式
.insert_header(("Content-Encoding", "br")) // Brotli压缩
.insert_header(("X-Original-Content-Type", image.mime_type.clone())) // 保留原始类型信息
.insert_header(("Cache-Control", "public, max-age=31536000")) // 1年缓存
.insert_header(("ETag", format!("\"{}\"", image_id)))
.body(compressed_data)
}
Err(e) => {
eprintln!("图片压缩失败: {}", e);
// 压缩失败时返回原始数据
HttpResponse::Ok()
.content_type(image.mime_type.clone())
.insert_header(("Cache-Control", "public, max-age=31536000"))
.insert_header(("ETag", format!("\"{}\"", image_id)))
.body(data)
}
}
} else {
// 不支持压缩的图片类型直接返回
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);
@@ -435,4 +463,19 @@ pub async fn get_image(
}))
}
}
}
/// 使用Brotli压缩图片数据
fn compress_image_data(data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
use brotli::CompressorWriter;
use std::io::Write;
let mut compressed = Vec::new();
{
let mut compressor = CompressorWriter::new(&mut compressed, 4096, 11, 22); // 高质量压缩
Write::write_all(&mut compressor, data)?;
compressor.flush()?;
}
Ok(compressed)
}