Compare commits

...

17 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
17 changed files with 1877 additions and 4249 deletions

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"] } 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 = ["blocking","rustls-tls"] }
config = "0.13" config = "0.13"
rand = "0.8"
tracing = "0.1"
tracing-subscriber = "0.3"
thiserror = "1.0"
mimalloc = "0.1.48"

View File

@@ -21,6 +21,7 @@
} }
* { margin: 0; padding: 0; box-sizing: border-box; } * { margin: 0; padding: 0; box-sizing: border-box; }
html { scroll-behavior: smooth; }
body { body {
font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif; font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
background: linear-gradient(135deg, var(--light-blue) 0%, var(--white) 100%); background: linear-gradient(135deg, var(--light-blue) 0%, var(--white) 100%);
@@ -28,6 +29,10 @@ body {
color: var(--text-dark); color: var(--text-dark);
line-height: 1.6; line-height: 1.6;
overflow-x: hidden; overflow-x: hidden;
/* 优化渲染性能 */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
} }
.container { .container {
max-width: 1400px; max-width: 1400px;
@@ -400,6 +405,31 @@ body {
opacity: 1; 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 { .overlay-content {
display: flex; display: flex;
gap: 6px; gap: 6px;
@@ -1223,6 +1253,85 @@ body {
color: var(--medium-gray); 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) { @media (max-width: 1024px) {
.container { .container {

View File

@@ -16,7 +16,7 @@
<div class="search-container"> <div class="search-container">
<div class="search-box"> <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> <button onclick="searchAlbums()"><i class="fas fa-search"></i></button>
</div> </div>

View File

@@ -10,6 +10,118 @@ const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
// API基础URL // API基础URL
const API_BASE = '/api'; 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() { document.addEventListener('DOMContentLoaded', function() {
// 添加设备类到body // 添加设备类到body
@@ -31,8 +143,77 @@ document.addEventListener('DOMContentLoaded', function() {
// 初始化键盘导航和触摸手势 // 初始化键盘导航和触摸手势
initLightboxControls(); 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) { function showImageSkeleton(count = 8) {
const container = document.getElementById('images-container'); const container = document.getElementById('images-container');
@@ -118,7 +299,7 @@ function displayImages() {
let dataSrc = ''; let dataSrc = '';
if (image.id) { if (image.id) {
dataSrc = `/api/thumbnail/${image.id}`; dataSrc = `/api/image/${image.id}`;
imageUrl = '/assets/placeholder.svg'; // 初始使用占位图 imageUrl = '/assets/placeholder.svg'; // 初始使用占位图
} else if (image.original_url) { } else if (image.original_url) {
dataSrc = image.original_url; dataSrc = image.original_url;
@@ -133,9 +314,10 @@ function displayImages() {
<div class="image-item ${orientation}" onclick="openLightbox(${index})"> <div class="image-item ${orientation}" onclick="openLightbox(${index})">
<img <img
src="${imageUrl}" src="${imageUrl}"
${dataSrc ? `data-src="${dataSrc}"` : ''} ${image.id ? `data-image-id="${image.id}"` : ''}
alt="${title}" alt="${title}"
class="lazy" class="lazy"
loading="lazy"
onerror="this.src='/assets/placeholder.svg'" onerror="this.src='/assets/placeholder.svg'"
> >
<div class="image-caption"> <div class="image-caption">
@@ -230,7 +412,7 @@ function updateLightboxContent(newIndex) {
// 在lightbox中优先使用原始图片以获得更好的显示效果 // 在lightbox中优先使用原始图片以获得更好的显示效果
let imageUrl = '/assets/placeholder.svg'; let imageUrl = '/assets/placeholder.svg';
if (image.id) { if (image.id) {
imageUrl = `/api/original/${image.id}`; imageUrl = `/api/image/${image.id}`;
} else if (image.original_url) { } else if (image.original_url) {
imageUrl = image.original_url; imageUrl = image.original_url;
} }
@@ -261,36 +443,36 @@ function updateLightboxContent(newIndex) {
// 初始化图片懒加载 // 初始化图片懒加载
function initLazyLoading() { function initLazyLoading() {
// 使用Intersection Observer实现懒加载
if ('IntersectionObserver' in window) { if ('IntersectionObserver' in window) {
const imageObserver = new IntersectionObserver((entries, observer) => { const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => { entries.forEach(entry => {
if (entry.isIntersecting) { if (entry.isIntersecting) {
const img = entry.target; const img = entry.target;
if (img.dataset.src) { const imageId = img.getAttribute('data-image-id');
img.src = img.dataset.src;
img.classList.remove('lazy'); if (imageId && !img.classList.contains('loaded')) {
delete img.dataset.src; imageLoader.loadImage(imageId, img);
} }
imageObserver.unobserve(img);
observer.unobserve(img);
} }
}); });
}, { }, {
rootMargin: '50px 0px', rootMargin: '200px 0px', // 提前200px开始加载
threshold: 0.1 threshold: 0.1
}); });
document.querySelectorAll('img.lazy').forEach(img => { // 观察所有带有data-image-id的图片
imageObserver.observe(img); document.querySelectorAll('img[data-image-id]').forEach(img => {
}); if (!img.classList.contains('loaded')) {
} else { observer.observe(img);
// 不支持IntersectionObserver的浏览器回退方案
document.querySelectorAll('img.lazy').forEach(img => {
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy');
delete img.dataset.src;
} }
}); });
} else {
// 不支持Intersection Observer的回退方案
console.warn('浏览器不支持Intersection Observer,使用回退懒加载方案');
initAlbumFallbackLazyLoading();
} }
} }

View File

@@ -1,14 +1,89 @@
// 全局变量 // 全局变量
let allAlbums = []; let allAlbums = []; // 存储所有相册数据
let displayedAlbums = []; // 当前显示的相册数据
let searchTimeout = null; let searchTimeout = null;
let currentPage = 1; let currentDisplayPage = 1; // 前端显示的分页
let albumsPerPage = 200; let albumsPerPage = 50; // 每次显示50个相册
let isLoadingMore = false; let isLoadingMore = false;
let hasMoreAlbums = true; let hasMoreAlbums = true;
let lazyLoadObserver = null;
let isAllAlbumsLoaded = false; // 标记是否已加载所有相册数据
let isInFavoritesPage = false; // 标记当前是否在收藏页
// API基础URL // API基础URL
const API_BASE = '/api'; const API_BASE = '/api';
// 图片加载器类
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 imageData = await response.blob();
// 创建Blob URL
const mimeType = 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;
}
// 清理缓存
clearCache() {
// 清理所有Blob URL
for (const [imageId, cached] of this.cache.entries()) {
URL.revokeObjectURL(cached.blobUrl);
}
this.cache.clear();
}
}
// 创建全局图片加载器实例
const imageLoader = new ImageLoader();
// 设备检测 // 设备检测
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0; const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
@@ -27,6 +102,7 @@ document.addEventListener('DOMContentLoaded', function () {
loadAlbums(); loadAlbums();
initSearch(); initSearch();
initInfiniteScroll(); initInfiniteScroll();
initLazyLoading(); // 初始化图片懒加载
}); });
// 初始化搜索功能 // 初始化搜索功能
@@ -36,7 +112,12 @@ function initSearch() {
// 防抖搜索 // 防抖搜索
searchInput.addEventListener('input', function () { searchInput.addEventListener('input', function () {
clearTimeout(searchTimeout); clearTimeout(searchTimeout);
searchTimeout = setTimeout(debouncedSearch, 300);
// 优化:根据输入长度动态调整延迟
const inputLength = this.value.length;
const debounceDelay = inputLength > 3 ? 200 : 500; // 长文本快速搜索,短文本慢速搜索
searchTimeout = setTimeout(debouncedSearch, debounceDelay);
}); });
// 移动端优化:搜索框聚焦时自动滚动到可视区域 // 移动端优化:搜索框聚焦时自动滚动到可视区域
@@ -59,8 +140,81 @@ function initInfiniteScroll() {
}); });
} }
// 初始化图片懒加载
function initLazyLoading() {
// 使用Intersection Observer实现懒加载
if ('IntersectionObserver' in window) {
if (lazyLoadObserver) {
lazyLoadObserver.disconnect();
}
lazyLoadObserver = 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);
}
lazyLoadObserver.unobserve(img);
}
});
}, {
rootMargin: '100px 0px', // 提前100px开始加载
threshold: 0.1
});
// 观察所有带有data-image-id的图片
document.querySelectorAll('img[data-image-id]').forEach(img => {
if (!img.classList.contains('loaded')) {
lazyLoadObserver.observe(img);
}
});
} else {
// 不支持Intersection Observer的回退方案
console.warn('浏览器不支持Intersection Observer,使用回退懒加载方案');
initFallbackLazyLoading();
}
}
// 回退懒加载方案
function initFallbackLazyLoading() {
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 + 200 && rect.bottom > -200;
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 handleScroll() { function handleScroll() {
// 如果在收藏页,禁用无限滚动
if (isInFavoritesPage) return;
if (isLoadingMore || !hasMoreAlbums) return; if (isLoadingMore || !hasMoreAlbums) return;
// 检查是否滚动到底部 // 检查是否滚动到底部
@@ -74,18 +228,36 @@ function handleScroll() {
} }
} }
// 加载更多相册 // 加载更多相册(从前端已加载的数据中获取)
async function loadMoreAlbums() { async function loadMoreAlbums() {
if (isLoadingMore || !hasMoreAlbums) return; // 如果在收藏页,不加载更多数据
if (isInFavoritesPage) return;
if (isLoadingMore || !hasMoreAlbums || !isAllAlbumsLoaded) return;
isLoadingMore = true; isLoadingMore = true;
try { try {
await loadAlbums(); // 显示加载更多指示器
showLoadingMore();
// 增加当前显示页数
currentDisplayPage++;
// 显示下一页数据
displayCurrentPage();
// 初始化图片懒加载
initLazyLoading();
// 预加载下一批图片
preloadNextBatchImages();
} catch (error) { } catch (error) {
console.error('加载更多相册失败:', error); console.error('加载更多相册失败:', error);
showLoadMoreError(); showLoadMoreError();
} finally { } finally {
isLoadingMore = false; isLoadingMore = false;
hideLoadingMore();
} }
} }
@@ -109,11 +281,6 @@ function showLoadMoreError() {
container.appendChild(errorElement); container.appendChild(errorElement);
} }
// 防抖搜索
function debouncedSearch() {
searchAlbums();
}
// 显示骨架屏 // 显示骨架屏
function showSkeleton(count = 6) { function showSkeleton(count = 6) {
const container = document.getElementById('albums-container'); const container = document.getElementById('albums-container');
@@ -132,6 +299,22 @@ function showSkeleton(count = 6) {
`).join(''); `).join('');
} }
// 显示详细加载状态
function showLoadingState(message = '加载中...', progress = 0) {
const container = document.getElementById('albums-container');
const progressWidth = Math.min(Math.max(progress, 0), 100);
container.innerHTML = `
<div class="loading-state">
<i class="fas fa-spinner fa-spin"></i>
<p>${message}</p>
<div class="progress-bar">
<div class="progress" style="width: ${progressWidth}%"></div>
</div>
</div>
`;
}
// 显示加载更多指示器 // 显示加载更多指示器
function showLoadingMore() { function showLoadingMore() {
const container = document.getElementById('albums-container'); const container = document.getElementById('albums-container');
@@ -164,7 +347,7 @@ function appendAlbums(albums) {
let dataSrc = ''; let dataSrc = '';
if (album.cover_image_id) { if (album.cover_image_id) {
dataSrc = `/api/thumbnail/${album.cover_image_id}`; dataSrc = `/api/image/${album.cover_image_id}`;
coverImageUrl = '/assets/placeholder.svg'; // 初始使用占位图 coverImageUrl = '/assets/placeholder.svg'; // 初始使用占位图
} }
@@ -176,7 +359,7 @@ function appendAlbums(albums) {
<div class="album-cover"> <div class="album-cover">
<img <img
src="${coverImageUrl}" src="${coverImageUrl}"
${dataSrc ? `data-src="${dataSrc}"` : ''} ${album.cover_image_id ? `data-image-id="${album.cover_image_id}"` : ''}
alt="${album.title}" alt="${album.title}"
class="lazy" class="lazy"
onerror="this.src='/assets/placeholder.svg'" onerror="this.src='/assets/placeholder.svg'"
@@ -199,112 +382,153 @@ function appendAlbums(albums) {
// 移除加载指示器并添加新相册 // 移除加载指示器并添加新相册
hideLoadingMore(); hideLoadingMore();
container.insertAdjacentHTML('beforeend', newAlbumsHTML); container.insertAdjacentHTML('beforeend', newAlbumsHTML);
// 重新初始化懒加载,观察新添加的图片
initLazyLoading();
} }
// 加载所有相册 // 加载所有相册数据(一次性加载全部)
async function loadAlbums(reset = false) { async function loadAlbums(reset = false) {
try { try {
if (reset) { if (reset) {
currentPage = 1; currentDisplayPage = 1;
allAlbums = []; allAlbums = [];
displayedAlbums = [];
hasMoreAlbums = true; hasMoreAlbums = true;
isAllAlbumsLoaded = false;
const container = document.getElementById('albums-container'); const container = document.getElementById('albums-container');
container.innerHTML = ''; container.innerHTML = '';
} }
if (!hasMoreAlbums) return; // 如果已经加载过所有数据,直接显示当前页
if (isAllAlbumsLoaded) {
// 显示骨架屏 displayCurrentPage();
if (currentPage === 1) { return;
showSkeleton();
} else {
showLoadingMore();
} }
const response = await fetch(`${API_BASE}/albums?page=${currentPage}&limit=${albumsPerPage}`); // 显示骨架屏
showSkeleton();
// 一次性加载所有相册数据
const response = await fetch(`${API_BASE}/albums`);
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
const newAlbums = await response.json(); allAlbums = await response.json();
isAllAlbumsLoaded = true;
// 检查是否还有更多数据 // 显示第一页数据
if (newAlbums.length < albumsPerPage) { displayCurrentPage();
hasMoreAlbums = false;
}
// 合并到现有相册列表
allAlbums = [...allAlbums, ...newAlbums];
if (currentPage === 1) {
displayAlbums(allAlbums);
} else {
appendAlbums(newAlbums);
}
updateStats(allAlbums); updateStats(allAlbums);
// 初始化图片懒加载 // 初始化图片懒加载
initLazyLoading(); initLazyLoading();
currentPage++; // 预加载下一批图片
preloadNextBatchImages();
// 隐藏加载更多指示器
hideLoadingMore();
} catch (error) { } catch (error) {
console.error('加载相册失败:', error); console.error('加载相册失败:', error);
showError('加载相册数据失败,请刷新页面重试'); showError('加载相册数据失败,请刷新页面重试');
hideLoadingMore();
} }
} }
// 显示当前页的相册数据
function displayCurrentPage() {
const startIndex = (currentDisplayPage - 1) * albumsPerPage;
const endIndex = startIndex + albumsPerPage;
// 获取当前页要显示的相册
displayedAlbums = allAlbums.slice(startIndex, endIndex);
// 如果是第一页,直接显示;否则追加显示
if (currentDisplayPage === 1) {
displayAlbums(displayedAlbums);
} else {
appendAlbums(displayedAlbums);
}
// 检查是否还有更多数据可以显示
hasMoreAlbums = (currentDisplayPage * albumsPerPage) < allAlbums.length;
}
// 搜索相册 // 搜索相册
async function searchAlbums() { // 防抖搜索函数
async function debouncedSearch() {
const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
if (searchTerm === '') { if (searchTerm === '') {
// 显示所有相册,重置分页 // 显示所有已加载的相册
loadAlbums(true); displayAlbums(allAlbums);
updateStats();
return; return;
} }
try { // 直接使用后端搜索API进行全站搜索
// 重置搜索状态 await performServerSearch(searchTerm);
currentPage = 1; }
allAlbums = [];
hasMoreAlbums = true;
// 在当前已加载的数据集中搜索
function searchInLoadedAlbums(searchTerm) {
if (!allAlbums.length) return [];
return allAlbums.filter(album => {
// 搜索标题和描述
const titleMatch = album.title.toLowerCase().includes(searchTerm);
const descriptionMatch = album.description && album.description.toLowerCase().includes(searchTerm);
return titleMatch || descriptionMatch;
});
}
// 显示搜索提示
function showSearchHint(searchTerm) {
const container = document.getElementById('albums-container');
container.innerHTML = `
<div class="search-hint">
<i class="fas fa-search"></i>
<h3>未在当前页面找到 "${searchTerm}"</h3>
<p>尝试:</p>
<ul>
<li>继续滚动加载更多相册</li>
<li>使用更精确的搜索词</li>
<li><button class="btn-primary" onclick="performServerSearch('${searchTerm}')">在全站搜索 "${searchTerm}"</button></li>
</ul>
</div>
`;
document.getElementById('stats').innerHTML = `在当前页面中未找到包含 "${searchTerm}" 的相册`;
}
// 执行服务器端搜索(全站搜索)
async function performServerSearch(searchTerm) {
try {
// 显示搜索中的骨架屏 // 显示搜索中的骨架屏
showSkeleton(4); showSkeleton(4);
const response = await fetch(`${API_BASE}/search?q=${encodeURIComponent(searchTerm)}&page=${currentPage}&limit=${albumsPerPage}`); const response = await fetch(`${API_BASE}/search?q=${encodeURIComponent(searchTerm)}&page=1&limit=${albumsPerPage}`);
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
const filteredAlbums = await response.json(); const serverResults = await response.json();
allAlbums = filteredAlbums;
// 检查是否还有更多数据 if (serverResults.length === 0) {
if (filteredAlbums.length < albumsPerPage) { showError(`没有找到包含 "${searchTerm}" 的相册`);
hasMoreAlbums = false; return;
} }
displayAlbums(filteredAlbums); // 显示服务器搜索结果
displayAlbums(serverResults);
if (filteredAlbums.length === 0) { document.getElementById('stats').innerHTML = `在全站找到 ${serverResults.length} 个包含 "${searchTerm}" 的相册`;
document.getElementById('stats').innerHTML = `没有找到包含 "${searchTerm}" 的相册`;
} else {
document.getElementById('stats').innerHTML = `找到 ${filteredAlbums.length} 个包含 "${searchTerm}" 的相册`;
}
// 初始化图片懒加载 // 初始化图片懒加载
initLazyLoading(); initLazyLoading();
currentPage++;
} catch (error) { } catch (error) {
console.error('搜索失败:', error); console.error('全站搜索失败:', error);
showError('搜索失败,请重试'); showError('全站搜索失败,请重试');
} }
} }
@@ -323,7 +547,7 @@ function displayAlbums(albums) {
let dataSrc = ''; let dataSrc = '';
if (album.cover_image_id) { if (album.cover_image_id) {
dataSrc = `/api/thumbnail/${album.cover_image_id}`; dataSrc = `/api/image/${album.cover_image_id}`;
coverImageUrl = '/assets/placeholder.svg'; // 初始使用占位图 coverImageUrl = '/assets/placeholder.svg'; // 初始使用占位图
} }
@@ -335,7 +559,7 @@ function displayAlbums(albums) {
<div class="album-cover"> <div class="album-cover">
<img <img
src="${coverImageUrl}" src="${coverImageUrl}"
${dataSrc ? `data-src="${dataSrc}"` : ''} ${album.cover_image_id ? `data-image-id="${album.cover_image_id}"` : ''}
alt="${album.title}" alt="${album.title}"
class="lazy" class="lazy"
onerror="this.src='/assets/placeholder.svg'" onerror="this.src='/assets/placeholder.svg'"
@@ -356,43 +580,35 @@ function displayAlbums(albums) {
}).join(''); }).join('');
} }
// 初始化图片懒加载
function initLazyLoading() {
if ('IntersectionObserver' in window) { // 预加载下一批图片
const imageObserver = new IntersectionObserver((entries, observer) => { function preloadNextBatchImages() {
entries.forEach(entry => { const imagesToPreload = [];
if (entry.isIntersecting) { const visibleImages = document.querySelectorAll('img[data-image-id]:not(.loaded)');
const img = entry.target;
if (img.dataset.src) { // 预加载前5张可见图片
img.src = img.dataset.src; visibleImages.forEach((img, index) => {
img.classList.remove('lazy'); if (index < 5) {
delete img.dataset.src; const imageId = img.getAttribute('data-image-id');
if (imageId) {
imagesToPreload.push(imageId);
} }
imageObserver.unobserve(img);
} }
}); });
}, {
rootMargin: '50px 0px',
threshold: 0.1
});
document.querySelectorAll('img.lazy').forEach(img => { // 使用图片加载器预加载
imageObserver.observe(img); imagesToPreload.forEach(imageId => {
const tempImg = new Image();
imageLoader.loadImage(imageId, tempImg);
}); });
} 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;
}
});
}
} }
// 更新统计信息 // 更新统计信息
function updateStats(albums) { function updateStats(albums) {
if (!albums) {
albums = allAlbums;
}
const totalImages = albums.reduce((sum, album) => sum + album.image_count, 0); const totalImages = albums.reduce((sum, album) => sum + album.image_count, 0);
document.getElementById('stats').innerHTML = `共发现 ${albums.length} 个相册,包含 ${totalImages} 张图片`; document.getElementById('stats').innerHTML = `共发现 ${albums.length} 个相册,包含 ${totalImages} 张图片`;
} }
@@ -404,22 +620,39 @@ function showError(message) {
document.getElementById('stats').innerHTML = ''; document.getElementById('stats').innerHTML = '';
} }
// 键盘事件处理 // 搜索相册函数
function handleKeyPress(event) { async function searchAlbums() {
if (event.key === 'Enter') { await debouncedSearch();
searchAlbums();
}
} }
// 性能监控 // 性能监控
function logPerformance() { function logPerformance() {
if ('performance' in window) { if ('performance' in window) {
window.addEventListener('load', () => { // 使用更可靠的方式获取页面加载时间
setTimeout(() => { const calculateLoadTime = () => {
const navigationTiming = performance.getEntriesByType('navigation')[0]; const navigationTiming = performance.getEntriesByType('navigation')[0];
console.log('页面加载时间:', navigationTiming.loadEventEnd - navigationTiming.navigationStart, 'ms'); if (navigationTiming && navigationTiming.loadEventEnd > 0 && navigationTiming.navigationStart > 0) {
}, 0); const loadTime = navigationTiming.loadEventEnd - navigationTiming.navigationStart;
}); console.log('页面加载时间:', loadTime, 'ms');
} else {
// 备用方案:使用DOMContentLoaded时间
const domContentLoadedTime = performance.timing?.domContentLoadedEventEnd - performance.timing?.navigationStart;
if (domContentLoadedTime && domContentLoadedTime > 0) {
console.log('DOM加载时间:', domContentLoadedTime, 'ms');
} else {
console.log('页面加载时间: 无法计算');
}
}
};
// 如果页面已经加载完成,直接计算
if (document.readyState === 'complete') {
calculateLoadTime();
} else {
// 否则等待页面加载完成
window.addEventListener('load', calculateLoadTime);
}
} }
} }
@@ -437,33 +670,145 @@ function preventDoubleTapZoom() {
} }
} }
// 预加载关键资源
function preloadCriticalResources() {
// 预加载字体文件(CSS文件不应该预加载,因为已经在HTML中引用了)
const fontResources = [
'/assets/webfonts/fa-solid-900.woff2',
'/assets/webfonts/fa-brands-400.woff2',
'/assets/webfonts/fa-regular-400.woff2'
];
fontResources.forEach(resource => {
const link = document.createElement('link');
link.rel = 'preload';
link.href = resource;
link.as = 'font';
link.crossOrigin = 'anonymous';
document.head.appendChild(link);
});
// 预加载第一屏可能需要的图片
setTimeout(() => {
const firstScreenImages = [
'/assets/placeholder.svg'
];
firstScreenImages.forEach(img => {
const preload = document.createElement('link');
preload.rel = 'preload';
preload.href = img;
preload.as = 'image';
document.head.appendChild(preload);
});
}, 100);
}
// 优化滚动性能
function optimizeScrollPerformance() {
// 使用requestAnimationFrame优化滚动
let ticking = false;
function updateOnScroll() {
// 在滚动时暂停非关键任务
if (!ticking) {
requestAnimationFrame(() => {
// 延迟加载非关键图片
delayNonCriticalImages();
ticking = false;
});
ticking = true;
}
}
window.addEventListener('scroll', updateOnScroll, {passive: true});
}
// 延迟加载非关键图片
function delayNonCriticalImages() {
const nonCriticalImages = document.querySelectorAll('img[data-delayed]');
nonCriticalImages.forEach(img => {
if (isElementInViewport(img)) {
const src = img.getAttribute('data-delayed');
if (src) {
img.src = src;
img.removeAttribute('data-delayed');
}
}
});
}
// 检查元素是否在视口中
function isElementInViewport(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
// 初始化性能监控和移动端优化 // 初始化性能监控和移动端优化
logPerformance(); logPerformance();
preventDoubleTapZoom(); preventDoubleTapZoom();
// 预加载关键资源
preloadCriticalResources();
// 优化滚动性能
optimizeScrollPerformance();
// 随机打开相册 // 随机打开相册
function openRandomAlbum() { function openRandomAlbum() {
if (allAlbums.length === 0) {
alert('暂无相册数据,请稍后再试');
return;
}
const randomIndex = Math.floor(Math.random() * allAlbums.length);
const randomAlbum = allAlbums[randomIndex];
// 添加随机动画效果 // 添加随机动画效果
const randomButton = document.querySelector('.random-button'); const randomButton = document.querySelector('.random-button');
randomButton.style.transform = 'scale(0.95)'; randomButton.style.transform = 'scale(0.95)';
randomButton.disabled = true;
// 显示加载状态
const originalText = randomButton.textContent;
randomButton.textContent = '随机加载中...';
// 调用新的随机相册API
fetch(`${API_BASE}/album/random`)
.then(response => {
if (!response.ok) {
if (response.status === 404) {
throw new Error('暂无相册数据,请稍后再试');
}
throw new Error('获取随机相册失败');
}
return response.json();
})
.then(randomAlbum => {
// 恢复按钮状态
setTimeout(() => { setTimeout(() => {
randomButton.style.transform = ''; randomButton.style.transform = '';
randomButton.disabled = false;
randomButton.textContent = originalText;
}, 200); }, 200);
// 跳转到随机相册 // 跳转到随机相册
window.location.href = `/album?id=${randomAlbum.id}`; window.location.href = `/album?id=${randomAlbum.id}`;
})
.catch(error => {
// 恢复按钮状态
setTimeout(() => {
randomButton.style.transform = '';
randomButton.disabled = false;
randomButton.textContent = originalText;
}, 200);
alert(error.message);
});
} }
// 显示收藏夹 // 显示收藏夹
function showFavorites() { function showFavorites() {
// 设置当前在收藏页
isInFavoritesPage = true;
// 从后端API获取收藏列表 // 从后端API获取收藏列表
fetch(`${API_BASE}/favorites`) fetch(`${API_BASE}/favorites`)
.then(response => { .then(response => {
@@ -504,17 +849,18 @@ function displayFavorites(favoriteImages) {
</button> </button>
</div> </div>
` : `${favoriteImages.map((fav, index) => ` ` : `${favoriteImages.map((fav, index) => `
<div class="favorite-card" onclick="openFavoriteImage('${fav.favorite.album_id}')"> <div class="favorite-card" onclick="openFavoriteImage('${fav.favorite.album_id}')" tabindex="0">
<div class="card-image"> <div class="card-image">
<img src="${API_BASE}/thumbnail/${fav.image.id}" <img src="/assets/placeholder.svg"
data-image-id="${fav.image.id}"
alt="${fav.image.title || '收藏的图片'}" alt="${fav.image.title || '收藏的图片'}"
loading="lazy"> loading="lazy">
<div class="card-overlay"> <div class="card-overlay">
<div class="overlay-content"> <div class="overlay-content">
<button class="quick-view" onclick="event.stopPropagation(); previewFavorite(${index})"> <button class="quick-view" onclick="event.stopPropagation(); previewFavorite(${index})" aria-label="预览图片">
<i class="fas fa-expand"></i> <i class="fas fa-expand"></i>
</button> </button>
<button class="remove-favorite" onclick="removeFavorite(event, '${fav.favorite.id}')"> <button class="remove-favorite" onclick="removeFavorite(event, '${fav.favorite.id}')" aria-label="移除收藏">
<i class="fas fa-trash"></i> <i class="fas fa-trash"></i>
</button> </button>
</div> </div>
@@ -554,13 +900,16 @@ function displayFavorites(favoriteImages) {
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="action-buttons"> <div class="action-buttons">
<button class="back-button" onclick="loadAlbums()"> <button class="back-button" onclick="backToHome()">
<i class="fas fa-arrow-left"></i> 返回首页 <i class="fas fa-arrow-left"></i> 返回首页
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</div>`; </div>`;
// 初始化图片懒加载,确保收藏的图片被加载
initLazyLoading();
} }
// 格式化日期 // 格式化日期
@@ -573,6 +922,14 @@ function formatDate(dateString) {
}); });
} }
// 返回首页
function backToHome() {
// 重置收藏页标记
isInFavoritesPage = false;
// 重新加载首页相册
loadAlbums(true);
}
// 全局变量存储收藏列表和当前预览索引 // 全局变量存储收藏列表和当前预览索引
let currentFavorites = []; let currentFavorites = [];
let currentPreviewIndex = -1; let currentPreviewIndex = -1;
@@ -630,7 +987,7 @@ function showPreviewModal(index) {
</div> </div>
<div class="preview-content"> <div class="preview-content">
<div class="preview-image-container"> <div class="preview-image-container">
<img src="${API_BASE}/original/${favorite.image.id}" <img src="${API_BASE}/image/${favorite.image.id}"
alt="${favorite.image.title || '预览图片'}" alt="${favorite.image.title || '预览图片'}"
class="preview-image" class="preview-image"
id="preview-image" id="preview-image"
@@ -748,7 +1105,7 @@ function updatePreviewContent(newIndex) {
// 加载新图片 // 加载新图片
const newImage = new Image(); const newImage = new Image();
newImage.src = `${API_BASE}/original/${favorite.image.id}`; newImage.src = `${API_BASE}/image/${favorite.image.id}`;
newImage.alt = favorite.image.title || '预览图片'; newImage.alt = favorite.image.title || '预览图片';
newImage.className = 'preview-image'; newImage.className = 'preview-image';
@@ -805,12 +1162,6 @@ function removeFavoriteFromPreview(favoriteId) {
} }
} }
// 排序收藏夹
function sortFavorites(mode) {
// 这里可以实现排序功能
alert('排序功能开发中...');
}
// 从收藏夹移除图片 // 从收藏夹移除图片
function removeFavorite(event, favoriteId) { function removeFavorite(event, favoriteId) {
event.stopPropagation(); // 阻止事件冒泡 event.stopPropagation(); // 阻止事件冒泡
@@ -844,7 +1195,6 @@ function openFavoriteImage(favoriteId) {
} }
// 导出函数供全局使用 // 导出函数供全局使用
window.handleKeyPress = handleKeyPress;
window.searchAlbums = searchAlbums; window.searchAlbums = searchAlbums;
window.openRandomAlbum = openRandomAlbum; window.openRandomAlbum = openRandomAlbum;
window.showFavorites = showFavorites; window.showFavorites = showFavorites;

View File

@@ -7,4 +7,9 @@ port = 8080
[storage] [storage]
images_dir = "./albums" 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,6 +5,7 @@ CREATE TABLE IF NOT EXISTS albums (
document TEXT NOT NULL, document TEXT NOT NULL,
description TEXT, description TEXT,
cover_image_id TEXT, cover_image_id TEXT,
image_count INTEGER NOT NULL DEFAULT 0, -- 新增图片数量字段
created_at DATETIME NOT NULL, created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL updated_at DATETIME NOT NULL
); );

View File

@@ -7,6 +7,7 @@ pub struct Config {
pub database: DatabaseConfig, pub database: DatabaseConfig,
pub server: ServerConfig, pub server: ServerConfig,
pub storage: StorageConfig, pub storage: StorageConfig,
pub queue: QueueConfig,
} }
@@ -24,7 +25,14 @@ pub struct ServerConfig {
#[derive(Debug, Deserialize, Clone)] #[derive(Debug, Deserialize, Clone)]
pub struct StorageConfig { pub struct StorageConfig {
pub images_dir: PathBuf, 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 { 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::config::Config;
use crate::models::*; use crate::models::*;
use uuid::Uuid; use uuid::Uuid;
use std::time::Duration;
use tokio::time::sleep;
pub struct Database { pub struct Database {
pub pool: SqlitePool, pub pool: SqlitePool,
config: Config,
} }
impl Database { impl Database {
@@ -33,11 +32,11 @@ impl Database {
} }
let pool = SqlitePoolOptions::new() let pool = SqlitePoolOptions::new()
.max_connections(10) // 增加连接数 .max_connections(10) // 优化:减少最大连接数,避免资源浪费
.min_connections(2) // 保持最小连接数 .min_connections(2) // 优化:减少最小连接数
.acquire_timeout(std::time::Duration::from_secs(30)) // 增加获取连接超时时间 .acquire_timeout(std::time::Duration::from_secs(5)) // 优化:减少获取连接超时时间
.idle_timeout(std::time::Duration::from_secs(300)) // 增加空闲超时时间 .idle_timeout(std::time::Duration::from_secs(300)) // 优化:减少空闲超时时间
.max_lifetime(std::time::Duration::from_secs(1800)) // 增加最大生命周期 .max_lifetime(std::time::Duration::from_secs(1800)) // 优化:减少最大生命周期
.connect(url) .connect(url)
.await?; .await?;
@@ -54,82 +53,82 @@ impl Database {
// 创建表 // 创建表
sqlx::migrate!("./migrations").run(&pool).await?; sqlx::migrate!("./migrations").run(&pool).await?;
Ok(Database { pool }) // 确保image_count字段存在并正确初始化
} let db = Database {
pool,
config: config.clone(), // 保存配置副本
/// 带重试机制的数据库操作执行器 };
async fn execute_with_retry<F, T>(&self, operation: F, operation_name: &str) -> Result<T, sqlx::Error> db.ensure_image_count_field().await?;
where
F: Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, sqlx::Error>> + Send>>, Ok(db)
{
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,
}
} }
// 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, page: Option<usize>, limit: Option<usize>) -> Result<Vec<AlbumInfo>, sqlx::Error> { pub async fn get_all_albums(&self) -> Result<Vec<AlbumInfo>, sqlx::Error> {
let page = page.unwrap_or(1);
let limit = limit.unwrap_or(200);
let offset = (page - 1) * limit;
let albums = sqlx::query( let albums = sqlx::query(
r#" r#"
SELECT SELECT
a.id, id,
a.title, title,
a.document, document,
a.description, description,
a.cover_image_id, cover_image_id,
COUNT(img.id) as image_count, image_count,
a.created_at created_at
FROM albums a FROM albums
LEFT JOIN images img ON img.album_id = a.id ORDER BY created_at DESC
GROUP BY a.id, a.title, a.document, a.description, a.cover_image_id, a.created_at
ORDER BY a.document DESC
LIMIT ? OFFSET ?
"# "#
) )
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(&self.pool) .fetch_all(&self.pool)
.await?; .await?;
@@ -158,61 +157,58 @@ impl Database {
Ok(result) Ok(result)
} }
pub async fn search_albums(&self, query: &str, page: Option<usize>, limit: Option<usize>) -> Result<Vec<AlbumInfo>, sqlx::Error> { // 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 search_pattern = format!("%{}%", query);
let page = page.unwrap_or(1); // let page = page.unwrap_or(1);
let limit = limit.unwrap_or(200); // let limit = limit.unwrap_or(50); // 减少默认加载数量,提高响应速度
let offset = (page - 1) * limit; // let offset = (page - 1) * limit;
//
let albums = sqlx::query( // let albums = sqlx::query(
r#" // r#"
SELECT // SELECT
a.id, // id,
a.title, // title,
a.document, // document,
a.description, // description,
a.cover_image_id, // cover_image_id,
COUNT(img.id) as image_count, // image_count,
a.created_at // created_at
FROM albums a // FROM albums
LEFT JOIN images img ON img.album_id = a.id // WHERE title LIKE ?
LEFT JOIN images i ON i.id = a.cover_image_id // ORDER BY created_at DESC
WHERE a.title LIKE ? // LIMIT ? OFFSET ?
GROUP BY a.id, a.title, a.document, a.description, a.cover_image_id, a.created_at // "#
ORDER BY a.created_at DESC // )
LIMIT ? OFFSET ? // .bind(&search_pattern)
"# // .bind(limit as i64)
) // .bind(offset as i64)
.bind(&search_pattern) // .fetch_all(&self.pool)
.bind(limit as i64) // .await?;
.bind(offset as i64) //
.fetch_all(&self.pool) // let mut result = Vec::new();
.await?; // for row in albums {
// let id_str = row.get::<String, _>("id");
let mut result = Vec::new(); // let id = match Uuid::parse_str(&id_str) {
for row in albums { // Ok(uuid) => uuid,
let id_str = row.get::<String, _>("id"); // Err(e) => {
let id = match Uuid::parse_str(&id_str) { // eprintln!("无效的UUID格式: {} - 错误: {}", id_str, e);
Ok(uuid) => uuid, // continue; // 跳过无效的记录
Err(e) => { // }
eprintln!("无效的UUID格式: {} - 错误: {}", id_str, e); // };
continue; // 跳过无效的记录 //
} // result.push(AlbumInfo {
}; // id,
// title: row.get("title"),
result.push(AlbumInfo { // document: row.get("document"),
id, // description: row.get("description"),
title: row.get("title"), // cover_image_id: row.get("cover_image_id"),
document: row.get("document"), // image_count: row.get("image_count"),
description: row.get("description"), // created_at: row.get::<String, _>("created_at"),
cover_image_id: row.get("cover_image_id"), // });
image_count: row.get("image_count"), // }
created_at: row.get::<String, _>("created_at"), //
}); // Ok(result)
} // }
Ok(result)
}
pub async fn get_album_with_images(&self, album_id: Uuid) -> Result<Option<AlbumWithImages>, sqlx::Error> { pub async fn get_album_with_images(&self, album_id: Uuid) -> Result<Option<AlbumWithImages>, sqlx::Error> {
// 获取相册基本信息 // 获取相册基本信息
@@ -249,6 +245,7 @@ impl Database {
title: row.get("title"), title: row.get("title"),
description: row.get("description"), description: row.get("description"),
cover_image_id, cover_image_id,
image_count: row.get("image_count"),
created_at: row.get::<String, _>("created_at"), created_at: row.get::<String, _>("created_at"),
updated_at: row.get::<String, _>("updated_at"), updated_at: row.get::<String, _>("updated_at"),
}; };
@@ -313,7 +310,7 @@ impl Database {
let now = chrono::Utc::now().to_rfc3339(); let now = chrono::Utc::now().to_rfc3339();
sqlx::query( 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(id.to_string())
.bind(album.title) .bind(album.title)
@@ -328,46 +325,69 @@ impl Database {
} }
// 图片操作 // 图片操作
pub async fn add_image(&self, image: CreateImage) -> Result<Uuid, sqlx::Error> { // pub async fn add_image(&self, image: CreateImage) -> Result<Uuid, sqlx::Error> {
let id = Uuid::new_v4(); // let id = Uuid::new_v4();
let now = chrono::Utc::now().to_rfc3339(); // 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( 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(album_id.to_string())
.bind(image.album_id.to_string()) .bind(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) .execute(&self.pool)
.await?; .await?;
// 如果这是相册的第一张图片,设置为封面 Ok(())
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 add_images(&self, images: Vec<CreateImage>) -> Result<Vec<Uuid>, sqlx::Error> { pub async fn add_images(&self, images: Vec<CreateImage>) -> Result<Vec<Uuid>, sqlx::Error> {
@@ -432,12 +452,15 @@ impl Database {
.await?; .await?;
} }
} }
// 更新相册的图片数量
self.update_album_image_count(album_id).await?;
} }
Ok(ids) Ok(ids)
} }
/// 获取相册中的图片数量 /// 获取相册中的图片数量(直接从image_count字段读取)
pub async fn get_album_image_count(&self, album_id: Uuid) -> Result<i64, sqlx::Error> { pub async fn get_album_image_count(&self, album_id: Uuid) -> Result<i64, sqlx::Error> {
let count = sqlx::query_scalar::<_, i64>( let count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM images WHERE album_id = ?" "SELECT COUNT(*) FROM images WHERE album_id = ?"
@@ -449,6 +472,38 @@ impl Database {
Ok(count) 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> { pub async fn delete_album(&self, album_id: Uuid) -> Result<(), sqlx::Error> {
let mut tx = self.pool.begin().await?; let mut tx = self.pool.begin().await?;
@@ -469,6 +524,39 @@ impl Database {
Ok(()) 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> { 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()); let cover_id_str = cover_image_id.map(|id| id.to_string());
@@ -699,4 +787,60 @@ impl Database {
Ok(()) 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 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 struct ImageProcessor {
pub config: StorageConfig, pub config: StorageConfig,
@@ -12,12 +39,15 @@ impl ImageProcessor {
pub fn new(config: StorageConfig) -> Self { pub fn new(config: StorageConfig) -> Self {
// 确保目录存在 // 确保目录存在
fs::create_dir_all(&config.images_dir).unwrap_or(()); fs::create_dir_all(&config.images_dir).unwrap_or(());
fs::create_dir_all(&config.thumbnails_dir).unwrap_or(());
Self { config } 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 image_id = Uuid::new_v4();
let file_extension = Path::new(filename) let file_extension = Path::new(filename)
.extension() .extension()
@@ -35,10 +65,7 @@ impl ImageProcessor {
let (width, height) = img.dimensions(); let (width, height) = img.dimensions();
let file_size = image_data.len() as i64; 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, 0, 0)?;
Ok(ImageInfo { Ok(ImageInfo {
id: image_id, id: image_id,
filename: new_filename, filename: new_filename,
@@ -50,23 +77,15 @@ impl ImageProcessor {
} }
/// 生成缩略图并保存到指定路径(使用统一尺寸) /// 生成缩略图并保存到指定路径(使用统一尺寸)
/// 此功能已被移除,直接返回成功
pub fn generate_thumbnail( pub fn generate_thumbnail(
&self, &self,
img: &image::DynamicImage, _img: &image::DynamicImage,
output_path: &Path, _output_path: &Path,
_max_width: u32, _max_width: u32,
_max_height: u32, _max_height: u32,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), ImageProcessorError> {
// 使用统一的缩略图尺寸(400x300,保持宽高比) // 缩略图功能已移除,此函数不再执行任何操作
let thumbnail = img.thumbnail(400, 300);
// 确保输出目录存在
if let Some(parent) = output_path.parent() {
fs::create_dir_all(parent)?;
}
thumbnail.save_with_format(output_path, ImageFormat::Jpeg)?;
Ok(()) Ok(())
} }
@@ -80,61 +99,67 @@ 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(); // 无需调整
} }
pub fn get_thumbnail_url(&self, filename: &str) -> String { let new_height = (height as f32 * max_width as f32 / width as f32) as u32;
format!("/thumbnails/thumb_{}", filename) 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_image_url(&self, filename: &str) -> String {
format!("/images/{}", filename)
} }
pub async fn download_and_save_image( pub async fn download_and_save_image(
&self, &self,
url: &str, url: &str,
filename: &str, filename: &str,
) -> Result<ImageInfo, Box<dyn std::error::Error>> { ) -> Result<ImageInfo, ImageProcessorError> {
let response = reqwest::get(url).await?; let response = reqwest::get(url).await?;
let image_data = response.bytes().await?; let image_data = response.bytes().await?;
self.save_image(&image_data, filename).await self.save_image(&image_data, filename).await
} }
/// 从图片数据生成缩略图并保存到文件 /// 检测图片格式
pub async fn generate_thumbnail_from_data( fn detect_image_format(&self, image_data: &[u8]) -> Option<String> {
&self, if image_data.len() < 12 {
image_data: &[u8], return None;
thumbnail_filename: &str,
) -> Result<(), Box<dyn std::error::Error>> {
// 使用统一的缩略图生成方法
let thumbnail_data = self.generate_thumbnail_from_memory(image_data, thumbnail_filename).await?;
// 确保缩略图目录存在
fs::create_dir_all(&self.config.thumbnails_dir)?;
// 保存缩略图到文件
let thumbnail_path = self.config.thumbnails_dir.join(thumbnail_filename);
fs::write(&thumbnail_path, thumbnail_data)?;
Ok(())
} }
/// 从内存中的图片数据生成缩略图数据(不保存到文件) match &image_data[0..12] {
pub async fn generate_thumbnail_from_memory( b"\xff\xd8\xff" => Some("JPEG".to_string()),
&self, b"\x89PNG\r\n\x1a\n" => Some("PNG".to_string()),
image_data: &[u8], b"GIF87a" => Some("GIF87a".to_string()),
_thumbnail_filename: &str, b"GIF89a" => Some("GIF89a".to_string()),
) -> Result<Vec<u8>, Box<dyn std::error::Error>> { b"BM" => Some("BMP".to_string()),
// 加载图片 b"RIFF" if image_data.len() > 12 && &image_data[8..12] == b"WEBP" => {
let img = image::load_from_memory(image_data)?; Some("WebP".to_string())
}
// 生成缩略图(400x300,保持宽高比) _ => None,
let thumbnail = img.thumbnail(400, 300); }
// 将缩略图数据保存到内存缓冲区
let mut buffer = std::io::Cursor::new(Vec::new());
thumbnail.write_to(&mut buffer, ImageFormat::Jpeg)?;
Ok(buffer.into_inner())
} }
} }

View File

@@ -9,13 +9,49 @@ use crate::config::Config;
use crate::database::Database; use crate::database::Database;
use crate::models::*; use crate::models::*;
#[derive(Debug, Deserialize)] /// 批量插入图片并设置封面缩略图的辅助函数
struct AlbumIndex { async fn batch_insert_images_and_set_cover(
title: String, db: &Database,
images: Vec<String>, 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);
} }
pub async fn import_existing_data(config: &Config, db: Arc<Database>) -> Result<(), Box<dyn std::error::Error>> { 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>, _task_queue: Option<Arc<crate::queue::TaskQueue>>) -> Result<(), Box<dyn std::error::Error>> {
println!("开始扫描图片目录并导入新相册..."); println!("开始扫描图片目录并导入新相册...");
let albums_dir = Path::new(&config.storage.images_dir); let albums_dir = Path::new(&config.storage.images_dir);
@@ -26,7 +62,7 @@ pub async fn import_existing_data(config: &Config, db: Arc<Database>) -> Result<
} }
// 获取数据库中现有的相册列表 // 获取数据库中现有的相册列表
let existing_albums = db.get_all_albums(None, None).await?; let existing_albums = db.get_all_albums().await?;
let existing_titles: Vec<String> = existing_albums.iter() let existing_titles: Vec<String> = existing_albums.iter()
.map(|album| album.document.to_lowercase()) .map(|album| album.document.to_lowercase())
.collect(); .collect();
@@ -102,8 +138,9 @@ pub async fn import_existing_data(config: &Config, db: Arc<Database>) -> Result<
return Ok(()); return Ok(());
} }
// 第二阶段:串行处理相册导入,避免数据库死锁 // 使用简单的串行处理方式导入相册
// 对于SQLite,高并发写入容易导致死锁,改为串行处理 println!("📁 开始导入新相册...");
let mut total_imported = 0; let mut total_imported = 0;
let mut successful_albums = 0; let mut successful_albums = 0;
@@ -125,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); println!("🎉 导入完成!成功导入 {} 个相册,共 {} 张图片", successful_albums, total_imported);
Ok(()) Ok(())
} }
@@ -261,46 +296,12 @@ async fn import_single_album(db: &Database, folder_name: &str, path: &Path) -> R
} }
} }
// 批量插入图片 // 使用辅助函数批量插入图片并设置封面
if !images_to_insert.is_empty() { batch_insert_images_and_set_cover(&db, images_to_insert, album_id, path, folder_name).await
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 {
// 生成缩略图
match generate_thumbnail_for_image(&first_image, path, folder_name).await {
Ok(_) => println!(" 封面缩略图生成成功"),
Err(e) => eprintln!(" 封面缩略图生成失败: {}", e),
}
}
}
Ok(ids.len())
}
Err(e) => {
eprintln!(" 批量插入失败: {}", e);
Ok(0)
}
}
} else {
Ok(0)
}
} }
/// 快速扫描图片文件 /// 快速扫描图片文件
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(); let mut image_files = Vec::new();
for entry in fs::read_dir(path)? { for entry in fs::read_dir(path)? {
@@ -438,78 +439,8 @@ async fn reimport_single_album(
println!(" 发现 {} 张图片需要导入", images_to_insert.len()); println!(" 发现 {} 张图片需要导入", images_to_insert.len());
// 批量插入图片 // 使用辅助函数批量插入图片并设置封面
if !images_to_insert.is_empty() { batch_insert_images_and_set_cover(&db, images_to_insert, album_id, path, folder_name).await
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 {
// 生成缩略图
match generate_thumbnail_for_image(&first_image, path, folder_name).await {
Ok(_) => println!(" 封面缩略图生成成功"),
Err(e) => eprintln!(" 封面缩略图生成失败: {}", e),
}
}
}
Ok(ids.len())
}
Err(e) => {
eprintln!(" 批量插入失败: {}", e);
Ok(0)
}
}
} else {
Ok(0)
}
}
/// 为图片生成缩略图(使用ImageProcessor)
async fn generate_thumbnail_for_image(
image: &crate::models::Image,
album_path: &Path,
_folder_name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
// 构建图片文件路径
let image_filename = image.filename.split('/').last().unwrap_or(&image.filename);
let image_path = album_path.join(image_filename);
if !image_path.exists() {
return Err(format!("图片文件不存在: {}", image_path.display()).into());
}
// 读取图片数据
let image_data = fs::read(&image_path)?;
// 创建临时的ImageProcessor实例
// 注意:这里使用默认的缩略图目录路径
let config = crate::config::StorageConfig {
images_dir: Path::new("./albums").to_path_buf(),
thumbnails_dir: Path::new("./thumbnails").to_path_buf(),
};
let image_processor = crate::image_processor::ImageProcessor::new(config);
// 生成缩略图
match image_processor.generate_thumbnail_from_data(&image_data, &image.id.to_string()).await {
Ok(_) => {
println!(" 缩略图生成成功 (ID: {})", image.id);
Ok(())
}
Err(e) => {
Err(format!("缩略图生成失败: {}", e).into())
}
}
}

View File

@@ -3,60 +3,109 @@ mod database;
mod image_processor; mod image_processor;
mod import; mod import;
mod models; mod models;
mod queue;
mod routes; mod routes;
use crate::models::AlbumsCache;
use actix_files as afs; 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::fs;
use std::sync::Arc; use std::sync::Arc;
use tokio::time::{Duration, interval};
use tracing::{error, info};
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
// 初始化结构化日志
tracing_subscriber::fmt::init();
// 加载配置 // 加载配置
let config = match config::Config::load() { let config = match config::Config::load() {
Ok(cfg) => cfg, Ok(cfg) => cfg,
Err(e) => { Err(e) => {
eprintln!("加载配置失败: {}", e); error!("加载配置失败: {}", e);
std::process::exit(1); std::process::exit(1);
} }
}; };
println!("启动图片展示服务..."); info!("启动图片展示服务...");
println!("服务地址: http://{}", config.server_address()); info!("服务地址: http://localhost:{} http://{}", config.server.port, config.server_address());
// 初始化数据库 // 初始化数据库
let db = match database::Database::new(&config).await { let db = match database::Database::new(&config).await {
Ok(db) => { Ok(db) => {
println!("数据库连接成功"); info!("数据库连接成功");
Arc::new(db) Arc::new(db)
} }
Err(e) => { Err(e) => {
eprintln!("数据库连接失败: {}", e); error!("数据库连接失败: {}", e);
std::process::exit(1); std::process::exit(1);
} }
}; };
let image_processor = Arc::new(image_processor::ImageProcessor::new(config.storage.clone()));
// 在后台线程中自动导入新相册(不阻塞HTTP服务启动) // 在后台线程中自动导入新相册(不阻塞HTTP服务启动)
let config_clone = config.clone(); let config_clone = config.clone();
let db_clone = Arc::clone(&db); let db_clone = Arc::clone(&db);
tokio::spawn(async move { tokio::spawn(async move {
println!("[后台任务] 开始扫描图片目录并导入新相册..."); info!("[后台任务] 开始扫描图片目录并导入新相册...");
match import::import_existing_data(&config_clone, db_clone).await { match import::import_existing_data(&config_clone, db_clone, None).await {
Ok(_) => println!("[后台任务] 相册导入完成"), Ok(_) => info!("[后台任务] 相册导入完成"),
Err(e) => eprintln!("[后台任务] 相册导入失败: {}", e), 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!("API接口:");
println!(" - GET /api/albums - 获取所有相册"); println!(" - GET /api/albums - 获取所有相册");
println!(" - GET /api/search?q=关键词 - 搜索相册"); println!(" - GET /api/search?q=关键词 - 搜索相册");
println!(" - GET /api/album/:id - 获取相册详情"); println!(" - GET /api/album/:id - 获取相册详情");
println!(" - POST /api/albums - 创建新相册"); println!(" - POST /api/albums - 创建新相册");
println!(" - GET /api/thumbnail/:id - 获取缩略图"); println!(" - GET /api/image/:id - 获取图片(已移除缩略图功能)");
println!(" - GET /api/original/:id - 获取原始图片");
println!(" - GET /api/favorites - 获取收藏列表"); println!(" - GET /api/favorites - 获取收藏列表");
println!(" - GET /api/favorites/status/:id - 检查收藏状态"); println!(" - GET /api/favorites/status/:id - 检查收藏状态");
println!(" - POST /api/favorites - 添加收藏"); 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.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(); let server_address = config.server_address();
HttpServer::new(move || { HttpServer::new(move || {
App::new() 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(&db)))
.app_data(web::Data::new(Arc::clone(&image_processor))) .app_data(web::Data::new(Arc::clone(&image_processor)))
.app_data(web::Data::new(Arc::clone(&albums_cache)))
// API路由 // API路由
.route("/api/albums", web::get().to(routes::get_albums)) .route("/api/albums", web::get().to(routes::get_albums))
.route("/api/search", web::get().to(routes::search_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/album/{id}", web::get().to(routes::get_album_detail))
.route("/api/albums", web::post().to(routes::create_album)) .route("/api/albums", web::post().to(routes::create_album))
.route("/api/thumbnail/{id}", web::get().to(routes::get_thumbnail)) .route("/api/image/{id}", web::get().to(routes::get_image))
.route(
"/api/original/{id}",
web::get().to(routes::get_original_image),
)
// 收藏功能API路由 // 收藏功能API路由
.route("/api/favorites", web::get().to(routes::get_favorites)) .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", web::post().to(routes::add_favorite))
.route("/api/favorites/{id}", web::delete().to(routes::remove_favorite)) .route(
.route("/api/favorites/image/{id}", web::delete().to(routes::remove_favorite_by_image)) "/api/favorites/{id}",
// 静态文件服务 web::delete().to(routes::remove_favorite),
.service(afs::Files::new("/assets", "./assets").show_files_listing()) )
.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页面路由 // HTML页面路由
.route( .route(
"/", "/",
@@ -119,6 +185,8 @@ async fn main() -> std::io::Result<()> {
) )
}) })
.bind(server_address)? .bind(server_address)?
// 限制worker数量为2个,减少系统资源占用
.workers(3)
.run() .run()
.await .await
} }

View File

@@ -1,4 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::info;
use uuid::Uuid; use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -7,11 +9,12 @@ pub struct Album {
pub title: String, pub title: String,
pub description: Option<String>, pub description: Option<String>,
pub cover_image_id: Option<Uuid>, pub cover_image_id: Option<Uuid>,
pub image_count: i64, // 新增图片数量字段
pub created_at: String, pub created_at: String,
pub updated_at: String, pub updated_at: String,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Image { pub struct Image {
pub id: Uuid, pub id: Uuid,
pub album_id: Uuid, pub album_id: Uuid,
@@ -33,7 +36,7 @@ pub struct AlbumWithImages {
pub image_count: i64, pub image_count: i64,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AlbumInfo { pub struct AlbumInfo {
pub id: Uuid, pub id: Uuid,
pub title: String, pub title: String,
@@ -91,3 +94,137 @@ pub struct FavoriteStatus {
pub is_favorited: bool, pub is_favorited: bool,
pub favorite_id: Option<Uuid>, 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,46 +4,35 @@ use crate::models::*;
use actix_web::{HttpResponse, Responder, web}; use actix_web::{HttpResponse, Responder, web};
use std::fs; use std::fs;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::error;
use uuid::Uuid; use uuid::Uuid;
use crate::queue;
pub async fn get_albums(
db: web::Data<Arc<Database>>,
query: web::Query<std::collections::HashMap<String, String>>,
) -> impl Responder {
let page = query.get("page").and_then(|s| s.parse::<usize>().ok());
let limit = query.get("limit").and_then(|s| s.parse::<usize>().ok());
match db.get_all_albums(page, limit).await {
Ok(albums) => HttpResponse::Ok().json(albums),
Err(e) => {
eprintln!("获取相册列表失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({
"error": "获取相册列表失败"
}))
}
}
}
// 收藏功能API路由 // 收藏功能API路由
// 获取用户的收藏列表 // 获取用户的收藏列表
pub async fn get_favorites( pub async fn get_favorites(db: web::Data<Arc<Database>>) -> impl Responder {
db: web::Data<Arc<Database>>,
) -> impl Responder {
// 这里使用固定用户ID,实际项目中应该从认证信息中获取 // 这里使用固定用户ID,实际项目中应该从认证信息中获取
let user_id = "default_user".to_string(); let user_id = "default_user".to_string();
match db.get_user_favorites(&user_id).await { let favorites = match db.get_user_favorites(&user_id).await {
Ok(favorites) => HttpResponse::Ok().json(favorites), Ok(value) => value,
Err(e) => { Err(e) => {
eprintln!("获取收藏列表失败: {}", e); error!("获取收藏列表失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({ return HttpResponse::InternalServerError().json(serde_json::json!({
"error": "获取收藏列表失败" "error": "获取收藏列表失败"
})) }));
}
} }
};
HttpResponse::Ok().json(favorites)
} }
// 图片质量检查功能已移除,直接返回原始图片
// 检查图片是否被收藏 // 检查图片是否被收藏
pub async fn check_favorite_status( pub async fn check_favorite_status(
db: web::Data<Arc<Database>>, db: web::Data<Arc<Database>>,
@@ -61,15 +50,17 @@ pub async fn check_favorite_status(
// 这里使用固定用户ID,实际项目中应该从认证信息中获取 // 这里使用固定用户ID,实际项目中应该从认证信息中获取
let user_id = "default_user".to_string(); let user_id = "default_user".to_string();
match db.get_favorite_status(&user_id, image_id).await { let status = match db.get_favorite_status(&user_id, image_id).await {
Ok(status) => HttpResponse::Ok().json(status), Ok(value) => value,
Err(e) => { Err(e) => {
eprintln!("检查收藏状态失败: {}", e); error!("检查收藏状态失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({ return HttpResponse::InternalServerError().json(serde_json::json!({
"error": "检查收藏状态失败" "error": "检查收藏状态失败"
})) }));
}
} }
};
HttpResponse::Ok().json(status)
} }
// 添加收藏 // 添加收藏
@@ -121,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取消收藏 // 通过图片ID取消收藏
pub async fn remove_favorite_by_image( pub async fn remove_favorite_by_image(
db: web::Data<Arc<Database>>, db: web::Data<Arc<Database>>,
@@ -151,81 +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>>, pub async fn get_albums(albums_cache: web::Data<Arc<RwLock<AlbumsCache>>>) -> impl Responder {
path: web::Path<String>, // 从内存缓存获取数据
) -> impl Responder { let cache = albums_cache.read().await;
let image_id = match Uuid::parse_str(&path.into_inner()) { let total_albums = cache.albums.len();
Ok(id) => id,
Err(_) => { // 应用分页
return HttpResponse::BadRequest().json(serde_json::json!({ let start = 0;
"error": "无效的图片ID" 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 { drop(cache); // 释放读锁
Ok(Some(image)) => {
let original_path = image_processor.config.images_dir.join(&image.filename);
if original_path.exists() { HttpResponse::Ok().json(paginated_albums)
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": "获取图片信息失败"
}))
}
}
} }
pub async fn search_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>>, query: web::Query<std::collections::HashMap<String, String>>,
) -> impl Responder { ) -> impl Responder {
let q = query.get("q").map(|s| s.as_str()).unwrap_or(""); let q = query.get("q").map(|s| s.as_str()).unwrap_or("");
let page = query.get("page").and_then(|s| s.parse::<usize>().ok());
let limit = query.get("limit").and_then(|s| s.parse::<usize>().ok()); // 输入验证
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::<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() { if q.is_empty() {
return match db.get_all_albums(page, limit).await { // 如果没有搜索词,返回所有相册(带分页)
Ok(albums) => HttpResponse::Ok().json(albums), let cache = albums_cache.read().await;
Err(e) => { let total_albums = cache.albums.len();
eprintln!("获取相册列表失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({ // 应用分页
"error": "获取相册列表失败" 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);
} }
match db.search_albums(q, page, limit).await { // 从内存缓存搜索
Ok(albums) => HttpResponse::Ok().json(albums), let cache = albums_cache.read().await;
Err(e) => { let mut search_results = cache.search(q);
eprintln!("搜索相册失败: {}", e);
HttpResponse::InternalServerError().json(serde_json::json!({ // 应用分页到搜索结果
"error": "搜索失败" 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( pub async fn get_album_detail(
@@ -273,7 +311,8 @@ pub async fn create_album(
} }
} }
pub async fn get_thumbnail( /// 获取原始图片
pub async fn get_image(
db: web::Data<Arc<Database>>, db: web::Data<Arc<Database>>,
image_processor: web::Data<Arc<ImageProcessor>>, image_processor: web::Data<Arc<ImageProcessor>>,
path: web::Path<String>, path: web::Path<String>,
@@ -289,60 +328,16 @@ pub async fn get_thumbnail(
match db.get_image(image_id).await { match db.get_image(image_id).await {
Ok(Some(image)) => { 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); let original_path = image_processor.config.images_dir.join(&image.filename);
if thumbnail_path.exists() { if original_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() {
// 生成缩略图并返回
match fs::read(&original_path) { match fs::read(&original_path) {
Ok(data) => { Ok(data) => {
// 使用ImageProcessor生成缩略图
match image_processor.generate_thumbnail_from_memory(&data, &image.id.to_string()).await {
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);
}
});
// 返回缩略图数据
HttpResponse::Ok() HttpResponse::Ok()
.content_type("image/jpeg") .content_type(image.mime_type.clone())
.body(thumbnail_data) .insert_header(("Cache-Control", "public, max-age=31536000"))
} .insert_header(("ETag", format!("\"{}\"", image_id)))
Err(e) => { .body(data)
eprintln!("生成缩略图失败: {}", e);
// 如果生成缩略图失败,返回原始图片
HttpResponse::Ok().content_type(image.mime_type).body(data)
}
}
} }
Err(e) => { Err(e) => {
eprintln!("读取原始图片失败: {}", e); eprintln!("读取原始图片失败: {}", e);