refactor(api): move 17 group-file methods to GroupFileApi (#6 commit 4/13)

Inlines `actions/group-file.ts` into `apis/group-file.ts::GroupFileApi`,
deletes the old action file, removes the matching 17 facade methods
off `Bridge`, and slims `BridgeInterface` accordingly.

Method renaming follows the same "strip the redundant suffix" rule we
applied to GroupAdminApi:

  uploadGroupFile           → upload
  uploadPrivateFile         → uploadPrivate
  sendGroupFileMessage      → publish        (OIDB 0x6d9_4)
  fetchGroupFiles           → list
  fetchGroupFileCount       → getCount
  fetchGroupFileUrl         → getUrl
  fetchPrivateFileUrl       → getPrivateUrl
  fetchGroupPttUrlByNode    → getPttUrl
  fetchPrivatePttUrlByNode  → getPrivatePttUrl
  fetchGroupVideoUrlByNode  → getVideoUrl
  fetchPrivateVideoUrlByNode → getPrivateVideoUrl
  deleteGroupFile           → delete
  moveGroupFile             → move
  createGroupFileFolder     → createFolder
  deleteGroupFileFolder     → deleteFolder
  renameGroupFileFolder     → renameFolder

`upload`'s atomic upload+publish flow now calls `this.publish(...)`
directly instead of going through `bridge.sendGroupFileMessage`, and
`uploadPrivate` calls `this.ctx.apis.message.sendC2cFile(...)`.

Callers updated: `instance-context.ts`, `media-url-resolver.ts`,
`actions/group-file.ts` (onebot), `actions/extended.ts`,
`modules/{contact,media,message}-actions.ts`.

Tests: `group-file.test.ts` rewritten to use
`new GroupFileApi(bridge as any).method(...)`. The "verify publish was
called" assertions now use `vi.spyOn(api, 'publish').mockResolvedValue()`
since `publish` is an instance method on the same Api. `_helpers.ts`
gains `mockGroupFileApi()` for cross-Api callers and drops the flat
`sendGroupFileMessage` shim. `media-url-resolver.test.ts` and
`send-group-file.test.ts` switched to `bridge.apis.groupFile.*`; the
extended-actions `APIS_ROUTING` map now carries a `[area, newName]`
tuple so renamed methods auto-promote.

587/587 tests pass. The network-manager file remains as the only
failing test file (pre-existing infrastructure issue unrelated to #6).
This commit is contained in:
DrSmoothl committed 2026-05-20 23:08:50 +08:00
1 parent 0b91e4db8d
commit dad501ebc0
17 files changed
+1241 -1185

No files matched your search

+44 -4
View File
@@ -61,9 +61,50 @@ export function mockContactsApi(): MockContactsApi {
};
}
export interface MockGroupFileApi {
upload: ReturnType<typeof vi.fn>;
uploadPrivate: ReturnType<typeof vi.fn>;
publish: ReturnType<typeof vi.fn>;
getCount: ReturnType<typeof vi.fn>;
list: ReturnType<typeof vi.fn>;
getUrl: ReturnType<typeof vi.fn>;
getPrivateUrl: ReturnType<typeof vi.fn>;
getPttUrl: ReturnType<typeof vi.fn>;
getPrivatePttUrl: ReturnType<typeof vi.fn>;
getVideoUrl: ReturnType<typeof vi.fn>;
getPrivateVideoUrl: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
move: ReturnType<typeof vi.fn>;
createFolder: ReturnType<typeof vi.fn>;
deleteFolder: ReturnType<typeof vi.fn>;
renameFolder: ReturnType<typeof vi.fn>;
}
export function mockGroupFileApi(): MockGroupFileApi {
return {
upload: vi.fn(async () => ({ fileId: 'stub-fid' })),
uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })),
publish: vi.fn(async () => undefined),
getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })),
list: vi.fn(async () => ({ files: [], folders: [] })),
getUrl: vi.fn(async () => 'stub://url'),
getPrivateUrl: vi.fn(async () => 'stub://private-url'),
getPttUrl: vi.fn(async () => 'stub://ptt-url'),
getPrivatePttUrl: vi.fn(async () => 'stub://private-ptt-url'),
getVideoUrl: vi.fn(async () => 'stub://video-url'),
getPrivateVideoUrl: vi.fn(async () => 'stub://private-video-url'),
delete: vi.fn(async () => undefined),
move: vi.fn(async () => undefined),
createFolder: vi.fn(async () => undefined),
deleteFolder: vi.fn(async () => undefined),
renameFolder: vi.fn(async () => undefined),
};
}
export interface MockApiHub {
message: MockMessageApi;
contacts: MockContactsApi;
groupFile: MockGroupFileApi;
// additional Apis added commit-by-commit as #6 progresses
}
@@ -71,6 +112,7 @@ export function mockApiHub(overrides: Partial<MockApiHub> = {}): MockApiHub {
return {
message: overrides.message ?? mockMessageApi(),
contacts: overrides.contacts ?? mockContactsApi(),
groupFile: overrides.groupFile ?? mockGroupFileApi(),
};
}
@@ -89,9 +131,8 @@ export interface MockBridge {
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
resolveUserUid: ReturnType<typeof vi.fn>;
sendGroupFileMessage: ReturnType<typeof vi.fn>;
// Uploaded-file metadata cache helpers — actions like uploadGroupFile
// / uploadPrivateFile call these to remember the upload, so tests
// Uploaded-file metadata cache helpers — GroupFileApi.upload /
// uploadPrivate call these to remember the upload, so tests
// covering those code paths get a default-no-op shim.
rememberUploadedFile: ReturnType<typeof vi.fn>;
recallUploadedFile: ReturnType<typeof vi.fn>;
@@ -121,7 +162,6 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
sendGroupFileMessage: vi.fn(async () => undefined),
rememberUploadedFile: vi.fn(),
recallUploadedFile: vi.fn(() => undefined),
...overrides,
+80 -66
View File
@@ -45,7 +45,7 @@ vi.mock('../../src/bridge/highway/utils', () => ({
import * as oidb from '../../src/bridge/bridge-oidb';
import * as highwayClient from '../../src/bridge/highway/highway-client';
import * as groupFile from '../../src/bridge/actions/group-file';
import { GroupFileApi } from '../../src/bridge/apis/group-file';
import { mockBridge } from './_helpers';
describe('actions/group-file', () => {
@@ -57,27 +57,27 @@ describe('actions/group-file', () => {
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => {
it('getCount returns { fileCount, maxCount } from the OIDB response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({
body: { count: { fileCount: 42, maxCount: 1000 } },
}),
);
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
const out = await new GroupFileApi(bridge as any).getCount(12345);
expect(out).toEqual({ fileCount: 42, maxCount: 1000 });
});
it('fetchGroupFileCount falls back to defaults on partial response', async () => {
it('getCount falls back to defaults on partial response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({ body: { count: {} } }),
);
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
const out = await new GroupFileApi(bridge as any).getCount(12345);
expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
});
it('uploadGroupFile skips highway when boolFileExist is true', async () => {
it('upload skips highway when boolFileExist is true', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
@@ -90,13 +90,16 @@ describe('actions/group-file', () => {
} as any,
}),
);
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
const api = new GroupFileApi(bridge as any);
// Suppress the auto-publish — that path is covered separately.
vi.spyOn(api, 'publish').mockResolvedValue();
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => {
it('upload runs highway PUT when boolFileExist is false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
@@ -113,90 +116,99 @@ describe('actions/group-file', () => {
} as any,
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/file.bin');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadGroupFile throws on missing upload response', async () => {
it('upload throws on missing upload response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: {} }),
);
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'))
.rejects.toThrow(/response missing/);
});
it('uploadGroupFile bubbles up OIDB retCode errors', async () => {
it('upload bubbles up OIDB retCode errors', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any },
}),
);
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'))
.rejects.toThrow(/code=999/);
});
it('uploadGroupFile publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
// call the file never appears in the chat. Earlier attempts used
// PbSendMsg with a transElem(24) but the QQ-NT server rejects that
// with result=79 (transElem(24) is a receive-side decoding shape,
// not a send-side one). Asserts that `bridge.sendGroupFileMessage`
// is invoked with the uploaded fileId.
// not a send-side one). Asserts that `this.publish` is invoked
// with the uploaded fileId.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any },
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt');
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
const [groupId, fileId] = bridge.sendGroupFileMessage.mock.calls[0]!;
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/some-file.bin', 'mynote.txt');
expect(publishSpy).toHaveBeenCalledOnce();
const [groupId, fileId] = publishSpy.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(fileId).toBe('fid-pub');
// sendGroupMessage must NOT be touched — the previous wire shape
// sendGroup must NOT be touched — the previous wire shape
// (PbSendMsg w/ transElem(24)) is the bug we're guarding against.
expect(bridge.apis.message.sendGroup).not.toHaveBeenCalled();
});
it('uploadGroupFile skips the chat post when uploadFile=false', async () => {
it('upload skips the chat post when uploadFile=false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any },
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false);
expect(bridge.sendGroupFileMessage).not.toHaveBeenCalled();
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/file.bin', '', '/', false);
expect(publishSpy).not.toHaveBeenCalled();
});
it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => {
it('upload returns success even when the chat post fails (file is still uploaded)', async () => {
const bridge = mockBridge();
vi.mocked(bridge.sendGroupFileMessage).mockRejectedValueOnce(new Error('message rejected'));
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any },
}),
);
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockRejectedValueOnce(new Error('message rejected'));
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-tolerant' });
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
expect(publishSpy).toHaveBeenCalledOnce();
});
it('uploadGroupFile caches the upload metadata for later resend by file_id', async () => {
it('upload caches the upload metadata for later resend by file_id', async () => {
// After upload, a later `send_group_msg` carrying just the file_id
// needs to recover the name/size/md5 from somewhere. Production
// populates `bridge.rememberUploadedFile` with the full tuple.
// populates `ctx.rememberUploadedFile` with the full tuple.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any },
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/x.bin', 'x.bin');
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/x.bin', 'x.bin');
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
expect(meta).toMatchObject({
@@ -207,13 +219,13 @@ describe('actions/group-file', () => {
});
});
it('sendGroupFileMessage hits OIDB 0x6d9_4 with the right body', async () => {
it('publish hits OIDB 0x6d9_4 with the right body', async () => {
// Direct cover of the new bridge method. The previous send-shape
// (PbSendMsg + transElem(24)) failed with result=79; this is the
// Lagrange-V2-mirrored fix.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array());
await groupFile.sendGroupFileMessage(bridge as any, 12345, 'fid-publish');
await new GroupFileApi(bridge as any).publish(12345, 'fid-publish');
expect(oidb.runOidb).toHaveBeenCalledOnce();
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4');
@@ -234,7 +246,7 @@ describe('actions/group-file', () => {
);
});
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
it('uploadPrivate resolves both target + self UID before OIDB call', async () => {
const bridge = mockBridge({
identity: {
uin: '10001',
@@ -253,17 +265,17 @@ describe('actions/group-file', () => {
body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any },
}),
);
const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file');
const out = await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file');
expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' });
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
});
it('uploadPrivateFile publishes the file via sendC2cFileMessage after upload', async () => {
it('uploadPrivate publishes the file via apis.message.sendC2cFile after upload', async () => {
// C2C files use `RichText.notOnlineFile` (not in the elems array),
// so `uploadPrivateFile` calls the dedicated `sendC2cFileMessage`
// path on the bridge rather than `sendPrivateMessage`. Same bug
// class as the group case — without this the recipient sees no
// message even though the bytes are on the server.
// so `uploadPrivate` calls the dedicated `sendC2cFile` path on
// the bridge rather than `sendPrivate`. Same bug class as the
// group case — without this the recipient sees no message even
// though the bytes are on the server.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
@@ -271,7 +283,7 @@ describe('actions/group-file', () => {
body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any },
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/private-file.bin', 'doc.pdf');
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/private-file.bin', 'doc.pdf');
expect(bridge.apis.message.sendC2cFile).toHaveBeenCalledOnce();
const [userUin, userUid, info] = bridge.apis.message.sendC2cFile.mock.calls[0]!;
expect(userUin).toBe(67890);
@@ -280,12 +292,12 @@ describe('actions/group-file', () => {
expect(bridge.apis.message.sendPrivate).not.toHaveBeenCalled();
});
it('uploadPrivateFile caches the upload metadata for later resend by file_id', async () => {
it('uploadPrivate caches the upload metadata for later resend by file_id', async () => {
// C2C file resend (send_private_msg with just file_id) was the
// "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/
// fileName/fileHash, but the OneBot caller only knows the file_id.
// Caching the upload tuple lets the OneBot send-message path
// recover the rest via `bridge.recallUploadedFile(fileId)`.
// recover the rest via `ctx.recallUploadedFile(fileId)`.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
@@ -293,7 +305,7 @@ describe('actions/group-file', () => {
body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any },
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/cache-me.txt', 'cache-me.txt');
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/cache-me.txt', 'cache-me.txt');
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
expect(meta).toMatchObject({
@@ -305,7 +317,7 @@ describe('actions/group-file', () => {
});
});
it('uploadPrivateFile skips the chat post when uploadFile=false', async () => {
it('uploadPrivate skips the chat post when uploadFile=false', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
@@ -313,11 +325,11 @@ describe('actions/group-file', () => {
body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any },
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file', '', false);
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', '', false);
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
});
it('uploadPrivateFile reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
// The 2026 QQ-NT server rollout moved the upload host out of the
// legacy `uploadIp` (field 60) string into the new
// `rtpMediaPlatformUploadAddress` (field 210, repeated IPv4 message).
@@ -342,11 +354,11 @@ describe('actions/group-file', () => {
},
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin');
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin');
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadPrivateFile falls back to uploadDomain when uploadIp is empty', async () => {
it('uploadPrivate falls back to uploadDomain when uploadIp is empty', async () => {
// Regression: the server has been observed in the wild returning the
// highway host in `uploadDomain` (field 70) instead of `uploadIp`
// (field 60), causing "private file upload host is invalid". The
@@ -371,11 +383,11 @@ describe('actions/group-file', () => {
},
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin');
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin');
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadPrivateFile throws "host is invalid" only when every host field is empty', async () => {
it('uploadPrivate throws "host is invalid" only when every host field is empty', async () => {
// The diagnostic warn-log lists every host slot to help users
// report which one the server actually populated; this test just
// asserts that the throw still fires when none of them carry a
@@ -387,11 +399,11 @@ describe('actions/group-file', () => {
body: { upload: { uuid: 'pfid', fileAddon: 'phash', uploadPort: 8080 } as any },
}),
);
await expect(groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'))
await expect(new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'))
.rejects.toThrow(/upload host is invalid/);
});
it('fetchGroupFiles paginates files + folders out of OIDB items', async () => {
it('list paginates files + folders out of OIDB items', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileViewResp>>({
@@ -406,14 +418,14 @@ describe('actions/group-file', () => {
},
}),
);
const out = await groupFile.fetchGroupFiles(bridge as any, 12345);
const out = await new GroupFileApi(bridge as any).list(12345);
expect(out.files).toHaveLength(1);
expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' });
expect(out.folders).toHaveLength(1);
expect(out.folders[0]).toMatchObject({ folderId: 'd1', folderName: 'dir', creator: 2, creatorName: 'bob' });
});
it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => {
it('getUrl builds the https URL from downloadDns + hex-encoded path', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
@@ -425,44 +437,46 @@ describe('actions/group-file', () => {
},
}),
);
const url = await groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz');
const url = await new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz');
expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz');
});
it('fetchGroupFileUrl throws when response is missing dns or url', async () => {
it('getUrl throws when response is missing dns or url', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { download: {} as any },
}),
);
await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'))
await expect(new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz'))
.rejects.toThrow(/invalid/);
});
it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => {
it('delete / move dispatch the right sub-commands', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { move: {} as any } }));
await groupFile.deleteGroupFile(bridge as any, 12345, 'fid');
await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b');
const api = new GroupFileApi(bridge as any);
await api.delete(12345, 'fid');
await api.move(12345, 'fid', '/a', '/b');
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]);
});
it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => {
it('createFolder / deleteFolder / renameFolder dispatch 0x6d7 family', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { create: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { rename: {} as any } }));
await groupFile.createGroupFileFolder(bridge as any, 1, 'folder');
await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid');
await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname');
const api = new GroupFileApi(bridge as any);
await api.createFolder(1, 'folder');
await api.deleteFolder(1, 'fid');
await api.renameFolder(1, 'fid', 'newname');
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]);
});
it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => {
it('get*Url builds https://domain/path?rkey from the NTV2 response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValue(
protobuf_encode<OidbBase<NTV2RichMediaResp>>({
@@ -475,7 +489,7 @@ describe('actions/group-file', () => {
} as any,
}),
);
const url = await groupFile.fetchGroupVideoUrlByNode(bridge as any, 12345, { fileUuid: 'uuid' });
const url = await new GroupFileApi(bridge as any).getVideoUrl(12345, { fileUuid: 'uuid' });
expect(url).toBe('https://media.example.com/path/x?rkey=abc');
});
});
+27 -18
View File
@@ -4,16 +4,25 @@ import type { MessageElement } from '../src/bridge/events';
// Minimal stand-ins for the two collaborators. Each test wires whatever
// subset of Bridge methods the element type exercises.
//
// MediaUrlResolver now reaches `bridge.apis.groupFile.{getUrl,
// getPrivateUrl, getPttUrl, getPrivatePttUrl, getVideoUrl,
// getPrivateVideoUrl}` per the #6 Api-on-ctx refactor. The helper here
// builds an `apis.groupFile` stub directly so tests can keep asserting
// "which file/url helper got called" without going through the
// `mockBridge` shared fixture.
function makeBridge(overrides: Record<string, ReturnType<typeof vi.fn>> = {}) {
return {
fetchGroupFileUrl: vi.fn(async () => 'http://group/file'),
fetchPrivateFileUrl: vi.fn(async () => 'http://private/file'),
fetchGroupPttUrlByNode: vi.fn(async () => 'http://group/ptt'),
fetchPrivatePttUrlByNode: vi.fn(async () => 'http://private/ptt'),
fetchGroupVideoUrlByNode: vi.fn(async () => 'http://group/video'),
fetchPrivateVideoUrlByNode: vi.fn(async () => 'http://private/video'),
...overrides,
apis: {
groupFile: {
getUrl: overrides.getUrl ?? vi.fn(async () => 'http://group/file'),
getPrivateUrl: overrides.getPrivateUrl ?? vi.fn(async () => 'http://private/file'),
getPttUrl: overrides.getPttUrl ?? vi.fn(async () => 'http://group/ptt'),
getPrivatePttUrl: overrides.getPrivatePttUrl ?? vi.fn(async () => 'http://private/ptt'),
getVideoUrl: overrides.getVideoUrl ?? vi.fn(async () => 'http://group/video'),
getPrivateVideoUrl: overrides.getPrivateVideoUrl ?? vi.fn(async () => 'http://private/video'),
},
},
};
}
@@ -34,7 +43,7 @@ describe('MediaUrlResolver — file element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
const out = await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupFileUrl).toHaveBeenCalledWith(12345, 'fid-x');
expect(bridge.apis.groupFile.getUrl).toHaveBeenCalledWith(12345, 'fid-x');
expect(element.url).toBe('http://group/file');
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
expect(out).toBe('http://group/file');
@@ -44,7 +53,7 @@ describe('MediaUrlResolver — file element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x', fileHash: 'hash-y' };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivateFileUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y');
expect(bridge.apis.groupFile.getPrivateUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y');
expect(element.url).toBe('http://private/file');
});
@@ -52,7 +61,7 @@ describe('MediaUrlResolver — file element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivateFileUrl).not.toHaveBeenCalled();
expect(bridge.apis.groupFile.getPrivateUrl).not.toHaveBeenCalled();
expect(element.url).toBe('');
});
});
@@ -66,7 +75,7 @@ describe('MediaUrlResolver — record / video element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupPttUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(bridge.apis.groupFile.getPttUrl).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(element.url).toBe('http://group/ptt');
});
@@ -74,7 +83,7 @@ describe('MediaUrlResolver — record / video element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivatePttUrlByNode).toHaveBeenCalledWith(MEDIA_NODE);
expect(bridge.apis.groupFile.getPrivatePttUrl).toHaveBeenCalledWith(MEDIA_NODE);
expect(element.url).toBe('http://private/ptt');
});
@@ -82,7 +91,7 @@ describe('MediaUrlResolver — record / video element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupVideoUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(bridge.apis.groupFile.getVideoUrl).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(element.url).toBe('http://group/video');
});
@@ -90,7 +99,7 @@ describe('MediaUrlResolver — record / video element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivateVideoUrlByNode).toHaveBeenCalledWith(MEDIA_NODE);
expect(bridge.apis.groupFile.getPrivateVideoUrl).toHaveBeenCalledWith(MEDIA_NODE);
expect(element.url).toBe('http://private/video');
});
@@ -98,7 +107,7 @@ describe('MediaUrlResolver — record / video element', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record' };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupPttUrlByNode).not.toHaveBeenCalled();
expect(bridge.apis.groupFile.getPttUrl).not.toHaveBeenCalled();
expect(element.url).toBeUndefined();
});
});
@@ -110,13 +119,13 @@ describe('MediaUrlResolver — short-circuits and resilience', () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid', url: 'already-set' };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupFileUrl).not.toHaveBeenCalled();
expect(bridge.apis.groupFile.getUrl).not.toHaveBeenCalled();
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
});
it('bridge throws: swallowed, rkey still applied', async () => {
const bridge = makeBridge({
fetchGroupFileUrl: vi.fn(async () => { throw new Error('network down'); }),
getUrl: vi.fn(async () => { throw new Error('network down'); }),
});
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') });
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
@@ -28,23 +28,32 @@ function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
* pre-stubbed for the test. Same pattern as contact-actions.test.ts —
* keeps tests honest about which surface they actually need.
*/
// Maps flat method names → ApiHub area they moved to under the #6
// refactor. Auto-promotion lets tests written against the pre-refactor
// flat surface (`fetchGroupRequests: vi.fn()`) keep working without
// per-test restructure.
const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
// Maps flat method names → [area, newMethodName] on the ApiHub under
// the #6 refactor. Auto-promotion lets tests written against the
// pre-refactor flat surface (`fetchGroupRequests: vi.fn()`) keep
// working without per-test restructure, even when the new method name
// drops the redundant `Group`/`File` prefix.
const APIS_ROUTING: Record<string, [string, string]> = {
fetchFriendList: ['contacts', 'fetchFriendList'],
fetchGroupList: ['contacts', 'fetchGroupList'],
fetchGroupMemberList: ['contacts', 'fetchGroupMemberList'],
fetchUserProfile: ['contacts', 'fetchUserProfile'],
fetchGroupRequests: ['contacts', 'fetchGroupRequests'],
fetchDownloadRKeys: ['contacts', 'fetchDownloadRKeys'],
// GroupFileApi: methods drop `Group`/`File`/`Folder` suffix where
// the area name already says it.
deleteGroupFileFolder: ['groupFile', 'deleteFolder'],
fetchGroupPttUrlByNode: ['groupFile', 'getPttUrl'],
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
for (const [k, v] of Object.entries(overrides)) {
const area = APIS_ROUTING[k];
if (area) {
const route = APIS_ROUTING[k];
if (route) {
const [area, newName] = route;
if (!apisSynth[area]) apisSynth[area] = {};
apisSynth[area][k] = v;
apisSynth[area][newName] = v;
}
}
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
@@ -11,7 +11,7 @@
//
// Fix: split file segments off at the OneBot layer (same pattern as
// the c2c-file split for private messages) and dispatch through
// `bridge.sendGroupFileMessage`, which calls dedicated OIDB
// `bridge.apis.groupFile.publish`, which calls dedicated OIDB
// `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's
// `GroupSendFileService.cs`.
@@ -45,7 +45,7 @@ const goodReceipt = {
};
describe('send_group_msg with {type:"file"} segment', () => {
it('file-only message routes through sendGroupFileMessage (not sendGroupMessage_bridge)', async () => {
it('file-only message routes through apis.groupFile.publish (not apis.message.sendGroup)', async () => {
// Pure-file case — the elems[] path used to ship a transElem(24)
// and got result=79. The dedicated OIDB-0x6d9_4 route must take
// over for group file publishing.
@@ -53,10 +53,12 @@ describe('send_group_msg with {type:"file"} segment', () => {
// Declare params on the fn so `mock.calls[0]` infers a tuple of
// [groupId, fileId] instead of `[]` (which makes the destructuring
// a tsc error under noUncheckedIndexedAccess).
const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage_bridge } } as any,
sendGroupFileMessage,
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
@@ -65,20 +67,22 @@ describe('send_group_msg with {type:"file"} segment', () => {
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
}] as any, false);
expect(sendGroupFileMessage).toHaveBeenCalledOnce();
expect(publish).toHaveBeenCalledOnce();
expect(sendGroupMessage_bridge).not.toHaveBeenCalled();
const [groupId, fileId] = sendGroupFileMessage.mock.calls[0]!;
const [groupId, fileId] = publish.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(fileId).toBe('gfid-abc');
});
it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => {
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage_bridge } } as any,
sendGroupFileMessage,
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
@@ -89,13 +93,13 @@ describe('send_group_msg with {type:"file"} segment', () => {
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(sendGroupFileMessage).toHaveBeenCalledOnce();
expect(publish).toHaveBeenCalledOnce();
const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!;
expect(textGid).toBe(12345);
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
const [fileGid, fileFileId] = sendGroupFileMessage.mock.calls[0]!;
const [fileGid, fileFileId] = publish.mock.calls[0]!;
expect(fileGid).toBe(12345);
expect(fileFileId).toBe('gfid-xyz');
});
@@ -104,10 +108,12 @@ describe('send_group_msg with {type:"file"} segment', () => {
// Same upload-by-reference contract as the c2c file path —
// missing file_id means there's nothing to publish.
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const sendGroupFileMessage = vi.fn();
const publish = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage_bridge } } as any,
sendGroupFileMessage,
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
@@ -118,6 +124,6 @@ describe('send_group_msg with {type:"file"} segment', () => {
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(sendGroupFileMessage).not.toHaveBeenCalled();
expect(publish).not.toHaveBeenCalled();
});
});