Merge pull request #27 from SnowLuma/dev
chore: promote dev → main (8636222)
This commit is contained in:
+2
-2
@@ -1,3 +1,3 @@
|
||||
# V2.0.0 前计划
|
||||
- [ ] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。
|
||||
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。
|
||||
|
||||
@@ -9,10 +9,13 @@ import { computeHashes, computeMd5, loadBinarySource } from './highway/utils';
|
||||
import { buildSendElems } from './builders/element-builder';
|
||||
import { parseMsgPush } from './handlers/msg-push-handler';
|
||||
import type { ForwardNodePayload, MessageElement } from './events';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { PushMsgSchema } from './proto/message';
|
||||
import {
|
||||
OidbMuteMemberSchema,
|
||||
OidbMuteAllSchema,
|
||||
Oidb0x89a_0AddOptionSchema,
|
||||
Oidb0x89a_0SearchSchema,
|
||||
OidbKickMemberSchema,
|
||||
OidbLeaveGroupSchema,
|
||||
OidbFriendRequestActionSchema,
|
||||
@@ -49,6 +52,10 @@ import {
|
||||
OidbSetProfileSchema,
|
||||
Oidb0x7edReqSchema,
|
||||
Oidb0x7edRespSchema,
|
||||
Oidb0x8a0ReqSchema,
|
||||
Oidb0x8a0RespSchema,
|
||||
Oidb0xf16ReqSchema,
|
||||
Oidb0xf16RespSchema,
|
||||
Oidb0x8a7RespSchema,
|
||||
Oidb0x8a7ReqSchema,
|
||||
Oidb0xe17RespSchema,
|
||||
@@ -65,6 +72,10 @@ import {
|
||||
Oidb0x112eRespSchema,
|
||||
Oidb0xeb7ReqSchema,
|
||||
Oidb0xeb7RespSchema,
|
||||
FaceroamOpReqSchema,
|
||||
FaceroamOpRespSchema,
|
||||
Oidb0x9083ReqSchema,
|
||||
Oidb0x9083RespSchema,
|
||||
} from './proto/oidb-action';
|
||||
import { FileUploadExtSchema } from './proto/highway';
|
||||
import {
|
||||
@@ -76,6 +87,8 @@ import {
|
||||
} from './proto/longmsg';
|
||||
import { gzipSync, gunzipSync } from 'zlib';
|
||||
|
||||
const log = createLogger('BridgeActions');
|
||||
|
||||
export interface GroupFileInfo {
|
||||
fileId: string;
|
||||
fileName: string;
|
||||
@@ -407,6 +420,11 @@ export async function setFriendRemark(bridge: Bridge, userId: number, remark: st
|
||||
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema);
|
||||
}
|
||||
|
||||
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
|
||||
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1,
|
||||
{ inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Group file count
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -438,12 +456,28 @@ export async function muteGroupAll(bridge: Bridge, groupId: number, enable: bool
|
||||
{ groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema);
|
||||
}
|
||||
|
||||
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
|
||||
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
|
||||
{ groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, Oidb0x89a_0AddOptionSchema);
|
||||
}
|
||||
|
||||
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
|
||||
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
|
||||
{ groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema);
|
||||
}
|
||||
|
||||
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
const uid = await resolveUserUid(bridge, userId, groupId);
|
||||
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
|
||||
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema);
|
||||
}
|
||||
|
||||
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
const targetUids = await Promise.all(userIds.map(userId => resolveUserUid(bridge, userId, groupId)));
|
||||
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
|
||||
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema);
|
||||
}
|
||||
|
||||
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
|
||||
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1,
|
||||
{ groupUin: groupId }, OidbLeaveGroupSchema);
|
||||
@@ -1732,3 +1766,49 @@ export async function setAvatar(
|
||||
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
|
||||
}
|
||||
|
||||
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),
|
||||
field3: 1,
|
||||
field6: 1,
|
||||
};
|
||||
const request = protoEncode(req, FaceroamOpReqSchema);
|
||||
const result = await bridge.sendRawPacket('Faceroam.OpReq', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'fetch custom face failed');
|
||||
}
|
||||
const resp = protoDecode(result.responseData, FaceroamOpRespSchema);
|
||||
if (!resp || (resp as any).retCode !== 0) {
|
||||
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`);
|
||||
}
|
||||
|
||||
export async function getEmojiLikes(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
emojiId: string,
|
||||
emojiType: number = 1,
|
||||
count: number = 10,
|
||||
cookie: string = ''
|
||||
): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> {
|
||||
const req = {
|
||||
groupId: BigInt(groupId),
|
||||
sequence,
|
||||
emojiType,
|
||||
emojiId,
|
||||
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
|
||||
field7: 0,
|
||||
count,
|
||||
field12: 1,
|
||||
};
|
||||
const resp = await sendOidbAndDecode<any>(bridge, 'OidbSvcTrpcTcp.0x9083_1', 0x9083, 1, req, Oidb0x9083ReqSchema, Oidb0x9083RespSchema);
|
||||
const uin = resp?.inner?.userInfo?.uin;
|
||||
const users = uin ? [{ uin: Number(uin) }] : [];
|
||||
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
|
||||
return { users, cookie: respCookie, isLast: !respCookie };
|
||||
}
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
|
||||
if (nextUin === 0) nextUin = null;
|
||||
} while (nextUin !== null);
|
||||
|
||||
bridge.qqInfo.setFriends(friends);
|
||||
bridge.identity.rememberFriends(friends);
|
||||
return friends;
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
});
|
||||
}
|
||||
}
|
||||
bridge.qqInfo.setGroups(groups);
|
||||
bridge.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
|
||||
token = resp?.token ?? '';
|
||||
} while (token);
|
||||
|
||||
bridge.qqInfo.setGroupMembers(groupId, members);
|
||||
bridge.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
@@ -248,9 +248,7 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
|
||||
info.age = numMap.get(20037) ?? 0;
|
||||
}
|
||||
|
||||
bridge.qqInfo.setUserProfile(info);
|
||||
const selfUin = parseInt(bridge.qqInfo.uin, 10) || 0;
|
||||
if (info.uin === selfUin) bridge.qqInfo.setSelfProfile(info);
|
||||
bridge.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
@@ -286,6 +284,7 @@ export async function fetchGroupRequests(bridge: Bridge, filtered = false): Prom
|
||||
filtered,
|
||||
});
|
||||
}
|
||||
bridge.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
|
||||
@@ -74,15 +74,15 @@ export async function sendOidbAndDecode<T>(
|
||||
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
|
||||
// Try group member first
|
||||
if (groupId !== undefined) {
|
||||
const uid = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
|
||||
const uid = bridge.identity.findUidByUin(uin, groupId);
|
||||
if (uid) return uid;
|
||||
// Try fetching member list
|
||||
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
|
||||
const uid2 = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
|
||||
const uid2 = bridge.identity.findUidByUin(uin, groupId);
|
||||
if (uid2) return uid2;
|
||||
}
|
||||
// Try cached
|
||||
const uid = bridge.qqInfo.findUidByUin(uin);
|
||||
const uid = bridge.identity.findUidByUin(uin);
|
||||
if (uid) return uid;
|
||||
// Fetch profile
|
||||
const profile = await bridge.fetchUserProfile(uin);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { MSG_PUSH_CMD, parseMsgPush } from './handlers/msg-push-handler';
|
||||
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||
import { protoEncode, protoDecode } from '../protobuf/decode';
|
||||
import { buildSendElems } from './builders/element-builder';
|
||||
import { IdentityService } from './identity-service';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import {
|
||||
SendMessageRequestSchema,
|
||||
@@ -30,7 +31,10 @@ import type { WebHonorType } from './web/group-honor';
|
||||
import {
|
||||
muteGroupMember as muteGroupMember_,
|
||||
muteGroupAll as muteGroupAll_,
|
||||
setGroupAddOption as setGroupAddOption_,
|
||||
setGroupSearch as setGroupSearch_,
|
||||
kickGroupMember as kickGroupMember_,
|
||||
kickGroupMembers as kickGroupMembers_,
|
||||
leaveGroup as leaveGroup_,
|
||||
setGroupAdmin as setGroupAdmin_,
|
||||
setGroupCard as setGroupCard_,
|
||||
@@ -64,6 +68,7 @@ import {
|
||||
markPrivateMessageRead as markGroupMsgAsRead_,
|
||||
markGroupMessageRead as markPrivateMsgAsRead_,
|
||||
setFriendRemark as setFriendRemark_,
|
||||
setGroupRemark as setGroupRemark_,
|
||||
fetchGroupFileCount as fetchGroupFileCount_,
|
||||
setOnlineStatus as setOnlineStatus_,
|
||||
setProfile as setProfile_,
|
||||
@@ -77,6 +82,8 @@ import {
|
||||
clickInlineKeyboardButton as clickInlineKeyboardButton_,
|
||||
sendGroupSign as sendGroupSign_,
|
||||
setAvatar as setAvatar_,
|
||||
fetchCustomFace as fetchCustomFace_,
|
||||
getEmojiLikes as getEmojiLikes_,
|
||||
} from './bridge-actions';
|
||||
import {
|
||||
getGroupHonorInfo as getGroupHonorInfo_,
|
||||
@@ -118,6 +125,8 @@ export interface ClientKeyInfo {
|
||||
keyIndex: string
|
||||
}
|
||||
|
||||
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const eventLog = createLogger('Event');
|
||||
|
||||
@@ -125,6 +134,7 @@ export class Bridge {
|
||||
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
private qqInfo_: QQInfo;
|
||||
readonly identity: IdentityService;
|
||||
private pids_ = new Set<number>();
|
||||
/**
|
||||
* Per-kind event subscription. Replaces the legacy single-callback
|
||||
@@ -149,13 +159,19 @@ export class Bridge {
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
|
||||
constructor(qqInfo: QQInfo) {
|
||||
constructor(qqInfo: QQInfo, identity = IdentityService.memory(qqInfo)) {
|
||||
this.qqInfo_ = qqInfo;
|
||||
this.identity = identity;
|
||||
this.registerDefaultHandlers();
|
||||
}
|
||||
|
||||
get qqInfo(): QQInfo { return this.qqInfo_; }
|
||||
|
||||
dispose(): void {
|
||||
this.identity.close();
|
||||
this.events.clear();
|
||||
}
|
||||
|
||||
setPacketClient(client: PacketSender): void {
|
||||
this.packetClient_ = client;
|
||||
}
|
||||
@@ -199,9 +215,13 @@ export class Bridge {
|
||||
try {
|
||||
const events = handler(pkt, this.qqInfo_);
|
||||
for (const event of events) {
|
||||
this.triggerMemberCacheRefresh(event);
|
||||
printEvent(event);
|
||||
this.emitEvent(event);
|
||||
if (this.needsPreDispatchIdentityRefresh(event)) {
|
||||
void this.dispatchAfterIdentityRefresh(event);
|
||||
} else {
|
||||
this.triggerMemberCacheRefresh(event);
|
||||
printEvent(event);
|
||||
this.emitEvent(event);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
@@ -209,13 +229,68 @@ export class Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
|
||||
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
|
||||
}
|
||||
|
||||
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
|
||||
let refreshed = false;
|
||||
try {
|
||||
refreshed = await this.prepareGroupMemberJoinIdentity(event);
|
||||
} catch (e) {
|
||||
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
this.triggerMemberCacheRefresh(event, refreshed);
|
||||
printEvent(event);
|
||||
this.emitEvent(event);
|
||||
}
|
||||
|
||||
private emitEvent(event: QQEventVariant): void {
|
||||
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
|
||||
// own onError hook so one bad listener never blocks the others.
|
||||
void this.events.emit(event);
|
||||
}
|
||||
|
||||
private triggerMemberCacheRefresh(event: QQEventVariant): void {
|
||||
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
|
||||
this.resolveMemberIdentityFromCache(event);
|
||||
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
|
||||
|
||||
const refreshed = await this.refreshMemberCache(
|
||||
event.groupId,
|
||||
!this.qqInfo_.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
|
||||
true,
|
||||
);
|
||||
this.resolveMemberIdentityFromCache(event);
|
||||
return refreshed;
|
||||
}
|
||||
|
||||
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
|
||||
if (event.groupId <= 0) return;
|
||||
if (event.userUin <= 0 && event.userUid) {
|
||||
const uin = this.resolveUidFromCache(event.groupId, event.userUid);
|
||||
if (uin !== null) event.userUin = uin;
|
||||
}
|
||||
if (event.operatorUin <= 0 && event.operatorUid) {
|
||||
const uin = this.resolveUidFromCache(event.groupId, event.operatorUid);
|
||||
if (uin !== null) event.operatorUin = uin;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveUidFromCache(groupId: number, uid: string): number | null {
|
||||
return this.identity.findUinByUid(uid, groupId);
|
||||
}
|
||||
|
||||
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
|
||||
const selfUin = Number(this.qqInfo_.uin);
|
||||
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.qqInfo_.selfUid);
|
||||
}
|
||||
|
||||
private triggerMemberCacheRefresh(event: QQEventVariant, alreadyRefreshed = false): void {
|
||||
this.rememberEventIdentity(event);
|
||||
if (alreadyRefreshed) return;
|
||||
|
||||
let groupId = 0;
|
||||
let reason = '';
|
||||
let refreshGroupList = false;
|
||||
@@ -223,7 +298,7 @@ export class Bridge {
|
||||
case 'group_member_join':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_member_join';
|
||||
refreshGroupList = event.userUin === Number(this.qqInfo_.uin);
|
||||
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
groupId = event.groupId;
|
||||
@@ -239,15 +314,13 @@ export class Bridge {
|
||||
|
||||
if (groupId <= 0) return;
|
||||
if (this.memberRefreshTasks_.has(groupId)) return;
|
||||
if (event.kind === 'group_member_join' && !this.qqInfo_.findGroup(groupId)) {
|
||||
refreshGroupList = true;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
if (refreshGroupList) {
|
||||
try { await this.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
if (this.qqInfo_.findGroup(groupId)) {
|
||||
await this.fetchGroupMemberList(groupId);
|
||||
}
|
||||
await this.refreshMemberCache(groupId, refreshGroupList, false);
|
||||
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
} catch (e) {
|
||||
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
@@ -260,6 +333,62 @@ export class Bridge {
|
||||
this.memberRefreshTasks_.set(groupId, task);
|
||||
}
|
||||
|
||||
private rememberEventIdentity(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_member_join':
|
||||
this.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.userUid,
|
||||
uin: event.userUin,
|
||||
});
|
||||
this.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.operatorUid,
|
||||
uin: event.operatorUin,
|
||||
});
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
this.identity.markGroupMemberInactive(event.groupId, {
|
||||
uid: event.userUid,
|
||||
uin: event.userUin,
|
||||
});
|
||||
this.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.operatorUid,
|
||||
uin: event.operatorUin,
|
||||
});
|
||||
break;
|
||||
case 'group_admin':
|
||||
this.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uin: event.userUin,
|
||||
});
|
||||
break;
|
||||
case 'friend_request':
|
||||
this.identity.rememberRequestIdentity({
|
||||
uid: event.fromUid,
|
||||
uin: event.fromUin,
|
||||
source: 'friend_request',
|
||||
});
|
||||
break;
|
||||
case 'group_invite':
|
||||
this.identity.rememberRequestIdentity({
|
||||
groupId: event.groupId,
|
||||
uid: event.fromUid,
|
||||
uin: event.fromUin,
|
||||
source: 'group_request',
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
|
||||
if (refreshGroupList) {
|
||||
try { await this.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
if (!this.qqInfo_.findGroup(groupId)) return false;
|
||||
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- Sequence / random generators ---
|
||||
|
||||
private nextClientSequence(): number {
|
||||
@@ -341,7 +470,7 @@ export class Bridge {
|
||||
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
// Resolve UID for image upload (C++ resolves UID before building elems)
|
||||
// Resolve UID for media upload and the final c2c routing head.
|
||||
let userUid = '';
|
||||
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
||||
if (hasMedia) {
|
||||
@@ -356,6 +485,7 @@ export class Bridge {
|
||||
routingHead: {
|
||||
c2c: {
|
||||
uin: userUin,
|
||||
...(userUid ? { uid: userUid } : {}),
|
||||
},
|
||||
} as any,
|
||||
contentHead: {
|
||||
@@ -416,11 +546,11 @@ export class Bridge {
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
|
||||
async fetchGroupMemberList(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
|
||||
const kMemberListTtlMs = 60_000;
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch_.get(groupId);
|
||||
if (last && now - last.at < kMemberListTtlMs) {
|
||||
if (!options.force && last && now - last.at < kMemberListTtlMs) {
|
||||
return last.data;
|
||||
}
|
||||
const inflight = this.memberListInflight_.get(groupId);
|
||||
@@ -445,7 +575,10 @@ export class Bridge {
|
||||
|
||||
async muteGroupMember(groupId: number, userId: number, duration: number): Promise<void> { return muteGroupMember_(this, groupId, userId, duration); }
|
||||
async muteGroupAll(groupId: number, enable: boolean): Promise<void> { return muteGroupAll_(this, groupId, enable); }
|
||||
async setGroupAddOption(groupId: number, addType: number): Promise<void> { return setGroupAddOption_(this, groupId, addType); }
|
||||
async setGroupSearch(groupId: number): Promise<void> { return setGroupSearch_(this, groupId); }
|
||||
async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
|
||||
async kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> { return kickGroupMembers_(this, groupId, userIds, reject); }
|
||||
async leaveGroup(groupId: number): Promise<void> { return leaveGroup_(this, groupId); }
|
||||
async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void> { return setGroupAdmin_(this, groupId, userId, enable); }
|
||||
async setGroupCard(groupId: number, userId: number, card: string): Promise<void> { return setGroupCard_(this, groupId, userId, card); }
|
||||
@@ -483,6 +616,7 @@ export class Bridge {
|
||||
async markGroupMsgAsRead(groupId: number, sequence: number): Promise<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
|
||||
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
|
||||
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
|
||||
async setGroupRemark(groupId: number, remark: string): Promise<void> { return setGroupRemark_(this, groupId, remark); }
|
||||
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
|
||||
return getGroupHonorInfo_(this, groupId, type);
|
||||
}
|
||||
@@ -549,6 +683,12 @@ export class Bridge {
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
return setAvatar_(this, source);
|
||||
}
|
||||
async fetchCustomFace(count?: number): Promise<string[]> {
|
||||
return fetchCustomFace_(this, count);
|
||||
}
|
||||
async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) {
|
||||
return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Module-level helper functions ---
|
||||
@@ -575,6 +715,11 @@ function elementsToText(elements: MessageElement[]): string {
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function formatEventUser(uin: number, uid?: string): string {
|
||||
if (uin > 0) return String(uin);
|
||||
return uid || '未知用户';
|
||||
}
|
||||
|
||||
function printEvent(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_message':
|
||||
@@ -589,10 +734,10 @@ function printEvent(event: QQEventVariant): void {
|
||||
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
|
||||
break;
|
||||
case 'group_member_join':
|
||||
eventLog.info('入群 %d 加入 %d', event.userUin, event.groupId);
|
||||
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
eventLog.warn('退群 %d %s %d', event.userUin, event.isKick ? '被踢出' : '退出', event.groupId);
|
||||
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
|
||||
break;
|
||||
case 'group_mute':
|
||||
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
|
||||
|
||||
@@ -98,6 +98,8 @@ export interface GroupMemberJoin extends QQEvent {
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
operatorUin: number;
|
||||
userUid?: string;
|
||||
operatorUid?: string;
|
||||
}
|
||||
|
||||
export interface GroupMemberLeave extends QQEvent {
|
||||
@@ -105,6 +107,8 @@ export interface GroupMemberLeave extends QQEvent {
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
operatorUin: number;
|
||||
userUid?: string;
|
||||
operatorUid?: string;
|
||||
isKick: boolean;
|
||||
}
|
||||
|
||||
@@ -140,6 +144,7 @@ export interface GroupRecallEvent extends QQEvent {
|
||||
export interface FriendRequestEvent extends QQEvent {
|
||||
kind: 'friend_request';
|
||||
fromUin: number;
|
||||
fromUid?: string;
|
||||
message: string;
|
||||
flag: string;
|
||||
}
|
||||
@@ -148,6 +153,7 @@ export interface GroupInviteEvent extends QQEvent {
|
||||
kind: 'group_invite';
|
||||
groupId: number;
|
||||
fromUin: number;
|
||||
fromUid?: string;
|
||||
subType: string;
|
||||
message: string;
|
||||
flag: string;
|
||||
|
||||
@@ -597,12 +597,16 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
case PkgType.GroupMemberIncreaseNotice: {
|
||||
const change = protoDecode(content, GroupChangeSchema);
|
||||
if (!change) return [];
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join', time: timestamp, selfUin,
|
||||
groupId: change.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
|
||||
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
|
||||
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
|
||||
groupId,
|
||||
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -611,12 +615,16 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const change = protoDecode(content, GroupChangeSchema);
|
||||
if (!change) return [];
|
||||
const dt = change.decreaseType ?? 0;
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberLeave = {
|
||||
kind: 'group_member_leave', time: timestamp, selfUin,
|
||||
groupId: change.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
|
||||
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
|
||||
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
|
||||
groupId,
|
||||
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
isKick: dt !== 0 && dt !== 130,
|
||||
};
|
||||
return [ev];
|
||||
@@ -643,6 +651,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: join.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
|
||||
fromUid: join.targetUid ?? '',
|
||||
subType: 'add', message: '',
|
||||
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
|
||||
};
|
||||
@@ -657,6 +666,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: inner.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
|
||||
fromUid: inner.invitorUid ?? '',
|
||||
subType: 'invite', message: '',
|
||||
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
|
||||
};
|
||||
@@ -670,6 +680,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: invite.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
|
||||
fromUid: invite.invitorUid ?? '',
|
||||
subType: 'invite', message: '',
|
||||
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
|
||||
};
|
||||
@@ -685,6 +696,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
|
||||
const ev: FriendRequestEvent = {
|
||||
kind: 'friend_request', time: timestamp, selfUin,
|
||||
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin),
|
||||
fromUid: sourceUid,
|
||||
message: request.info.message ?? '', flag: sourceUid,
|
||||
};
|
||||
return [ev];
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
EncodableMediaMsgInfoSchema,
|
||||
} from '../proto/highway';
|
||||
import { loadBinarySource, computeHashes } from './utils';
|
||||
import { loadBinarySource, computeHashes, resolveLocalFilePath } from './utils';
|
||||
import {
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
@@ -49,23 +49,6 @@ interface PttPayload {
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether `source` looks like a local filesystem path. The shape
|
||||
* matches the heuristics used inside `loadBinarySource`: we only reuse the
|
||||
* caller-supplied path verbatim for things the addon can read directly.
|
||||
*/
|
||||
function asLocalFilePath(source: string): string | null {
|
||||
if (!source) return null;
|
||||
if (source.startsWith('base64://')) return null;
|
||||
if (source.startsWith('http://') || source.startsWith('https://')) return null;
|
||||
|
||||
let filePath = source;
|
||||
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('record source is empty');
|
||||
@@ -87,7 +70,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
||||
// Resolve the on-disk path the addon should read. Anything that isn't
|
||||
// already a local file (base64, HTTP) gets staged into the temp dir.
|
||||
let inputPath: string;
|
||||
const local = asLocalFilePath(source);
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
inputPath = local;
|
||||
} else {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
@@ -25,14 +26,42 @@ export interface ImageFormat {
|
||||
|
||||
// --- Binary source loading ---
|
||||
|
||||
export function resolveLocalFilePath(source: string): string | null {
|
||||
if (!source) return null;
|
||||
if (/^base64:\/\//i.test(source)) return null;
|
||||
if (/^https?:\/\//i.test(source)) return null;
|
||||
|
||||
let filePath = source;
|
||||
if (/^file:\/\//i.test(source)) {
|
||||
try {
|
||||
filePath = fileURLToPath(source);
|
||||
} catch {
|
||||
filePath = source.replace(/^file:\/+/i, '/');
|
||||
try {
|
||||
filePath = decodeURIComponent(filePath);
|
||||
} catch {
|
||||
// Keep the original fallback path when percent decoding fails.
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform !== 'win32' && filePath.startsWith('//')) {
|
||||
filePath = filePath.replace(/^\/+/, '/');
|
||||
}
|
||||
}
|
||||
|
||||
// Windows-style paths can arrive from file:///C:/... as /C:/...
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (source.startsWith('base64://')) {
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
|
||||
}
|
||||
|
||||
if (source.startsWith('http://') || source.startsWith('https://')) {
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source);
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
@@ -40,11 +69,8 @@ export async function loadBinarySource(source: string, resourceName: string): Pr
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
// File path (strip file:// prefix)
|
||||
let filePath = source;
|
||||
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
|
||||
// Windows: strip leading / before drive letter
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
loadBinarySource,
|
||||
computeHashes,
|
||||
detectImageFormat,
|
||||
resolveLocalFilePath,
|
||||
} from './utils';
|
||||
import {
|
||||
fetchHighwaySession,
|
||||
@@ -212,18 +213,6 @@ function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function asLocalFilePath(source: string): string | null {
|
||||
if (!source) return null;
|
||||
if (source.startsWith('base64://')) return null;
|
||||
if (source.startsWith('http://') || source.startsWith('https://')) return null;
|
||||
|
||||
let filePath = source;
|
||||
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function defaultVideoTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-video');
|
||||
}
|
||||
@@ -232,7 +221,7 @@ function sourceExtension(fileName: string, source: string): string {
|
||||
const fromName = path.extname(fileName);
|
||||
if (fromName) return fromName;
|
||||
|
||||
const local = asLocalFilePath(source);
|
||||
const local = resolveLocalFilePath(source);
|
||||
const fromSource = local ? path.extname(local) : '';
|
||||
return fromSource || '.mp4';
|
||||
}
|
||||
@@ -250,7 +239,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('video source is empty');
|
||||
|
||||
const local = asLocalFilePath(source);
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
return {
|
||||
bytes: new Uint8Array(fs.readFileSync(local)),
|
||||
|
||||
@@ -0,0 +1,758 @@
|
||||
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 { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('Identity');
|
||||
|
||||
interface UserInput {
|
||||
uid?: string;
|
||||
uin?: number;
|
||||
nickname?: string;
|
||||
remark?: string;
|
||||
isFriend?: boolean;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
interface GroupInput {
|
||||
groupId: number;
|
||||
groupName?: string;
|
||||
remark?: string;
|
||||
memberCount?: number;
|
||||
memberMax?: number;
|
||||
}
|
||||
|
||||
interface MemberInput {
|
||||
groupId: number;
|
||||
uid?: string;
|
||||
uin?: number;
|
||||
nickname?: string;
|
||||
card?: string;
|
||||
role?: string;
|
||||
level?: number;
|
||||
title?: string;
|
||||
joinTime?: number;
|
||||
lastSentTime?: number;
|
||||
shutUpTime?: number;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
interface UserRow {
|
||||
id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
is_friend: number;
|
||||
source: string;
|
||||
}
|
||||
|
||||
interface MemberRow {
|
||||
id: number;
|
||||
group_id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
active: number;
|
||||
}
|
||||
|
||||
export class IdentityService {
|
||||
private readonly db: DatabaseSync | null;
|
||||
private readonly uinByUid = new Map<string, number>();
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
private inTransaction = false;
|
||||
private writeFailed = false;
|
||||
|
||||
constructor(
|
||||
private readonly qqInfo: QQInfo,
|
||||
dbPath: string | null,
|
||||
) {
|
||||
if (!dbPath) {
|
||||
this.db = null;
|
||||
return;
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
static openForUin(qqInfo: QQInfo, dataRoot = 'data'): IdentityService {
|
||||
return new IdentityService(qqInfo, path.join(dataRoot, qqInfo.uin, 'snowluma_identity.db'));
|
||||
}
|
||||
|
||||
static memory(qqInfo: QQInfo): IdentityService {
|
||||
return new IdentityService(qqInfo, null);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db?.close();
|
||||
}
|
||||
|
||||
get persistent(): boolean {
|
||||
return this.db !== null;
|
||||
}
|
||||
|
||||
get hasWriteFailure(): boolean {
|
||||
return this.writeFailed;
|
||||
}
|
||||
|
||||
rememberFriends(friends: FriendInfo[]): void {
|
||||
this.qqInfo.setFriends(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')
|
||||
.run(nowSeconds());
|
||||
for (const friend of friends) {
|
||||
this.upsertUser({
|
||||
uid: friend.uid,
|
||||
uin: friend.uin,
|
||||
nickname: friend.nickname,
|
||||
remark: friend.remark,
|
||||
isFriend: true,
|
||||
source: 'friend',
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberGroups(groups: QQGroupInfo[]): void {
|
||||
this.qqInfo.setGroups(groups);
|
||||
this.runWrite('groups', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
.run(nowSeconds());
|
||||
for (const group of groups) {
|
||||
this.upsertGroup({
|
||||
groupId: group.groupId,
|
||||
groupName: group.groupName,
|
||||
remark: group.remark,
|
||||
memberCount: group.memberCount,
|
||||
memberMax: group.memberMax,
|
||||
});
|
||||
}
|
||||
}));
|
||||
this.hydrateActiveMembersForGroups(groups.map((group) => group.groupId));
|
||||
}
|
||||
|
||||
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||
this.qqInfo.setGroupMembers(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 });
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
|
||||
.run(nowSeconds(), groupId);
|
||||
for (const member of members) {
|
||||
this.upsertGroupMember({
|
||||
groupId,
|
||||
uid: member.uid,
|
||||
uin: member.uin,
|
||||
nickname: member.nickname,
|
||||
card: member.card,
|
||||
role: member.role,
|
||||
level: member.level,
|
||||
title: member.title,
|
||||
joinTime: member.joinTime,
|
||||
lastSentTime: member.lastSentTime,
|
||||
shutUpTime: member.shutUpTime,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
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.rememberUidUin(info.uid, info.uin);
|
||||
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
|
||||
uid: info.uid,
|
||||
uin: info.uin,
|
||||
nickname: info.nickname,
|
||||
remark: info.remark,
|
||||
source: 'profile',
|
||||
})));
|
||||
}
|
||||
|
||||
rememberGroupRequests(requests: GroupRequestInfo[]): void {
|
||||
for (const request of requests) {
|
||||
this.rememberUidUin(request.targetUid, request.targetUin);
|
||||
this.rememberUidUin(request.invitorUid, request.invitorUin);
|
||||
this.rememberUidUin(request.operatorUid, request.operatorUin);
|
||||
}
|
||||
this.runWrite('group requests', () => this.transaction(() => {
|
||||
for (const request of requests) {
|
||||
this.upsertGroup({ groupId: request.groupId, groupName: request.groupName });
|
||||
this.upsertUser({
|
||||
uid: request.targetUid,
|
||||
uin: request.targetUin,
|
||||
nickname: request.targetName,
|
||||
source: 'group_request',
|
||||
});
|
||||
this.upsertUser({
|
||||
uid: request.invitorUid,
|
||||
uin: request.invitorUin,
|
||||
nickname: request.invitorName,
|
||||
source: 'group_request',
|
||||
});
|
||||
this.upsertUser({
|
||||
uid: request.operatorUid,
|
||||
uin: request.operatorUin,
|
||||
nickname: request.operatorName,
|
||||
source: 'group_request',
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberRequestIdentity(
|
||||
identity: { groupId?: number; uid?: string; uin?: number; nickname?: string; source?: string },
|
||||
): void {
|
||||
this.rememberUidUin(identity.uid, identity.uin);
|
||||
this.runWrite('request identity', () => this.transaction(() => {
|
||||
if (identity.groupId !== undefined) this.upsertGroup({ groupId: identity.groupId });
|
||||
this.upsertUser({
|
||||
uid: identity.uid,
|
||||
uin: identity.uin,
|
||||
nickname: identity.nickname,
|
||||
source: identity.source || 'request',
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
rememberGroupMemberIdentity(
|
||||
groupId: number,
|
||||
identity: { uid?: string; uin?: number; nickname?: string; card?: string },
|
||||
): void {
|
||||
this.rememberUidUin(identity.uid, identity.uin);
|
||||
this.runWrite('group member identity', () => this.transaction(() => this.upsertGroupMember({
|
||||
groupId,
|
||||
uid: identity.uid,
|
||||
uin: identity.uin,
|
||||
nickname: identity.nickname,
|
||||
card: identity.card,
|
||||
active: true,
|
||||
})));
|
||||
}
|
||||
|
||||
markGroupMemberInactive(groupId: number, identity: { uid?: string; uin?: number }): void {
|
||||
this.runWrite('group member inactive', () => {
|
||||
const uid = normalizeUid(identity.uid);
|
||||
const uin = normalizeUin(identity.uin);
|
||||
if (!uid && uin === null) return;
|
||||
const rows = this.findMemberRows(groupId, uid, uin);
|
||||
const updatedAt = nowSeconds();
|
||||
this.transaction(() => {
|
||||
for (const row of rows) {
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
|
||||
.run(updatedAt, row.id);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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 rememberUidUin(uid: unknown, uin: unknown): void {
|
||||
const normalizedUid = normalizeUid(uid);
|
||||
const normalizedUin = normalizeUin(uin);
|
||||
if (!normalizedUid || normalizedUin === null) return;
|
||||
this.uinByUid.set(normalizedUid, normalizedUin);
|
||||
this.uidByUin.set(normalizedUin, normalizedUid);
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db!.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid TEXT UNIQUE,
|
||||
uin INTEGER UNIQUE,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
is_friend INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_users_uid ON users(uid);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_users_uin ON users(uin);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
group_id INTEGER PRIMARY KEY,
|
||||
group_name TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
member_count INTEGER NOT NULL DEFAULT 0,
|
||||
member_max INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS group_members (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
group_id INTEGER NOT NULL,
|
||||
uid TEXT,
|
||||
uin INTEGER,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
card TEXT NOT NULL DEFAULT '',
|
||||
role TEXT NOT NULL DEFAULT 'member',
|
||||
level INTEGER NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
join_time INTEGER NOT NULL DEFAULT 0,
|
||||
last_sent_time INTEGER NOT NULL DEFAULT 0,
|
||||
shut_up_time INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(group_id, uid),
|
||||
UNIQUE(group_id, uin)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_active
|
||||
ON group_members(group_id, active);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uid
|
||||
ON group_members(group_id, uid);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uin
|
||||
ON group_members(group_id, uin);
|
||||
`);
|
||||
}
|
||||
|
||||
private loadSnapshot(): void {
|
||||
const friendRows = this.db!.prepare(
|
||||
`SELECT uid, uin, nickname, remark
|
||||
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) => ({
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
remark: row.remark,
|
||||
})));
|
||||
|
||||
const groups = this.db!.prepare(
|
||||
`SELECT group_id, group_name, remark, member_count, member_max
|
||||
FROM groups
|
||||
WHERE active = 1`,
|
||||
).all() as Array<{
|
||||
group_id: number;
|
||||
group_name: string;
|
||||
remark: string;
|
||||
member_count: number;
|
||||
member_max: number;
|
||||
}>;
|
||||
this.qqInfo.setGroups(groups.map((row) => ({
|
||||
groupId: row.group_id,
|
||||
groupName: row.group_name,
|
||||
remark: row.remark,
|
||||
memberCount: row.member_count,
|
||||
memberMax: row.member_max,
|
||||
members: new Map(),
|
||||
})));
|
||||
this.hydrateActiveMembersForGroups(groups.map((row) => row.group_id));
|
||||
}
|
||||
|
||||
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
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND active = 1`,
|
||||
);
|
||||
for (const groupId of groupIds) {
|
||||
const rows = select.all(groupId) as Array<{
|
||||
group_id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private upsertUser(input: UserInput): void {
|
||||
if (!this.db) return;
|
||||
|
||||
const uid = normalizeUid(input.uid);
|
||||
const uin = normalizeUin(input.uin);
|
||||
if (!uid && uin === null) return;
|
||||
|
||||
const rows = this.findUserRows(uid, uin);
|
||||
const primary = rows[0];
|
||||
const merged = {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: normalizeText(input.nickname) || primary?.nickname || '',
|
||||
remark: normalizeText(input.remark) || primary?.remark || '',
|
||||
isFriend: input.isFriend === true ? 1 : (primary?.is_friend ?? 0),
|
||||
source: normalizeText(input.source) || primary?.source || '',
|
||||
updatedAt: nowSeconds(),
|
||||
};
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
`UPDATE users
|
||||
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.remark,
|
||||
merged.isFriend,
|
||||
merged.source,
|
||||
merged.updatedAt,
|
||||
primary.id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.remark,
|
||||
merged.isFriend,
|
||||
merged.source,
|
||||
merged.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
private upsertGroup(input: GroupInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const existing = this.db.prepare(
|
||||
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
|
||||
).get(input.groupId) as {
|
||||
group_name: string;
|
||||
remark: string;
|
||||
member_count: number;
|
||||
member_max: number;
|
||||
} | undefined;
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?)
|
||||
ON CONFLICT(group_id) DO UPDATE SET
|
||||
group_name = excluded.group_name,
|
||||
remark = excluded.remark,
|
||||
member_count = excluded.member_count,
|
||||
member_max = excluded.member_max,
|
||||
active = 1,
|
||||
updated_at = excluded.updated_at`,
|
||||
).run(
|
||||
input.groupId,
|
||||
normalizeText(input.groupName) || existing?.group_name || '',
|
||||
normalizeText(input.remark) || existing?.remark || '',
|
||||
normalizeNonNegative(input.memberCount, existing?.member_count ?? 0),
|
||||
normalizeNonNegative(input.memberMax, existing?.member_max ?? 0),
|
||||
nowSeconds(),
|
||||
);
|
||||
}
|
||||
|
||||
private upsertGroupMember(input: MemberInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const uid = normalizeUid(input.uid);
|
||||
const uin = normalizeUin(input.uin);
|
||||
if (!uid && uin === null) return;
|
||||
|
||||
this.upsertGroup({ groupId: input.groupId });
|
||||
this.upsertUser({
|
||||
uid,
|
||||
uin: uin ?? undefined,
|
||||
nickname: input.nickname,
|
||||
source: 'group_member',
|
||||
});
|
||||
|
||||
const rows = this.findMemberRows(input.groupId, uid, uin);
|
||||
const primary = rows[0];
|
||||
const merged = {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: normalizeText(input.nickname) || primary?.nickname || '',
|
||||
card: normalizeText(input.card) || primary?.card || '',
|
||||
role: normalizeText(input.role) || primary?.role || 'member',
|
||||
level: normalizeNonNegative(input.level, primary?.level ?? 0),
|
||||
title: normalizeText(input.title) || primary?.title || '',
|
||||
joinTime: normalizeNonNegative(input.joinTime, primary?.join_time ?? 0),
|
||||
lastSentTime: normalizeNonNegative(input.lastSentTime, primary?.last_sent_time ?? 0),
|
||||
shutUpTime: normalizeNonNegative(input.shutUpTime, primary?.shut_up_time ?? 0),
|
||||
active: input.active === false ? 0 : input.active === true ? 1 : (primary?.active ?? 1),
|
||||
updatedAt: nowSeconds(),
|
||||
};
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
`UPDATE group_members
|
||||
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
|
||||
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
merged.joinTime,
|
||||
merged.lastSentTime,
|
||||
merged.shutUpTime,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
primary.id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO group_members
|
||||
(group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
input.groupId,
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
merged.joinTime,
|
||||
merged.lastSentTime,
|
||||
merged.shutUpTime,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
private findUserRows(uid: string, uin: number | null): UserRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id',
|
||||
).all(uid, uin) as unknown as UserRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id',
|
||||
).all(uid) as unknown as UserRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
|
||||
).all(uin) as unknown as UserRow[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND (uid = ? OR uin = ?)
|
||||
ORDER BY id`,
|
||||
).all(groupId, uid, uin) as unknown as MemberRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND uid = ?
|
||||
ORDER BY id`,
|
||||
).all(groupId, uid) as unknown as MemberRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND uin = ?
|
||||
ORDER BY id`,
|
||||
).all(groupId, uin) as unknown as MemberRow[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private transaction<T>(fn: () => T): T {
|
||||
if (!this.db || this.inTransaction) return fn();
|
||||
this.inTransaction = true;
|
||||
this.db.exec('BEGIN');
|
||||
try {
|
||||
const result = fn();
|
||||
this.db.exec('COMMIT');
|
||||
return result;
|
||||
} catch (err) {
|
||||
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
|
||||
throw err;
|
||||
} finally {
|
||||
this.inTransaction = false;
|
||||
}
|
||||
}
|
||||
|
||||
private runWrite(label: string, fn: () => void): void {
|
||||
if (!this.db) return;
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
this.writeFailed = true;
|
||||
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rowToMemberInfo(row: {
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
}): GroupMemberInfo {
|
||||
return {
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
role: row.role || 'member',
|
||||
level: row.level,
|
||||
title: row.title,
|
||||
joinTime: row.join_time,
|
||||
lastSentTime: row.last_sent_time,
|
||||
shutUpTime: row.shut_up_time,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeUid(uid: unknown): string {
|
||||
return typeof uid === 'string' ? uid.trim() : '';
|
||||
}
|
||||
|
||||
function normalizeUin(uin: unknown): number | null {
|
||||
if (typeof uin === 'number' && Number.isFinite(uin)) {
|
||||
const n = Math.trunc(uin);
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
if (typeof uin === 'string' && uin.trim()) {
|
||||
const parsed = Number(uin);
|
||||
if (Number.isFinite(parsed)) {
|
||||
const n = Math.trunc(parsed);
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeText(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function normalizeNonNegative(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function nowSeconds(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
import type { NtqqHandler } from '../protocol/ntqq-handler';
|
||||
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';
|
||||
@@ -48,6 +49,7 @@ export class BridgeManager {
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
if (this.onSessionClosed_) this.onSessionClosed_(uin);
|
||||
session.bridge.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +109,7 @@ export class BridgeManager {
|
||||
if (session) return { session, created: false };
|
||||
|
||||
const qqInfo = new QQInfo(uin);
|
||||
const bridge = new Bridge(qqInfo);
|
||||
const bridge = new Bridge(qqInfo, IdentityService.openForUin(qqInfo));
|
||||
session = { qqInfo, bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
|
||||
@@ -28,6 +28,26 @@ export const OidbMuteAllSchema = {
|
||||
muteState: { field: 2, type: 'message' as const, schema: OidbMuteAllStateSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x89A_0: Set group add option ---
|
||||
|
||||
export const Oidb0x89a_0AddOptionSettingsSchema = {
|
||||
addType: { field: 16, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0x89a_0AddOptionSchema = {
|
||||
groupUin: { field: 1, type: 'uint64' as const },
|
||||
settings: { field: 2, type: 'message' as const, schema: Oidb0x89a_0AddOptionSettingsSchema },
|
||||
field12: { field: 12, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x89A_0: Set group search ---
|
||||
|
||||
export const Oidb0x89a_0SearchSchema = {
|
||||
groupUin: { field: 1, type: 'uint64' as const },
|
||||
settings: { field: 2, type: 'bytes' as const },
|
||||
field12: { field: 12, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x8A0_1: Kick group member ---
|
||||
|
||||
export const OidbKickMemberSchema = {
|
||||
@@ -1018,4 +1038,86 @@ export const Oidb0xeb7ReqSchema = {
|
||||
signInInfo: { field: 2, type: 'message' as const, schema: Oidb0xeb7SignInInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0xeb7RespSchema = {} satisfies ProtoSchema;
|
||||
export const Oidb0xeb7RespSchema = {} satisfies ProtoSchema;
|
||||
|
||||
// --- Faceroam.OpReq: Fetch custom face ---
|
||||
|
||||
export const FaceroamOpReqInnerSchema = {
|
||||
field1: { field: 1, type: 'uint32' as const },
|
||||
osVersion: { field: 2, type: 'string' as const },
|
||||
qqVersion: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FaceroamOpReqSchema = {
|
||||
inner: { field: 1, type: 'message' as const, schema: FaceroamOpReqInnerSchema },
|
||||
uin: { field: 2, type: 'uint64' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
field6: { field: 6, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FaceroamOpRespItemSchema = {
|
||||
faceIds: { field: 1, type: 'repeated_string' as const },
|
||||
category: { field: 3, type: 'string' as const },
|
||||
totalCount: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FaceroamOpRespSchema = {
|
||||
retCode: { field: 1, type: 'uint32' as const },
|
||||
message: { field: 2, type: 'string' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
item: { field: 4, type: 'message' as const, schema: FaceroamOpRespItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x9083_1: Get emoji likes ---
|
||||
|
||||
export const Oidb0x9083ReqSchema = {
|
||||
groupId: { field: 2, type: 'uint64' as const },
|
||||
sequence: { field: 3, type: 'uint32' as const },
|
||||
emojiType: { field: 4, type: 'uint32' as const },
|
||||
emojiId: { field: 5, type: 'string' as const },
|
||||
cookie: { field: 6, type: 'bytes' as const },
|
||||
field7: { field: 7, type: 'uint32' as const },
|
||||
count: { field: 8, type: 'uint32' as const },
|
||||
field12: { field: 12, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0x9083RespUserInfoSchema = {
|
||||
uin: { field: 1, type: 'uint64' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0x9083RespInnerSchema = {
|
||||
userInfo: { field: 1, type: 'message' as const, schema: Oidb0x9083RespUserInfoSchema },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0x9083RespSchema = {
|
||||
inner: { field: 4, type: 'message' as const, schema: Oidb0x9083RespInnerSchema },
|
||||
cookie: { field: 5, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x8a0_1: Kick group members (batch) ---
|
||||
|
||||
export const Oidb0x8a0ReqSchema = {
|
||||
groupId: { field: 1, type: 'uint64' as const },
|
||||
targetUids: { field: 3, type: 'repeated_string' as const },
|
||||
rejectAddRequest: { field: 4, type: 'uint32' as const },
|
||||
kickReason: { field: 5, type: 'bytes' as const },
|
||||
field12: { field: 12, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0x8a0RespSchema = {} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xf16_1: Set group remark ---
|
||||
|
||||
export const Oidb0xf16InnerSchema = {
|
||||
groupId: { field: 1, type: 'uint64' as const },
|
||||
remark: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0xf16ReqSchema = {
|
||||
inner: { field: 1, type: 'message' as const, schema: Oidb0xf16InnerSchema },
|
||||
field12: { field: 12, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0xf16RespSchema = {} satisfies ProtoSchema;
|
||||
@@ -9,6 +9,7 @@ export const PIPE_VERSION = 1;
|
||||
export const HEADER_SIZE = 40;
|
||||
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
|
||||
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
|
||||
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
|
||||
|
||||
export enum PipeOp {
|
||||
hello = 1,
|
||||
@@ -102,6 +103,63 @@ function mojoPipeName(pid: number, suffix: string): string {
|
||||
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
|
||||
}
|
||||
|
||||
type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
|
||||
|
||||
async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await fs.stat(socketPath);
|
||||
if (!stat.isSocket()) return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let socket: net.Socket;
|
||||
try {
|
||||
socket = net.createConnection(socketPath);
|
||||
} catch {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
let done = false;
|
||||
let timer: NodeJS.Timeout;
|
||||
const finish = (ok: boolean) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolve(ok);
|
||||
};
|
||||
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
|
||||
socket.once('connect', () => finish(true));
|
||||
socket.once('error', () => finish(false));
|
||||
});
|
||||
}
|
||||
|
||||
export async function listLiveLinuxPipePids(
|
||||
runtimeDir = linuxRuntimeDir(),
|
||||
probe: LinuxPipeProbe = isConnectableUnixSocket,
|
||||
): Promise<Set<number>> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.readdir(runtimeDir);
|
||||
} catch {
|
||||
return result;
|
||||
}
|
||||
|
||||
await Promise.all(names.map(async (name) => {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
|
||||
if (!m) return;
|
||||
const pid = Number(m[1]);
|
||||
if (!Number.isInteger(pid) || pid <= 0) return;
|
||||
if (await probe(path.join(runtimeDir, name))) result.add(pid);
|
||||
}));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
|
||||
if (Buffer.isBuffer(body)) return body;
|
||||
if (body instanceof Uint8Array) return Buffer.from(body);
|
||||
@@ -312,11 +370,7 @@ export class QqHookClient extends EventEmitter {
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
} else {
|
||||
const names = await fs.readdir(linuxRuntimeDir());
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
return await listLiveLinuxPipePids();
|
||||
}
|
||||
} catch {
|
||||
/* directory missing or inaccessible — treat as no live pipes */
|
||||
|
||||
@@ -494,6 +494,15 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_remark', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const remark = asString(params.remark) ?? '';
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!ctx.setGroupRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupRemark(groupId, remark);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_msg_emoji_like', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const emojiId = asString(params.emoji_id);
|
||||
@@ -644,6 +653,59 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('fetch_custom_face', async (params) => {
|
||||
const count = asNumber(params.count) || 10;
|
||||
if (!ctx.fetchCustomFace) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
try {
|
||||
const urls = await ctx.fetchCustomFace(count);
|
||||
return okResponse(urls);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_emoji_likes', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const emojiId = asString(params.emoji_id) || '';
|
||||
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
|
||||
if (!ctx.getEmojiLikes) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
try {
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
|
||||
const result = await ctx.getEmojiLikes(meta.targetId, meta.sequence, emojiId);
|
||||
return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) });
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('fetch_emoji_like', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const emojiId = asString(params.emojiId) || '';
|
||||
const emojiType = asNumber(params.emojiType) || 1;
|
||||
const count = asNumber(params.count) || 10;
|
||||
const cookie = asString(params.cookie) || '';
|
||||
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required');
|
||||
if (!ctx.getEmojiLikes) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
try {
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
|
||||
const result = await ctx.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
|
||||
return okResponse({
|
||||
result: 0,
|
||||
errMsg: '',
|
||||
emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })),
|
||||
cookie: result.cookie,
|
||||
isLastPage: result.isLast,
|
||||
isFirstPage: !cookie,
|
||||
});
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_friends_with_category', async () => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
|
||||
@@ -13,6 +13,16 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_kick_members', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
|
||||
if (!ctx.setGroupKickMembers) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupKickMembers(groupId, userIds, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
@@ -32,6 +42,23 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_option', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const addType = asNumber(params.add_type);
|
||||
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
|
||||
if (!ctx.setGroupAddOption) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupAddOption(groupId, addType);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_search', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!ctx.setGroupSearch) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupSearch(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_admin', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
|
||||
@@ -48,8 +48,11 @@ export interface ApiActionContext {
|
||||
getStrangerInfo?: (userId: number) => Promise<JsonObject | null>;
|
||||
// Group admin
|
||||
setGroupKick?: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
|
||||
setGroupKickMembers?: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
|
||||
setGroupBan?: (groupId: number, userId: number, duration: number) => Promise<void>;
|
||||
setGroupWholeBan?: (groupId: number, enable: boolean) => Promise<void>;
|
||||
setGroupAddOption?: (groupId: number, addType: number) => Promise<void>;
|
||||
setGroupSearch?: (groupId: number) => Promise<void>;
|
||||
setGroupAdmin?: (groupId: number, userId: number, enable: boolean) => Promise<void>;
|
||||
setGroupCard?: (groupId: number, userId: number, card: string) => Promise<void>;
|
||||
setGroupName?: (groupId: number, name: string) => Promise<void>;
|
||||
@@ -100,11 +103,14 @@ export interface ApiActionContext {
|
||||
getForwardMsg?: (resId: string) => Promise<JsonObject[]>;
|
||||
// Extended NapCat-compatible
|
||||
setFriendRemark?: (userId: number, remark: string) => Promise<void>;
|
||||
setGroupRemark?: (groupId: number, remark: string) => Promise<void>;
|
||||
getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
|
||||
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
|
||||
markGroupMsgAsRead?: (groupId: number, sequence: number) => Promise<void>;
|
||||
markPrivateMsgAsRead?: (userId: number, sequence: number) => Promise<void>;
|
||||
getProfileLike?: (userId?: number, start?: number, limit?: number) => Promise<any>;
|
||||
fetchCustomFace?: (count?: number) => Promise<string[]>;
|
||||
getEmojiLikes?: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>;
|
||||
// Web
|
||||
getGroupHonorInfo?: (groupId: number, type: WebHonorType | string) => Promise<any>;
|
||||
getGroupEssence?: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
|
||||
|
||||
@@ -135,7 +135,7 @@ export class EventConverter {
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
sub_type: event.operatorUin === event.userUin ? 'approve' : 'invite',
|
||||
sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
@@ -330,6 +330,11 @@ function parseSelfId(instanceUin: string): number {
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
function isSameActor(leftUin: number, leftUid: string | undefined, rightUin: number, rightUid: string | undefined): boolean {
|
||||
if (leftUin > 0 && rightUin > 0) return leftUin === rightUin;
|
||||
return Boolean(leftUid) && leftUid === rightUid;
|
||||
}
|
||||
|
||||
async function elementsToJson(
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
|
||||
@@ -72,8 +72,11 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getStrangerInfo: (userId) => handleGetStrangerInfo(bridge, qqInfo, userId),
|
||||
// Group admin
|
||||
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
|
||||
setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject),
|
||||
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
|
||||
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
|
||||
setGroupAddOption: (groupId, addType) => bridge.setGroupAddOption(groupId, addType),
|
||||
setGroupSearch: (groupId) => bridge.setGroupSearch(groupId),
|
||||
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
|
||||
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
|
||||
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
|
||||
@@ -107,6 +110,8 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true),
|
||||
deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false),
|
||||
getProfileLike: (userId?: number, start: number = 0, limit: number = 10) => bridge.getProfileLike(userId, start, limit),
|
||||
fetchCustomFace: (count?: number) => bridge.fetchCustomFace(count),
|
||||
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
|
||||
getUnidirectionalFriendList: () => bridge.getUnidirectionalFriendList(),
|
||||
setSelfLongNick: (longNick) => bridge.setSelfLongNick(longNick),
|
||||
setInputStatus: (userId, eventType) => bridge.setInputStatus(userId, eventType),
|
||||
@@ -154,6 +159,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
|
||||
// Extended NapCat-compatible
|
||||
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
|
||||
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
|
||||
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
|
||||
setMsgEmojiLike: async (messageId, emojiId, set) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface ParseMessageOptions {
|
||||
|
||||
// --- CQ Code parsing ---
|
||||
|
||||
const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g;
|
||||
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
|
||||
|
||||
function parseCQParams(raw: string): Record<string, string> {
|
||||
const params: Record<string, string> = {};
|
||||
@@ -71,6 +71,7 @@ async function parseFromCQString(message: string, options?: ParseMessageOptions)
|
||||
interface MessageSegment {
|
||||
type: string;
|
||||
data?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function isSegmentArray(val: unknown): val is MessageSegment[] {
|
||||
@@ -80,7 +81,8 @@ function isSegmentArray(val: unknown): val is MessageSegment[] {
|
||||
}
|
||||
|
||||
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
||||
switch (type) {
|
||||
const normalizedType = type.toLowerCase();
|
||||
switch (normalizedType) {
|
||||
case 'text': {
|
||||
const text = String(data.text ?? '');
|
||||
return text ? { type: 'text', text } : null;
|
||||
@@ -143,14 +145,14 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
case 'image': {
|
||||
return {
|
||||
type: 'image',
|
||||
url: String(data.file ?? data.url ?? ''),
|
||||
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
|
||||
flash: data.type === 'flash',
|
||||
subType: parseInt(String(data.subType ?? '0'), 10),
|
||||
summary: data.summary ? String(data.summary) : undefined,
|
||||
};
|
||||
}
|
||||
case 'record': {
|
||||
const source = String(data.file ?? data.url ?? data.path ?? '');
|
||||
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
|
||||
if (!source) return null;
|
||||
return {
|
||||
type: 'record',
|
||||
@@ -158,7 +160,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
};
|
||||
}
|
||||
case 'video': {
|
||||
const source = String(data.file ?? data.url ?? data.path ?? '');
|
||||
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
|
||||
if (!source) return null;
|
||||
return {
|
||||
type: 'video',
|
||||
@@ -320,6 +322,16 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
}
|
||||
}
|
||||
|
||||
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
const topLevel = { ...seg } as Record<string, unknown>;
|
||||
delete topLevel.type;
|
||||
delete topLevel.data;
|
||||
const nested = (seg.data && typeof seg.data === 'object' && !Array.isArray(seg.data))
|
||||
? seg.data
|
||||
: {};
|
||||
return { ...topLevel, ...nested };
|
||||
}
|
||||
|
||||
// --- Public API ---
|
||||
|
||||
/**
|
||||
@@ -341,7 +353,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
|
||||
if (isSegmentArray(message)) {
|
||||
const elements: MessageElement[] = [];
|
||||
for (const seg of message) {
|
||||
const data = (seg.data ?? {}) as Record<string, unknown>;
|
||||
const data = segmentPayload(seg);
|
||||
const elem = await segmentToElement(seg.type, data, options);
|
||||
if (elem) elements.push(elem);
|
||||
}
|
||||
@@ -352,7 +364,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
|
||||
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
|
||||
const seg = message as unknown as MessageSegment;
|
||||
if (seg.type) {
|
||||
const data = (seg.data ?? {}) as Record<string, unknown>;
|
||||
const data = segmentPayload(seg);
|
||||
const elem = await segmentToElement(seg.type, data, options);
|
||||
return elem ? [elem] : [];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
|
||||
import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events';
|
||||
import type { PacketInfo } from '../src/protocol/types';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
|
||||
function makeGroupMember(uin: number, uid: string): GroupMemberInfo {
|
||||
return {
|
||||
uin,
|
||||
uid,
|
||||
nickname: '',
|
||||
card: '',
|
||||
role: 'member',
|
||||
level: 0,
|
||||
title: '',
|
||||
joinTime: 0,
|
||||
lastSentTime: 0,
|
||||
shutUpTime: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
|
||||
return {
|
||||
groupId: GROUP_ID,
|
||||
groupName: '',
|
||||
remark: '',
|
||||
memberCount: members.length,
|
||||
memberMax: 500,
|
||||
members: new Map(members.map((member) => [member.uin, member])),
|
||||
};
|
||||
}
|
||||
|
||||
class RefreshingBridge extends Bridge {
|
||||
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
|
||||
|
||||
constructor(qqInfo: QQInfo, private readonly refreshedMembers: GroupMemberInfo[]) {
|
||||
super(qqInfo);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return this.refreshedMembers;
|
||||
}
|
||||
}
|
||||
|
||||
function makePacket(): PacketInfo {
|
||||
return {
|
||||
pid: 1,
|
||||
uin: SELF_UIN,
|
||||
serviceCmd: 'test.member_join',
|
||||
seqId: 1,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: new Uint8Array(0),
|
||||
};
|
||||
}
|
||||
|
||||
function makeRequestPacket(): PacketInfo {
|
||||
return {
|
||||
...makePacket(),
|
||||
serviceCmd: 'test.request_identity',
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin> {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
if (events[0]) return events[0];
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
throw new Error('timed out waiting for group_member_join');
|
||||
}
|
||||
|
||||
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 seen: GroupMemberJoin[] = [];
|
||||
|
||||
bridge.registerCmd('test.member_join', () => [{
|
||||
kind: 'group_member_join',
|
||||
time: 1710000000,
|
||||
selfUin: Number(SELF_UIN),
|
||||
groupId: GROUP_ID,
|
||||
userUin: 0,
|
||||
operatorUin: 0,
|
||||
userUid: member.uid,
|
||||
operatorUid: member.uid,
|
||||
}]);
|
||||
bridge.events.on('group_member_join', (event) => {
|
||||
seen.push(event);
|
||||
});
|
||||
|
||||
bridge.onPacket(makePacket());
|
||||
const event = await waitForEvent(seen);
|
||||
|
||||
expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
|
||||
expect(event.userUin).toBe(member.uin);
|
||||
expect(event.operatorUin).toBe(member.uin);
|
||||
});
|
||||
|
||||
it('remembers UID mappings from realtime request events', () => {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const bridge = new Bridge(qqInfo);
|
||||
const events: QQEventVariant[] = [
|
||||
{
|
||||
kind: 'friend_request',
|
||||
time: 1710000000,
|
||||
selfUin: Number(SELF_UIN),
|
||||
fromUin: 55555,
|
||||
fromUid: 'u_friend_request',
|
||||
message: '',
|
||||
flag: 'u_friend_request',
|
||||
},
|
||||
{
|
||||
kind: 'group_invite',
|
||||
time: 1710000000,
|
||||
selfUin: Number(SELF_UIN),
|
||||
groupId: GROUP_ID,
|
||||
fromUin: 66666,
|
||||
fromUid: 'u_group_request',
|
||||
subType: 'add',
|
||||
message: '',
|
||||
flag: 'add:123456789:u_group_request',
|
||||
},
|
||||
];
|
||||
|
||||
bridge.registerCmd('test.request_identity', () => events);
|
||||
bridge.onPacket(makeRequestPacket());
|
||||
|
||||
expect(bridge.identity.findUidByUin(55555)).toBe('u_friend_request');
|
||||
expect(bridge.identity.findUidByUin(66666)).toBe('u_group_request');
|
||||
expect(bridge.identity.findUinByUid('u_friend_request')).toBe(55555);
|
||||
expect(bridge.identity.findUinByUid('u_group_request')).toBe(66666);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { SendPacketResult } from '../src/protocol/packet-sender';
|
||||
import { protoDecode, protoEncode } from '../src/protobuf/decode';
|
||||
import { SendMessageRequestSchema, SendMessageResponseSchema } from '../src/bridge/proto/action';
|
||||
|
||||
vi.mock('../src/bridge/builders/element-builder', () => ({
|
||||
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
|
||||
}));
|
||||
|
||||
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');
|
||||
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
|
||||
override async resolveUserUid(uin: number): Promise<string> {
|
||||
expect(uin).toBe(12345);
|
||||
return 'u_peer_12345';
|
||||
}
|
||||
|
||||
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
|
||||
this.capturedBody = body;
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protoEncode({
|
||||
result: 0,
|
||||
privateSequence: 88,
|
||||
timestamp1: 1710000000,
|
||||
}, SendMessageResponseSchema)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const bridge = new TestBridge(new QQInfo('10000'));
|
||||
await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
|
||||
|
||||
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
|
||||
const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema);
|
||||
expect(request?.routingHead?.c2c).toMatchObject({
|
||||
uin: 12345,
|
||||
uid: 'u_peer_12345',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils';
|
||||
|
||||
describe('highway source paths', () => {
|
||||
it('normalizes file URLs with an extra leading slash on POSIX', () => {
|
||||
if (process.platform === 'win32') return;
|
||||
expect(resolveLocalFilePath('file:////AstrBot/data/plugin/cache/BV-test.mp4'))
|
||||
.toBe('/AstrBot/data/plugin/cache/BV-test.mp4');
|
||||
});
|
||||
|
||||
it('loads encoded file URLs from the local filesystem', async () => {
|
||||
const filePath = path.join(os.tmpdir(), `snowluma video ${process.pid}-${Date.now()}.txt`);
|
||||
fs.writeFileSync(filePath, 'ok');
|
||||
|
||||
try {
|
||||
const source = pathToFileURL(filePath).href;
|
||||
const loaded = await loadBinarySource(source, 'test file');
|
||||
expect(Buffer.from(loaded.bytes).toString('utf8')).toBe('ok');
|
||||
expect(loaded.fileName).toBe(path.basename(filePath));
|
||||
} finally {
|
||||
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { IdentityService } from '../src/bridge/identity-service';
|
||||
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
|
||||
const dbs: string[] = [];
|
||||
|
||||
function tempDbPath(label: string): string {
|
||||
const dbPath = path.join(
|
||||
'data',
|
||||
'test',
|
||||
`snowluma-identity-${label}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.db`,
|
||||
);
|
||||
dbs.push(dbPath);
|
||||
return dbPath;
|
||||
}
|
||||
|
||||
function cleanupDb(dbPath: string): void {
|
||||
for (const ext of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
function makeGroup(): QQGroupInfo {
|
||||
return {
|
||||
groupId: GROUP_ID,
|
||||
groupName: 'group',
|
||||
remark: '',
|
||||
memberCount: 0,
|
||||
memberMax: 500,
|
||||
members: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
function makeMember(uin: number, uid: string, card = ''): GroupMemberInfo {
|
||||
return {
|
||||
uin,
|
||||
uid,
|
||||
nickname: `nick-${uin}`,
|
||||
card,
|
||||
role: 'member',
|
||||
level: 1,
|
||||
title: '',
|
||||
joinTime: 10,
|
||||
lastSentTime: 20,
|
||||
shutUpTime: 0,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dbPath of dbs.splice(0)) cleanupDb(dbPath);
|
||||
});
|
||||
|
||||
describe('IdentityService', () => {
|
||||
it('persists friends, groups, and active group members', () => {
|
||||
const dbPath = tempDbPath('persist');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' }]);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]);
|
||||
identity.close();
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, 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.findUidByUin(33333, GROUP_ID)).toBe('u_member');
|
||||
expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333);
|
||||
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('marks missing members inactive only after a successful full refresh', () => {
|
||||
const dbPath = tempDbPath('inactive-refresh');
|
||||
const first = makeMember(33333, 'u_first');
|
||||
const second = makeMember(44444, 'u_second');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [first, second]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [second]);
|
||||
identity.close();
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
|
||||
expect(qqInfo.findGroupMember(GROUP_ID, first.uin)).toBeNull();
|
||||
expect(qqInfo.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);
|
||||
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('marks missing friends and groups inactive after successful full refreshes', () => {
|
||||
const dbPath = tempDbPath('inactive-lists');
|
||||
const member = makeMember(33333, 'u_member');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' }]);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [member]);
|
||||
identity.rememberFriends([]);
|
||||
identity.rememberGroups([]);
|
||||
identity.close();
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
|
||||
expect(qqInfo.findFriend(22222)).toBeNull();
|
||||
expect(qqInfo.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);
|
||||
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('can mark one member inactive without losing the identity mapping', () => {
|
||||
const dbPath = tempDbPath('inactive-event');
|
||||
const member = makeMember(33333, 'u_member');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [member]);
|
||||
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
|
||||
identity.close();
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
|
||||
expect(qqInfo.findGroupMember(GROUP_ID, member.uin)).toBeNull();
|
||||
expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin);
|
||||
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('persists identities learned from request events', () => {
|
||||
const dbPath = tempDbPath('request-events');
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, dbPath);
|
||||
identity.rememberRequestIdentity({
|
||||
uid: 'u_friend_request',
|
||||
uin: 55555,
|
||||
source: 'friend_request',
|
||||
});
|
||||
identity.rememberRequestIdentity({
|
||||
groupId: GROUP_ID,
|
||||
uid: 'u_group_request',
|
||||
uin: 66666,
|
||||
source: 'group_request',
|
||||
});
|
||||
identity.close();
|
||||
}
|
||||
|
||||
{
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
const identity = new IdentityService(qqInfo, 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.findUidByUin(66666)).toBe('u_group_request');
|
||||
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -108,6 +108,14 @@ describe('parseMessage', () => {
|
||||
expect(result).toEqual([{ type: 'video', url: '/tmp/clip.mp4', thumbUrl: '/tmp/clip.png' }]);
|
||||
});
|
||||
|
||||
it('parses AstrBot-style Video segment with top-level media', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'Video', media: 'file:////AstrBot/data/cache/BV-test.mp4' }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'video', url: 'file:////AstrBot/data/cache/BV-test.mp4', thumbUrl: undefined }]);
|
||||
});
|
||||
|
||||
it('drops video segment with empty source', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'video', data: {} }] as any,
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/handlers/msg-push-handler';
|
||||
import { QQInfo, type GroupMemberInfo, type 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';
|
||||
import type { PacketInfo } from '../src/protocol/types';
|
||||
import { protoEncode } from '../src/protobuf/decode';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
|
||||
function makeGroupMember(uin: number, uid: string): GroupMemberInfo {
|
||||
return {
|
||||
uin,
|
||||
uid,
|
||||
nickname: '',
|
||||
card: '',
|
||||
role: 'member',
|
||||
level: 0,
|
||||
title: '',
|
||||
joinTime: 0,
|
||||
lastSentTime: 0,
|
||||
shutUpTime: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
|
||||
return {
|
||||
groupId: GROUP_ID,
|
||||
groupName: '',
|
||||
remark: '',
|
||||
memberCount: members.length,
|
||||
memberMax: 500,
|
||||
members: new Map(members.map((member) => [member.uin, member])),
|
||||
};
|
||||
}
|
||||
|
||||
function makeQqInfo(members: GroupMemberInfo[] = []): QQInfo {
|
||||
const qqInfo = new QQInfo(SELF_UIN);
|
||||
qqInfo.setGroups([makeGroup(members)]);
|
||||
return qqInfo;
|
||||
}
|
||||
|
||||
function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo {
|
||||
const operatorBytes = operatorUid
|
||||
? protoEncode({ operatorField: { uid: operatorUid } } as any, OperatorInfoSchema)
|
||||
: new Uint8Array(0);
|
||||
const content = protoEncode({
|
||||
groupUin: GROUP_ID,
|
||||
memberUid,
|
||||
operatorBytes,
|
||||
} as any, GroupChangeSchema);
|
||||
const body = protoEncode({
|
||||
message: {
|
||||
responseHead: { fromUin },
|
||||
contentHead: { msgType: 33, timestamp: 1710000000 },
|
||||
body: { msgContent: content },
|
||||
},
|
||||
status: 0,
|
||||
} as any, PushMsgSchema);
|
||||
|
||||
return {
|
||||
pid: 1,
|
||||
uin: SELF_UIN,
|
||||
serviceCmd: MSG_PUSH_CMD,
|
||||
seqId: 1,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body,
|
||||
};
|
||||
}
|
||||
|
||||
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[];
|
||||
|
||||
expect(event.kind).toBe('group_member_join');
|
||||
expect(event.groupId).toBe(GROUP_ID);
|
||||
expect(event.userUin).toBe(0);
|
||||
expect(event.operatorUin).toBe(0);
|
||||
expect(event.userUid).toBe('u_new_member');
|
||||
});
|
||||
|
||||
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[];
|
||||
|
||||
expect(event.userUin).toBe(member.uin);
|
||||
expect(event.operatorUin).toBe(operator.uin);
|
||||
expect(event.userUid).toBe(member.uid);
|
||||
expect(event.operatorUid).toBe(operator.uid);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listLiveLinuxPipePids } from '../src/hook/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
async function makeRuntimeDir(): Promise<string> {
|
||||
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (!tmpDir) return;
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
});
|
||||
|
||||
describe('listLiveLinuxPipePids', () => {
|
||||
it('ignores stale-looking control socket names when the probe rejects them', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
|
||||
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
|
||||
|
||||
expect([...pids]).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns only connectable control sockets', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), '');
|
||||
|
||||
const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock'));
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, probe);
|
||||
|
||||
expect([...pids]).toEqual([56]);
|
||||
expect(probe).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user