diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index dbd61704..6b6f1f4a 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -24,6 +24,17 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; // resolve a forward immediately after receiving the parent message. const forwardResCache = new Map(); +/** QQ's placeholder when it doesn't hand back a real sender name — treated as + * "missing" so #174's enrichment resolves the real nickname. */ +const FORWARD_NAME_PLACEHOLDER = 'QQ用户'; + +/** Bounds on the L4 (per-uin profile) fallback when enriching forward senders. + * Profile lookups are un-cached single-point OIDB calls Tencent rate-limits + * aggressively, so cap how many distinct uins one forward resolves and how + * many run at once — the rest keep the placeholder. */ +const FORWARD_PROFILE_MAX = 20; +const FORWARD_PROFILE_CONCURRENCY = 4; + // Per-layer piggyback entry. Each level of a nested forward attaches // its own msgBody under a uuid `actionCommand`, so when the receiver // fetches the outermost res_id it gets every layer in one shot @@ -518,7 +529,7 @@ export class ForwardApi { const bridge = asBridge(this.ctx); const cached = forwardResCache.get(resId); if (cached) { - return cached.map(node => ({ + const nodes = cached.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements], @@ -529,6 +540,10 @@ export class ForwardApi { senderCard: node.senderCard, messageType: node.messageType, })); + // Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich + // on read (a no-op once names are present) and persist so later hits skip. + if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes)); + return nodes; } const selfUid = await resolveSelfUid(bridge); @@ -588,12 +603,96 @@ export class ForwardApi { this.consumePiggybacks(nodes, piggybackByUuid); } + // Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty + // or stamped with the "QQ用户" placeholder (#174) — the long-msg member name + // isn't always populated, and the sync decode only consults the L1 cache. + await this.enrichSenders(nodes); + if (nodes.length > 0) { forwardResCache.set(resId, cloneNodes(nodes)); } return nodes; } + /** A node whose display name the server didn't give us (empty or the QQ + * placeholder) and that we can resolve (has a uin). */ + private needsName(n: ForwardNodePayload): boolean { + return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER); + } + + /** Backfill sender nickname/card on forward nodes the long-msg payload left + * nameless. Resolves group senders via one member-list fetch per group (L3, + * inflight+TTL cached in ContactsApi), then any residue + private nodes via + * the user-profile lookup (L4). Best-effort: a failed lookup keeps the + * placeholder rather than failing the whole forward. Returns true if any + * node was changed (so callers can persist the enriched cache). */ + private async enrichSenders(nodes: ForwardNodePayload[]): Promise { + const pending = nodes.filter(n => this.needsName(n)); + if (pending.length === 0) return false; + let changed = false; + + // L3 — group member lists (one fetch resolves every sender from that group). + const byGroup = new Map(); + const residue: ForwardNodePayload[] = []; + for (const n of pending) { + if (n.messageType === 'group' && n.groupId) { + const arr = byGroup.get(n.groupId) ?? []; + arr.push(n); + byGroup.set(n.groupId, arr); + } else { + residue.push(n); + } + } + for (const [groupId, groupNodes] of byGroup) { + let byUin: Map; + try { + const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId); + byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }])); + } catch { + // Member list (one cheap, cached call) failed — keep the placeholder + // rather than fanning the whole group out to per-uin profile lookups. + // That error path is exactly what would amplify into a rate-limit ban. + continue; + } + for (const n of groupNodes) { + const m = byUin.get(n.userUin); + const name = m?.card || m?.nickname; + if (name) { + n.senderCard = m!.card || n.senderCard || ''; + n.nickname = name; + changed = true; + } else { + residue.push(n); // in-group sender that left the group → profile fallback + } + } + } + + // L4 — user profile for the residue (members who left the group, private + // nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and + // Tencent rate-limits these hard (see ContactsApi's member-list note), so: + // dedupe by uin, CAP the count (drop the rest to placeholder), and resolve + // in small concurrency-limited batches. Best-effort. + const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))] + .slice(0, FORWARD_PROFILE_MAX); + if (uins.length > 0) { + const byUin = new Map(); + for (let i = 0; i < uins.length; i += FORWARD_PROFILE_CONCURRENCY) { + const batch = uins.slice(i, i + FORWARD_PROFILE_CONCURRENCY); + const results = await Promise.all(batch.map(async (uin): Promise => { + try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; } + catch { return [uin, ''] as const; } + })); + for (const [uin, nick] of results) byUin.set(uin, nick); + } + for (const n of residue) { + if (!this.needsName(n)) continue; + const nick = byUin.get(n.userUin); + if (nick) { n.nickname = nick; changed = true; } + } + } + return changed; + } + /** Walk a list of PushMsgBody, run each through the regular msg-push * pipeline, and shape the result into ForwardNodePayloads. Extracted * so both the outer + piggyback decode paths share one implementation. */ diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index fa424d0b..1f47c895 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -151,3 +151,71 @@ describe('actions/forward', () => { expect(sendRawPacket).toHaveBeenCalledOnce(); }); }); + +describe('actions/forward — sender name enrichment (#174)', () => { + function apiWith(contacts: { fetchGroupMemberList: any; fetchUserProfile: any }) { + return new ForwardApi({ apis: { contacts } } as any); + } + + it('fills empty / "QQ用户" names via the group member list (L3), card preferred', async () => { + const fetchGroupMemberList = vi.fn(async () => [ + { uin: 10001, nickname: 'AliceNick', card: 'AliceCard' }, + { uin: 10002, nickname: 'BobNick', card: '' }, + ]); + const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'Stranger' })); + const api = apiWith({ fetchGroupMemberList, fetchUserProfile }); + + const nodes: any[] = [ + { userUin: 10001, nickname: '', groupId: 700, messageType: 'group', elements: [] }, + { userUin: 10002, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] }, + { userUin: 10003, nickname: '', groupId: 700, messageType: 'group', elements: [] }, // not in list + { userUin: 10009, nickname: '', messageType: 'private', elements: [] }, // private + { userUin: 10005, nickname: 'KeepMe', groupId: 700, messageType: 'group', elements: [] }, + ]; + const changed = await (api as any).enrichSenders(nodes); + + expect(changed).toBe(true); + expect(nodes[0].nickname).toBe('AliceCard'); // card preferred over nick + expect(nodes[0].senderCard).toBe('AliceCard'); + expect(nodes[1].nickname).toBe('BobNick'); // card empty → nickname + expect(nodes[2].nickname).toBe('Stranger'); // not in member list → L4 profile + expect(nodes[3].nickname).toBe('Stranger'); // private node → L4 profile + expect(nodes[4].nickname).toBe('KeepMe'); // already named → untouched + expect(fetchGroupMemberList).toHaveBeenCalledTimes(1); // one fetch covers the whole group + }); + + it('is a no-op (no fetch) when every node already has a name', async () => { + const fetchGroupMemberList = vi.fn(); + const fetchUserProfile = vi.fn(); + const api = apiWith({ fetchGroupMemberList, fetchUserProfile }); + const nodes: any[] = [{ userUin: 1, nickname: 'has-name', groupId: 7, messageType: 'group', elements: [] }]; + expect(await (api as any).enrichSenders(nodes)).toBe(false); + expect(fetchGroupMemberList).not.toHaveBeenCalled(); + }); + + it('keeps the placeholder and never throws when resolution fails', async () => { + const api = apiWith({ + fetchGroupMemberList: vi.fn(async () => { throw new Error('net down'); }), + fetchUserProfile: vi.fn(async () => { throw new Error('net down'); }), + }); + const nodes: any[] = [{ userUin: 10001, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] }]; + await expect((api as any).enrichSenders(nodes)).resolves.toBe(false); + expect(nodes[0].nickname).toBe('QQ用户'); + }); + + it('does NOT fan a member-list failure out to per-uin profile lookups (rate-limit guard)', async () => { + const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'X' })); + const api = apiWith({ + fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }), + fetchUserProfile, + }); + // 5 distinct group senders whose member list errors → must keep placeholder, + // NOT trigger 5 profile calls. + const nodes: any[] = Array.from({ length: 5 }, (_, i) => ({ + userUin: 20000 + i, nickname: '', groupId: 700, messageType: 'group', elements: [], + })); + expect(await (api as any).enrichSenders(nodes)).toBe(false); + expect(fetchUserProfile).not.toHaveBeenCalled(); + expect(nodes.every((n) => n.nickname === '')).toBe(true); + }); +});