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;
|
||||
|
||||
Reference in new issue
Block a user