diff --git a/assets/album.html b/assets/album.html index 5885773..30e33f4 100644 --- a/assets/album.html +++ b/assets/album.html @@ -4,7 +4,7 @@ 相册详情 - 图片展示服务 - + @@ -27,15 +27,55 @@ - -
diff --git a/assets/js/album.js b/assets/js/album.js index 28c42b4..8b3ab03 100644 --- a/assets/js/album.js +++ b/assets/js/album.js @@ -3,8 +3,23 @@ let currentAlbum = null; let currentImageIndex = 0; let images = []; +// 设备检测 +const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); +const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0; + +// API基础URL +const API_BASE = '/api'; + // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', function() { + // 添加设备类到body + if (isMobile) { + document.body.classList.add('mobile-device'); + } + if (isTouchDevice) { + document.body.classList.add('touch-device'); + } + const urlParams = new URLSearchParams(window.location.search); const albumId = urlParams.get('id'); @@ -13,11 +28,32 @@ document.addEventListener('DOMContentLoaded', function() { } else { showError('缺少相册ID参数'); } + + // 初始化键盘导航和触摸手势 + initLightboxControls(); }); +// 显示图片骨架屏 +function showImageSkeleton(count = 8) { + const container = document.getElementById('images-container'); + container.innerHTML = Array(count).fill(0).map(() => ` +
+
+ +
+
+ 加载中... +
+
+ `).join(''); +} + // 加载相册详情 async function loadAlbum(albumId) { try { + // 显示骨架屏 + showImageSkeleton(); + const response = await fetch(`/api/album/${albumId}`); if (!response.ok) { if (response.status === 404) { @@ -32,6 +68,9 @@ async function loadAlbum(albumId) { updateAlbumInfo(); displayImages(); + + // 初始化图片懒加载 + initLazyLoading(); } catch (error) { console.error('加载相册失败:', error); showError('加载相册失败: ' + error.message); @@ -46,6 +85,21 @@ function updateAlbumInfo() { document.title = `${currentAlbum.title} - 图片展示服务`; } +// 智能判断图片方向 - 更精确的判断逻辑 +function getImageOrientation(width, height) { + if (!width || !height) return 'square'; + + const ratio = width / height; + + // 更精确的阈值判断 + if (ratio > 1.5) return 'landscape'; // 宽幅图片 + if (ratio < 0.67) return 'portrait'; // 竖幅图片 + if (ratio > 1.2) return 'wide'; // 较宽图片 + if (ratio < 0.83) return 'tall'; // 较高图片 + + return 'square'; // 方形或接近方形的图片 +} + // 显示图片列表 function displayImages() { const container = document.getElementById('images-container'); @@ -56,121 +110,358 @@ function displayImages() { } container.innerHTML = images.map((image, index) => { - // 优先使用缩略图API,如果没有则使用原始URL + // 智能判断图片方向 + const orientation = getImageOrientation(image.width, image.height); + + // 使用懒加载技术 let imageUrl = '/assets/placeholder.svg'; + let dataSrc = ''; + if (image.id) { - imageUrl = `/api/thumbnail/${image.id}`; + dataSrc = `/api/thumbnail/${image.id}`; + imageUrl = '/assets/placeholder.svg'; // 初始使用占位图 } else if (image.original_url) { - imageUrl = image.original_url; + dataSrc = image.original_url; + imageUrl = '/assets/placeholder.svg'; } const title = image.title || `图片 ${index + 1}`; + // 检查图片是否已被收藏 + const isFavorited = isImageFavorited(image.id || image.original_url); + return ` -
- ${title} +
+ ${title}
${image.width ? `${image.width}×${image.height}` : ''} - ${image.file_size ? `${(image.file_size / 1024 ).toFixed(2)} KB` : ''} + ${image.file_size ? `${(image.file_size / 1024).toFixed(2)} KB` : ''}
`; }).join(''); } -// 打开图片查看器 +// 打开图片查看器 - 使用previewModal相同逻辑 function openLightbox(index) { currentImageIndex = index; const lightbox = document.getElementById('lightbox'); - const lightboxImg = document.getElementById('lightbox-img'); - const lightboxInfo = document.getElementById('lightbox-info'); - const image = images[index]; - // 在lightbox中优先使用原始图片以获得更好的显示效果 - let imageUrl = '/assets/placeholder.svg'; - if (image.id) { - imageUrl = `/api/original/${image.id}`; - } else if (image.original_url) { - imageUrl = image.original_url; - } + // 更新lightbox内容 + updateLightboxContent(index); - lightboxImg.src = imageUrl; - - const title = image.title || `图片 ${index + 1}`; - let infoText = `${title} (${index + 1}/${images.length})`; - if (image.width && image.height) { - infoText += ` | ${image.width}×${image.height}`; - } - if (image.file_size) { - infoText += ` | ${(image.file_size / 1024 ).toFixed(2)} KB`; - } - - lightboxInfo.textContent = infoText; - lightbox.style.display = 'flex'; + // 显示lightbox + lightbox.classList.add('active'); document.body.style.overflow = 'hidden'; } // 关闭图片查看器 function closeLightbox() { const lightbox = document.getElementById('lightbox'); - lightbox.style.display = 'none'; + lightbox.classList.remove('active'); document.body.style.overflow = 'auto'; } // 下一张图片 function nextImage() { - currentImageIndex = (currentImageIndex + 1) % images.length; - updateLightboxImage(); + const newIndex = (currentImageIndex + 1) % images.length; + updateLightboxContent(newIndex); } // 上一张图片 function prevImage() { - currentImageIndex = (currentImageIndex - 1 + images.length) % images.length; - updateLightboxImage(); + const newIndex = (currentImageIndex - 1 + images.length) % images.length; + updateLightboxContent(newIndex); } -// 更新图片查看器显示 -function updateLightboxImage() { - const lightboxImg = document.getElementById('lightbox-img'); - const lightboxInfo = document.getElementById('lightbox-info'); +// 更新lightbox内容(不关闭面板) +function updateLightboxContent(newIndex) { + currentImageIndex = newIndex; + const image = images[newIndex]; + // 更新标题和相册信息 + const titleElement = document.getElementById('lightbox-title'); + const albumElement = document.getElementById('lightbox-album'); + if (titleElement) titleElement.textContent = image.title || `图片 ${newIndex + 1}`; + if (albumElement) albumElement.textContent = `来自: ${currentAlbum.title}`; + + // 更新计数器 + const counterElement = document.getElementById('lightbox-counter'); + if (counterElement) counterElement.textContent = `${newIndex + 1} / ${images.length}`; + + // 更新导航按钮状态 + const prevButton = document.getElementById('lightbox-prev'); + const nextButton = document.getElementById('lightbox-next'); + if (prevButton) prevButton.disabled = newIndex === 0; + if (nextButton) nextButton.disabled = newIndex === images.length - 1; + + // 检查收藏状态 + checkLightboxFavoriteStatus(); + + // 更新元数据 + const dimensionsElement = document.getElementById('lightbox-dimensions'); + const sizeElement = document.getElementById('lightbox-size'); + + if (dimensionsElement) { + dimensionsElement.innerHTML = ` ${image.width || 0} × ${image.height || 0}`; + } + + if (sizeElement) { + const fileSizeKB = image.file_size ? (image.file_size / 1024).toFixed(2) : '0'; + sizeElement.innerHTML = ` ${fileSizeKB} KB`; + } + + // 更新图片 + const imageElement = document.getElementById('lightbox-img'); + const loadingElement = document.querySelector('#lightbox .preview-loading'); + + if (imageElement && loadingElement) { + // 显示加载状态 + imageElement.style.opacity = '0'; + loadingElement.style.display = 'flex'; + + // 加载新图片 + const newImage = new Image(); + // 在lightbox中优先使用原始图片以获得更好的显示效果 + let imageUrl = '/assets/placeholder.svg'; + if (image.id) { + imageUrl = `/api/original/${image.id}`; + } else if (image.original_url) { + imageUrl = image.original_url; + } + + newImage.src = imageUrl; + newImage.alt = image.title || `图片 ${newIndex + 1}`; + newImage.className = 'preview-image'; + + newImage.onload = function() { + // 替换图片 + if (imageElement.parentNode) { + imageElement.parentNode.replaceChild(newImage, imageElement); + // 重新设置ID + newImage.id = 'lightbox-img'; + } + + // 隐藏加载状态 + loadingElement.style.display = 'none'; + newImage.style.opacity = '1'; + }; + + newImage.onerror = function() { + // 图片加载失败 + loadingElement.innerHTML = '图片加载失败'; + }; + } +} + +// 初始化图片懒加载 +function initLazyLoading() { + if ('IntersectionObserver' in window) { + const imageObserver = new IntersectionObserver((entries, observer) => { + entries.forEach(entry => { + if (entry.isIntersecting) { + const img = entry.target; + if (img.dataset.src) { + img.src = img.dataset.src; + img.classList.remove('lazy'); + delete img.dataset.src; + } + imageObserver.unobserve(img); + } + }); + }, { + rootMargin: '50px 0px', + threshold: 0.1 + }); + + document.querySelectorAll('img.lazy').forEach(img => { + imageObserver.observe(img); + }); + } else { + // 不支持IntersectionObserver的浏览器回退方案 + document.querySelectorAll('img.lazy').forEach(img => { + if (img.dataset.src) { + img.src = img.dataset.src; + img.classList.remove('lazy'); + delete img.dataset.src; + } + }); + } +} + +// 初始化lightbox控制 +function initLightboxControls() { + // 键盘导航 + document.addEventListener('keydown', function(event) { + const lightbox = document.getElementById('lightbox'); + if (lightbox.classList.contains('active')) { + switch(event.key) { + case 'Escape': + closeLightbox(); + break; + case 'ArrowLeft': + prevImage(); + break; + case 'ArrowRight': + nextImage(); + break; + } + } + }); + + // 点击背景关闭 + document.getElementById('lightbox').addEventListener('click', function(event) { + if (event.target === this) closeLightbox(); + }); + + // 触摸手势支持 + if (isTouchDevice) { + let touchStartX = 0; + let touchStartY = 0; + + document.addEventListener('touchstart', function(event) { + touchStartX = event.touches[0].clientX; + touchStartY = event.touches[0].clientY; + }); + + document.addEventListener('touchend', function(event) { + const lightbox = document.getElementById('lightbox'); + if (!lightbox.classList.contains('active')) return; + + const touchEndX = event.changedTouches[0].clientX; + const touchEndY = event.changedTouches[0].clientY; + + const deltaX = touchEndX - touchStartX; + const deltaY = touchEndY - touchStartY; + + // 水平滑动距离大于垂直滑动距离,且水平滑动距离足够大 + if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) { + if (deltaX > 0) { + prevImage(); + } else { + nextImage(); + } + } + + // 轻点关闭(如果移动距离很小) + if (Math.abs(deltaX) < 10 && Math.abs(deltaY) < 10) { + closeLightbox(); + } + }); + } +} + +// 从lightbox添加收藏 +function addToFavoritesFromLightbox() { const image = images[currentImageIndex]; - // 在lightbox中优先使用原始图片以获得更好的显示效果 - let imageUrl = '/assets/placeholder.svg'; - if (image.id) { - imageUrl = `/api/original/${image.id}`; - } else if (image.original_url) { - imageUrl = image.original_url; + const imageId = image.id; + + if (!imageId) { + alert('无法收藏此图片:缺少图片ID'); + return; } - lightboxImg.src = imageUrl; - - const title = image.title || `图片 ${currentImageIndex + 1}`; - let infoText = `${title} (${currentImageIndex + 1}/${images.length})`; - if (image.width && image.height) { - infoText += ` | ${image.width}×${image.height}`; - } - if (image.file_size) { - infoText += ` | ${(image.file_size / 1024 ).toFixed(2)} KB`; + // 检查是否已经收藏 + const favoriteBtn = document.getElementById('lightbox-favorite-btn'); + if (favoriteBtn.classList.contains('favorited')) { + // 取消收藏 + fetch(`${API_BASE}/favorites/image/${imageId}`, { + method: 'DELETE' + }) + .then(response => { + if (!response.ok) { + throw new Error('取消收藏失败'); + } + return response.json(); + }) + .then(() => { + favoriteBtn.classList.remove('favorited'); + favoriteBtn.innerHTML = ' 加入收藏'; + showFavoriteToast('已取消收藏', false); + }) + .catch(error => { + console.error('取消收藏失败:', error); + alert('取消收藏失败,请稍后重试'); + }); + } else { + // 添加收藏 + const favoriteData = { + image_id: imageId, + album_id: currentAlbum.id + }; + + fetch(`${API_BASE}/favorites`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(favoriteData) + }) + .then(response => { + if (!response.ok) { + throw new Error('添加收藏失败'); + } + return response.json(); + }) + .then(() => { + favoriteBtn.classList.add('favorited'); + favoriteBtn.innerHTML = ' 已收藏'; + showFavoriteToast('已添加到收藏夹', true); + }) + .catch(error => { + console.error('添加收藏失败:', error); + alert('添加收藏失败,请稍后重试'); + }); } - lightboxInfo.textContent = infoText; + // 添加动画效果 + const heartIcon = favoriteBtn.querySelector('i'); + if (heartIcon) { + heartIcon.style.transform = 'scale(1.3)'; + setTimeout(() => { + heartIcon.style.transform = 'scale(1)'; + }, 300); + } } -// 键盘导航 -document.addEventListener('keydown', function(event) { - const lightbox = document.getElementById('lightbox'); - if (lightbox.style.display === 'flex') { - if (event.key === 'Escape') closeLightbox(); - if (event.key === 'ArrowRight') nextImage(); - if (event.key === 'ArrowLeft') prevImage(); - } -}); - -// 点击背景关闭 -document.getElementById('lightbox').addEventListener('click', function(event) { - if (event.target === this) closeLightbox(); -}); +// 检查图片收藏状态并更新lightbox按钮 +function checkLightboxFavoriteStatus() { + const image = images[currentImageIndex]; + const imageId = image.id; + const favoriteBtn = document.getElementById('lightbox-favorite-btn'); + console.log(image) + if (!imageId || !favoriteBtn) return; + + // 检查收藏状态 + fetch(`${API_BASE}/favorites/status/${imageId}`) + .then(response => { + if (!response.ok) { + throw new Error('检查收藏状态失败'); + } + return response.json(); + }) + .then(status => { + if (status.is_favorited) { + favoriteBtn.classList.add('favorited'); + favoriteBtn.innerHTML = ' 已收藏'; + } else { + favoriteBtn.classList.remove('favorited'); + favoriteBtn.innerHTML = ' 加入收藏'; + } + }) + .catch(error => { + console.error('检查收藏状态失败:', error); + // 失败时默认显示"加入收藏" + favoriteBtn.classList.remove('favorited'); + favoriteBtn.innerHTML = ' 加入收藏'; + }); +} // 显示错误信息 function showError(message) { @@ -179,4 +470,178 @@ function showError(message) { document.getElementById('album-title').textContent = '加载失败'; document.getElementById('album-info').innerHTML = ''; -} \ No newline at end of file +} + +// 移动端优化:防止双击缩放 +function preventDoubleTapZoom() { + if (isTouchDevice) { + let lastTouchEnd = 0; + document.addEventListener('touchend', function(event) { + const now = (new Date()).getTime(); + if (now - lastTouchEnd <= 300) { + event.preventDefault(); + } + lastTouchEnd = now; + }, false); + } +} + +// 性能监控 +function logPerformance() { + if ('performance' in window) { + window.addEventListener('load', () => { + setTimeout(() => { + const navigationTiming = performance.getEntriesByType('navigation')[0]; + console.log('相册页面加载时间:', navigationTiming.loadEventEnd - navigationTiming.navigationStart, 'ms'); + }, 0); + }); + } +} + +// 检查图片是否已收藏 +function isImageFavorited(imageId) { + // 这里需要从后端API获取收藏状态 + // 暂时返回false,实际实现中需要调用API + return false; +} + +// 切换收藏状态 +function toggleFavorite(event, imageIndex) { + event.stopPropagation(); // 阻止事件冒泡,避免打开lightbox + + const image = images[imageIndex]; + const imageId = image.id; + + if (!imageId) { + alert('无法收藏此图片:缺少图片ID'); + return; + } + + // 检查当前收藏状态 + const isFavorited = event.target.classList.contains('favorited'); + + if (isFavorited) { + // 取消收藏 + fetch(`${API_BASE}/favorites/image/${imageId}`, { + method: 'DELETE' + }) + .then(response => { + if (!response.ok) { + throw new Error('取消收藏失败'); + } + return response.json(); + }) + .then(() => { + event.target.classList.remove('favorited'); + showFavoriteToast('已取消收藏', false); + }) + .catch(error => { + console.error('取消收藏失败:', error); + alert('取消收藏失败,请稍后重试'); + }); + } else { + // 添加收藏 + const favoriteData = { + image_id: imageId, + album_id: currentAlbum.id + }; + fetch(`${API_BASE}/favorites`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(favoriteData) + }) + .then(response => { + if (!response.ok) { + throw new Error('添加收藏失败'); + } + return response.json(); + }) + .then(() => { + event.target.classList.add('favorited'); + showFavoriteToast('已添加到收藏夹', true); + }) + .catch(error => { + console.error('添加收藏失败:', error); + alert('添加收藏失败,请稍后重试'); + }); + } + + // 添加动画效果 + let heartIcon; + // 确保找到正确的图标元素 + if (event.target.tagName === 'I') { + heartIcon = event.target; + } else if (event.target.tagName === 'BUTTON') { + heartIcon = event.target.querySelector('i'); + } else { + heartIcon = event.target.closest('.favorite-btn')?.querySelector('i'); + } + + if (heartIcon) { + heartIcon.style.transform = 'scale(1.3)'; + setTimeout(() => { + heartIcon.style.transform = 'scale(1)'; + }, 300); + } +} + +// 显示收藏提示 +function showFavoriteToast(message, isAdd) { + // 创建提示元素 + let toast = document.getElementById('favorite-toast'); + if (!toast) { + toast = document.createElement('div'); + toast.id = 'favorite-toast'; + toast.style.cssText = ` + position: fixed; + top: 20px; + right: 20px; + background: ${isAdd ? '#10b981' : '#ef4444'}; + color: white; + padding: 12px 20px; + border-radius: 25px; + box-shadow: 0 4px 12px rgba(0,0,0,0.15); + z-index: 1000; + opacity: 0; + transform: translateX(100px); + transition: all 0.3s ease; + display: flex; + align-items: center; + gap: 8px; + `; + document.body.appendChild(toast); + } + + toast.innerHTML = ` ${message}`; + toast.style.background = isAdd ? '#10b981' : '#ef4444'; + + // 显示动画 + setTimeout(() => { + toast.style.opacity = '1'; + toast.style.transform = 'translateX(0)'; + }, 10); + + // 隐藏动画 + setTimeout(() => { + toast.style.opacity = '0'; + toast.style.transform = 'translateX(100px)'; + setTimeout(() => { + if (toast.parentNode) { + toast.parentNode.removeChild(toast); + } + }, 300); + }, 2000); +} + +// 初始化性能监控和移动端优化 +logPerformance(); +preventDoubleTapZoom(); + +// 导出函数供全局使用 +window.openLightbox = openLightbox; +window.closeLightbox = closeLightbox; +window.prevImage = prevImage; +window.nextImage = nextImage; +window.toggleFavorite = toggleFavorite; \ No newline at end of file diff --git a/assets/js/app.js b/assets/js/app.js index 3a20022..9a60c44 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -1,17 +1,78 @@ // 全局变量 let allAlbums = []; +let searchTimeout = null; // API基础URL const API_BASE = '/api'; +// 设备检测 +const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); +const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0; + + // 页面加载完成后初始化 -document.addEventListener('DOMContentLoaded', function() { +document.addEventListener('DOMContentLoaded', function () { + // 添加设备类到body + if (isMobile) { + document.body.classList.add('mobile-device'); + } + if (isTouchDevice) { + document.body.classList.add('touch-device'); + } + loadAlbums(); + initSearch(); }); +// 初始化搜索功能 +function initSearch() { + const searchInput = document.getElementById('search-input'); + + // 防抖搜索 + searchInput.addEventListener('input', function () { + clearTimeout(searchTimeout); + searchTimeout = setTimeout(debouncedSearch, 300); + }); + + // 移动端优化:搜索框聚焦时自动滚动到可视区域 + if (isMobile) { + searchInput.addEventListener('focus', function () { + setTimeout(() => { + searchInput.scrollIntoView({behavior: 'smooth', block: 'center'}); + }, 100); + }); + } +} + +// 防抖搜索 +function debouncedSearch() { + searchAlbums(); +} + +// 显示骨架屏 +function showSkeleton(count = 6) { + const container = document.getElementById('albums-container'); + container.innerHTML = Array(count).fill(0).map(() => ` +
+
+
+
+
+
+
+
+
+
+
+ `).join(''); +} + // 加载所有相册 async function loadAlbums() { try { + // 显示骨架屏 + showSkeleton(); + const response = await fetch(`${API_BASE}/albums`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); @@ -19,6 +80,9 @@ async function loadAlbums() { allAlbums = await response.json(); displayAlbums(allAlbums); updateStats(allAlbums); + + // 初始化图片懒加载 + initLazyLoading(); } catch (error) { console.error('加载相册失败:', error); showError('加载相册数据失败,请刷新页面重试'); @@ -28,27 +92,33 @@ async function loadAlbums() { // 搜索相册 async function searchAlbums() { const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); - + if (searchTerm === '') { // 显示所有相册 displayAlbums(allAlbums); updateStats(allAlbums); return; } - + try { + // 显示搜索中的骨架屏 + showSkeleton(4); + const response = await fetch(`${API_BASE}/search?q=${encodeURIComponent(searchTerm)}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const filteredAlbums = await response.json(); displayAlbums(filteredAlbums); - + if (filteredAlbums.length === 0) { document.getElementById('stats').innerHTML = `没有找到包含 "${searchTerm}" 的相册`; } else { document.getElementById('stats').innerHTML = `找到 ${filteredAlbums.length} 个包含 "${searchTerm}" 的相册`; } + + // 初始化图片懒加载 + initLazyLoading(); } catch (error) { console.error('搜索失败:', error); showError('搜索失败,请重试'); @@ -58,26 +128,35 @@ async function searchAlbums() { // 显示相册列表 function displayAlbums(albums) { const container = document.getElementById('albums-container'); - + if (albums.length === 0) { container.innerHTML = '

没有找到匹配的相册
'; return; } - + container.innerHTML = albums.map(album => { - // 处理封面图片URL + // 处理封面图片URL - 使用懒加载 let coverImageUrl = '/assets/placeholder.svg'; + let dataSrc = ''; + if (album.cover_image_id) { - coverImageUrl = `/api/thumbnail/${album.cover_image_id}`; + dataSrc = `/api/thumbnail/${album.cover_image_id}`; + coverImageUrl = '/assets/placeholder.svg'; // 初始使用占位图 } - + // 格式化日期 const createdDate = new Date(album.created_at).toLocaleDateString('zh-CN'); - + return ` -
+
- ${album.title} + ${album.title}

${album.title}

@@ -94,6 +173,41 @@ function displayAlbums(albums) { }).join(''); } +// 初始化图片懒加载 +function initLazyLoading() { + if ('IntersectionObserver' in window) { + const imageObserver = new IntersectionObserver((entries, observer) => { + entries.forEach(entry => { + if (entry.isIntersecting) { + const img = entry.target; + if (img.dataset.src) { + img.src = img.dataset.src; + img.classList.remove('lazy'); + delete img.dataset.src; + } + imageObserver.unobserve(img); + } + }); + }, { + rootMargin: '50px 0px', + threshold: 0.1 + }); + + document.querySelectorAll('img.lazy').forEach(img => { + imageObserver.observe(img); + }); + } else { + // 不支持IntersectionObserver的浏览器回退方案 + document.querySelectorAll('img.lazy').forEach(img => { + if (img.dataset.src) { + img.src = img.dataset.src; + img.classList.remove('lazy'); + delete img.dataset.src; + } + }); + } +} + // 更新统计信息 function updateStats(albums) { const totalImages = albums.reduce((sum, album) => sum + album.image_count, 0); @@ -112,4 +226,442 @@ function handleKeyPress(event) { if (event.key === 'Enter') { searchAlbums(); } -} \ No newline at end of file +} + +// 性能监控 +function logPerformance() { + if ('performance' in window) { + window.addEventListener('load', () => { + setTimeout(() => { + const navigationTiming = performance.getEntriesByType('navigation')[0]; + console.log('页面加载时间:', navigationTiming.loadEventEnd - navigationTiming.navigationStart, 'ms'); + }, 0); + }); + } +} + +// 移动端优化:防止双击缩放 +function preventDoubleTapZoom() { + if (isTouchDevice) { + let lastTouchEnd = 0; + document.addEventListener('touchend', function (event) { + const now = (new Date()).getTime(); + if (now - lastTouchEnd <= 300) { + event.preventDefault(); + } + lastTouchEnd = now; + }, false); + } +} + +// 初始化性能监控和移动端优化 +logPerformance(); +preventDoubleTapZoom(); + +// 随机打开相册 +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'); + randomButton.style.transform = 'scale(0.95)'; + setTimeout(() => { + randomButton.style.transform = ''; + }, 200); + + // 跳转到随机相册 + window.location.href = `/album?id=${randomAlbum.id}`; +} + +// 显示收藏夹 +function showFavorites() { + // 从后端API获取收藏列表 + fetch(`${API_BASE}/favorites`) + .then(response => { + if (!response.ok) { + throw new Error('获取收藏列表失败'); + } + return response.json(); + }) + .then(favoriteImages => { + if (favoriteImages.length === 0) { + alert('收藏夹为空,快去收藏一些喜欢的图片吧!'); + return; + } + + // 创建收藏夹页面或跳转到收藏夹视图 + displayFavorites(favoriteImages); + }) + .catch(error => { + console.error('获取收藏列表失败:', error); + alert('获取收藏列表失败,请稍后重试'); + }); +} + +// 显示收藏夹内容 +function displayFavorites(favoriteImages) { + const container = document.getElementById('albums-container'); + + container.innerHTML = ` + ${favoriteImages.length === 0 ? ` +
+
+ +
+

收藏夹空空如也

+

快去收藏一些喜欢的图片吧!

+ +
+ ` : `${favoriteImages.map((fav, index) => ` +
+
+ ${fav.image.title || '收藏的图片'} +
+
+ + +
+
+
+ +
+
+
+
+ + + ${formatDate(fav.favorite.created_at)} + + + + ${fav.image.width}×${fav.image.height} + +
+
+
+ `).join('')} + `} + `; + + // 更新统计信息 - 显示收藏数量 + document.getElementById('stats').innerHTML = `
+
+
+
+ +
+
+

我的收藏夹

+

共收藏了 ${favoriteImages.length} 张图片

+
+
+
+
+ +
+
+
+
`; +} + +// 格式化日期 +function formatDate(dateString) { + const date = new Date(dateString); + return date.toLocaleDateString('zh-CN', { + year: 'numeric', + month: 'short', + day: 'numeric' + }); +} + +// 全局变量存储收藏列表和当前预览索引 +let currentFavorites = []; +let currentPreviewIndex = -1; + +// 预览收藏的图片 +function previewFavorite(index) { + // 获取收藏列表 + fetch(`${API_BASE}/favorites`) + .then(response => { + if (!response.ok) { + throw new Error('获取收藏列表失败'); + } + return response.json(); + }) + .then(favorites => { + if (favorites && favorites.length > index) { + currentFavorites = favorites; + currentPreviewIndex = index; + showPreviewModal(index); + } else { + alert('图片不存在或已被删除'); + } + }) + .catch(error => { + console.error('预览图片失败:', error); + alert('预览图片失败,请稍后重试'); + }); +} + +// 显示预览模态框 +function showPreviewModal(index) { + const favorite = currentFavorites[index]; + + // 构建模态框HTML + const modalHtml = ` +
+
+
+
+
+ 来自: ${favorite.album_title} +
+
+ + ${index + 1} / ${currentFavorites.length} + + +
+
+
+
+ ${favorite.image.title || '预览图片'} +
+
+ +
+
+ `; + + // 添加到页面 + document.body.insertAdjacentHTML('beforeend', modalHtml); + + // 显示模态框 + setTimeout(() => { + const modal = document.getElementById('previewModal'); + modal.classList.add('active'); + }, 10); + + // 监听键盘事件 + document.addEventListener('keydown', handlePreviewKeydown); +} + +// 关闭预览模态框 +function closePreviewModal() { + const modal = document.getElementById('previewModal'); + if (modal) { + modal.classList.remove('active'); + setTimeout(() => { + modal.remove(); + }, 300); + } + + // 移除键盘事件监听 + document.removeEventListener('keydown', handlePreviewKeydown); +} + +// 导航预览图片 +function navigatePreview(direction) { + const newIndex = currentPreviewIndex + direction; + if (newIndex >= 0 && newIndex < currentFavorites.length) { + updatePreviewContent(newIndex); + } +} + +// 更新预览内容(不关闭面板) +function updatePreviewContent(newIndex) { + const favorite = currentFavorites[newIndex]; + currentPreviewIndex = newIndex; + + // 更新标题和相册信息 + const titleElement = document.querySelector('.preview-title h3'); + const infoElement = document.querySelector('.preview-info'); + if (titleElement) titleElement.textContent = favorite.image.title || '未命名图片'; + if (infoElement) infoElement.textContent = `来自: ${favorite.album_title}`; + + // 更新计数器 + const counterElement = document.querySelector('.preview-counter'); + if (counterElement) counterElement.textContent = `${newIndex + 1} / ${currentFavorites.length}`; + + // 更新导航按钮状态 + const prevButton = document.querySelector('.preview-prev'); + const nextButton = document.querySelector('.preview-next'); + if (prevButton) prevButton.disabled = newIndex === 0; + if (nextButton) nextButton.disabled = newIndex === currentFavorites.length - 1; + + // 更新元数据 + const metaElements = document.querySelectorAll('.preview-meta .meta-item'); + if (metaElements.length >= 3) { + metaElements[0].innerHTML = ` ${formatDate(favorite.favorite.created_at)}`; + metaElements[1].innerHTML = ` ${favorite.image.width} × ${favorite.image.height}`; + } + + // 更新操作按钮 + const openAlbumButton = document.querySelector('.preview-action:first-child'); + const removeButton = document.querySelector('.preview-remove'); + if (openAlbumButton) { + openAlbumButton.onclick = () => openFavoriteImage(favorite.favorite.album_id); + } + if (removeButton) { + removeButton.onclick = () => removeFavoriteFromPreview(favorite.favorite.id); + } + + // 更新图片 + const imageElement = document.getElementById('preview-image'); + + if (imageElement ) { + // 显示加载状态 + imageElement.style.opacity = '0'; + + + // 加载新图片 + const newImage = new Image(); + newImage.src = `${API_BASE}/original/${favorite.image.id}`; + newImage.alt = favorite.image.title || '预览图片'; + newImage.className = 'preview-image'; + + newImage.onload = function() { + // 替换图片 + if (imageElement.parentNode) { + imageElement.parentNode.replaceChild(newImage, imageElement); + // 重新设置ID + newImage.id = 'preview-image'; + } + + newImage.style.opacity = '1'; + }; + + newImage.onerror = function() { + // 图片加载失败 + imageElement.innerHTML = '图片加载失败'; + }; + } +} + +// 处理键盘事件 +function handlePreviewKeydown(event) { + if (event.key === 'Escape') { + closePreviewModal(); + } else if (event.key === 'ArrowLeft') { + navigatePreview(-1); + } else if (event.key === 'ArrowRight') { + navigatePreview(1); + } +} + +// 从预览中移除收藏 +function removeFavoriteFromPreview(favoriteId) { + if (confirm('确定要从收藏夹移除这张图片吗?')) { + fetch(`${API_BASE}/favorites/${favoriteId}`, { + method: 'DELETE' + }) + .then(response => { + if (!response.ok) { + throw new Error('取消收藏失败'); + } + return response.json(); + }) + .then(() => { + closePreviewModal(); + // 重新显示收藏夹 + showFavorites(); + }) + .catch(error => { + console.error('取消收藏失败:', error); + alert('取消收藏失败,请稍后重试'); + }); + } +} + +// 排序收藏夹 +function sortFavorites(mode) { + // 这里可以实现排序功能 + alert('排序功能开发中...'); +} + +// 从收藏夹移除图片 +function removeFavorite(event, favoriteId) { + event.stopPropagation(); // 阻止事件冒泡 + + if (confirm('确定要从收藏夹移除这张图片吗?')) { + fetch(`${API_BASE}/favorites/${favoriteId}`, { + method: 'DELETE' + }) + .then(response => { + if (!response.ok) { + throw new Error('取消收藏失败'); + } + return response.json(); + }) + .then(() => { + // 重新显示收藏夹 + showFavorites(); + }) + .catch(error => { + console.error('取消收藏失败:', error); + alert('取消收藏失败,请稍后重试'); + }); + } +} + +// 打开收藏的图片 +function openFavoriteImage(favoriteId) { + // 这里可以跳转到对应的相册页面 + // 在实际实现中,我们需要根据favoriteId获取相册信息 + window.location.href = `/album?id=${favoriteId}`; +} + +// 导出函数供全局使用 +window.handleKeyPress = handleKeyPress; +window.searchAlbums = searchAlbums; +window.openRandomAlbum = openRandomAlbum; +window.showFavorites = showFavorites; \ No newline at end of file diff --git a/assets/webfonts/fa-brands-400.ttf b/assets/webfonts/fa-brands-400.ttf new file mode 100644 index 0000000..227f022 Binary files /dev/null and b/assets/webfonts/fa-brands-400.ttf differ diff --git a/assets/webfonts/fa-brands-400.woff2 b/assets/webfonts/fa-brands-400.woff2 new file mode 100644 index 0000000..73c5c12 Binary files /dev/null and b/assets/webfonts/fa-brands-400.woff2 differ diff --git a/assets/webfonts/fa-regular-400.ttf b/assets/webfonts/fa-regular-400.ttf new file mode 100644 index 0000000..c8ed46d Binary files /dev/null and b/assets/webfonts/fa-regular-400.ttf differ diff --git a/assets/webfonts/fa-regular-400.woff2 b/assets/webfonts/fa-regular-400.woff2 new file mode 100644 index 0000000..c9291c7 Binary files /dev/null and b/assets/webfonts/fa-regular-400.woff2 differ diff --git a/assets/webfonts/fa-solid-900.ttf b/assets/webfonts/fa-solid-900.ttf new file mode 100644 index 0000000..99b35ad Binary files /dev/null and b/assets/webfonts/fa-solid-900.ttf differ diff --git a/assets/webfonts/fa-solid-900.woff2 b/assets/webfonts/fa-solid-900.woff2 new file mode 100644 index 0000000..c7bd59c Binary files /dev/null and b/assets/webfonts/fa-solid-900.woff2 differ diff --git a/assets/webfonts/fa-v4compatibility.ttf b/assets/webfonts/fa-v4compatibility.ttf new file mode 100644 index 0000000..be0afc2 Binary files /dev/null and b/assets/webfonts/fa-v4compatibility.ttf differ diff --git a/assets/webfonts/fa-v4compatibility.woff2 b/assets/webfonts/fa-v4compatibility.woff2 new file mode 100644 index 0000000..37a9b8c Binary files /dev/null and b/assets/webfonts/fa-v4compatibility.woff2 differ diff --git a/config.toml b/config.toml index ba3dd5c..b6fe01e 100644 --- a/config.toml +++ b/config.toml @@ -1,10 +1,10 @@ [database] -url = "sqlite:data/imager.db" +url = "sqlite:./data/imager.db" [server] -host = "127.0.0.1" +host = "0.0.0.0" port = 8080 [storage] -images_dir = "albums" -thumbnails_dir = "thumbnails" \ No newline at end of file +images_dir = "./albums" +thumbnails_dir = "./thumbnails" diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql index c12a543..5b4bdf8 100644 --- a/migrations/001_initial.sql +++ b/migrations/001_initial.sql @@ -26,8 +26,23 @@ CREATE TABLE IF NOT EXISTS images ( FOREIGN KEY (album_id) REFERENCES albums(id) ON DELETE CASCADE ); +-- 创建收藏表 +CREATE TABLE IF NOT EXISTS favorites ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + image_id TEXT NOT NULL, + album_id TEXT NOT NULL, + created_at DATETIME NOT NULL, + FOREIGN KEY (image_id) REFERENCES images(id) ON DELETE CASCADE, + FOREIGN KEY (album_id) REFERENCES albums(id) ON DELETE CASCADE +); + -- 创建索引以提高查询性能 CREATE INDEX IF NOT EXISTS idx_albums_created_at ON albums(created_at); CREATE INDEX IF NOT EXISTS idx_images_album_id ON images(album_id); CREATE INDEX IF NOT EXISTS idx_images_created_at ON images(created_at); -CREATE INDEX IF NOT EXISTS idx_albums_title ON albums(title); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_albums_title ON albums(title); +CREATE INDEX IF NOT EXISTS idx_favorites_user_id ON favorites(user_id); +CREATE INDEX IF NOT EXISTS idx_favorites_image_id ON favorites(image_id); +CREATE INDEX IF NOT EXISTS idx_favorites_album_id ON favorites(album_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_favorites_user_image ON favorites(user_id, image_id); \ No newline at end of file diff --git a/src/database.rs b/src/database.rs index afb7690..2d1e248 100644 --- a/src/database.rs +++ b/src/database.rs @@ -404,4 +404,176 @@ impl Database { Ok(None) } } + + // 收藏功能数据库操作 + + // 获取用户的收藏列表 + pub async fn get_user_favorites(&self, user_id: &str) -> Result, sqlx::Error> { + let rows = sqlx::query( + r#" + SELECT + f.id as favorite_id, + f.user_id, + f.image_id, + f.album_id, + f.created_at as favorite_created_at, + i.id as image_id, + i.album_id, + i.filename, + i.original_url, + i.title, + i.description, + i.file_size, + i.width, + i.height, + i.mime_type, + i.created_at as image_created_at, + a.title as album_title + FROM favorites f + JOIN images i ON f.image_id = i.id + JOIN albums a ON f.album_id = a.id + WHERE f.user_id = ? + ORDER BY f.created_at DESC + "# + ) + .bind(user_id) + .fetch_all(&self.pool) + .await?; + + let mut favorites = Vec::new(); + for row in rows { + let favorite_id_str = row.get::("favorite_id"); + let favorite_id = match Uuid::parse_str(&favorite_id_str) { + Ok(uuid) => uuid, + Err(e) => { + eprintln!("无效的收藏UUID格式: {} - 错误: {}", favorite_id_str, e); + continue; + } + }; + + let image_id_str = row.get::("image_id"); + let image_id = match Uuid::parse_str(&image_id_str) { + Ok(uuid) => uuid, + Err(e) => { + eprintln!("无效的图片UUID格式: {} - 错误: {}", image_id_str, e); + continue; + } + }; + + let album_id_str = row.get::("album_id"); + let album_id = match Uuid::parse_str(&album_id_str) { + Ok(uuid) => uuid, + Err(e) => { + eprintln!("无效的相册UUID格式: {} - 错误: {}", album_id_str, e); + continue; + } + }; + + let favorite = Favorite { + id: favorite_id, + user_id: row.get("user_id"), + image_id, + album_id, + created_at: row.get::("favorite_created_at"), + }; + + let image = Image { + id: image_id, + album_id, + filename: row.get("filename"), + original_url: row.get("original_url"), + title: row.get("title"), + description: row.get("description"), + file_size: row.get("file_size"), + width: row.get("width"), + height: row.get("height"), + mime_type: row.get("mime_type"), + created_at: row.get::("image_created_at"), + }; + + favorites.push(FavoriteWithImage { + favorite, + image, + album_title: row.get("album_title"), + }); + } + + Ok(favorites) + } + + // 检查图片是否被用户收藏 + pub async fn get_favorite_status(&self, user_id: &str, image_id: Uuid) -> Result { + let row = sqlx::query( + "SELECT id FROM favorites WHERE user_id = ? AND image_id = ?" + ) + .bind(user_id) + .bind(image_id.to_string()) + .fetch_optional(&self.pool) + .await?; + + if let Some(row) = row { + let favorite_id_str = row.get::("id"); + let favorite_id = match Uuid::parse_str(&favorite_id_str) { + Ok(uuid) => Some(uuid), + Err(e) => { + eprintln!("无效的收藏UUID格式: {} - 错误: {}", favorite_id_str, e); + None + } + }; + + Ok(FavoriteStatus { + is_favorited: true, + favorite_id, + }) + } else { + Ok(FavoriteStatus { + is_favorited: false, + favorite_id: None, + }) + } + } + + // 添加收藏 + pub async fn add_favorite(&self, user_id: &str, favorite_data: CreateFavorite) -> Result { + let favorite_id = Uuid::new_v4(); + let now = chrono::Utc::now().to_rfc3339(); + + sqlx::query( + "INSERT INTO favorites (id, user_id, image_id, album_id, created_at) VALUES (?, ?, ?, ?, ?)" + ) + .bind(favorite_id.to_string()) + .bind(user_id) + .bind(favorite_data.image_id.to_string()) + .bind(favorite_data.album_id.to_string()) + .bind(&now) + .execute(&self.pool) + .await?; + + Ok(favorite_id) + } + + // 移除收藏(通过收藏ID) + pub async fn remove_favorite(&self, favorite_id: Uuid) -> Result<(), sqlx::Error> { + sqlx::query( + "DELETE FROM favorites WHERE id = ?" + ) + .bind(favorite_id.to_string()) + .execute(&self.pool) + .await?; + + Ok(()) + } + + // 移除收藏(通过用户ID和图片ID) + pub async fn remove_favorite_by_image(&self, user_id: &str, image_id: Uuid) -> Result<(), sqlx::Error> { + sqlx::query( + "DELETE FROM favorites WHERE user_id = ? AND image_id = ?" + ) + .bind(user_id) + .bind(image_id.to_string()) + .execute(&self.pool) + .await?; + + Ok(()) + } } \ No newline at end of file diff --git a/src/import.rs b/src/import.rs index d800830..f155f9d 100644 --- a/src/import.rs +++ b/src/import.rs @@ -1,7 +1,9 @@ use std::fs; use std::path::Path; +use std::sync::Arc; use image::GenericImageView; use serde::Deserialize; +use tokio::task; use crate::config::Config; use crate::database::Database; use crate::models::*; @@ -12,7 +14,7 @@ struct AlbumIndex { images: Vec, } -pub async fn import_existing_data(config: &Config, db: &Database) -> Result<(), Box> { +pub async fn import_existing_data(config: &Config, db: Arc) -> Result<(), Box> { println!("开始扫描图片目录并导入新相册..."); let albums_dir = Path::new(&config.storage.images_dir); @@ -30,13 +32,12 @@ pub async fn import_existing_data(config: &Config, db: &Database) -> Result<(), println!("数据库中现有相册数量: {}", existing_albums.len()); - let entries = fs::read_dir(albums_dir)?; - let mut imported_count = 0; + // 第一阶段:快速扫描所有相册文件夹 + let entries: Vec<_> = fs::read_dir(albums_dir)?.collect::, _>>()?; + let mut album_folders = Vec::new(); for entry in entries { - let entry = entry?; let path = entry.path(); - if path.is_dir() { if let Some(folder_name) = path.file_name().and_then(|s| s.to_str()) { // 检查是否已存在同名相册 @@ -44,198 +45,260 @@ pub async fn import_existing_data(config: &Config, db: &Database) -> Result<(), println!("跳过已存在的相册: {}", folder_name); continue; } - - println!("发现新相册: {}", folder_name); - - // 读取index.json文件 - let index_file_path = path.join("index.json"); - let album_title = if index_file_path.exists() { - match fs::read_to_string(&index_file_path) { - Ok(content) => { - match serde_json::from_str::(&content) { - Ok(index) => { - println!(" 从index.json读取相册标题: {}", index.title); - index.title - } - Err(e) => { - println!(" 解析index.json失败: {}, 使用文件夹名作为标题", e); - folder_name.to_string() - } - } - } - Err(e) => { - println!(" 读取index.json失败: {}, 使用文件夹名作为标题", e); - folder_name.to_string() - } - } - } else { - println!(" index.json不存在,使用文件夹名作为标题"); - folder_name.to_string() - }; - - // 创建新相册 - let new_album = CreateAlbum { - title: album_title.clone(), - document: folder_name.to_string(), - description: Some(format!("从文件夹 {} 自动导入的相册", folder_name)), - }; - - let album_id = db.create_album(new_album).await?; - println!(" 创建相册: {} (ID: {})", album_title, album_id); - - // 读取图片URL列表(如果有index.json) - let image_urls = if index_file_path.exists() { - match fs::read_to_string(&index_file_path) { - Ok(content) => { - match serde_json::from_str::(&content) { - Ok(index) => { - println!(" 从index.json读取到 {} 个图片URL", index.images.len()); - Some(index.images) - } - Err(_) => None - } - } - Err(_) => None - } - } else { - None - }; - - // 扫描文件夹中的图片文件 - let image_entries = fs::read_dir(&path)?; - let mut image_files = Vec::new(); - - for image_entry in image_entries { - let image_entry = image_entry?; - let image_path = image_entry.path(); - - if image_path.is_file() { - if let Some(extension) = image_path.extension().and_then(|s| s.to_str()) { - let valid_extensions = ["jpg", "jpeg", "png", "gif", "webp", "bmp"]; - - if valid_extensions.contains(&extension.to_lowercase().as_str()) { - let filename = image_path.file_name() - .and_then(|s| s.to_str()) - .unwrap_or("unknown.jpg") - .to_string(); - - image_files.push((filename, image_path)); - } - } - } - } - - // 按数字顺序排序文件名 - image_files.sort_by(|a, b| { - // 提取文件名中的数字部分进行排序 - let num_a = a.0.chars() - .take_while(|c| c.is_ascii_digit()) - .collect::() - .parse::() - .unwrap_or(0); - - let num_b = b.0.chars() - .take_while(|c| c.is_ascii_digit()) - .collect::() - .parse::() - .unwrap_or(0); - - num_a.cmp(&num_b) - }); - - let mut image_count = 0; - let mut images_to_insert = Vec::new(); - - // 收集所有图片信息 - for (filename, image_path) in image_files { - image_count += 1; - - // 获取对应的URL(如果有的话) - let original_url = if let Some(ref urls) = image_urls { - if urls.len() >= image_count { - Some(urls[image_count - 1].clone()) - } else { - None - } - } else { - None - }; - - // 生成图片标题 - let image_title = if let Some(ref urls) = image_urls { - if urls.len() >= image_count { - Some(format!("图片 {}", image_count)) - } else { - Some(format!("图片 {}", image_count)) - } - } else { - Some(format!("图片 {}", image_count)) - }; - - // 获取图片的实际信息 - let (file_size, width, height) = match get_image_info(&image_path) { - Ok(info) => info, - Err(e) => { - eprintln!("获取图片信息失败: {} - {}", image_path.display(), e); - (0, 0, 0) - } - }; - - let image = CreateImage { - album_id, - filename: format!("{}/{}", folder_name, filename).clone(), - original_url: original_url.clone(), - title: image_title, - description: Some(format!("从文件夹 {} 导入的图片", folder_name)), - file_size, - width, - height, - mime_type: match image_path.extension().and_then(|s| s.to_str()).unwrap_or("jpg").to_lowercase().as_str() { - "jpg" | "jpeg" => "image/jpeg".to_string(), - "png" => "image/png".to_string(), - "gif" => "image/gif".to_string(), - "webp" => "image/webp".to_string(), - "bmp" => "image/bmp".to_string(), - _ => "image/jpeg".to_string(), - }, - }; - - images_to_insert.push(image.clone()); - } - - // 批量插入图片 - if !images_to_insert.is_empty() { - println!(" 批量插入 {} 张图片...", images_to_insert.len()); - match db.add_images(images_to_insert.clone()).await { - Ok(ids) => { - println!(" 批量插入成功,共插入 {} 张图片", ids.len()); - } - Err(e) => { - eprintln!(" 批量插入失败: {}", e); - // 如果批量插入失败,尝试逐条插入 - println!(" 尝试逐条插入图片..."); - let mut success_count = 0; - for image in images_to_insert { - match db.add_image(image).await { - Ok(_) => success_count += 1, - Err(e) => eprintln!(" 单条插入失败: {}", e), - } - } - println!(" 逐条插入完成,成功 {} 张", success_count); - } - } - } - - println!(" 相册 {} 导入完成,共导入 {} 张图片", folder_name, image_count); - imported_count += 1; + album_folders.push((folder_name.to_string(), path)); } } } - println!("导入完成!共导入 {} 个新相册", imported_count); + println!("发现 {} 个新相册需要导入", album_folders.len()); + + if album_folders.is_empty() { + println!("没有新相册需要导入"); + return Ok(()); + } + + // 第二阶段:并行处理相册导入 + let mut tasks = Vec::new(); + + // 限制并发数量,避免内存爆炸 + let max_concurrent = std::thread::available_parallelism()?.get().min(4); + let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent)); + + for (folder_name, path) in album_folders { + let db_clone = Arc::clone(&db); + let semaphore_clone = Arc::clone(&semaphore); + let folder_name_clone = folder_name.clone(); + let path_clone = path.clone(); + + let task = task::spawn(async move { + let _permit = semaphore_clone.acquire().await.unwrap(); + match import_single_album(&db_clone, &folder_name_clone, &path_clone).await { + Ok(count) => { + println!("✅ 相册 {} 导入完成,共导入 {} 张图片", folder_name_clone, count); + count + } + Err(e) => { + eprintln!("❌ 相册 {} 导入失败: {}", folder_name_clone, e); + 0 + } + } + }); + + tasks.push(task); + } + + // 等待所有任务完成 + let mut total_imported = 0; + let mut successful_albums = 0; + + for task in tasks { + match task.await { + Ok(count) => { + if count > 0 { + successful_albums += 1; + total_imported += count; + } + } + Err(e) => { + eprintln!("任务执行失败: {}", e); + } + } + } + + println!("🎉 导入完成!成功导入 {} 个相册,共 {} 张图片", successful_albums, total_imported); Ok(()) } +/// 导入单个相册的辅助函数 +async fn import_single_album(db: &Database, folder_name: &str, path: &Path) -> Result> { + println!("📁 开始导入相册: {}", folder_name); + + // 读取index.json文件 + let index_file_path = path.join("index.json"); + let album_title = if index_file_path.exists() { + match fs::read_to_string(&index_file_path) { + Ok(content) => { + match serde_json::from_str::(&content) { + Ok(index) => { + println!(" 从index.json读取相册标题: {}", index.title); + index.title + } + Err(e) => { + println!(" 解析index.json失败: {}, 使用文件夹名作为标题", e); + folder_name.to_string() + } + } + } + Err(e) => { + println!(" 读取index.json失败: {}, 使用文件夹名作为标题", e); + folder_name.to_string() + } + } + } else { + println!(" index.json不存在,使用文件夹名作为标题"); + folder_name.to_string() + }; + + // 创建新相册 + let new_album = CreateAlbum { + title: album_title.clone(), + document: folder_name.to_string(), + description: Some(format!("从文件夹 {} 自动导入的相册", folder_name)), + }; + + let album_id = db.create_album(new_album).await?; + println!(" 创建相册: {} (ID: {})", album_title, album_id); + + // 读取图片URL列表(如果有index.json) + let image_urls = if index_file_path.exists() { + match fs::read_to_string(&index_file_path) { + Ok(content) => { + match serde_json::from_str::(&content) { + Ok(index) => { + println!(" 从index.json读取到 {} 个图片URL", index.images.len()); + Some(index.images) + } + Err(_) => None + } + } + Err(_) => None + } + } else { + None + }; + + // 快速扫描图片文件 + let image_files = scan_image_files(path, folder_name)?; + + if image_files.is_empty() { + println!(" 相册 {} 中没有找到图片文件", folder_name); + return Ok(0); + } + + println!(" 发现 {} 张图片,开始处理...", image_files.len()); + + // 并行处理图片信息获取 + let mut image_tasks = Vec::new(); + + for (index, (filename, image_path)) in image_files.iter().enumerate() { + let image_url = image_urls.as_ref().and_then(|urls| { + if urls.len() > index { + Some(urls[index].clone()) + } else { + None + } + }); + + let filename_clone = filename.clone(); + let image_path_clone = image_path.clone(); + let album_id_clone = album_id; + let folder_name_clone = folder_name.to_string(); + + let task = task::spawn_blocking(move || { + // 在阻塞线程中处理图片信息 + let (file_size, width, height) = match get_image_info(&image_path_clone) { + Ok(info) => info, + Err(e) => { + eprintln!("获取图片信息失败: {} - {}", image_path_clone.display(), e); + (0, 0, 0) + } + }; + + CreateImage { + album_id: album_id_clone, + filename: format!("{}/{}", folder_name_clone, filename_clone), + original_url: image_url, + title: Some(format!("图片 {}", index + 1)), + description: Some(format!("从文件夹 {} 导入的图片", folder_name_clone)), + file_size, + width, + height, + mime_type: match image_path_clone.extension().and_then(|s| s.to_str()).unwrap_or("jpg").to_lowercase().as_str() { + "jpg" | "jpeg" => "image/jpeg".to_string(), + "png" => "image/png".to_string(), + "gif" => "image/gif".to_string(), + "webp" => "image/webp".to_string(), + "bmp" => "image/bmp".to_string(), + _ => "image/jpeg".to_string(), + }, + } + }); + + image_tasks.push(task); + } + + // 收集所有图片信息 + let mut images_to_insert = Vec::new(); + for task in image_tasks { + match task.await { + Ok(image) => images_to_insert.push(image), + Err(e) => eprintln!("图片处理任务失败: {}", e), + } + } + + // 批量插入图片 + if !images_to_insert.is_empty() { + println!(" 批量插入 {} 张图片...", images_to_insert.len()); + match db.add_images(images_to_insert).await { + Ok(ids) => { + println!(" 批量插入成功,共插入 {} 张图片", ids.len()); + Ok(ids.len()) + } + Err(e) => { + eprintln!(" 批量插入失败: {}", e); + Ok(0) + } + } + } else { + Ok(0) + } +} + +/// 快速扫描图片文件 +fn scan_image_files(path: &Path, _folder_name: &str) -> Result, Box> { + let mut image_files = Vec::new(); + + for entry in fs::read_dir(path)? { + let entry = entry?; + let image_path = entry.path(); + + if image_path.is_file() { + if let Some(extension) = image_path.extension().and_then(|s| s.to_str()) { + let valid_extensions = ["jpg", "jpeg", "png", "gif", "webp", "bmp"]; + + if valid_extensions.contains(&extension.to_lowercase().as_str()) { + let filename = image_path.file_name() + .and_then(|s| s.to_str()) + .unwrap_or("unknown.jpg") + .to_string(); + + image_files.push((filename, image_path)); + } + } + } + } + + // 按数字顺序排序文件名 + image_files.sort_by(|a, b| { + // 提取文件名中的数字部分进行排序 + let num_a = a.0.chars() + .take_while(|c| c.is_ascii_digit()) + .collect::() + .parse::() + .unwrap_or(0); + + let num_b = b.0.chars() + .take_while(|c| c.is_ascii_digit()) + .collect::() + .parse::() + .unwrap_or(0); + + num_a.cmp(&num_b) + }); + + Ok(image_files) +} + /// 获取图片的实际信息(文件大小、宽度、高度) fn get_image_info(image_path: &Path) -> Result<(i64, i32, i32), Box> { // 获取文件大小 diff --git a/src/main.rs b/src/main.rs index c1785b0..b45f180 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,14 @@ mod config; -mod models; mod database; mod image_processor; -mod routes; mod import; +mod models; +mod routes; use actix_files as afs; -use actix_web::{web, App, HttpServer, HttpResponse}; -use std::sync::Arc; +use actix_web::{App, HttpResponse, HttpServer, web}; use std::fs; +use std::sync::Arc; #[actix_web::main] async fn main() -> std::io::Result<()> { @@ -20,10 +20,10 @@ async fn main() -> std::io::Result<()> { std::process::exit(1); } }; - + println!("启动图片展示服务..."); println!("服务地址: http://{}", config.server_address()); - + // 初始化数据库 let db = match database::Database::new(&config).await { Ok(db) => { @@ -35,21 +35,21 @@ async fn main() -> std::io::Result<()> { std::process::exit(1); } }; - + // 在后台线程中自动导入新相册(不阻塞HTTP服务启动) let config_clone = config.clone(); let db_clone = Arc::clone(&db); tokio::spawn(async move { println!("[后台任务] 开始扫描图片目录并导入新相册..."); - match import::import_existing_data(&config_clone, &db_clone).await { + match import::import_existing_data(&config_clone, db_clone).await { Ok(_) => println!("[后台任务] 相册导入完成"), Err(e) => eprintln!("[后台任务] 相册导入失败: {}", e), } }); - + // 初始化图片处理器 let image_processor = Arc::new(image_processor::ImageProcessor::new(config.storage.clone())); - + println!("API接口:"); println!(" - GET /api/albums - 获取所有相册"); println!(" - GET /api/search?q=关键词 - 搜索相册"); @@ -57,16 +57,21 @@ async fn main() -> std::io::Result<()> { println!(" - POST /api/albums - 创建新相册"); println!(" - GET /api/thumbnail/:id - 获取缩略图"); println!(" - GET /api/original/:id - 获取原始图片"); + println!(" - GET /api/favorites - 获取收藏列表"); + println!(" - GET /api/favorites/status/:id - 检查收藏状态"); + println!(" - POST /api/favorites - 添加收藏"); + println!(" - DELETE /api/favorites/:id - 取消收藏"); + println!(" - DELETE /api/favorites/image/:id - 通过图片ID取消收藏"); println!("按 Ctrl+C 停止服务"); - + // 创建数据目录 - std::fs::create_dir_all(&config.storage.images_dir).unwrap_or(()); - std::fs::create_dir_all(&config.storage.thumbnails_dir).unwrap_or(()); - std::fs::create_dir_all("./data").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(); - + HttpServer::new(move || { App::new() .app_data(web::Data::new(Arc::clone(&db))) @@ -77,26 +82,41 @@ async fn main() -> std::io::Result<()> { .route("/api/album/{id}", web::get().to(routes::get_album_detail)) .route("/api/albums", web::post().to(routes::create_album)) .route("/api/thumbnail/{id}", web::get().to(routes::get_thumbnail)) - .route("/api/original/{id}", web::get().to(routes::get_original_image)) + .route( + "/api/original/{id}", + web::get().to(routes::get_original_image), + ) + // 收藏功能API路由 + .route("/api/favorites", web::get().to(routes::get_favorites)) + .route("/api/favorites/status/{id}", web::get().to(routes::check_favorite_status)) + .route("/api/favorites", web::post().to(routes::add_favorite)) + .route("/api/favorites/{id}", web::delete().to(routes::remove_favorite)) + .route("/api/favorites/image/{id}", web::delete().to(routes::remove_favorite_by_image)) // 静态文件服务 .service(afs::Files::new("/assets", "./assets").show_files_listing()) // HTML页面路由 - .route("/", web::get().to(|| async { - match fs::read_to_string("./assets/index.html") { - Ok(content) => HttpResponse::Ok() - .content_type("text/html; charset=utf-8") - .body(content), - Err(_) => HttpResponse::NotFound().body("首页文件不存在") - } - })) - .route("/album", web::get().to(|| async { - match fs::read_to_string("./assets/album.html") { - Ok(content) => HttpResponse::Ok() - .content_type("text/html; charset=utf-8") - .body(content), - Err(_) => HttpResponse::NotFound().body("相册页面文件不存在") - } - })) + .route( + "/", + web::get().to(|| async { + match fs::read_to_string("./assets/index.html") { + Ok(content) => HttpResponse::Ok() + .content_type("text/html; charset=utf-8") + .body(content), + Err(_) => HttpResponse::NotFound().body("首页文件不存在"), + } + }), + ) + .route( + "/album", + web::get().to(|| async { + match fs::read_to_string("./assets/album.html") { + Ok(content) => HttpResponse::Ok() + .content_type("text/html; charset=utf-8") + .body(content), + Err(_) => HttpResponse::NotFound().body("相册页面文件不存在"), + } + }), + ) }) .bind(server_address)? .run() diff --git a/src/models.rs b/src/models.rs index de86b64..fa28d69 100644 --- a/src/models.rs +++ b/src/models.rs @@ -62,4 +62,32 @@ pub struct CreateImage { pub width: i32, pub height: i32, pub mime_type: String, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Favorite { + pub id: Uuid, + pub user_id: String, + pub image_id: Uuid, + pub album_id: Uuid, + pub created_at: String, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct CreateFavorite { + pub image_id: Uuid, + pub album_id: Uuid, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FavoriteWithImage { + pub favorite: Favorite, + pub image: Image, + pub album_title: String, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FavoriteStatus { + pub is_favorited: bool, + pub favorite_id: Option, } \ No newline at end of file diff --git a/src/routes.rs b/src/routes.rs index ba7f502..378d956 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -18,6 +18,133 @@ pub async fn get_albums(db: web::Data>) -> impl Responder { } } +// 收藏功能API路由 + +// 获取用户的收藏列表 +pub async fn get_favorites( + db: web::Data>, +) -> impl Responder { + // 这里使用固定用户ID,实际项目中应该从认证信息中获取 + let user_id = "default_user".to_string(); + + match db.get_user_favorites(&user_id).await { + Ok(favorites) => HttpResponse::Ok().json(favorites), + Err(e) => { + eprintln!("获取收藏列表失败: {}", e); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "获取收藏列表失败" + })) + } + } +} + +// 检查图片是否被收藏 +pub async fn check_favorite_status( + db: web::Data>, + path: web::Path, +) -> impl Responder { + let image_id = match Uuid::parse_str(&path.into_inner()) { + Ok(id) => id, + Err(_) => { + return HttpResponse::BadRequest().json(serde_json::json!({ + "error": "无效的图片ID" + })); + } + }; + + // 这里使用固定用户ID,实际项目中应该从认证信息中获取 + let user_id = "default_user".to_string(); + + match db.get_favorite_status(&user_id, image_id).await { + Ok(status) => HttpResponse::Ok().json(status), + Err(e) => { + eprintln!("检查收藏状态失败: {}", e); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "检查收藏状态失败" + })) + } + } +} + +// 添加收藏 +pub async fn add_favorite( + db: web::Data>, + favorite_data: web::Json, +) -> impl Responder { + // 这里使用固定用户ID,实际项目中应该从认证信息中获取 + let user_id = "default_user".to_string(); + + match db.add_favorite(&user_id, favorite_data.into_inner()).await { + Ok(favorite_id) => HttpResponse::Created().json(serde_json::json!({ + "id": favorite_id, + "message": "收藏成功" + })), + Err(e) => { + eprintln!("添加收藏失败: {}", e); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "添加收藏失败" + })) + } + } +} + +// 取消收藏 +pub async fn remove_favorite( + db: web::Data>, + path: web::Path, +) -> impl Responder { + let favorite_id = match Uuid::parse_str(&path.into_inner()) { + Ok(id) => id, + Err(_) => { + return HttpResponse::BadRequest().json(serde_json::json!({ + "error": "无效的收藏ID" + })); + } + }; + + match db.remove_favorite(favorite_id).await { + Ok(_) => HttpResponse::Ok().json(serde_json::json!({ + "message": "取消收藏成功" + })), + Err(e) => { + eprintln!("取消收藏失败: {}", e); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "取消收藏失败" + })) + } + } +} + +// 通过图片ID取消收藏 +pub async fn remove_favorite_by_image( + db: web::Data>, + path: web::Path, +) -> impl Responder { + let image_id = match Uuid::parse_str(&path.into_inner()) { + Ok(id) => id, + Err(_) => { + return HttpResponse::BadRequest().json(serde_json::json!({ + "error": "无效的图片ID" + })); + } + }; + + // 这里使用固定用户ID,实际项目中应该从认证信息中获取 + let user_id = "default_user".to_string(); + + match db.remove_favorite_by_image(&user_id, image_id).await { + Ok(_) => HttpResponse::Ok().json(serde_json::json!({ + "message": "取消收藏成功" + })), + Err(e) => { + eprintln!("取消收藏失败: {}", e); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "取消收藏失败" + })) + } + } +} + pub async fn get_original_image( db: web::Data>, image_processor: web::Data>, @@ -263,4 +390,4 @@ pub async fn get_thumbnail( })) } } -} +} \ No newline at end of file