Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,334 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
/**
|
||||
* 图像生成管理钩子
|
||||
* @param {Function} onImageGenerated 图片生成成功后的回调函数
|
||||
* @returns {Object} 图像生成相关状态和方法
|
||||
*/
|
||||
const useImageGeneration = (onImageGenerated) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 状态管理
|
||||
const [generatedImages, setGeneratedImages] = useState([]);
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [generationParams, setGenerationParams] = useState({});
|
||||
|
||||
// 加载状态管理
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [loadingProgress, setLoadingProgress] = useState(0);
|
||||
|
||||
// 用于存储上一次成功生成的参数
|
||||
const lastSuccessfulParamsRef = useRef({});
|
||||
|
||||
// 清除错误信息
|
||||
const clearError = useCallback(() => {
|
||||
setError('');
|
||||
}, []);
|
||||
|
||||
// 清除生成的图片
|
||||
const clearGeneratedImages = useCallback(() => {
|
||||
setGeneratedImages([]);
|
||||
clearError();
|
||||
}, [clearError]);
|
||||
|
||||
/**
|
||||
* 生成图片
|
||||
* @param {Object} params 生成参数
|
||||
* @param {string} params.prompt 提示词
|
||||
* @param {string} params.model 模型名称
|
||||
* @param {string} params.size 图片尺寸
|
||||
* @param {string} params.quality 图片质量
|
||||
* @param {string} params.negativePrompt 反向提示词
|
||||
* @param {number} params.n 生成图片数量
|
||||
*/
|
||||
const generateImage = useCallback(
|
||||
async (params) => {
|
||||
const {
|
||||
prompt,
|
||||
model,
|
||||
size,
|
||||
quality,
|
||||
negativePrompt = '',
|
||||
n = 1,
|
||||
} = params;
|
||||
|
||||
// 参数验证
|
||||
if (!prompt || !prompt.trim()) {
|
||||
setError(t('请输入提示词'));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!model) {
|
||||
setError(t('请选择生成模型'));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!size) {
|
||||
setError(t('请选择图片尺寸'));
|
||||
return false;
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
setIsGenerating(true);
|
||||
setError('');
|
||||
setIsLoading(true);
|
||||
setLoadingProgress(0);
|
||||
|
||||
// 保存当前参数
|
||||
setGenerationParams(params);
|
||||
|
||||
try {
|
||||
// 模拟进度更新
|
||||
const progressInterval = setInterval(() => {
|
||||
setLoadingProgress((prev) => {
|
||||
if (prev >= 90) {
|
||||
clearInterval(progressInterval);
|
||||
return prev;
|
||||
}
|
||||
return prev + Math.random() * 10;
|
||||
});
|
||||
}, 200);
|
||||
|
||||
// 这里是模拟API调用,实际实现需要替换为真实的API请求
|
||||
// 模拟网络延迟
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
|
||||
clearInterval(progressInterval);
|
||||
|
||||
// 模拟生成的图片数据
|
||||
const mockImages = Array.from({ length: n }, (_, index) => ({
|
||||
id: Date.now() + index,
|
||||
url: `https://picsum.photos/seed/${Date.now() + index}/${size.split('x')[0]}/${size.split('x')[1]}`,
|
||||
revised_prompt: prompt,
|
||||
created_at: new Date().toISOString(),
|
||||
metadata: {
|
||||
model,
|
||||
size,
|
||||
quality,
|
||||
negative_prompt: negativePrompt,
|
||||
},
|
||||
}));
|
||||
|
||||
setGeneratedImages(mockImages);
|
||||
|
||||
// 更新上一次成功生成的参数
|
||||
lastSuccessfulParamsRef.current = params;
|
||||
|
||||
// 调用回调函数
|
||||
if (onImageGenerated) {
|
||||
onImageGenerated(mockImages, params);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('Image generation failed:', err);
|
||||
setError(t('图片生成失败,请重试') + ': ' + (err.message || ''));
|
||||
return false;
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
setIsLoading(false);
|
||||
setLoadingProgress(100);
|
||||
}
|
||||
},
|
||||
[t, onImageGenerated],
|
||||
);
|
||||
|
||||
/**
|
||||
* 重新生成图片
|
||||
* 使用上一次成功生成的参数或当前保存的参数
|
||||
*/
|
||||
const regenerateImage = useCallback(async () => {
|
||||
// 获取有效的参数
|
||||
const params =
|
||||
Object.keys(lastSuccessfulParamsRef.current).length > 0
|
||||
? lastSuccessfulParamsRef.current
|
||||
: Object.keys(generationParams).length > 0
|
||||
? generationParams
|
||||
: null;
|
||||
|
||||
if (!params) {
|
||||
setError(t('没有可用的生成参数'));
|
||||
return false;
|
||||
}
|
||||
|
||||
// 确保参数完整
|
||||
if (!params.prompt || !params.model || !params.size) {
|
||||
setError(t('参数不完整,无法重新生成'));
|
||||
return false;
|
||||
}
|
||||
|
||||
return generateImage(params);
|
||||
}, [generateImage, generationParams, t]);
|
||||
|
||||
/**
|
||||
* 下载单个图片
|
||||
* @param {string} imageUrl 图片URL
|
||||
* @param {number} index 图片索引
|
||||
* @param {string} prompt 提示词(用于生成文件名)
|
||||
*/
|
||||
const downloadImage = useCallback((imageUrl, index = 0, prompt = '') => {
|
||||
const link = document.createElement('a');
|
||||
|
||||
// 生成文件名
|
||||
let filename = 'generated-image';
|
||||
|
||||
// 如果有提示词,使用前20个字符作为文件名的一部分
|
||||
if (prompt && prompt.trim()) {
|
||||
const safePrompt = prompt
|
||||
.trim()
|
||||
.replace(/[^a-z0-9]/gi, '_')
|
||||
.substring(0, 20);
|
||||
filename = `${filename}-${safePrompt}`;
|
||||
}
|
||||
|
||||
// 添加索引和时间戳
|
||||
filename = `${filename}-${index}-${Date.now()}.png`;
|
||||
|
||||
link.href = imageUrl;
|
||||
link.download = filename;
|
||||
|
||||
// 模拟点击下载
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
|
||||
// 清理
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link);
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 批量下载所有生成的图片
|
||||
* @param {string} prompt 提示词(用于生成文件名前缀)
|
||||
*/
|
||||
const downloadAllImages = useCallback(
|
||||
(prompt = '') => {
|
||||
if (generatedImages.length === 0) {
|
||||
setError(t('没有可下载的图片'));
|
||||
return;
|
||||
}
|
||||
|
||||
// 为每个图片创建下载
|
||||
generatedImages.forEach((image, index) => {
|
||||
downloadImage(image.url, index, prompt);
|
||||
});
|
||||
},
|
||||
[generatedImages, downloadImage, t],
|
||||
);
|
||||
|
||||
/**
|
||||
* 将图片转换为Blob对象
|
||||
* @param {string} imageUrl 图片URL
|
||||
* @returns {Promise<Blob>} Blob对象
|
||||
*/
|
||||
const imageUrlToBlob = useCallback(async (imageUrl) => {
|
||||
try {
|
||||
const response = await fetch(imageUrl);
|
||||
const blob = await response.blob();
|
||||
return blob;
|
||||
} catch (error) {
|
||||
console.error('Failed to convert image to blob:', error);
|
||||
throw error;
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 将图片复制到剪贴板
|
||||
* @param {string} imageUrl 图片URL
|
||||
*/
|
||||
const copyImageToClipboard = useCallback(
|
||||
async (imageUrl) => {
|
||||
try {
|
||||
const blob = await imageUrlToBlob(imageUrl);
|
||||
|
||||
// 检查浏览器是否支持剪贴板API
|
||||
if (navigator.clipboard && window.ClipboardItem) {
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'image/png': blob,
|
||||
}),
|
||||
]);
|
||||
return true;
|
||||
} else {
|
||||
setError(t('您的浏览器不支持复制图片到剪贴板'));
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to copy image to clipboard:', error);
|
||||
setError(t('复制图片失败: {{error}}', { error: error.message }));
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[imageUrlToBlob, t],
|
||||
);
|
||||
|
||||
/**
|
||||
* 查看图片详情
|
||||
* @param {Object} image 图片对象
|
||||
*/
|
||||
const viewImageDetails = useCallback((image) => {
|
||||
// 可以在这里实现图片详情查看逻辑,比如打开模态框显示大图
|
||||
console.log('Viewing image details:', image);
|
||||
|
||||
// 如果是浏览器环境,可以在新标签页打开图片
|
||||
if (typeof window !== 'undefined' && window.open) {
|
||||
window.open(image.url, '_blank');
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 获取图片信息
|
||||
* @param {string} imageId 图片ID
|
||||
* @returns {Object|null} 图片对象
|
||||
*/
|
||||
const getImageById = useCallback(
|
||||
(imageId) => {
|
||||
return generatedImages.find((image) => image.id === imageId) || null;
|
||||
},
|
||||
[generatedImages],
|
||||
);
|
||||
|
||||
return {
|
||||
// 状态
|
||||
generatedImages,
|
||||
isGenerating,
|
||||
error,
|
||||
loadingProgress,
|
||||
isLoading,
|
||||
generationParams,
|
||||
|
||||
// 操作方法
|
||||
generateImage,
|
||||
regenerateImage,
|
||||
downloadImage,
|
||||
downloadAllImages,
|
||||
copyImageToClipboard,
|
||||
viewImageDetails,
|
||||
clearGeneratedImages,
|
||||
clearError,
|
||||
getImageById,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageGeneration;
|
||||
@@ -0,0 +1,401 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// 本地存储键名
|
||||
const STORAGE_KEY = 'imageGenerationHistory';
|
||||
// 最大历史记录条数
|
||||
const MAX_HISTORY_ITEMS = 50;
|
||||
|
||||
/**
|
||||
* 图像生成历史记录管理钩子
|
||||
* @param {number} maxItems 最大历史记录条数
|
||||
* @returns {Object} 历史记录相关状态和方法
|
||||
*/
|
||||
const useImageHistory = (maxItems = MAX_HISTORY_ITEMS) => {
|
||||
const { t: _t } = useTranslation();
|
||||
|
||||
// 状态管理
|
||||
const [history, setHistory] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// 从本地存储加载历史记录
|
||||
const loadHistory = useCallback(() => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const savedHistory = localStorage.getItem(STORAGE_KEY);
|
||||
if (savedHistory) {
|
||||
const parsedHistory = JSON.parse(savedHistory);
|
||||
// 确保是数组格式
|
||||
if (Array.isArray(parsedHistory)) {
|
||||
setHistory(parsedHistory);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load history from localStorage:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 保存历史记录到本地存储
|
||||
const saveHistory = useCallback((historyData) => {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(historyData));
|
||||
} catch (error) {
|
||||
console.error('Failed to save history to localStorage:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 初始化时加载历史记录
|
||||
useEffect(() => {
|
||||
loadHistory();
|
||||
}, [loadHistory]);
|
||||
|
||||
/**
|
||||
* 添加新的生成记录
|
||||
* @param {Object} record 生成记录
|
||||
* @param {string} record.model 使用的模型
|
||||
* @param {string} record.prompt 使用的提示词
|
||||
* @param {string} record.negativePrompt 使用的反向提示词
|
||||
* @param {string} record.size 图片尺寸
|
||||
* @param {string} record.quality 图片质量
|
||||
* @param {Array} record.images 生成的图片数组
|
||||
*/
|
||||
const addHistoryRecord = useCallback(
|
||||
(record) => {
|
||||
if (
|
||||
!record ||
|
||||
!record.prompt ||
|
||||
!record.images ||
|
||||
!Array.isArray(record.images)
|
||||
) {
|
||||
console.error('Invalid history record:', record);
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建完整的记录对象
|
||||
const newRecord = {
|
||||
id: Date.now().toString(), // 使用时间戳作为唯一ID
|
||||
timestamp: new Date().toISOString(),
|
||||
model: record.model || '',
|
||||
prompt: record.prompt,
|
||||
negativePrompt: record.negativePrompt || '',
|
||||
size: record.size || '',
|
||||
quality: record.quality || 'standard',
|
||||
style: record.style || 'natural',
|
||||
images: record.images,
|
||||
};
|
||||
|
||||
setHistory((prev) => {
|
||||
// 添加新记录到开头,并限制最大数量
|
||||
const updatedHistory = [newRecord, ...prev].slice(0, maxItems);
|
||||
// 保存到本地存储
|
||||
saveHistory(updatedHistory);
|
||||
return updatedHistory;
|
||||
});
|
||||
},
|
||||
[maxItems, saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 删除单条历史记录
|
||||
* @param {string} recordId 记录ID
|
||||
*/
|
||||
const deleteHistoryRecord = useCallback(
|
||||
(recordId) => {
|
||||
setHistory((prev) => {
|
||||
const updatedHistory = prev.filter((item) => item.id !== recordId);
|
||||
// 保存到本地存储
|
||||
saveHistory(updatedHistory);
|
||||
return updatedHistory;
|
||||
});
|
||||
},
|
||||
[saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 清空所有历史记录
|
||||
*/
|
||||
const clearAllHistory = useCallback(() => {
|
||||
setHistory([]);
|
||||
// 从本地存储中删除
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error('Failed to clear history from localStorage:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 根据ID获取历史记录
|
||||
* @param {string} recordId 记录ID
|
||||
* @returns {Object|null} 历史记录对象
|
||||
*/
|
||||
const getHistoryRecordById = useCallback(
|
||||
(recordId) => {
|
||||
return history.find((item) => item.id === recordId) || null;
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 从历史记录中加载参数
|
||||
* @param {string} recordId 记录ID
|
||||
* @returns {Object|null} 生成参数对象
|
||||
*/
|
||||
const loadParamsFromHistory = useCallback(
|
||||
(recordId) => {
|
||||
const record = getHistoryRecordById(recordId);
|
||||
if (!record) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
model: record.model,
|
||||
prompt: record.prompt,
|
||||
negativePrompt: record.negativePrompt,
|
||||
size: record.size,
|
||||
quality: record.quality,
|
||||
style: record.style,
|
||||
images: record.images,
|
||||
};
|
||||
},
|
||||
[getHistoryRecordById],
|
||||
);
|
||||
|
||||
/**
|
||||
* 搜索历史记录
|
||||
* @param {string} keyword 搜索关键词
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const searchHistory = useCallback(
|
||||
(keyword) => {
|
||||
if (!keyword || !keyword.trim()) {
|
||||
return history;
|
||||
}
|
||||
|
||||
const searchTerm = keyword.toLowerCase().trim();
|
||||
return history.filter(
|
||||
(item) =>
|
||||
item.prompt.toLowerCase().includes(searchTerm) ||
|
||||
(item.negativePrompt &&
|
||||
item.negativePrompt.toLowerCase().includes(searchTerm)) ||
|
||||
item.model.toLowerCase().includes(searchTerm),
|
||||
);
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 按时间范围过滤历史记录
|
||||
* @param {Date} startDate 开始时间
|
||||
* @param {Date} endDate 结束时间
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const filterHistoryByDate = useCallback(
|
||||
(startDate, endDate) => {
|
||||
if (!startDate && !endDate) {
|
||||
return history;
|
||||
}
|
||||
|
||||
return history.filter((item) => {
|
||||
const itemDate = new Date(item.timestamp);
|
||||
|
||||
if (startDate && itemDate < startDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (endDate && itemDate > endDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 按模型过滤历史记录
|
||||
* @param {string} modelName 模型名称
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const filterHistoryByModel = useCallback(
|
||||
(modelName) => {
|
||||
if (!modelName || !modelName.trim()) {
|
||||
return history;
|
||||
}
|
||||
|
||||
return history.filter((item) => item.model === modelName);
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 导出历史记录为JSON
|
||||
* @returns {string} JSON格式的历史记录
|
||||
*/
|
||||
const exportHistory = useCallback(() => {
|
||||
return JSON.stringify(history, null, 2);
|
||||
}, [history]);
|
||||
|
||||
/**
|
||||
* 导入历史记录
|
||||
* @param {string} jsonData JSON格式的历史记录数据
|
||||
* @returns {boolean} 是否导入成功
|
||||
*/
|
||||
const importHistory = useCallback(
|
||||
(jsonData) => {
|
||||
try {
|
||||
const importedData = JSON.parse(jsonData);
|
||||
|
||||
// 验证导入的数据格式
|
||||
if (!Array.isArray(importedData)) {
|
||||
throw new Error('Invalid history data format');
|
||||
}
|
||||
|
||||
// 验证每条记录的格式
|
||||
const validRecords = importedData.filter(
|
||||
(record) =>
|
||||
record.id &&
|
||||
record.timestamp &&
|
||||
record.prompt &&
|
||||
Array.isArray(record.images),
|
||||
);
|
||||
|
||||
if (validRecords.length === 0) {
|
||||
throw new Error('No valid history records found');
|
||||
}
|
||||
|
||||
// 合并现有历史记录,避免重复,并限制最大数量
|
||||
const combinedRecords = [...validRecords, ...history];
|
||||
|
||||
// 去重(基于ID)
|
||||
const uniqueRecords = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const record of combinedRecords) {
|
||||
if (!seenIds.has(record.id)) {
|
||||
seenIds.add(record.id);
|
||||
uniqueRecords.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
// 按时间戳排序(最新的在前)
|
||||
uniqueRecords.sort(
|
||||
(a, b) => new Date(b.timestamp) - new Date(a.timestamp),
|
||||
);
|
||||
|
||||
// 限制最大数量
|
||||
const finalRecords = uniqueRecords.slice(0, maxItems);
|
||||
|
||||
// 更新状态并保存
|
||||
setHistory(finalRecords);
|
||||
saveHistory(finalRecords);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to import history:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[history, maxItems, saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取最近使用的提示词列表
|
||||
* @param {number} limit 最大返回数量
|
||||
* @returns {Array} 提示词数组
|
||||
*/
|
||||
const getRecentPrompts = useCallback(
|
||||
(limit = 10) => {
|
||||
const prompts = [];
|
||||
const seenPrompts = new Set();
|
||||
|
||||
for (const item of history) {
|
||||
if (item.prompt && !seenPrompts.has(item.prompt)) {
|
||||
seenPrompts.add(item.prompt);
|
||||
prompts.push(item.prompt);
|
||||
|
||||
if (prompts.length >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return prompts;
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取历史记录统计信息
|
||||
* @returns {Object} 统计信息
|
||||
*/
|
||||
const getHistoryStats = useCallback(() => {
|
||||
const stats = {
|
||||
totalRecords: history.length,
|
||||
models: {},
|
||||
sizes: {},
|
||||
recentActivity:
|
||||
history.length > 0 ? new Date(history[0].timestamp) : null,
|
||||
};
|
||||
|
||||
// 统计各模型和尺寸的使用次数
|
||||
history.forEach((item) => {
|
||||
// 模型统计
|
||||
if (item.model) {
|
||||
stats.models[item.model] = (stats.models[item.model] || 0) + 1;
|
||||
}
|
||||
|
||||
// 尺寸统计
|
||||
if (item.size) {
|
||||
stats.sizes[item.size] = (stats.sizes[item.size] || 0) + 1;
|
||||
}
|
||||
});
|
||||
|
||||
return stats;
|
||||
}, [history]);
|
||||
|
||||
return {
|
||||
// 状态
|
||||
history,
|
||||
isLoading,
|
||||
|
||||
// 操作方法
|
||||
addHistoryRecord,
|
||||
deleteHistoryRecord,
|
||||
clearAllHistory,
|
||||
getHistoryRecordById,
|
||||
loadParamsFromHistory,
|
||||
searchHistory,
|
||||
filterHistoryByDate,
|
||||
filterHistoryByModel,
|
||||
exportHistory,
|
||||
importHistory,
|
||||
getRecentPrompts,
|
||||
getHistoryStats,
|
||||
loadHistory,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageHistory;
|
||||
@@ -0,0 +1,276 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// 导入模型判断函数
|
||||
import { IsImageGenerationModel } from '../../../common/model';
|
||||
|
||||
// 定义支持的图片生成模型列表
|
||||
const IMAGE_GENERATION_MODELS = [
|
||||
{
|
||||
value: 'dall-e-3',
|
||||
label: 'DALL-E 3',
|
||||
vendor: 'OpenAI',
|
||||
description: '最新一代DALL-E模型,生成高质量、详细的图像',
|
||||
recommended: true,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1024x1792', '1792x1024'],
|
||||
supportsQuality: true,
|
||||
maxImages: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'dall-e-2',
|
||||
label: 'DALL-E 2',
|
||||
vendor: 'OpenAI',
|
||||
description: '较早的DALL-E模型,平衡效果和速度',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['256x256', '512x512', '1024x1024'],
|
||||
supportsQuality: false,
|
||||
maxImages: 10,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'gpt-image-1',
|
||||
label: 'GPT-4V Image',
|
||||
vendor: 'OpenAI',
|
||||
description: '基于GPT-4V的图像生成能力',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024'],
|
||||
supportsQuality: true,
|
||||
maxImages: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'imagen-3',
|
||||
label: 'Imagen 3',
|
||||
vendor: 'Google',
|
||||
description: 'Google最新的图像生成模型,擅长文本理解',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1792x1024', '1024x1792'],
|
||||
supportsQuality: true,
|
||||
maxImages: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'flux.1-schnell',
|
||||
label: 'FLUX.1 Schnell',
|
||||
vendor: 'Black Forest Labs',
|
||||
description: '快速版FLUX.1模型,生成速度快',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1344x1024', '1024x1344'],
|
||||
supportsQuality: true,
|
||||
maxImages: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'flux.1-dev',
|
||||
label: 'FLUX.1 Dev',
|
||||
vendor: 'Black Forest Labs',
|
||||
description: '开发版FLUX.1模型,质量更高',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1344x1024', '1024x1344'],
|
||||
supportsQuality: true,
|
||||
maxImages: 4,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// 定义图片尺寸选项
|
||||
const IMAGE_SIZES = [
|
||||
{ value: '256x256', label: '256×256', description: '最小尺寸,生成速度最快' },
|
||||
{
|
||||
value: '512x512',
|
||||
label: '512×512',
|
||||
description: '中等尺寸,平衡质量和速度',
|
||||
},
|
||||
{ value: '1024x1024', label: '1024×1024', description: '标准高清尺寸' },
|
||||
{
|
||||
value: '1024x1792',
|
||||
label: '1024×1792 (9:16)',
|
||||
description: '纵向比例,适合手机壁纸',
|
||||
},
|
||||
{
|
||||
value: '1792x1024',
|
||||
label: '1792×1024 (16:9)',
|
||||
description: '横向比例,适合桌面壁纸',
|
||||
},
|
||||
{ value: '1344x1024', label: '1344×1024', description: '宽屏比例' },
|
||||
{ value: '1024x1344', label: '1024×1344', description: '竖屏比例' },
|
||||
];
|
||||
|
||||
// 定义图片质量选项
|
||||
const IMAGE_QUALITY = [
|
||||
{ value: 'standard', label: '标准', description: '标准质量,速度较快' },
|
||||
{ value: 'hd', label: '高清', description: '更高质量,细节更丰富' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 图像生成模型管理钩子
|
||||
* @returns {Object} 模型选择相关状态和方法
|
||||
*/
|
||||
const useImageModel = () => {
|
||||
const { t: _t } = useTranslation();
|
||||
|
||||
// 获取推荐模型(默认选择第一个推荐的模型)
|
||||
const getRecommendedModel = () => {
|
||||
const recommended = IMAGE_GENERATION_MODELS.find(
|
||||
(model) => model.recommended,
|
||||
);
|
||||
return recommended ? recommended.value : IMAGE_GENERATION_MODELS[0].value;
|
||||
};
|
||||
|
||||
// 状态管理
|
||||
const [selectedModel, setSelectedModel] = useState(() => {
|
||||
// 尝试从localStorage获取上次选择的模型
|
||||
const savedModel = localStorage.getItem('selectedImageModel');
|
||||
return savedModel && IsImageGenerationModel(savedModel)
|
||||
? savedModel
|
||||
: getRecommendedModel();
|
||||
});
|
||||
|
||||
const [selectedSize, setSelectedSize] = useState('1024x1024');
|
||||
const [selectedQuality, setSelectedQuality] = useState('standard');
|
||||
|
||||
// 当模型改变时,更新可用的尺寸和质量设置
|
||||
useEffect(() => {
|
||||
// 保存选择的模型到localStorage
|
||||
localStorage.setItem('selectedImageModel', selectedModel);
|
||||
|
||||
// 获取当前模型的能力
|
||||
const currentModel = IMAGE_GENERATION_MODELS.find(
|
||||
(m) => m.value === selectedModel,
|
||||
);
|
||||
|
||||
if (currentModel) {
|
||||
// 检查当前选择的尺寸是否可用,如果不可用则选择第一个可用尺寸
|
||||
if (!currentModel.capabilities.sizes.includes(selectedSize)) {
|
||||
setSelectedSize(currentModel.capabilities.sizes[0]);
|
||||
}
|
||||
|
||||
// 如果模型不支持质量选择,确保质量设置为standard
|
||||
if (
|
||||
!currentModel.capabilities.supportsQuality &&
|
||||
selectedQuality !== 'standard'
|
||||
) {
|
||||
setSelectedQuality('standard');
|
||||
}
|
||||
}
|
||||
}, [selectedModel]);
|
||||
|
||||
// 获取当前选中模型的详细信息
|
||||
const getCurrentModelInfo = useCallback(() => {
|
||||
return (
|
||||
IMAGE_GENERATION_MODELS.find((model) => model.value === selectedModel) ||
|
||||
IMAGE_GENERATION_MODELS[0]
|
||||
);
|
||||
}, [selectedModel]);
|
||||
|
||||
// 获取当前模型可用的尺寸选项
|
||||
const getAvailableSizes = useCallback(() => {
|
||||
const modelInfo = getCurrentModelInfo();
|
||||
return IMAGE_SIZES.filter((size) =>
|
||||
modelInfo.capabilities.sizes.includes(size.value),
|
||||
);
|
||||
}, [getCurrentModelInfo]);
|
||||
|
||||
// 检查当前模型是否支持质量选择
|
||||
const supportsQualityOption = useCallback(() => {
|
||||
const modelInfo = getCurrentModelInfo();
|
||||
return modelInfo.capabilities.supportsQuality;
|
||||
}, [getCurrentModelInfo]);
|
||||
|
||||
// 获取当前模型支持的最大图片数量
|
||||
const getMaxImages = useCallback(() => {
|
||||
const modelInfo = getCurrentModelInfo();
|
||||
return modelInfo.capabilities.maxImages;
|
||||
}, [getCurrentModelInfo]);
|
||||
|
||||
// 按厂商分组模型
|
||||
const getModelsByVendor = useCallback(() => {
|
||||
const grouped = {};
|
||||
IMAGE_GENERATION_MODELS.forEach((model) => {
|
||||
if (!grouped[model.vendor]) {
|
||||
grouped[model.vendor] = [];
|
||||
}
|
||||
grouped[model.vendor].push(model);
|
||||
});
|
||||
return grouped;
|
||||
}, []);
|
||||
|
||||
// 获取模型描述信息
|
||||
const getModelDescription = useCallback((modelValue) => {
|
||||
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
|
||||
return model ? model.description : '';
|
||||
}, []);
|
||||
|
||||
// 获取模型厂商信息
|
||||
const getVendorInfo = useCallback((modelValue) => {
|
||||
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
|
||||
return model ? model.vendor : '';
|
||||
}, []);
|
||||
|
||||
// 检查模型是否为推荐模型
|
||||
const isRecommendedModel = useCallback((modelValue) => {
|
||||
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
|
||||
return model ? model.recommended : false;
|
||||
}, []);
|
||||
|
||||
return {
|
||||
// 模型列表和信息
|
||||
models: IMAGE_GENERATION_MODELS,
|
||||
modelOptions: IMAGE_GENERATION_MODELS.map((model) => ({
|
||||
value: model.value,
|
||||
label: model.label,
|
||||
vendor: model.vendor,
|
||||
recommended: model.recommended,
|
||||
})),
|
||||
|
||||
// 状态和setter
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
selectedSize,
|
||||
setSelectedSize,
|
||||
selectedQuality,
|
||||
setSelectedQuality,
|
||||
|
||||
// 尺寸和质量选项
|
||||
sizeOptions: IMAGE_SIZES,
|
||||
qualityOptions: IMAGE_QUALITY,
|
||||
|
||||
// 功能方法
|
||||
getCurrentModelInfo,
|
||||
getAvailableSizes,
|
||||
supportsQualityOption,
|
||||
getMaxImages,
|
||||
getModelsByVendor,
|
||||
getModelDescription,
|
||||
getVendorInfo,
|
||||
isRecommendedModel,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageModel;
|
||||
@@ -0,0 +1,314 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
|
||||
/**
|
||||
* 错误类型枚举
|
||||
*/
|
||||
export const ERROR_TYPES = {
|
||||
NETWORK: 'network',
|
||||
VALIDATION: 'validation',
|
||||
API: 'api',
|
||||
RATE_LIMIT: 'rate_limit',
|
||||
CREDIT: 'credit',
|
||||
UNKNOWN: 'unknown',
|
||||
};
|
||||
|
||||
/**
|
||||
* 加载阶段枚举
|
||||
*/
|
||||
export const LOADING_STAGES = {
|
||||
IDLE: 'idle',
|
||||
PROCESSING: 'processing',
|
||||
GENERATING: 'generating',
|
||||
COMPLETING: 'completing',
|
||||
};
|
||||
|
||||
/**
|
||||
* 图片状态管理钩子
|
||||
* 用于管理图片生成过程中的加载状态、错误处理、进度显示等
|
||||
*/
|
||||
const useImageStatus = () => {
|
||||
// 状态管理
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [loadingStage, setLoadingStage] = useState(LOADING_STAGES.IDLE);
|
||||
const [error, setError] = useState(null);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [successMessage, setSuccessMessage] = useState('');
|
||||
const [notification, setNotification] = useState(null);
|
||||
|
||||
// 重置状态
|
||||
const resetStatus = useCallback(() => {
|
||||
setIsLoading(false);
|
||||
setLoadingStage(LOADING_STAGES.IDLE);
|
||||
setError(null);
|
||||
setProgress(0);
|
||||
setSuccessMessage('');
|
||||
}, []);
|
||||
|
||||
// 设置加载状态
|
||||
const setLoading = useCallback((stage, customProgress) => {
|
||||
setIsLoading(true);
|
||||
setLoadingStage(stage || LOADING_STAGES.PROCESSING);
|
||||
setError(null);
|
||||
setSuccessMessage('');
|
||||
if (typeof customProgress !== 'undefined') {
|
||||
setProgress(customProgress);
|
||||
} else {
|
||||
// 根据阶段设置默认进度
|
||||
const stageProgress = {
|
||||
[LOADING_STAGES.IDLE]: 0,
|
||||
[LOADING_STAGES.PROCESSING]: 25,
|
||||
[LOADING_STAGES.GENERATING]: 50,
|
||||
[LOADING_STAGES.COMPLETING]: 75,
|
||||
};
|
||||
setProgress(stageProgress[stage] || 0);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 设置错误
|
||||
const setErrorState = useCallback(
|
||||
(message, type = ERROR_TYPES.UNKNOWN, details = {}) => {
|
||||
setIsLoading(false);
|
||||
setLoadingStage(LOADING_STAGES.IDLE);
|
||||
setError({
|
||||
message,
|
||||
type,
|
||||
details,
|
||||
});
|
||||
setProgress(0);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 设置成功
|
||||
const setSuccess = useCallback((message = '') => {
|
||||
setIsLoading(false);
|
||||
setLoadingStage(LOADING_STAGES.IDLE);
|
||||
setError(null);
|
||||
setProgress(100);
|
||||
setSuccessMessage(message);
|
||||
|
||||
// 如果有成功消息,短暂显示通知
|
||||
if (message) {
|
||||
showNotification(message, 'success');
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 更新进度
|
||||
const updateProgress = useCallback((newProgress) => {
|
||||
setProgress(Math.min(Math.max(0, newProgress), 100));
|
||||
}, []);
|
||||
|
||||
// 显示通知
|
||||
const showNotification = useCallback(
|
||||
(message, type = 'info', duration = 3000) => {
|
||||
setNotification({
|
||||
message,
|
||||
type,
|
||||
duration,
|
||||
id: Date.now(),
|
||||
});
|
||||
|
||||
// 自动清除通知
|
||||
setTimeout(() => {
|
||||
setNotification(null);
|
||||
}, duration);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 清除通知
|
||||
const clearNotification = useCallback(() => {
|
||||
setNotification(null);
|
||||
}, []);
|
||||
|
||||
// 根据错误类型获取建议操作
|
||||
const getErrorAction = useCallback((errorType) => {
|
||||
const actionMap = {
|
||||
[ERROR_TYPES.NETWORK]: {
|
||||
label: '重试连接',
|
||||
type: 'retry',
|
||||
},
|
||||
[ERROR_TYPES.VALIDATION]: {
|
||||
label: '修改参数',
|
||||
type: 'edit',
|
||||
},
|
||||
[ERROR_TYPES.API]: {
|
||||
label: '查看详情',
|
||||
type: 'details',
|
||||
},
|
||||
[ERROR_TYPES.RATE_LIMIT]: {
|
||||
label: '稍后重试',
|
||||
type: 'wait',
|
||||
},
|
||||
[ERROR_TYPES.CREDIT]: {
|
||||
label: '充值',
|
||||
type: 'recharge',
|
||||
},
|
||||
[ERROR_TYPES.UNKNOWN]: {
|
||||
label: '联系支持',
|
||||
type: 'support',
|
||||
},
|
||||
};
|
||||
|
||||
return actionMap[errorType] || actionMap[ERROR_TYPES.UNKNOWN];
|
||||
}, []);
|
||||
|
||||
// 根据加载阶段获取描述文本
|
||||
const getStageText = useCallback((stage) => {
|
||||
const stageTextMap = {
|
||||
[LOADING_STAGES.IDLE]: '准备中...',
|
||||
[LOADING_STAGES.PROCESSING]: '处理提示词...',
|
||||
[LOADING_STAGES.GENERATING]: '正在生成图像...',
|
||||
[LOADING_STAGES.COMPLETING]: '优化图片质量...',
|
||||
};
|
||||
|
||||
return stageTextMap[stage] || stageTextMap[LOADING_STAGES.IDLE];
|
||||
}, []);
|
||||
|
||||
// 格式化错误消息
|
||||
const formatErrorMessage = useCallback((errorObj) => {
|
||||
if (!errorObj) return '';
|
||||
|
||||
const { message, type, details } = errorObj;
|
||||
|
||||
// 特定错误类型的格式化
|
||||
if (type === ERROR_TYPES.VALIDATION && details.field) {
|
||||
return `${details.field}: ${message}`;
|
||||
}
|
||||
|
||||
if (type === ERROR_TYPES.API && details.code) {
|
||||
return `${message} (错误码: ${details.code})`;
|
||||
}
|
||||
|
||||
return message;
|
||||
}, []);
|
||||
|
||||
// 处理API错误响应
|
||||
const handleApiError = useCallback(
|
||||
(apiResponse) => {
|
||||
if (!apiResponse) {
|
||||
return setErrorState('未知错误,请重试', ERROR_TYPES.UNKNOWN);
|
||||
}
|
||||
|
||||
const { error, status } = apiResponse;
|
||||
|
||||
if (!error) {
|
||||
return setErrorState('API返回异常,请重试', ERROR_TYPES.API);
|
||||
}
|
||||
|
||||
// 根据状态码和错误信息判断错误类型
|
||||
if (status === 429) {
|
||||
return setErrorState(
|
||||
error.message || '请求过于频繁,请稍后重试',
|
||||
ERROR_TYPES.RATE_LIMIT,
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 400 && error.validationErrors) {
|
||||
return setErrorState(
|
||||
error.message || '参数验证失败',
|
||||
ERROR_TYPES.VALIDATION,
|
||||
{ status, validationErrors: error.validationErrors },
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 402) {
|
||||
return setErrorState(
|
||||
error.message || '余额不足,请充值',
|
||||
ERROR_TYPES.CREDIT,
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
// 网络相关错误
|
||||
if (status >= 500 || status === 0) {
|
||||
return setErrorState(
|
||||
error.message || '网络错误,请检查连接后重试',
|
||||
ERROR_TYPES.NETWORK,
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
// 其他API错误
|
||||
return setErrorState(error.message || 'API请求失败', ERROR_TYPES.API, {
|
||||
status,
|
||||
});
|
||||
},
|
||||
[setErrorState],
|
||||
);
|
||||
|
||||
// 导出的状态和方法
|
||||
const statusProps = useMemo(
|
||||
() => ({
|
||||
// 状态
|
||||
isLoading,
|
||||
loadingStage,
|
||||
error,
|
||||
progress,
|
||||
successMessage,
|
||||
notification,
|
||||
|
||||
// 操作方法
|
||||
resetStatus,
|
||||
setLoading,
|
||||
setErrorState,
|
||||
setSuccess,
|
||||
updateProgress,
|
||||
showNotification,
|
||||
clearNotification,
|
||||
|
||||
// 辅助方法
|
||||
getErrorAction,
|
||||
getStageText,
|
||||
formatErrorMessage,
|
||||
handleApiError,
|
||||
|
||||
// 常量
|
||||
ERROR_TYPES,
|
||||
LOADING_STAGES,
|
||||
}),
|
||||
[
|
||||
isLoading,
|
||||
loadingStage,
|
||||
error,
|
||||
progress,
|
||||
successMessage,
|
||||
notification,
|
||||
resetStatus,
|
||||
setLoading,
|
||||
setErrorState,
|
||||
setSuccess,
|
||||
updateProgress,
|
||||
showNotification,
|
||||
clearNotification,
|
||||
getErrorAction,
|
||||
getStageText,
|
||||
formatErrorMessage,
|
||||
handleApiError,
|
||||
],
|
||||
);
|
||||
|
||||
return statusProps;
|
||||
};
|
||||
|
||||
export default useImageStatus;
|
||||
@@ -0,0 +1,752 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { API, showError, showSuccess } from '../../helpers';
|
||||
import { buildImageRequestBody } from '../../constants/imageModelCapabilities';
|
||||
|
||||
/**
|
||||
* 图片生成任务管理 Hook
|
||||
*/
|
||||
export const useImageTaskManagement = () => {
|
||||
// 任务列表
|
||||
const [tasks, setTasks] = useState([]);
|
||||
|
||||
// 加载状态
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// 轮询定时器
|
||||
const pollingTimerRef = useRef(null);
|
||||
|
||||
// 正在轮询的任务ID集合
|
||||
const pollingTasksRef = useRef(new Set());
|
||||
|
||||
// 轮询失败计数器
|
||||
const pollingErrorCountRef = useRef(new Map());
|
||||
|
||||
/**
|
||||
* 将后端任务数据转换为前端格式
|
||||
*/
|
||||
const convertBackendTask = useCallback((backendTask) => {
|
||||
// 解析任务数据
|
||||
let taskData = {};
|
||||
let imageUrl = null;
|
||||
let imageBase64 = null; // 标记是否有base64数据(用于刷新链接功能)
|
||||
let sourceImageUrl = null; // 图生图的原图URL
|
||||
let sourceImageBase64 = null; // 标记是否有原图base64数据
|
||||
let prompt = '';
|
||||
let width = 1024;
|
||||
let height = 1024;
|
||||
|
||||
// 尝试解析 data 字段
|
||||
if (backendTask.data) {
|
||||
try {
|
||||
if (typeof backendTask.data === 'string') {
|
||||
taskData = JSON.parse(backendTask.data);
|
||||
} else {
|
||||
taskData = backendTask.data;
|
||||
}
|
||||
|
||||
// 从 data 中提取图片URL和base64标记
|
||||
if (
|
||||
taskData.data &&
|
||||
Array.isArray(taskData.data) &&
|
||||
taskData.data.length > 0
|
||||
) {
|
||||
const firstImage = taskData.data[0];
|
||||
// 优先使用 url
|
||||
if (firstImage.url) {
|
||||
imageUrl = firstImage.url;
|
||||
}
|
||||
// 记录是否有 b64_json(用于刷新链接功能,不保存完整数据避免内存问题)
|
||||
if (firstImage.b64_json) {
|
||||
imageBase64 = true; // 只保存标记,表示后端有base64数据可用
|
||||
}
|
||||
}
|
||||
// 注意:任务处理中时data只包含请求参数,没有图片URL是正常的
|
||||
|
||||
// 从 properties 或 data 中提取提示词和尺寸
|
||||
prompt = taskData.prompt || backendTask.properties?.input || '';
|
||||
|
||||
// 从 size 字段解析宽高
|
||||
if (taskData.size) {
|
||||
const [w, h] = taskData.size.split('x').map(Number);
|
||||
width = w || 1024;
|
||||
height = h || 1024;
|
||||
}
|
||||
|
||||
// 提取图生图的原图URL和base64标记
|
||||
if (taskData.source_image) {
|
||||
sourceImageUrl = taskData.source_image;
|
||||
}
|
||||
if (taskData.source_image_base64) {
|
||||
// 记录是否有原图base64数据
|
||||
sourceImageBase64 = true;
|
||||
// 如果没有source_image URL,使用base64作为显示(但这会影响性能)
|
||||
// 为了兼容性,暂时保留这个逻辑
|
||||
if (!sourceImageUrl) {
|
||||
sourceImageUrl = taskData.source_image_base64;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse task data:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果从 data 中没有提取到,尝试从 properties 中提取
|
||||
if (!prompt && backendTask.properties?.input) {
|
||||
prompt = backendTask.properties.input;
|
||||
}
|
||||
|
||||
// 映射状态
|
||||
let status = 'processing';
|
||||
if (backendTask.status === 'SUCCESS') {
|
||||
status = 'success';
|
||||
} else if (backendTask.status === 'FAILURE') {
|
||||
status = 'failed';
|
||||
} else if (
|
||||
backendTask.status === 'NOT_START' ||
|
||||
backendTask.status === 'SUBMITTED' ||
|
||||
backendTask.status === 'QUEUED' ||
|
||||
backendTask.status === 'IN_PROGRESS'
|
||||
) {
|
||||
status = 'processing';
|
||||
}
|
||||
|
||||
// 判断生成模式:优先从 taskData.mode 获取,其次从 properties.mode 获取,默认为文生图
|
||||
const mode =
|
||||
taskData.mode || backendTask.properties?.mode || 'text-to-image';
|
||||
|
||||
// 获取模型名称:优先从 taskData.model,其次从 properties.origin_model_name 或 upstream_model_name
|
||||
const model =
|
||||
taskData.model ||
|
||||
backendTask.properties?.origin_model_name ||
|
||||
backendTask.properties?.upstream_model_name ||
|
||||
'unknown';
|
||||
|
||||
const convertedTask = {
|
||||
id: backendTask.task_id || backendTask.id?.toString(),
|
||||
backendId: backendTask.id,
|
||||
prompt: prompt,
|
||||
width: width,
|
||||
height: height,
|
||||
model: model,
|
||||
mode: mode,
|
||||
status: status,
|
||||
createdAt: backendTask.created_at || new Date().toISOString(),
|
||||
imageUrl: imageUrl,
|
||||
imageBase64: imageBase64,
|
||||
sourceImageUrl: sourceImageUrl,
|
||||
sourceImageBase64: sourceImageBase64,
|
||||
progress: parseInt(backendTask.progress) || 0,
|
||||
errorMessage: backendTask.fail_reason || null,
|
||||
quality: taskData.quality,
|
||||
n: taskData.n,
|
||||
negativePrompt: taskData.negative_prompt || taskData.negativePrompt,
|
||||
taskData: taskData,
|
||||
};
|
||||
|
||||
// 如果是成功状态但没有图片URL也没有base64,打印警告
|
||||
if (status === 'success' && !imageUrl && !imageBase64) {
|
||||
console.warn('警告:任务已成功但没有图片数据', {
|
||||
taskId: convertedTask.id,
|
||||
backendTask: backendTask,
|
||||
taskData: taskData,
|
||||
});
|
||||
}
|
||||
|
||||
return convertedTask;
|
||||
}, []);
|
||||
|
||||
// 添加新任务
|
||||
const addTask = useCallback(
|
||||
async (taskData) => {
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const modelName = taskData.model || 'sora_image';
|
||||
let requestData = buildImageRequestBody(modelName, {
|
||||
prompt: taskData.prompt,
|
||||
width: taskData.width,
|
||||
height: taskData.height,
|
||||
quality: taskData.quality,
|
||||
n: taskData.n,
|
||||
negativePrompt: taskData.negativePrompt,
|
||||
mode: taskData.mode || 'text-to-image',
|
||||
});
|
||||
|
||||
// 图生图模式:将图片转换为 base64
|
||||
if (taskData.mode === 'image-to-image' && taskData.referenceImage) {
|
||||
// 获取原始文件对象
|
||||
const file =
|
||||
taskData.referenceImage.fileInstance || taskData.referenceImage;
|
||||
|
||||
// 将文件转换为 base64
|
||||
const base64Image = await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = (error) => reject(error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
requestData.image = base64Image;
|
||||
}
|
||||
|
||||
const response = await API.post('/api/images/generations', requestData);
|
||||
|
||||
console.log('创建任务响应:', response.data);
|
||||
|
||||
// 后端返回任务信息,不是图片URL
|
||||
if (response.data?.success && response.data?.data) {
|
||||
const backendTask = response.data.data;
|
||||
|
||||
// 转换为前端格式并添加到任务列表
|
||||
const newTask = convertBackendTask({
|
||||
id: backendTask.id,
|
||||
task_id: backendTask.task_id,
|
||||
status: backendTask.status,
|
||||
progress: backendTask.progress,
|
||||
created_at: backendTask.created_at,
|
||||
properties: {
|
||||
input: taskData.prompt,
|
||||
model: taskData.model,
|
||||
mode: taskData.mode || 'text-to-image',
|
||||
},
|
||||
});
|
||||
|
||||
setTasks((prev) => [newTask, ...prev]);
|
||||
|
||||
// 将任务添加到轮询列表;终态以服务端为准,前端不再合成本地超时失败
|
||||
pollingTasksRef.current.add(newTask.id);
|
||||
|
||||
showSuccess('图片生成任务已创建,正在生成中...');
|
||||
return newTask.id;
|
||||
} else {
|
||||
throw new Error('Invalid response format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('创建图片生成任务失败:', error);
|
||||
showError(
|
||||
'图片生成失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[convertBackendTask],
|
||||
);
|
||||
|
||||
// 更新任务状态
|
||||
const updateTaskStatus = useCallback(
|
||||
(taskId, status, additionalData = {}) => {
|
||||
setTasks((prev) =>
|
||||
prev.map((task) =>
|
||||
task.id === taskId
|
||||
? {
|
||||
...task,
|
||||
status,
|
||||
...additionalData,
|
||||
}
|
||||
: task,
|
||||
),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 更新单个任务数据
|
||||
const updateTask = useCallback((taskId, updates) => {
|
||||
setTasks((prev) =>
|
||||
prev.map((task) =>
|
||||
task.id === taskId
|
||||
? {
|
||||
...task,
|
||||
...updates,
|
||||
}
|
||||
: task,
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
|
||||
// 刷新任务图片URL
|
||||
// type: 'generated'(生成图,默认)或 'source'(原图,图生图模式)
|
||||
// 支持两种场景:
|
||||
// 1. 有URL时:刷新预签名URL
|
||||
// 2. 无URL但有base64时:上传base64到COS,获取新URL
|
||||
// 3. 无URL且前端无base64标记时:仍然发起请求,让后端从数据库获取base64
|
||||
// silent: 是否静默模式(不显示提示信息)
|
||||
const refreshTaskUrl = useCallback(
|
||||
async (taskId, type = 'generated', silent = false) => {
|
||||
const task = tasks.find((t) => t.id === taskId);
|
||||
if (!task) {
|
||||
if (!silent) showError('任务不存在');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 根据类型确定要刷新的URL
|
||||
const urlToRefresh =
|
||||
type === 'source' ? task.sourceImageUrl : task.imageUrl;
|
||||
|
||||
// 如果URL是base64格式(data: 开头),说明前端保存了base64但还没上传到COS
|
||||
// 这种情况需要上传到COS
|
||||
const isBase64Url = urlToRefresh && urlToRefresh.startsWith('data:');
|
||||
|
||||
try {
|
||||
// 构建请求参数
|
||||
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(taskId)}&type=${type}`;
|
||||
|
||||
// 如果有有效的COS URL(不是base64),传递给后端刷新
|
||||
if (urlToRefresh && !isBase64Url) {
|
||||
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
|
||||
}
|
||||
// 如果URL是空的或者是base64格式,不传url参数,后端会从数据库读取base64并上传
|
||||
|
||||
const response = await API.get(apiUrl);
|
||||
|
||||
if (response.data?.success && response.data?.data?.url) {
|
||||
const newUrl = response.data.data.url;
|
||||
console.log(
|
||||
`${type === 'source' ? '原图' : '生成图'}URL刷新成功,新URL:`,
|
||||
newUrl,
|
||||
);
|
||||
|
||||
// 根据类型更新对应的URL,并清除base64数据(因为已上传到COS)
|
||||
if (type === 'source') {
|
||||
updateTask(taskId, {
|
||||
sourceImageUrl: newUrl,
|
||||
sourceImageBase64: null,
|
||||
});
|
||||
} else {
|
||||
updateTask(taskId, { imageUrl: newUrl, imageBase64: null });
|
||||
}
|
||||
|
||||
if (!silent) showSuccess('链接已刷新');
|
||||
return true;
|
||||
} else {
|
||||
if (!silent) showError('刷新链接失败');
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('刷新URL失败:', error);
|
||||
if (!silent)
|
||||
showError(
|
||||
'刷新链接失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[tasks, updateTask],
|
||||
);
|
||||
|
||||
// 批量刷新所有成功状态任务的图片链接(静默模式,用于页面加载时自动刷新)
|
||||
const refreshAllSuccessUrls = useCallback(
|
||||
async (taskList) => {
|
||||
// 筛选出成功状态的任务
|
||||
const successTasks = taskList.filter((task) => task.status === 'success');
|
||||
|
||||
if (successTasks.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`开始批量刷新 ${successTasks.length} 个任务的图片链接...`);
|
||||
|
||||
// 并发刷新,但限制并发数避免请求过多
|
||||
const BATCH_SIZE = 5;
|
||||
let refreshedCount = 0;
|
||||
|
||||
for (let i = 0; i < successTasks.length; i += BATCH_SIZE) {
|
||||
const batch = successTasks.slice(i, i + BATCH_SIZE);
|
||||
|
||||
await Promise.all(
|
||||
batch.map(async (task) => {
|
||||
try {
|
||||
// 构建请求参数
|
||||
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(task.id)}&type=generated`;
|
||||
|
||||
const urlToRefresh = task.imageUrl;
|
||||
const isBase64Url =
|
||||
urlToRefresh && urlToRefresh.startsWith('data:');
|
||||
|
||||
if (urlToRefresh && !isBase64Url) {
|
||||
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
|
||||
}
|
||||
|
||||
const response = await API.get(apiUrl);
|
||||
|
||||
if (response.data?.success && response.data?.data?.url) {
|
||||
const newUrl = response.data.data.url;
|
||||
updateTask(task.id, { imageUrl: newUrl, imageBase64: null });
|
||||
refreshedCount++;
|
||||
}
|
||||
} catch (error) {
|
||||
// 静默失败,不影响其他任务
|
||||
console.warn(`刷新任务 ${task.id} 链接失败:`, error.message);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (refreshedCount > 0) {
|
||||
console.log(
|
||||
`批量刷新完成,成功刷新 ${refreshedCount} 个任务的图片链接`,
|
||||
);
|
||||
}
|
||||
},
|
||||
[updateTask],
|
||||
);
|
||||
|
||||
// 取消/删除任务
|
||||
const deleteTask = useCallback(
|
||||
async (taskId) => {
|
||||
// 找到任务,判断是否需要调用取消API
|
||||
const task = tasks.find((t) => t.id === taskId);
|
||||
|
||||
// 立即从轮询列表中移除,停止轮询
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
|
||||
// 如果任务正在处理中,调用后端取消API
|
||||
if (task && task.status === 'processing') {
|
||||
try {
|
||||
const response = await API.post(
|
||||
`/api/images/generations/${taskId}/cancel`,
|
||||
);
|
||||
if (response.data?.success) {
|
||||
showSuccess('任务已取消');
|
||||
} else {
|
||||
console.warn('后端取消任务失败:', response.data?.message);
|
||||
showSuccess('任务已从列表中移除');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('取消任务失败:', error);
|
||||
showSuccess('任务已从列表中移除');
|
||||
}
|
||||
} else {
|
||||
// 已完成的任务,调用删除API(软删除)
|
||||
try {
|
||||
const response = await API.delete(
|
||||
`/api/images/generations/${taskId}`,
|
||||
);
|
||||
if (response.data?.success) {
|
||||
showSuccess('任务已删除');
|
||||
} else {
|
||||
console.warn('后端删除任务失败:', response.data?.message);
|
||||
showSuccess('任务已从列表中移除');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除任务失败:', error);
|
||||
showSuccess('任务已从列表中移除');
|
||||
}
|
||||
}
|
||||
|
||||
// 从前端列表中移除
|
||||
setTasks((prev) => prev.filter((t) => t.id !== taskId));
|
||||
},
|
||||
[tasks],
|
||||
);
|
||||
|
||||
// 重试任务 - 使用原任务的参数创建新任务
|
||||
const retryTask = useCallback(
|
||||
async (taskId) => {
|
||||
const task = tasks.find((t) => t.id === taskId);
|
||||
if (!task) {
|
||||
showError('任务不存在');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 检查是否是图生图模式
|
||||
const isImageToImage = task.mode === 'image-to-image';
|
||||
|
||||
// 对于图生图任务,需要有原图数据
|
||||
if (isImageToImage) {
|
||||
// 检查是否有原图数据
|
||||
if (!task.sourceImageUrl) {
|
||||
showError('图生图任务缺少原图数据,无法重试。请重新上传图片');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 如果原图是COS URL(不是base64),无法直接重试
|
||||
if (!task.sourceImageUrl.startsWith('data:')) {
|
||||
showError(
|
||||
'图生图任务的原图已上传到云存储,无法直接重试。请重新上传图片',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// 构建请求数据 — 复用 capability registry 清洗
|
||||
const modelName = task.model || 'sora_image';
|
||||
let requestData = buildImageRequestBody(modelName, {
|
||||
prompt: task.prompt,
|
||||
width: task.width,
|
||||
height: task.height,
|
||||
quality: task.quality,
|
||||
n: task.n,
|
||||
negativePrompt: task.negativePrompt,
|
||||
mode: task.mode || 'text-to-image',
|
||||
});
|
||||
|
||||
// 图生图模式:添加原图数据
|
||||
if (isImageToImage && task.sourceImageUrl) {
|
||||
requestData.image = task.sourceImageUrl;
|
||||
}
|
||||
|
||||
const response = await API.post('/api/images/generations', requestData);
|
||||
|
||||
if (response.data?.success && response.data?.data) {
|
||||
const backendTask = response.data.data;
|
||||
|
||||
// 转换为前端格式并添加到任务列表
|
||||
const newTask = convertBackendTask({
|
||||
id: backendTask.id,
|
||||
task_id: backendTask.task_id,
|
||||
status: backendTask.status,
|
||||
progress: backendTask.progress,
|
||||
created_at: backendTask.created_at,
|
||||
properties: {
|
||||
input: task.prompt,
|
||||
model: task.model,
|
||||
mode: task.mode || 'text-to-image',
|
||||
},
|
||||
});
|
||||
|
||||
setTasks((prev) => [newTask, ...prev]);
|
||||
|
||||
// 将任务添加到轮询列表,并记录开始时间
|
||||
pollingTasksRef.current.add(newTask.id);
|
||||
|
||||
showSuccess('重试任务已创建,正在生成中...');
|
||||
return newTask.id;
|
||||
} else {
|
||||
throw new Error('Invalid response format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('重试任务失败:', error);
|
||||
showError(
|
||||
'重试失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[tasks, convertBackendTask],
|
||||
);
|
||||
|
||||
// 刷新任务列表
|
||||
// autoRefreshUrls: 是否自动刷新成功任务的图片链接(默认 true,首次加载时使用)
|
||||
const refreshTasks = useCallback(
|
||||
async (showNotification = false, autoRefreshUrls = true) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await API.get('/api/images/tasks?page=1&page_size=50');
|
||||
|
||||
console.log('获取任务列表响应:', response.data);
|
||||
|
||||
if (response.data?.success && response.data?.data?.items) {
|
||||
const backendTasks = response.data.data.items;
|
||||
|
||||
// 转换所有任务为前端格式
|
||||
const convertedTasks = backendTasks.map((task) =>
|
||||
convertBackendTask(task),
|
||||
);
|
||||
|
||||
setTasks(convertedTasks);
|
||||
|
||||
// 找出所有正在进行中的任务,添加到轮询列表
|
||||
convertedTasks.forEach((task) => {
|
||||
if (task.status === 'processing') {
|
||||
// 如果任务还没在轮询列表中,添加并记录开始时间
|
||||
if (!pollingTasksRef.current.has(task.id)) {
|
||||
pollingTasksRef.current.add(task.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 自动刷新成功任务的图片链接(在后台静默执行,不阻塞页面)
|
||||
if (autoRefreshUrls) {
|
||||
// 使用 setTimeout 确保不阻塞 UI 渲染
|
||||
setTimeout(() => {
|
||||
refreshAllSuccessUrls(convertedTasks);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
if (showNotification) {
|
||||
showSuccess('刷新成功');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('刷新任务列表失败:', error);
|
||||
if (showNotification) {
|
||||
showError(
|
||||
'刷新失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[convertBackendTask, refreshAllSuccessUrls],
|
||||
);
|
||||
|
||||
// 轮询单个任务状态
|
||||
const pollTaskStatus = useCallback(
|
||||
async (taskId) => {
|
||||
try {
|
||||
const response = await API.get(`/api/images/generations/${taskId}`);
|
||||
|
||||
if (response.data?.success && response.data?.data) {
|
||||
const backendTask = response.data.data;
|
||||
const updatedTask = convertBackendTask(backendTask);
|
||||
|
||||
// 轮询成功,清除错误计数
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
|
||||
// 更新任务状态
|
||||
setTasks((prev) =>
|
||||
prev.map((task) => (task.id === taskId ? updatedTask : task)),
|
||||
);
|
||||
|
||||
// 如果任务已完成(成功或失败),从轮询列表中移除
|
||||
if (
|
||||
updatedTask.status === 'success' ||
|
||||
updatedTask.status === 'failed'
|
||||
) {
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
}
|
||||
|
||||
return updatedTask;
|
||||
} else {
|
||||
// 非终态 API 错误只记录,不把本地状态伪造为失败;后端任务可能仍会成功并扣费。
|
||||
const errorCount =
|
||||
(pollingErrorCountRef.current.get(taskId) || 0) + 1;
|
||||
const errorMessage =
|
||||
response.data?.message || response.data?.error?.message || '';
|
||||
if (errorMessage.toLowerCase().includes('task not found')) {
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
setTasks((prev) =>
|
||||
prev.map((task) =>
|
||||
task.id === taskId
|
||||
? {
|
||||
...task,
|
||||
status: 'failed',
|
||||
errorMessage: '任务不存在',
|
||||
}
|
||||
: task,
|
||||
),
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
pollingErrorCountRef.current.set(taskId, Math.min(errorCount, 3));
|
||||
if (errorCount === 3) {
|
||||
console.warn(`任务 ${taskId} 状态暂时无法获取,将继续轮询`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`轮询任务 ${taskId} 状态失败:`, error);
|
||||
|
||||
// 增加错误计数
|
||||
const errorCount = (pollingErrorCountRef.current.get(taskId) || 0) + 1;
|
||||
pollingErrorCountRef.current.set(taskId, Math.min(errorCount, 3));
|
||||
|
||||
// 如果是404错误,直接停止轮询
|
||||
if (error.response?.status === 404) {
|
||||
console.warn(`任务 ${taskId} 不存在,停止轮询`);
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
|
||||
// 更新任务状态为失败
|
||||
setTasks((prev) =>
|
||||
prev.map((task) =>
|
||||
task.id === taskId
|
||||
? { ...task, status: 'failed', errorMessage: '任务不存在' }
|
||||
: task,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (errorCount === 3) {
|
||||
console.warn(`任务 ${taskId} 状态暂时无法获取,将继续轮询`);
|
||||
}
|
||||
}
|
||||
},
|
||||
[convertBackendTask],
|
||||
);
|
||||
|
||||
// 轮询所有进行中的任务
|
||||
const pollAllTasks = useCallback(async () => {
|
||||
const tasksToPool = Array.from(pollingTasksRef.current);
|
||||
|
||||
if (tasksToPool.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('轮询任务:', tasksToPool);
|
||||
|
||||
// 并发轮询所有任务
|
||||
await Promise.all(tasksToPool.map((taskId) => pollTaskStatus(taskId)));
|
||||
}, [pollTaskStatus]);
|
||||
|
||||
// 启动轮询定时器
|
||||
useEffect(() => {
|
||||
// 组件挂载时加载任务列表
|
||||
refreshTasks();
|
||||
|
||||
// 设置定时器,每5秒轮询一次
|
||||
pollingTimerRef.current = setInterval(() => {
|
||||
pollAllTasks();
|
||||
}, 5000);
|
||||
|
||||
// 清理函数
|
||||
return () => {
|
||||
if (pollingTimerRef.current) {
|
||||
clearInterval(pollingTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [refreshTasks, pollAllTasks]);
|
||||
|
||||
// 清空所有任务
|
||||
const clearAllTasks = useCallback(() => {
|
||||
setTasks([]);
|
||||
showSuccess('已清空所有任务');
|
||||
}, []);
|
||||
|
||||
return {
|
||||
tasks,
|
||||
loading,
|
||||
addTask,
|
||||
updateTaskStatus,
|
||||
deleteTask,
|
||||
retryTask,
|
||||
refreshTasks,
|
||||
refreshTaskUrl,
|
||||
clearAllTasks,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user