Merge upstream/dev into feat/onebot
This commit is contained in:
commit
0d40a03f28
122 files changed
+7842
-1099
No files matched your search
@@ -66,6 +66,9 @@ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<St
|
||||
request: {
|
||||
schema: OidbStrangerStatusReqSchema,
|
||||
value: { uin, key: [{ key: 27372 }] },
|
||||
// Same UIN-form flag fetchUserProfile sets — without it newer
|
||||
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
|
||||
isUid: true,
|
||||
},
|
||||
response: { schema: OidbStrangerStatusRespSchema },
|
||||
});
|
||||
|
||||
@@ -28,12 +28,23 @@ const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
||||
async function buildForwardPushBody(
|
||||
bridge: Bridge,
|
||||
node: ForwardNodePayload,
|
||||
groupId?: number,
|
||||
userUid?: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
|
||||
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
|
||||
|
||||
const nickname = node.nickname.trim() || String(fromUin);
|
||||
const elems = await buildSendElems(node.elements);
|
||||
// image/record/video upload inside a forward node must be scoped to the
|
||||
// forward's recipient: group → groupId, private → recipient uid.
|
||||
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
|
||||
// element builder throws "private image target uid is missing".
|
||||
const sendCtx = groupId !== undefined
|
||||
? { bridge, groupId }
|
||||
: userUid
|
||||
? { bridge, userUid }
|
||||
: { bridge };
|
||||
const elems = await buildSendElems(node.elements, sendCtx);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
|
||||
const seq = Math.floor(Math.random() * 9000000) + 1000000;
|
||||
@@ -62,12 +73,32 @@ async function buildForwardPushBody(
|
||||
};
|
||||
}
|
||||
|
||||
export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise<string> {
|
||||
export async function uploadForwardNodes(
|
||||
bridge: Bridge,
|
||||
nodes: ForwardNodePayload[],
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<string> {
|
||||
if (!Array.isArray(nodes) || nodes.length === 0) {
|
||||
throw new Error('forward nodes are required');
|
||||
}
|
||||
|
||||
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node)));
|
||||
// For a private forward to `userId`, any image/record/video inside a node
|
||||
// needs the recipient's uid as upload scene. Resolve it once up-front,
|
||||
// and only when at least one node actually contains media (saves an RPC
|
||||
// for text-only forwards).
|
||||
let userUid: string | undefined;
|
||||
if (groupId === undefined && userId !== undefined && userId > 0) {
|
||||
const hasMedia = nodes.some(node => node.elements.some(
|
||||
e => e.type === 'image' || e.type === 'record' || e.type === 'video',
|
||||
));
|
||||
if (hasMedia) {
|
||||
const resolved = await bridge.resolveUserUid(userId);
|
||||
if (resolved) userUid = resolved;
|
||||
}
|
||||
}
|
||||
|
||||
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid)));
|
||||
const longMsgResult = protoEncode({
|
||||
action: [
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { Bridge } from '../bridge';
|
||||
import { protoEncode } from '../../protobuf/decode';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
|
||||
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
|
||||
import {
|
||||
OidbGroupFileCountViewReqSchema,
|
||||
OidbGroupFileCountViewRespSchema,
|
||||
@@ -288,7 +288,9 @@ export async function uploadGroupFile(
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const loaded = await loadBinarySource(source, 'file');
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('group file is empty');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
@@ -366,7 +368,9 @@ export async function uploadPrivateFile(
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const loaded = await loadBinarySource(source, 'file');
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await bridge.resolveUserUid(userId);
|
||||
|
||||
@@ -103,6 +103,19 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
// The config flags ask QQ which per-group fields to include in the
|
||||
// response. Asking for everything looks innocent on small accounts
|
||||
// but on ~200+ groups it makes the QQ NT process write a payload
|
||||
// large enough to blow the named-pipe write buffer — we then read
|
||||
// EPIPE and the whole session dies. See issue #42.
|
||||
//
|
||||
// The user-verified safe combination: keep `config1.*` mostly on
|
||||
// (the response decoder pulls groupOwner / memberMax / memberCount /
|
||||
// groupName / description / question / announcement from this
|
||||
// group), but turn off the costly groups of bools that never map
|
||||
// back to a decoded field:
|
||||
// - config1.field5002, field5003 (expansive 5xxx-range descriptors)
|
||||
// - all of config2 (auxiliary per-group blob the decoder ignores)
|
||||
const allTrue = true;
|
||||
const body = {
|
||||
config: {
|
||||
@@ -114,11 +127,11 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
|
||||
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
|
||||
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
|
||||
},
|
||||
config2: {
|
||||
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
|
||||
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
|
||||
field1: false, field2: false, field3: false, field4: false,
|
||||
field5: false, field6: false, field7: false, field8: false,
|
||||
},
|
||||
config3: { field5: allTrue, field6: allTrue },
|
||||
},
|
||||
@@ -208,16 +221,23 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
|
||||
|
||||
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
|
||||
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
|
||||
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
|
||||
// sending field 2 makes the server reject the request.
|
||||
const body = {
|
||||
uin,
|
||||
field2: 0,
|
||||
keys: keys.map(k => ({ key: k })),
|
||||
};
|
||||
|
||||
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
|
||||
// name is historical, the wire semantic is "this is the UIN-form
|
||||
// variant of the call"). Without it newer QQ NT versions take the
|
||||
// UID-form validation path, find neither uid nor openid in the body
|
||||
// and bounce the request with `[oidb] one of uid/openid is invaild`.
|
||||
// Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1).
|
||||
const resp = await runOidb<any>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
|
||||
oidbCmd: 0xFE1, subCmd: 2,
|
||||
request: { schema: OidbUserInfoRequestSchema, value: body },
|
||||
request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true },
|
||||
response: { schema: OidbUserInfoResponseSchema },
|
||||
});
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ export interface BridgeInterface {
|
||||
likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any>;
|
||||
|
||||
// ─── Forward ───
|
||||
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
|
||||
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string>;
|
||||
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
|
||||
|
||||
// ─── Message ops ───
|
||||
|
||||
@@ -20,10 +20,16 @@ export interface OidbCall<TResp = void> {
|
||||
schema: ProtoSchema;
|
||||
value: any;
|
||||
/**
|
||||
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
|
||||
* of commands (group/friend list, rkey download) operate on
|
||||
* UID-keyed data and require this flag — the wire format is
|
||||
* otherwise identical.
|
||||
* Sets the OIDB envelope `reserved` field to 1 when true.
|
||||
*
|
||||
* The name is historical and misleading: empirically (see Lagrange
|
||||
* FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own
|
||||
* highway uploads) the `reserved = 1` flag indicates the UIN-form
|
||||
* variant of an OIDB call — it tells newer QQ NT to translate the
|
||||
* UIN in the body to an internal UID rather than running the
|
||||
* UID-form validator that expects a uid/openid string in the body.
|
||||
*
|
||||
* Omit (default false) for genuinely UID-keyed calls.
|
||||
*/
|
||||
isUid?: boolean;
|
||||
};
|
||||
|
||||
@@ -461,7 +461,7 @@ export class Bridge implements BridgeInterface {
|
||||
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
|
||||
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
|
||||
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
|
||||
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
|
||||
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId, userId); }
|
||||
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
|
||||
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
|
||||
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
|
||||
|
||||
@@ -37,19 +37,43 @@ function makeFaceElem(faceId: number): ProtoElem {
|
||||
};
|
||||
}
|
||||
|
||||
function makeMentionElem(element: MessageElement): ProtoElem {
|
||||
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
|
||||
if (!ctx || !targetUin) return '';
|
||||
if (ctx.groupId !== undefined) {
|
||||
const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin);
|
||||
return member?.card?.trim() || member?.nickname?.trim() || '';
|
||||
}
|
||||
const friend = ctx.bridge.identity.findFriend(targetUin);
|
||||
return friend?.remark?.trim() || friend?.nickname?.trim() || '';
|
||||
}
|
||||
|
||||
function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem {
|
||||
const mentionAll = element.uid === 'all' || element.targetUin === 0;
|
||||
const targetUin = element.targetUin ?? 0;
|
||||
|
||||
const extra = protoEncode({
|
||||
type: mentionAll ? 1 : 2,
|
||||
uin: mentionAll ? 0 : (element.targetUin ?? 0),
|
||||
uin: mentionAll ? 0 : targetUin,
|
||||
field5: 0,
|
||||
uid: mentionAll ? 'all' : (element.uid ?? ''),
|
||||
}, MentionExtraSendSchema);
|
||||
|
||||
// Prefer an explicit display string from the caller; otherwise look the
|
||||
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
|
||||
// Falls back to the bare uin when the roster doesn't know them yet.
|
||||
let str = element.text;
|
||||
if (!str) {
|
||||
if (mentionAll) {
|
||||
str = '@全体成员 ';
|
||||
} else {
|
||||
const name = resolveMentionDisplay(ctx, targetUin);
|
||||
str = name ? `@${name} ` : `@${targetUin} `;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text: {
|
||||
str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `),
|
||||
str,
|
||||
pbReserve: extra,
|
||||
} as any,
|
||||
};
|
||||
@@ -260,7 +284,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
break;
|
||||
|
||||
case 'at':
|
||||
result.push(makeMentionElem(elem));
|
||||
result.push(makeMentionElem(elem, ctx));
|
||||
break;
|
||||
|
||||
case 'reply':
|
||||
|
||||
@@ -230,6 +230,22 @@ export interface FriendAddEvent extends QQEvent {
|
||||
userUin: number;
|
||||
}
|
||||
|
||||
export interface GroupMsgEmojiLikeEvent extends QQEvent {
|
||||
kind: 'group_msg_emoji_like';
|
||||
groupId: number;
|
||||
operatorUin: number;
|
||||
operatorUid: string;
|
||||
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
|
||||
msgSeq: number;
|
||||
/** Emoji ID. QQ system faces are short numeric strings; market faces
|
||||
* are alphanumeric. We keep the wire string verbatim. */
|
||||
emojiId: string;
|
||||
/** Multiplicity of the reaction event. Usually 1. */
|
||||
count: number;
|
||||
/** True when the reaction is being added; false when removed. */
|
||||
isAdd: boolean;
|
||||
}
|
||||
|
||||
export type QQEventVariant =
|
||||
| FriendMessage
|
||||
| GroupMessage
|
||||
@@ -246,4 +262,5 @@ export type QQEventVariant =
|
||||
| GroupPokeEvent
|
||||
| GroupEssenceEvent
|
||||
| GroupFileUploadEvent
|
||||
| FriendAddEvent;
|
||||
| FriendAddEvent
|
||||
| GroupMsgEmojiLikeEvent;
|
||||
@@ -129,10 +129,31 @@ export function buildHighwayExtend(
|
||||
|
||||
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection({ host, port }, () => resolve(socket));
|
||||
let settled = false;
|
||||
const onTimeout = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
reject(new Error('TCP connect timeout'));
|
||||
};
|
||||
const onError = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(err);
|
||||
};
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
// Drop the connect-only listeners so subsequent IO errors / idle
|
||||
// timeouts don't try to reject this already-resolved promise.
|
||||
socket.setTimeout(0);
|
||||
socket.removeListener('timeout', onTimeout);
|
||||
socket.removeListener('error', onError);
|
||||
resolve(socket);
|
||||
});
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
|
||||
socket.on('error', reject);
|
||||
socket.once('timeout', onTimeout);
|
||||
socket.once('error', onError);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -148,8 +169,21 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
let headerEnd = -1;
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
let settled = false;
|
||||
|
||||
const checkComplete = () => {
|
||||
const detach = () => {
|
||||
socket.off('data', onData);
|
||||
socket.off('error', onError);
|
||||
socket.off('close', onClose);
|
||||
};
|
||||
const finish = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
detach();
|
||||
fn();
|
||||
};
|
||||
const onData = (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd < 0) {
|
||||
const idx = buf.indexOf('\r\n\r\n');
|
||||
@@ -162,19 +196,19 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
}
|
||||
}
|
||||
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||
socket.removeAllListeners('data');
|
||||
socket.removeAllListeners('error');
|
||||
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
|
||||
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
|
||||
}
|
||||
};
|
||||
|
||||
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
|
||||
socket.on('error', reject);
|
||||
socket.on('close', () => {
|
||||
const onError = (err: Error) => finish(() => reject(err));
|
||||
const onClose = () => finish(() => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
});
|
||||
|
||||
socket.on('data', onData);
|
||||
socket.on('error', onError);
|
||||
socket.on('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
@@ -16,6 +17,14 @@ import {
|
||||
} from './pipeline';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Image');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
interface ImageData {
|
||||
/** Empty when the caller is forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
@@ -106,7 +115,13 @@ export async function uploadImageMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
|
||||
@@ -25,6 +25,9 @@ import {
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
} from '../proto/highway';
|
||||
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
|
||||
// ─────────────── public types ───────────────
|
||||
|
||||
@@ -123,6 +126,11 @@ export function hexToBytes(hex: string): Uint8Array {
|
||||
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
// Build the full body once. Pulling this in here means each format file
|
||||
// only specifies the seven fields that actually vary.
|
||||
@@ -184,6 +192,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
return session;
|
||||
};
|
||||
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
@@ -203,7 +212,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
|
||||
return upload;
|
||||
|
||||
@@ -22,7 +22,13 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
|
||||
const log = createLogger('Ptt');
|
||||
const moduleLog = createLogger('Highway.Ptt');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_PTT_CMD_ID = 1007;
|
||||
export const GROUP_PTT_CMD_ID = 1008;
|
||||
@@ -105,7 +111,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
||||
const silk = await encodeSilk(inputPath, tempDir);
|
||||
if (silk.converted) {
|
||||
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
||||
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
@@ -141,8 +147,15 @@ export async function uploadPttMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const tempDir = defaultPttTempDir();
|
||||
const ptt = await loadPtt(element, tempDir);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
|
||||
ptt.fileSize,
|
||||
ptt.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
ptt.duration);
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
|
||||
@@ -11,6 +11,20 @@ export interface LoadedBinary {
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default cap on a single binary load issued through this helper. Callers
|
||||
* that route here (image / voice via base64+HTTP, group/private file
|
||||
* uploads, avatar) get bounded reads. Not all callers route through here
|
||||
* — in particular `video-upload.stageVideoSource` reads local-video files
|
||||
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
|
||||
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
|
||||
* file protocol legitimately supports up to 4 GiB.
|
||||
*/
|
||||
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
@@ -54,24 +68,74 @@ export function resolveLocalFilePath(source: string): string | null {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
|
||||
const bytes = Buffer.from(source.slice(9), 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName: '' };
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source);
|
||||
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
// Stream the body incrementally so a server that omits or
|
||||
// understates Content-Length can't make us buffer a chunked response
|
||||
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
|
||||
// the entire payload before we get a chance to length-check it.
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw new Error(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.size > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`);
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
return { bytes, fileName };
|
||||
@@ -183,7 +247,12 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
if (offset + 4 > bytes.length) break;
|
||||
const segLen = readBE16(bytes, offset + 2);
|
||||
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
|
||||
if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) {
|
||||
// Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC
|
||||
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
|
||||
// and friends, then misread Huffman table bytes as image dimensions.
|
||||
const isSof = marker >= 0xC0 && marker <= 0xCF
|
||||
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
|
||||
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
|
||||
height = readBE16(bytes, offset + 5);
|
||||
width = readBE16(bytes, offset + 7);
|
||||
return { format: 1000, width, height };
|
||||
|
||||
@@ -29,7 +29,13 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
|
||||
const log = createLogger('Video');
|
||||
const moduleLog = createLogger('Highway.Video');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_VIDEO_CMD_ID = 1001;
|
||||
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
|
||||
@@ -280,6 +286,14 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
// Pre-check on disk size BEFORE reading bytes into memory. The later
|
||||
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
|
||||
// run after we'd already allocated the entire file (so a 10 GiB
|
||||
// local path still OOMs us before the check fires).
|
||||
const stat = fs.statSync(local);
|
||||
if (stat.size > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
return {
|
||||
bytes: new Uint8Array(fs.readFileSync(local)),
|
||||
filePath: local,
|
||||
@@ -287,7 +301,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
|
||||
};
|
||||
}
|
||||
|
||||
const loaded = await loadBinarySource(source, 'video');
|
||||
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
|
||||
const fileName = element.fileName || loaded.fileName || '';
|
||||
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
|
||||
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
|
||||
@@ -315,7 +329,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
try {
|
||||
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
|
||||
} catch (err) {
|
||||
log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,7 +343,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
thumbBytes = new Uint8Array(info.image);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,7 +389,7 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
|
||||
const staged = await stageVideoSource(element, tempDir, cleanups);
|
||||
if (staged.bytes.length === 0) throw new Error('video file is empty');
|
||||
if (staged.bytes.length > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB`);
|
||||
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
|
||||
const hashes = computeHashes(staged.bytes);
|
||||
@@ -422,7 +436,13 @@ export async function uploadVideoMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const video = await loadVideo(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
video.fileSize,
|
||||
video.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
@@ -487,11 +507,17 @@ export async function uploadVideoMsgInfo(
|
||||
subFileType: 100,
|
||||
},
|
||||
],
|
||||
// Scene tag the NTV2 upload registers under. image-upload and
|
||||
// ptt-upload both differentiate (group=2, c2c=1); video was
|
||||
// hardcoded to the group value, which contributed to the c2c
|
||||
// send-back rejection (PbSendMsg result=79).
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
// Hardcoded 2 even on c2c (matches NapCat). Image/PTT use
|
||||
// `isGroup ? 2 : 1` because their legacy compat elements differ
|
||||
// per scene (notOnlineImage vs customFace; ptt c2c vs group),
|
||||
// but the legacy `videoFile` element has no scene split — its
|
||||
// fromChatType/toChatType live inside the element itself — so
|
||||
// the server generates a single group-shaped compat payload
|
||||
// regardless. Setting 1 here makes the server emit a c2c-scene
|
||||
// shaped compat blob that old QQ clients fail to resolve,
|
||||
// showing the message as "视频已过期" on those receivers while
|
||||
// new clients (which only read the commonElem) display fine.
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: {
|
||||
pic: { bizType: 0, textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
|
||||
|
||||
@@ -6,9 +6,9 @@ import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('Identity');
|
||||
const moduleLogger = createLogger('Identity');
|
||||
|
||||
/**
|
||||
* Hooks Identity uses when its read methods miss every cache layer. Wired in
|
||||
@@ -112,9 +112,14 @@ export class IdentityService {
|
||||
private readonly db: DatabaseSync | null;
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(uin: string, dbPath: string | null) {
|
||||
this.uin_ = uin;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLogger.child({ uin: uinNum })
|
||||
: moduleLogger;
|
||||
|
||||
if (!dbPath) {
|
||||
this.db = null;
|
||||
@@ -440,6 +445,13 @@ export class IdentityService {
|
||||
const normalizedUid = normalizeUid(uid);
|
||||
const normalizedUin = normalizeUin(uin);
|
||||
if (!normalizedUid || normalizedUin === null) return;
|
||||
// Drop any stale mapping for the old partner first; otherwise the two
|
||||
// maps disagree (`findUinByUid(oldUid) -> uin` while
|
||||
// `findUidByUin(uin) -> newUid`) after a uid/uin re-binding.
|
||||
const oldUid = this.uidByUin.get(normalizedUin);
|
||||
if (oldUid && oldUid !== normalizedUid) this.uinByUid.delete(oldUid);
|
||||
const oldUin = this.uinByUid.get(normalizedUid);
|
||||
if (oldUin !== undefined && oldUin !== normalizedUin) this.uidByUin.delete(oldUin);
|
||||
this.uinByUid.set(normalizedUid, normalizedUin);
|
||||
this.uidByUin.set(normalizedUin, normalizedUid);
|
||||
}
|
||||
@@ -833,7 +845,7 @@ export class IdentityService {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import { Event0x210SubType } from '../enums';
|
||||
import {
|
||||
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
|
||||
} from '../helpers';
|
||||
import { createLogger } from '../../../utils/logger';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x210SubType) {
|
||||
@@ -21,6 +24,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
|
||||
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
|
||||
// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21).
|
||||
// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) /
|
||||
// GroupGreyTip (20) / GroupEssence (21).
|
||||
|
||||
import { protoDecode } from '../../../protobuf/decode';
|
||||
import {
|
||||
GroupMuteSchema, NotifyMessageBodySchema,
|
||||
GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema,
|
||||
} from '../../proto/notify';
|
||||
import type {
|
||||
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
|
||||
GroupMsgEmojiLikeEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
@@ -16,14 +18,19 @@ import {
|
||||
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
|
||||
unwrapGroupNotifyPayload,
|
||||
} from '../helpers';
|
||||
import { createLogger } from '../../../utils/logger';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x2DCSubType) {
|
||||
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
|
||||
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
|
||||
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
|
||||
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
@@ -104,3 +111,51 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
// Magic prefix QQ prepends to the GroupReactNotify payload inside
|
||||
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
|
||||
// (see api/group.ts: `msgContent?.slice(7)`).
|
||||
const GROUP_REACT_PREFIX_BYTES = 7;
|
||||
// Discriminator on GroupReactNotify.field13 — same subType is reused
|
||||
// for other notify variants, only 35 means "emoji react". Anything
|
||||
// else falls through to MsgPush.Unknown for protocol-drift visibility.
|
||||
const GROUP_REACT_DISCRIMINATOR = 35;
|
||||
|
||||
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
|
||||
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
|
||||
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
|
||||
const notify = protoDecode(payload, GroupReactNotifySchema);
|
||||
if (!notify) return [];
|
||||
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
|
||||
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
|
||||
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
|
||||
return [];
|
||||
}
|
||||
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
|
||||
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
|
||||
if (!content) return [];
|
||||
|
||||
const groupId = Number(notify.groupUin ?? 0n);
|
||||
const operatorUid = content.operatorUid ?? '';
|
||||
const emojiId = content.code ?? '';
|
||||
const count = content.count ?? 1;
|
||||
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
|
||||
// removed. Older payloads occasionally omit it; default to "add"
|
||||
// since most clients can only generate add events.
|
||||
const isAdd = (content.type ?? 1) === 1;
|
||||
const msgSeq = Number(target?.seq ?? 0n);
|
||||
|
||||
const ev: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
|
||||
operatorUid,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
count,
|
||||
isAdd,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export enum PkgType {
|
||||
|
||||
export enum Event0x2DCSubType {
|
||||
GroupMuteNotice = 12,
|
||||
GroupMsgEmojiLikeNotice = 16,
|
||||
GroupRecallNotice = 17,
|
||||
GroupGreyTipNotice = 20,
|
||||
GroupEssenceNotice = 21,
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { MsgPushContext } from './context';
|
||||
import type { PkgType } from './enums';
|
||||
|
||||
const log = createLogger('MsgPush');
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
|
||||
|
||||
@@ -27,7 +28,13 @@ export class MsgPushRegistry {
|
||||
|
||||
decode(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
|
||||
if (!decoder) return [];
|
||||
if (!decoder) {
|
||||
// Unrecognized PkgType: either we don't care about this notify, or
|
||||
// the QQ NT client added a new variant. Surface at debug so a
|
||||
// protocol change can be spotted without spamming production logs.
|
||||
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return decoder(ctx);
|
||||
} catch (e) {
|
||||
|
||||
@@ -20,10 +20,23 @@ import type { PacketInfo } from '../protocol/types';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { IdentityService } from './identity-service';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { formatEvent } from '../utils/event-format';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const eventLog = createLogger('Event');
|
||||
const moduleLog = createLogger('Bridge');
|
||||
const moduleEventLog = createLogger('Event');
|
||||
|
||||
// Notice kinds that get logged as a warning (operationally important
|
||||
// state changes that an operator probably wants to see at default
|
||||
// info level). Everything else falls through to info.
|
||||
const WARN_EVENT_KINDS = new Set([
|
||||
'group_recall',
|
||||
'friend_recall',
|
||||
'group_member_leave',
|
||||
'group_mute',
|
||||
'friend_request',
|
||||
'group_invite',
|
||||
]);
|
||||
|
||||
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
|
||||
|
||||
@@ -43,8 +56,18 @@ export interface PacketPipelineDeps {
|
||||
export class IncomingPacketPipeline {
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
private readonly log: Logger;
|
||||
private readonly eventLog: Logger;
|
||||
|
||||
constructor(private readonly deps: PacketPipelineDeps) {}
|
||||
constructor(private readonly deps: PacketPipelineDeps) {
|
||||
// Tag every line we emit with this Bridge's UIN so per-account file
|
||||
// routing works. Unparseable uin (shouldn't happen) falls back to
|
||||
// the module-level logger so we still log, just without the slot.
|
||||
const uinNum = Number.parseInt(deps.identity.uin, 10);
|
||||
const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null;
|
||||
this.log = bind ? moduleLog.child(bind) : moduleLog;
|
||||
this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog;
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
const arr = this.cmdHandlers_.get(cmd) ?? [];
|
||||
@@ -65,15 +88,18 @@ export class IncomingPacketPipeline {
|
||||
const events = handler(pkt, this.deps.identity);
|
||||
for (const event of events) {
|
||||
if (this.needsPreDispatchIdentityRefresh(event)) {
|
||||
void this.dispatchAfterIdentityRefresh(event);
|
||||
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
|
||||
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
} else {
|
||||
this.handleSideEffects(event);
|
||||
printEvent(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,12 +119,12 @@ export class IncomingPacketPipeline {
|
||||
try {
|
||||
refreshed = await this.prepareGroupMemberJoinIdentity(event);
|
||||
} catch (e) {
|
||||
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
this.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.handleSideEffects(event, refreshed);
|
||||
printEvent(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
|
||||
@@ -166,9 +192,9 @@ export class IncomingPacketPipeline {
|
||||
const task = (async () => {
|
||||
try {
|
||||
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
|
||||
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
this.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',
|
||||
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
groupId, reason, e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
this.memberRefreshTasks_.delete(groupId);
|
||||
@@ -226,50 +252,16 @@ export class IncomingPacketPipeline {
|
||||
}
|
||||
}
|
||||
|
||||
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':
|
||||
case 'friend_message':
|
||||
case 'temp_message':
|
||||
// Message logging is handled by OneBot layer with message ID
|
||||
break;
|
||||
case 'group_recall':
|
||||
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
||||
break;
|
||||
case 'friend_recall':
|
||||
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
|
||||
break;
|
||||
case 'group_member_join':
|
||||
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
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);
|
||||
break;
|
||||
case 'group_admin':
|
||||
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
|
||||
break;
|
||||
case 'friend_poke':
|
||||
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'group_poke':
|
||||
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'friend_request':
|
||||
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
|
||||
break;
|
||||
case 'group_invite':
|
||||
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
|
||||
break;
|
||||
case 'group_essence':
|
||||
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
|
||||
break;
|
||||
function printEvent(log: Logger, identity: IdentityService, event: QQEventVariant): void {
|
||||
// Message-class events (group/friend/temp message) get rendered by the
|
||||
// OneBot layer's logReceivedMessage — its output already includes the
|
||||
// assigned message ID, which the raw packet doesn't have. Returning
|
||||
// null here is the formatter's signal to skip.
|
||||
const message = formatEvent(identity, event);
|
||||
if (!message) return;
|
||||
if (WARN_EVENT_KINDS.has(event.kind)) {
|
||||
log.warn('%s', message);
|
||||
} else {
|
||||
log.info('%s', message);
|
||||
}
|
||||
}
|
||||
@@ -205,3 +205,41 @@ export const NotifyMessageBodySchema = {
|
||||
msgSequence: { field: 37, type: 'uint32' as const },
|
||||
field39: { field: 39, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// ─── Event0x2DC subType=16: GroupMsgEmojiLike ──────────────────────────────
|
||||
//
|
||||
// QQ pushes a Group message emoji reaction (someone tapped an emoji on a
|
||||
// message in a group). The payload nesting matches NapCat's transformer
|
||||
// (packet/transformer/proto/message/message.ts → GroupReactNotify); the
|
||||
// outermost message is preceded by a 7-byte prefix that must be stripped
|
||||
// before decoding (see the call site).
|
||||
|
||||
export const GroupReactionDataInnerDataTargetSchema = {
|
||||
seq: { field: 1, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataContentSchema = {
|
||||
code: { field: 1, type: 'string' as const },
|
||||
count: { field: 3, type: 'uint32' as const },
|
||||
operatorUid: { field: 4, type: 'string' as const },
|
||||
type: { field: 5, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataInnerDataSchema = {
|
||||
groupReactionTarget: { field: 2, type: 'message' as const, schema: GroupReactionDataInnerDataTargetSchema },
|
||||
groupReactionDataContent: { field: 3, type: 'message' as const, schema: GroupReactionDataContentSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataInnerSchema = {
|
||||
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataSchema = {
|
||||
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactNotifySchema = {
|
||||
groupUin: { field: 4, type: 'uint64' as const },
|
||||
field13: { field: 13, type: 'uint32' as const },
|
||||
groupReactionData: { field: 44, type: 'message' as const, schema: GroupReactionDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -190,10 +190,14 @@ export const OidbUserInfoKeySchema = {
|
||||
key: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions
|
||||
// reinterpret field 2 as `uid: string` / `openid: string` and reject
|
||||
// the request with "one of uid/openid is invaild" when a varint 0
|
||||
// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin`
|
||||
// and `key[]`, so we match that exactly.
|
||||
export const OidbUserInfoRequestSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbTwoNumberSchema = {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
// 定义接口返回类型
|
||||
export interface GroupEssenceMsgRet {
|
||||
@@ -39,6 +42,8 @@ export async function getGroupEssenceMsg(
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export enum WebHonorType {
|
||||
TALKATIVE = 'talkative',
|
||||
@@ -43,7 +46,8 @@ export async function getHonorListWebAPI(cookieObject: Record<string, string>, g
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
// console.error(e);
|
||||
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
|
||||
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import https from 'node:https';
|
||||
// import { readFileSync } from 'node:fs';
|
||||
// import * as console from "node:console";
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec?: number;
|
||||
@@ -112,6 +113,7 @@ export async function setGroupNoticeWebAPI(
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -158,7 +160,8 @@ export async function getGroupNoticeWebAPI(
|
||||
);
|
||||
// console.log(JSON.stringify(ret, null, 2));
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -215,11 +218,15 @@ export async function uploadGroupNoticeImage(
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', () => resolve(undefined));
|
||||
req.on('error', (err) => {
|
||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
||||
resolve(undefined);
|
||||
});
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -260,7 +267,8 @@ export async function deleteGroupNotice(
|
||||
false
|
||||
);
|
||||
return ret?.ec === 0;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user