fix(onebot): expose robot status for group members
Fetch QQ's versioned robot UIN ranges, classify and persist member status, and surface is_robot from both group member actions. Preserve unknown legacy cache entries and fail visibly when classification is unavailable. Closes #265
This commit is contained in:
16 files changed
+596
-36
No files matched your search
@@ -4,6 +4,11 @@ import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetc
|
||||
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import {
|
||||
FetchRobotUinRanges,
|
||||
type RobotUinRange,
|
||||
type RobotUinRangeSnapshot,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
|
||||
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
|
||||
@@ -74,6 +79,12 @@ export function permissionToRole(permission: number): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean {
|
||||
return Number.isInteger(uin)
|
||||
&& uin > 0
|
||||
&& ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin);
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
@@ -91,9 +102,38 @@ export class ContactsApi {
|
||||
ttlMs: MEMBER_LIST_TTL_MS,
|
||||
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
|
||||
});
|
||||
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
|
||||
if (this.robotUinRangesPromise_) return this.robotUinRangesPromise_;
|
||||
|
||||
const pending = FetchRobotUinRanges.invoke(this.ctx).then((snapshot) => {
|
||||
log.info(
|
||||
'loaded robot UIN ranges uin=%s version=%d count=%d',
|
||||
this.ctx.identity.uin,
|
||||
snapshot.version,
|
||||
snapshot.ranges.length,
|
||||
);
|
||||
return snapshot;
|
||||
});
|
||||
this.robotUinRangesPromise_ = pending;
|
||||
|
||||
// A failed first load must be observable and retryable. Keep the rejection
|
||||
// visible to the caller instead of converting every member to false.
|
||||
void pending.catch((err: unknown) => {
|
||||
if (this.robotUinRangesPromise_ === pending) this.robotUinRangesPromise_ = null;
|
||||
log.error(
|
||||
'failed to load robot UIN ranges: uin=%s group=%d err=%s',
|
||||
this.ctx.identity.uin,
|
||||
groupId,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Server-built ARK share card (JSON string) recommending a friend. */
|
||||
getBuddyRecommendArk(userId: number, phoneNumber = ''): Promise<string> {
|
||||
return GetBuddyRecommendArk.invoke(this.ctx, { userId, phoneNumber });
|
||||
@@ -241,6 +281,10 @@ export class ContactsApi {
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
// QQ's native group service obtains the robot classification separately
|
||||
// from 0xFE7_3. Start both reads together so the metadata adds no serial
|
||||
// round trip to paginated member fetches.
|
||||
const robotSnapshotPromise = this.fetchRobotUinRanges(groupId);
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
do {
|
||||
@@ -251,6 +295,7 @@ export class ContactsApi {
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
isRobot: false,
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
@@ -262,6 +307,11 @@ export class ContactsApi {
|
||||
token = resp.token ?? '';
|
||||
} while (token);
|
||||
|
||||
const robotSnapshot = await robotSnapshotPromise;
|
||||
for (const member of members) {
|
||||
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
@@ -5,9 +5,14 @@ import type {
|
||||
OidbBase,
|
||||
OidbFriend,
|
||||
OidbFriendCategory,
|
||||
OidbRobotUinRangeResponse,
|
||||
OidbSvcTrpcTcp0xFD4_1Response,
|
||||
OidbSvcTrpcTcp0xFE7_3Response,
|
||||
} from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type {
|
||||
OidbFriendListRequest,
|
||||
OidbRobotUinRangeRequest,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
|
||||
import { ContactsApi } from '../../src/bridge/apis/contacts';
|
||||
|
||||
@@ -55,6 +60,30 @@ function packet(body: OidbSvcTrpcTcp0xFD4_1Response): SendPacketResult {
|
||||
};
|
||||
}
|
||||
|
||||
function robotRangePacket(body: OidbRobotUinRangeResponse): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<OidbRobotUinRangeResponse>>({ body }),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function memberListPacket(body: OidbSvcTrpcTcp0xFE7_3Response): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>({ body }),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) {
|
||||
let index = 0;
|
||||
const sendRawPacket = vi.fn(async (
|
||||
@@ -160,3 +189,91 @@ describe('apis/contacts / categorized friend roster', () => {
|
||||
.rejects.toThrow('repeated friend-list cookie aa');
|
||||
});
|
||||
});
|
||||
|
||||
describe('apis/contacts / robot group-member classification', () => {
|
||||
it('loads QQ robot ranges once and marks every fetched member', async () => {
|
||||
const rememberGroupMembers = vi.fn();
|
||||
const sendRawPacket = vi.fn(async (cmd: string, _data: Uint8Array): Promise<SendPacketResult> => {
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x496_0') {
|
||||
return robotRangePacket({
|
||||
robotConfig: {
|
||||
version: 206,
|
||||
ranges: [{ minUin: 3_889_000_000n, maxUin: 3_889_999_999n }],
|
||||
},
|
||||
});
|
||||
}
|
||||
if (cmd === 'OidbSvcTrpcTcp.0xfe7_3') {
|
||||
return memberListPacket({
|
||||
groupUin: 42,
|
||||
members: [
|
||||
{ uin: { uid: 'u_robot', uin: 3_889_054_356 }, memberName: 'robot' },
|
||||
{ uin: { uid: 'u_person', uin: 1_234_567_890 }, memberName: 'person' },
|
||||
],
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected command: ${cmd}`);
|
||||
});
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { uin: '10001', rememberGroupMembers },
|
||||
} as any);
|
||||
|
||||
const first = await api.fetchGroupMemberList(42);
|
||||
const second = await api.fetchGroupMemberList(42, { force: true });
|
||||
|
||||
expect(first).toEqual([
|
||||
expect.objectContaining({ uin: 3_889_054_356, isRobot: true }),
|
||||
expect.objectContaining({ uin: 1_234_567_890, isRobot: false }),
|
||||
]);
|
||||
expect(second).toEqual(first);
|
||||
expect(rememberGroupMembers).toHaveBeenCalledWith(42, first);
|
||||
expect(sendRawPacket.mock.calls.map(([cmd]) => cmd).sort()).toEqual([
|
||||
'OidbSvcTrpcTcp.0x496_0',
|
||||
'OidbSvcTrpcTcp.0xfe7_3',
|
||||
'OidbSvcTrpcTcp.0xfe7_3',
|
||||
]);
|
||||
expect(sendRawPacket.mock.calls.filter(([cmd]) => cmd === 'OidbSvcTrpcTcp.0x496_0'))
|
||||
.toHaveLength(1);
|
||||
|
||||
const rangeCall = sendRawPacket.mock.calls.find(([cmd]) => cmd === 'OidbSvcTrpcTcp.0x496_0')!;
|
||||
const request = protobuf_decode<OidbBase<OidbRobotUinRangeRequest>>(rangeCall[1]);
|
||||
expect(request.body).toMatchObject({ justFetchMsgConfig: 1, type: 1 });
|
||||
});
|
||||
|
||||
it('propagates an invalid range snapshot and retries it on the next fetch', async () => {
|
||||
let rangeAttempts = 0;
|
||||
const sendRawPacket = vi.fn(async (cmd: string, _data: Uint8Array): Promise<SendPacketResult> => {
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x496_0') {
|
||||
rangeAttempts += 1;
|
||||
return rangeAttempts === 1
|
||||
? robotRangePacket({})
|
||||
: robotRangePacket({
|
||||
robotConfig: {
|
||||
version: 206,
|
||||
ranges: [{ minUin: 3_889_000_000n, maxUin: 3_889_999_999n }],
|
||||
},
|
||||
});
|
||||
}
|
||||
if (cmd === 'OidbSvcTrpcTcp.0xfe7_3') {
|
||||
return memberListPacket({
|
||||
groupUin: 42,
|
||||
members: [{ uin: { uid: 'u_robot', uin: 3_889_054_356 }, memberName: 'robot' }],
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected command: ${cmd}`);
|
||||
});
|
||||
const rememberGroupMembers = vi.fn();
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { uin: '10001', rememberGroupMembers },
|
||||
} as any);
|
||||
|
||||
await expect(api.fetchGroupMemberList(42))
|
||||
.rejects.toThrow('0x496_0 response missing robot range config');
|
||||
await expect(api.fetchGroupMemberList(42))
|
||||
.resolves.toEqual([expect.objectContaining({ isRobot: true })]);
|
||||
|
||||
expect(rangeAttempts).toBe(2);
|
||||
expect(rememberGroupMembers).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ function makeGroupMember(uin: number, uid: string): GroupMemberInfo {
|
||||
uid,
|
||||
nickname: '',
|
||||
card: '',
|
||||
isRobot: false,
|
||||
role: 'member',
|
||||
level: 0,
|
||||
title: '',
|
||||
|
||||
@@ -51,12 +51,13 @@ function makeGroup(): QQGroupInfo {
|
||||
};
|
||||
}
|
||||
|
||||
function makeMember(uin: number, uid: string, card = ''): GroupMemberInfo {
|
||||
function makeMember(uin: number, uid: string, card = '', isRobot = false): GroupMemberInfo {
|
||||
return {
|
||||
uin,
|
||||
uid,
|
||||
nickname: `nick-${uin}`,
|
||||
card,
|
||||
isRobot,
|
||||
role: 'member',
|
||||
level: 1,
|
||||
title: '',
|
||||
@@ -96,6 +97,82 @@ describe('IdentityService', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('persists group member robot classification across restarts', () => {
|
||||
const dbPath = tempDbPath('persist-robot');
|
||||
|
||||
{
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_robot', '', true)]);
|
||||
identity.close();
|
||||
}
|
||||
|
||||
{
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBe(true);
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('migrates legacy member caches without inventing a robot classification', () => {
|
||||
const dbPath = tempDbPath('migrate-robot');
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
legacy.exec(`
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid TEXT UNIQUE,
|
||||
uin INTEGER UNIQUE,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
is_friend INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE groups (
|
||||
group_id INTEGER PRIMARY KEY,
|
||||
group_name TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
member_count INTEGER NOT NULL DEFAULT 0,
|
||||
member_max INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE group_members (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
group_id INTEGER NOT NULL,
|
||||
uid TEXT,
|
||||
uin INTEGER,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
card TEXT NOT NULL DEFAULT '',
|
||||
role TEXT NOT NULL DEFAULT 'member',
|
||||
level INTEGER NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
join_time INTEGER NOT NULL DEFAULT 0,
|
||||
last_sent_time INTEGER NOT NULL DEFAULT 0,
|
||||
shut_up_time INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(group_id, uid),
|
||||
UNIQUE(group_id, uin)
|
||||
);
|
||||
INSERT INTO groups (group_id, group_name, updated_at)
|
||||
VALUES (${GROUP_ID}, 'legacy-group', 1);
|
||||
INSERT INTO group_members (group_id, uid, uin, nickname, updated_at)
|
||||
VALUES (${GROUP_ID}, 'u_legacy', 33333, 'legacy-member', 1);
|
||||
`);
|
||||
legacy.close();
|
||||
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
|
||||
identity.close();
|
||||
|
||||
const migrated = new DatabaseSync(dbPath);
|
||||
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{ name: string }>;
|
||||
expect(columns.map((column) => column.name)).toContain('is_robot');
|
||||
migrated.close();
|
||||
});
|
||||
|
||||
it('keeps updateGroupMember changes after reopening the persistent cache', () => {
|
||||
const dbPath = tempDbPath('update-member');
|
||||
const member = makeMember(33333, 'u_member', 'old-card');
|
||||
|
||||
@@ -39,6 +39,7 @@ function makeGroupMember(uin: number, uid: string): GroupMemberInfo {
|
||||
uid,
|
||||
nickname: '',
|
||||
card: '',
|
||||
isRobot: false,
|
||||
role: 'member',
|
||||
level: 0,
|
||||
title: '',
|
||||
|
||||
Reference in new issue
Block a user