feat(flash-transfer): let create_flash_task set per-file names
upload_file_stream now returns file_name with the original name.
create_flash_task accepts { file, name } so a streamed path can
keep the real filename on the fileset.
Fixes #361
This commit is contained in:
8 files changed
+170
-28
No files matched your search
@@ -60,6 +60,21 @@ interface StagedFlashItem {
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
|
||||
/** One create_flash_task source: a path/URL, or a path plus a display name. */
|
||||
export type FlashTaskFileInput = string | { file: string; name?: string };
|
||||
|
||||
function flashFileDisplayName(override: string | undefined, fallback: string): string {
|
||||
const cleaned = (override ?? '').replace(/[/\\]/g, '_').trim();
|
||||
return cleaned || fallback;
|
||||
}
|
||||
|
||||
function normalizeFlashTaskInputs(
|
||||
files: FlashTaskFileInput | FlashTaskFileInput[],
|
||||
): { file: string; name?: string }[] {
|
||||
const list = Array.isArray(files) ? files : [files];
|
||||
return list.map((item) => (typeof item === 'string' ? { file: item } : item));
|
||||
}
|
||||
|
||||
/** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */
|
||||
export interface FlashFileInfo {
|
||||
filesetUuid: string;
|
||||
@@ -415,14 +430,19 @@ export class FlashTransferApi {
|
||||
* 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit
|
||||
* 的 f6 一致,否则文件不计入 fileset。ApplyFileset 的 fileName 是 fileset 显示名
|
||||
* (卡片标题):有 name 用 name,否则单文件用首文件名、多文件用「<首文件名>等N个文件」。
|
||||
* fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里仍用真实文件名。
|
||||
* fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里用
|
||||
* 条目上的 name(若有),否则用路径 basename。
|
||||
*
|
||||
* 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经
|
||||
* loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB);
|
||||
* 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。
|
||||
*/
|
||||
async createFlashTask(files: string | string[], name?: string, _thumbPath?: string): Promise<{ filesetId: string }> {
|
||||
const fileList = Array.isArray(files) ? files : [files];
|
||||
async createFlashTask(
|
||||
files: FlashTaskFileInput | FlashTaskFileInput[],
|
||||
name?: string,
|
||||
_thumbPath?: string,
|
||||
): Promise<{ filesetId: string }> {
|
||||
const fileList = normalizeFlashTaskInputs(files);
|
||||
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
|
||||
const uploader = {
|
||||
uin: this.ctx.identity.uin,
|
||||
@@ -434,9 +454,10 @@ export class FlashTransferApi {
|
||||
const items: StagedFlashItem[] = [];
|
||||
try {
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const source = fileList[i];
|
||||
const source = fileList[i]!.file;
|
||||
if (!source) throw new Error('create_flash_task: files is empty');
|
||||
const staged = await stageSourceToDisk(source, flashStageMaxBytes(source));
|
||||
const fileName = staged.fileName;
|
||||
const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName);
|
||||
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
|
||||
items.push({
|
||||
filePath: staged.filePath,
|
||||
|
||||
@@ -285,6 +285,48 @@ describe('FlashTransferApi.createFlashTask — disk streaming (#359)', () => {
|
||||
expect(commit.entries[1]).toEqual(expect.objectContaining({ fileName: 'b.zip' }));
|
||||
});
|
||||
|
||||
it('uses a per-file name on commit and keeps the fileset title separate (#361)', async () => {
|
||||
const file = writeSrc('uuid__clip.mp4', synth(40, 3));
|
||||
installSliceuploadOk();
|
||||
|
||||
await api().createFlashTask({ file, name: 'clip.mp4' }, '自定义名称');
|
||||
|
||||
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
fileName: '自定义名称',
|
||||
origName: '自定义名称',
|
||||
}));
|
||||
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
entries: [expect.objectContaining({ fileName: 'clip.mp4', origName: 'clip.mp4', fileSize: 40 })],
|
||||
}));
|
||||
});
|
||||
|
||||
it('uses per-file names in a mixed files list (#361)', async () => {
|
||||
const fileA = writeSrc('a-id__a.mp4', synth(50, 1));
|
||||
const fileB = writeSrc('b.zip', synth(70, 2));
|
||||
installSliceuploadOk();
|
||||
|
||||
await api().createFlashTask([{ file: fileA, name: 'a.mp4' }, fileB]);
|
||||
|
||||
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
fileName: 'a.mp4等2个文件',
|
||||
fileSize: 120,
|
||||
}));
|
||||
const commit = vi.mocked(CommitFile.invoke).mock.calls[0]![1];
|
||||
expect(commit.entries[0]).toEqual(expect.objectContaining({ fileName: 'a.mp4' }));
|
||||
expect(commit.entries[1]).toEqual(expect.objectContaining({ fileName: 'b.zip' }));
|
||||
});
|
||||
|
||||
it('falls back to the path basename when the per-file name is blank (#361)', async () => {
|
||||
const file = writeSrc('clip.mp4', synth(32, 9));
|
||||
installSliceuploadOk();
|
||||
|
||||
await api().createFlashTask({ file, name: ' ' });
|
||||
|
||||
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
entries: [expect.objectContaining({ fileName: 'clip.mp4' })],
|
||||
}));
|
||||
});
|
||||
|
||||
it('falls back to the filename title when name is blank (#363)', async () => {
|
||||
const file = writeSrc('clip.mp4', synth(32, 9));
|
||||
installSliceuploadOk();
|
||||
|
||||
@@ -924,7 +924,8 @@
|
||||
"name": "files",
|
||||
"type": "raw",
|
||||
"required": false,
|
||||
"schema": {}
|
||||
"schema": {},
|
||||
"desc": "路径、{ file, name },或它们的数组"
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
@@ -947,7 +948,9 @@
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"files": {},
|
||||
"files": {
|
||||
"description": "路径、{ file, name },或它们的数组"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -11578,7 +11581,7 @@
|
||||
"name": "upload_file_stream",
|
||||
"aliases": [],
|
||||
"summary": "以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)",
|
||||
"returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)",
|
||||
"returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
|
||||
@@ -927,7 +927,8 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"name": "files",
|
||||
"type": "raw",
|
||||
"required": false,
|
||||
"schema": {}
|
||||
"schema": {},
|
||||
"desc": "路径、{ file, name },或它们的数组"
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
@@ -950,7 +951,9 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"files": {},
|
||||
"files": {
|
||||
"description": "路径、{ file, name },或它们的数组"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -11581,7 +11584,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"name": "upload_file_stream",
|
||||
"aliases": [],
|
||||
"summary": "以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)",
|
||||
"returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)",
|
||||
"returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
|
||||
@@ -302,6 +302,31 @@ async function groupTodoRun(
|
||||
return okResponse();
|
||||
}
|
||||
|
||||
function parseFlashTaskFiles(
|
||||
raw: unknown,
|
||||
): { files: Array<{ file: string; name?: string }> } | { error: string } {
|
||||
const items = Array.isArray(raw) ? raw : raw == null ? [] : [raw];
|
||||
if (items.length === 0) return { error: 'files must not be empty' };
|
||||
const files: Array<{ file: string; name?: string }> = [];
|
||||
for (const item of items) {
|
||||
if (typeof item === 'string') {
|
||||
if (item === '') return { error: 'files must not be empty' };
|
||||
files.push({ file: item });
|
||||
continue;
|
||||
}
|
||||
if (item && typeof item === 'object' && !Array.isArray(item)) {
|
||||
const file = (item as { file?: unknown }).file;
|
||||
const name = (item as { name?: unknown }).name;
|
||||
if (typeof file !== 'string' || file === '') return { error: 'files must not be empty' };
|
||||
if (name !== undefined && typeof name !== 'string') return { error: 'files[].name must be a string' };
|
||||
files.push({ file, name });
|
||||
continue;
|
||||
}
|
||||
return { error: 'files must be a path string, { file, name }, or an array of those' };
|
||||
}
|
||||
return { files };
|
||||
}
|
||||
|
||||
/** FlashTransferApi 返回的 FlashFileInfo → OneBot JSON 响应(plain object,JsonObject 兼容)。
|
||||
* 字段名对齐 NapCat(get_flash_file_list 用 size,非 file_size),便于客户端 drop-in 迁移。 */
|
||||
function flashFileInfoToJson(f: {
|
||||
@@ -2584,25 +2609,15 @@ export const actions = [
|
||||
name: 'create_flash_task',
|
||||
summary: '创建闪传任务',
|
||||
params: {
|
||||
// files 支持单个路径(string)或多个路径(string[]),多文件共用一个 fileset
|
||||
files: f.raw(),
|
||||
// 路径、{ file, name },或它们的数组;name 是该文件在闪传里的显示名
|
||||
files: f.raw().describe('路径、{ file, name },或它们的数组'),
|
||||
name: f.string().optional(),
|
||||
thumb_path: f.string().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
// f.raw() 不做校验,这里归一化为 string[] 并校验
|
||||
const rawFiles = p.files;
|
||||
let fileList: string[];
|
||||
if (typeof rawFiles === 'string') {
|
||||
if (rawFiles === '') return failedResponse(RETCODE.BAD_REQUEST, 'files must not be empty');
|
||||
fileList = [rawFiles];
|
||||
} else if (Array.isArray(rawFiles) && rawFiles.every((x) => typeof x === 'string' && x !== '')) {
|
||||
if (rawFiles.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'files must not be empty');
|
||||
fileList = rawFiles as string[];
|
||||
} else {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'files must be a string or string array');
|
||||
}
|
||||
const result = await ctx.bridge.apis.flashTransfer.createFlashTask(fileList, p.name, p.thumb_path);
|
||||
const parsed = parseFlashTaskFiles(p.files);
|
||||
if ('error' in parsed) return failedResponse(RETCODE.BAD_REQUEST, parsed.error);
|
||||
const result = await ctx.bridge.apis.flashTransfer.createFlashTask(parsed.files, p.name, p.thumb_path);
|
||||
return okResponse({ fileset_id: result.filesetId, task_id: result.filesetId });
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -251,6 +251,7 @@ async function completeUpload(state: UploadState): Promise<ApiResponse> {
|
||||
received_chunks: received,
|
||||
total_chunks: total,
|
||||
file_path: finalPath,
|
||||
file_name: state.filename,
|
||||
file_size: fileSize,
|
||||
sha256,
|
||||
});
|
||||
@@ -346,7 +347,7 @@ type UploadParams = {
|
||||
const uploadFileStream = defineStreamAction({
|
||||
name: 'upload_file_stream',
|
||||
summary: '以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)',
|
||||
returns: '流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)',
|
||||
returns: '流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)',
|
||||
params: uploadParams,
|
||||
run: (p, ctx) => handleUpload(p, accountKey(ctx)),
|
||||
});
|
||||
|
||||
@@ -2209,3 +2209,46 @@ describe('extended-actions / get_fileset_id', () => {
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / create_flash_task (#361)', () => {
|
||||
it('accepts a path string', async () => {
|
||||
const createFlashTask = vi.fn(async () => ({ filesetId: 'fs-1' }));
|
||||
const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', { files: '/tmp/a.pdf' });
|
||||
expect(res).toMatchObject({ status: 'ok', data: { fileset_id: 'fs-1', task_id: 'fs-1' } });
|
||||
expect(createFlashTask).toHaveBeenCalledWith([{ file: '/tmp/a.pdf' }], undefined, undefined);
|
||||
});
|
||||
|
||||
it('accepts { file, name } and forwards the per-file name', async () => {
|
||||
const createFlashTask = vi.fn(async () => ({ filesetId: 'fs-2' }));
|
||||
const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', {
|
||||
files: { file: '/tmp/uuid__a.pdf', name: 'a.pdf' },
|
||||
name: '卡片',
|
||||
});
|
||||
expect(res.status).toBe('ok');
|
||||
expect(createFlashTask).toHaveBeenCalledWith(
|
||||
[{ file: '/tmp/uuid__a.pdf', name: 'a.pdf' }],
|
||||
'卡片',
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an empty files value', async () => {
|
||||
const createFlashTask = vi.fn(async () => ({ filesetId: 'fs' }));
|
||||
const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', { files: [] });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400, wording: 'files must not be empty' });
|
||||
expect(createFlashTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a non-string per-file name', async () => {
|
||||
const createFlashTask = vi.fn(async () => ({ filesetId: 'fs' }));
|
||||
const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', {
|
||||
files: { file: '/tmp/a.pdf', name: 1 },
|
||||
});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400, wording: 'files[].name must be a string' });
|
||||
expect(createFlashTask).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -42,7 +42,10 @@ describe('upload_file_stream', () => {
|
||||
|
||||
r = await handleUpload(mk({ stream_id: id, total_chunks: 3, is_complete: true, expected_sha256: sha }));
|
||||
const data = r.data as Record<string, unknown>;
|
||||
expect(data).toMatchObject({ type: 'response', status: 'file_complete', total_chunks: 3, file_size: full.length, sha256: sha });
|
||||
expect(data).toMatchObject({
|
||||
type: 'response', status: 'file_complete', total_chunks: 3,
|
||||
file_size: full.length, sha256: sha, file_name: `upload_${id}`,
|
||||
});
|
||||
expect(fs.readFileSync(String(data.file_path), 'utf8')).toBe(full);
|
||||
// state dropped after completion, chunk dir gone
|
||||
expect(uploads.has(id)).toBe(false);
|
||||
@@ -97,6 +100,17 @@ describe('upload_file_stream', () => {
|
||||
await expect(handleUpload(mk({ stream_id: 'nope', verify_only: true }))).rejects.toThrow(/not found/i);
|
||||
});
|
||||
|
||||
it('returns the original filename alongside the prefixed file_path (#361)', async () => {
|
||||
const id = 'up-named';
|
||||
await handleUpload(mk({
|
||||
stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x'), filename: 'report.pdf',
|
||||
}));
|
||||
const r = await handleUpload(mk({ stream_id: id, total_chunks: 1, is_complete: true }));
|
||||
const data = r.data as Record<string, unknown>;
|
||||
expect(data.file_name).toBe('report.pdf');
|
||||
expect(String(data.file_path)).toBe(path.join(STREAM_UPLOAD_DIR, `${id}__report.pdf`));
|
||||
});
|
||||
|
||||
it('strips path separators from filename (no temp-dir escape)', async () => {
|
||||
const id = 'up-escape';
|
||||
await handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x'), filename: '../../evil.sh' }));
|
||||
|
||||
Reference in new issue
Block a user