fix(onebot): repair group system message queries
This commit is contained in:
6 files changed
+229
-24
No files matched your search
@@ -183,13 +183,39 @@ export const actions = [
|
||||
name: 'get_group_system_msg',
|
||||
summary: '获取群系统消息',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
returns: '群系统消息数组,可按群号或未处理状态过滤。',
|
||||
returnsSchema: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
group_id: { type: 'integer', description: '群号' },
|
||||
group_name: { type: 'string', description: '群名称' },
|
||||
request_id: { type: 'integer', description: '请求序列号' },
|
||||
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
|
||||
requester_nick: { type: 'string', description: '申请人昵称' },
|
||||
message: { type: 'string', description: '验证留言' },
|
||||
checked: { type: 'boolean', description: '是否已处理' },
|
||||
flag: { type: 'string', description: '处理请求使用的规范 flag' },
|
||||
},
|
||||
required: [
|
||||
'group_id', 'group_name', 'request_id', 'requester_uin',
|
||||
'requester_nick', 'message', 'checked', 'flag',
|
||||
],
|
||||
},
|
||||
},
|
||||
params: {
|
||||
group_id: f.groupId().optional(),
|
||||
only_pending: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg({
|
||||
groupId: p.group_id,
|
||||
onlyPending: p.only_pending,
|
||||
}));
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type CompiledActionKind,
|
||||
type CompiledActionRegistry,
|
||||
} from './actions';
|
||||
import type { GroupSystemMessageQuery } from './modules/contact-actions';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import { RETCODE, failedResponse, okResponse } from './types';
|
||||
@@ -54,7 +55,7 @@ export interface ApiActionContext {
|
||||
deleteEssenceMsg: (messageId: number) => Promise<void>;
|
||||
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
|
||||
handleGetGroupSystemMsg: (query: GroupSystemMessageQuery) => Promise<JsonObject[]>;
|
||||
getDownloadRKeys: () => Promise<JsonObject[]>;
|
||||
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
|
||||
@@ -81,7 +81,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
|
||||
getGroupMsgHistory: (groupId, messageId, count) => getGroupHistory(ref, groupId, messageId, count),
|
||||
getFriendMsgHistory: (userId, messageId, count) => getFriendHistory(ref, userId, messageId, count),
|
||||
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
|
||||
handleGetGroupSystemMsg: (query) => getGroupSystemMessages(bridge, query),
|
||||
getDownloadRKeys: () => getDownloadRKeys(bridge),
|
||||
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
|
||||
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
|
||||
@@ -125,4 +125,3 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
}
|
||||
|
||||
export type { Bridge, WebHonorType };
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
|
||||
import {
|
||||
formatGroupRequestFlag,
|
||||
type GroupRequestInfo,
|
||||
type UserProfileInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
const REQUESTER_PROFILE_CONCURRENCY = 4;
|
||||
|
||||
export interface GroupSystemMessageQuery {
|
||||
groupId?: number;
|
||||
onlyPending?: boolean;
|
||||
}
|
||||
|
||||
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
|
||||
const userId = parseInt(ref.uin, 10) || 0;
|
||||
const nickname = ref.bridge.identity.nickname || ref.uin;
|
||||
@@ -230,21 +242,70 @@ export async function getStrangerInfo(
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
try {
|
||||
const reqs = await bridge.apis.contacts.fetchGroupRequests();
|
||||
return reqs.map(r => ({
|
||||
group_id: r.groupId,
|
||||
group_name: r.groupName,
|
||||
request_id: r.sequence,
|
||||
requester_uin: r.targetUin,
|
||||
requester_nick: r.targetName,
|
||||
message: r.comment,
|
||||
flag: formatGroupRequestFlag(r),
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
async function resolveRequesterUins(
|
||||
bridge: BridgeInterface,
|
||||
requests: readonly GroupRequestInfo[],
|
||||
): Promise<Map<string, number>> {
|
||||
const resolved = new Map<string, number>();
|
||||
const unresolved = new Set<string>();
|
||||
|
||||
for (const request of requests) {
|
||||
const uid = request.targetUid;
|
||||
if (!uid || resolved.has(uid)) continue;
|
||||
if (request.targetUin > 0) {
|
||||
resolved.set(uid, request.targetUin);
|
||||
unresolved.delete(uid);
|
||||
continue;
|
||||
}
|
||||
if (unresolved.has(uid)) continue;
|
||||
const cached = bridge.identity.findUinByUid(uid, request.groupId)
|
||||
?? bridge.identity.findUinByUid(uid);
|
||||
if (cached && cached > 0) resolved.set(uid, cached);
|
||||
else unresolved.add(uid);
|
||||
}
|
||||
|
||||
const profiles = await mapWithConcurrency(
|
||||
[...unresolved],
|
||||
REQUESTER_PROFILE_CONCURRENCY,
|
||||
async (uid) => {
|
||||
let profile: UserProfileInfo;
|
||||
try {
|
||||
profile = await bridge.apis.contacts.fetchUserProfileByUid(uid);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`failed to resolve requester UIN for UID ${uid}: ${message}`, { cause: error });
|
||||
}
|
||||
if (!Number.isSafeInteger(profile.uin) || profile.uin <= 0) {
|
||||
throw new Error(`failed to resolve requester UIN for UID ${uid}`);
|
||||
}
|
||||
return [uid, profile.uin] as const;
|
||||
},
|
||||
);
|
||||
for (const [uid, uin] of profiles) resolved.set(uid, uin);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
export async function getGroupSystemMessages(
|
||||
bridge: BridgeInterface,
|
||||
query: GroupSystemMessageQuery = {},
|
||||
): Promise<JsonObject[]> {
|
||||
const requests = (await bridge.apis.contacts.fetchGroupRequests()).filter((request) => {
|
||||
if (query.groupId !== undefined && request.groupId !== query.groupId) return false;
|
||||
if (query.onlyPending && request.state !== 1) return false;
|
||||
return true;
|
||||
});
|
||||
const requesterUins = await resolveRequesterUins(bridge, requests);
|
||||
|
||||
return requests.map((request) => ({
|
||||
group_id: request.groupId,
|
||||
group_name: request.groupName,
|
||||
request_id: request.sequence,
|
||||
requester_uin: requesterUins.get(request.targetUid) ?? request.targetUin,
|
||||
requester_nick: request.targetName,
|
||||
message: request.comment,
|
||||
checked: request.state !== 1,
|
||||
flag: formatGroupRequestFlag(request),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { defineAction, defineStreamAction, type RegisteredActionSpec } from '../src/action-kit';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import {
|
||||
@@ -129,6 +129,25 @@ describe('compiled production Action registry', () => {
|
||||
.map((entry) => [entry.name, entry.kind]),
|
||||
);
|
||||
});
|
||||
|
||||
it('validates and forwards get_group_system_msg filters', async () => {
|
||||
const handleGetGroupSystemMsg = vi.fn(async () => []);
|
||||
const handler = new ApiHandler({ handleGetGroupSystemMsg } as unknown as ApiActionContext);
|
||||
|
||||
const response = await handler.handle('get_group_system_msg', {
|
||||
group_id: '100000002',
|
||||
only_pending: true,
|
||||
});
|
||||
|
||||
expect(response.status).toBe('ok');
|
||||
expect(handleGetGroupSystemMsg).toHaveBeenCalledWith({
|
||||
groupId: 100000002,
|
||||
onlyPending: true,
|
||||
});
|
||||
const doc = ACTION_REGISTRY.resolve('get_group_system_msg');
|
||||
if (!doc || doc.kind === 'raw') throw new Error('get_group_system_msg action missing');
|
||||
expect(doc.action.doc.params.map((param) => param.name)).toEqual(['group_id', 'only_pending']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiHandler constructor-time registry transaction', () => {
|
||||
|
||||
@@ -34,7 +34,8 @@ import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
const APIS_ROUTING: Record<string, string> = {
|
||||
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
|
||||
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
|
||||
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
|
||||
fetchUserProfileByUid: 'contacts', fetchGroupRequests: 'contacts',
|
||||
fetchDownloadRKeys: 'contacts',
|
||||
fetchGroupDetail: 'contacts',
|
||||
};
|
||||
|
||||
@@ -393,7 +394,105 @@ describe('onebot/contact-actions / getGroupSystemMessages', () => {
|
||||
expect(result[0]).toMatchObject({
|
||||
request_id: 123456,
|
||||
group_id: 999,
|
||||
checked: false,
|
||||
flag: 'slreq:1:123456:999:22:1',
|
||||
});
|
||||
});
|
||||
|
||||
it('filters by group and pending state before resolving requester identities', async () => {
|
||||
const fetchUserProfileByUid = vi.fn(async (uid: string) =>
|
||||
makeProfile(uid === 'u_pending' ? 101 : 202, uid));
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
makeGroupRequest({ groupId: 100, sequence: 1, state: 1, targetUid: 'u_pending', targetUin: 0 }),
|
||||
makeGroupRequest({ groupId: 100, sequence: 2, state: 2, targetUid: 'u_checked', targetUin: 0 }),
|
||||
makeGroupRequest({ groupId: 200, sequence: 3, state: 1, targetUid: 'u_other_group', targetUin: 0 }),
|
||||
]),
|
||||
fetchUserProfileByUid,
|
||||
identity: fakeIdentity({ findUinByUid: () => null }),
|
||||
});
|
||||
|
||||
const result = await getGroupSystemMessages(bridge, { groupId: 100, onlyPending: true });
|
||||
|
||||
expect(result).toEqual([expect.objectContaining({
|
||||
group_id: 100,
|
||||
request_id: 1,
|
||||
requester_uin: 101,
|
||||
checked: false,
|
||||
})]);
|
||||
expect(fetchUserProfileByUid).toHaveBeenCalledOnce();
|
||||
expect(fetchUserProfileByUid).toHaveBeenCalledWith('u_pending');
|
||||
});
|
||||
|
||||
it('deduplicates requester profile lookups and limits QQ query concurrency', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const fetchUserProfileByUid = vi.fn(async (uid: string) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
inFlight--;
|
||||
return makeProfile(1_000 + Number(uid.slice(2)), uid);
|
||||
});
|
||||
const requests = Array.from({ length: 6 }, (_, index) => makeGroupRequest({
|
||||
sequence: index + 1,
|
||||
targetUid: `u_${index + 1}`,
|
||||
targetUin: 0,
|
||||
}));
|
||||
requests.push(makeGroupRequest({ sequence: 7, targetUid: 'u_1', targetUin: 0 }));
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => requests),
|
||||
fetchUserProfileByUid,
|
||||
identity: fakeIdentity({ findUinByUid: () => null }),
|
||||
});
|
||||
|
||||
const result = await getGroupSystemMessages(bridge);
|
||||
|
||||
expect(fetchUserProfileByUid).toHaveBeenCalledTimes(6);
|
||||
expect(peak).toBeLessThanOrEqual(4);
|
||||
expect(result.map((item) => item.requester_uin)).toEqual([
|
||||
1001, 1002, 1003, 1004, 1005, 1006, 1001,
|
||||
]);
|
||||
});
|
||||
|
||||
it('uses a known UIN from a duplicate request without querying QQ', async () => {
|
||||
const fetchUserProfileByUid = vi.fn(async () => {
|
||||
throw new Error('profile lookup must not run');
|
||||
});
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
makeGroupRequest({ sequence: 1, targetUid: 'u_known', targetUin: 0 }),
|
||||
makeGroupRequest({ sequence: 2, targetUid: 'u_known', targetUin: 4242 }),
|
||||
]),
|
||||
fetchUserProfileByUid,
|
||||
identity: fakeIdentity({ findUinByUid: () => null }),
|
||||
});
|
||||
|
||||
const result = await getGroupSystemMessages(bridge);
|
||||
|
||||
expect(fetchUserProfileByUid).not.toHaveBeenCalled();
|
||||
expect(result.map((item) => item.requester_uin)).toEqual([4242, 4242]);
|
||||
});
|
||||
|
||||
it('propagates inbox failures instead of disguising them as an empty list', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => { throw new Error('OIDB unavailable'); }),
|
||||
});
|
||||
|
||||
await expect(getGroupSystemMessages(bridge)).rejects.toThrow('OIDB unavailable');
|
||||
});
|
||||
|
||||
it('identifies the requester UID when profile resolution fails', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
makeGroupRequest({ targetUid: 'u_missing', targetUin: 0 }),
|
||||
]),
|
||||
fetchUserProfileByUid: vi.fn(async () => { throw new Error('profile OIDB unavailable'); }),
|
||||
identity: fakeIdentity({ findUinByUid: () => null }),
|
||||
});
|
||||
|
||||
await expect(getGroupSystemMessages(bridge)).rejects.toThrow(
|
||||
'failed to resolve requester UIN for UID u_missing: profile OIDB unavailable',
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user