更新下载进度,修复不能重新下载的问题

This commit is contained in:
2025-08-23 12:03:40 +08:00
parent 8d4e479ee1
commit b0179139cc
18 changed files with 1986 additions and 633 deletions
BIN
View File
Binary file not shown.
@@ -0,0 +1,416 @@
<template>
<div class="download-progress" v-if="task">
<div class="progress-header">
<h4 class="progress-title">{{ task.artwork_title || '下载中...' }}</h4>
<div class="progress-actions">
<button
v-if="task.status === 'downloading'"
@click="pauseTask"
class="btn btn-sm btn-secondary"
:disabled="loading"
>
暂停
</button>
<button
v-if="task.status === 'paused'"
@click="resumeTask"
class="btn btn-sm btn-primary"
:disabled="loading"
>
恢复
</button>
<button
@click="cancelTask"
class="btn btn-sm btn-danger"
:disabled="loading"
>
取消
</button>
</div>
</div>
<div class="progress-overview">
<div class="progress-bar">
<div
class="progress-fill"
:style="{ width: `${task.progress}%` }"
:class="progressClass"
></div>
</div>
<div class="progress-text">
{{ task.progress }}% ({{ task.completed_files }}/{{ task.total_files }})
</div>
</div>
<div class="task-status">
<span class="status-badge" :class="statusClass">
{{ getStatusText(task.status) }}
</span>
<span class="task-time">{{ formatTime(task.start_time) }}</span>
</div>
<!-- 错误信息 -->
<div v-if="task.error" class="task-error">
<span class="error-icon"></span>
{{ task.error }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import downloadService from '@/services/download';
import type { DownloadTask } from '@/types';
interface Props {
task: DownloadTask;
loading?: boolean;
}
const props = defineProps<Props>();
const emit = defineEmits<{
update: [task: DownloadTask];
remove: [taskId: string];
}>();
// 计算属性
const progressClass = computed(() => {
if (props.task.status === 'completed') return 'completed';
if (props.task.status === 'failed') return 'failed';
if (props.task.status === 'paused') return 'paused';
return 'downloading';
});
const statusClass = computed(() => {
return `status-${props.task.status}`;
});
// 方法
const getStatusText = (status: string) => {
const statusMap: Record<string, string> = {
downloading: '下载中',
completed: '已完成',
failed: '失败',
partial: '部分完成',
cancelled: '已取消',
paused: '已暂停'
};
return statusMap[status] || status;
};
const formatTime = (timeString: string) => {
const date = new Date(timeString);
return date.toLocaleString('zh-CN');
};
const pauseTask = async () => {
try {
const response = await downloadService.pauseTask(props.task.id);
if (response.success) {
emit('update', { ...props.task, status: 'paused' });
}
} catch (error) {
console.error('暂停任务失败:', error);
}
};
const resumeTask = async () => {
try {
const response = await downloadService.resumeTask(props.task.id);
if (response.success) {
emit('update', { ...props.task, status: 'downloading' });
}
} catch (error) {
console.error('恢复任务失败:', error);
}
};
const cancelTask = async () => {
try {
const response = await downloadService.cancelTask(props.task.id);
if (response.success) {
emit('remove', props.task.id);
}
} catch (error) {
console.error('取消任务失败:', error);
}
};
</script>
<style scoped>
.download-progress {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 0.75rem;
padding: 1.25rem;
margin-bottom: 0;
}
.progress-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.75rem;
}
.progress-title {
font-size: 1.125rem;
font-weight: 600;
color: #1f2937;
margin: 0;
}
.progress-actions {
display: flex;
gap: 0.5rem;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
font-weight: 500;
text-decoration: none;
transition: all 0.2s;
border: none;
cursor: pointer;
font-size: 0.875rem;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-sm {
padding: 0.375rem 0.75rem;
font-size: 0.75rem;
min-width: 60px;
}
.btn-primary {
background: #3b82f6;
color: white;
}
.btn-primary:hover:not(:disabled) {
background: #2563eb;
}
.btn-secondary {
background: #f3f4f6;
color: #374151;
border: 1px solid #d1d5db;
}
.btn-secondary:hover:not(:disabled) {
background: #e5e7eb;
}
.btn-danger {
background: #ef4444;
color: white;
}
.btn-danger:hover:not(:disabled) {
background: #dc2626;
}
.progress-overview {
margin-bottom: 0.75rem;
}
.progress-bar {
width: 100%;
height: 0.375rem;
background: #e5e7eb;
border-radius: 0.25rem;
overflow: hidden;
margin-bottom: 0.5rem;
}
.progress-fill {
height: 100%;
transition: width 0.3s ease;
}
.progress-fill.downloading {
background: #3b82f6;
}
.progress-fill.completed {
background: #10b981;
}
.progress-fill.failed {
background: #ef4444;
}
.progress-fill.paused {
background: #f59e0b;
}
.progress-text {
font-size: 0.875rem;
color: #6b7280;
text-align: center;
}
.task-status {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.75rem;
}
.status-badge {
padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.75rem;
font-weight: 500;
}
.status-downloading {
background: #dbeafe;
color: #1d4ed8;
}
.status-completed {
background: #d1fae5;
color: #065f46;
}
.status-failed {
background: #fee2e2;
color: #dc2626;
}
.status-partial {
background: #fef3c7;
color: #d97706;
}
.status-cancelled {
background: #f3f4f6;
color: #6b7280;
}
.status-paused {
background: #fef3c7;
color: #d97706;
}
.task-time {
font-size: 0.75rem;
color: #9ca3af;
}
.files-progress {
border-top: 1px solid #e5e7eb;
padding-top: 1rem;
}
.file-item {
margin-bottom: 0.75rem;
}
.file-info {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.25rem;
}
.file-name {
font-size: 0.875rem;
color: #374151;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-right: 0.5rem;
}
.file-status {
font-size: 0.75rem;
font-weight: 500;
padding: 0.125rem 0.5rem;
border-radius: 0.25rem;
}
.file-status-pending {
background: #f3f4f6;
color: #6b7280;
}
.file-status-downloading {
background: #dbeafe;
color: #1d4ed8;
}
.file-status-completed {
background: #d1fae5;
color: #065f46;
}
.file-status-failed {
background: #fee2e2;
color: #dc2626;
}
.file-progress {
display: flex;
align-items: center;
gap: 0.5rem;
}
.file-progress-bar {
flex: 1;
height: 0.25rem;
background: #f3f4f6;
border-radius: 0.125rem;
overflow: hidden;
}
.file-progress-fill {
height: 100%;
background: #3b82f6;
transition: width 0.3s ease;
}
.file-progress-text {
font-size: 0.75rem;
color: #6b7280;
min-width: 2.5rem;
text-align: right;
}
.file-error {
font-size: 0.75rem;
color: #dc2626;
margin-top: 0.25rem;
}
.task-error {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem;
background: #fef2f2;
border: 1px solid #fecaca;
border-radius: 0.5rem;
color: #dc2626;
font-size: 0.875rem;
}
.error-icon {
font-size: 1rem;
}
</style>
+1 -1
View File
@@ -10,7 +10,7 @@ class ApiService {
constructor() {
this.client = axios.create({
baseURL: API_BASE_URL,
timeout: 30000,
timeout: 60000, // 增加到60秒
headers: {
'Content-Type': 'application/json',
},
+92 -45
View File
@@ -9,10 +9,60 @@ class DownloadService {
size?: string;
quality?: string;
format?: string;
skipExisting?: boolean;
} = {}) {
return apiService.post(`/api/download/artwork/${artworkId}`, options);
}
/**
* 获取任务进度
*/
async getTaskProgress(taskId: string) {
return apiService.get(`/api/download/progress/${taskId}`);
}
/**
* 获取所有任务
*/
async getAllTasks() {
return apiService.get('/api/download/tasks');
}
/**
* 暂停任务
*/
async pauseTask(taskId: string) {
return apiService.post(`/api/download/pause/${taskId}`);
}
/**
* 恢复任务
*/
async resumeTask(taskId: string) {
return apiService.post(`/api/download/resume/${taskId}`);
}
/**
* 取消任务
*/
async cancelTask(taskId: string) {
return apiService.delete(`/api/download/cancel/${taskId}`);
}
/**
* 获取下载历史
*/
async getDownloadHistory(offset = 0, limit = 50) {
return apiService.get('/api/download/history', { params: { offset, limit } });
}
/**
* 检查作品是否已下载
*/
async checkArtworkDownloaded(artworkId: number) {
return apiService.get(`/api/download/check/${artworkId}`);
}
/**
* 批量下载作品
*/
@@ -42,56 +92,12 @@ class DownloadService {
}
/**
* 获取任务进度
*/
async getTaskProgress(taskId: string) {
return apiService.get(`/api/download/progress/${taskId}`);
}
/**
* 获取所有任务
*/
async getAllTasks() {
return apiService.get('/api/download/tasks');
}
/**
* 取消下载任务
*/
async cancelTask(taskId: string) {
return apiService.post(`/api/download/cancel/${taskId}`);
}
/**
* 获取下载历史
*/
async getDownloadHistory(limit: number = 50, offset: number = 0) {
return apiService.get('/api/download/history', {
params: { limit, offset }
});
}
/**
* 获取下载的文件列表
* 获取已下载的文件列表
*/
async getDownloadedFiles() {
return apiService.get('/api/download/files');
}
/**
* 检查作品是否已下载
*/
async checkArtworkDownloaded(artworkId: number) {
return apiService.get(`/api/download/check/${artworkId}`);
}
/**
* 获取已下载的作品ID列表
*/
async getDownloadedArtworkIds() {
return apiService.get('/api/download/downloaded-ids');
}
/**
* 删除下载的文件
*/
@@ -100,6 +106,47 @@ class DownloadService {
data: { artist, artwork }
});
}
/**
* 获取已下载的作品ID列表
*/
async getDownloadedArtworkIds() {
return apiService.get('/api/download/downloaded-ids');
}
/**
* 使用SSE监听下载进度
*/
streamTaskProgress(taskId: string, onProgress: (task: DownloadTask) => void, onComplete?: () => void) {
const eventSource = new EventSource(`http://localhost:3000/api/download/stream/${taskId}`);
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'progress') {
onProgress(data.data);
} else if (data.type === 'complete') {
onProgress(data.data);
if (onComplete) {
onComplete();
}
eventSource.close();
}
} catch (error) {
console.error('解析SSE数据失败:', error);
}
};
eventSource.onerror = (error) => {
console.error('SSE连接错误:', error);
eventSource.close();
};
// 返回关闭函数
return () => {
eventSource.close();
};
}
}
export default new DownloadService();
+7 -12
View File
@@ -98,22 +98,17 @@ export interface LoginStatus {
export interface DownloadTask {
id: string;
type: 'artwork' | 'batch' | 'artist';
status: 'downloading' | 'completed' | 'failed' | 'partial' | 'cancelled';
status: 'downloading' | 'completed' | 'failed' | 'partial' | 'cancelled' | 'paused';
progress: number;
total: number;
completed: number;
failed: number;
total_files: number;
completed_files: number;
failed_files: number;
artwork_id?: number;
artist_name?: string;
artwork_title?: string;
start_time: string;
end_time?: string;
error?: string;
artwork_id?: number;
artist_id?: number;
files?: Array<{
path: string;
url: string;
size: string;
filename: string;
}>;
results?: any[];
}
+135 -14
View File
@@ -55,8 +55,12 @@
{{ artwork.is_bookmarked ? '取消收藏' : '收藏' }}
</button>
</div>
</div>
<!-- 下载状态和进度区域 -->
<div class="download-section">
<!-- 下载状态提示 -->
<div v-if="isDownloaded" class="download-status">
<div v-if="isDownloaded && !currentTask" class="download-status">
<div class="status-indicator">
<svg viewBox="0 0 24 24" fill="currentColor" class="status-icon">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
@@ -64,6 +68,15 @@
<span>已下载到本地</span>
</div>
</div>
<!-- 下载进度 -->
<DownloadProgress
v-if="currentTask"
:task="currentTask"
:loading="downloading"
@update="updateTask"
@remove="removeTask"
/>
</div>
<!-- 作者信息 -->
@@ -182,9 +195,10 @@ import artworkService from '@/services/artwork';
import artistService from '@/services/artist';
import downloadService from '@/services/download';
import { useRepositoryStore } from '@/stores/repository';
import type { Artwork } from '@/types';
import type { Artwork, DownloadTask } from '@/types';
import LoadingSpinner from '@/components/common/LoadingSpinner.vue';
import ErrorMessage from '@/components/common/ErrorMessage.vue';
import DownloadProgress from '@/components/download/DownloadProgress.vue';
const route = useRoute();
const router = useRouter();
@@ -202,6 +216,10 @@ const downloading = ref(false);
const isDownloaded = ref(false);
const checkingDownloadStatus = ref(false);
// 下载任务状态
const currentTask = ref<DownloadTask | null>(null);
const sseConnection = ref<(() => void) | null>(null);
// 导航相关状态
const artistArtworks = ref<Artwork[]>([]);
const currentArtworkIndex = ref(-1);
@@ -255,6 +273,10 @@ const fetchArtworkDetail = async () => {
imageError.value = false;
currentPage.value = 0;
// 清理之前的任务状态
currentTask.value = null;
stopTaskStreaming();
const response = await artworkService.getArtworkDetail(artworkId);
if (response.success && response.data) {
@@ -299,15 +321,40 @@ const handleDownload = async () => {
try {
downloading.value = true;
const response = await downloadService.downloadArtwork(artwork.value.id);
// 如果已经下载过,则强制重新下载(跳过现有文件检查)
const skipExisting = !isDownloaded.value;
const response = await downloadService.downloadArtwork(artwork.value.id, {
skipExisting
});
if (response.success) {
// 可以显示下载成功提示
console.log('下载任务已创建:', response.data);
// 下载完成后重新检查下载状态
setTimeout(() => {
checkDownloadStatus(artwork.value!.id);
}, 2000); // 等待2秒让下载完成
console.log('下载响应:', response.data);
// 检查是否跳过下载
if (response.data.skipped) {
console.log('作品已存在,跳过下载');
// 重新检查下载状态
await checkDownloadStatus(artwork.value.id);
return;
}
// 如果是新任务,开始监听进度
if (response.data.task_id) {
currentTask.value = {
id: response.data.task_id,
type: 'artwork',
status: 'downloading',
progress: 0,
total_files: 0,
completed_files: 0,
failed_files: 0,
artwork_id: artwork.value.id,
start_time: new Date().toISOString()
};
// 开始SSE监听任务进度
startTaskStreaming(response.data.task_id);
}
} else {
throw new Error(response.error || '下载失败');
}
@@ -319,6 +366,72 @@ const handleDownload = async () => {
}
};
// 开始SSE监听任务进度
const startTaskStreaming = (taskId: string) => {
// 清除之前的连接
if (sseConnection.value) {
sseConnection.value();
}
console.log('开始SSE监听任务进度:', taskId);
// 建立SSE连接
sseConnection.value = downloadService.streamTaskProgress(
taskId,
(task) => {
console.log('收到SSE进度更新:', {
taskId,
status: task.status,
progress: task.progress,
completed: task.completed_files,
total: task.total_files
});
currentTask.value = task;
// 如果任务完成,清理连接并检查下载状态
if (['completed', 'failed', 'cancelled', 'partial'].includes(task.status)) {
console.log('任务完成,关闭SSE连接');
stopTaskStreaming();
// 延迟检查下载状态,确保文件写入完成
setTimeout(async () => {
await checkDownloadStatus(artwork.value!.id);
// 清理任务状态,显示下载完成状态
currentTask.value = null;
}, 1000);
}
},
() => {
console.log('SSE连接完成');
stopTaskStreaming();
}
);
};
// 停止SSE监听
const stopTaskStreaming = () => {
if (sseConnection.value) {
sseConnection.value();
sseConnection.value = null;
}
};
// 更新任务状态
const updateTask = (task: DownloadTask) => {
currentTask.value = task;
};
// 移除任务
const removeTask = (taskId: string) => {
if (currentTask.value?.id === taskId) {
currentTask.value = null;
stopTaskStreaming();
}
};
// 收藏/取消收藏
const handleBookmark = () => {
// 这里可以添加收藏功能
@@ -423,6 +536,10 @@ const goBackToArtist = () => {
// 监听路由变化,重新获取作品详情和导航数据
watch(() => route.params.id, () => {
// 清理之前的任务状态
currentTask.value = null;
stopTaskStreaming();
// 重新获取作品详情
fetchArtworkDetail();
@@ -458,9 +575,10 @@ onMounted(() => {
document.addEventListener('keydown', handleKeydown);
});
// 组件卸载时移除事件监听
// 组件卸载时移除事件监听和清理SSE连接
onUnmounted(() => {
document.removeEventListener('keydown', handleKeydown);
stopTaskStreaming();
});
</script>
@@ -578,6 +696,10 @@ onUnmounted(() => {
}
.artwork-header {
margin-bottom: 1.5rem;
}
.download-section {
margin-bottom: 2rem;
}
@@ -649,7 +771,7 @@ onUnmounted(() => {
padding: 1.5rem;
background: #f8fafc;
border-radius: 0.75rem;
margin-bottom: 2rem;
margin-bottom: 1.5rem;
}
.artist-avatar {
@@ -814,11 +936,10 @@ onUnmounted(() => {
}
.download-status {
margin-top: 1rem;
padding: 0.75rem 1rem;
padding: 1rem 1.25rem;
background: #f0f9ff;
border: 1px solid #bae6fd;
border-radius: 0.5rem;
border-radius: 0.75rem;
display: flex;
align-items: center;
gap: 0.5rem;
+17 -7
View File
@@ -92,7 +92,7 @@
></div>
</div>
<div class="progress-text">
{{ task.completed }}/{{ task.total }} ({{ task.progress }}%)
{{ task.completed_files }}/{{ task.total_files }} ({{ task.progress }}%)
</div>
</div>
@@ -271,9 +271,9 @@ const getTaskTitle = (task: DownloadTask) => {
if (task.type === 'artwork') {
return `作品 ${task.artwork_id}`;
} else if (task.type === 'artist') {
return `作者 ${task.artist_id}作品`;
return `作者作品`;
} else if (task.type === 'batch') {
return `批量下载 ${task.total} 个作品`;
return `批量下载 ${task.total_files} 个作品`;
}
return '未知任务';
};
@@ -521,6 +521,7 @@ onUnmounted(() => {
border-radius: 0.5rem;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
overflow: hidden;
margin-top: 1rem;
}
.loading-section,
@@ -559,17 +560,26 @@ onUnmounted(() => {
.tasks-list,
.history-list,
.files-list {
padding: 1rem;
padding: 1.5rem;
}
.task-card,
.history-card,
.file-card {
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
padding: 1rem;
margin-bottom: 1rem;
border-radius: 0.75rem;
padding: 1.5rem;
margin-bottom: 1.5rem;
background: white;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
}
.task-card:hover,
.history-card:hover,
.file-card:hover {
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
border-color: #d1d5db;
}
.task-header,