refactor(identity): absorb QQInfo into IdentityService
QQInfo's in-memory state (self identity, friends, group rosters,
profile cache) and read methods (findFriend / findGroup /
findGroupMember / findUserProfile / nickname / uin / selfProfile) now
live directly on IdentityService. The QQInfo class is gone; its
interfaces stay in `qq-info.ts` as plain types shared across the
remember*/find* surface.
This eliminates a long-standing duplication: every observation used to
maintain both QQInfo's in-memory structures and IdentityService's
SQLite mirror in parallel, with the uidByUin/uinByUid Maps tracked
separately. With one Module owning all three layers, every remember*
hydrates one set of structures and `loadSnapshot` repopulates the
in-memory uid↔uin index from SQLite on startup — closing the cold-cache
gap that previously forced findUidByUin to fall through to a SQLite
query after every restart.
Knock-on changes:
- `Bridge` no longer holds a QQInfo; constructor takes an
`IdentityService`. The CmdParser signature on the cmd dispatch
table now passes `IdentityService` to parsers.
- `msg-push-handler.ts` drops its private `resolveUidToUin(qqInfo, …)`
helper that bypassed IdentityService's cascade — the parser hot
path now reads through `identity.findUinByUid(uid, groupId)` and
benefits from the O(1) `uinByUid` map even on freshly-loaded
sessions.
- `BridgeManager`'s session-started callback drops the QQInfo
parameter; OneBotInstance no longer carries a `qqInfo` field and
exposes a `nickname` getter for the WebUI listing.
- `contact-actions` and the per-theme bridge action files stop
importing QQInfo; they read everything via `bridge.identity.*`.
This commit is contained in:
27 files changed
+363
-428
No files matched your search
@@ -29,7 +29,7 @@ async function buildForwardPushBody(
|
||||
bridge: Bridge,
|
||||
node: ForwardNodePayload,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.qqInfo.uin);
|
||||
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
|
||||
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
|
||||
|
||||
const nickname = node.nickname.trim() || String(fromUin);
|
||||
@@ -41,7 +41,7 @@ async function buildForwardPushBody(
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin,
|
||||
toUid: bridge.qqInfo.selfUid ?? '',
|
||||
toUid: bridge.identity.selfUid ?? '',
|
||||
forward: {
|
||||
friendName: nickname,
|
||||
},
|
||||
@@ -173,14 +173,14 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<
|
||||
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
|
||||
const pkt: PacketInfo = {
|
||||
pid: 0,
|
||||
uin: bridge.qqInfo.uin,
|
||||
uin: bridge.identity.uin,
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
seqId: 0,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: wrapped,
|
||||
};
|
||||
const events = parseMsgPush(pkt, bridge.qqInfo);
|
||||
const events = parseMsgPush(pkt, bridge.identity);
|
||||
const event = events.find(e =>
|
||||
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
|
||||
if (!event) continue;
|
||||
|
||||
@@ -123,7 +123,7 @@ export async function getGroupAtAllRemain(
|
||||
basic1: 1,
|
||||
basic2: 2,
|
||||
basic3: 1,
|
||||
uin: BigInt(bridge.qqInfo.uin),
|
||||
uin: BigInt(bridge.identity.uin),
|
||||
groupId: BigInt(groupId),
|
||||
type: 0,
|
||||
};
|
||||
|
||||
@@ -327,7 +327,7 @@ export async function uploadGroupFile(
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(bridge.qqInfo.uin);
|
||||
const senderUin = toInt(bridge.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
@@ -369,16 +369,16 @@ export async function uploadPrivateFile(
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await bridge.resolveUserUid(userId);
|
||||
let selfUid = bridge.qqInfo.selfUid;
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (!selfUid) {
|
||||
const selfUin = toInt(bridge.qqInfo.uin);
|
||||
const selfUin = toInt(bridge.identity.uin);
|
||||
if (selfUin > 0) {
|
||||
selfUid = await bridge.resolveUserUid(selfUin);
|
||||
}
|
||||
}
|
||||
if (!selfUid) throw new Error('self uid is unavailable');
|
||||
|
||||
const senderUin = toInt(bridge.qqInfo.uin);
|
||||
const senderUin = toInt(bridge.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
@@ -489,7 +489,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
|
||||
if (type === 1 && item?.fileInfo) {
|
||||
const file = item.fileInfo;
|
||||
const uploader = toInt(file.uploaderUin);
|
||||
const cached = bridge.qqInfo.findGroupMember(groupId, uploader);
|
||||
const cached = bridge.identity.findGroupMember(groupId, uploader);
|
||||
files.push({
|
||||
fileId: typeof file.fileId === 'string' ? file.fileId : '',
|
||||
fileName: typeof file.fileName === 'string' ? file.fileName : '',
|
||||
@@ -508,7 +508,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
|
||||
} else if (type === 2 && item?.folderInfo) {
|
||||
const folder = item.folderInfo;
|
||||
const creator = toInt(folder.creatorUin);
|
||||
const cached = bridge.qqInfo.findGroupMember(groupId, creator);
|
||||
const cached = bridge.identity.findGroupMember(groupId, creator);
|
||||
folders.push({
|
||||
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
|
||||
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
|
||||
|
||||
@@ -155,7 +155,7 @@ export async function sendGroupSign(
|
||||
) {
|
||||
const req = {
|
||||
signInInfo: {
|
||||
uin: String(bridge.qqInfo.uin),
|
||||
uin: String(bridge.identity.uin),
|
||||
groupId: String(groupId),
|
||||
version: '9.0.90',
|
||||
},
|
||||
|
||||
@@ -60,7 +60,7 @@ export async function setProfile(
|
||||
nickname?: string,
|
||||
personalNote?: string,
|
||||
): Promise<void> {
|
||||
const uin = BigInt(bridge.qqInfo.uin);
|
||||
const uin = BigInt(bridge.identity.uin);
|
||||
const stringProfiles: any[] = [];
|
||||
const intProfiles: any[] = [];
|
||||
|
||||
@@ -96,7 +96,7 @@ export async function setSelfLongNick(
|
||||
longNick: string,
|
||||
) {
|
||||
const req = {
|
||||
uin: BigInt(bridge.qqInfo.uin),
|
||||
uin: BigInt(bridge.identity.uin),
|
||||
profile: {
|
||||
tag: 102,
|
||||
value: String(longNick),
|
||||
@@ -220,7 +220,7 @@ export async function getUnidirectionalFriendList(
|
||||
bridge: Bridge,
|
||||
) {
|
||||
const reqObj = {
|
||||
uint64_uin: String(bridge.qqInfo.uin),
|
||||
uint64_uin: String(bridge.identity.uin),
|
||||
uint64_top: 0,
|
||||
uint32_req_num: 99,
|
||||
bytes_cookies: '',
|
||||
@@ -251,7 +251,7 @@ export async function getUnidirectionalFriendList(
|
||||
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
|
||||
const req = {
|
||||
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
|
||||
uin: BigInt(bridge.qqInfo.uin),
|
||||
uin: BigInt(bridge.identity.uin),
|
||||
field3: 1,
|
||||
field6: 1,
|
||||
};
|
||||
@@ -265,5 +265,5 @@ export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promi
|
||||
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
|
||||
}
|
||||
const faceIds = (resp as any).item?.faceIds || [];
|
||||
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.qqInfo.uin}/${id}/0`);
|
||||
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.identity.uin}/${id}/0`);
|
||||
}
|
||||
@@ -36,14 +36,15 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the bot's own UID. Cached on QQInfo when warmed up, but
|
||||
* forward/profile actions need a fast path before warmup completes.
|
||||
* Look up the bot's own UID. Cached on Identity once warmup populates
|
||||
* `selfProfile`; forward/profile actions need this fast path before
|
||||
* warmup completes.
|
||||
*/
|
||||
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
|
||||
let selfUid = bridge.qqInfo.selfUid;
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (selfUid) return selfUid;
|
||||
|
||||
const selfUin = toInt(bridge.qqInfo.uin);
|
||||
const selfUin = toInt(bridge.identity.uin);
|
||||
if (selfUin <= 0) {
|
||||
throw new Error('self uid is unavailable');
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
|
||||
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
|
||||
import { QQInfo } from './qq-info';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push-handler';
|
||||
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||
import { protoEncode, protoDecode } from '../protobuf/decode';
|
||||
@@ -114,7 +113,7 @@ import type { GroupFilesResult } from './actions/group-file';
|
||||
import type { MediaIndexNode } from './actions/shared';
|
||||
import { BridgeEventBus } from './event-bus';
|
||||
|
||||
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
|
||||
type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
|
||||
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
@@ -146,7 +145,6 @@ const eventLog = createLogger('Event');
|
||||
export class Bridge {
|
||||
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
private qqInfo_: QQInfo;
|
||||
readonly identity: IdentityService;
|
||||
private pids_ = new Set<number>();
|
||||
/**
|
||||
@@ -172,8 +170,7 @@ export class Bridge {
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
|
||||
constructor(qqInfo: QQInfo, identity = IdentityService.memory(qqInfo)) {
|
||||
this.qqInfo_ = qqInfo;
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
this.identity.setFetcher({
|
||||
fetchProfile: (uin) => this.fetchUserProfile(uin),
|
||||
@@ -182,8 +179,6 @@ export class Bridge {
|
||||
this.registerDefaultHandlers();
|
||||
}
|
||||
|
||||
get qqInfo(): QQInfo { return this.qqInfo_; }
|
||||
|
||||
dispose(): void {
|
||||
this.identity.close();
|
||||
this.events.clear();
|
||||
@@ -230,7 +225,7 @@ export class Bridge {
|
||||
|
||||
for (const handler of handlers) {
|
||||
try {
|
||||
const events = handler(pkt, this.qqInfo_);
|
||||
const events = handler(pkt, this.identity);
|
||||
for (const event of events) {
|
||||
if (this.needsPreDispatchIdentityRefresh(event)) {
|
||||
void this.dispatchAfterIdentityRefresh(event);
|
||||
@@ -276,7 +271,7 @@ export class Bridge {
|
||||
|
||||
const refreshed = await this.refreshMemberCache(
|
||||
event.groupId,
|
||||
!this.qqInfo_.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
|
||||
!this.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
|
||||
true,
|
||||
);
|
||||
this.resolveMemberIdentityFromCache(event);
|
||||
@@ -300,8 +295,8 @@ export class Bridge {
|
||||
}
|
||||
|
||||
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
|
||||
const selfUin = Number(this.qqInfo_.uin);
|
||||
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.qqInfo_.selfUid);
|
||||
const selfUin = Number(this.identity.uin);
|
||||
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.identity.selfUid);
|
||||
}
|
||||
|
||||
private triggerMemberCacheRefresh(event: QQEventVariant, alreadyRefreshed = false): void {
|
||||
@@ -331,7 +326,7 @@ export class Bridge {
|
||||
|
||||
if (groupId <= 0) return;
|
||||
if (this.memberRefreshTasks_.has(groupId)) return;
|
||||
if (event.kind === 'group_member_join' && !this.qqInfo_.findGroup(groupId)) {
|
||||
if (event.kind === 'group_member_join' && !this.identity.findGroup(groupId)) {
|
||||
refreshGroupList = true;
|
||||
}
|
||||
|
||||
@@ -401,7 +396,7 @@ export class Bridge {
|
||||
if (refreshGroupList) {
|
||||
try { await this.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
if (!this.qqInfo_.findGroup(groupId)) return false;
|
||||
if (!this.identity.findGroup(groupId)) return false;
|
||||
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ export async function uploadHighwayHttp(
|
||||
bridge: Bridge, session: HighwaySession, commandId: number,
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
@@ -201,7 +201,7 @@ export async function uploadHighwayHttp(
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize,
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
|
||||
@@ -2,8 +2,10 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
|
||||
import { QQInfo } from './qq-info';
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('Identity');
|
||||
@@ -77,17 +79,43 @@ interface MemberRow {
|
||||
active: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authoritative store for everything we know about QQ actors observed
|
||||
* during this session: the bot's own identity, friends, groups, group
|
||||
* members, user profiles, plus the bidirectional UID↔UIN index that
|
||||
* powers all OIDB-bound translation.
|
||||
*
|
||||
* Two layers internally:
|
||||
* - In-memory state (this file) — O(1) for find* on the hot path.
|
||||
* - SQLite (optional, opened by openForUin) — survives restarts.
|
||||
*
|
||||
* Both layers are kept in sync by the remember* / refresh paths.
|
||||
* Callers should never reach below the public surface; the cascade and
|
||||
* storage details are intentionally hidden.
|
||||
*/
|
||||
export class IdentityService {
|
||||
private readonly db: DatabaseSync | null;
|
||||
// ─── Self identity ───
|
||||
private readonly uin_: string;
|
||||
private nickname_ = '';
|
||||
private selfProfile_: UserProfileInfo | null = null;
|
||||
|
||||
// ─── In-memory domain state ───
|
||||
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
|
||||
private friends_: FriendInfo[] = [];
|
||||
private readonly groups_ = new Map<number, QQGroupInfo>();
|
||||
|
||||
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
|
||||
private readonly uinByUid = new Map<string, number>();
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: DatabaseSync | null;
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly qqInfo: QQInfo,
|
||||
dbPath: string | null,
|
||||
) {
|
||||
constructor(uin: string, dbPath: string | null) {
|
||||
this.uin_ = uin;
|
||||
|
||||
if (!dbPath) {
|
||||
this.db = null;
|
||||
return;
|
||||
@@ -101,12 +129,12 @@ export class IdentityService {
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
static openForUin(qqInfo: QQInfo, dataRoot = 'data'): IdentityService {
|
||||
return new IdentityService(qqInfo, path.join(dataRoot, qqInfo.uin, 'snowluma_identity.db'));
|
||||
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
|
||||
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
|
||||
}
|
||||
|
||||
static memory(qqInfo: QQInfo): IdentityService {
|
||||
return new IdentityService(qqInfo, null);
|
||||
static memory(uin: string): IdentityService {
|
||||
return new IdentityService(uin, null);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
@@ -121,6 +149,49 @@ export class IdentityService {
|
||||
this.fetcher = fetcher;
|
||||
}
|
||||
|
||||
// ─── Self identity surface ───
|
||||
|
||||
get uin(): string { return this.uin_; }
|
||||
|
||||
get nickname(): string { return this.nickname_; }
|
||||
set nickname(v: string) { this.nickname_ = v; }
|
||||
|
||||
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
|
||||
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
|
||||
|
||||
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
|
||||
|
||||
// ─── Domain object reads ───
|
||||
|
||||
findUserProfile(uin: number): UserProfileInfo | null {
|
||||
return this.userProfiles_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
get friends(): FriendInfo[] { return this.friends_; }
|
||||
|
||||
findFriend(uin: number): FriendInfo | null {
|
||||
return this.friends_.find((f) => f.uin === uin) ?? null;
|
||||
}
|
||||
|
||||
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
|
||||
|
||||
findGroup(groupId: number): QQGroupInfo | null {
|
||||
return this.groups_.get(groupId) ?? null;
|
||||
}
|
||||
|
||||
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
|
||||
return this.groups_.get(groupId)?.members.get(uin) ?? null;
|
||||
}
|
||||
|
||||
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.set(member.uin, member);
|
||||
this.rememberUidUin(member.uid, member.uin);
|
||||
}
|
||||
|
||||
// ─── ID translation ───
|
||||
|
||||
/**
|
||||
* UIN → UID with network fallback. Returns cached value on hit; otherwise
|
||||
* invokes the registered fetcher (typically `bridge.fetchUserProfile`),
|
||||
@@ -149,8 +220,68 @@ export class IdentityService {
|
||||
throw new Error(`failed to resolve UID for UIN ${normalized}`);
|
||||
}
|
||||
|
||||
findUinByUid(uid: string, groupId?: number): number | null {
|
||||
const normalized = normalizeUid(uid);
|
||||
if (!normalized) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const member = this.findGroupMemberByUid(groupId, normalized);
|
||||
if (member) return member.uin;
|
||||
}
|
||||
const mapped = this.uinByUid.get(normalized);
|
||||
if (mapped !== undefined) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
`SELECT uin FROM group_members
|
||||
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uin: number | null } | undefined;
|
||||
const uin = normalizeUin(row?.uin);
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uin: number | null } | undefined;
|
||||
return normalizeUin(row?.uin);
|
||||
}
|
||||
|
||||
findUidByUin(uin: number, groupId?: number): string | null {
|
||||
const normalized = normalizeUin(uin);
|
||||
if (normalized === null) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const member = this.groups_.get(groupId)?.members.get(normalized);
|
||||
if (member?.uid) return member.uid;
|
||||
}
|
||||
const mapped = this.uidByUin.get(normalized);
|
||||
if (mapped) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
`SELECT uid FROM group_members
|
||||
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uid: string | null } | undefined;
|
||||
const uid = normalizeUid(row?.uid);
|
||||
if (uid) return uid;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uid: string | null } | undefined;
|
||||
return normalizeUid(row?.uid) || null;
|
||||
}
|
||||
|
||||
// ─── Observation (write side) ───
|
||||
|
||||
rememberFriends(friends: FriendInfo[]): void {
|
||||
this.qqInfo.setFriends(friends);
|
||||
this.friends_ = friends;
|
||||
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
|
||||
this.runWrite('friends', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
|
||||
@@ -169,7 +300,7 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
rememberGroups(groups: QQGroupInfo[]): void {
|
||||
this.qqInfo.setGroups(groups);
|
||||
this.setGroupsInMemory(groups);
|
||||
this.runWrite('groups', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
.run(nowSeconds());
|
||||
@@ -187,7 +318,7 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||
this.qqInfo.setGroupMembers(groupId, members);
|
||||
this.setGroupMembersInMemory(groupId, members);
|
||||
for (const member of members) this.rememberUidUin(member.uid, member.uin);
|
||||
this.runWrite('group members', () => this.transaction(() => {
|
||||
this.upsertGroup({ groupId, memberCount: members.length });
|
||||
@@ -213,9 +344,9 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
rememberUserProfile(info: UserProfileInfo): void {
|
||||
this.qqInfo.setUserProfile(info);
|
||||
const selfUin = parseInt(this.qqInfo.uin, 10) || 0;
|
||||
if (info.uin === selfUin) this.qqInfo.setSelfProfile(info);
|
||||
this.userProfiles_.set(info.uin, info);
|
||||
const selfUin = parseInt(this.uin_, 10) || 0;
|
||||
if (info.uin === selfUin) this.selfProfile_ = info;
|
||||
this.rememberUidUin(info.uid, info.uin);
|
||||
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
|
||||
uid: info.uid,
|
||||
@@ -303,67 +434,7 @@ export class IdentityService {
|
||||
});
|
||||
}
|
||||
|
||||
findUinByUid(uid: string, groupId?: number): number | null {
|
||||
const normalized = normalizeUid(uid);
|
||||
if (!normalized) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const cached = this.qqInfo.resolveGroupMemberUid(groupId, normalized);
|
||||
if (cached !== null) return cached;
|
||||
}
|
||||
const globalCached = this.qqInfo.resolveUid(normalized);
|
||||
if (globalCached !== null) return globalCached;
|
||||
const mapped = this.uinByUid.get(normalized);
|
||||
if (mapped !== undefined) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
`SELECT uin FROM group_members
|
||||
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uin: number | null } | undefined;
|
||||
const uin = normalizeUin(row?.uin);
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uin: number | null } | undefined;
|
||||
return normalizeUin(row?.uin);
|
||||
}
|
||||
|
||||
findUidByUin(uin: number, groupId?: number): string | null {
|
||||
const normalized = normalizeUin(uin);
|
||||
if (normalized === null) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const cached = this.qqInfo.findUidByUinInGroup(groupId, normalized);
|
||||
if (cached) return cached;
|
||||
}
|
||||
const globalCached = this.qqInfo.findUidByUin(normalized);
|
||||
if (globalCached) return globalCached;
|
||||
const mapped = this.uidByUin.get(normalized);
|
||||
if (mapped) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
`SELECT uid FROM group_members
|
||||
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uid: string | null } | undefined;
|
||||
const uid = normalizeUid(row?.uid);
|
||||
if (uid) return uid;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uid: string | null } | undefined;
|
||||
return normalizeUid(row?.uid) || null;
|
||||
}
|
||||
// ─── Private helpers ───
|
||||
|
||||
private rememberUidUin(uid: unknown, uin: unknown): void {
|
||||
const normalizedUid = normalizeUid(uid);
|
||||
@@ -373,6 +444,38 @@ export class IdentityService {
|
||||
this.uidByUin.set(normalizedUin, normalizedUid);
|
||||
}
|
||||
|
||||
private setGroupsInMemory(groups: QQGroupInfo[]): void {
|
||||
// Preserve existing member maps where possible so a roster refresh
|
||||
// doesn't blow away cached members for groups we already track.
|
||||
const previous = new Map(this.groups_);
|
||||
this.groups_.clear();
|
||||
for (const g of groups) {
|
||||
const existing = previous.get(g.groupId);
|
||||
this.groups_.set(g.groupId, {
|
||||
...g,
|
||||
members: existing?.members ?? g.members ?? new Map(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.clear();
|
||||
for (const m of members) {
|
||||
g.members.set(m.uin, m);
|
||||
}
|
||||
}
|
||||
|
||||
private findGroupMemberByUid(groupId: number, uid: string): GroupMemberInfo | null {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return null;
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uid === uid) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db!.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
@@ -431,12 +534,13 @@ export class IdentityService {
|
||||
FROM users
|
||||
WHERE is_friend = 1 AND uin IS NOT NULL`,
|
||||
).all() as Array<{ uid: string | null; uin: number | null; nickname: string; remark: string }>;
|
||||
this.qqInfo.setFriends(friendRows.map((row) => ({
|
||||
this.friends_ = friendRows.map((row) => ({
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
remark: row.remark,
|
||||
})));
|
||||
}));
|
||||
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
|
||||
|
||||
const groups = this.db!.prepare(
|
||||
`SELECT group_id, group_name, remark, member_count, member_max
|
||||
@@ -449,7 +553,7 @@ export class IdentityService {
|
||||
member_count: number;
|
||||
member_max: number;
|
||||
}>;
|
||||
this.qqInfo.setGroups(groups.map((row) => ({
|
||||
this.setGroupsInMemory(groups.map((row) => ({
|
||||
groupId: row.group_id,
|
||||
groupName: row.group_name,
|
||||
remark: row.remark,
|
||||
@@ -463,7 +567,6 @@ export class IdentityService {
|
||||
private hydrateActiveMembersForGroups(groupIds: number[]): void {
|
||||
if (!this.db || groupIds.length === 0) return;
|
||||
|
||||
const membersByGroup = new Map<number, GroupMemberInfo[]>();
|
||||
const select = this.db.prepare(
|
||||
`SELECT group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time
|
||||
@@ -484,11 +587,9 @@ export class IdentityService {
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
}>;
|
||||
membersByGroup.set(groupId, rows.map(rowToMemberInfo));
|
||||
}
|
||||
|
||||
for (const [groupId, members] of membersByGroup) {
|
||||
this.qqInfo.setGroupMembers(groupId, members);
|
||||
const members = rows.map(rowToMemberInfo);
|
||||
this.setGroupMembersInMemory(groupId, members);
|
||||
for (const m of members) this.rememberUidUin(m.uid, m.uin);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,15 +6,13 @@
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import { Bridge } from './bridge';
|
||||
import { IdentityService } from './identity-service';
|
||||
import { QQInfo } from './qq-info';
|
||||
import type { PacketSender } from '../protocol/packet-sender';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
|
||||
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
|
||||
interface QQSession {
|
||||
qqInfo: QQInfo;
|
||||
bridge: Bridge;
|
||||
}
|
||||
|
||||
@@ -67,7 +65,7 @@ export class BridgeManager {
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,7 +90,7 @@ export class BridgeManager {
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,9 +102,8 @@ export class BridgeManager {
|
||||
let session = this.sessions_.get(uin);
|
||||
if (session) return { session, created: false };
|
||||
|
||||
const qqInfo = new QQInfo(uin);
|
||||
const bridge = new Bridge(qqInfo, IdentityService.openForUin(qqInfo));
|
||||
session = { qqInfo, bridge };
|
||||
const bridge = new Bridge(IdentityService.openForUin(uin));
|
||||
session = { bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
// Each downstream consumer (e.g. OneBotInstance) subscribes to
|
||||
@@ -119,7 +116,7 @@ export class BridgeManager {
|
||||
return this.sessions_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
get sessions(): Map<string, { qqInfo: QQInfo; bridge: Bridge }> {
|
||||
get sessions(): Map<string, { bridge: Bridge }> {
|
||||
return this.sessions_;
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
GroupMuteSchema, NotifyMessageBodySchema,
|
||||
GeneralGrayTipInfoSchema, OperatorInfoSchema,
|
||||
} from './proto/notify';
|
||||
import type { QQInfo } from './qq-info';
|
||||
import type { IdentityService } from './identity-service';
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import type {
|
||||
QQEventVariant, MessageElement,
|
||||
@@ -98,17 +98,16 @@ function parseU64OrZero(value: string): number {
|
||||
return isNaN(n) ? 0 : n;
|
||||
}
|
||||
|
||||
function resolveUidToUin(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number {
|
||||
function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number {
|
||||
if (!uid) return fallback;
|
||||
if (isNumericUin(uid)) {
|
||||
const n = parseInt(uid, 10);
|
||||
if (!isNaN(n)) return n;
|
||||
}
|
||||
if (groupId) {
|
||||
const uin = qqInfo.resolveGroupMemberUid(groupId, uid);
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
const uin = qqInfo.resolveUid(uid);
|
||||
// identity.findUinByUid cascades group-scoped lookup → in-memory map → SQLite.
|
||||
// No network fallback on the parse hot path: missing identities fall back to
|
||||
// `fallback` and downstream events drive a roster refresh asynchronously.
|
||||
const uin = identity.findUinByUid(uid, groupId || undefined);
|
||||
if (uin !== null) return uin;
|
||||
return fallback;
|
||||
}
|
||||
@@ -564,7 +563,7 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]):
|
||||
|
||||
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[] {
|
||||
export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
|
||||
if (pkt.body.length === 0) return [];
|
||||
|
||||
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
|
||||
@@ -620,8 +619,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join', time: timestamp, selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
|
||||
userUin: resolveUidToUin(identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
};
|
||||
@@ -638,8 +637,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupMemberLeave = {
|
||||
kind: 'group_member_leave', time: timestamp, selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
|
||||
userUin: resolveUidToUin(identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
isKick: dt !== 0 && dt !== 130,
|
||||
@@ -655,7 +654,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupAdminEvent = {
|
||||
kind: 'group_admin', time: timestamp, selfUin,
|
||||
groupId: admin.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin),
|
||||
userUin: resolveUidToUin(identity, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin),
|
||||
set: admin.body.extraEnable !== undefined,
|
||||
};
|
||||
return [ev];
|
||||
@@ -667,7 +666,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: join.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
|
||||
fromUin: resolveUidToUin(identity, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
|
||||
fromUid: join.targetUid ?? '',
|
||||
subType: 'add', message: '',
|
||||
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
|
||||
@@ -682,7 +681,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: inner.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
|
||||
fromUin: resolveUidToUin(identity, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
|
||||
fromUid: inner.invitorUid ?? '',
|
||||
subType: 'invite', message: '',
|
||||
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
|
||||
@@ -696,7 +695,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: invite.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
|
||||
fromUin: resolveUidToUin(identity, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
|
||||
fromUid: invite.invitorUid ?? '',
|
||||
subType: 'invite', message: '',
|
||||
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
|
||||
@@ -712,7 +711,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const sourceUid = request.info.newSource || request.info.sourceUid || '';
|
||||
const ev: FriendRequestEvent = {
|
||||
kind: 'friend_request', time: timestamp, selfUin,
|
||||
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin),
|
||||
fromUin: resolveUidToUin(identity, 0, sourceUid, fromUin),
|
||||
fromUid: sourceUid,
|
||||
message: request.info.message ?? '', flag: sourceUid,
|
||||
};
|
||||
@@ -723,7 +722,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
if (!recall?.info) return [];
|
||||
const ev: FriendRecall = {
|
||||
kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin,
|
||||
userUin: resolveUidToUin(qqInfo, 0, recall.info.fromUid ?? '', fromUin),
|
||||
userUin: resolveUidToUin(identity, 0, recall.info.fromUid ?? '', fromUin),
|
||||
msgSeq: recall.info.clientSequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
@@ -736,8 +735,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: FriendPokeEvent = {
|
||||
kind: 'friend_poke', time: timestamp, selfUin,
|
||||
userUin: resolveUidToUin(qqInfo, 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(qqInfo, 0, target, parseU64OrZero(target)),
|
||||
userUin: resolveUidToUin(identity, 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(identity, 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
@@ -757,8 +756,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupMuteEvent = {
|
||||
kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin,
|
||||
groupId: mute.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
|
||||
userUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
|
||||
operatorUin: resolveUidToUin(identity, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
|
||||
userUin: resolveUidToUin(identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
|
||||
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
|
||||
};
|
||||
return [ev];
|
||||
@@ -772,9 +771,9 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupRecallEvent = {
|
||||
kind: 'group_recall', time: recalled.time ?? timestamp, selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(identity, notify.groupUin ?? 0,
|
||||
notify.recall.operatorUid || notify.operatorUid || '', fromUin),
|
||||
authorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin),
|
||||
authorUin: resolveUidToUin(identity, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin),
|
||||
msgSeq: recalled.sequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
@@ -790,8 +789,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: GroupPokeEvent = {
|
||||
kind: 'group_poke', time: timestamp, selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, target, parseU64OrZero(target)),
|
||||
userUin: resolveUidToUin(identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(identity, notify.groupUin ?? 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
@@ -835,7 +834,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = msg.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
const member = qqInfo.findGroupMember(ev.groupId, fromUin);
|
||||
const member = identity.findGroupMember(ev.groupId, fromUin);
|
||||
if (member) {
|
||||
if (!ev.senderNick) ev.senderNick = member.nickname;
|
||||
ev.senderCard = member.card;
|
||||
@@ -856,7 +855,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
ev.senderNick = msg.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
if (!ev.senderNick) {
|
||||
const friend = qqInfo.findFriend(fromUin);
|
||||
const friend = identity.findFriend(fromUin);
|
||||
if (friend) ev.senderNick = friend.nickname;
|
||||
}
|
||||
return [ev];
|
||||
@@ -876,7 +875,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
if (msg.responseHead?.forward?.friendName) {
|
||||
ev.senderNick = msg.responseHead.forward.friendName;
|
||||
}
|
||||
const friend = qqInfo.findFriend(fromUin);
|
||||
const friend = identity.findFriend(fromUin);
|
||||
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
|
||||
return [ev];
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// QQ info store — per-UIN state for friends, groups, member lookup.
|
||||
// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp
|
||||
// Domain object shapes shared by IdentityService and its callers. The
|
||||
// concrete state (own UIN, friends list, group rosters, profile cache)
|
||||
// lives inside IdentityService — these interfaces just describe the
|
||||
// records that flow across remember*/refresh* and find* boundaries.
|
||||
|
||||
export interface UserProfileInfo {
|
||||
uin: number;
|
||||
@@ -60,146 +62,3 @@ export interface GroupRequestInfo {
|
||||
comment: string;
|
||||
filtered: boolean;
|
||||
}
|
||||
|
||||
export class QQInfo {
|
||||
private uin_: string;
|
||||
private nickname_ = '';
|
||||
private selfProfile_: UserProfileInfo | null = null;
|
||||
private userProfiles_ = new Map<number, UserProfileInfo>();
|
||||
private friends_: FriendInfo[] = [];
|
||||
private groups_ = new Map<number, QQGroupInfo>();
|
||||
|
||||
constructor(uin: string) {
|
||||
this.uin_ = uin;
|
||||
}
|
||||
|
||||
get uin(): string { return this.uin_; }
|
||||
|
||||
get nickname(): string { return this.nickname_; }
|
||||
set nickname(v: string) { this.nickname_ = v; }
|
||||
|
||||
// --- Self profile ---
|
||||
|
||||
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
|
||||
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
|
||||
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
|
||||
|
||||
// --- User profiles ---
|
||||
|
||||
setUserProfile(info: UserProfileInfo): void {
|
||||
this.userProfiles_.set(info.uin, info);
|
||||
}
|
||||
|
||||
findUserProfile(uin: number): UserProfileInfo | null {
|
||||
return this.userProfiles_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
// --- Friends ---
|
||||
|
||||
setFriends(friends: FriendInfo[]): void { this.friends_ = friends; }
|
||||
get friends(): FriendInfo[] { return this.friends_; }
|
||||
|
||||
findFriend(uin: number): FriendInfo | null {
|
||||
return this.friends_.find(f => f.uin === uin) ?? null;
|
||||
}
|
||||
|
||||
// --- Groups ---
|
||||
|
||||
setGroups(groups: QQGroupInfo[]): void {
|
||||
this.groups_.clear();
|
||||
for (const g of groups) {
|
||||
this.groups_.set(g.groupId, g);
|
||||
}
|
||||
}
|
||||
|
||||
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
|
||||
|
||||
findGroup(groupId: number): QQGroupInfo | null {
|
||||
return this.groups_.get(groupId) ?? null;
|
||||
}
|
||||
|
||||
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
|
||||
return this.groups_.get(groupId)?.members.get(uin) ?? null;
|
||||
}
|
||||
|
||||
setGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.clear();
|
||||
for (const m of members) {
|
||||
g.members.set(m.uin, m);
|
||||
}
|
||||
}
|
||||
|
||||
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.set(member.uin, member);
|
||||
}
|
||||
|
||||
// --- UID resolution ---
|
||||
|
||||
resolveUid(uid: string): number | null {
|
||||
// Check self
|
||||
if (this.selfProfile_?.uid === uid) {
|
||||
return this.selfProfile_.uin || parseInt(this.uin_, 10) || null;
|
||||
}
|
||||
// Check friends
|
||||
for (const f of this.friends_) {
|
||||
if (f.uid === uid) return f.uin;
|
||||
}
|
||||
// Check user profiles
|
||||
for (const [, p] of this.userProfiles_) {
|
||||
if (p.uid === uid) return p.uin;
|
||||
}
|
||||
// Check all group members
|
||||
for (const [, g] of this.groups_) {
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uid === uid) return m.uin;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
resolveGroupMemberUid(groupId: number, uid: string): number | null {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return null;
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uid === uid) return m.uin;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Reverse UID lookup (UIN → UID) ---
|
||||
|
||||
findUidByUin(uin: number): string | null {
|
||||
// Check self
|
||||
if (this.selfProfile_ && this.selfProfile_.uin === uin && this.selfProfile_.uid) {
|
||||
return this.selfProfile_.uid;
|
||||
}
|
||||
// Check friends
|
||||
for (const f of this.friends_) {
|
||||
if (f.uin === uin && f.uid) return f.uid;
|
||||
}
|
||||
// Check user profiles
|
||||
for (const [, p] of this.userProfiles_) {
|
||||
if (p.uin === uin && p.uid) return p.uid;
|
||||
}
|
||||
// Check all group members
|
||||
for (const [, g] of this.groups_) {
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uin === uin && m.uid) return m.uid;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
findUidByUinInGroup(groupId: number, uin: number): string | null {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return null;
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uin === uin && m.uid) return m.uid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -66,9 +66,9 @@ export async function getCookies(bridge: Bridge, domain: string) {
|
||||
// Build the ptlogin2 jump URL: this is the canonical way for the
|
||||
// bot to swap its clientKey for cookie-jar entries on a given
|
||||
// qq.com subdomain.
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
@@ -99,7 +99,7 @@ export async function getSKey(bridge: Bridge): Promise<string> {
|
||||
|
||||
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
|
||||
'&clientuin=' + bridge.qqInfo.uin +
|
||||
'&clientuin=' + bridge.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=' + u1 +
|
||||
'&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { WebHonorType } from '@/bridge/web/group-honor';
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import type { ApiActionContext } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import type { MediaStore } from './media-store';
|
||||
@@ -56,7 +55,6 @@ export interface OneBotInstanceContext {
|
||||
/** Self UIN parsed once, used in event payloads. */
|
||||
selfId: number;
|
||||
|
||||
qqInfo: QQInfo;
|
||||
bridge: Bridge;
|
||||
|
||||
messageStore: MessageStore;
|
||||
@@ -74,7 +72,7 @@ export interface OneBotInstanceContext {
|
||||
}
|
||||
|
||||
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
const { bridge, qqInfo, messageStore, mediaStore } = ref;
|
||||
const { bridge, messageStore, mediaStore } = ref;
|
||||
|
||||
return {
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
@@ -90,12 +88,12 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
|
||||
|
||||
// OneBot11 info actions.
|
||||
getFriendList: () => getFriendList(bridge, qqInfo),
|
||||
getGroupList: (noCache) => getGroupList(bridge, qqInfo, noCache),
|
||||
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, qqInfo, groupId, noCache),
|
||||
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, qqInfo, groupId, noCache),
|
||||
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
|
||||
getStrangerInfo: (userId) => getStrangerInfo(bridge, qqInfo, userId),
|
||||
getFriendList: () => getFriendList(bridge),
|
||||
getGroupList: (noCache) => getGroupList(bridge, noCache),
|
||||
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
|
||||
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
|
||||
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
|
||||
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
|
||||
|
||||
// Group admin.
|
||||
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import path from 'path';
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
@@ -27,7 +26,6 @@ const log = createLogger('Event');
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
|
||||
readonly qqInfo: QQInfo;
|
||||
private readonly bridge: Bridge;
|
||||
private readonly apiHandler: ApiHandler;
|
||||
private readonly converterCtx: ConverterContext;
|
||||
@@ -43,9 +41,10 @@ export class OneBotInstance {
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||
|
||||
constructor(uin: string, qqInfo: QQInfo, bridge: Bridge, config: OneBotConfig) {
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
constructor(uin: string, bridge: Bridge, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.qqInfo = qqInfo;
|
||||
this.bridge = bridge;
|
||||
|
||||
this.rkeyCache = new RKeyCache();
|
||||
@@ -75,7 +74,6 @@ export class OneBotInstance {
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: this.uin,
|
||||
selfId: parseInt(this.uin, 10) || 0,
|
||||
qqInfo: this.qqInfo,
|
||||
bridge: this.bridge,
|
||||
messageStore: this.messageStore,
|
||||
mediaStore: this.mediaStore,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { OneBotInstance } from './instance';
|
||||
@@ -12,8 +11,8 @@ export class OneBotManager {
|
||||
private readonly instances = new Map<string, OneBotInstance>();
|
||||
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.setSessionStartedCallback((uin, qqInfo, bridge) => {
|
||||
this.onSessionStarted(uin, qqInfo, bridge);
|
||||
bridgeManager.setSessionStartedCallback((uin, bridge) => {
|
||||
this.onSessionStarted(uin, bridge);
|
||||
});
|
||||
|
||||
bridgeManager.setSessionClosedCallback((uin) => {
|
||||
@@ -49,11 +48,11 @@ export class OneBotManager {
|
||||
this.instances.clear();
|
||||
}
|
||||
|
||||
private onSessionStarted(uin: string, qqInfo: QQInfo, bridge: Bridge): void {
|
||||
private onSessionStarted(uin: string, bridge: Bridge): void {
|
||||
if (this.instances.has(uin)) return;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const instance = new OneBotInstance(uin, qqInfo, bridge, config);
|
||||
const instance = new OneBotInstance(uin, bridge, config);
|
||||
|
||||
const activePid = bridge.activePid;
|
||||
if (activePid !== null) {
|
||||
@@ -62,13 +61,13 @@ export class OneBotManager {
|
||||
|
||||
// Seed nickname with the UIN so the WebUI never renders blank while
|
||||
// warmup is in flight or if warmup never resolves a real nickname.
|
||||
if (!qqInfo.nickname) qqInfo.nickname = uin;
|
||||
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
|
||||
|
||||
this.instances.set(uin, instance);
|
||||
log.info('session started: UIN=%s', uin);
|
||||
|
||||
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
|
||||
warmUpBridgeState(uin, qqInfo, bridge).catch((err) => {
|
||||
warmUpBridgeState(uin, bridge).catch((err) => {
|
||||
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
@@ -84,13 +83,13 @@ export class OneBotManager {
|
||||
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {
|
||||
async function warmUpBridgeState(uin: string, bridge: Bridge): Promise<void> {
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
let selfResolved = false;
|
||||
|
||||
// Step 1: Fetch friend list + derive self profile when QQ happens to
|
||||
// include self in the response. Some accounts / versions omit self,
|
||||
// which used to leave qqInfo.nickname empty — see step 1b for the
|
||||
// which used to leave identity.nickname empty — see step 1b for the
|
||||
// explicit fallback.
|
||||
try {
|
||||
const friends = await bridge.fetchFriendList();
|
||||
@@ -98,12 +97,12 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
|
||||
|
||||
for (const f of friends) {
|
||||
if (f.uin === selfUin) {
|
||||
qqInfo.setSelfProfile({
|
||||
bridge.identity.setSelfProfile({
|
||||
uin: f.uin, uid: f.uid,
|
||||
nickname: f.nickname || uin,
|
||||
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
|
||||
});
|
||||
qqInfo.nickname = f.nickname || uin;
|
||||
bridge.identity.nickname = f.nickname || uin;
|
||||
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
|
||||
selfResolved = true;
|
||||
break;
|
||||
@@ -120,8 +119,8 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
|
||||
if (!selfResolved && selfUin > 0) {
|
||||
try {
|
||||
const profile = await bridge.fetchUserProfile(selfUin);
|
||||
qqInfo.setSelfProfile(profile);
|
||||
qqInfo.nickname = profile.nickname || uin;
|
||||
bridge.identity.setSelfProfile(profile);
|
||||
bridge.identity.nickname = profile.nickname || uin;
|
||||
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
|
||||
uin, profile.uid, profile.nickname);
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { Bridge } from '../../bridge/bridge';
|
||||
import type { QQInfo } from '../../bridge/qq-info';
|
||||
import type { IdentityService } from '../../bridge/identity-service';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
|
||||
const userId = parseInt(ref.uin, 10) || 0;
|
||||
const nickname = ref.qqInfo.nickname || ref.uin;
|
||||
const nickname = ref.bridge.identity.nickname || ref.uin;
|
||||
return { userId, nickname };
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promi
|
||||
}
|
||||
}
|
||||
|
||||
export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
|
||||
export async function getFriendList(bridge: Bridge): Promise<JsonObject[]> {
|
||||
try {
|
||||
const friends = await bridge.fetchFriendList();
|
||||
return friends.map(f => ({
|
||||
@@ -28,7 +28,7 @@ export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Jso
|
||||
remark: f.remark as any,
|
||||
}));
|
||||
} catch {
|
||||
return qqInfo.friends.map(f => ({
|
||||
return bridge.identity.friends.map(f => ({
|
||||
user_id: f.uin as any,
|
||||
nickname: f.nickname as any,
|
||||
remark: f.remark as any,
|
||||
@@ -38,17 +38,16 @@ export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Jso
|
||||
|
||||
export async function getGroupList(
|
||||
bridge: Bridge,
|
||||
qqInfo: QQInfo,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject[]> {
|
||||
try {
|
||||
if (noCache || qqInfo.groups.length === 0) {
|
||||
if (noCache || bridge.identity.groups.length === 0) {
|
||||
await bridge.fetchGroupList();
|
||||
}
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
return qqInfo.groups.map(g => ({
|
||||
return bridge.identity.groups.map(g => ({
|
||||
group_id: g.groupId as any,
|
||||
group_name: g.groupName as any,
|
||||
member_count: g.memberCount as any,
|
||||
@@ -58,18 +57,17 @@ export async function getGroupList(
|
||||
|
||||
export async function getGroupInfo(
|
||||
bridge: Bridge,
|
||||
qqInfo: QQInfo,
|
||||
groupId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject | null> {
|
||||
if (noCache || !qqInfo.findGroup(groupId)) {
|
||||
if (noCache || !bridge.identity.findGroup(groupId)) {
|
||||
try {
|
||||
await bridge.fetchGroupList();
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
}
|
||||
const g = qqInfo.findGroup(groupId);
|
||||
const g = bridge.identity.findGroup(groupId);
|
||||
if (!g) return null;
|
||||
return {
|
||||
group_id: g.groupId as any,
|
||||
@@ -81,34 +79,32 @@ export async function getGroupInfo(
|
||||
|
||||
export async function getGroupMemberList(
|
||||
bridge: Bridge,
|
||||
qqInfo: QQInfo,
|
||||
groupId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject[]> {
|
||||
if (noCache) {
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
return getCachedGroupMembers(qqInfo, groupId);
|
||||
return getCachedGroupMembers(bridge.identity, groupId);
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await bridge.fetchGroupMemberList(groupId);
|
||||
return members.map(m => formatGroupMember(groupId, m));
|
||||
} catch {
|
||||
return getCachedGroupMembers(qqInfo, groupId);
|
||||
return getCachedGroupMembers(bridge.identity, groupId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupMemberInfo(
|
||||
bridge: Bridge,
|
||||
qqInfo: QQInfo,
|
||||
groupId: number,
|
||||
userId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject | null> {
|
||||
if (noCache || !qqInfo.findGroupMember(groupId, userId)) {
|
||||
if (noCache || !bridge.identity.findGroupMember(groupId, userId)) {
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
}
|
||||
const m = qqInfo.findGroupMember(groupId, userId);
|
||||
const m = bridge.identity.findGroupMember(groupId, userId);
|
||||
if (!m) return null;
|
||||
return formatGroupMember(groupId, m);
|
||||
}
|
||||
@@ -147,7 +143,6 @@ export async function getGroupFiles(
|
||||
|
||||
export async function getStrangerInfo(
|
||||
bridge: Bridge,
|
||||
qqInfo: QQInfo,
|
||||
userId: number,
|
||||
): Promise<JsonObject | null> {
|
||||
try {
|
||||
@@ -159,7 +154,7 @@ export async function getStrangerInfo(
|
||||
age: p.age as any,
|
||||
};
|
||||
} catch {
|
||||
const p = qqInfo.findUserProfile(userId);
|
||||
const p = bridge.identity.findUserProfile(userId);
|
||||
if (!p) return null;
|
||||
return {
|
||||
user_id: p.uin as any,
|
||||
@@ -201,8 +196,8 @@ export async function getDownloadRKeys(bridge: Bridge): Promise<JsonObject[]> {
|
||||
}
|
||||
}
|
||||
|
||||
function getCachedGroupMembers(qqInfo: QQInfo, groupId: number): JsonObject[] {
|
||||
const g = qqInfo.findGroup(groupId);
|
||||
function getCachedGroupMembers(identity: IdentityService, groupId: number): JsonObject[] {
|
||||
const g = identity.findGroup(groupId);
|
||||
if (!g) return [];
|
||||
const result: JsonObject[] = [];
|
||||
for (const [, member] of g.members) {
|
||||
|
||||
@@ -306,7 +306,7 @@ export async function initWebUI(
|
||||
|
||||
app.get('/api/qq-list', (c) => {
|
||||
const instances = oneBotManager.getInstances();
|
||||
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.qqInfo.nickname }));
|
||||
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
|
||||
return c.json({ list });
|
||||
});
|
||||
|
||||
|
||||
@@ -11,14 +11,13 @@ import { vi } from 'vitest';
|
||||
import type { SendPacketResult } from '../../src/protocol/packet-sender';
|
||||
|
||||
export interface MockBridge {
|
||||
qqInfo: {
|
||||
identity: {
|
||||
uin: string;
|
||||
selfUid: string;
|
||||
findGroupMember: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
identity: {
|
||||
nickname: string;
|
||||
findUidByUin: ReturnType<typeof vi.fn>;
|
||||
findUinByUid: ReturnType<typeof vi.fn>;
|
||||
findGroupMember: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
sendRawPacket: ReturnType<typeof vi.fn>;
|
||||
fetchFriendList: ReturnType<typeof vi.fn>;
|
||||
@@ -36,15 +35,13 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
|
||||
responseData: Buffer.alloc(0),
|
||||
};
|
||||
return {
|
||||
qqInfo: {
|
||||
identity: {
|
||||
uin: '10001',
|
||||
selfUid: 'self-uid',
|
||||
findGroupMember: vi.fn(() => null),
|
||||
...(overrides.qqInfo ?? {}),
|
||||
} as MockBridge['qqInfo'],
|
||||
identity: {
|
||||
nickname: 'self-nick',
|
||||
findUidByUin: vi.fn(() => 'cached-uid'),
|
||||
findUinByUid: vi.fn(() => 0),
|
||||
findGroupMember: vi.fn(() => null),
|
||||
...(overrides.identity ?? {}),
|
||||
} as MockBridge['identity'],
|
||||
sendRawPacket: vi.fn(async () => defaultResp),
|
||||
|
||||
@@ -100,7 +100,14 @@ describe('actions/group-file', () => {
|
||||
|
||||
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
|
||||
const bridge = mockBridge({
|
||||
qqInfo: { uin: '10001', selfUid: '', findGroupMember: vi.fn(() => null) },
|
||||
identity: {
|
||||
uin: '10001',
|
||||
selfUid: '',
|
||||
nickname: 'self-nick',
|
||||
findUidByUin: vi.fn(() => 'cached-uid'),
|
||||
findUinByUid: vi.fn(() => 0),
|
||||
findGroupMember: vi.fn(() => null),
|
||||
},
|
||||
});
|
||||
vi.mocked(bridge.resolveUserUid)
|
||||
.mockResolvedValueOnce('target-uid') // target user
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
|
||||
import { IdentityService } from '../src/bridge/identity-service';
|
||||
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
|
||||
import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events';
|
||||
import type { PacketInfo } from '../src/protocol/types';
|
||||
|
||||
@@ -36,14 +37,14 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
|
||||
class RefreshingBridge extends Bridge {
|
||||
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
|
||||
|
||||
constructor(qqInfo: QQInfo, private readonly refreshedMembers: GroupMemberInfo[]) {
|
||||
super(qqInfo);
|
||||
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
|
||||
super(identity);
|
||||
}
|
||||
|
||||
override async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
|
||||
this.memberFetches.push({ groupId, force: Boolean(options.force) });
|
||||
for (const member of this.refreshedMembers) {
|
||||
this.qqInfo.updateGroupMember(groupId, member);
|
||||
this.identity.updateGroupMember(groupId, member);
|
||||
}
|
||||
return this.refreshedMembers;
|
||||
}
|
||||
@@ -79,9 +80,9 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
|
||||
describe('Bridge group member identity refresh', () => {
|
||||
it('forces a fresh member list before dispatching an unresolved join event', async () => {
|
||||
const member = makeGroupMember(22222, 'u_new_member');
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
qqInfo.setGroups([makeGroup()]);
|
||||
const bridge = new RefreshingBridge(qqInfo, [member]);
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
const bridge = new RefreshingBridge(identity, [member]);
|
||||
const seen: GroupMemberJoin[] = [];
|
||||
|
||||
bridge.registerCmd('test.member_join', () => [{
|
||||
@@ -107,8 +108,7 @@ describe('Bridge group member identity refresh', () => {
|
||||
});
|
||||
|
||||
it('remembers UID mappings from realtime request events', () => {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const bridge = new Bridge(qqInfo);
|
||||
const bridge = new Bridge(IdentityService.memory(SELF_UIN));
|
||||
const events: QQEventVariant[] = [
|
||||
{
|
||||
kind: 'friend_request',
|
||||
|
||||
@@ -10,7 +10,7 @@ vi.mock('../src/bridge/element-builder', () => ({
|
||||
describe('Bridge private media routing', () => {
|
||||
it('includes resolved uid in the final c2c send request for media messages', async () => {
|
||||
const { Bridge } = await import('../src/bridge/bridge');
|
||||
const { QQInfo } = await import('../src/bridge/qq-info');
|
||||
const { IdentityService } = await import('../src/bridge/identity-service');
|
||||
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
@@ -37,7 +37,7 @@ describe('Bridge private media routing', () => {
|
||||
}
|
||||
}
|
||||
|
||||
const bridge = new TestBridge(new QQInfo('10000'));
|
||||
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||
await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
|
||||
|
||||
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
|
||||
|
||||
@@ -104,7 +104,6 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: SELF_UIN,
|
||||
selfId: SELF_ID,
|
||||
qqInfo: {} as never,
|
||||
bridge: fakeBridge as never,
|
||||
messageStore: {} as never,
|
||||
mediaStore: {} as never,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { IdentityService } from '../src/bridge/identity-service';
|
||||
import { QQInfo, type GroupMemberInfo, type QQGroupInfo, type UserProfileInfo } from '../src/bridge/qq-info';
|
||||
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '../src/bridge/qq-info';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
@@ -60,8 +60,7 @@ describe('IdentityService', () => {
|
||||
const dbPath = tempDbPath('persist');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' }]);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]);
|
||||
@@ -69,12 +68,11 @@ describe('IdentityService', () => {
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
expect(qqInfo.findFriend(22222)?.uid).toBe('u_friend');
|
||||
expect(qqInfo.findGroup(GROUP_ID)?.groupName).toBe('group');
|
||||
expect(qqInfo.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
|
||||
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
|
||||
expect(identity.findGroup(GROUP_ID)?.groupName).toBe('group');
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
|
||||
expect(identity.findUidByUin(33333, GROUP_ID)).toBe('u_member');
|
||||
expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333);
|
||||
|
||||
@@ -88,8 +86,7 @@ describe('IdentityService', () => {
|
||||
const second = makeMember(44444, 'u_second');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [first, second]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [second]);
|
||||
@@ -97,11 +94,10 @@ describe('IdentityService', () => {
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
expect(qqInfo.findGroupMember(GROUP_ID, first.uin)).toBeNull();
|
||||
expect(qqInfo.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
|
||||
expect(identity.findGroupMember(GROUP_ID, first.uin)).toBeNull();
|
||||
expect(identity.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
|
||||
// Historical identity remains available for UID/UIN resolution.
|
||||
expect(identity.findUidByUin(first.uin, GROUP_ID)).toBe(first.uid);
|
||||
|
||||
@@ -114,8 +110,7 @@ describe('IdentityService', () => {
|
||||
const member = makeMember(33333, 'u_member');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' }]);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [member]);
|
||||
@@ -125,11 +120,10 @@ describe('IdentityService', () => {
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
expect(qqInfo.findFriend(22222)).toBeNull();
|
||||
expect(qqInfo.findGroup(GROUP_ID)).toBeNull();
|
||||
expect(identity.findFriend(22222)).toBeNull();
|
||||
expect(identity.findGroup(GROUP_ID)).toBeNull();
|
||||
// Identity mappings remain useful for historical events/actions.
|
||||
expect(identity.findUidByUin(22222)).toBe('u_friend');
|
||||
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
|
||||
@@ -143,8 +137,7 @@ describe('IdentityService', () => {
|
||||
const member = makeMember(33333, 'u_member');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [member]);
|
||||
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
|
||||
@@ -152,10 +145,9 @@ describe('IdentityService', () => {
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
expect(qqInfo.findGroupMember(GROUP_ID, member.uin)).toBeNull();
|
||||
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
|
||||
expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin);
|
||||
|
||||
identity.close();
|
||||
@@ -166,8 +158,7 @@ describe('IdentityService', () => {
|
||||
const dbPath = tempDbPath('request-events');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
identity.rememberRequestIdentity({
|
||||
uid: 'u_friend_request',
|
||||
uin: 55555,
|
||||
@@ -183,12 +174,11 @@ describe('IdentityService', () => {
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
expect(identity.findUidByUin(55555)).toBe('u_friend_request');
|
||||
expect(identity.findUinByUid('u_friend_request')).toBe(55555);
|
||||
expect(qqInfo.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
|
||||
expect(identity.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
|
||||
expect(identity.findUidByUin(66666)).toBe('u_group_request');
|
||||
|
||||
identity.close();
|
||||
@@ -202,8 +192,7 @@ describe('IdentityService.resolveUid', () => {
|
||||
}
|
||||
|
||||
it('returns the cached uid without invoking the fetcher', async () => {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = IdentityService.memory(qqInfo);
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberRequestIdentity({ uid: 'u_known', uin: 12345 });
|
||||
const fetchProfile = vi.fn(async (uin: number) => makeProfile(uin, 'should-not-be-used'));
|
||||
identity.setFetcher({ fetchProfile });
|
||||
@@ -213,8 +202,7 @@ describe('IdentityService.resolveUid', () => {
|
||||
});
|
||||
|
||||
it('falls back to fetchProfile on miss and returns the resolved uid', async () => {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = IdentityService.memory(qqInfo);
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
const fetchProfile = vi.fn(async (uin: number) => {
|
||||
// Simulate the bridge writing the result back via rememberUserProfile.
|
||||
identity.rememberUserProfile(makeProfile(uin, 'u_fetched'));
|
||||
@@ -227,16 +215,14 @@ describe('IdentityService.resolveUid', () => {
|
||||
});
|
||||
|
||||
it('throws when neither cache nor fetcher can produce a uid', async () => {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = IdentityService.memory(qqInfo);
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.setFetcher({ fetchProfile: async (uin) => makeProfile(uin, '') });
|
||||
|
||||
await expect(identity.resolveUid(99999)).rejects.toThrow(/failed to resolve UID/);
|
||||
});
|
||||
|
||||
it('tries fetchGroupMemberList before fetchProfile when groupId is provided', async () => {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = IdentityService.memory(qqInfo);
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([{
|
||||
groupId: GROUP_ID, groupName: '', remark: '',
|
||||
memberCount: 0, memberMax: 0, members: new Map(),
|
||||
@@ -256,8 +242,7 @@ describe('IdentityService.resolveUid', () => {
|
||||
});
|
||||
|
||||
it('throws on invalid (zero / negative) uin without calling fetcher', async () => {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = IdentityService.memory(qqInfo);
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
const fetchProfile = vi.fn();
|
||||
identity.setFetcher({ fetchProfile });
|
||||
|
||||
|
||||
@@ -258,7 +258,7 @@ describe('parseMessage', () => {
|
||||
}, respSchema);
|
||||
|
||||
const bridge = {
|
||||
qqInfo: { uin: '10000' },
|
||||
identity: { uin: '10000' },
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push-handler';
|
||||
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
|
||||
import { IdentityService } from '../src/bridge/identity-service';
|
||||
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
|
||||
import { PushMsgSchema } from '../src/bridge/proto/message';
|
||||
import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify';
|
||||
import type { GroupMemberJoin } from '../src/bridge/events';
|
||||
@@ -36,10 +37,11 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
|
||||
};
|
||||
}
|
||||
|
||||
function makeQqInfo(members: GroupMemberInfo[] = []): QQInfo {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
qqInfo.setGroups([makeGroup(members)]);
|
||||
return qqInfo;
|
||||
function makeIdentity(members: GroupMemberInfo[] = []): IdentityService {
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([makeGroup(members)]);
|
||||
if (members.length) identity.rememberGroupMembers(GROUP_ID, members);
|
||||
return identity;
|
||||
}
|
||||
|
||||
function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo {
|
||||
@@ -73,7 +75,7 @@ function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin =
|
||||
|
||||
describe('parseMsgPush group member increase', () => {
|
||||
it('does not fall back to the group id when a joining uid is unresolved', () => {
|
||||
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeQqInfo()) as GroupMemberJoin[];
|
||||
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeIdentity()) as GroupMemberJoin[];
|
||||
|
||||
expect(event.kind).toBe('group_member_join');
|
||||
expect(event.groupId).toBe(GROUP_ID);
|
||||
@@ -85,7 +87,10 @@ describe('parseMsgPush group member increase', () => {
|
||||
it('resolves joining uid and operator uid from the member cache when available', () => {
|
||||
const member = makeGroupMember(22222, 'u_member');
|
||||
const operator = makeGroupMember(33333, 'u_operator');
|
||||
const [event] = parseMsgPush(makeGroupIncreasePacket(member.uid, operator.uid), makeQqInfo([member, operator])) as GroupMemberJoin[];
|
||||
const [event] = parseMsgPush(
|
||||
makeGroupIncreasePacket(member.uid, operator.uid),
|
||||
makeIdentity([member, operator]),
|
||||
) as GroupMemberJoin[];
|
||||
|
||||
expect(event.userUin).toBe(member.uin);
|
||||
expect(event.operatorUin).toBe(operator.uin);
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
getCredentials,
|
||||
} from '../../src/bridge/web-actions/cookies';
|
||||
|
||||
const bridge = { qqInfo: { uin: '10001' } } as any;
|
||||
const bridge = { identity: { uin: '10001' } } as any;
|
||||
|
||||
describe('cookies — forceFetchClientKey', () => {
|
||||
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); });
|
||||
|
||||
Reference in new issue
Block a user