修改上传文件,上传封面图,上传urdf过滤文件

This commit is contained in:
2026-10-28 16:31:42 +08:00
parent c02faf30a7
commit 6783858383
17 changed files with 713 additions and 43 deletions
+2 -2
View File
@@ -49,9 +49,9 @@ DevTools 中 `preflight` 是浏览器发送的 OPTIONS 跨域预检,`fetch`
- 用户管理:列表筛选、详情、名下项目、编辑昵称、启用/禁用(不可禁用自己与官方账号)
- 项目管理:列表筛选、新建(封面 OSS 直传、归属官方或普通用户)、编辑、删除
- 发布 / 更新发布 / 撤回 / 下架 / 解除下架(发布前确认当前 main SHA,409 冲突需刷新重新确认)
- 文件:目录浏览、预览(文本/图片)、在线编辑提交、新建文件/目录、删除文件、多文件/文件夹上传(含限额与路径预检)、鉴权下载
- 文件:目录浏览、预览(文本/图片)、在线编辑提交、新建文件/目录、删除文件、多文件/文件夹上传(单次合计 ≤ 1 GiB,含选择、限额与路径预检、进度反馈)、鉴权下载
- 提交历史,并可只读浏览任一历史版本
- URDF 目录上传绑定(签名 → 并发 OSS 直传 → 确认)与移除
- URDF 目录上传绑定(签名 → 并发 OSS 直传 → 确认)与移除;项目详情和迁移页均按扩展名保留 URDF、模型、材质、贴图及模型数据,过滤代码、文档、配置、隐藏文件和依赖目录,数量/大小限制仅计算待上传资源
- GitHub 迁移:预检 → 补充信息(可选上传封面、URDF)→ 创建任务并绑定资源 → 3 秒串行轮询阶段 → 检查后手动发布;重复来源跳转已有项目
- 迁移重试:`FAILED`、`REVIEW` 始终提供手动重试入口,不按 `canRetry` 隐藏;列表点击重试即进入任务确认框,展示 `retryMessage`,由重试接口判断是否受理;支持 `CLEANING` 清理阶段,409 后刷新状态,网络异常时先查询确认结果
+2 -1
View File
@@ -8,7 +8,8 @@ location ^~ /admin-api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 60m;
# 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。
client_max_body_size 1100m;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
+2 -1
View File
@@ -8,7 +8,8 @@ location ^~ /admin-api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 60m;
# 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。
client_max_body_size 1100m;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
+2 -1
View File
@@ -13,7 +13,8 @@ server {
root /usr/share/nginx/vibemake-admin;
index index.html;
client_max_body_size 60m;
# 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。
client_max_body_size 1100m;
# 后台接口反向代理
location ^~ /admin-api/ {
+2 -1
View File
@@ -13,7 +13,8 @@ server {
root /usr/share/nginx/vibemake-admin;
index index.html;
client_max_body_size 60m;
# 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。
client_max_body_size 1100m;
# 后台接口反向代理
location ^~ /admin-api/ {
+20 -7
View File
@@ -1,4 +1,5 @@
import { downloadAdmin, queryString, requestAdmin, setToken, uploadOssFile } from './request';
import { downloadAdmin, queryString, requestAdmin, requestAdminUpload, setToken, uploadOssFile } from './request';
import { compressCoverImage } from '@/utils/compressImage';
import type {
AdminView,
CommitInput,
@@ -139,6 +140,7 @@ export function uploadProjectFiles(
message: string,
selected: SelectedFile[],
directory = '',
onProgress?: (loaded: number, total: number) => void,
): Promise<CommitView> {
const form = new FormData();
form.append('expectedCommitSha', expectedCommitSha);
@@ -148,19 +150,30 @@ export function uploadProjectFiles(
form.append('files', item.file, item.file.name);
form.append('paths', item.relativePath);
}
return requestAdmin<CommitView>(`/projects/${enc(code)}/uploads/commit`, {
method: 'POST',
body: form,
});
const totalBytes = selected.reduce((sum, item) => sum + item.file.size, 0);
return requestAdminUpload<CommitView>(
`/projects/${enc(code)}/uploads/commit`,
form,
(loaded, requestTotal) => {
if (!onProgress) return;
if (!requestTotal) {
onProgress(0, totalBytes);
return;
}
onProgress(Math.min(totalBytes, Math.round((loaded / requestTotal) * totalBytes)), totalBytes);
},
() => onProgress?.(totalBytes, totalBytes),
);
}
// ---------- 封面 ----------
export async function uploadCover(file: File): Promise<string> {
const uploadFile = await compressCoverImage(file);
const signature = await requestAdmin<CoverUploadSignature>('/uploads/project-covers/signature', {
method: 'POST',
body: { contentType: file.type, fileSize: file.size },
body: { contentType: uploadFile.type, fileSize: uploadFile.size },
});
await uploadOssFile(signature.uploadUrl, signature.formFields, file);
await uploadOssFile(signature.uploadUrl, signature.formFields, uploadFile);
return signature.coverUrl;
}
+55
View File
@@ -80,6 +80,61 @@ export async function requestAdmin<T>(path: string, options: AdminRequestOptions
return result.data;
}
/** 带上传进度的管理端 multipart 请求。XHR 才能监听请求体上传进度。 */
export function requestAdminUpload<T>(
path: string,
body: FormData,
onProgress?: (loaded: number, total: number) => void,
onUploadComplete?: () => void,
): Promise<T> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
let lastTotal = 0;
let uploadComplete = false;
const signalUploadComplete = () => {
if (uploadComplete) return;
uploadComplete = true;
if (lastTotal > 0) onProgress?.(lastTotal, lastTotal);
onUploadComplete?.();
};
xhr.open('POST', `${ADMIN_API_BASE}${path}`);
buildHeaders().forEach((value, key) => xhr.setRequestHeader(key, value));
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) lastTotal = event.total;
onProgress?.(event.loaded, event.lengthComputable ? event.total : 0);
};
xhr.upload.onload = signalUploadComplete;
xhr.upload.onloadend = signalUploadComplete;
xhr.onerror = () => reject(new TypeError('网络异常,请检查网络后刷新确认结果'));
xhr.onabort = () => reject(new DOMException('请求已取消', 'AbortError'));
xhr.onload = () => {
let result: ApiResponse<T> | null = null;
try {
result = JSON.parse(xhr.responseText || 'null') as ApiResponse<T> | null;
} catch {
// Keep response parsing failures on the normal API error path.
}
if (xhr.status < 200 || xhr.status >= 300 || result?.code !== 'OK') {
handle401(path, xhr.status);
reject(new AdminApiError(
xhr.status,
result?.code ?? 'INVALID_RESPONSE',
result?.message ?? `服务响应异常(HTTP ${xhr.status}),请稍后查看状态`,
result?.requestId ?? xhr.getResponseHeader('X-Request-Id'),
result?.data,
));
return;
}
resolve(result.data);
};
try {
xhr.send(body);
} catch (error) {
reject(error);
}
});
}
/** 带鉴权的二进制下载,不经过 JSON 解包 */
export async function downloadAdmin(path: string, fallbackName: string): Promise<void> {
const response = await fetch(`${ADMIN_API_BASE}${path}`, { headers: buildHeaders() });
+1 -1
View File
@@ -15,7 +15,7 @@ export default function ProjectFields({ types }: { types: TypeView[] }) {
<Form.Item name="projectType" label="项目类型" rules={[{ required: true, message: '请选择项目类型' }]}>
<Select placeholder="请选择" options={types.map((t) => ({ value: t.code, label: t.name }))} style={{ maxWidth: 320 }} />
</Form.Item>
<Form.Item name="coverUrl" label="封面" extra="JPG / PNG / WEBP,最大 5 MiB">
<Form.Item name="coverUrl" label="封面" extra="JPG / PNG / WEBP,原图最大 5 MiB,上传后自动优化">
<CoverUpload />
</Form.Item>
</>
+111 -22
View File
@@ -10,6 +10,7 @@ import {
Input,
Modal,
Popconfirm,
Progress,
Space,
Table,
Tag,
@@ -30,6 +31,10 @@ import { AdminApiError } from '@/api/request';
import { errorText, formatSize, MiB, shortSha, utf8Bytes } from '@/utils/format';
import FileViewer from './FileViewer';
import { joinPath, pickFiles, toSelected, validatePath } from './pickFiles';
import {
MAX_PROJECT_UPLOAD_FILE,
validateProjectUpload,
} from './projectUpload';
interface Props {
projectCode: string;
@@ -326,36 +331,55 @@ function UploadModal({
onDone: (sha: string) => void;
}) {
const { message } = App.useApp();
const [keepRoot, setKeepRoot] = useState(true);
const [keepRoot, setKeepRoot] = useState(false);
const [commitMsg, setCommitMsg] = useState('');
const [loading, setLoading] = useState(false);
const [checkedIndexes, setCheckedIndexes] = useState<Set<number>>(new Set());
const [progress, setProgress] = useState<{
loaded: number;
total: number;
status: 'uploading' | 'processing' | 'error';
} | null>(null);
useEffect(() => {
setKeepRoot(true);
setKeepRoot(false);
setCheckedIndexes(new Set(files?.map((_, index) => index) ?? []));
setCommitMsg(files ? `上传 ${files.length} 个文件` : '');
setLoading(false);
setProgress(null);
}, [files]);
if (!files) return null;
const isDir = files.some((f) => (f.file as File & { webkitRelativePath?: string }).webkitRelativePath);
const selected = isDir ? toSelected(files.map((f) => f.file), keepRoot) : files;
const allFiles = isDir ? toSelected(files.map((f) => f.file), keepRoot) : files;
const selected = allFiles.filter((_, index) => checkedIndexes.has(index));
const total = selected.reduce((s, f) => s + f.file.size, 0);
const tooBig = selected.filter((f) => f.file.size > 50 * MiB);
const pathErrors = selected.map((f) => validatePath(joinPath(dir, f.relativePath))).filter(Boolean);
const problems = [
selected.length > 500 && '单次最多 500 个文件,请分批上传',
total > 200 * MiB && `合计 ${formatSize(total)},超过 200 MiB,请分批上传`,
tooBig.length > 0 && `${tooBig.length} 个文件超过单文件 50 MiB 限制:${tooBig.slice(0, 3).map((f) => f.relativePath).join('、')}`,
pathErrors.length > 0 && `存在非法路径:${pathErrors[0]}`,
].filter(Boolean) as string[];
const problems = validateProjectUpload(selected, dir);
const allChecked = allFiles.length > 0 && checkedIndexes.size === allFiles.length;
const partiallyChecked = checkedIndexes.size > 0 && !allChecked;
const submit = async () => {
if (!commitMsg.trim()) return message.warning('请填写提交说明');
if (problems.length > 0) return;
setLoading(true);
setProgress({ loaded: 0, total, status: 'uploading' });
try {
const res = await api.uploadProjectFiles(projectCode, expectedSha, commitMsg.trim(), selected, dir);
const res = await api.uploadProjectFiles(
projectCode,
expectedSha,
commitMsg.trim(),
selected,
dir,
(loaded, uploadTotal) => setProgress({
loaded,
total: uploadTotal || total,
status: uploadTotal > 0 && loaded >= uploadTotal ? 'processing' : 'uploading',
}),
);
message.success(`上传成功,新版本 ${shortSha(res.commitSha)}`);
onDone(res.commitSha);
} catch (e) {
setProgress((current) => current ? { ...current, status: 'error' } : { loaded: 0, total, status: 'error' });
message.error(errorText(e));
} finally {
setLoading(false);
@@ -367,29 +391,94 @@ function UploadModal({
title="上传文件"
open
width={760}
closable={!loading}
onCancel={loading ? undefined : onClose}
maskClosable={false}
footer={[
<Button key="c" onClick={onClose} disabled={loading}>取消</Button>,
<Button key="o" type="primary" loading={loading} disabled={problems.length > 0} onClick={submit}>提交上传</Button>,
<Button key="o" type="primary" loading={loading} disabled={problems.length > 0 || loading} onClick={submit}>提交上传</Button>,
]}
>
<Space direction="vertical" style={{ width: '100%' }}>
<Typography.Text>
目标目录:<span className="mono">{dir || '(根目录)'}</span> · {selected.length} 个文件 · {formatSize(total)}
</Typography.Text>
{isDir && <Checkbox checked={keepRoot} onChange={(e) => setKeepRoot(e.target.checked)}>保留所选文件夹名称</Checkbox>}
{isDir && (
<Checkbox checked={keepRoot} disabled={loading} onChange={(e) => setKeepRoot(e.target.checked)}>
保留所选文件夹名称
</Checkbox>
)}
{problems.map((p) => <Alert key={p} type="error" showIcon message={p} />)}
<Typography.Text type="secondary">同名路径会覆盖已有文件。最终路径预览:</Typography.Text>
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
<Typography.Text type="secondary">同名路径会覆盖已有文件。最终路径预览:</Typography.Text>
<Checkbox
checked={allChecked}
indeterminate={partiallyChecked}
disabled={loading || allFiles.length === 0}
onChange={(e) => setCheckedIndexes(e.target.checked ? new Set(allFiles.map((_, index) => index)) : new Set())}
>
全选
</Checkbox>
</Space>
<div style={{ maxHeight: 260, overflow: 'auto', border: '1px solid #f0f0f0', borderRadius: 6, padding: 8 }}>
{selected.map((f) => (
<div key={f.relativePath} className="mono" style={{ fontSize: 12, display: 'flex', justifyContent: 'space-between' }}>
<span>{joinPath(dir, f.relativePath)}</span>
<span style={{ color: f.file.size > 50 * MiB ? '#ff4d4f' : '#999' }}>{formatSize(f.file.size)}</span>
</div>
))}
{allFiles.map((f, index) => {
const checked = checkedIndexes.has(index);
return (
<div
key={index}
className="mono"
style={{
fontSize: 12,
display: 'flex',
alignItems: 'center',
gap: 8,
opacity: checked ? 1 : 0.5,
}}
>
<Checkbox
checked={checked}
disabled={loading}
aria-label={`选择 ${joinPath(dir, f.relativePath)}`}
onChange={(e) => setCheckedIndexes((current) => {
const next = new Set(current);
if (e.target.checked) next.add(index);
else next.delete(index);
return next;
})}
/>
<span style={{ flex: 1, minWidth: 0, overflowWrap: 'anywhere' }}>{joinPath(dir, f.relativePath)}</span>
<span style={{ color: f.file.size > MAX_PROJECT_UPLOAD_FILE ? '#ff4d4f' : '#999', whiteSpace: 'nowrap' }}>
{formatSize(f.file.size)}
</span>
</div>
);
})}
</div>
<Input placeholder="提交说明(必填)" value={commitMsg} maxLength={1000} onChange={(e) => setCommitMsg(e.target.value)} />
{progress && (
<div>
<Typography.Text>
{progress.status === 'error'
? '上传失败,可修改选择后重试'
: progress.status === 'processing'
? '正在处理并提交版本'
: '正在上传文件'}
</Typography.Text>
<Progress
status={progress.status === 'error' ? 'exception' : 'active'}
percent={progress.total > 0 ? Math.min(100, Math.round((progress.loaded / progress.total) * 100)) : 0}
format={() => progress.status === 'processing'
? '正在处理'
: `${formatSize(progress.loaded)} / ${formatSize(progress.total)}`}
/>
</div>
)}
<Input
placeholder="提交说明(必填)"
value={commitMsg}
maxLength={1000}
disabled={loading}
onChange={(e) => setCommitMsg(e.target.value)}
/>
</Space>
</Modal>
);
+20 -6
View File
@@ -4,6 +4,7 @@ import { CloseOutlined, FolderOpenOutlined } from '@ant-design/icons';
import type { SelectedFile } from '@/api/types';
import { formatSize, MiB } from '@/utils/format';
import { pickFiles, toSelected, validatePath } from './pickFiles';
import { filterUrdfFiles } from './urdfFiles';
export interface UrdfSelection {
selected: SelectedFile[];
@@ -26,7 +27,15 @@ export function checkUrdf(selected: SelectedFile[]): string[] {
].filter(Boolean) as string[];
}
/** URDF 目录选择:生成相对路径清单并展示校验结果 */
function getUrdfSelection(files: File[], keepRoot: boolean): UrdfSelection {
const selected = toSelected(filterUrdfFiles(files), keepRoot);
const problems = files.length > 0 && selected.length === 0
? ['所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择']
: checkUrdf(selected);
return { selected, problems };
}
/** URDF 目录选择:过滤非渲染资源,生成相对路径清单并展示校验结果 */
export default function UrdfDirPicker({
onChange,
disabled,
@@ -37,13 +46,12 @@ export default function UrdfDirPicker({
const [raw, setRaw] = useState<File[]>([]);
const [keepRoot, setKeepRoot] = useState(false);
const selected = useMemo(() => toSelected(raw, keepRoot), [raw, keepRoot]);
const problems = useMemo(() => checkUrdf(selected), [selected]);
const { selected, problems } = useMemo(() => getUrdfSelection(raw, keepRoot), [raw, keepRoot]);
const filteredCount = raw.length - selected.length;
const total = selected.reduce((s, f) => s + f.file.size, 0);
const emit = (files: File[], keep: boolean) => {
const sel = toSelected(files, keep);
onChange({ selected: sel, problems: checkUrdf(sel) });
onChange(getUrdfSelection(files, keep));
};
const choose = async () => {
@@ -69,6 +77,9 @@ export default function UrdfDirPicker({
<Button type="text" icon={<CloseOutlined />} onClick={clear} disabled={disabled}>清除</Button>
)}
</Space>
<Typography.Text type="secondary">
支持 URDF、STL/DAE/OBJ、GLTF/GLB/FBX/PLY、MTL、BIN 及常见贴图;自动过滤代码、文档、配置和隐藏文件。
</Typography.Text>
{raw.length > 0 && (
<>
<Space wrap>
@@ -82,7 +93,10 @@ export default function UrdfDirPicker({
>
保留所选文件夹名称
</Checkbox>
<Typography.Text type="secondary">{selected.length} 个文件 · {formatSize(total)}</Typography.Text>
<Typography.Text type="secondary">
待上传 {selected.length} 个文件 · {formatSize(total)}
{filteredCount > 0 && ` · 已过滤 ${filteredCount} 个无关文件`}
</Typography.Text>
</Space>
<div className="file-list">
{selected.map((f) => (
+28
View File
@@ -0,0 +1,28 @@
import type { SelectedFile } from '@/api/types';
import { joinPath, validatePath } from './pickFiles';
const MiB = 1024 * 1024;
export const MAX_PROJECT_UPLOAD_TOTAL = 1024 * MiB;
export const MAX_PROJECT_UPLOAD_FILE = 50 * MiB;
export const MAX_PROJECT_UPLOAD_COUNT = 500;
function formatProjectSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < MiB) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / MiB).toFixed(2)} MB`;
}
export function validateProjectUpload(selected: SelectedFile[], directory: string): string[] {
const total = selected.reduce((sum, item) => sum + item.file.size, 0);
const tooBig = selected.filter((item) => item.file.size > MAX_PROJECT_UPLOAD_FILE);
const pathError = selected
.map((item) => validatePath(joinPath(directory, item.relativePath)))
.find(Boolean);
return [
selected.length === 0 && '至少选择一个文件',
selected.length > MAX_PROJECT_UPLOAD_COUNT && `单次最多 ${MAX_PROJECT_UPLOAD_COUNT} 个文件,请分批上传`,
total > MAX_PROJECT_UPLOAD_TOTAL && `合计 ${formatProjectSize(total)},超过 1 GiB,请分批上传`,
tooBig.length > 0 && `${tooBig.length} 个文件超过单文件 50 MiB 限制:${tooBig.slice(0, 3).map((item) => item.relativePath).join('、')}`,
pathError && `存在非法路径:${pathError}`,
].filter(Boolean) as string[];
}
+23
View File
@@ -0,0 +1,23 @@
// URDF 预览可能依赖模型、材质、外部二进制数据和贴图;按扩展名保留资源,
// 不改写相对路径,避免破坏 URDF → mesh → 材质/贴图之间的引用。
const RENDER_EXTENSIONS = new Set([
'urdf',
'stl', 'dae', 'obj', 'gltf', 'glb', 'fbx', 'ply', '3ds', '3mf',
'mtl', 'bin', 'drc',
'png', 'jpg', 'jpeg', 'jpe', 'jfif', 'webp', 'avif', 'bmp', 'gif',
'tga', 'tif', 'tiff', 'dds', 'ktx', 'ktx2', 'basis', 'hdr', 'exr', 'svg',
]);
/** 过滤 URDF 目录中的非渲染资源,以及隐藏文件、依赖目录和系统元数据。 */
export function filterUrdfFiles(files: File[]): File[] {
return files.filter((file) => {
const path = file.webkitRelativePath || file.name;
const parts = path.split('/');
if (parts.some((part) => part.startsWith('.') || part === '__MACOSX' || part === 'node_modules')) {
return false;
}
const name = parts[parts.length - 1];
const dot = name.lastIndexOf('.');
return dot > 0 && RENDER_EXTENSIONS.has(name.slice(dot + 1).toLowerCase());
});
}
+89
View File
@@ -0,0 +1,89 @@
export const COVER_MAX_BYTES = 5 * 1024 * 1024;
const MAX_WIDTH = 768;
const MAX_HEIGHT = 480;
const TARGET_BYTES = 500 * 1024;
const DEFAULT_QUALITY = 0.72;
const FALLBACK_QUALITY = 0.62;
type DecodedImage = {
source: CanvasImageSource;
width: number;
height: number;
dispose: () => void;
};
async function decodeImage(file: File): Promise<DecodedImage> {
if (typeof createImageBitmap === 'function') {
try {
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
return { source: bitmap, width: bitmap.width, height: bitmap.height, dispose: () => bitmap.close() };
} catch {
// Fall back to an HTMLImageElement for browsers without ImageBitmap support.
}
}
const objectUrl = URL.createObjectURL(file);
try {
const image = await new Promise<HTMLImageElement>((resolve, reject) => {
const element = new Image();
element.onload = () => resolve(element);
element.onerror = () => reject(new Error('无法读取封面图片'));
element.src = objectUrl;
});
return {
source: image,
width: image.naturalWidth,
height: image.naturalHeight,
dispose: () => URL.revokeObjectURL(objectUrl),
};
} catch (error) {
URL.revokeObjectURL(objectUrl);
throw error;
}
}
function canvasBlob(canvas: HTMLCanvasElement, quality: number): Promise<Blob | null> {
return new Promise((resolve) => canvas.toBlob(resolve, 'image/webp', quality));
}
/** Resize covers for the largest current display and encode them as a compact WebP. */
export async function compressCoverImage(file: File): Promise<File> {
if (file.size <= 0 || file.size > COVER_MAX_BYTES) return file;
let decoded: DecodedImage;
try {
decoded = await decodeImage(file);
} catch {
return file;
}
try {
if (decoded.width <= 0 || decoded.height <= 0) return file;
const scale = Math.min(1, MAX_WIDTH / decoded.width, MAX_HEIGHT / decoded.height);
const width = Math.max(1, Math.round(decoded.width * scale));
const height = Math.max(1, Math.round(decoded.height * scale));
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
if (!context) return file;
context.drawImage(decoded.source, 0, 0, width, height);
const candidates: Blob[] = [];
const normal = await canvasBlob(canvas, DEFAULT_QUALITY);
if (normal) candidates.push(normal);
if (normal && normal.size > TARGET_BYTES) {
const smaller = await canvasBlob(canvas, FALLBACK_QUALITY);
if (smaller) candidates.push(smaller);
}
const smallest = candidates.sort((a, b) => a.size - b.size)[0];
if (!smallest || smallest.type !== 'image/webp' || smallest.size >= file.size) return file;
const name = file.name.replace(/\.[^.]+$/, '') || 'cover';
return new File([smallest], `${name}.webp`, { type: 'image/webp', lastModified: file.lastModified });
} catch {
return file;
} finally {
decoded.dispose();
}
}
+44
View File
@@ -0,0 +1,44 @@
import { expect, test } from '@playwright/test';
test('封面上传前按比例缩放并压缩为更小的 WebP', async ({ page }) => {
await page.goto('/login');
const result = await page.evaluate(async () => {
const canvas = document.createElement('canvas');
canvas.width = 1600;
canvas.height = 1000;
const context = canvas.getContext('2d');
if (!context) throw new Error('Canvas 不可用');
const gradient = context.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#e53935');
gradient.addColorStop(0.5, '#43a047');
gradient.addColorStop(1, '#1e88e5');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < 120; i++) {
context.fillStyle = `rgba(${i * 2}, ${255 - i}, ${i}, 0.7)`;
context.fillRect((i * 137) % canvas.width, (i * 83) % canvas.height, 180, 96);
}
const sourceBlob = await new Promise<Blob>((resolve, reject) => {
canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error('JPEG 编码失败')), 'image/jpeg', 0.94);
});
const source = new File([sourceBlob], 'robot-cover.jpg', { type: 'image/jpeg' });
const { compressCoverImage } = await import('/src/utils/compressImage.ts');
const compressed = await compressCoverImage(source);
const decoded = await createImageBitmap(compressed);
const result = {
sourceSize: source.size,
outputSize: compressed.size,
type: compressed.type,
width: decoded.width,
height: decoded.height,
};
decoded.close();
return result;
});
expect(result.type).toBe('image/webp');
expect(result.outputSize).toBeLessThan(result.sourceSize);
expect(result.width).toBeLessThanOrEqual(768);
expect(result.height).toBeLessThanOrEqual(480);
expect(result.width / result.height).toBeCloseTo(1.6, 1);
});
+137
View File
@@ -0,0 +1,137 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import { MAX_PROJECT_UPLOAD_FILE, MAX_PROJECT_UPLOAD_TOTAL, validateProjectUpload } from '../src/components/project/projectUpload';
import type { ManagedProjectView, SelectedFile } from '../src/api/types';
const project: ManagedProjectView = {
project: {
projectCode: 'upload-test', name: '上传测试项目', description: '', coverUrl: null,
urdfMainUrl: null, urdfBaseUrl: null, projectType: 'WHEELED',
owner: { userCode: null, nickname: '社区官方' }, repoStatus: 'READY', publishStatus: 'UNPUBLISHED',
publishedCommitSha: null, publishedAt: null, sourceProjectCode: null, sourceCommitSha: null,
likeCount: 0, commentCount: 0, liked: false, sourceRepositoryUrl: null, sourceLicense: null,
createdAt: '2026-10-27T00:00:00', updatedAt: '2026-10-27T00:00:00',
},
moderationStatus: 'NORMAL', moderationReason: null, deleted: false,
};
async function ok(route: Route, data: unknown) {
await route.fulfill({ json: { code: 'OK', message: '成功', data, requestId: null } });
}
async function prepare(page: Page, onCommit: (route: Route) => Promise<void>) {
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
await page.route('**/admin-api/**', async (route) => {
const path = new URL(route.request().url()).pathname.replace('/admin-api', '');
if (path === '/auth/me') return ok(route, { userCode: 'admin', nickname: '测试管理员', role: 'ADMIN' });
if (path === '/projects/types') return ok(route, [{ code: 'WHEELED', name: '轮式机器人' }]);
if (path === '/projects/upload-test') return ok(route, project);
if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] });
if (path.endsWith('/commits')) return ok(route, { items: [], page: 1, size: 20, total: 0 });
if (path.endsWith('/uploads/commit')) return onCommit(route);
return ok(route, { items: [], page: 1, size: 20, total: 0 });
});
await page.goto('/projects/upload-test');
await page.getByRole('button', { name: '上传' }).click();
}
async function chooseDirectory(page: Page) {
const parent = await import('node:fs/promises').then(({ mkdtemp }) => mkdtemp('/tmp/project-upload-'));
const fs = await import('node:fs/promises');
const path = await import('node:path');
const directory = path.join(parent, 'robot');
try {
await fs.mkdir(path.join(directory, 'left'), { recursive: true });
await fs.mkdir(path.join(directory, 'right'), { recursive: true });
await fs.writeFile(path.join(directory, 'left', 'model.stl'), '1234');
await fs.writeFile(path.join(directory, 'right', 'notes.txt'), 'abcd');
const chooser = page.waitForEvent('filechooser');
await page.getByRole('menuitem', { name: '上传文件夹' }).click();
await (await chooser).setFiles(directory);
} finally {
await fs.rm(parent, { recursive: true, force: true });
}
}
test('项目文件夹上传可勾选路径并展示实际上传进度', async ({ page }) => {
let requestBody = '';
let finishCommit!: () => void;
const commitGate = new Promise<void>((resolve) => { finishCommit = resolve; });
await prepare(page, async (route) => {
requestBody = route.request().postDataBuffer()?.toString('utf8') ?? '';
await commitGate;
await ok(route, { commitSha: 'new-sha', message: '上传文件' });
});
await chooseDirectory(page);
const keepRoot = page.getByRole('checkbox', { name: '保留所选文件夹名称' });
await expect(keepRoot).not.toBeChecked();
await expect(page.getByText('left/model.stl', { exact: true })).toBeVisible();
await expect(page.getByText('right/notes.txt', { exact: true })).toBeVisible();
const notes = page.getByRole('checkbox', { name: '选择 right/notes.txt' });
await notes.uncheck();
await expect(page.getByText(/目标目录:.*1 个文件 · 4 B/)).toBeVisible();
await keepRoot.check();
await expect(page.getByRole('checkbox', { name: '选择 robot/left/model.stl' })).toBeChecked();
await expect(page.getByRole('checkbox', { name: '选择 robot/right/notes.txt' })).not.toBeChecked();
await page.getByRole('checkbox', { name: '选择 robot/left/model.stl' }).uncheck();
await expect(page.getByText('至少选择一个文件', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '提交上传' })).toBeDisabled();
await page.getByRole('checkbox', { name: '选择 robot/left/model.stl' }).check();
await page.getByPlaceholder('提交说明(必填)').fill('只上传模型');
await page.getByRole('button', { name: '提交上传' }).click();
const failsafe = setTimeout(finishCommit, 8000);
await expect(page.getByText('正在上传文件')).toBeVisible();
await expect(page.getByRole('progressbar')).toBeVisible();
await expect(page.getByPlaceholder('提交说明(必填)')).toBeDisabled();
finishCommit();
await expect(page.getByText('上传成功,新版本 new-sha')).toBeVisible();
expect(requestBody).toContain('robot/left/model.stl');
expect(requestBody).not.toContain('robot/right/notes.txt');
expect(requestBody).toContain('只上传模型');
clearTimeout(failsafe);
});
test('上传失败保留弹窗和选择状态,可重试', async ({ page }) => {
let attempts = 0;
await prepare(page, async (route) => {
attempts += 1;
if (attempts === 1) {
await route.fulfill({ status: 500, json: { code: 'UPLOAD_FAILED', message: '模拟上传失败', data: null } });
} else {
await ok(route, { commitSha: 'retry-sha', message: '重试上传' });
}
});
await chooseDirectory(page);
const first = page.getByRole('checkbox', { name: '选择 left/model.stl' });
await first.uncheck();
await page.getByRole('button', { name: '提交上传' }).click();
await expect(page.getByText('上传失败,可修改选择后重试')).toBeVisible();
await expect(first).not.toBeChecked();
await expect(page.getByRole('button', { name: '提交上传' })).toBeEnabled();
await first.check();
await page.getByRole('button', { name: '提交上传' }).click();
await expect(page.getByText('上传成功,新版本 retry-sha')).toBeVisible();
expect(attempts).toBe(2);
});
test('项目文件上传限制只校验已选文件并允许总计正好 1 GiB', () => {
const file = (size: number, relativePath: string): SelectedFile => ({
file: { size } as File,
relativePath,
});
const exactTotal = [
...Array.from({ length: 20 }, (_, index) => file(MAX_PROJECT_UPLOAD_FILE, `${index}.bin`)),
file(24 * 1024 * 1024, 'last.bin'),
];
expect(validateProjectUpload(exactTotal, '')).toEqual([]);
expect(validateProjectUpload([...exactTotal, file(1, 'overflow.bin')], '').find((problem) => problem.includes('超过 1 GiB'))).toBeTruthy();
expect(validateProjectUpload([file(MAX_PROJECT_UPLOAD_FILE + 1, 'large.bin')], '')[0]).toContain('50 MiB');
expect(validateProjectUpload(Array.from({ length: 501 }, (_, index) => file(1, `${index}.txt`)), '')[0]).toContain('最多 500 个');
expect(validateProjectUpload([], '')[0]).toBe('至少选择一个文件');
expect(validateProjectUpload([file(MAX_PROJECT_UPLOAD_FILE + 1, 'ignored.bin')], '').length).toBeGreaterThan(0);
expect(validateProjectUpload([file(1, 'kept.txt')], '')).toEqual([]);
});
+174
View File
@@ -0,0 +1,174 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import type { ManagedProjectView, UrdfFile } from '../src/api/types';
import { filterUrdfFiles } from '../src/components/project/urdfFiles';
const resources = [
'robot.URDF', 'meshes/base.STL', 'meshes/body.dae', 'meshes/arm.obj',
'materials/arm.mtl', 'meshes/sensor.gltf', 'meshes/sensor.bin',
'textures/base.PNG', 'textures/arm.ktx2',
];
const unrelated = [
'README.md', 'src/main.py', 'package.xml', 'config/settings.yaml', 'archive.zip',
'.git/backup.urdf', '.DS_Store', '__MACOSX/._base.stl', 'node_modules/example/mesh.obj',
];
const project: ManagedProjectView = {
project: {
projectCode: 'test-robot', name: '测试机器人', description: '', coverUrl: null,
urdfMainUrl: null, urdfBaseUrl: null, projectType: 'WHEELED',
owner: { userCode: null, nickname: '社区官方' }, repoStatus: 'READY', publishStatus: 'UNPUBLISHED',
publishedCommitSha: null, publishedAt: null, sourceProjectCode: null, sourceCommitSha: null,
likeCount: 0, commentCount: 0, liked: false, sourceRepositoryUrl: null, sourceLicense: null,
createdAt: '2026-10-27T00:00:00', updatedAt: '2026-10-27T00:00:00',
},
moderationStatus: 'NORMAL', moderationReason: null, deleted: false,
};
async function ok(route: Route, data: unknown) {
await route.fulfill({ json: { code: 'OK', message: '成功', data, requestId: null } });
}
async function prepare(page: Page, entry: 'project' | 'import') {
const signed: UrdfFile[][] = [];
const confirmed: UrdfFile[][] = [];
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
await page.addInitScript(() => {
const originalFetch = window.fetch.bind(window);
window.fetch = (input, init) => {
const url = typeof input === 'string' ? input : input instanceof Request ? input.url : input.href;
if (new URL(url, window.location.href).pathname === '/mock-oss' && init?.body instanceof FormData) {
const uploads = JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]');
uploads.push(Object.fromEntries([...init.body.entries()].map(([key, value]) => [key, value instanceof File ? value.name : value])));
localStorage.setItem('urdf_test_uploads', JSON.stringify(uploads));
}
return originalFetch(input, init);
};
});
await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
await page.route('**/mock-oss', async (route) => {
await route.fulfill({ status: 204 });
});
// 拦截全部管理 API 和 OSS,测试不会向真实后端上传或创建项目。
await page.route('**/admin-api/**', async (route) => {
const path = new URL(route.request().url()).pathname.replace('/admin-api', '');
if (path === '/auth/me') return ok(route, { userCode: 'admin', nickname: '测试管理员', role: 'ADMIN' });
if (path === '/projects/types') return ok(route, [{ code: 'WHEELED', name: '轮式机器人' }]);
if (path === '/projects/test-robot') return ok(route, project);
if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] });
if (path === '/project-imports/preview') return ok(route, {
repositoryUrl: 'https://github.com/example/robot', defaultBranch: 'main', name: '测试机器人',
description: '', license: null, existingProjectCode: null,
});
if (path.endsWith('/urdf/signature')) {
const files = route.request().postDataJSON().files as UrdfFile[];
signed.push(files);
return ok(route, {
batchCode: 'test-batch', mainRelativePath: files[0].relativePath,
uploadUrl: 'http://127.0.0.1:5190/mock-oss',
files: files.map(({ relativePath }) => ({ relativePath, formFields: { key: relativePath } })),
});
}
if (path.endsWith('/urdf') && route.request().method() === 'PUT') {
confirmed.push(route.request().postDataJSON().files);
return ok(route, project.project);
}
if (path === '/project-imports' && route.request().method() === 'POST') {
confirmed.push(route.request().postDataJSON().urdf.files);
// 留在创建页,便于断言本次提交,避免进入任务轮询。
return route.fulfill({ status: 409, json: { code: 'DUPLICATE_SOURCE', message: '模拟重复来源', data: null } });
}
return ok(route, { items: [], page: 1, size: 20, total: 0 });
});
if (entry === 'project') {
await page.goto('/projects/test-robot');
await page.getByRole('tab', { name: 'URDF', exact: true }).click();
} else {
await page.goto('/imports/new');
await page.getByRole('textbox', { name: 'GitHub 仓库地址' }).fill('https://github.com/example/robot');
await page.getByRole('button', { name: /预\s*检/, exact: true }).click();
await page.getByRole('combobox', { name: '项目类型' }).click();
await page.getByText('轮式机器人', { exact: true }).click();
}
return { signed, confirmed };
}
async function chooseDirectory(page: Page, paths: string[], label = '选择 URDF 目录') {
const parent = await mkdtemp(join(tmpdir(), 'urdf-filter-'));
const directory = join(parent, 'robot');
try {
await Promise.all(paths.map(async (path) => {
const fullPath = join(directory, path);
await mkdir(dirname(fullPath), { recursive: true });
await writeFile(fullPath, 'test');
}));
const chooser = page.waitForEvent('filechooser');
await page.getByRole('button', { name: new RegExp(label) }).click();
await (await chooser).setFiles(directory);
await expect(page.getByRole('button', { name: '重新选择目录' })).toBeVisible();
} finally {
await rm(parent, { recursive: true, force: true });
}
}
for (const entry of ['project', 'import'] as const) {
test(`${entry} URDF 目录仅签名、上传和绑定渲染资源,保留嵌套引用路径`, async ({ page }) => {
const requests = await prepare(page, entry);
await chooseDirectory(page, [...resources, ...unrelated]);
await expect(page.getByText(`已过滤 ${unrelated.length} 个无关文件`, { exact: false })).toBeVisible();
await expect(page.locator('.file-list-row')).toHaveCount(resources.length);
await expect(page.locator('.file-list-main')).toHaveText('robot.URDF');
const keepRoot = page.getByRole('checkbox', { name: '保留所选文件夹名称' });
await keepRoot.check();
await expect(page.locator('.file-list-main')).toHaveText('robot/robot.URDF');
if (entry === 'project') await keepRoot.uncheck();
const expected = resources.map((relativePath) => ({
relativePath: entry === 'import' ? `robot/${relativePath}` : relativePath, sizeBytes: 4,
})).sort((a, b) => a.relativePath.localeCompare(b.relativePath));
await page.getByRole('button', { name: entry === 'project' ? '上传并绑定' : '创建迁移任务', exact: true }).click();
await expect.poll(() => requests.confirmed.length).toBe(1);
expect(requests.signed).toHaveLength(1);
expect([...requests.signed[0]].sort((a, b) => a.relativePath.localeCompare(b.relativePath))).toEqual(expected);
expect(requests.confirmed[0]).toEqual(requests.signed[0]);
await expect.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]').length)).toBe(expected.length);
const uploads = await page.evaluate(() => JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]')) as Record<string, string>[];
expect(uploads.map(({ key }) => key).sort()).toEqual(expected.map((file) => file.relativePath).sort());
expect(uploads.map(({ file }) => file).sort()).toEqual(expected.map((file) => file.relativePath.split('/').at(-1)!).sort());
});
}
test('过滤后仍校验多个或缺失的 URDF,全部过滤时阻止创建,清除后可继续', async ({ page }) => {
const requests = await prepare(page, 'import');
await chooseDirectory(page, ['first.urdf', 'second.URDF', 'README.md']);
await expect(page.getByText('目录中必须有且仅有一个 .urdf 文件(当前 2 个)', { exact: true })).toBeVisible();
await chooseDirectory(page, ['meshes/base.stl'], '重新选择目录');
await expect(page.getByText('目录中必须有且仅有一个 .urdf 文件(当前 0 个)', { exact: true })).toBeVisible();
await chooseDirectory(page, ['README.md', 'src/main.py'], '重新选择目录');
await expect(page.getByText('所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择')).toBeVisible();
await expect(page.locator('.file-list-row')).toHaveCount(0);
await page.getByRole('button', { name: '创建迁移任务', exact: true }).click();
await expect(page.getByText('URDF 目录不符合要求,请重新选择或清除后再创建')).toBeVisible();
expect(requests.signed).toHaveLength(0);
expect(requests.confirmed).toHaveLength(0);
await page.getByRole('button', { name: /清\s*除/, exact: true }).click();
await expect(page.getByText('所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择')).toHaveCount(0);
await expect(page.getByRole('button', { name: '选择 URDF 目录' })).toBeVisible();
});
test('扩展名大小写不敏感,保留材质和贴图数据,排除伪装扩展名和隐藏路径', () => {
const paths = [
'robot.URDF', 'meshes/arm.OBJ', 'materials/arm.MTL', 'textures/base.KTX2', 'mesh.bin',
'robot.urdf.bak', 'mesh.stl.zip', '.hidden.urdf', '.cache/mesh.stl',
'assets/.git/mesh.stl', '__MACOSX/mesh.stl', 'node_modules/pkg/model.glb',
];
const files = paths.map((path) => {
const file = new File(['test'], path.split('/').at(-1)!);
Object.defineProperty(file, 'webkitRelativePath', { value: `robot/${path}` });
return file;
});
expect(filterUrdfFiles(files)).toEqual(files.slice(0, 5));
expect(filterUrdfFiles([new File(['test'], 'standalone.STL')])).toHaveLength(1);
});
+1 -1
View File
@@ -25,7 +25,7 @@ export default defineConfig(({ mode }) => {
resolve: { alias: { '@': path.resolve(__dirname, 'src') } },
server: {
host: '0.0.0.0',
port: 5188,
port: 8091,
strictPort: true,
// 开发环境统一代理 /admin-api 到后端,避免跨域
proxy,