Files
monkey-ai-web/src/hooks/playground/useFileUpload.js
T

464 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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 { useCallback, useRef, useState } from 'react';
import { Toast } from '@/components/ui';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
// 唯一 ID 生成(不依赖 crypto.randomUUID 以兼容旧浏览器)
const genId = () =>
`f_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
// 仅当图片上传失败原因看起来是临时性的(网络中断、5xx)时才回退到 base64
// 业务错误(4xx,含 401/403/413/429)保留 failed 状态让用户重试或换文件
const isTransientError = (err) => {
const status = err?.response?.status;
return !status || status >= 500;
};
// 后端如果在错误里返回了真实的 max_size_mb,优先用它显示
const extractMaxSize = (err, fallback) => {
const raw = err?.response?.data?.data?.max_size_mb;
const n = parseInt(raw, 10);
return Number.isFinite(n) && n > 0 ? n : fallback;
};
// 给图片生成 96px 长边的缩略图,用于附件 chip 上的预览
const buildImageThumbnail = (file) =>
new Promise((resolve) => {
if (!file || !file.type?.startsWith('image/')) {
resolve(null);
return;
}
try {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const MAX = 96;
const scale = Math.min(MAX / img.width, MAX / img.height, 1);
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
try {
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
resolve(canvas.toDataURL('image/jpeg', 0.7));
} catch {
resolve(event.target.result);
}
};
img.onerror = () => resolve(null);
img.src = event.target.result;
};
reader.onerror = () => resolve(null);
reader.readAsDataURL(file);
} catch {
resolve(null);
}
});
const readAsDataURL = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
/**
* useFileUpload — 体验中心文件上传统一 Hook
*
* 状态:files 数组,每项 { id, name, size, fileType, status, progress, url, thumbnail, error, _rawFile, _abort }
* - fileType: 'image' | 'file'
* - status: 'uploading' | 'success' | 'failed'
* - progress: 0..1(axios 真实上传进度)
*
* @param {object} opts
* @param {number} opts.maxSizeMB 单文件大小上限(MB)
* @param {number} opts.maxCount 队列最大容量(默认 10)
* @param {(file)=>void} opts.onSuccess 每个文件传完后回调(拿到 url/type 写入消息附件区)
*/
export const useFileUpload = ({ maxSizeMB, maxCount = 10, onSuccess } = {}) => {
const { t } = useTranslation();
const [files, setFiles] = useState([]);
// 用 ref 保证 retry/remove 在闭包里看到最新列表
const filesRef = useRef([]);
filesRef.current = files;
// 双击 retry 的硬隔离:React 的 setState 不是同步 commit 的,filesRef 在两次同步点击之间
// 可能还来不及刷成 'uploading',下面 retry 检查 entry.status 就会漏判。用同步 Set 兜底,
// 进入 runUpload 时立刻 add,结束时(成功/失败/取消)remove。
const inFlightIds = useRef(new Set());
const updateFile = useCallback((id, patch) => {
setFiles((prev) => {
const next = prev.map((f) => (f.id === id ? { ...f, ...patch } : f));
filesRef.current = next;
return next;
});
}, []);
const replaceFiles = useCallback((updater) => {
setFiles((prev) => {
const next = typeof updater === 'function' ? updater(prev) : updater;
filesRef.current = next;
return next;
});
}, []);
// 执行单个文件的真实上传(被 add 和 retry 共用)
const runUpload = useCallback(
async (entry) => {
if (!entry || !entry._rawFile) return;
// 同步占位 — 任何并发 retry 都会被 retry() 的 inFlight 检查挡住
inFlightIds.current.add(entry.id);
const rawFile = entry._rawFile;
const abortCtrl = new AbortController();
updateFile(entry.id, {
status: 'uploading',
progress: 0,
error: null,
_abort: abortCtrl,
});
try {
const formData = new FormData();
formData.append('file', rawFile);
const res = await API.post('/api/user/upload/file', formData, {
skipErrorHandler: true,
signal: abortCtrl.signal,
onUploadProgress: (e) => {
if (!e.total) return;
updateFile(entry.id, {
progress: Math.min(0.99, e.loaded / e.total),
});
},
});
if (res?.data?.success) {
const url = res.data.data.url;
updateFile(entry.id, {
status: 'success',
progress: 1,
url,
error: null,
_abort: null,
_rawFile: null, // 释放内存
});
onSuccess?.({
name: entry.name,
size: entry.size,
type: entry.fileType,
url,
thumbnail: entry.thumbnail,
});
// 老二进制 Office 格式(.doc/.ppt/.xls)OpenAI 解析率极低,
// 大概率"模型说看不到文件内容",给用户一次明确提示,引导改用新格式
const lowerName = (entry.name || '').toLowerCase();
if (/\.(doc|ppt|xls)$/.test(lowerName)) {
const newFormat = lowerName.endsWith('.doc')
? '.docx'
: lowerName.endsWith('.ppt')
? '.pptx'
: '.xlsx';
Toast.warning({
content: t(
'老格式 {{old}} 大模型解析效果不佳,建议另存为 {{new}} 后再上传',
{
old: lowerName.match(/\.(doc|ppt|xls)$/)[0],
new: newFormat,
},
),
// 6 秒:默认 3 秒会让用户在阅读完文件名前就消失。chip 上还有持久角标兜底,
// 但 Toast 是上传完瞬间的提醒,必须让用户来得及看完
duration: 6,
});
}
return;
}
// 后端返回 success=false(业务错)
const message = res?.data?.message || t('文件上传失败');
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: message,
_abort: null,
});
Toast.error({ content: message, duration: 3 });
} catch (err) {
// 取消请求 → 直接移除条目(取消由 abort() 触发,无需 toast)
if (
err?.name === 'CanceledError' ||
err?.code === 'ERR_CANCELED' ||
abortCtrl.signal.aborted
) {
replaceFiles((prev) => prev.filter((f) => f.id !== entry.id));
return;
}
// 临时错误 + 是图片 → 自动回退 base64,仍可送入对话
if (entry.fileType === 'image' && isTransientError(err)) {
try {
const dataUrl = await readAsDataURL(rawFile);
updateFile(entry.id, {
status: 'success',
progress: 1,
url: dataUrl,
error: null,
_abort: null,
_rawFile: null,
});
onSuccess?.({
name: entry.name,
size: entry.size,
type: 'image',
url: dataUrl,
thumbnail: entry.thumbnail || dataUrl,
fromLocalFallback: true,
});
Toast.info({
content: t('网络异常,图片以本地数据上送'),
duration: 3,
});
return;
} catch {
// fall through to failed state
}
}
// 文件超大 → 显示后端返回的真实限制
if (
err?.response?.status === 400 &&
err?.response?.data?.data?.max_size_mb
) {
const limit = extractMaxSize(err, maxSizeMB);
const msg = t('文件大小不能超过 {{size}}MB', { size: limit });
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: msg,
_abort: null,
});
Toast.error({ content: msg, duration: 3 });
return;
}
// 限流 / 鉴权 / 服务器错误
const status = err?.response?.status;
let message =
err?.response?.data?.message || t('文件上传失败,请稍后重试');
if (status === 429) message = t('上传太频繁,请稍后再试');
if (status === 401) message = t('登录已过期,请重新登录');
if (status === 403) message = t('没有上传权限');
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: message,
_abort: null,
});
Toast.error({ content: message, duration: 3 });
} finally {
inFlightIds.current.delete(entry.id);
}
},
[updateFile, replaceFiles, onSuccess, maxSizeMB, t],
);
/**
* upload — 接收一个 FileList / File[] 并行上传
* 自动做:大小校验、数量校验、同名同大小去重、图片缩略图、并行 axios 上传
*/
const upload = useCallback(
async (rawFiles) => {
const arr = Array.from(rawFiles || []);
if (arr.length === 0) return;
const current = filesRef.current;
const slotsLeft = Math.max(0, maxCount - current.length);
if (slotsLeft === 0) {
Toast.warning({
content: t('附件数量已达上限({{max}} 个)', { max: maxCount }),
duration: 3,
});
return;
}
const accepted = [];
for (const file of arr) {
if (accepted.length >= slotsLeft) {
Toast.warning({
content: t('附件数量已达上限({{max}} 个)', { max: maxCount }),
duration: 3,
});
break;
}
// 大小校验:本地阈值,后端会再校验一次
const limitMB = maxSizeMB || 10;
if (file.size > limitMB * 1024 * 1024) {
Toast.error({
content: t('文件「{{name}}」超过 {{size}}MB 限制', {
name: file.name,
size: limitMB,
}),
duration: 3,
});
continue;
}
// 去重:同名 + 同大小视为重复
const dup = [...current, ...accepted].some(
(f) => f.name === file.name && f.size === file.size,
);
if (dup) {
Toast.info({
content: t('文件「{{name}}」已添加', { name: file.name }),
duration: 2,
});
continue;
}
accepted.push({
id: genId(),
name: file.name,
size: file.size,
// SVG 虽然 MIME 是 image/*,但本质是 XML 文本,多数大模型不接受 SVG 作为
// input_image(OpenAI vision 会返 "invalid image"),所以当 file 处理走文件分支。
fileType:
file.type?.startsWith('image/') && file.type !== 'image/svg+xml'
? 'image'
: 'file',
status: 'uploading',
progress: 0,
url: null,
thumbnail: null,
error: null,
_rawFile: file,
_abort: null,
});
}
if (accepted.length === 0) return;
// 先入队(UI 立即反馈),再异步起上传
replaceFiles((prev) => [...prev, ...accepted]);
// 并行起:缩略图 + 真实上传,每个文件独立
await Promise.all(
accepted.map(async (entry) => {
// 图片预生成缩略图(不阻塞上传)
if (entry.fileType === 'image') {
buildImageThumbnail(entry._rawFile).then((thumb) => {
if (thumb) updateFile(entry.id, { thumbnail: thumb });
});
}
await runUpload(entry);
}),
);
},
[maxCount, maxSizeMB, replaceFiles, runUpload, updateFile, t],
);
const retry = useCallback(
(id) => {
const entry = filesRef.current.find((f) => f.id === id);
if (!entry) return;
// 与 entry.status 双重保险:inFlightIds 是同步状态,能挡住 React 还没 flush 的并发点击
if (entry.status === 'uploading' || inFlightIds.current.has(id)) return;
if (!entry._rawFile) {
Toast.error({ content: t('原文件已释放,请重新选择'), duration: 3 });
return;
}
runUpload(entry);
},
[runUpload, t],
);
const remove = useCallback(
(id) => {
const entry = filesRef.current.find((f) => f.id === id);
if (!entry) return null;
const wasUploading = entry.status === 'uploading';
if (entry._abort) {
try {
entry._abort.abort();
} catch {
/* ignore */
}
}
replaceFiles((prev) => prev.filter((f) => f.id !== id));
// 返回被删条目供 UI 层做 undo —— uploading 状态的 abort 不可逆,返回 null 表示
// "无法撤销",调用方据此决定是否显示撤销按钮
return wasUploading ? null : entry;
},
[replaceFiles],
);
// 把被 remove 还回去的条目重新挂回列表末尾。简单实现:append 而不还原原 index,
// 避免在频繁删除时维护精确位置的复杂度;用户感受是"它回来了",足够好。
// 如果同 id 已经存在(罕见,比如用户飞快重传同名文件)就静默忽略不重复加。
const restore = useCallback(
(entry) => {
if (!entry || !entry.id) return;
replaceFiles((prev) => {
if (prev.some((f) => f.id === entry.id)) return prev;
return [...prev, entry];
});
},
[replaceFiles],
);
const clearAll = useCallback(() => {
filesRef.current.forEach((f) => {
if (f._abort) {
try {
f._abort.abort();
} catch {
/* ignore */
}
}
});
replaceFiles([]);
}, [replaceFiles]);
// clearSucceeded:仅清掉已成功发送的附件,保留失败状态的让用户继续重试 / 移除。
// 用在"发送完消息后"的场景 —— 用户明确感知到的成功附件已经走出去了,但失败的还没被处理,
// 一并清掉等于把用户的重试机会偷偷拿走。
const clearSucceeded = useCallback(() => {
replaceFiles((prev) => prev.filter((f) => f.status !== 'success'));
}, [replaceFiles]);
const isUploading = files.some((f) => f.status === 'uploading');
return {
files,
upload,
retry,
remove,
restore,
clearAll,
clearSucceeded,
isUploading,
};
};
export default useFileUpload;