重构批量下载逻辑,优化历史显示和下载管理

This commit is contained in:
2025-08-25 09:10:00 +08:00
parent 29ef34b5a9
commit 4033e4eed2
10 changed files with 1240 additions and 254 deletions
+367 -175
View File
@@ -4,13 +4,25 @@
<div class="page-header">
<h1>下载管理</h1>
<div class="header-actions">
<button @click="refreshData" class="btn btn-secondary" :disabled="loading">
<svg viewBox="0 0 24 24" fill="currentColor" class="w-4 h-4">
<button @click="refreshData" class="btn btn-primary" :disabled="loading">
<svg viewBox="0 0 24 24" fill="currentColor" class="btn-icon">
<path
d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
</svg>
刷新
</button>
<button @click="cleanupTasks" class="btn btn-secondary" :disabled="loading">
<svg viewBox="0 0 24 24" fill="currentColor" class="btn-icon">
<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />
</svg>
清理任务
</button>
<button @click="cleanupHistory" class="btn btn-secondary" :disabled="loading">
<svg viewBox="0 0 24 24" fill="currentColor" class="btn-icon">
<path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z" />
</svg>
清理历史
</button>
</div>
</div>
@@ -26,9 +38,6 @@
<button @click="activeTab = 'history'" class="tab-btn" :class="{ active: activeTab === 'history' }">
下载历史
</button>
<button @click="activeTab = 'files'" class="tab-btn" :class="{ active: activeTab === 'files' }">
文件管理
</button>
</div>
<!-- 下载任务 -->
@@ -37,7 +46,7 @@
<LoadingSpinner text="加载中..." />
</div>
<div v-else-if="tasks.length === 0" class="empty-section">
<div v-else-if="activeTasks.length === 0" class="empty-section">
<div class="empty-content">
<svg viewBox="0 0 24 24" fill="currentColor" class="empty-icon">
<path
@@ -49,7 +58,7 @@
</div>
<div v-else class="tasks-list">
<div v-for="task in tasks" :key="task.id" class="task-card">
<div v-for="task in activeTasks" :key="task.id" class="task-card">
<div class="task-header">
<div class="task-info">
<h3 class="task-title">
@@ -75,6 +84,36 @@
</div>
</div>
<!-- 批量下载的详细进度 -->
<div v-if="task.type === 'batch' || task.type === 'artist'" class="batch-progress">
<div class="batch-stats">
<div class="stat-item">
<span class="stat-label">已完成:</span>
<span class="stat-value success">{{ task.completed_files }}</span>
</div>
<div class="stat-item">
<span class="stat-label">失败:</span>
<span class="stat-value error">{{ task.failed_files }}</span>
</div>
<div class="stat-item">
<span class="stat-label">剩余:</span>
<span class="stat-value">{{ task.total_files - task.completed_files - task.failed_files }}</span>
</div>
</div>
<!-- 最近完成的作品列表 -->
<div v-if="task.recent_completed && task.recent_completed.length > 0" class="recent-completed">
<h4>最近完成:</h4>
<div class="completed-list">
<div v-for="item in task.recent_completed.slice(0, 5)" :key="item.artwork_id" class="completed-item">
<span class="artwork-id">#{{ item.artwork_id }}</span>
<span v-if="item.artwork_title" class="artwork-title">{{ item.artwork_title }}</span>
<span v-if="item.artist_name" class="artist-name">by {{ item.artist_name }}</span>
</div>
</div>
</div>
</div>
<div class="task-details">
<div class="detail-item">
<span class="label">类型:</span>
@@ -125,11 +164,6 @@
{{ getStatusText(item.status) }}
</span>
</div>
<div class="history-actions">
<button @click="openFolder(item.download_path)" class="btn btn-text btn-sm">
打开文件夹
</button>
</div>
</div>
<div class="history-details">
@@ -141,10 +175,6 @@
<span class="label">文件数:</span>
<span class="value">{{ item.completed_files }}/{{ item.total_files }}</span>
</div>
<div class="detail-item">
<span class="label">下载路径:</span>
<span class="value path">{{ item.download_path }}</span>
</div>
<div class="detail-item">
<span class="label">完成时间:</span>
<span class="value">{{ formatDate(item.end_time) }}</span>
@@ -153,90 +183,43 @@
</div>
</div>
</div>
<!-- 文件管理 -->
<div v-if="activeTab === 'files'" class="tab-content">
<div v-if="loading" class="loading-section">
<LoadingSpinner text="加载中..." />
</div>
<div v-else-if="files.length === 0" class="empty-section">
<div class="empty-content">
<svg viewBox="0 0 24 24" fill="currentColor" class="empty-icon">
<path
d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z" />
</svg>
<h3>暂无下载文件</h3>
<p>下载完成后文件将显示在这里</p>
</div>
</div>
<div v-else class="files-list">
<div v-for="file in files" :key="`${file.artist}_${file.artwork}`" class="file-card">
<div class="file-header">
<div class="file-info">
<h3 class="file-title">{{ file.artwork }}</h3>
<p class="file-artist">{{ file.artist }}</p>
</div>
<div class="file-actions">
<button @click="openFolder(file.path)" class="btn btn-text btn-sm">
打开
</button>
<button @click="deleteFile(file.artist, file.artwork)" class="btn btn-danger btn-sm">
删除
</button>
</div>
</div>
<div class="file-details">
<div class="detail-item">
<span class="label">文件数:</span>
<span class="value">{{ file.files.length }}</span>
</div>
<div class="detail-item">
<span class="label">大小:</span>
<span class="value">{{ formatFileSize(file.total_size) }}</span>
</div>
<div class="detail-item">
<span class="label">创建时间:</span>
<span class="value">{{ formatDate(file.created_at) }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
import downloadService from '@/services/download';
import type { DownloadTask } from '@/types';
const authStore = useAuthStore();
// 状态
const activeTab = ref<'tasks' | 'history' | 'files'>('tasks');
const activeTab = ref<'tasks' | 'history'>('tasks');
const loading = ref(false);
const error = ref<string | null>(null);
const tasks = ref<DownloadTask[]>([]);
const history = ref<any[]>([]);
const files = ref<any[]>([]);
// 定时器
let progressTimer: number | null = null;
// SSE连接管理
const sseConnections = ref<Map<string, () => void>>(new Map());
// 计算属性:只显示活跃任务
const activeTasks = computed(() => {
return tasks.value.filter(task =>
['downloading', 'paused'].includes(task.status)
);
});
// 获取任务标题
const getTaskTitle = (task: DownloadTask) => {
if (task.type === 'artwork') {
return `作品 ${task.artwork_id}`;
return task.artwork_title || `作品 ${task.artwork_id}`;
} else if (task.type === 'artist') {
return `作者作品`;
return `作者作品 - ${task.artist_name || '未知作者'}`;
} else if (task.type === 'batch') {
return `批量下载 ${task.total_files} 个作品`;
return `批量下载 (${task.total_files} 个作品)`;
}
return '未知任务';
};
@@ -248,7 +231,8 @@ const getStatusText = (status: string) => {
'completed': '已完成',
'failed': '失败',
'cancelled': '已取消',
'partial': '部分完成'
'partial': '部分完成',
'paused': '已暂停'
};
return statusMap[status] || status;
};
@@ -258,7 +242,8 @@ const getTypeText = (type: string) => {
const typeMap: Record<string, string> = {
'artwork': '单个作品',
'artist': '作者作品',
'batch': '批量下载'
'batch': '批量下载',
'ranking': '排行榜下载'
};
return typeMap[type] || type;
};
@@ -274,30 +259,35 @@ const getHistoryTitle = (item: any) => {
return `作者作品 (${artist})`;
} else if (item.type === 'batch') {
return `批量下载 (${item.total_files || 0} 个作品)`;
} else if (item.type === 'ranking') {
return `排行榜下载 (${item.total_files || 0} 个作品)`;
}
return '未知下载任务';
};
// 格式化日期
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString('zh-CN');
};
if (!dateString) return '未知时间';
// 格式化文件大小
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
try {
// 处理不同的日期格式
const date = new Date(dateString);
if (isNaN(date.getTime())) {
console.warn('无效的日期格式:', dateString);
return '时间格式错误';
}
return date.toLocaleString('zh-CN');
} catch (error) {
console.error('日期格式化错误:', error);
return '时间解析失败';
}
};
// 刷新数据
const refreshData = async () => {
await Promise.all([
fetchTasks(),
fetchHistory(),
fetchFiles()
fetchHistory()
]);
};
@@ -307,6 +297,13 @@ const fetchTasks = async () => {
const response = await downloadService.getAllTasks();
if (response.success) {
tasks.value = response.data || [];
// 为活跃任务建立SSE连接
activeTasks.value.forEach(task => {
if (!sseConnections.value.has(task.id)) {
startTaskStreaming(task.id);
}
});
} else {
throw new Error(response.error || '获取任务列表失败');
}
@@ -315,12 +312,14 @@ const fetchTasks = async () => {
}
};
// 获取历史记录
// 获取历史记录(只获取最近200条)
const fetchHistory = async () => {
try {
const response = await downloadService.getDownloadHistory();
if (response.success) {
history.value = response.data || [];
const response = await downloadService.getDownloadHistory(0, 200);
if (response.success && response.data) {
// 后端返回的结构是 { history: [], total: number, offset: number, limit: number }
history.value = response.data.history || [];
console.log('历史记录获取成功:', history.value.length, '条记录');
} else {
throw new Error(response.error || '获取历史记录失败');
}
@@ -329,17 +328,57 @@ const fetchHistory = async () => {
}
};
// 获取文件列表
const fetchFiles = async () => {
try {
const response = await downloadService.getDownloadedFiles();
if (response.success) {
files.value = response.data || [];
} else {
throw new Error(response.error || '获取文件列表失败');
// 开始SSE监听任务进度
const startTaskStreaming = (taskId: string) => {
// 如果已经有连接,先关闭
if (sseConnections.value.has(taskId)) {
sseConnections.value.get(taskId)!();
}
console.log('开始SSE监听任务进度:', taskId);
const closeConnection = downloadService.streamTaskProgress(
taskId,
(task) => {
console.log('收到SSE进度更新:', {
taskId,
status: task.status,
progress: task.progress,
completed: task.completed_files,
total: task.total_files
});
// 更新任务状态
const index = tasks.value.findIndex(t => t.id === taskId);
if (index !== -1) {
tasks.value[index] = task;
}
// 如果任务完成,清理连接
if (['completed', 'failed', 'cancelled', 'partial'].includes(task.status)) {
console.log('任务完成,关闭SSE连接:', taskId);
stopTaskStreaming(taskId);
// 延迟刷新历史记录
setTimeout(() => {
fetchHistory();
}, 1000);
}
},
() => {
console.log('SSE连接完成:', taskId);
stopTaskStreaming(taskId);
}
} catch (err) {
console.error('获取文件列表失败:', err);
);
sseConnections.value.set(taskId, closeConnection);
};
// 停止SSE监听
const stopTaskStreaming = (taskId: string) => {
if (sseConnections.value.has(taskId)) {
sseConnections.value.get(taskId)!();
sseConnections.value.delete(taskId);
}
};
@@ -358,30 +397,46 @@ const cancelTask = async (taskId: string) => {
}
};
// 删除文件
const deleteFile = async (artist: string, artwork: string) => {
if (!confirm(`确定要删除 "${artist}/${artwork}" 的所有文件吗?`)) {
return;
}
try {
const response = await downloadService.deleteDownloadedFiles(artist, artwork);
if (response.success) {
await fetchFiles();
} else {
throw new Error(response.error || '删除文件失败');
// 清理历史记录
const cleanupHistory = async () => {
if (confirm('确定要清理下载历史吗?这将保留最新的500条记录。')) {
try {
loading.value = true;
const response = await downloadService.cleanupHistory(500);
if (response.success) {
await fetchHistory(); // 重新获取历史记录
alert('下载历史已清理!');
} else {
throw new Error(response.error || '清理历史失败');
}
} catch (err) {
error.value = err instanceof Error ? err.message : '清理历史失败';
console.error('清理历史失败:', err);
} finally {
loading.value = false;
}
} catch (err) {
error.value = err instanceof Error ? err.message : '删除文件失败';
console.error('删除文件失败:', err);
}
};
// 打开文件夹
const openFolder = (path: string) => {
// 这里可以调用系统API打开文件夹
console.log('打开文件夹:', path);
// 在实际应用中,可以通过electron或其他方式打开文件夹
// 清理任务
const cleanupTasks = async () => {
if (confirm('确定要清理已完成的任务吗?这将保留活跃任务和最新的100个已完成任务。')) {
try {
loading.value = true;
const response = await downloadService.cleanupTasks(true, 100);
if (response.success) {
await fetchTasks(); // 重新获取任务列表
alert('下载任务已清理!');
} else {
throw new Error(response.error || '清理任务失败');
}
} catch (err) {
error.value = err instanceof Error ? err.message : '清理任务失败';
console.error('清理任务失败:', err);
} finally {
loading.value = false;
}
}
};
// 清除错误
@@ -389,29 +444,18 @@ const clearError = () => {
error.value = null;
};
// 开始进度轮询
const startProgressPolling = () => {
progressTimer = setInterval(async () => {
const hasActiveTasks = tasks.value.some(task => task.status === 'downloading');
if (hasActiveTasks) {
await fetchTasks();
}
}, 2000);
};
// 停止进度轮询
const stopProgressPolling = () => {
if (progressTimer) {
clearInterval(progressTimer);
progressTimer = null;
}
// 清理所有SSE连接
const cleanupSSEConnections = () => {
sseConnections.value.forEach(closeConnection => {
closeConnection();
});
sseConnections.value.clear();
};
onMounted(async () => {
loading.value = true;
try {
await refreshData();
startProgressPolling();
} catch (err) {
error.value = err instanceof Error ? err.message : '加载数据失败';
} finally {
@@ -420,7 +464,7 @@ onMounted(async () => {
});
onUnmounted(() => {
stopProgressPolling();
cleanupSSEConnections();
});
</script>
@@ -451,6 +495,66 @@ onUnmounted(() => {
margin: 0;
}
.header-actions {
display: flex;
gap: 0.75rem;
align-items: center;
}
.btn {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1.25rem;
border: none;
border-radius: 0.5rem;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
text-decoration: none;
white-space: nowrap;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
pointer-events: none;
}
.btn-icon {
width: 1.25rem;
height: 1.25rem;
flex-shrink: 0;
}
.btn-primary {
background: #3b82f6;
color: white;
border: 1px solid #3b82f6;
}
.btn-primary:hover:not(:disabled) {
background: #2563eb;
border-color: #2563eb;
transform: translateY(-1px);
box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.3);
}
.btn-secondary {
background: white;
color: #374151;
border: 1px solid #d1d5db;
}
.btn-secondary:hover:not(:disabled) {
background: #f9fafb;
border-color: #9ca3af;
transform: translateY(-1px);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.tabs {
display: flex;
gap: 0.5rem;
@@ -521,14 +625,12 @@ onUnmounted(() => {
}
.tasks-list,
.history-list,
.files-list {
.history-list {
padding: 1.5rem;
}
.task-card,
.history-card,
.file-card {
.history-card {
border: 1px solid #e5e7eb;
border-radius: 0.75rem;
padding: 1.5rem;
@@ -539,15 +641,13 @@ onUnmounted(() => {
}
.task-card:hover,
.history-card:hover,
.file-card:hover {
.history-card:hover {
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
border-color: #d1d5db;
}
.task-header,
.history-header,
.file-header {
.history-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
@@ -555,8 +655,7 @@ onUnmounted(() => {
}
.task-title,
.history-title,
.file-title {
.history-title {
font-size: 1.125rem;
font-weight: 600;
color: #1f2937;
@@ -603,6 +702,11 @@ onUnmounted(() => {
color: #d97706;
}
.task-status.paused {
background: #fef3c7;
color: #d97706;
}
.task-progress {
margin-bottom: 1rem;
}
@@ -628,9 +732,83 @@ onUnmounted(() => {
text-align: center;
}
/* 批量下载进度样式 */
.batch-progress {
margin-bottom: 1rem;
padding: 1rem;
background: #f8fafc;
border-radius: 0.5rem;
border: 1px solid #e2e8f0;
}
.batch-stats {
display: flex;
gap: 2rem;
margin-bottom: 1rem;
}
.stat-item {
display: flex;
align-items: center;
gap: 0.5rem;
}
.stat-label {
font-size: 0.875rem;
color: #6b7280;
font-weight: 500;
}
.stat-value {
font-size: 0.875rem;
font-weight: 600;
}
.stat-value.success {
color: #059669;
}
.stat-value.error {
color: #dc2626;
}
.recent-completed h4 {
font-size: 0.875rem;
font-weight: 600;
color: #374151;
margin: 0 0 0.5rem 0;
}
.completed-list {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.completed-item {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.75rem;
color: #6b7280;
}
.artwork-id {
font-weight: 600;
color: #3b82f6;
}
.artwork-title {
color: #374151;
font-weight: 500;
}
.artist-name {
color: #6b7280;
}
.task-details,
.history-details,
.file-details {
.history-details {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 0.5rem;
@@ -658,20 +836,8 @@ onUnmounted(() => {
color: #dc2626;
}
.detail-item .value.path {
font-family: monospace;
font-size: 0.75rem;
word-break: break-all;
}
.file-artist {
font-size: 0.875rem;
color: #6b7280;
margin: 0;
}
.btn-sm {
padding: 0.25rem 0.5rem;
padding: 0.5rem 0.75rem;
font-size: 0.75rem;
}
@@ -681,18 +847,44 @@ onUnmounted(() => {
border: 1px solid #dc2626;
}
.btn-danger:hover {
.btn-danger:hover:not(:disabled) {
background: #b91c1c;
border-color: #b91c1c;
transform: translateY(-1px);
box-shadow: 0 4px 6px -1px rgba(220, 38, 38, 0.3);
}
.btn-text {
background: none;
color: #3b82f6;
border: none;
}
@media (max-width: 768px) {
.container {
padding: 0 1rem;
}
.btn-text:hover {
background: #f3f4f6;
.page-header {
flex-direction: column;
gap: 1rem;
align-items: flex-start;
}
.header-actions {
width: 100%;
justify-content: flex-start;
flex-wrap: wrap;
gap: 0.5rem;
}
.btn {
padding: 0.625rem 1rem;
font-size: 0.8125rem;
}
.batch-stats {
flex-direction: column;
gap: 0.5rem;
}
.task-details,
.history-details {
grid-template-columns: 1fr;
}
}
</style>