refactor(packages): rename @snowluma/bridge → @snowluma/protocol

The package previously named "bridge" houses the protocol-byte layer
(OIDB cmds, msg-push decoders, highway uploaders, element-builder,
event bus). The name "bridge" suggested transport/lifecycle, which it
isn't — that role lives in core/hook and core/bridge/manager. Rename
to match what's actually inside.

This is a pure rename: zero logic changes, all 73 import sites updated
mechanically and TS-verified. core/onebot dependencies key updated.
ESLint override path adjusted for the moved oidb-services directory.

Rename detection threshold: git log --find-renames=20% recommended
when following history across this commit — content-replacement
(@snowluma/bridge → @snowluma/protocol) dropped per-file similarity
below git's default 50% on import-heavy files.
This commit is contained in:
DrSmoothl committed 2026-05-23 23:31:03 +08:00
1 parent 98296fcec5
commit c16064d7e3
238 files changed
+247 -284

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
// BridgeContext — the protocol-layer surface that anything inside
// @snowluma/protocol (highway uploaders, OIDB envelope helper, element
// builder, msg-push parsers) accepts when it needs `bridge.identity`
// or `bridge.sendRawPacket` plus the upload-metadata cache.
//
// Deliberately apis-less: @snowluma/protocol knows nothing about the
// `apis.<area>.method()` hub that lives in @snowluma/core, so the
// type that bridge code accepts must NOT mention `ApiHub`. The api-
// layer's own extended context (with `apis: ApiHub`) lives at
// @snowluma/core's same-named file and `extends` this one — Api
// classes import from THERE, bridge helpers import from HERE.
//
// The concrete `Bridge` class (in @snowluma/core) implements the
// extended interface, which is a superset of this one. Passing a
// `Bridge` where a slim `BridgeContext` is expected is a free upcast.
import type { IdentityService } from './identity-service';
import type { BridgeEventBus } from './event-bus';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
/**
* Metadata remembered after `upload_group_file` / `upload_private_file`
* succeeds. Lets the OneBot send-message path reconstruct the full
* payload when the caller only echoes the `file_id` back later. Lives
* here (not on @snowluma/core's `bridge.ts`) so element-builder + the
* forward-builder — both inside @snowluma/protocol — can read the cache
* without circular-importing @snowluma/core.
*/
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface BridgeContext {
// ── Per-instance state (one set per QQ account in a multi-account
// runtime; `BridgeManager` allocates one `Bridge` per uin and
// each Bridge owns its own identity/events/pipeline/apis). ──
readonly identity: IdentityService;
readonly events: BridgeEventBus;
// ── Raw I/O ──
/** Escape hatch for arbitrary protocol calls (used by Api classes
* and by the `send_packet` OneBot action). Every typed wrapper on an
* Api class eventually routes through here. */
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
/** uin → uid lookup (cached in IdentityService). `groupId` is an
* optional hint that lets the resolver fall back to a group-member
* roster when the friend list doesn't have the uin. */
resolveUserUid(uin: number, groupId?: number): Promise<string>;
// ── Send-side protocol helpers (Api classes that build a
// `SendMessageRequest` need these monotonic generators to fill in
// `clientSequence` and `random`). They were previously `private`
// on Bridge — promoted to public so the new Api classes can call
// them without `(bridge as any).nextXxx()`. ──
nextMessageRandom(): number;
nextClientSequence(): number;
// ── Uploaded-file metadata cache ──
//
// Bookkeeping shared between `GroupFileApi.upload*File` (writes the
// tuple at upload time) and `MessageApi.sendPrivateMessage` (reads
// it on later `send_msg` calls that carry only a file_id). Lives at
// this layer rather than inside `GroupFileApi` because the message
// send path is what queries the cache, and it shouldn't have to
// reach into a different Api class for an infrastructure lookup.
rememberUploadedFile(meta: UploadedFileMeta): void;
recallUploadedFile(fileId: string): UploadedFileMeta | undefined;
}
+69
View File
@@ -0,0 +1,69 @@
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb';
// Sender capability is the minimal interface needed by runOidb. The
// concrete BridgeContext (and the Bridge class extending it) is
// structurally a superset, so callers keep passing `bridge` unchanged.
import type { OidbSender } from './oidb-service';
/**
* Build the OidbBase<T>-shaped TS value. Pure helper, no protobuf
* encoding happens here — pair with `encodeOidbEnv<T>` to produce the
* wire bytes.
*
* The `isUid` flag sets the envelope `reserved` field to 1; despite the
* name (kept for back-compat with the legacy API), `reserved = 1`
* empirically signals the UIN-form variant of an OIDB call. Omit
* (default false) for genuinely UID-keyed calls.
*/
export function makeOidbEnvelope<T>(
oidbCmd: number,
subCmd: number,
body: T,
isUid: boolean = false,
): OidbBase<T> {
return {
command: oidbCmd,
subCommand: subCmd,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
};
}
/**
* Issue one OIDB request and return the raw response bytes.
*
* Typical usage:
* const env = makeOidbEnvelope<MyReq>(0x1253, 1, value);
* const buf = await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
* const resp = decodeOidbEnv<MyResp>(buf).body;
*
* Fire-and-check (no body decode):
* await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
*
* Always peeks at the envelope errorCode via the non-generic
* `OidbBaseMeta` view so a server-side rejection cannot slip past
* silently. Returns the raw response bytes (empty `Uint8Array` if the
* packet carried no payload).
*/
export async function runOidb(
sender: OidbSender,
cmd: string,
envelopeBytes: Uint8Array,
timeoutMs?: number,
): Promise<Uint8Array> {
const result = await sender.sendRawPacket(cmd, envelopeBytes, timeoutMs);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
const bytes = result.responseData ?? new Uint8Array(0);
if (bytes.length > 0) {
const meta = protobuf_decode<OidbBaseMeta>(bytes);
const code = meta?.errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`);
}
}
return bytes;
}
+461
View File
@@ -0,0 +1,461 @@
import { protobuf_encode } from '@snowluma/proton';
import { deflateSync } from 'zlib';
import { randomUUID } from 'crypto';
import type { BridgeContext } from './bridge-context';
import type { MessageElement } from './events';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
import type {
MarkdownData,
MentionExtraSend,
} from '@snowluma/proto-defs/action';
import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element';
type ProtoElem = Partial<Elem>;
export interface SendContext {
bridge: BridgeContext;
groupId?: number;
userUid?: string;
/**
* Set by the forward-message upload path. When `true`, file segments
* are encoded as receive-side wire shapes (group → `transElem(24)`,
* c2c → caller writes `body.msgContent` separately) instead of being
* dropped. The QQ-NT server rejects outgoing PbSendMsg with
* `transElem(24)` (result=79), but the long-msg upload service does
* NOT — it stores the gzipped protobuf verbatim, so the receiver
* can walk it back through the regular decoder. Mirrors NapCat's
* `PacketMsgFileElement.buildElement` + `buildContent` split (see
* `dev/napcatQQ/.../packet/message/element.ts:530-610`).
*/
forwardFake?: boolean;
}
function makeTextElem(text: string): ProtoElem {
return {
text: { str: text } as any,
};
}
function makeFaceElem(faceId: number): ProtoElem {
return {
face: { index: faceId } as any,
};
}
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 = protobuf_encode<MentionExtraSend>({
type: mentionAll ? 1 : 2,
uin: mentionAll ? 0 : targetUin,
field5: 0,
uid: mentionAll ? 'all' : (element.uid ?? ''),
});
// 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,
pbReserve: extra,
} as any,
};
}
function makeReplyElem(element: MessageElement): ProtoElem {
const seq = element.replySeq! & 0xFFFFFFFF;
const srcMsg: any = {
origSeqs: [seq],
};
// Add additional fields if available for better reply display
if (element.replySenderUin) {
srcMsg.senderUin = BigInt(element.replySenderUin);
}
if (element.replyTime) {
srcMsg.time = element.replyTime;
}
return { srcMsg };
}
function makeJsonElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: 1,
template1: payload,
} as any,
};
}
function makeXmlElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
template1: payload,
} as any,
};
}
function makeMarkdownElem(element: MessageElement): ProtoElem {
const data = protobuf_encode<MarkdownData>({ content: element.text ?? '' });
return {
commonElem: {
serviceType: 45,
pbElem: data,
businessType: 1,
} as any,
};
}
function makeForwardElem(element: MessageElement): ProtoElem {
const resId = (element.resId ?? '').trim();
if (!resId) {
throw new Error('forward resId is required');
}
// `uniseq` MUST round-trip between the preview JSON and the outer
// upload's piggyback `actionCommand` for nested forwards to resolve
// without an extra server hit. Generate one fresh if absent (flat
// forwards don't piggyback anyway, so the value is cosmetic there).
const uniseq = (element.forwardUuid ?? '').trim() || randomUUID();
const source = element.forwardSource && element.forwardSource.length > 0
? element.forwardSource
: '聊天记录';
const summary = element.forwardSummary && element.forwardSummary.length > 0
? element.forwardSummary
: '查看转发消息';
const prompt = element.forwardPrompt && element.forwardPrompt.length > 0
? element.forwardPrompt
: '[聊天记录]';
const news = Array.isArray(element.forwardNews) ? element.forwardNews : [];
const tSum = element.forwardTSum && element.forwardTSum > 0
? element.forwardTSum
: Math.max(news.length, 1);
// LightApp / `com.tencent.multimsg` is the modern wire shape both
// QQ-NT, Lagrange.Core, and NapCat emit and decode. The older
// `richMsg serviceID=35 m_resid=…` XML still renders on mobile QQ
// but it doesn't carry `uniseq`, so nested forwards lose the link
// between the inner preview and the piggybacked actions on the
// outer's LongMsgResult — cross-checked against
// `dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115`
// and `dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122`.
const lightApp = {
app: 'com.tencent.multimsg',
config: {
autosize: 1,
forward: 1,
round: 1,
type: 'normal',
width: 300,
},
desc: prompt,
extra: JSON.stringify({ filename: uniseq, tsum: tSum }),
meta: {
detail: {
news: news.map(n => ({ text: n.text ?? '' })),
resid: resId,
source,
summary,
uniseq,
},
},
prompt,
ver: '0.0.0.5',
view: 'contact',
};
const json = JSON.stringify(lightApp);
const deflated = deflateSync(Buffer.from(json, 'utf8'));
const payload = new Uint8Array(deflated.length + 1);
payload[0] = 0x01; // 0x01 prefix = deflated JSON (vs 0x00 = uncompressed XML)
payload.set(deflated, 1);
return {
lightApp: {
data: payload,
} as any,
};
}
async function makeImageElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private image target uid is missing');
}
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 20 : 10,
} as any,
};
}
async function makePttElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private record target uid is missing');
}
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 12=c2c, 22=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 22 : 12,
} as any,
};
}
/**
* Receive-side group file element shape — `transElem(elemType=24,
* elemValue: 0x01 | BE16(len) | GroupFileExtra)`.
*
* NOT used for outgoing PbSendMsg (the QQ-NT server rejects that with
* result=79); the group-file send-side flow goes through dedicated
* OIDB 0x6d9_4 via `bridge.apis.groupFile.publish`. This shape IS used
* inside the long-msg upload (forward / multi-msg) — the long-msg
* service stores the gzipped protobuf verbatim, and the receiver
* decodes file entities from `transElem(24)` (see
* `msg-push/rich-body-decoder.ts:169-187`).
*
* `ctx` is consulted to fill in size/name/md5/sha1 from the upload
* metadata cache when the caller only threaded the file_id through.
* Mirrors the c2c forward path in `apis/forward.ts::buildForwardPushBody`
* which already does this lookup — without it the receiver sees a
* "0 B" file with no name (OneBot11 `{type:'file', file_id}` segments
* typically omit the metadata since the upload action returned only
* the id).
*/
function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoElem {
if (!element.fileId) throw new Error('file element missing fileId');
const cached = ctx?.bridge.recallUploadedFile(element.fileId);
const fileSize = element.fileSize ?? cached?.fileSize ?? 0;
const fileName = element.fileName ?? cached?.fileName ?? '';
const md5 = element.md5Hex
? hexToBytes(element.md5Hex)
: (cached?.fileMd5 ?? new Uint8Array(0));
const sha1 = element.sha1Hex
? hexToBytes(element.sha1Hex)
: (cached?.fileSha1 ?? new Uint8Array(0));
// Outer field1 is hardcoded to 6 in NapCat's encoder
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
// busId=102 + the file_id + name + size + sha1/md5 hashes.
const extraBytes = protobuf_encode<GroupFileExtra>({
field1: 6,
fileName,
inner: {
info: {
busId: 102,
fileId: element.fileId,
fileSize: BigInt(fileSize),
fileName,
fileSha: sha1,
extInfoString: '',
fileMd5: md5,
},
},
});
if (extraBytes.length > 0xFFFF) {
// The 16-bit length prefix caps the payload at 64 KiB; even the
// densest GroupFileExtra (fileId/name/two hashes) is well under.
throw new Error(`group file extra too large (${extraBytes.length} > 65535)`);
}
const elemValue = new Uint8Array(3 + extraBytes.length);
elemValue[0] = 0x01;
elemValue[1] = (extraBytes.length >> 8) & 0xff;
elemValue[2] = extraBytes.length & 0xff;
elemValue.set(extraBytes, 3);
return {
transElem: {
elemType: 24,
elemValue,
} as any,
};
}
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private video target uid is missing');
}
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 21 : 11,
} as any,
};
}
/**
* Build proto Elem objects from an array of MessageElements.
* Supports: text, face, at, reply, json, xml, markdown, image, record, video, forward.
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
*/
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
const result: ProtoElem[] = [];
for (const elem of elements) {
switch (elem.type) {
case 'text':
if (elem.text) result.push(makeTextElem(elem.text));
break;
case 'face':
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
break;
case 'at':
result.push(makeMentionElem(elem, ctx));
break;
case 'reply':
if (elem.replySeq) result.push(makeReplyElem(elem));
break;
case 'json':
if (elem.text) result.push(makeJsonElem(elem));
break;
case 'xml':
if (elem.text) result.push(makeXmlElem(elem));
break;
case 'markdown':
if (elem.text) result.push(makeMarkdownElem(elem));
break;
case 'image':
if (ctx) {
result.push(await makeImageElem(ctx, elem));
} else {
console.warn('[ElemBuilder] image send requires SendContext');
}
break;
case 'forward':
if (elem.resId) result.push(makeForwardElem(elem));
break;
case 'record':
if (ctx) {
result.push(await makePttElem(ctx, elem));
} else {
console.warn('[ElemBuilder] record send requires SendContext');
}
break;
case 'video':
if (ctx) {
result.push(await makeVideoElem(ctx, elem));
} else {
console.warn('[ElemBuilder] video send requires SendContext');
}
break;
case 'file':
// Files split into two routes depending on whether this is a
// live send or a forward-message fake-send:
//
// 1. LIVE send (PbSendMsg / OIDB 0x6d9_4) — never carried on
// elems[]. The OneBot layer splits file segments off before
// calling buildSendElems:
// * c2c (private): split → `bridge.sendC2cFileMessage`
// (routingHead.trans0x211 + msgContent FileExtra).
// * group: split → `bridge.sendGroupFileMessage`
// (OIDB 0x6d9_4 publish).
// The QQ-NT server REJECTS outgoing PbSendMsg with a
// transElem(24) (result=79), so an element reaching here
// in live-send mode is a routing bug — drop with a warn.
//
// 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`.
// The long-msg service stores the gzipped protobuf verbatim
// and the receiver decodes file entities from transElem(24)
// + msgContent FileExtra. Mirror NapCat's split (see
// `dev/napcatQQ/.../packet/message/element.ts:530-610`):
// * group → emit transElem(24) via makeGroupFileElem
// * c2c → emit NOTHING here; the forward-builder pulls
// the file segment off and writes msgContent
// separately (because RichText.notOnlineFile +
// FileExtra both live outside elems[]).
if (ctx && ctx.forwardFake) {
if (ctx.groupId !== undefined) {
result.push(makeGroupFileElem(elem, ctx));
}
// c2c forwardFake intentionally falls through — handled by
// the forward-builder at the msgContent level.
} else {
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
}
break;
default:
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
break;
}
}
return result;
}
+119
View File
@@ -0,0 +1,119 @@
import { createLogger } from '@snowluma/common/logger';
import type { QQEventVariant } from './events';
type EventKind = QQEventVariant['kind'];
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;
export type EventHandler<K extends EventKind> = (event: EventOf<K>) => void | Promise<void>;
export type AnyEventHandler = (event: QQEventVariant) => void | Promise<void>;
export interface EventBusOptions {
/** Logger label for handler failures. Defaults to `Bridge.Events`. */
loggerName?: string;
/** Override the default error reporter (e.g. for tests). */
onError?: (kind: EventKind | '*', err: unknown) => void;
}
const DEFAULT_LOGGER = createLogger('Bridge.Events');
export class BridgeEventBus {
// Per-kind subscribers are stored as `Set<unknown>` so the container
// doesn't carry a contravariant function type that fights TS variance
// rules. The runtime invariant is straightforward: handlers stored under
// key `K` only ever see `EventOf<K>` events, which is what the single
// narrowing cast at the dispatch site below relies on.
private readonly handlers = new Map<EventKind, Set<unknown>>();
private readonly anyHandlers = new Set<AnyEventHandler>();
private readonly onError: (kind: EventKind | '*', err: unknown) => void;
constructor(opts: EventBusOptions = {}) {
if (opts.onError) {
this.onError = opts.onError;
} else {
const log = opts.loggerName ? createLogger(opts.loggerName) : DEFAULT_LOGGER;
this.onError = (kind, err) => {
log.error(
'event handler error [%s]: %s',
kind,
err instanceof Error ? (err.stack ?? err.message) : String(err),
);
};
}
}
/** Subscribe to one kind. Returns an unsubscribe function. */
on<K extends EventKind>(kind: K, handler: EventHandler<K>): () => void {
let set = this.handlers.get(kind);
if (!set) {
set = new Set();
this.handlers.set(kind, set);
}
set.add(handler);
return () => {
this.handlers.get(kind)?.delete(handler);
};
}
/** Subscribe to every kind (low-volume callers like loggers). */
onAny(handler: AnyEventHandler): () => void {
this.anyHandlers.add(handler);
return () => {
this.anyHandlers.delete(handler);
};
}
off<K extends EventKind>(kind: K, handler: EventHandler<K>): void {
this.handlers.get(kind)?.delete(handler);
}
has(kind: EventKind): boolean {
return (this.handlers.get(kind)?.size ?? 0) + this.anyHandlers.size > 0;
}
/** Drop every subscriber. Mostly useful for tests. */
clear(): void {
this.handlers.clear();
this.anyHandlers.clear();
}
/**
* Dispatch an event in parallel to every subscriber for its kind plus every
* onAny handler. Rejections are isolated per-handler — one bad subscriber
* never blocks the others, and the returned promise resolves once every
* subscriber settles.
*/
async emit<K extends EventKind>(event: EventOf<K>): Promise<void> {
const kindHandlers = this.handlers.get(event.kind);
if ((!kindHandlers || kindHandlers.size === 0) && this.anyHandlers.size === 0) {
return;
}
const tasks: Promise<unknown>[] = [];
if (kindHandlers) {
for (const handler of kindHandlers) {
// Single narrowing cast — the only place we re-assert that handlers
// stored under `event.kind` accept `EventOf<event.kind>` events.
const typed = handler as EventHandler<K>;
tasks.push(invoke(this.onError, event.kind, () => typed(event)));
}
}
for (const handler of this.anyHandlers) {
tasks.push(invoke(this.onError, '*', () => handler(event)));
}
await Promise.allSettled(tasks);
}
}
async function invoke(
onError: (kind: EventKind | '*', err: unknown) => void,
kind: EventKind | '*',
fn: () => unknown,
): Promise<void> {
try {
const ret = fn();
if (ret && typeof (ret as Promise<unknown>).then === 'function') {
await ret;
}
} catch (err) {
onError(kind, err);
}
}
+283
View File
@@ -0,0 +1,283 @@
export interface MessageElement {
type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward'
text?: string;
faceId?: number;
targetUin?: number;
uid?: string;
imageUrl?: string;
fileId?: string;
thumbFileId?: string;
fileName?: string;
fileSize?: number;
replySeq?: number;
replyMessageId?: number; // For reply: original message ID (for logging)
replySenderUin?: number; // For reply: original sender's UIN
replyTime?: number; // For reply: original message timestamp
replyRandom?: number; // For reply: original message random/msgId
url?: string;
thumbUrl?: string;
subType?: number;
duration?: number;
width?: number;
height?: number;
summary?: string;
flash?: boolean;
resId?: string;
fileHash?: string;
// Preview-bubble metadata for the `forward` element. Drives the
// `com.tencent.multimsg` LightApp JSON the recipient renders before
// they tap to expand. When unset, the element builder falls back to
// generic defaults so old call sites keep working.
forwardSource?: string;
forwardSummary?: string;
forwardPrompt?: string;
forwardNews?: Array<{ text: string }>;
forwardTSum?: number;
/** `uniseq` baked into the preview's LightApp JSON. For a nested
* forward, the *outer* upload uses this same uuid as the
* `actionCommand` for the piggyback entry carrying the inner
* layer's msgBody — so receivers (Mobile QQ / QQ-NT clients) can
* resolve the inner layer from the outer's single fetch instead of
* hitting the server again. Defaults to a fresh UUID on send when
* omitted (i.e. for non-nested forwards). */
forwardUuid?: string;
// Server-side fingerprints carried from receive side so a forward can do a
// pure md5/sha1 fast-upload without re-downloading the original bytes.
// Set together with `noByteFallback: true` to make the upload modules throw
// instead of falling back to fetch(url).
md5Hex?: string;
sha1Hex?: string;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
noByteFallback?: boolean;
mediaNode?: {
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
};
}
export interface ForwardNodePayload {
userUin: number;
nickname: string;
elements: MessageElement[];
// Optional context preserved when known (download path or upload-via-id),
// so `get_forward_msg` can emit OneBot11-compatible OB11Message objects.
time?: number;
msgId?: number;
msgSeq?: number;
groupId?: number;
senderCard?: string;
messageType?: 'group' | 'private';
// When set, this node's `content` is a nested forward chain. The
// upload pipeline (see `actions/forward.ts::uploadForwardNodes`)
// recursively uploads the inner chain and replaces this node's
// `elements` with an ARK preview element pointing at the inner
// res_id. We also piggyback the inner chain's msgBody onto the
// outer long-msg upload as an extra `actionCommand` slot so the
// NapCat-compatible receiver can walk the whole tree from one
// server fetch without resolving each layer's res_id separately
// (modelled after `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`).
// Caller never sets this on top-level OneBot input — `parseForward
// Nodes` synthesises it when it detects a nested-node array.
innerForward?: ForwardNodePayload[];
}
export interface QQEvent {
time: number;
selfUin: number;
}
export interface FriendMessage extends QQEvent {
kind: 'friend_message';
senderUin: number;
senderNick: string;
msgSeq: number;
msgId: number;
elements: MessageElement[];
}
export interface GroupMessage extends QQEvent {
kind: 'group_message';
groupId: number;
senderUin: number;
senderNick: string;
senderCard: string;
senderRole: string;
msgSeq: number;
msgId: number;
elements: MessageElement[];
}
export interface TempMessage extends QQEvent {
kind: 'temp_message';
senderUin: number;
groupId: number;
senderNick: string;
msgSeq: number;
elements: MessageElement[];
}
export interface GroupMemberJoin extends QQEvent {
kind: 'group_member_join';
groupId: number;
userUin: number;
operatorUin: number;
userUid?: string;
operatorUid?: string;
}
export interface GroupMemberLeave extends QQEvent {
kind: 'group_member_leave';
groupId: number;
userUin: number;
operatorUin: number;
userUid?: string;
operatorUid?: string;
isKick: boolean;
}
export interface GroupMuteEvent extends QQEvent {
kind: 'group_mute';
groupId: number;
userUin: number;
operatorUin: number;
duration: number;
}
export interface GroupAdminEvent extends QQEvent {
kind: 'group_admin';
groupId: number;
userUin: number;
set: boolean;
}
export interface FriendRecall extends QQEvent {
kind: 'friend_recall';
userUin: number;
msgSeq: number;
}
export interface GroupRecallEvent extends QQEvent {
kind: 'group_recall';
groupId: number;
operatorUin: number;
authorUin: number;
msgSeq: number;
}
export interface FriendRequestEvent extends QQEvent {
kind: 'friend_request';
fromUin: number;
fromUid?: string;
message: string;
flag: string;
}
export interface GroupInviteEvent extends QQEvent {
kind: 'group_invite';
groupId: number;
fromUin: number;
fromUid?: string;
subType: string;
message: string;
flag: string;
}
export interface FriendPokeEvent extends QQEvent {
kind: 'friend_poke';
userUin: number;
targetUin: number;
action: string;
suffix: string;
actionImgUrl: string;
}
export interface GroupPokeEvent extends QQEvent {
kind: 'group_poke';
groupId: number;
userUin: number;
targetUin: number;
action: string;
suffix: string;
actionImgUrl: string;
}
export interface GroupEssenceEvent extends QQEvent {
kind: 'group_essence';
groupId: number;
senderUin: number;
operatorUin: number;
msgSeq: number;
random: number;
set: boolean;
}
export interface GroupFileUploadEvent extends QQEvent {
kind: 'group_file_upload';
groupId: number;
userUin: number;
fileId: string;
fileName: string;
fileSize: number;
busId: number;
}
export interface FriendAddEvent extends QQEvent {
kind: 'friend_add';
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
| TempMessage
| GroupMemberJoin
| GroupMemberLeave
| GroupMuteEvent
| GroupAdminEvent
| FriendRecall
| GroupRecallEvent
| FriendRequestEvent
| GroupInviteEvent
| FriendPokeEvent
| GroupPokeEvent
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent
| GroupMsgEmojiLikeEvent;
+209
View File
@@ -0,0 +1,209 @@
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
import type { JsonObject, JsonValue } from '@snowluma/common/json';
/**
* Minimal shape of the OneBot-side `MessageStore` that `formatReply`
* needs — just `findEvent(id)`. Defined inline (instead of importing
* the full `MessageStore` class from @snowluma/onebot) so this
* package doesn't depend on the OneBot layer above it. The OneBot
* `MessageStore` is structurally a superset of this interface, so
* callers pass it through with zero adaptation.
*/
export interface ReplyEventLookup {
findEvent(messageId: number): JsonObject | null;
}
const MAX_TEXT_PREVIEW = 50;
const MAX_REPLY_BODY_PREVIEW = 30;
/** "[群名(12345)]" if known, else "12345" (or "0" if missing). */
export function formatGroup(identity: IdentityService, groupId: number): string {
if (!groupId || groupId <= 0) return String(groupId || 0);
try {
const g = identity.findGroup(groupId);
const name = g?.groupName?.trim();
return name ? `[${name}(${groupId})]` : String(groupId);
} catch {
return String(groupId);
}
}
/**
* "[card-or-nick(uin)]" when the uin is in the group-member or friend
* roster; falls back to the bare uin string. When only a uid is known
* (no uin yet) the uid is returned as-is so the line still references
* someone — better than logging "0".
*/
export function formatUser(
identity: IdentityService,
groupId: number | undefined,
uin: number,
uid?: string,
): string {
try {
if (!uin || uin <= 0) return uid ? uid : '0';
if (groupId !== undefined && groupId > 0) {
const member = identity.findGroupMember(groupId, uin);
const name = member?.card?.trim() || member?.nickname?.trim();
if (name) return `[${name}(${uin})]`;
}
const friend = identity.findFriend(uin);
const fname = friend?.remark?.trim() || friend?.nickname?.trim();
if (fname) return `[${fname}(${uin})]`;
return String(uin);
} catch {
return String(uin);
}
}
/**
* One-line preview of an OneBot-shape message (array of segments or
* raw string). Element rendering matches the existing logReceivedMessage
* vocabulary so this is a drop-in replacement, with a few additions
* (json / xml / markdown / forward / poke / file).
*/
export function formatMessageSegments(message: JsonValue): string {
try {
if (typeof message === 'string') {
return truncate(message, MAX_TEXT_PREVIEW) || '[空消息]';
}
if (!Array.isArray(message)) return '[空消息]';
const parts: string[] = [];
for (const seg of message) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const obj = seg as JsonObject;
const type = String(obj.type ?? '');
const data = (typeof obj.data === 'object' && obj.data !== null && !Array.isArray(obj.data))
? obj.data as Record<string, unknown>
: {};
parts.push(renderSegment(type, data));
}
return parts.join(' ').trim() || '[空消息]';
} catch {
return '[消息渲染异常]';
}
}
function renderSegment(type: string, data: Record<string, unknown>): string {
switch (type) {
case 'text': return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW);
case 'image': return '[图片]';
case 'face': return '[表情]';
case 'mface': return data.text ? `[${String(data.text)}]` : '[表情]';
case 'at': return data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`;
case 'reply': return `[回复:${data.id ?? ''}]`;
case 'record': return '[语音]';
case 'video': return '[视频]';
case 'file': return data.file ? `[文件:${truncate(String(data.file), 20)}]` : '[文件]';
case 'json': return '[JSON]';
case 'xml': return '[XML]';
case 'markdown': return '[Markdown]';
case 'forward': return '[聊天记录]';
case 'poke': return '[戳一戳]';
default: return `[${type}]`;
}
}
function truncate(s: string, max: number): string {
return s.length > max ? `${s.slice(0, max)}...` : s;
}
/**
* Resolve a `reply` segment's referenced message and return a short
* "[回复 user: body...]" string. On miss (older than store retention,
* never seen, lookup throws) falls back to "[回复:<id>]" so the chain
* reference is at least preserved.
*
* Deliberately one level deep — we don't recurse into the reply's own
* reply. Long chains aren't worth the runtime cost in the hot path,
* and a 1-level peek catches 90% of real-world "what's this referring
* to" questions.
*/
export function formatReply(
messageStore: ReplyEventLookup,
identity: IdentityService,
replyId: number,
): string {
try {
if (!replyId) return '[回复:0]';
const event = messageStore.findEvent(replyId);
if (!event) return `[回复:${replyId}]`;
const isGroup = event.message_type === 'group';
const uin = toIntOrZero(event.user_id);
const groupId = isGroup ? toIntOrZero(event.group_id) : undefined;
// Prefer cache; if cache miss, use the sender fields baked into the
// stored event itself (those came from the original receive path
// when the roster was warm).
let userPart = formatUser(identity, groupId, uin);
if (userPart === String(uin) && uin > 0) {
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
? event.sender as JsonObject
: {};
const fallback = ((sender.card as string) || (sender.nickname as string) || '').trim();
if (fallback) userPart = `[${fallback}(${uin})]`;
}
const body = truncate(formatMessageSegments(event.message as JsonValue), MAX_REPLY_BODY_PREVIEW);
return `[回复 ${userPart}: ${body}]`;
} catch {
return `[回复:${replyId}]`;
}
}
function toIntOrZero(v: unknown): number {
if (typeof v === 'number' && Number.isFinite(v)) return v;
if (typeof v === 'string') {
const n = Number.parseInt(v, 10);
return Number.isFinite(n) ? n : 0;
}
return 0;
}
/**
* Readable one-line rendering of a notice-class QQEventVariant. Returns
* null for kinds the OneBot layer's message log already renders
* (group_message / friend_message / temp_message / group_file_upload /
* friend_add — those have richer dedicated paths).
*/
export function formatEvent(identity: IdentityService, event: QQEventVariant): string | null {
try {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
case 'group_file_upload':
case 'friend_add':
return null;
case 'group_recall':
return `群撤回 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.authorUin)} 被 ${formatUser(identity, event.groupId, event.operatorUin)} 撤回`;
case 'friend_recall':
return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`;
case 'group_member_join':
return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`;
case 'group_member_leave':
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`;
case 'group_mute':
return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`;
case 'group_admin':
return `管理 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.set ? '+' : '-'}管理员`;
case 'friend_poke':
return `戳一戳 ${formatUser(identity, undefined, event.userUin)} -> ${formatUser(identity, undefined, event.targetUin)}`;
case 'group_poke':
return `群戳 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} -> ${formatUser(identity, event.groupId, event.targetUin)}`;
case 'friend_request':
return `好友请求 ${formatUser(identity, undefined, event.fromUin)}: ${event.message}`;
case 'group_invite':
return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`;
case 'group_essence':
return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`;
case 'group_msg_emoji_like':
return `表情回应 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.operatorUin, event.operatorUid)} ${event.isAdd ? '+' : '-'}[${event.emojiId}] msgSeq=${event.msgSeq}`;
default:
return null;
}
} catch {
return null;
}
}
@@ -0,0 +1,154 @@
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface FFmpegVideoInfo {
width: number;
height: number;
duration: number;
format: string;
videoCodec: string;
image: Buffer;
}
interface FFmpegNativeAddon {
convertFile(inputFile: string, outputFile: string, format: string): Promise<{ success: boolean }>;
getVideoInfo(filePath: string, format?: 'bmp' | 'bmp24'): Promise<FFmpegVideoInfo>;
getDuration(filePath: string): Promise<number>;
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>;
decodeAudioToFmt(filePath: string, pcmPath: string, format: string): Promise<{ channels: number; sampleRate: number; format: string }>;
}
let cachedAddon: FFmpegNativeAddon | null = null;
let cachedLoadError: string | null = null;
function addonFileName(): string {
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
}
function addonSearchDirs(): string[] {
// Mirrors the hook injector's resolution strategy so the addon is found
// regardless of whether we're running from:
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
// the dist root.
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
// __dirname is `packages/core/src/bridge/highway` — four levels deep
// under `packages/`. Note: the hook injector lives at
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
return [
path.resolve(__dirname, 'native', 'ffmpeg'),
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
];
}
function resolveAddonPath(): string | null {
const fileName = addonFileName();
for (const dir of addonSearchDirs()) {
const full = path.join(dir, fileName);
if (fs.existsSync(full)) return full;
}
return null;
}
/**
* Load the ffmpegAddon once and return a cached instance.
* Throws on first-use failure; subsequent calls replay the same error message
* so callers don't silently fall back.
*/
export function getFFmpegAddon(): FFmpegNativeAddon {
if (cachedAddon) return cachedAddon;
if (cachedLoadError) throw new Error(cachedLoadError);
const addonPath = resolveAddonPath();
if (!addonPath) {
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
throw new Error(cachedLoadError);
}
try {
const mod = { exports: {} as Record<string, unknown> };
process.dlopen(mod, addonPath);
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
return cachedAddon;
} catch (error) {
cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${error instanceof Error ? error.message : String(error)}`;
throw new Error(cachedLoadError);
}
}
/**
* Check whether `filePath` is already an NT SILK container. The addon can
* read any input directly so the only reason we peek at the header is to
* skip the conversion (and the temp file) when the caller already fed us
* a ready-to-upload silk file.
*/
export function isSilkFile(filePath: string): boolean {
try {
const fd = fs.openSync(filePath, 'r');
try {
const buf = Buffer.alloc(10);
fs.readSync(fd, buf, 0, 10, 0);
const header = buf.toString();
return header.includes('#!SILK') || header.includes('\x02#!SILK');
} finally {
fs.closeSync(fd);
}
} catch {
return false;
}
}
export interface EncodeSilkResult {
/** Absolute path to the silk file ready for highway upload. */
path: string;
/** Voice duration in whole seconds (>= 1). */
duration: number;
/** `true` if we wrote a new silk file and the caller should unlink it. */
converted: boolean;
}
/**
* Convert `inputFile` to NT SILK when necessary and return the output path
* + duration. The caller is responsible for unlinking the returned path
* when `converted === true`.
*/
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
const addon = getFFmpegAddon();
// Already silk — trust the file, just measure duration via the addon.
if (isSilkFile(inputFile)) {
let duration = 1;
try {
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
} catch {
// getDuration on a silk file occasionally fails on certain encodings;
// the upload path only needs a rough, non-zero value, so fall back
// to the size-based heuristic used by NapCat's audio.ts.
const stat = fs.statSync(inputFile);
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
}
return { path: inputFile, duration, converted: false };
}
fs.mkdirSync(tempDir, { recursive: true });
const outPath = path.join(tempDir, crypto.randomUUID());
await addon.convertToNTSilkTct(inputFile, outPath);
if (!fs.existsSync(outPath)) {
throw new Error('convertToNTSilkTct produced no output file');
}
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
return { path: outPath, duration, converted: true };
}
/** Default location for temporary silk files. */
export function defaultPttTempDir(): string {
return path.join(os.tmpdir(), 'snowluma-ptt');
}
@@ -0,0 +1,263 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import net from 'net';
import type { BridgeContext } from '../bridge-context';
import type {
HttpConn0x6FF501Request,
HttpConn0x6FF501Response,
NTV2RichMediaHighwayExt,
ReqDataHighwayHead,
RespDataHighwayHead,
} from '@snowluma/proto-defs/highway';
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
export const PRIVATE_IMAGE_CMD_ID = 1003;
export const GROUP_IMAGE_CMD_ID = 1004;
export interface HighwaySession {
sigSession: Uint8Array;
sessionKey: Uint8Array;
host: string;
port: number;
}
function ipv4ToString(value: number): string {
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
}
export async function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
const request = protobuf_encode<HttpConn0x6FF501Request>({
httpConn: {
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
serviceTypes: [1, 5, 10, 21],
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
},
});
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'HttpConn request failed');
}
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
throw new Error('HttpConn response missing sig_session');
}
const session: HighwaySession = {
sigSession: resp.httpConn.sigSession as Uint8Array,
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
host: 'htdata3.qq.com',
port: 80,
};
for (const si of resp.httpConn.serverInfos ?? []) {
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
for (const addr of si.serverAddrs) {
const ip = addr.ip ?? 0;
const port = addr.port ?? 0;
if (ip && port) {
session.host = ipv4ToString(ip);
session.port = port;
}
}
}
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
return session;
}
function makeHighwayHead(
uin: string, commandId: number, fileSize: number, offset: number, length: number,
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
): Uint8Array {
return protobuf_encode<ReqDataHighwayHead>({
msgBaseHead: {
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
},
msgSegHead: {
serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length,
retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0,
},
bytesReqExtendInfo: extend,
timestamp: 0n,
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
});
}
export function buildHighwayExtend(
uKey: string,
msgInfo: any,
ipv4s: any[],
sha1: Uint8Array | Uint8Array[],
fileIndex = 0,
): Uint8Array {
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0];
const networkIpv4s: any[] = [];
for (const ipv4 of ipv4s ?? []) {
const ip = ipv4.outIp ?? 0;
const port = ipv4.outPort ?? 0;
if (ip && port) {
networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port });
}
}
return protobuf_encode<NTV2RichMediaHighwayExt>({
fileUuid: selected?.index?.fileUuid ?? '',
uKey,
network: { ipv4s: networkIpv4s },
msgInfoBody: msgInfoBody.map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
})),
blockSize: HIGHWAY_BLOCK_SIZE,
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
});
}
// --- TCP-based HTTP highway upload ---
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
return new Promise((resolve, reject) => {
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.once('timeout', onTimeout);
socket.once('error', onError);
});
}
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
return new Promise((resolve, reject) => {
socket.write(data, (err) => err ? reject(err) : resolve());
});
}
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let headerEnd = -1;
let contentLength = 0;
let totalNeeded = 0;
let settled = false;
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');
if (idx >= 0) {
headerEnd = idx + 4;
const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase();
const clMatch = headerStr.match(/content-length:\s*(\d+)/);
contentLength = clMatch ? parseInt(clMatch[1], 10) : 0;
totalNeeded = headerEnd + contentLength;
}
}
if (headerEnd >= 0 && buf.length >= totalNeeded) {
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
}
};
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);
});
}
async function httpPostFrame(
socket: net.Socket, host: string, path: string, body: Uint8Array,
): Promise<Uint8Array> {
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
await socketWrite(socket, Buffer.from(header, 'ascii'));
if (body.length > 0) await socketWrite(socket, body);
return readHttpResponseBody(socket);
}
export async function uploadHighwayHttp(
bridge: BridgeContext, session: HighwaySession, commandId: number,
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
const socket = await tcpConnect(session.host, session.port);
try {
let offset = 0;
while (offset < bytes.length) {
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
const chunk = bytes.subarray(offset, offset + chunkSize);
const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead(
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend,
);
const frame = packHighwayFrame(head, chunk);
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
if (resp?.errorCode && resp.errorCode !== 0) {
// Surface every diagnostic the highway response carries so
// user reports of `error_code=921` and friends include the
// server-side context (segHead.retCode, chunk size, file md5)
// — without these we can't tell apart a malformed-payload
// reject, a session-ticket mismatch, or a per-account rate-
// limit.
const segRetCode = resp.msgSegHead?.retCode ?? 0;
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
throw new Error(
`highway upload error_code=${resp.errorCode}` +
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
` offset=${offset} segRetCode=${segRetCode}` +
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
);
}
offset += chunkSize;
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
}
} finally {
socket.destroy();
}
}
@@ -0,0 +1,178 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import type { MessageElement } from '../events';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
const moduleLog = createLogger('Highway.Image');
function loggerFor(bridge: BridgeContext) {
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;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
fileName: string;
fileSize: number;
summary: string;
subType: number;
width: number;
height: number;
picFormat: number;
/** True when `bytes` is empty; runNtv2Upload throws fastOnlyError if
* the server demands the bytes anyway. */
fastOnly: boolean;
}
function imageDataFromFingerprint(element: MessageElement): ImageData {
return {
bytes: new Uint8Array(0),
md5: hexToBytes(element.md5Hex ?? ''),
sha1: hexToBytes(element.sha1Hex ?? ''),
md5Hex: element.md5Hex ?? '',
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'image'}.jpg`,
fileSize: element.fileSize ?? 0,
// QQ ecosystem convention — mobile QQ + Lagrange.Core + NapCat all
// surface these exact Chinese strings as the chat-list bubble
// preview text. English fallbacks would render `[image]` /
// `[sticker]` in QQ users' chat lists instead of the expected
// `[图片]` / `[动画表情]`. Cross-checked against:
// dev/NapCatQQ/.../packet/message/element.ts:367-371
// dev/Lagrange.Core/.../Message/Entity/ImageEntity.cs:186-192
summary: element.summary || (element.subType === 1 ? '[动画表情]' : '[图片]'),
subType: element.subType ?? 0,
width: element.width ?? 0,
height: element.height ?? 0,
picFormat: element.picFormat ?? 1000,
fastOnly: true,
};
}
function loadImage(element: MessageElement): Promise<ImageData> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
return Promise.reject(new Error('image fast-upload requires md5Hex + sha1Hex'));
}
return Promise.resolve(imageDataFromFingerprint(element));
}
return loadImageFromSource(
element.url || element.fileId || '',
element.fileName ?? '',
element.subType ?? 0,
element.summary ?? '',
);
}
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
const loaded = await loadBinarySource(source, 'image');
const hashes = computeHashes(loaded.bytes);
const fmt = detectImageFormat(loaded.bytes);
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
const ext = extMap[fmt.format] ?? '.jpg';
let finalName = fileName || loaded.fileName;
if (!finalName) finalName = hashes.md5Hex + ext;
return {
bytes: loaded.bytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: finalName,
fileSize: loaded.bytes.length,
summary: summary || (subType === 1 ? '[动画表情]' : '[图片]'),
subType,
width: fmt.width,
height: fmt.height,
picFormat: fmt.format,
fastOnly: false,
};
}
/**
* Upload an image and return the encoded MsgInfo bytes for the outgoing
* commonElem.
*/
export async function uploadImageMsgInfo(
bridge: BridgeContext,
isGroup: boolean,
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',
cmdId: isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID,
bytes: image.bytes,
md5: image.md5,
sha1: image.sha1,
fastOnlyError: 'image fast-upload not available (server requires bytes)',
}];
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
requestId: 1,
businessType: 1,
uploadInfo: [{
fileInfo: {
fileSize: image.fileSize,
fileHash: image.md5Hex,
fileSha1: image.sha1Hex,
fileName: image.fileName,
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
width: image.width,
height: image.height,
time: 0,
original: 1,
},
subFileType: 0,
}],
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
pic: {
bizType: image.subType,
textSummary: image.summary,
...(isGroup
? { reserveTroop: { subType: image.subType } }
: { reserveC2c: { subType: image.subType } }),
},
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array(0),
bytesPbReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
uploads,
label: 'image',
});
return finalizeMediaMsgInfo(upload, { bizType: image.subType, textSummary: image.summary });
}
+247
View File
@@ -0,0 +1,247 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import crypto from 'crypto';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import { makeOidbEnvelope } from '../bridge-oidb';
import type {
EncodableMediaMsgInfo,
NTV2UploadRichMediaReq,
NTV2UploadRichMediaResp,
} from '@snowluma/proto-defs/highway';
import { OidbBase } from '@snowluma/proto-defs/oidb';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
const moduleLog = createLogger('Highway');
// ─────────────── public types ───────────────
/**
* Highway upload spec for one sub-file of an NTV2 upload response.
* The server returns 0..N sub-files; for each we either fast-path (skip)
* or do an HTTP PUT.
*/
export interface MediaSubFileUpload {
/**
* Where to read uKey + ipv4s from on the OIDB response:
* 'top' -> `upload.uKey` + `upload.ipv4s` (main file)
* N (int) -> `upload.subFileInfos[N].uKey` + `.ipv4s` (sub-file)
*
* Image and PTT use 'top' only. Video uses 'top' (main) and 0 (thumb).
*/
source: 'top' | number;
/** Highway command id for this sub-file. */
cmdId: number;
/** Bytes to upload. Empty when the caller is forwarding from cached
* fingerprints; in that case set fastOnlyError so we throw with a
* typed message when the server actually demands the bytes. */
bytes: Uint8Array;
/** md5 used for the highway request. */
md5: Uint8Array;
/** sha1 — single buffer or per-1MB block array. Passed verbatim to
* buildHighwayExtend. */
sha1: Uint8Array | Uint8Array[];
/** subFileIndex argument for buildHighwayExtend. Defaults to 0;
* video thumb passes 1. */
subFileIndex?: number;
/** Error message to throw when uKey is present but `bytes.length === 0`.
* Omit if the caller guarantees bytes always exist (e.g. video thumb
* always has FALLBACK_THUMB bytes). */
fastOnlyError?: string;
}
export interface NtV2UploadParams {
bridge: BridgeContext;
isGroup: boolean;
/** Group uin when isGroup, otherwise the recipient's uid string. */
targetIdOrUid: string | number;
/** OIDB command id (e.g. 0x11C4 / 0x11C5 / 0x126E / 0x126D / 0x11EA / 0x11E9). */
oidbCmd: number;
/** Service cmd (e.g. 'OidbSvcTrpcTcp.0x11c4_100'). */
serviceCmd: string;
/** `reqHead.common.requestId`. NTV2 sub-protocols use different values
* here (image=1, video=3, ptt = group:1 / c2c:4). */
requestId: number;
/** `reqHead.scene.businessType` (1=image, 3=voice, 2=video). */
businessType: number;
/** `upload.uploadInfo` array. Each entry is `{ fileInfo, subFileType }`. */
uploadInfo: unknown[];
/** `upload.compatQmsgSceneType`. */
compatQmsgSceneType: number;
/** `upload.extBizInfo` — type-specific bytes/flags. */
extBizInfo: unknown;
/** Sub-file Highway PUTs to perform after the OIDB response. */
uploads: MediaSubFileUpload[];
/** Used in error messages. Defaults to 'media'. */
label?: string;
}
// ─────────────── helpers ───────────────
/**
* 8 random bytes masked into the positive int64 range so the resulting
* BigInt survives signed-int64 protobuf encoding without surprises.
* Mirrors NapCat.
*/
export function makeClientRandomId(): bigint {
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
}
/** Hex string -> Uint8Array. Used by every format's fingerprint path. */
export function hexToBytes(hex: string): Uint8Array {
const clean = hex.length % 2 === 0 ? hex : '0' + hex;
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);
}
return out;
}
// ─────────────── main entrypoint ───────────────
/**
* Send a NTV2UploadRichMediaReq and run any Highway PUTs the server asks
* for. Returns the decoded `upload` object so the caller can pass it to
* `finalizeMediaMsgInfo`.
*
* Sessions are cached across sub-file uploads — video does two PUTs but
* only fetches the Highway session once.
*/
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.
const body: any = {
reqHead: {
common: { requestId: params.requestId, command: 100 },
scene: {
requestType: 2,
businessType: params.businessType,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
uploadInfo: params.uploadInfo,
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody: any = resp.body;
if (!uploadBody) throw new Error(`${label} upload response body missing`);
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
}
const upload = uploadBody.upload;
if (!upload) throw new Error(`${label} upload response body missing`);
// Highway PUTs. Session is lazily fetched and cached — video does two
// PUTs (main + thumb) and shouldn't pay for two sessions.
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
session ??= await fetchHighwaySession(bridge);
return session;
};
let didPut = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
// Either the server fast-pathed this sub-file (no uKey) or msgInfo is
// missing entirely; either way nothing to push.
if (!uKey || !upload.msgInfo) continue;
if (sub.bytes.length === 0) {
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
continue;
}
const extend = buildHighwayExtend(
uKey,
upload.msgInfo,
target.ipv4s ?? [],
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;
}
// ─────────────── shared finalize ───────────────
/**
* Build the encoded MsgInfo bytes that go inside the outgoing commonElem.
*
* `defaultPic` is the image-only fall-back: image uploads inject
* `bizType` + `textSummary` defaults when the server response omits the
* `pic` ext-biz-info. PTT and video pass `undefined` here — they leave
* pic alone unless the server populates it.
*/
export function finalizeMediaMsgInfo(
upload: any,
defaultPic?: { bizType: number; textSummary: string },
): Uint8Array {
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) {
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
if (defaultPic) {
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? defaultPic.bizType;
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? defaultPic.textSummary;
}
} else if (defaultPic) {
extBizInfo.pic = { bizType: defaultPic.bizType, textSummary: defaultPic.textSummary };
}
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
}
+210
View File
@@ -0,0 +1,210 @@
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import type { MessageElement } from '../events';
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
const moduleLog = createLogger('Highway.Ptt');
function loggerFor(bridge: BridgeContext) {
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;
interface PttPayload {
/** Silk bytes uploaded to Highway. Empty when forwarding from cached fingerprints. */
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
fileName: string;
fileSize: number;
/** Whole seconds, >= 1. */
duration: number;
voiceFormat: number;
/** True when bytes is empty; pipeline throws fastOnlyError if the
* server demands the bytes anyway. */
fastOnly: boolean;
/** Cleanup hooks for any temp silk files staged during loadPtt. */
cleanups: Array<() => void>;
}
function pttPayloadFromFingerprint(element: MessageElement): PttPayload {
return {
bytes: new Uint8Array(0),
md5: hexToBytes(element.md5Hex ?? ''),
sha1: hexToBytes(element.sha1Hex ?? ''),
md5Hex: element.md5Hex ?? '',
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'record'}.amr`,
fileSize: element.fileSize ?? 0,
duration: element.duration ?? 1,
// Voice format: 1 = silk (NTV2 standard). Honour any fingerprint that
// declares a different format; legacy NTQQ paths all use 1.
voiceFormat: element.voiceFormat || 1,
fastOnly: true,
cleanups: [],
};
}
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
throw new Error('record fast-upload requires md5Hex + sha1Hex');
}
return pttPayloadFromFingerprint(element);
}
const source = element.url || element.fileId || '';
if (!source) throw new Error('record source is empty');
const cleanups: Array<() => void> = [];
// Run all queued cleanups; called both on the success path (via the
// returned `cleanups` array) and on the failure path (try/catch below).
const runCleanups = () => {
while (cleanups.length > 0) {
const fn = cleanups.pop();
if (!fn) continue;
try { fn(); } catch { /* best-effort */ }
}
};
fs.mkdirSync(tempDir, { recursive: true });
try {
// 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 = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
inputPath = local;
} else {
const loaded = await loadBinarySource(source, 'record');
inputPath = path.join(tempDir, `snowluma-ptt-in-${crypto.randomUUID()}`);
fs.writeFileSync(inputPath, Buffer.from(loaded.bytes));
cleanups.push(() => { try { fs.unlinkSync(inputPath); } catch { /* ignore */ } });
}
const silk = await encodeSilk(inputPath, tempDir);
if (silk.converted) {
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
}
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
const hashes = computeHashes(silkBytes);
return {
bytes: silkBytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: `${hashes.md5Hex}.amr`,
fileSize: silkBytes.length,
duration: silk.duration,
voiceFormat: 1,
fastOnly: false,
cleanups: [...cleanups],
};
} catch (err) {
runCleanups();
throw err;
}
}
/**
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
* a `commonElem { serviceType: 48, businessType: 22 }`.
*/
export async function uploadPttMsgInfo(
bridge: BridgeContext,
isGroup: boolean,
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',
cmdId: isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID,
bytes: ptt.bytes,
md5: ptt.md5,
sha1: ptt.sha1,
fastOnlyError: 'record fast-upload not available (server requires bytes)',
}];
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
oidbCmd: isGroup ? 0x126E : 0x126D,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100',
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
requestId: isGroup ? 1 : 4,
businessType: 3,
uploadInfo: [{
fileInfo: {
fileSize: ptt.fileSize,
fileHash: ptt.md5Hex,
fileSha1: ptt.sha1Hex,
fileName: ptt.fileName,
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: ptt.voiceFormat },
width: 0,
height: 0,
time: ptt.duration,
original: 0,
},
subFileType: 0,
}],
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
// NapCat fills in a placeholder textSummary so the legacy compat
// QMsg path still has something to render. Mirror it.
pic: { textSummary: 'Nya~' },
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array([0x08, 0x00, 0x38, 0x00]),
bytesPbReserve: new Uint8Array(0),
// `bytesGeneralFlags` differs between group / c2c voice. Lifted
// verbatim from NapCat (UploadGroupPtt.ts / UploadPrivatePtt.ts).
bytesGeneralFlags: isGroup
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
},
},
uploads,
label: 'ptt',
});
return finalizeMediaMsgInfo(upload);
} finally {
for (const fn of ptt.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
}
}
}
+290
View File
@@ -0,0 +1,290 @@
import { createHash } from 'crypto';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
export interface LoadedBinary {
bytes: Uint8Array;
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;
md5Hex: string;
sha1Hex: string;
}
export interface ImageFormat {
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
width: number;
height: number;
}
// --- 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,
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
): Promise<LoadedBinary> {
if (!source) throw new Error(`${resourceName} source is empty`);
if (/^base64:\/\//i.test(source)) {
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, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
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 };
}
function guessFileNameFromUrl(url: string): string {
const queryPos = url.search(/[?#]/);
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
const lastSlash = pathPart.lastIndexOf('/');
return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
}
// --- Hashing ---
export function computeHashes(data: Uint8Array): ImageHashes {
const md5 = createHash('md5').update(data).digest();
const sha1 = createHash('sha1').update(data).digest();
return {
md5: new Uint8Array(md5),
sha1: new Uint8Array(sha1),
md5Hex: md5.toString('hex'),
sha1Hex: sha1.toString('hex'),
};
}
export function computeMd5(data: Uint8Array): Uint8Array {
return new Uint8Array(createHash('md5').update(data).digest());
}
// --- Image format detection (port of C++ detect_image_format) ---
function readBE16(data: Uint8Array, offset: number): number {
return (data[offset] << 8) | data[offset + 1];
}
function readBE32(data: Uint8Array, offset: number): number {
return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
}
function readLE16(data: Uint8Array, offset: number): number {
return data[offset] | (data[offset + 1] << 8);
}
function readLE32(data: Uint8Array, offset: number): number {
return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
}
function readBE24(data: Uint8Array, offset: number): number {
return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
}
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
let width = 0;
let height = 0;
// PNG
if (bytes.length >= 24 &&
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
width = readBE32(bytes, 16);
height = readBE32(bytes, 20);
return { format: 1001, width, height };
}
// GIF
if (bytes.length >= 10 &&
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
width = readLE16(bytes, 6);
height = readLE16(bytes, 8);
return { format: 2000, width, height };
}
// BMP
if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) {
width = readLE32(bytes, 18);
height = readLE32(bytes, 22);
return { format: 1005, width, height };
}
// WebP
if (bytes.length >= 30 &&
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
width = readLE16(bytes, 26);
height = readLE16(bytes, 28);
return { format: 1002, width, height };
}
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) {
const bits = readLE32(bytes, 21);
width = (bits & 0x3FFF) + 1;
height = ((bits >> 14) & 0x3FFF) + 1;
return { format: 1002, width, height };
}
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) {
width = readBE24(bytes, 24) + 1;
height = readBE24(bytes, 27) + 1;
return { format: 1002, width, height };
}
}
// JPEG
if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) {
let offset = 2;
while (offset + 9 <= bytes.length) {
if (bytes[offset] !== 0xFF) { offset++; continue; }
const marker = bytes[offset + 1];
if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; }
if (offset + 4 > bytes.length) break;
const segLen = readBE16(bytes, offset + 2);
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
// 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 };
}
offset += 2 + segLen;
}
return { format: 1000, width: 0, height: 0 };
}
return { format: 1000, width: 0, height: 0 };
}
// --- Highway frame packing/unpacking ---
export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array {
const frame = new Uint8Array(9 + head.length + body.length + 1);
frame[0] = 0x28;
const dv = new DataView(frame.buffer, frame.byteOffset);
dv.setUint32(1, head.length, false);
dv.setUint32(5, body.length, false);
frame.set(head, 9);
frame.set(body, 9 + head.length);
frame[frame.length - 1] = 0x29;
return frame;
}
export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } {
if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) {
throw new Error('invalid highway response frame');
}
const dv = new DataView(frame.buffer, frame.byteOffset);
const headLen = dv.getUint32(1, false);
const bodyLen = dv.getUint32(5, false);
return {
head: frame.subarray(9, 9 + headLen),
body: frame.subarray(9 + headLen, 9 + headLen + bodyLen),
};
}
@@ -0,0 +1,541 @@
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import type { MessageElement } from '../events';
import { getFFmpegAddon } from './ffmpeg-addon';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import {
computeHashes,
detectImageFormat,
loadBinarySource,
resolveLocalFilePath,
} from './utils';
const moduleLog = createLogger('Highway.Video');
function loggerFor(bridge: BridgeContext) {
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;
export const GROUP_VIDEO_CMD_ID = 1005;
export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
const FALLBACK_THUMB = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
'base64',
);
interface VideoPayload {
/** Video bytes. Empty when forwarding from cached fingerprints. */
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
sha1Blocks: Uint8Array[];
md5Hex: string;
sha1Hex: string;
fileName: string;
filePath: string;
fileSize: number;
width: number;
height: number;
duration: number;
videoFormat: number;
thumb: ThumbPayload;
/** When true, video bytes are empty; pipeline throws fastOnlyError
* for the main file if the server demands the bytes. The thumb is
* always present (FALLBACK_THUMB at worst) so its sub-file uploads
* normally regardless. */
fastOnly: boolean;
cleanups: Array<() => void>;
}
function makeFallbackThumb(): ThumbPayload {
const bytes = new Uint8Array(FALLBACK_THUMB);
const hashes = computeHashes(bytes);
return {
bytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
width: 1,
height: 1,
};
}
function videoPayloadFromFingerprint(element: MessageElement): VideoPayload {
return {
bytes: new Uint8Array(0),
md5: hexToBytes(element.md5Hex ?? ''),
sha1: hexToBytes(element.sha1Hex ?? ''),
sha1Blocks: [],
md5Hex: element.md5Hex ?? '',
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'video'}.mp4`,
filePath: '',
fileSize: element.fileSize ?? 0,
width: element.width ?? 0,
height: element.height ?? 0,
duration: element.duration ?? 1,
videoFormat: element.videoFormat ?? 0,
thumb: makeFallbackThumb(),
fastOnly: true,
cleanups: [],
};
}
interface ThumbPayload {
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
width: number;
height: number;
}
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
// Highway expects sha1 computed over each 1 MB block of the file, plus
// the final overall sha1. This is a streaming implementation that doesn't
// reuse Node's crypto because Node only exposes the final digest.
class Sha1StreamState {
readonly blockSize = 64;
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
private readonly state = new Uint32Array(5);
private readonly count = new Uint32Array(2);
private readonly buffer = Buffer.allocUnsafe(this.blockSize);
private readonly w = new Uint32Array(80);
constructor() {
this.reset();
}
private reset(): void {
this.state[0] = 0x67452301;
this.state[1] = 0xEFCDAB89;
this.state[2] = 0x98BADCFE;
this.state[3] = 0x10325476;
this.state[4] = 0xC3D2E1F0;
this.count[0] = 0;
this.count[1] = 0;
this.buffer.fill(0);
}
private rotateLeft(value: number, offset: number): number {
return ((value << offset) | (value >>> (32 - offset))) >>> 0;
}
private transform(chunk: Uint8Array, offset: number): void {
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize);
for (let i = 0; i < 16; i++) {
this.w[i] = view.getUint32(i * 4, false);
}
for (let i = 16; i < 80; i++) {
this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1);
}
let a = this.state[0];
let b = this.state[1];
let c = this.state[2];
let d = this.state[3];
let e = this.state[4];
for (let i = 0; i < 80; i++) {
let temp: number;
if (i < 20) {
temp = ((b & c) | (~b & d)) + 0x5A827999;
} else if (i < 40) {
temp = (b ^ c ^ d) + 0x6ED9EBA1;
} else if (i < 60) {
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
} else {
temp = (b ^ c ^ d) + 0xCA62C1D6;
}
temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0;
e = d;
d = c;
c = this.rotateLeft(b, 30);
b = a;
a = temp >>> 0;
}
this.state[0] = (this.state[0] + a) >>> 0;
this.state[1] = (this.state[1] + b) >>> 0;
this.state[2] = (this.state[2] + c) >>> 0;
this.state[3] = (this.state[3] + d) >>> 0;
this.state[4] = (this.state[4] + e) >>> 0;
}
update(data: Uint8Array): void {
let index = (this.count[0] >>> 3) & 0x3F;
const dataLen = data.length;
this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0;
if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0;
const partLen = this.blockSize - index;
let i = 0;
if (dataLen >= partLen) {
this.buffer.set(data.subarray(0, partLen), index);
this.transform(this.buffer, 0);
for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) {
this.transform(data, i);
}
index = 0;
}
if (i < dataLen) {
this.buffer.set(data.subarray(i, dataLen), index);
}
}
hash(bigEndian = true): Uint8Array {
const digest = Buffer.allocUnsafe(20);
for (let i = 0; i < 5; i++) {
if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4);
else digest.writeUInt32LE(this.state[i], i * 4);
}
return new Uint8Array(digest);
}
final(): Uint8Array {
const bits = Buffer.allocUnsafe(8);
bits.writeUInt32BE(this.count[1], 0);
bits.writeUInt32BE(this.count[0], 4);
const index = (this.count[0] >>> 3) & 0x3F;
const padLen = index < 56 ? 56 - index : 120 - index;
this.update(this.padding.subarray(0, padLen));
this.update(bits);
return this.hash(true);
}
}
function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
const sha1 = new Sha1StreamState();
const blocks: Uint8Array[] = [];
let bytesRead = 0;
let offset = 0;
while (offset + sha1.blockSize <= bytes.length) {
const block = bytes.subarray(offset, offset + sha1.blockSize);
sha1.update(block);
offset += sha1.blockSize;
bytesRead += sha1.blockSize;
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
blocks.push(sha1.hash(false));
}
}
if (offset < bytes.length) sha1.update(bytes.subarray(offset));
blocks.push(sha1.final());
return blocks;
}
// ─────────────── source staging + thumb extraction ───────────────
function defaultVideoTempDir(): string {
return path.join(os.tmpdir(), 'snowluma-video');
}
function sourceExtension(fileName: string, source: string): string {
const fromName = path.extname(fileName);
if (fromName) return fromName;
const local = resolveLocalFilePath(source);
const fromSource = local ? path.extname(local) : '';
return fromSource || '.mp4';
}
async function stageVideoSource(element: MessageElement, tempDir: string, cleanups: Array<() => void>): Promise<{
bytes: Uint8Array;
filePath: string;
fileName: string;
}> {
const source = element.url || element.fileId || '';
if (!source) throw new Error('video source is empty');
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,
fileName: element.fileName || path.basename(local),
};
}
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));
cleanups.push(() => { try { fs.unlinkSync(stagedPath); } catch { /* ignore */ } });
return {
bytes: loaded.bytes,
filePath: stagedPath,
fileName,
};
}
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
thumb: ThumbPayload;
width: number;
height: number;
duration: number;
}> {
let width = element.width ?? 0;
let height = element.height ?? 0;
let duration = element.duration ?? 0;
let thumbBytes: Uint8Array | null = null;
if (element.thumbUrl) {
try {
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
} catch (err) {
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
}
}
if (!thumbBytes) {
try {
const info = await getFFmpegAddon().getVideoInfo(videoPath);
width = width || info.width || 0;
height = height || info.height || 0;
duration = duration || Math.max(1, Math.round(info.duration || 0));
if (info.image && info.image.length > 0) {
thumbBytes = new Uint8Array(info.image);
}
} catch (err) {
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
}
}
if (!thumbBytes) {
thumbBytes = new Uint8Array(FALLBACK_THUMB);
}
const fmt = detectImageFormat(thumbBytes);
width = width || fmt.width || 1;
height = height || fmt.height || 1;
duration = duration || 1;
const hashes = computeHashes(thumbBytes);
return {
width,
height,
duration,
thumb: {
bytes: thumbBytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
width,
height,
},
};
}
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
throw new Error('video fast-upload requires md5Hex + sha1Hex');
}
return videoPayloadFromFingerprint(element);
}
const tempDir = defaultVideoTempDir();
const cleanups: Array<() => void> = [];
fs.mkdirSync(tempDir, { recursive: true });
try {
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. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
}
const hashes = computeHashes(staged.bytes);
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
return {
bytes: staged.bytes,
md5: hashes.md5,
sha1: hashes.sha1,
sha1Blocks: computeVideoSha1Blocks(staged.bytes),
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: staged.fileName || `${hashes.md5Hex}.mp4`,
filePath: staged.filePath,
fileSize: staged.bytes.length,
width,
height,
duration,
videoFormat: 0,
thumb,
fastOnly: false,
cleanups: [...cleanups],
};
} catch (err) {
for (const fn of cleanups.reverse()) {
try { fn(); } catch { /* best-effort cleanup */ }
}
throw err;
}
}
// ─────────────── exported entry ───────────────
/**
* Upload a video and return the encoded MsgInfo bytes that go inside a
* `commonElem { serviceType: 48, businessType: 21 }`.
*
* Two highway PUTs run when the server doesn't fast-path: the main video
* (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`).
*/
export async function uploadVideoMsgInfo(
bridge: BridgeContext,
isGroup: boolean,
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[] = [
{
source: 'top',
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
bytes: video.bytes,
md5: video.md5,
sha1: video.sha1Blocks,
subFileIndex: 0,
fastOnlyError: 'video fast-upload not available (server requires bytes)',
},
{
source: 0, // upload.subFileInfos[0]
cmdId: isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID,
bytes: video.thumb.bytes,
md5: video.thumb.md5,
sha1: video.thumb.sha1,
subFileIndex: 1,
// No fastOnlyError: thumb always has bytes (FALLBACK_THUMB at worst).
},
];
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
oidbCmd: isGroup ? 0x11EA : 0x11E9,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100',
requestId: 3,
businessType: 2,
uploadInfo: [
{
fileInfo: {
fileSize: video.fileSize,
fileHash: video.md5Hex,
fileSha1: video.sha1Hex,
fileName: 'nya.mp4',
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
// Width/height kept at 0 — NapCat does the same and the QQ-NT
// server has been observed to reject non-zero dimensions
// here on c2c sends with a schema-mismatch error. acidify
// *does* fill them (`payload.videoWidth/Height`) but we
// leave that alone until c2c regression coverage exists.
height: 0,
width: 0,
// `time` MUST be the real duration in seconds, otherwise
// every receiving client renders "00:00" on the video.
// NapCat ships `time: 0` because it sits on top of QQ-NT's
// IPC layer, which the desktop client patches up before
// the wire message goes out. We're a protocol-direct
// client (same position as acidify), so we own this field.
// acidify writes `payload.videoDuration` here for the same
// reason — verified against `RichMediaUpload.kt::
// buildVideoUploadInfoList` (2026-04 refactor).
time: video.duration,
original: 0,
},
subFileType: 0,
},
{
fileInfo: {
fileSize: video.thumb.bytes.length,
fileHash: video.thumb.md5Hex,
fileSha1: video.thumb.sha1Hex,
fileName: 'nya.jpg',
type: { type: 1, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
height: video.thumb.height,
width: video.thumb.width,
time: 0,
original: 0,
},
subFileType: 100,
},
],
// 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]) },
ptt: {
bytesPbReserve: new Uint8Array(0),
bytesReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
uploads,
label: 'video',
});
log.debug('video upload completed: md5=%s scene=%s', video.md5Hex, isGroup ? 'group' : 'c2c');
return finalizeMediaMsgInfo(upload);
} finally {
for (const fn of video.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
}
}
}
+926
View File
@@ -0,0 +1,926 @@
import fs from 'fs';
import path from 'path';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger, type Logger } from '@snowluma/common/logger';
const moduleLogger = createLogger('Identity');
/**
* Hooks Identity uses when its read methods miss every cache layer. Wired in
* after construction (Bridge owns these methods, but Bridge can't exist
* before Identity does). Each call is expected to invoke the matching
* remember* observation on this service as a side effect.
*/
export interface IdentityFetcher {
fetchProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupMemberList?(groupId: number): Promise<unknown>;
}
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;
}
/**
* Authoritative store for everything we know about QQ actors observed
* during this session: the bot's own identity, friends, groups, group
* members, user profiles, plus the bidirectional UID↔UIN index that
* powers all OIDB-bound translation.
*
* Two layers internally:
* - In-memory state (this file) — O(1) for find* on the hot path.
* - SQLite (optional, opened by openForUin) — survives restarts.
*
* Both layers are kept in sync by the remember* / refresh paths.
* Callers should never reach below the public surface; the cascade and
* storage details are intentionally hidden.
*/
export class IdentityService {
// ─── Self identity ───
private readonly uin_: string;
private nickname_ = '';
private selfProfile_: UserProfileInfo | null = null;
// ─── In-memory domain state ───
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private readonly groups_ = new Map<number, QQGroupInfo>();
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
private readonly uinByUid = new Map<string, number>();
private readonly uidByUin = new Map<number, string>();
// ─── Persistence + fetcher ───
private readonly db: DatabaseType | null;
// Prepared-statement cache. Every `.prepare(sql)` call in this
// service re-parses the SQL — that's the SQLite anti-pattern
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
// call sites stay readable (no need to enumerate 20+ named fields
// upfront); the Map lookup is O(1) hash + string-eq, which is
// negligible next to the SQL parse it replaces.
private readonly stmtCache_ = new Map<string, Statement>();
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;
return;
}
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.initSchema();
this.loadSnapshot();
}
/** Cached `prepare(sql)`. First call per unique SQL parses; later
* calls reuse the same `Statement` object. See `stmtCache_`. */
private pstmt(sql: string): Statement {
let cached = this.stmtCache_.get(sql);
if (cached !== undefined) return cached;
cached = this.db!.prepare(sql);
this.stmtCache_.set(sql, cached);
return cached;
}
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
}
static memory(uin: string): IdentityService {
return new IdentityService(uin, null);
}
close(): void {
this.db?.close();
}
get persistent(): boolean {
return this.db !== null;
}
setFetcher(fetcher: IdentityFetcher): void {
this.fetcher = fetcher;
}
// ─── Self identity surface ───
get uin(): string { return this.uin_; }
get nickname(): string { return this.nickname_; }
set nickname(v: string) { this.nickname_ = v; }
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
// ─── Domain object reads ───
findUserProfile(uin: number): UserProfileInfo | null {
return this.userProfiles_.get(uin) ?? null;
}
get friends(): FriendInfo[] { return this.friends_; }
findFriend(uin: number): FriendInfo | null {
return this.friends_.find((f) => f.uin === uin) ?? null;
}
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
findGroup(groupId: number): QQGroupInfo | null {
return this.groups_.get(groupId) ?? null;
}
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
return this.groups_.get(groupId)?.members.get(uin) ?? null;
}
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.set(member.uin, member);
this.rememberUidUin(member.uid, member.uin);
}
// ─── ID translation ───
/**
* UIN → UID with network fallback. Returns cached value on hit; otherwise
* invokes the registered fetcher (typically `bridge.fetchUserProfile`),
* which is expected to write the result back through `rememberUserProfile`
* before this method re-queries the cache. Throws if no UID can be
* obtained from any layer.
*/
async resolveUid(uin: number, groupId?: number): Promise<string> {
const normalized = normalizeUin(uin);
if (normalized === null) throw new Error(`invalid uin: ${uin}`);
const cached = this.findUidByUin(normalized, groupId);
if (cached) return cached;
if (groupId !== undefined && this.fetcher?.fetchGroupMemberList) {
try { await this.fetcher.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const afterMembers = this.findUidByUin(normalized, groupId);
if (afterMembers) return afterMembers;
}
if (!this.fetcher) throw new Error(`failed to resolve UID for UIN ${normalized}: no fetcher`);
const profile = await this.fetcher.fetchProfile(normalized);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${normalized}`);
}
findUinByUid(uid: string, groupId?: number): number | null {
const normalized = normalizeUid(uid);
if (!normalized) return null;
if (groupId !== undefined) {
const member = this.findGroupMemberByUid(groupId, normalized);
if (member) return member.uin;
}
const mapped = this.uinByUid.get(normalized);
if (mapped !== undefined) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.pstmt(
`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.pstmt(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
}
findUidByUin(uin: number, groupId?: number): string | null {
const normalized = normalizeUin(uin);
if (normalized === null) return null;
if (groupId !== undefined) {
const member = this.groups_.get(groupId)?.members.get(normalized);
if (member?.uid) return member.uid;
}
const mapped = this.uidByUin.get(normalized);
if (mapped) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.pstmt(
`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.pstmt(
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
).get(normalized) as { uid: string | null } | undefined;
return normalizeUid(row?.uid) || null;
}
// ─── Observation (write side) ───
rememberFriends(friends: FriendInfo[]): void {
this.friends_ = friends;
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
this.runWrite('friends', () => this.transaction(() => {
this.pstmt('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.setGroupsInMemory(groups);
this.runWrite('groups', () => this.transaction(() => {
this.pstmt('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.setGroupMembersInMemory(groupId, members);
for (const member of members) this.rememberUidUin(member.uid, member.uin);
this.runWrite('group members', () => this.transaction(() => {
this.upsertGroup({ groupId, memberCount: members.length });
this.pstmt('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.userProfiles_.set(info.uin, info);
const selfUin = parseInt(this.uin_, 10) || 0;
if (info.uin === selfUin) this.selfProfile_ = info;
this.rememberUidUin(info.uid, info.uin);
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
uid: info.uid,
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.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
.run(updatedAt, row.id);
}
});
});
}
// ─── Private helpers ───
private rememberUidUin(uid: unknown, uin: unknown): void {
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);
}
private setGroupsInMemory(groups: QQGroupInfo[]): void {
// Preserve existing member maps where possible so a roster refresh
// doesn't blow away cached members for groups we already track.
const previous = new Map(this.groups_);
this.groups_.clear();
for (const g of groups) {
const existing = previous.get(g.groupId);
this.groups_.set(g.groupId, {
...g,
members: existing?.members ?? g.members ?? new Map(),
});
}
}
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.clear();
for (const m of members) {
g.members.set(m.uin, m);
}
}
private findGroupMemberByUid(groupId: number, uid: string): GroupMemberInfo | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uid === uid) return m;
}
return null;
}
private initSchema(): void {
this.db!.exec(`
CREATE TABLE IF NOT EXISTS users (
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.pstmt(
`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.friends_ = friendRows.map((row) => ({
uid: row.uid ?? '',
uin: row.uin ?? 0,
nickname: row.nickname,
remark: row.remark,
}));
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
const groups = this.pstmt(
`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.setGroupsInMemory(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 select = this.pstmt(
`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;
}>;
const members = rows.map(rowToMemberInfo);
this.setGroupMembersInMemory(groupId, members);
for (const m of members) this.rememberUidUin(m.uid, m.uin);
}
}
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.pstmt('DELETE FROM users WHERE id = ?').run(duplicate.id);
}
this.pstmt(
`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.pstmt(
`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.pstmt(
'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.pstmt(
`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.pstmt('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
}
this.pstmt(
`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.pstmt(
`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.pstmt(
'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.pstmt(
'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.pstmt(
'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.pstmt(
`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.pstmt(
`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.pstmt(
`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.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);
}
+76
View File
@@ -0,0 +1,76 @@
import { protobuf_decode } from '@snowluma/proton';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { IdentityService } from '../identity-service';
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message';
export type PushMsgBody = MessageBody;
export type PushMsgResponseHead = ResponseHead;
export type PushMsgContentHead = ContentHead;
export interface MsgPushHead {
readonly msgType: number;
readonly subType: number;
readonly sequence: number;
readonly timestamp: number;
readonly msgId: number;
}
export interface MsgPushContext {
readonly head: MsgPushHead;
readonly fromUin: number;
readonly fromUid: string;
readonly selfUin: number;
readonly content: Uint8Array;
readonly body: PushMsgBody | undefined;
readonly responseHead: PushMsgResponseHead | undefined;
readonly identity: IdentityService;
}
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
if (pkt.body.length === 0) return null;
// `pkt.body` is already a `Uint8Array` (see `PacketInfo` in
// @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)`
// wrap was a no-op copy — Buffer is a Uint8Array subclass and
// proton's decoder accepts the parent type directly. Dropping the
// wrap saves one allocation per incoming push packet.
const push = protobuf_decode<PushMsg>(pkt.body);
if (!push?.message) return null;
const msg = push.message;
if (!msg.contentHead) return null;
const head: MsgPushHead = {
msgType: msg.contentHead.msgType ?? 0,
subType: msg.contentHead.subType ?? 0,
sequence: msg.contentHead.sequence ?? 0,
timestamp: msg.contentHead.timestamp ?? 0,
msgId: msg.contentHead.msgId ?? 0,
};
let fromUin = 0;
let fromUid = '';
if (msg.responseHead) {
fromUin = msg.responseHead.fromUin ?? 0;
fromUid = msg.responseHead.fromUid ?? '';
}
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
const content = msg.body?.msgContent ?? new Uint8Array(0);
return {
head,
fromUin,
fromUid,
selfUin,
content,
body: msg.body,
responseHead: msg.responseHead,
identity,
};
}
@@ -0,0 +1,132 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type {
FriendAddEvent,
FriendPokeEvent,
FriendRequestEvent,
QQEventVariant,
} from '../../events';
import type {
FriendRecall,
FriendRequest,
GeneralGrayTipInfo,
NewFriend,
} from '@snowluma/proto-defs/notify';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
buildTemplateMap, findTemplateValue,
parseU64OrZero,
resolveUidToUin,
} from '../helpers';
import type { MsgPushDecoder } from '../registry';
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
// 138 (other-recalled) and 139 (self-recalled) share the same
// FriendRecall wire shape; the helper picks the right uid side
// based on the subType.
case Event0x210SubType.FriendRecallNotice:
case Event0x210SubType.FriendRecallSelfNotice:
return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
// 179 + 226 both carry the NewFriend payload — see enum comment.
case Event0x210SubType.NewFriendNotice:
case Event0x210SubType.NewFriendNoticeAlt:
return decodeNewFriend(ctx);
case Event0x210SubType.GroupAppStatePush:
// QQ-client-internal troop shortcut bar / discussion app state
// push — no OneBot-level event. See enum comment for the
// decompiled-source breakdown of the sub_cmd dispatch.
return [];
case Event0x210SubType.UnmappedClientState380:
// QQ-NT-era subType with no reference handler: the legacy QQ
// Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26
// through SubType0x146 under msgType0x210/, so 380 / 0x17C is
// an NT-era addition. None of the NT clients (Lagrange.Core,
// LagrangeGo, lagrange-python, mania) handle it either. See the
// enum comment for the full investigation; acknowledge silently
// until someone maps the schema.
return [];
}
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
return [];
};
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protobuf_decode<FriendRequest>(ctx.content);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid, ctx.fromUin),
fromUid: sourceUid,
message: request.info.message ?? '',
flag: sourceUid,
};
return [ev];
}
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
const recall = protobuf_decode<FriendRecall>(ctx.content);
if (!recall?.info) return [];
// 138 = friend recalled their own message sent to bot (peer = fromUid).
// 139 = bot recalled own message sent to friend (peer = toUid). Same
// ambiguity acidify handles in `parseFriendRecall:380`. Without this
// split, self-recall events surface `userUin` as the bot itself which
// confuses downstream OneBot consumers that key off `user_id`.
const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice;
const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? '';
const ev: FriendRecallEvent = {
kind: 'friend_recall',
time: recall.info.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
msgSeq: recall.info.clientSequence ?? 0,
};
return [ev];
}
function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
const nf = protobuf_decode<NewFriend>(ctx.content);
if (!nf?.info) return [];
const newFriendUid = nf.info.uid ?? '';
const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin);
if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot
const ev: FriendAddEvent = {
kind: 'friend_add',
// proto field is `fixed32 Time` — already uint32 seconds epoch.
// Fall back to head.timestamp if the field is missing (some
// captures have it as 0).
time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: newFriendUin,
};
return [ev];
}
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
@@ -0,0 +1,164 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type {
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupPokeEvent,
GroupRecallEvent,
QQEventVariant,
} from '../../events';
import type {
GroupMute,
GroupReactNotify,
NotifyMessageBody,
} from '@snowluma/proto-defs/notify';
import type { MsgPushContext } from '../context';
import { Event0x2DCSubType } from '../enums';
import {
buildTemplateMap, findTemplateValue,
parseU64OrZero,
resolveUidToUin,
unwrapGroupNotifyPayload,
} from '../helpers';
import type { MsgPushDecoder } from '../registry';
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 [];
};
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
const mute = protobuf_decode<GroupMute>(ctx.content);
if (!mute?.data?.state) return [];
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
kind: 'group_mute',
time: mute.data.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: mute.groupUin ?? 0,
operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? '', ctx.fromUin),
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
};
return [ev];
}
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
kind: 'group_recall',
time: recalled.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
operatorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || '', ctx.fromUin),
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? '', ctx.fromUin),
msgSeq: recalled.sequence ?? 0,
};
return [ev];
}
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: GroupPokeEvent = {
kind: 'group_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.essenceMessage) return [];
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
const ev: GroupEssenceEvent = {
kind: 'group_essence',
time: essence.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: essence.groupUin ?? notify.groupUin ?? 0,
senderUin: essence.memberUin ?? 0,
operatorUin: essence.operatorUin ?? ctx.fromUin,
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
random: essence.random ?? 0,
set: setFlag === 1,
};
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 = protobuf_decode<GroupReactNotify>(payload);
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];
}
@@ -0,0 +1,22 @@
import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const ev: FriendMessage = {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements: decodeRichBody(ctx.body, false),
senderNick: '',
};
if (ctx.responseHead?.forward?.friendName) {
ev.senderNick = ctx.responseHead.forward.friendName;
}
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
return [ev];
};
@@ -0,0 +1,21 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupAdminEvent } from '../../events';
import type { GroupAdmin } from '@snowluma/proto-defs/notify';
import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protobuf_decode<GroupAdmin>(ctx.content);
if (!admin?.body) return [];
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
if (!extra) return [];
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: admin.groupUin ?? 0,
userUin: resolveUidToUin(ctx.identity, admin.groupUin ?? 0, extra.adminUid ?? '', ctx.fromUin),
set: admin.body.extraEnable !== undefined,
};
return [ev];
};
@@ -0,0 +1,68 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupInviteEvent } from '../../events';
import type {
GroupInvitation, GroupInvite,
GroupJoin,
} from '@snowluma/proto-defs/notify';
import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
const join = protobuf_decode<GroupJoin>(ctx.content);
if (!join) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: join.groupUin ?? 0,
// Strangers (not in our cache, not yet group members) won't resolve
// here — pass 0 instead of ctx.fromUin (which on a group-scoped push
// IS the group's own uin, so falling back to it produces a bogus
// `fromUin === groupId` collision). The packet-pipeline's pre-
// dispatch hook does an async UID-form FetchUserProfile lookup to
// fill in the uin + nickname before the event is emitted — same
// shape as Lagrange's flow at
// `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', 0),
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
return [ev];
};
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
if (!invitation?.info?.inner) return [];
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', 0),
fromUid: inner.invitorUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
return [ev];
};
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
const invite = protobuf_decode<GroupInvite>(ctx.content);
if (!invite) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', 0),
fromUid: invite.invitorUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
};
@@ -0,0 +1,71 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
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: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
userUid,
operatorUid,
};
return [ev];
};
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
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: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
userUid,
operatorUid,
isKick: dt !== 0 && dt !== 130,
};
return [ev];
};
export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => {
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
if (!joined) return [];
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
// — saturate to 0 on the unlikely overflow rather than letting
// BigInt propagate downstream where consumers expect a number.
const groupUinBig = joined.groupUin ?? 0n;
const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0;
const operatorUid = joined.operatorUid ?? '';
// We're the one joining — surface the bot's own identity as userUin
// so the existing converter's `notice.group_increase` shape works
// unchanged.
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: ctx.selfUin,
userUid: ctx.identity.selfUid ?? '',
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
operatorUid,
};
return [ev];
};
@@ -0,0 +1,30 @@
import type { GroupMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeGroupMessage: MsgPushDecoder = (ctx) => {
const ev: GroupMessage = {
kind: 'group_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements: decodeRichBody(ctx.body, true),
groupId: 0,
senderNick: '',
senderCard: '',
senderRole: '',
};
if (ctx.responseHead?.grp) {
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
}
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
if (member) {
if (!ev.senderNick) ev.senderNick = member.nickname;
ev.senderCard = member.card;
ev.senderRole = member.role;
}
return [ev];
};
@@ -0,0 +1,25 @@
import type { TempMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
elements: decodeRichBody(ctx.body, false),
groupId: 0,
senderNick: '',
};
if (ctx.responseHead?.grp) {
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
}
if (!ev.senderNick) {
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend) ev.senderNick = friend.nickname;
}
return [ev];
};
+108
View File
@@ -0,0 +1,108 @@
export enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
/**
* Self-join admittance — fires on the bot's session right after an
* admin approves its `set_group_add_request` or an invite-accept
* goes through. Ported from `lagrange-python`'s
* `server_push/msg.py:108 case 85`. Maps to OneBot11
* `notice.group_increase` with the bot itself as `user_id` —
* existing 33 (GroupMemberIncreaseNotice) doesn't fire for the
* bot's own join, so without this case the bot never knows it
* just entered a group until the first message arrives.
*/
GroupSelfJoinedNotice = 85,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
}
export enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupMsgEmojiLikeNotice = 16,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
export enum Event0x210SubType {
FriendRequestNotice = 35,
/**
* Outgoing friend-message recall — bot recalled its own message that
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
* difference is direction (138 = friend recalled their own message
* sent to bot, 139 = bot recalled own message sent to friend).
* Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor`
* registered for both 138 and 139) + acidify (`138, 139 ->
* parseFriendRecall`). The decoder uses the subType to figure out
* which UID side ends up as `userUin` on the emitted event.
*/
FriendRecallSelfNotice = 139,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
/**
* Mutual-accept friend notice — 179 fires when bot sent a friend
* request and the other side accepted; 226 fires for the opposite
* direction. Both decode through the same `NewFriend` wire shape
* (LagrangeGo registers them via a `case 226: case 179:` fallthrough
* in `client/listener.go:248-258`). Maps to OneBot11
* `notice.friend_add`.
*/
NewFriendNotice = 179,
NewFriendNoticeAlt = 226,
/**
* Group-app state push (troop shortcut bar / discussion app).
*
* Sourced from the decompiled stock QQ Android client decoder at
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
* (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody`
* dispatching on `uint32_sub_cmd`:
*
* - 0x1 → `UpdateAppUnreadNum`: a list of
* `{group_code, app_id, unread_num}` entries the QQ client uses
* to keep group-internal "mini-app" badges (e.g. `appId=101846662`
* / `101896870` for the shortcut bar) in sync.
* - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
* for discussion-group app tips, routed to `getGAudioHandler()`.
* - 0x4 → delegated to the troop online-push handler.
*
* None of these have a OneBot event mapping — they're QQ-client-UI
* state pushes (unread badges, in-app tips), not user-visible
* conversation events. Acknowledge the subType so it doesn't keep
* showing up as "unknown" in debug logs and drop it silently.
* Lagrange V2 / lagrange-python / LagrangeGo / acidify all also
* fall through on this one because they don't surface the shortcut
* bar either.
*/
GroupAppStatePush = 38,
/**
* Unmapped QQ-NT-internal subType — first seen as a recurring
* "Event0x210 unknown subType=380" debug log in production captures.
*
* The tsuzcx/qq_apk decompile of the legacy QQ Android client only
* enumerates SubType0x26 (38) through SubType0x146 (326) under
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` —
* `SubType0x17c.java` (380) literally doesn't exist in that tree, so
* 380 is a QQ-NT-era addition rather than a missed legacy subType.
*
* The NT-era reference clients also don't handle it: Lagrange.Core
* (`PushMessageService.cs`), LagrangeGo (`client/listener.go`),
* lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`)
* each enumerate explicit 0x210 subtypes and none include 380 / 0x17C.
*
* Most likely a QQ-NT-client-UI state push (similar to 38) that
* doesn't map to any OneBot event. Acknowledge silently to keep the
* unknown log clean; if a real OneBot event ends up depending on it,
* revisit with whichever NT-era project finally maps the schema.
*/
UnmappedClientState380 = 380,
}
+80
View File
@@ -0,0 +1,80 @@
import { protobuf_decode } from '@snowluma/proton';
import { inflateSync } from 'zlib';
import type { IdentityService } from '../identity-service';
import type { OperatorInfo } from '@snowluma/proto-defs/notify';
export function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
return 'http://gchat.qpic.cn' + origUrl;
}
export function decompressData(data: Uint8Array): string {
if (!data || data.length === 0) return '';
if (data[0] === 0x01 && data.length > 1) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)));
return inflated.toString('utf8');
} catch { return ''; }
}
if (data[0] === 0x00 && data.length > 1) {
return Buffer.from(data.subarray(1)).toString('utf8');
}
return Buffer.from(data).toString('utf8');
}
export function isNumericUin(value: string): boolean {
return value.length > 0 && /^\d+$/.test(value);
}
export function parseU64OrZero(value: string): number {
if (!value) return 0;
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
}
// Cascades group-scoped lookup → in-memory map → SQLite.
// No network fallback on the parse hot path: missing identities fall back to
// `fallback` and downstream events drive a roster refresh asynchronously.
export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number {
if (!uid) return fallback;
if (isNumericUin(uid)) {
const n = parseInt(uid, 10);
if (!isNaN(n)) return n;
}
const uin = identity.findUinByUid(uid, groupId || undefined);
if (uin !== null) return uin;
return fallback;
}
export function decodeOperatorUid(bytes: Uint8Array): string {
if (!bytes || bytes.length === 0) return '';
const info = protobuf_decode<OperatorInfo>(bytes);
if (info?.operatorField?.uid) return info.operatorField.uid;
return Buffer.from(bytes).toString('utf8');
}
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
if (p.name !== undefined) map.set(p.name, p.value ?? '');
}
return map;
}
export function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
for (const k of keys) {
const v = map.get(k);
if (v) return v;
}
return '';
}
export function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
if (content.length <= 7) return null;
const lenBe = (content[5] << 8) | content[6];
const lenLe = content[5] | (content[6] << 8);
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
return content.subarray(7);
}
+46
View File
@@ -0,0 +1,46 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { buildContext } from './context';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeFriendMessage } from './decoders/friend-message';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
decodeGroupInvitation, decodeGroupInvite,
decodeGroupJoinRequest,
} from './decoders/group-join-request';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
} from './decoders/group-member-change';
import { decodeGroupMessage } from './decoders/group-message';
import { decodeTempMessage } from './decoders/temp-message';
import { PkgType } from './enums';
import { MsgPushRegistry } from './registry';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
const registry = new MsgPushRegistry();
registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin);
registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave);
registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined);
registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin);
registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest);
registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation);
registry.register(PkgType.GroupInviteNotice, decodeGroupInvite);
registry.register(PkgType.Event0x210, decodeEvent0x210);
registry.register(PkgType.Event0x2DC, decodeEvent0x2DC);
registry.register(PkgType.GroupMessage, decodeGroupMessage);
registry.register(PkgType.TempMessage, decodeTempMessage);
registry.register([
PkgType.PrivateMessage,
PkgType.ForwardFakePrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
], decodeFriendMessage);
export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
const ctx = buildContext(pkt, identity);
if (!ctx) return [];
return registry.decode(ctx);
}
@@ -0,0 +1,42 @@
import { createLogger } from '@snowluma/common/logger';
import type { QQEventVariant } from '../events';
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[];
export class MsgPushRegistry {
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
register(pkgType: PkgType | PkgType[], decoder: MsgPushDecoder): void {
const list = Array.isArray(pkgType) ? pkgType : [pkgType];
for (const t of list) {
if (this.decoders_.has(t)) {
throw new Error(`MsgPushRegistry: PkgType ${t} already registered`);
}
this.decoders_.set(t, decoder);
}
}
decode(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
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) {
log.error('decoder error for PkgType=%d subType=%d: %s',
ctx.head.msgType, ctx.head.subType,
e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
}
}
}
@@ -0,0 +1,483 @@
import { protobuf_decode } from '@snowluma/proton';
import { toHexUpper } from '@snowluma/common/hex';
import type { MessageElement } from '../events';
import type {
Elem,
GroupFileExtra,
MentionExtra,
MsgInfo,
NotOnlineImage,
QFaceExtra,
QSmallFaceExtra,
} from '@snowluma/proto-defs/element';
import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
import { decompressData, makeImageUrl } from './helpers';
type ElemDecoded = Elem;
type RichTextDecoded = RichText;
export type PushMsgBody = MessageBody;
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
const elements: MessageElement[] = [];
if (body?.richText) {
const rt = body.richText;
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
extractRichtextExtras(rt, elements, isGroup);
}
if (body?.msgContent && body.msgContent.length > 0) {
extractMsgContent(body.msgContent, elements);
}
return elements;
}
function convertElements(elems: ElemDecoded[]): MessageElement[] {
const result: MessageElement[] = [];
let skipNext = false;
for (const elem of elems) {
if (skipNext) { skipNext = false; continue; }
// Reply / quote
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
}
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
let mention: MentionExtra | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
mention = protobuf_decode<MentionExtra>(t.pbReserve);
}
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
if (hasAttr6 || hasMention) {
const me: MessageElement = { type: 'at', text: t.str ?? '' };
if (hasAttr6) {
const buf = t.attr6Buf!;
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
}
if (hasMention && mention) {
me.uid = mention.uid ?? '';
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
}
result.push(me);
} else {
const text = t.str ?? '';
if (text) result.push({ type: 'text', text });
}
}
// Face
if (elem.face) {
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
}
// MarketFace
if (elem.marketFace) {
result.push({
type: 'mface',
text: elem.marketFace.faceName ?? '',
faceId: elem.marketFace.tabId ?? 0,
subType: elem.marketFace.subType ?? 0,
});
}
// NotOnlineImage (C2C image)
if (elem.notOnlineImage) {
const img = elem.notOnlineImage;
if (img.picMd5 && img.picMd5.length > 0) {
const urlPath = img.origUrl || img.bigUrl || '';
result.push({
type: 'image',
imageUrl: makeImageUrl(urlPath),
fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0,
width: img.picWidth ?? 0,
height: img.picHeight ?? 0,
subType: img.pbRes?.subType ?? 0,
// `[图片]` / `[动画表情]` are the QQ-ecosystem default
// bubble texts; mobile QQ + Lagrange.Core + NapCat all
// expect these literal Chinese strings when the wire
// doesn't carry a per-image override.
summary: img.pbRes?.summary || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'),
md5Hex: toHexUpper(img.picMd5),
});
}
}
// CustomFace (group image)
if (elem.customFace) {
const img = elem.customFace;
if (img.md5 && img.md5.length > 0) {
result.push({
type: 'image',
imageUrl: makeImageUrl(img.origUrl ?? ''),
fileId: img.filePath ?? '',
fileSize: img.size ?? 0,
width: img.width ?? 0,
height: img.height ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'),
md5Hex: toHexUpper(img.md5),
});
}
}
// VideoFile
if (elem.videoFile) {
const v = elem.videoFile;
result.push({
type: 'video',
fileId: v.fileUuid ?? '',
fileName: v.fileName ?? '',
fileSize: v.fileSize ?? 0,
duration: v.fileTime ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
mediaNode: {
fileUuid: v.fileUuid ?? '',
info: {
fileSize: v.fileSize ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
fileName: v.fileName ?? '',
width: v.fileWidth ?? 0,
height: v.fileHeight ?? 0,
time: v.fileTime ?? 0,
type: {
type: 2,
videoFormat: v.fileFormat ?? 0,
},
},
},
});
}
// GroupFile
if (elem.groupFile) {
const f = elem.groupFile;
result.push({
type: 'file',
fileId: f.fileId ?? '',
fileName: f.filename ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
});
}
// TransElem type=24 (group file via transport)
if (elem.transElem) {
const te = elem.transElem;
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
const val = te.elemValue;
const len = (val[1] << 8) | val[2];
if (val.length >= 3 + len) {
const extra = protobuf_decode<GroupFileExtra>(val.subarray(3, 3 + len));
if (extra?.inner?.info) {
const info = extra.inner.info;
result.push({
type: 'file',
fileName: info.fileName ?? '',
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
fileId: info.fileId ?? '',
});
}
}
}
}
// RichMsg
if (elem.richMsg) {
const rm = elem.richMsg;
if (rm.template1 && rm.template1.length > 0) {
const content = decompressData(rm.template1);
if (content) {
const svcId = rm.serviceId ?? 0;
if (svcId === 35) {
const pos = content.indexOf('m_resid="');
if (pos !== -1) {
const start = pos + 9;
const end = content.indexOf('"', start);
if (end !== -1) {
result.push({ type: 'forward', resId: content.substring(start, end) });
continue;
}
}
result.push({ type: 'xml', text: content, subType: svcId });
} else if (svcId === 1) {
result.push({ type: 'json', text: content });
} else {
result.push({ type: 'xml', text: content, subType: svcId });
}
}
}
}
// LightApp
if (elem.lightApp) {
const la = elem.lightApp;
if (la.data && la.data.length > 0) {
const content = decompressData(la.data);
if (content) {
// `com.tencent.multimsg` is the multi-msg / forward preview
// LightApp (the modern replacement for the XML serviceID=35
// shape). Parse out resid + uniseq so downstream callers can
// both render a `[聊天记录]` placeholder and walk into the
// forward chain via `fetch(resId)` — the uniseq is what links
// the inner layer to its piggybacked actions on the outer's
// LongMsgResult. Other LightApp messages fall through to the
// generic `{type: 'json'}` path.
try {
const parsed = JSON.parse(content);
if (parsed && parsed.app === 'com.tencent.multimsg') {
const detail = parsed.meta?.detail ?? {};
const resId = typeof detail.resid === 'string' ? detail.resid : '';
const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : '';
if (resId) {
result.push({
type: 'forward',
resId,
forwardUuid: uniseq || undefined,
});
continue;
}
}
} catch { /* fall through to generic json element */ }
result.push({ type: 'json', text: content });
}
}
}
// CommonElem
if (elem.commonElem) {
const ce = elem.commonElem;
const svcType = ce.serviceType ?? 0;
const bizType = ce.businessType ?? 0;
if (svcType === 2) {
// Poke
result.push({ type: 'poke', subType: bizType });
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
// Flash image
const pb = ce.pbElem;
let pos = 1;
let length = 0, shift = 0;
while (pos < pb.length) {
const b = pb[pos++];
length |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) === 0) break;
}
if (pos + length <= pb.length) {
const img = protobuf_decode<NotOnlineImage>(pb.subarray(pos, pos + length));
if (img) {
const me: MessageElement = {
type: 'image', fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
};
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
if (img.picMd5 && img.picMd5.length > 0) {
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + toHexUpper(img.picMd5) + '/0';
}
result.push(me);
}
}
skipNext = true;
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
// NTQQ new protocol image/record/video
const info = protobuf_decode<MsgInfo>(ce.pbElem);
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
const body = info.msgInfoBody[0];
if (body.index?.info) {
const idx = body.index;
const fi = idx.info!;
if (bizType === 10 || bizType === 20) {
// Image
let url = '';
if (body.picture) {
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
const path = body.picture.urlPath ?? '';
if (path) {
url = 'https://' + domain + path;
if (body.picture.ext?.originalParameter) {
url += body.picture.ext.originalParameter;
}
}
}
const me: MessageElement = {
type: 'image', fileId: fi.fileName ?? '',
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
height: fi.height ?? 0, imageUrl: url,
};
if (fi.fileHash) me.md5Hex = fi.fileHash;
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
if (info.extBizInfo?.pic) {
me.subType = info.extBizInfo.pic.bizType ?? 0;
me.summary = info.extBizInfo.pic.textSummary
|| (me.subType === 1 ? '[动画表情]' : '[图片]');
}
result.push(me);
} else if (bizType === 12 || bizType === 22) {
// Record
result.push({
type: 'record', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
fileSize: fi.fileSize ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
voiceFormat: fi.type?.voiceFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
} else if (bizType === 11 || bizType === 21) {
// Video
result.push({
type: 'video', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
width: fi.width ?? 0,
height: fi.height ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
videoFormat: fi.type?.videoFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
}
}
}
} else if (svcType === 33 && ce.pbElem) {
// Small face
const extra = protobuf_decode<QSmallFaceExtra>(ce.pbElem);
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
} else if (svcType === 37 && ce.pbElem) {
// Big face
const extra = protobuf_decode<QFaceExtra>(ce.pbElem);
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
skipNext = true;
}
}
}
return result;
}
function extractRichtextExtras(
rt: RichTextDecoded,
elements: MessageElement[],
isGroup = false
): void {
// Ptt (voice)
if (rt.ptt) {
const p = rt.ptt;
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '';
const me: MessageElement = {
type: 'record', fileName: p.fileName ?? '',
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
fileHash: md5Hex,
md5Hex,
voiceFormat: p.format ?? 0,
};
if (isGroup && (p.fileId ?? 0n) !== 0n) {
me.fileId = p.groupFileKey ?? '';
} else {
if (p.fileUuid && p.fileUuid.length > 0) {
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
}
}
me.mediaNode = {
fileUuid: me.fileId ?? '',
info: {
fileSize: p.fileSize ?? 0,
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '',
fileName: p.fileName ?? '',
time: p.time ?? 0,
type: {
type: 3,
voiceFormat: p.format ?? 0,
},
},
};
elements.push(me);
}
// NotOnlineFile (C2C file)
if (rt.notOnlineFile) {
const f = rt.notOnlineFile;
elements.push({
type: 'file', fileId: f.fileUuid ?? '',
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
// `MessageBody.msgContent` is where the QQ-NT server actually puts
// c2c file metadata — serialised `FileExtra { file: NotOnlineFile }`
// bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/
// fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire
// shape — every field landed at the wrong tag, so the four-field
// truthiness check below filtered out every real c2c file push as
// "incomplete metadata". After consolidating FileExtra to wrap
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
// this reads the right tags.
const extra = protobuf_decode<FileExtra>(msgContent);
if (!extra?.file) return;
const f = extra.file;
if (!f.fileUuid) return;
elements.push({
type: 'file',
fileId: f.fileUuid,
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
+174
View File
@@ -0,0 +1,174 @@
// OIDB service layer — the next architectural revision on top of the
// area-grouped Api facade pattern (InteractionApi / ProfileApi / …).
//
// Each OIDB cmd is modelled as a TypeScript namespace whose exported
// members ARE the `OidbCallSpec` shape (structural typing makes this
// implicit — no `implements` clause needed). The namespace also exports
// a thin `invoke()` that hands itself to `invokeOidb` for dispatch.
//
// Why namespace-as-spec instead of class:
// - stateless: no `new` overhead at the call site
// - no `this` binding, no implicit lifecycle
// - tree-shakes per-export (unused services drop out of the bundle)
// - spec ↔ code 1:1 (one file = one (cmd, subcmd) tuple)
//
// Why Pick-style minimal `Deps` per service:
// - Interface Segregation: a wire-only cmd doesn't see identity/events
// - tests mock only what's used (typically just `sendRawPacket`)
// - changes to BridgeContext don't bleed into services
// - the dep list IS the documentation of side-effects
//
// Why `ctx` threads into serialize/deserialize:
// - the namespace is then genuinely self-contained — "what does this
// cmd do on the wire + what state does it touch" lives in one file
// - earlier shape forced an `invoke = { ...Self, serialize: p =>
// localSerialize(p, await ctx.resolveUserUid(...)) }` rewrite for
// every cmd that needed identity/uid resolution; ctx-aware
// serialize collapses that to a single async serialize.
// - serialize is now `TReq | Promise<TReq>` so async lookups
// (resolveUserUid, identity reads) happen in place.
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { makeOidbEnvelope } from './bridge-oidb';
/**
* Capability narrow enough for any wire-only OIDB call. Anything that
* also needs identity / event bus / upload cache declares those via
* `Pick<BridgeContext, 'identity' | …>` and intersects with this.
*/
export interface OidbSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
}
/**
* The shape every cmd namespace exports. Structural typing means a
* namespace whose top-level exports match these names + types IS an
* `OidbCallSpec` — no `implements` clause needed.
*
* `TCtx` is the namespace's capability surface — always at least
* `OidbSender` (so `invokeOidb` can dispatch through it) plus any
* `Pick<BridgeContext, ...>` slices the cmd actually needs.
*
* One of `subCommand` (static) or `resolveSubCommand` (dynamic from
* params) must be present. `resolveSubCommand` wins if both are given.
*/
export interface OidbCallSpec<TCtx extends OidbSender, TReq, TResp, TParams, TResult> {
command: number;
subCommand?: number;
resolveSubCommand?(params: TParams): number;
/** Set OIDB envelope `reserved = 1` (UIN-form variant, see makeOidbEnvelope's isUid). */
uinForm?: boolean;
/** Override the default `OidbSvcTrpcTcp.0xNNNN_N` wire name. A few
* cmds route through different SSO names (e.g. 0xE17_0 lives at
* `MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`); supply a function
* that takes the resolved `(cmd, subCmd)` and returns the actual
* wire name. Omit for the default scheme. */
wireName?(command: number, subCommand: number): string;
/** Business params → wire-shaped request body. May be async (e.g.
* when ctx.resolveUserUid hits the cache or the network). */
serialize(ctx: TCtx, params: TParams): TReq | Promise<TReq>;
/** Wire-shaped response body → business result. */
deserialize(ctx: TCtx, body: TResp): TResult;
/** Per-type protobuf encoder — concrete generic call so the Vite plugin can monomorphize. */
encode(env: OidbBase<TReq>): Uint8Array;
/** Per-type protobuf decoder. */
decode(bytes: Uint8Array): OidbBase<TResp>;
}
export class OidbError extends Error {
constructor(
readonly code: number,
readonly serverMsg: string,
readonly command: number,
readonly subCommand: number,
) {
super(`OIDB error ${code} on 0x${command.toString(16)}_${subCommand}: ${serverMsg}`);
this.name = 'OidbError';
}
}
/**
* Template method for every OIDB call. Builds the envelope, encodes it,
* sends through the ctx's `sendRawPacket`, validates the envelope's
* `errorCode`, decodes the body, and hands the wire-shaped response to
* the spec's `deserialize` for transformation into the business result.
*
* `ctx` is threaded into both `serialize` and `deserialize` so the
* namespace can do uid resolution / identity reads in-place rather
* than forcing the caller to pre-bake values into the params.
*/
export async function invokeOidb<TCtx extends OidbSender, TReq, TResp, TParams, TResult>(
ctx: TCtx,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
params: TParams,
timeoutMs?: number,
): Promise<TResult> {
const subCommand = spec.resolveSubCommand
? spec.resolveSubCommand(params)
: spec.subCommand!;
const reqBody = await spec.serialize(ctx, params);
const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false);
const reqBytes = spec.encode(env);
const wireName = spec.wireName
? spec.wireName(spec.command, subCommand)
: `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
const result = await ctx.sendRawPacket(wireName, reqBytes, timeoutMs);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
const respBytes = result.responseData ?? new Uint8Array(0);
if (respBytes.length > 0) {
const meta = protobuf_decode<OidbBaseMeta>(respBytes);
const code = meta?.errorCode;
if (code && code !== 0) {
throw new OidbError(code, meta?.errorMsg ?? '', spec.command, subCommand);
}
}
// Server may legitimately respond with an empty envelope (ack-only
// cmds like 0x9082_1 — the response carries only `errorCode = 0`
// and no body). Substitute an empty placeholder so `deserialize`
// always receives a defined object; specs that read fields off the
// body must already guard with `?? []` etc.
const respBody = spec.decode(respBytes).body ?? ({} as TResp);
return spec.deserialize(ctx, respBody);
}
/**
* Build the request wire bytes for a spec without sending — useful for
* wire dump debugging, capability probing, and unit tests of the
* encode path. Threads `ctx` because `serialize` may want it (and
* because matching `invokeOidb`'s shape avoids two call patterns).
*/
export async function buildOidbRequest<TCtx extends OidbSender, TReq, TResp, TParams, TResult>(
ctx: TCtx,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
params: TParams,
): Promise<{ wireName: string; bytes: Uint8Array }> {
const subCommand = spec.resolveSubCommand
? spec.resolveSubCommand(params)
: spec.subCommand!;
const reqBody = await spec.serialize(ctx, params);
const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false);
const bytes = spec.encode(env);
const wireName = spec.wireName
? spec.wireName(spec.command, subCommand)
: `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
return { wireName, bytes };
}
/**
* Decode raw wire bytes into the business result via a spec's
* deserialize path — symmetric debug helper for buildOidbRequest.
*/
export function parseOidbResponse<TCtx extends OidbSender, TReq, TResp, TParams, TResult>(
ctx: TCtx,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
bytes: Uint8Array,
): TResult {
return spec.deserialize(ctx, spec.decode(bytes).body ?? ({} as TResp));
}
@@ -0,0 +1,53 @@
// 0x9067_202 — fetch download-rkey tokens for private/group/fallback
// image scopes. The rkey is a server-issued signed download token used
// to authenticate every CDN GET against `gchat.qpic.cn` / similar
// endpoints.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
const PRIVATE_IMAGE = 10;
const GROUP_IMAGE = 20;
const FALLBACK_IMAGE = 2;
export namespace FetchDownloadRkeys {
export const command = 0x9067;
export const subCommand = 202;
export const uinForm = true;
export interface Params {}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, _: Params): NTV2RichMediaReq => ({
reqHead: {
common: { requestId: 1, command: 202 },
scene: { requestType: 2, businessType: 1, sceneType: 0 },
client: { agentType: 2 },
},
downloadRkey: {
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
},
});
export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): NTV2RichMediaResp => {
// Propagate server-side OIDB-equivalent error via the embedded
// respHead.retCode — bytes-level OIDB errorCode would already
// have thrown OidbError before deserialize was called.
if (body.respHead?.retCode && body.respHead.retCode !== 0) {
throw new Error(body.respHead.message ?? 'fetch download rkey failed');
}
return body;
};
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
export const invoke = (deps: Deps): Promise<NTV2RichMediaResp> =>
invokeOidb(deps, FetchDownloadRkeys, {});
}
@@ -0,0 +1,54 @@
// 0xFD4_1 — single-page friend-roster fetch.
//
// QQ paginates the friend list with a wire-level cursor (`nextUin`).
// This namespace handles ONE round-trip — the facade drives the
// while-loop until the server stops emitting a next cursor and
// concatenates results into the public FriendInfo[] shape.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchFriendListPage {
export const command = 0xFD4;
export const subCommand = 1;
export interface Params {
/** Cursor: `null` for the first page, otherwise the previous
* page's `nextUin`. */
nextUin: number | null;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbFriendListRequest => {
const body: any = {
friendCount: 300,
field4: 0,
field6: 1,
field7: 0x7FFFFFFF,
body: [
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
],
field10002: [13578, 13579, 13573, 13572, 13568],
field10003: 4051,
};
if (p.nextUin !== null) {
body.nextUin = { uin: p.nextUin };
}
return body;
};
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFD4_1Response): OidbSvcTrpcTcp0xFD4_1Response => body;
export const encode = (env: OidbBase<OidbFriendListRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbFriendListRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFD4_1Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0xFD4_1Response> =>
invokeOidb(deps, FetchFriendListPage, params);
}
@@ -0,0 +1,57 @@
// 0xFE5_2 — fetch the bot's joined-groups list with full per-group
// info.
//
// The verbose `config` blob in the request body asks QQ which
// per-group fields to include. Asking for everything blows the
// named-pipe write buffer on accounts with ~200+ groups (see #42),
// so we keep `config1.*` mostly on but turn off the costly
// `field5002`/`field5003` and entire `config2` block that never map
// back to a decoded field anyway.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFE5_2Response } from '@snowluma/proto-defs/oidb';
import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchGroupList {
export const command = 0xFE5;
export const subCommand = 2;
export const uinForm = true;
export interface Params {}
export type Deps = OidbSender;
const allTrue = true;
export const serialize = (_ctx: Deps, _: Params): OidbGroupListRequest => ({
config: {
config1: {
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
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: false, field5003: false,
},
config2: {
field1: false, field2: false, field3: false, field4: false,
field5: false, field6: false, field7: false, field8: false,
},
config3: { field5: allTrue, field6: allTrue },
},
});
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFE5_2Response): OidbSvcTrpcTcp0xFE5_2Response => body;
export const encode = (env: OidbBase<OidbGroupListRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupListRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFE5_2Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(bytes);
export const invoke = (deps: Deps): Promise<OidbSvcTrpcTcp0xFE5_2Response> =>
invokeOidb(deps, FetchGroupList, {});
}
@@ -0,0 +1,54 @@
// 0xFE7_3 — single-page group-member-roster fetch.
//
// Pagination cursor is the server-issued `token` string. The facade
// drives the loop until `token` comes back empty; per-group caching
// + inflight coalescing also stays on the facade since both need
// state that's per-Bridge (and is what stops Tencent risk-control
// from banning the account on busy clients — see #42).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFE7_3Response } from '@snowluma/proto-defs/oidb';
import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchGroupMemberListPage {
export const command = 0xFE7;
export const subCommand = 3;
export interface Params {
groupId: number;
/** Empty string for the first page; pass the previous response's
* `token` to fetch the next page. */
token: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupMemberListRequest => {
const body: any = {
groupUin: p.groupId,
field2: 5,
field3: 2,
body: {
memberName: true, memberCard: true, level: true, field13: true,
field16: true, specialTitle: true, field18: true, field20: true,
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
shutUpTimestamp: true, field103: true, field104: true, field105: true,
field106: true, permission: true, field200: true, field201: true,
},
};
if (p.token) body.token = p.token;
return body;
};
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFE7_3Response): OidbSvcTrpcTcp0xFE7_3Response => body;
export const encode = (env: OidbBase<OidbGroupMemberListRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupMemberListRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFE7_3Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0xFE7_3Response> =>
invokeOidb(deps, FetchGroupMemberListPage, params);
}
@@ -0,0 +1,40 @@
// 0x10C0 — fetch pending group-add requests.
// subCommand 1 = main inbox, 2 = filtered (low-priority) inbox
//
// Returns the wire shape verbatim — the facade does the GroupRequestInfo
// mapping because it also needs to thread the `filtered` flag onto
// each entry, which the wire doesn't carry.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0x10C0Response } from '@snowluma/proto-defs/oidb';
import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchGroupRequests {
export const command = 0x10C0;
export interface Params {
/** false → subCmd 1 (main inbox), true → subCmd 2 (filtered). */
filtered: boolean;
}
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1;
export const serialize = (_ctx: Deps, _: Params): OidbGroupRequestList => ({
count: 20,
field2: 0,
});
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0x10C0Response): OidbSvcTrpcTcp0x10C0Response => body;
export const encode = (env: OidbBase<OidbGroupRequestList>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupRequestList>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0x10C0Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0x10C0Response> =>
invokeOidb(deps, FetchGroupRequests, params);
}
@@ -0,0 +1,99 @@
// 0xFE1_2 (UID form) — fetch a user's profile when only the UID is
// known. Same OIDB cmd + subcmd as `FetchUserProfile` (by UIN) but
// the request body's field 1 is `uid: string` instead of `uin:
// uint32`, and `reserved` stays 0 (no `uinForm`).
//
// Why two namespaces for the same (cmd, subcmd):
// - Group join requests / invitations carry the stranger's UID
// only — we never get a UIN for someone who hasn't joined yet.
// - The Tencent server WILL reject a UIN-form request with a uid-
// shaped value or vice versa, so the two variants must encode
// to byte-different wires.
// - Matches Lagrange's `OidbSvcTrpcTcp0xFE1_2Uid` vs `…Uin` split
// at `dev/Lagrange.Core/.../OidbSvcTrpcTcp0xFE1_2.cs:9-26`
// and the dispatch at
// `dev/Lagrange.Core/.../FetchUserInfoService.cs:66-78`.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
AvatarInfo,
OidbUserInfoByUidRequest,
OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { UserProfileInfo } from '../../qq-info';
import { invokeOidb, type OidbSender } from '../../oidb-service';
const REQUESTED_KEYS = [
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026,
105, 27372, 27406, 20037,
];
export namespace FetchUserProfileByUid {
export const command = 0xFE1;
export const subCommand = 2;
// No `uinForm` — the UID variant uses the default `reserved=0`
// envelope, mirroring Lagrange's untagged constructor at
// `OidbSvcTrpcTcp0xFE1_2.cs:9` (isUid=false → Reserved=0).
export interface Params {
uid: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbUserInfoByUidRequest => ({
uid: p.uid,
keys: REQUESTED_KEYS.map(k => ({ key: k })),
});
export const deserialize = (_ctx: Deps, body: OidbUserInfoResponse): UserProfileInfo => {
if (!body.body) throw new Error('user info response body missing');
const info: UserProfileInfo = {
uin: body.body.uin ?? 0,
uid: body.body.uid ?? '',
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
};
if (body.body.properties) {
const bytesMap = new Map<number, Uint8Array>();
const numMap = new Map<number, number>();
for (const bp of body.body.properties.bytesProperties ?? []) {
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
}
for (const np of body.body.properties.numberProperties ?? []) {
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
}
const getString = (code: number): string => {
const b = bytesMap.get(code);
return b ? Buffer.from(b).toString('utf8') : '';
};
info.nickname = getString(20002);
info.remark = getString(103);
info.qid = getString(27394);
info.sign = getString(102);
const avatarBytes = bytesMap.get(101);
if (avatarBytes) {
const av = protobuf_decode<AvatarInfo>(avatarBytes);
if (av?.url) info.avatar = av.url + '640';
}
const sexNum = numMap.get(20009) ?? 0;
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
info.age = numMap.get(20037) ?? 0;
info.level = numMap.get(105) ?? 0;
}
return info;
};
export const encode = (env: OidbBase<OidbUserInfoByUidRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbUserInfoByUidRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbUserInfoResponse> =>
protobuf_decode<OidbBase<OidbUserInfoResponse>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<UserProfileInfo> =>
invokeOidb(deps, FetchUserProfileByUid, params);
}
@@ -0,0 +1,115 @@
// 0xFE1_2 — fetch a user's profile (nickname / qid / sex / age / sign
// / avatar / QQ level).
//
// `uinForm` is set so the server takes the UIN-form validation path;
// without it newer NTQQ versions reject the request with
// `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's
// FetchStrangerByUin (Reserved = 1).
//
// Property key catalogue (cross-checked against LagrangeV2's
// FetchStrangerService.cs):
// 101 — avatar info (proto-encoded AvatarInfo)
// 102 — sign (signature)
// 103 — remark
// 105 — QQ level (numeric)
// 20002 — nickname
// 20009 — gender (1 male / 2 female / 255 unknown)
// 20037 — age
// 27394 — QID
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
AvatarInfo,
OidbUserInfoRequest,
OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { UserProfileInfo } from '../../qq-info';
import { invokeOidb, type OidbSender } from '../../oidb-service';
const REQUESTED_KEYS = [
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026,
105, 27372, 27406, 20037,
];
export namespace FetchUserProfile {
export const command = 0xFE1;
export const subCommand = 2;
export const uinForm = true;
export interface Params {
uin: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbUserInfoRequest => ({
uin: p.uin,
keys: REQUESTED_KEYS.map(k => ({ key: k })),
});
/** Defaults the response uin to `requestedUin` because the server
* sometimes elides its echo. `invoke` below binds `params.uin` via
* the spec override so the namespace's call surface still takes
* only `(ctx, body)`. */
export const deserializeWithFallback = (
body: OidbUserInfoResponse, requestedUin: number,
): UserProfileInfo => {
if (!body.body) throw new Error('user info response body missing');
const info: UserProfileInfo = {
uin: body.body.uin ?? requestedUin,
uid: body.body.uid ?? '',
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
};
if (body.body.properties) {
const bytesMap = new Map<number, Uint8Array>();
const numMap = new Map<number, number>();
for (const bp of body.body.properties.bytesProperties ?? []) {
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
}
for (const np of body.body.properties.numberProperties ?? []) {
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
}
const getString = (code: number): string => {
const b = bytesMap.get(code);
return b ? Buffer.from(b).toString('utf8') : '';
};
info.nickname = getString(20002);
info.remark = getString(103);
info.qid = getString(27394);
info.sign = getString(102);
const avatarBytes = bytesMap.get(101);
if (avatarBytes) {
const av = protobuf_decode<AvatarInfo>(avatarBytes);
if (av?.url) info.avatar = av.url + '640';
}
const sexNum = numMap.get(20009) ?? 0;
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
info.age = numMap.get(20037) ?? 0;
info.level = numMap.get(105) ?? 0;
}
return info;
};
// Default deserialize uses uin=0 fallback — invoke() rewires it to
// the requested uin via the per-call spec override below. Tests
// that call deserialize directly should use deserializeWithFallback.
export const deserialize = (_ctx: Deps, body: OidbUserInfoResponse): UserProfileInfo =>
deserializeWithFallback(body, 0);
export const encode = (env: OidbBase<OidbUserInfoRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbUserInfoRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbUserInfoResponse> =>
protobuf_decode<OidbBase<OidbUserInfoResponse>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<UserProfileInfo> =>
invokeOidb(deps, {
...FetchUserProfile,
deserialize: (_ctx, body) => deserializeWithFallback(body, params.uin),
}, params);
}
@@ -0,0 +1,50 @@
// 0x929D_0 — fetch the catalog of AI voices available for synthesis
// in a given group, grouped by category. Returns the categories
// straight from the wire (caller already expects the wire shape).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbAiVoiceListReq, OidbAiVoiceListResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
}
export namespace FetchAiVoiceList {
export const command = 0x929D;
export const subCommand = 0;
export interface Params {
groupId: number;
chatType: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbAiVoiceListReq => ({
groupUin: p.groupId,
chatType: p.chatType,
});
export const deserialize = (_ctx: Deps, body: OidbAiVoiceListResp): AiVoiceCategory[] =>
(body.content as AiVoiceCategory[] | undefined) ?? [];
export const encode = (env: OidbBase<OidbAiVoiceListReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbAiVoiceListReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbAiVoiceListResp> =>
protobuf_decode<OidbBase<OidbAiVoiceListResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<AiVoiceCategory[]> =>
invokeOidb(deps, FetchAiVoiceList, params);
}
@@ -0,0 +1,68 @@
// 0x929B_0 — kick off AI voice synthesis and poll until the rendered
// media is available. The server may return an empty msgInfo while
// the render is in-flight; the facade polls up to `maxRetries` times.
//
// `sessionId` is a random 32-bit value used by the server to
// de-duplicate retries of the same synthesis request.
//
// Each `invoke()` is a SINGLE poll — the retry loop lives on the
// facade so callers can plug their own back-off / cancellation in
// without forking the namespace.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbAiVoiceReq, OidbAiVoiceResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
/** Subset of AiVoiceMediaIndex (defined in @snowluma/core/apis/shared)
* that the AI voice response payload populates. Kept inline here so
* the namespace stays self-contained against @snowluma/protocol — the
* facade casts back to the richer core-side type. */
export interface AiVoiceMediaIndex {
info?: { fileSize?: number; fileName?: string; type?: { type?: number; voiceFormat?: number } };
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
}
export namespace FetchAiVoice {
export const command = 0x929B;
export const subCommand = 0;
export interface Params {
groupId: number;
voiceId: string;
text: string;
chatType: number;
/** Random 32-bit session id; server uses this to deduplicate polls. */
sessionId: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbAiVoiceReq => ({
groupUin: p.groupId,
voiceId: p.voiceId,
text: p.text,
chatType: p.chatType,
session: { sessionId: p.sessionId },
});
export const deserialize = (_ctx: Deps, body: OidbAiVoiceResp): AiVoiceMediaIndex | null => {
const node = body.msgInfo?.msgInfoBody?.[0]?.index as AiVoiceMediaIndex | undefined;
return node ?? null;
};
export const encode = (env: OidbBase<OidbAiVoiceReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbAiVoiceReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbAiVoiceResp> =>
protobuf_decode<OidbBase<OidbAiVoiceResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<AiVoiceMediaIndex | null> =>
invokeOidb(deps, FetchAiVoice, params);
}
@@ -0,0 +1,60 @@
// 0xFE1_2 — fetch the stranger's status (online / away / busy /
// invisible). Same OIDB cmd as fetchUserProfile but a different
// request shape (only key 27372 = status, no other property keys),
// and we decode the ext-bigint status word into napcat's
// (status × 10, ext_status) pair.
//
// `uinForm` is set so the server takes the UIN-form validation path;
// without it newer NTQQ rejects with `[oidb] one of uid/openid is
// invaild`. Same flag fetchUserProfile uses.
//
// On any transport / decode failure the deserialize step is bypassed
// — the facade swallows the namespace-level exception and surfaces
// `null` so callers get a clean retcode.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbStrangerStatusReq, OidbStrangerStatusResp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface StrangerStatus {
status: number;
ext_status: number;
}
export namespace GetStrangerStatus {
export const command = 0xFE1;
export const subCommand = 2;
export const uinForm = true;
export interface Params {
uin: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbStrangerStatusReq => ({
uin: p.uin,
key: [{ key: 27372 }],
});
export const deserialize = (_ctx: Deps, body: OidbStrangerStatusResp): StrangerStatus | null => {
const raw = body.data?.status?.value;
if (raw === undefined || raw === null) return null;
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw as any);
if (extBig <= 10n) {
return { status: Number(extBig) * 10, ext_status: 0 };
}
const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn));
return { status: 10, ext_status: status };
};
export const encode = (env: OidbBase<OidbStrangerStatusReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbStrangerStatusReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbStrangerStatusResp> =>
protobuf_decode<OidbBase<OidbStrangerStatusResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<StrangerStatus | null> =>
invokeOidb(deps, GetStrangerStatus, params);
}
@@ -0,0 +1,48 @@
// 0xF90 — group todo (群待办) CRUD.
// subCommand 1 = set, 2 = complete, 3 = cancel
//
// All three sub-cmds share the same request shape ((groupUin, msgSeq))
// so they collapse into one namespace with a dynamic subcmd resolver.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupTodo } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export type GroupTodoAction = 'set' | 'complete' | 'cancel';
const ACTION_TO_SUBCMD: Record<GroupTodoAction, number> = {
set: 1,
complete: 2,
cancel: 3,
};
export namespace GroupTodo {
export const command = 0xF90;
export interface Params {
groupId: number;
msgSeq: bigint;
action: GroupTodoAction;
}
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => ACTION_TO_SUBCMD[p.action];
export const serialize = (_ctx: Deps, p: Params): OidbGroupTodo => ({
groupUin: p.groupId,
msgSeq: p.msgSeq,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbGroupTodo>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupTodo>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, GroupTodo, params);
}
@@ -0,0 +1,53 @@
// 0x126B_0 — delete a friend (optionally with block flag).
//
// The deeply-nested field2 sub-message is a server-side discriminator
// that must be sent verbatim — the magic numbers (130 / 109 / 8/8/50)
// match the wire shape NTQQ's own client emits and aren't a SnowLuma
// invention. Server rejects the request if any of them is wrong.
//
// Cache invalidation (re-fetching the friend list after deletion)
// lives in the facade — keeps this namespace dependency-free of
// `apis.contacts` and the OneBot-side caches.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbDeleteFriend } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace DeleteFriend {
export const command = 0x126B;
export const subCommand = 0;
export interface Params {
userId: number;
/** Also block (拉黑) the user. Default false. */
block?: boolean;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbDeleteFriend> => ({
field1: {
targetUid: await ctx.resolveUserUid(p.userId),
field2: {
field1: 130,
field2: 109,
field3: { field1: 8, field2: 8, field3: 50 },
},
block: p.block ?? false,
field4: false,
},
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbDeleteFriend>): Uint8Array =>
protobuf_encode<OidbBase<OidbDeleteFriend>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteFriend, params);
}
@@ -0,0 +1,47 @@
// 0xB5D_44 — accept (3) / reject (5) an inbound friend request.
//
// Caller passes either a pre-resolved UID string or a numeric uin
// (encoded as a digit-only string); we detect the latter and resolve
// to UID first.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbFriendRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace HandleFriendRequest {
export const command = 0xB5D;
export const subCommand = 44;
export interface Params {
/** Pre-resolved UID, or a digit-only numeric uin to resolve on demand. */
uidOrFlag: string;
approve: boolean;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbFriendRequestAction> => {
const targetUid = /^\d+$/.test(p.uidOrFlag)
? await ctx.resolveUserUid(parseInt(p.uidOrFlag, 10))
: p.uidOrFlag;
return {
// Server discriminator: 3 = accept, 5 = reject. Pre-fix values
// verified against current production behaviour.
accept: p.approve ? 3 : 5,
targetUid,
};
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbFriendRequestAction>): Uint8Array =>
protobuf_encode<OidbBase<OidbFriendRequestAction>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, HandleFriendRequest, params);
}
@@ -0,0 +1,36 @@
// 0xB6E_2 — set the remark (备注) shown for a friend in the bot's
// own roster. Doesn't affect what the friend sees.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetFriendRemark {
export const command = 0xB6E;
export const subCommand = 2;
export interface Params {
userId: number;
remark: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbSetFriendRemark> => ({
targetUid: await ctx.resolveUserUid(p.userId),
remark: p.remark,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbSetFriendRemark>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetFriendRemark>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetFriendRemark, params);
}
@@ -0,0 +1,58 @@
// 0x8A7_0 — query "@everyone" remaining-use budget for the bot in
// the given group. Server returns two independent counters: a
// per-uin budget (the bot's daily allowance) and a per-group budget
// (the group's shared allowance). The OneBot action surfaces both
// alongside a single `can_at_all` boolean.
//
// The req's `basic{1,2,3}` triplet (1/2/1) is the wire-known
// validation cookie NTQQ emits; the server rejects requests with
// different values. `type = 0` means "query" (no other type seen).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x8a7Req, Oidb0x8a7Resp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export interface AtAllRemain {
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}
export namespace GetAtAllRemain {
export const command = 0x8A7;
export const subCommand = 0;
export interface Params { groupId: number; }
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
export const serialize = (ctx: Deps, p: Params): Oidb0x8a7Req => ({
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(ctx.identity.uin),
groupId: BigInt(p.groupId),
type: 0,
});
export const deserialize = (_ctx: Deps, body: Oidb0x8a7Resp): AtAllRemain => {
// Cast numbers to plain Number: the OIDB layer may surface uint32
// as BigInt and the WebUI JSON serializer chokes on those.
return {
can_at_all: !!body.canAtAll,
remain_at_all_count_for_group: Number(body.groupRemain ?? 0),
remain_at_all_count_for_uin: Number(body.uinRemain ?? 0),
};
};
export const encode = (env: OidbBase<Oidb0x8a7Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x8a7Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x8a7Resp> =>
protobuf_decode<OidbBase<Oidb0x8a7Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<AtAllRemain> =>
invokeOidb(deps, GetAtAllRemain, params);
}
@@ -0,0 +1,42 @@
// 0x8A0_1 — single-member kick. The batch variant (kickMembers) uses
// the same cmd but a different proto body shape; kept as a separate
// namespace because proton needs distinct types per call site.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbKickMember } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace KickMember {
export const command = 0x8A0;
export const subCommand = 1;
export interface Params {
groupId: number;
userId: number;
/** Reject the kicked user's future join requests. */
reject: boolean;
reason?: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbKickMember> => ({
groupUin: p.groupId,
targetUid: await ctx.resolveUserUid(p.userId, p.groupId),
rejectAddRequest: p.reject,
reason: p.reason ?? '',
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbKickMember>): Uint8Array =>
protobuf_encode<OidbBase<OidbKickMember>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, KickMember, params);
}
@@ -0,0 +1,41 @@
// 0x8A0_1 — batch member kick (repeated targetUids). Same cmd+subcmd
// as KickMember (single) but a different proto body shape; separate
// namespace so proton can monomorphize independently.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0x8a0Req } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace KickMembers {
export const command = 0x8A0;
export const subCommand = 1;
export interface Params {
groupId: number;
userIds: number[];
reject: boolean;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<Oidb0x8a0Req> => ({
groupId: BigInt(p.groupId),
targetUids: await Promise.all(p.userIds.map(uid => ctx.resolveUserUid(uid, p.groupId))),
rejectAddRequest: p.reject ? 1 : 0,
kickReason: new Uint8Array(0),
field12: 0,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<Oidb0x8a0Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x8a0Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, KickMembers, params);
}
@@ -0,0 +1,23 @@
// 0x1097_1 — leave a group (退群).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbLeaveGroup } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace LeaveGroup {
export const command = 0x1097;
export const subCommand = 1;
export interface Params { groupId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbLeaveGroup => ({ groupUin: p.groupId });
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbLeaveGroup>): Uint8Array =>
protobuf_encode<OidbBase<OidbLeaveGroup>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, LeaveGroup, params);
}
@@ -0,0 +1,34 @@
// 0x89A_0 — toggle group全员禁言. `state` is the duration multiplier
// (0xFFFFFFFF for permanent mute, 0 for unmute). Multiple OIDB cmds
// share the (0x89A, 0) tuple — see also SetAddOption / SetSearch /
// SetName — disambiguated by the body proto shape.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbMuteAll } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace MuteAll {
export const command = 0x89A;
export const subCommand = 0;
export interface Params { groupId: number; enable: boolean; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbMuteAll => ({
groupUin: p.groupId,
muteState: { state: p.enable ? 0xFFFFFFFF : 0 },
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbMuteAll>): Uint8Array =>
protobuf_encode<OidbBase<OidbMuteAll>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MuteAll, params);
}
@@ -0,0 +1,36 @@
// 0x1253_1 — mute a single group member for `duration` seconds.
// Server treats duration = 0 as "unmute now".
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbMuteMember } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace MuteMember {
export const command = 0x1253;
export const subCommand = 1;
export interface Params { groupId: number; userId: number; duration: number; }
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbMuteMember> => ({
groupUin: p.groupId, type: 1,
body: {
targetUid: await ctx.resolveUserUid(p.userId, p.groupId),
duration: p.duration,
},
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbMuteMember>): Uint8Array =>
protobuf_encode<OidbBase<OidbMuteMember>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MuteMember, params);
}
@@ -0,0 +1,34 @@
// 0x89A_0 — set group "how to join" option (anyone / verification /
// owner-only / etc). Same cmd+subcmd as MuteAll / SetSearch / SetName
// — disambiguated by the body proto shape.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0AddOption } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetAddOption {
export const command = 0x89A;
export const subCommand = 0;
export interface Params { groupId: number; addType: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0AddOption => ({
groupUin: BigInt(p.groupId),
settings: { addType: p.addType },
field12: 0,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<Oidb0x89a_0AddOption>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x89a_0AddOption>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetAddOption, params);
}
@@ -0,0 +1,49 @@
// 0x10C8 — approve/reject a pending group join request.
// subCommand 1 = main inbox, 2 = filtered inbox
//
// `uinForm=true` matches the request shape NTQQ emits. `accept: 1`
// is the server discriminator for approve; `2` for reject.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetAddRequest {
export const command = 0x10C8;
export const uinForm = true;
export interface Params {
groupId: number;
sequence: number;
eventType: number;
approve: boolean;
reason?: string;
filtered?: boolean;
}
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1;
export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestAction => ({
accept: p.approve ? 1 : 2,
body: {
sequence: BigInt(p.sequence),
eventType: p.eventType,
groupUin: p.groupId,
message: p.reason ?? '',
},
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbGroupRequestAction>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupRequestAction>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetAddRequest, params);
}
@@ -0,0 +1,30 @@
// 0x1096_1 — promote / demote a member to/from group administrator.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbSetAdmin } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetAdmin {
export const command = 0x1096;
export const subCommand = 1;
export interface Params { groupId: number; userId: number; enable: boolean; }
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbSetAdmin> => ({
groupUin: p.groupId,
uid: await ctx.resolveUserUid(p.userId, p.groupId),
isAdmin: p.enable,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbSetAdmin>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetAdmin>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetAdmin, params);
}
@@ -0,0 +1,27 @@
// 0x89A_15 — rename the group.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbRenameGroup } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetGroupName {
export const command = 0x89A;
export const subCommand = 15;
export interface Params { groupId: number; name: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbRenameGroup => ({
groupUin: p.groupId, body: { targetName: p.name },
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbRenameGroup>): Uint8Array =>
protobuf_encode<OidbBase<OidbRenameGroup>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetGroupName, params);
}
@@ -0,0 +1,29 @@
// 0xF16_1 — set the bot's local-only label/remark for a group (only
// the bot sees this — the group's actual name is untouched).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0xf16Req } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetGroupRemark {
export const command = 0xF16;
export const subCommand = 1;
export interface Params { groupId: number; remark: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0xf16Req => ({
inner: { groupId: BigInt(p.groupId), remark: p.remark },
field12: 0,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<Oidb0xf16Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0xf16Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetGroupRemark, params);
}
@@ -0,0 +1,32 @@
// 0x8FC_3 — set a member's group-card (群名片).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbRenameMember } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetMemberCard {
export const command = 0x8FC;
export const subCommand = 3;
export interface Params { groupId: number; userId: number; card: string; }
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbRenameMember> => ({
groupUin: p.groupId,
body: {
targetUid: await ctx.resolveUserUid(p.userId, p.groupId),
targetName: p.card,
},
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbRenameMember>): Uint8Array =>
protobuf_encode<OidbBase<OidbRenameMember>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetMemberCard, params);
}
@@ -0,0 +1,33 @@
// 0x89A_0 — toggle group "searchable" flag. Same cmd+subcmd shape as
// MuteAll / SetAddOption / SetName.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0Search } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetSearch {
export const command = 0x89A;
export const subCommand = 0;
export interface Params { groupId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0Search => ({
groupUin: BigInt(p.groupId),
settings: new Uint8Array(0),
field12: 0,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<Oidb0x89a_0Search>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x89a_0Search>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetSearch, params);
}
@@ -0,0 +1,34 @@
// 0x8FC_2 — assign a member a "special title" (群头衔). `expireTime=-1`
// is the wire constant for "permanent".
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbSpecialTitle } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetSpecialTitle {
export const command = 0x8FC;
export const subCommand = 2;
export interface Params { groupId: number; userId: number; title: string; }
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbSpecialTitle> => ({
groupUin: p.groupId,
body: {
targetUid: await ctx.resolveUserUid(p.userId, p.groupId),
specialTitle: p.title,
expireTime: -1,
},
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbSpecialTitle>): Uint8Array =>
protobuf_encode<OidbBase<OidbSpecialTitle>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetSpecialTitle, params);
}
@@ -0,0 +1,42 @@
// 0x6D7_0 — create a sub-folder under `parentId` in the group file
// hierarchy. parentId='/' is the root.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileFolderReq, OidbGroupFileFolderResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { ensureRetCodeZero } from '../shared';
export namespace CreateGroupFolder {
export const command = 0x6D7;
export const subCommand = 0;
export const uinForm = true;
export interface Params { groupId: number; parentId: string; folderName: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileFolderReq => ({
create: {
groupUin: p.groupId,
rootDirectory: p.parentId,
folderName: p.folderName,
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): void => {
const result = body.create;
if (!result) throw new Error('group folder create response missing');
ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording);
};
export const encode = (env: OidbBase<OidbGroupFileFolderReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileFolderResp> =>
protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, CreateGroupFolder, params);
}
@@ -0,0 +1,41 @@
// 0x6D6_3 — delete a single group file by id.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { ensureRetCodeZero } from '../shared';
export namespace DeleteGroupFile {
export const command = 0x6D6;
export const subCommand = 3;
export const uinForm = true;
export interface Params { groupId: number; fileId: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({
delete: {
groupUin: p.groupId,
busId: 102,
fileId: p.fileId,
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): void => {
const result = body.delete;
if (!result) throw new Error('group file delete response missing');
ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording);
};
export const encode = (env: OidbBase<OidbGroupFileReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileResp> =>
protobuf_decode<OidbBase<OidbGroupFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteGroupFile, params);
}
@@ -0,0 +1,38 @@
// 0x6D7_1 — delete a group folder by id (any files inside are
// orphaned; UI sometimes pre-empties first via per-file deletes).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileFolderReq, OidbGroupFileFolderResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { ensureRetCodeZero } from '../shared';
export namespace DeleteGroupFolder {
export const command = 0x6D7;
export const subCommand = 1;
export const uinForm = true;
export interface Params { groupId: number; folderId: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileFolderReq => ({
delete: { groupUin: p.groupId, folderId: p.folderId },
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): void => {
const result = body.delete;
if (!result) throw new Error('group folder delete response missing');
ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording);
};
export const encode = (env: OidbBase<OidbGroupFileFolderReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileFolderResp> =>
protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteGroupFolder, params);
}
@@ -0,0 +1,42 @@
// 0x6D8_3 — fetch group file slot usage. Returns the current count
// alongside the server-side ceiling (NTQQ's `maxCount` default is
// 10000; we surface that fallback so the OneBot action can render
// the gauge without a second call when the server elides the field).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileCountViewReq, OidbGroupFileCountViewResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupFileCount {
fileCount: number;
maxCount: number;
}
export namespace GetGroupFileCount {
export const command = 0x6D8;
export const subCommand = 3;
export interface Params { groupId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileCountViewReq => ({
count: { groupUin: p.groupId, appId: 7, busId: 0 },
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileCountViewResp): GroupFileCount => ({
fileCount: Number(body.count?.fileCount ?? 0),
maxCount: Number(body.count?.maxCount ?? 10000),
});
export const encode = (env: OidbBase<OidbGroupFileCountViewReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileCountViewReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileCountViewResp> =>
protobuf_decode<OidbBase<OidbGroupFileCountViewResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupFileCount> =>
invokeOidb(deps, GetGroupFileCount, params);
}
@@ -0,0 +1,44 @@
// 0x6D6_2 — resolve a group file_id → ftn_handler download URL. The
// server returns a `downloadUrl` blob (raw bytes that hex-encode the
// download key) and a `downloadDns` host. The facade composes the
// final `https://<dns>/ftn_handler/<HEX>/?fname=<fileId>` string.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp, OidbGroupFileDownloadResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetGroupFileUrl {
export const command = 0x6D6;
export const subCommand = 2;
export const uinForm = true;
export interface Params { groupId: number; fileId: string; busId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({
download: {
groupUin: p.groupId,
appId: 7,
busId: p.busId,
fileId: p.fileId,
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): OidbGroupFileDownloadResp => {
const download = body.download;
if (!download) throw new Error('group file url response missing');
return download;
};
export const encode = (env: OidbBase<OidbGroupFileReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileResp> =>
protobuf_decode<OidbBase<OidbGroupFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbGroupFileDownloadResp> =>
invokeOidb(deps, GetGroupFileUrl, params);
}
@@ -0,0 +1,49 @@
// 0x126E_200 — fetch a download URL for a group-scope rich-media node
// (voice in this case — busiType=3 means "ptt/voice", sceneType=2
// means group). Pairs with the c2c-scope variant `GetPrivatePttUrl`
// (0x126D_200) which only differs in scene.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import {
normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex,
} from './ntv2-download';
export namespace GetGroupPttUrl {
export const command = 0x126E;
export const subCommand = 200;
export const uinForm = true;
export interface Params { groupId: number; node: NtMediaIndex; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({
reqHead: {
common: { requestId: 4, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 2,
group: { groupUin: p.groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizeMediaNode(p.node) as any,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body);
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetGroupPttUrl, params);
}
@@ -0,0 +1,48 @@
// 0x11EA_200 — video URL fetch, group scope. Same envelope shape as
// GetGroupPttUrl; `requestType=2 + businessType=2` swaps voice for
// video. The scene's `group` block carries the group uin.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import {
normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex,
} from './ntv2-download';
export namespace GetGroupVideoUrl {
export const command = 0x11EA;
export const subCommand = 200;
export const uinForm = true;
export interface Params { groupId: number; node: NtMediaIndex; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 2,
group: { groupUin: p.groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizeMediaNode(p.node) as any,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body);
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetGroupVideoUrl, params);
}
@@ -0,0 +1,56 @@
// 0xE37_1200 — resolve a private (c2c) file_id → http download URL.
// Carries an opaque 4-byte `field99999` magic the server's deserializer
// requires (Lagrange has the same constant). The facade composes the
// final `http://<server>:<port><url>&isthumb=0` string.
//
// 5s timeout matches the original facade — the server batches these
// at low priority and stalls past the default 30s.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbPrivateFileDownloadReq, OidbPrivateFileDownloadResp,
OidbPrivateFileDownloadRespResult,
} from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
const TIMEOUT_MS = 5000;
export namespace GetPrivateFileUrl {
export const command = 0xE37;
export const subCommand = 1200;
export interface Params { selfUid: string; fileId: string; fileHash: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbPrivateFileDownloadReq => ({
subCommand: 1200,
field2: 1,
body: {
receiverUid: p.selfUid,
fileUuid: p.fileId,
type: 2,
fileHash: p.fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
});
export const deserialize = (_ctx: Deps, body: OidbPrivateFileDownloadResp): OidbPrivateFileDownloadRespResult => {
const result = body.body?.result;
if (!result) throw new Error('private file url response invalid');
return result;
};
export const encode = (env: OidbBase<OidbPrivateFileDownloadReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbPrivateFileDownloadReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbPrivateFileDownloadResp> =>
protobuf_decode<OidbBase<OidbPrivateFileDownloadResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbPrivateFileDownloadRespResult> =>
invokeOidb(deps, GetPrivateFileUrl, params, TIMEOUT_MS);
}
@@ -0,0 +1,48 @@
// 0x126D_200 — c2c-scope counterpart of GetGroupPttUrl. Same shape,
// `scene` is `c2c` rather than `group`. Needs the bot's own uid to
// fill the c2c.targetUid slot.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import {
normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex,
} from './ntv2-download';
export namespace GetPrivatePttUrl {
export const command = 0x126D;
export const subCommand = 200;
export const uinForm = true;
export interface Params { selfUid: string; node: NtMediaIndex; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 1,
c2c: { accountType: 2, targetUid: p.selfUid },
},
client: { agentType: 2 },
},
download: {
node: normalizeMediaNode(p.node) as any,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body);
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetPrivatePttUrl, params);
}
@@ -0,0 +1,48 @@
// 0x11E9_200 — c2c-scope video URL fetch (pair of GetGroupVideoUrl).
// `scene.c2c.targetUid` is the bot's own uid; the server uses it as
// the read-side identity for the asset lookup.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import {
normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex,
} from './ntv2-download';
export namespace GetPrivateVideoUrl {
export const command = 0x11E9;
export const subCommand = 200;
export const uinForm = true;
export interface Params { selfUid: string; node: NtMediaIndex; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 1,
c2c: { accountType: 2, targetUid: p.selfUid },
},
client: { agentType: 2 },
},
download: {
node: normalizeMediaNode(p.node) as any,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body);
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetPrivateVideoUrl, params);
}
@@ -0,0 +1,55 @@
// 0x6D8_1 — ONE page of the group-file listing under `targetDirectory`.
// Paginated; the facade loops this until `isEnd=true` or the page cap
// is hit. Each page yields a mix of files (`type=1`) and folders
// (`type=2`); the caller flattens them.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileViewReq, OidbGroupFileViewResp, OidbGroupFileListResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace ListGroupFilesPage {
export const command = 0x6D8;
export const subCommand = 1;
export const uinForm = true;
export interface Params {
groupId: number;
targetDirectory: string;
startIndex: number;
pageSize: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileViewReq => ({
list: {
groupUin: p.groupId,
appId: 7,
targetDirectory: p.targetDirectory,
fileCount: p.pageSize,
sortBy: 1,
startIndex: p.startIndex,
field17: 2,
field18: 0,
},
});
/** Returns the list body directly so the facade can inspect
* `items`, `isEnd`, and `retCode` in one place. Returns null when
* the server elides the list entirely (end-of-stream sentinel). */
export const deserialize = (_ctx: Deps, body: OidbGroupFileViewResp): OidbGroupFileListResp | null => {
return body.list ?? null;
};
export const encode = (env: OidbBase<OidbGroupFileViewReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileViewReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileViewResp> =>
protobuf_decode<OidbBase<OidbGroupFileViewResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbGroupFileListResp | null> =>
invokeOidb(deps, ListGroupFilesPage, params);
}
@@ -0,0 +1,47 @@
// 0x6D6_5 — move a group file between folders.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { ensureRetCodeZero } from '../shared';
export namespace MoveGroupFile {
export const command = 0x6D6;
export const subCommand = 5;
export const uinForm = true;
export interface Params {
groupId: number; fileId: string;
parentDirectory: string; targetDirectory: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({
move: {
groupUin: p.groupId,
appId: 7,
busId: 102,
fileId: p.fileId,
parentDirectory: p.parentDirectory,
targetDirectory: p.targetDirectory,
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): void => {
const result = body.move;
if (!result) throw new Error('group file move response missing');
ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording);
};
export const encode = (env: OidbBase<OidbGroupFileReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileResp> =>
protobuf_decode<OidbBase<OidbGroupFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MoveGroupFile, params);
}
@@ -0,0 +1,87 @@
// Shared deserializer for the four NTV2-rich-media URL fetchers:
// - get-group-ptt-url (0x126E_200)
// - get-private-ptt-url (0x126D_200)
// - get-group-video-url (0x11EA_200)
// - get-private-video-url (0x11E9_200)
//
// All four hit the `MultiMedia.OidbSvc.0x...` family with the same
// `NTV2RichMediaReq` shape; only the `scene` block + the wire cmd
// differ. The response is parsed into a `domain + urlPath +
// rKeyParam` triple → composed into `https://<domain><path><rKey>`.
import type { NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import { ensureRetCodeZero } from '../shared';
export function parseNtv2DownloadUrl(body: NTV2RichMediaResp): string {
ensureRetCodeZero('ntv2 download', body.respHead?.retCode, body.respHead?.message, undefined);
const domain = typeof body.download?.info?.domain === 'string' ? body.download.info.domain : '';
const path = typeof body.download?.info?.urlPath === 'string' ? body.download.info.urlPath : '';
const rKeyParam = typeof body.download?.rKeyParam === 'string' ? body.download.rKeyParam : '';
if (!domain || !path) throw new Error('ntv2 download response invalid');
return `https://${domain}${path}${rKeyParam}`;
}
/** Normalize a MediaIndexNode-shaped object into the wire-fields the
* NTV2RichMedia `download.node` slot expects: `info{...}` /
* `fileUuid` / `storeId` / `uploadTime` / `ttl` / `subType`. */
export function normalizeMediaNode(node: NtMediaIndex): Record<string, unknown> {
const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : '';
if (!fileUuid) throw new Error('media node fileUuid is required');
const info = node.info ?? {};
const type = info.type ?? {};
return {
info: {
fileSize: toInt(info.fileSize),
fileHash: typeof info.fileHash === 'string' ? info.fileHash : '',
fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '',
fileName: typeof info.fileName === 'string' ? info.fileName : '',
type: {
type: toInt(type.type),
picFormat: toInt(type.picFormat),
videoFormat: toInt(type.videoFormat),
voiceFormat: toInt(type.voiceFormat),
},
width: toInt(info.width),
height: toInt(info.height),
time: toInt(info.time),
original: toInt(info.original),
},
fileUuid,
storeId: toInt(node.storeId),
uploadTime: toInt(node.uploadTime),
ttl: toInt(node.ttl),
subType: toInt(node.subType),
};
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') return Number(value);
return 0;
}
export interface NtMediaIndex {
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
}
@@ -0,0 +1,47 @@
// 0x6D9_4 — publish a previously-uploaded group file as a chat
// message (the file-bubble in the group transcript).
//
// The QQ-NT server rejects the legacy `TransElem(elemType=24)` payload
// on outgoing send (`result=79`) so the file-publish path goes via a
// dedicated OIDB hop instead of `MessageSvc.PbSendMsg`. Mirror
// Lagrange.Core V2's `GroupSendFileService.cs`:
// - `info.field3` is a 31-bit random — Lagrange does `Random.Shared.Next()`
// - `info.field5 = true` is the discriminator the server's deserializer
// expects to recognise this branch.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupSendFileReq } from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace PublishGroupFile {
export const command = 0x6D9;
export const subCommand = 4;
export interface Params { groupId: number; fileId: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupSendFileReq => ({
body: {
groupUin: p.groupId,
type: 2,
info: {
busiType: 102,
fileId: p.fileId,
field3: Math.floor(Math.random() * 0x7fffffff) >>> 0,
field5: true,
},
},
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbGroupSendFileReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupSendFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, PublishGroupFile, params);
}
@@ -0,0 +1,43 @@
// 0x6D7_2 — rename a group folder. Note the wire field is
// `newFolderName` (not `folderName`); the rename slot lives on the
// shared `OidbGroupFileFolderReq` envelope.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileFolderReq, OidbGroupFileFolderResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { ensureRetCodeZero } from '../shared';
export namespace RenameGroupFolder {
export const command = 0x6D7;
export const subCommand = 2;
export const uinForm = true;
export interface Params { groupId: number; folderId: string; newFolderName: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileFolderReq => ({
rename: {
groupUin: p.groupId,
folderId: p.folderId,
newFolderName: p.newFolderName,
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): void => {
const result = body.rename;
if (!result) throw new Error('group folder rename response missing');
ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording);
};
export const encode = (env: OidbBase<OidbGroupFileFolderReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileFolderResp> =>
protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, RenameGroupFolder, params);
}
@@ -0,0 +1,69 @@
// 0x6D6_0 — group-file upload preflight. Hands the server the file
// metadata + hashes and gets back:
// - `boolFileExist` — if true, the bytes are already on the server
// and the highway step is skipped
// - `fileId` — the persistent id used by `publish` (0x6D9_4) and
// later download/delete/move calls
// - upload host/port + the `fileKey`/`checkKey` blob the highway
// PUT needs in its FileUploadExt envelope
//
// This namespace ONLY does the preflight; the highway PUT and the
// follow-on `publish` chat-message hop live on the facade because
// they're orchestration (highway client, ext blob composition) that
// doesn't fit a single OIDB call boundary.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp, OidbGroupFileUploadResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace UploadGroupFileRequest {
export const command = 0x6D6;
export const subCommand = 0;
export const uinForm = true;
export interface Params {
groupId: number;
fileName: string;
folderId: string;
fileSize: number;
fileSha1: Uint8Array;
fileMd5: Uint8Array;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({
file: {
groupUin: p.groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: p.folderId,
fileName: p.fileName,
localDirectory: `/${p.fileName}`,
fileSize: BigInt(p.fileSize),
fileSha1: p.fileSha1,
fileSha3: new Uint8Array(0),
fileMd5: p.fileMd5,
field15: true,
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): OidbGroupFileUploadResp => {
const upload = body.upload;
if (!upload) throw new Error('group file upload response missing');
return upload;
};
export const encode = (env: OidbBase<OidbGroupFileReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileResp> =>
protobuf_decode<OidbBase<OidbGroupFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbGroupFileUploadResp> =>
invokeOidb(deps, UploadGroupFileRequest, params);
}
@@ -0,0 +1,70 @@
// 0xE37_1700 — private (c2c) file upload preflight. Server returns
// the same shape of upload-host info as the group-file path but the
// fields are laid out differently (rtpMediaPlatformUploadAddress is
// the primary host source on current QQ-NT; legacy `uploadIp` /
// `uploadDomain` / `uploadIpList[]` are fallbacks).
//
// As with the group-file preflight, this namespace ONLY does the
// preflight; the highway PUT and the follow-on `sendC2cFile` chat
// hop live on the facade.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbPrivateFileUploadReq, OidbPrivateFileUploadResp,
OidbPrivateFileUploadRespBody,
} from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace UploadPrivateFileRequest {
export const command = 0xE37;
export const subCommand = 1700;
export interface Params {
senderUid: string;
receiverUid: string;
fileName: string;
fileSize: number;
fileSha1: Uint8Array;
fileMd5: Uint8Array;
/** md5 over the first 10 MiB; caller passes this in because we
* can't redo the hash here without re-reading the source. */
md510MCheckSum: Uint8Array;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbPrivateFileUploadReq => ({
command: 1700,
seq: 0,
upload: {
senderUid: p.senderUid,
receiverUid: p.receiverUid,
fileSize: p.fileSize,
fileName: p.fileName,
md510MCheckSum: p.md510MCheckSum,
sha1CheckSum: p.fileSha1,
localPath: '/',
md5CheckSum: p.fileMd5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
});
export const deserialize = (_ctx: Deps, body: OidbPrivateFileUploadResp): OidbPrivateFileUploadRespBody => {
const upload = body.upload;
if (!upload) throw new Error('private file upload response missing');
return upload;
};
export const encode = (env: OidbBase<OidbPrivateFileUploadReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbPrivateFileUploadReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbPrivateFileUploadResp> =>
protobuf_decode<OidbBase<OidbPrivateFileUploadResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbPrivateFileUploadRespBody> =>
invokeOidb(deps, UploadPrivateFileRequest, params);
}
@@ -0,0 +1,56 @@
// 0x7E5_104 — send "thumbs up" (赞) to another user (profile-card 点赞).
//
// Wire shape lives at fields 11/12/13 with a uid (NOT uin) target and a
// fixed `sourceId = 71` marker for the profile-card entry point. The
// server rejects uin-form payloads with "被点赞 QQ 号非法", so we resolve
// uin → uid through the identity service before encoding.
//
// `count` is the number of likes in this single call (QQ allows 1–20
// batched). Server caps daily quotas separately.
//
// Upstream parity:
// - Lagrange.Core `OidbSvcTrpcTcp0x7E5_104` (fields 11/12/13):
// dev/Lagrange.Core/.../Service/Oidb/Request/OidbSvcTrpcTcp0x7E5_104.cs:14-18
// - Lagrange.Core `FriendLikeService` (always emits `Field2 = 71`):
// dev/Lagrange.Core/.../Service/Action/FriendLikeService.cs:18-23
// - NapCat `UserApi.like` (`setBuddyProfileLike` with sourceId 71):
// dev/NapCatQQ/packages/napcat-core/apis/user.ts:63-70
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbLike } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SendLike {
export const command = 0x7E5;
export const subCommand = 104;
export interface Params {
userId: number;
count: number;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbLike> => {
const targetUid = await ctx.resolveUserUid(p.userId);
if (!targetUid) throw new Error(`failed to resolve uid for ${p.userId}`);
return {
targetUid,
sourceId: 71,
count: p.count,
};
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbLike>): Uint8Array =>
protobuf_encode<OidbBase<OidbLike>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SendLike, params);
}
@@ -0,0 +1,48 @@
// 0xED3_1 — group / friend poke (the "戳一戳" / "拍一拍" notice).
//
// Same envelope shape for both flavors; the discriminator is which of
// `groupUin` / `friendUin` is set:
// - group poke: groupUin = peer (the group), friendUin = 0,
// uin = targetUin (the member being poked) or peer
// - friend poke: groupUin = 0, friendUin = peer (the friend's uin),
// uin = targetUin or peer
// `ext` is always 0; QQ-NT uses it for "double-poke" / "shake" subtypes
// that SnowLuma hasn't exposed yet.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbPoke } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SendPoke {
export const command = 0xED3;
export const subCommand = 1;
export interface Params {
isGroup: boolean;
/** Group uin (if isGroup) or friend uin (otherwise). */
peerUin: number;
/** Specific member to poke in a group; defaults to peer for friend pokes. */
targetUin?: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbPoke => ({
uin: p.targetUin ?? p.peerUin,
groupUin: p.isGroup ? p.peerUin : 0,
friendUin: p.isGroup ? 0 : p.peerUin,
ext: 0,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbPoke>): Uint8Array =>
protobuf_encode<OidbBase<OidbPoke>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SendPoke, params);
}
@@ -0,0 +1,44 @@
// 0xEAC — set / unset a group "essence" message (群精华).
// subCommand 1 = mark as essence, 2 = remove from essence
//
// `random` is the message's wire-level random field (carried through
// from the original send so the server can resolve the canonical
// message identity).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbEssence } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetEssence {
export const command = 0xEAC;
export interface Params {
groupId: number;
sequence: number;
random: number;
/** true = mark essence (subCmd 1), false = unmark (subCmd 2). */
enable: boolean;
}
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.enable ? 1 : 2;
export const serialize = (_ctx: Deps, p: Params): OidbEssence => ({
groupUin: p.groupId,
sequence: p.sequence,
random: p.random,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbEssence>): Uint8Array =>
protobuf_encode<OidbBase<OidbEssence>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetEssence, params);
}
@@ -0,0 +1,60 @@
// 0x112E_1 — relay an inline-keyboard-button click event to the bot
// owning the button (so the bot can react). All identity fields go on
// the wire as uint_64 → callers pass JS numbers and we widen here.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x112eReq, Oidb0x112eResp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface InlineButtonClickResult {
result: number;
errMsg: string;
status: 0;
promptText: string;
promptType: 0;
promptIcon: 0;
}
export namespace ClickInlineKeyboardButton {
export const command = 0x112E;
export const subCommand = 1;
export interface Params {
groupId: number;
botAppid: number;
buttonId: string;
callbackData: string;
msgSeq: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x112eReq => ({
botAppid: BigInt(p.botAppid),
msgSeq: BigInt(p.msgSeq),
buttonId: String(p.buttonId),
callbackData: String(p.callbackData || ''),
unknown7: 0,
groupId: BigInt(p.groupId),
unknown9: 1,
});
export const deserialize = (_ctx: Deps, body: Oidb0x112eResp): InlineButtonClickResult => ({
result: Number(body.result || 0),
errMsg: body.errMsg || '',
status: 0,
promptText: body.promptText || '',
promptType: 0,
promptIcon: 0,
});
export const encode = (env: OidbBase<Oidb0x112eReq>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x112eReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x112eResp> =>
protobuf_decode<OidbBase<Oidb0x112eResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<InlineButtonClickResult> =>
invokeOidb(deps, ClickInlineKeyboardButton, params);
}
@@ -0,0 +1,48 @@
// 0xEB7_1 — group daily sign-in (群打卡).
//
// **Wire name case**: historically SnowLuma sent this cmd as
// `OidbSvcTrpcTcp.0xEB7_1` (uppercase EB7) while every other cmd uses
// lowercase. The server accepts either, but the refactor's hard rule
// is "wire-byte-equal to before", so we keep the uppercase via the
// `wireName` override. This is the ONLY cmd in the codebase with this
// quirk — every new cmd should use the default lowercase scheme.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xeb7Req, Oidb0xeb7Resp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SendGroupSign {
export const command = 0xEB7;
export const subCommand = 1;
/** Override the default lowercase wire-name to preserve the
* historic `OidbSvcTrpcTcp.0xEB7_1` byte-for-byte. */
export const wireName = (): string => 'OidbSvcTrpcTcp.0xEB7_1';
export interface Params {
groupId: number;
}
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
export const serialize = (ctx: Deps, p: Params): Oidb0xeb7Req => ({
signInInfo: {
uin: String(ctx.identity.uin),
groupId: String(p.groupId),
version: '9.0.90',
},
});
export const deserialize = (_ctx: Deps, _: Oidb0xeb7Resp): void => {};
export const encode = (env: OidbBase<Oidb0xeb7Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0xeb7Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0xeb7Resp> =>
protobuf_decode<OidbBase<Oidb0xeb7Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SendGroupSign, params);
}
@@ -0,0 +1,45 @@
// 0x990_2 — server-side English → Chinese translation. Returns the
// translated `dstWords` 1:1 paired with the input `words`. Magic
// constants `tag10=1` / `tag12=1` are documented as "always 1" in
// production traffic (purpose unknown).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x990Req, Oidb0x990Resp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace TranslateEnToZh {
export const command = 0x990;
export const subCommand = 2;
export interface Params {
words: string[];
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x990Req => ({
translateReq: {
srcLang: 'en',
dstLang: 'zh',
words: p.words,
},
tag10: 1,
tag12: 1,
});
export const deserialize = (_ctx: Deps, body: Oidb0x990Resp): string[] => {
const resp = body.translateResp;
if (!resp) throw new Error('translate response empty');
return resp.dstWords || [];
};
export const encode = (env: OidbBase<Oidb0x990Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x990Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x990Resp> =>
protobuf_decode<OidbBase<Oidb0x990Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string[]> =>
invokeOidb(deps, TranslateEnToZh, params);
}
@@ -0,0 +1,100 @@
// 0x7ED_12 — fetch QQ "thumbs up" (赞) summary for self or another user.
//
// Self lookup needs the bot's own UID, hence the `identity` dependency.
// For other users we use `resolveUserUid` to translate the uin first.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export interface LikeInfo {
uid: string;
time: number;
favoriteInfo: {
total_count: number;
last_time: number;
today_count: number;
userInfos: never[];
};
voteInfo: {
total_count: number;
new_count: number;
new_nearby_count: number;
last_visit_time: number;
userInfos: never[];
};
}
export namespace GetLike {
export const command = 0x7ED;
export const subCommand = 12;
export interface Params {
/** Omit / 0 → query self. */
userId?: number;
start?: number;
limit?: number;
}
export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<Oidb0x7edReq> => {
const targetUid = p.userId
? await ctx.resolveUserUid(p.userId)
: await resolveSelf(ctx);
if (!targetUid) throw new Error('target uid not found');
return {
targetUid,
basic: 1,
vote: 1,
favorite: 1,
start: p.start ?? 0,
limit: p.limit ?? 10,
};
};
export const deserialize = (_ctx: Deps, body: Oidb0x7edResp): LikeInfo => {
const data = body.userLikeInfos?.[0];
if (!data) throw new Error('get profile like info empty');
return {
uid: data.uid ?? '',
time: Number(data.time ?? 0),
favoriteInfo: {
total_count: data.favoriteInfo?.totalCount || 0,
last_time: Number(data.favoriteInfo?.lastTime || 0),
today_count: data.favoriteInfo?.newCount || 0,
userInfos: [],
},
voteInfo: {
total_count: data.voteInfo?.totalCount || 0,
new_count: data.voteInfo?.newCount || 0,
new_nearby_count: 0,
last_visit_time: Number(data.voteInfo?.lastTime || 0),
userInfos: [],
},
};
};
export const encode = (env: OidbBase<Oidb0x7edReq>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x7edReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x7edResp> =>
protobuf_decode<OidbBase<Oidb0x7edResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<LikeInfo> =>
invokeOidb(deps, GetLike, params);
}
async function resolveSelf(deps: Pick<BridgeContext, 'identity' | 'resolveUserUid'>): Promise<string> {
// Mirrors `apis/shared.ts::resolveSelfUid` — kept inline here so the
// namespace is self-contained against just the BridgeContext slice.
const cached = deps.identity.selfUid;
if (cached) return cached;
const selfUin = Number(deps.identity.uin);
if (!Number.isFinite(selfUin) || selfUin <= 0) {
throw new Error('self uid is unavailable');
}
return deps.resolveUserUid(selfUin);
}
@@ -0,0 +1,52 @@
// 0xE17_0 — fetch the unidirectional friend block list. Wire name is
// non-standard (`MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`) — uses
// the `wireName` override to bypass the default
// `OidbSvcTrpcTcp.0xNNNN_N` scheme.
//
// Request and response carry a JSON-encoded string in a single
// protobuf field, so the namespace's `serialize` / `deserialize` do
// the JSON marshalling.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xe17Req, Oidb0xe17Resp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace GetUnidirectionalFriendList {
export const command = 0xE17;
export const subCommand = 0;
/** Wire name override — this cmd lives outside the standard
* `OidbSvcTrpcTcp.0xNNNN_N` namespace. */
export const wireName = (): string => 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0';
export interface Params {}
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
export const serialize = (ctx: Deps, _p: Params): Oidb0xe17Req => {
const reqObj = {
uint64_uin: String(ctx.identity.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
};
return { jsonBody: JSON.stringify(reqObj) };
};
export const deserialize = (_ctx: Deps, body: Oidb0xe17Resp): unknown[] => {
if (!body || !body.jsonBody) throw new Error('get unidirectional friend list empty');
const parsed = JSON.parse(body.jsonBody);
return parsed.rpt_block_list || [];
};
export const encode = (env: OidbBase<Oidb0xe17Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0xe17Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0xe17Resp> =>
protobuf_decode<OidbBase<Oidb0xe17Resp>>(bytes);
export const invoke = (deps: Deps): Promise<unknown[]> =>
invokeOidb(deps, GetUnidirectionalFriendList, {});
}
@@ -0,0 +1,47 @@
// 0xCD4_1 — set typing / recording / etc. "input status" indicator
// shown to a peer in a 1:1 chat.
//
// Resolves the target uin → uid via the identity service before
// building the body. `chatType: 0` is the wire constant for friend
// chats (the only flavor SnowLuma currently supports here).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xcd4Req, Oidb0xcd4Resp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetInputStatus {
export const command = 0xCD4;
export const subCommand = 1;
export interface Params {
userId: number;
eventType: number;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<Oidb0xcd4Req> => {
const targetUid = await ctx.resolveUserUid(p.userId);
if (!targetUid) throw new Error('target uid not found');
return {
reqBody: {
uid: targetUid,
chatType: 0,
eventType: p.eventType,
},
};
};
export const deserialize = (_ctx: Deps, _: Oidb0xcd4Resp): void => {};
export const encode = (env: OidbBase<Oidb0xcd4Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0xcd4Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0xcd4Resp> =>
protobuf_decode<OidbBase<Oidb0xcd4Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetInputStatus, params);
}
@@ -0,0 +1,50 @@
// 0x112A_2 — write profile string/int field-value pairs.
//
// SnowLuma's facade currently exposes only nickname (field 20002) and
// personalNote (field 102) but the underlying wire supports arbitrary
// (fieldId, value) tuples. The `invoke` short-circuits when both
// inputs are undefined so the facade's historic no-op-on-no-input
// behaviour is preserved (no wasted SSO round-trip).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x112aResp, OidbSetProfile } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetProfile {
export const command = 0x112A;
export const subCommand = 2;
export interface Params {
nickname?: string;
personalNote?: string;
}
/** Needs identity to read `uin` for the request body. */
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
export const serialize = (ctx: Deps, p: Params): OidbSetProfile => {
const stringProfiles: { fieldId: number; value: string }[] = [];
if (p.nickname !== undefined) stringProfiles.push({ fieldId: 20002, value: p.nickname });
if (p.personalNote !== undefined) stringProfiles.push({ fieldId: 102, value: p.personalNote });
return { uin: BigInt(ctx.identity.uin), stringProfiles };
};
export const deserialize = (_ctx: Deps, _: Oidb0x112aResp): void => {};
export const encode = (env: OidbBase<OidbSetProfile>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetProfile>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x112aResp> =>
protobuf_decode<OidbBase<Oidb0x112aResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> => {
// No-op when there's nothing to write — preserves the facade's
// historic short-circuit (avoid a wasted SSO round-trip).
if (params.nickname === undefined && params.personalNote === undefined) {
return Promise.resolve();
}
return invokeOidb(deps, SetProfile, params);
};
}
@@ -0,0 +1,39 @@
// 0x112A_2 — set the self "long nick" / personal signature. Same cmd
// as SetProfile but a different request shape (uses the single
// `profile: { tag, value }` field instead of the repeated string
// profiles list). Kept separate because the wire body is structurally
// different — proton needs distinct types so the codec is correctly
// monomorphized per call site.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x112aReq, Oidb0x112aResp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetSelfLongNick {
export const command = 0x112A;
export const subCommand = 2;
export interface Params {
longNick: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
export const serialize = (ctx: Deps, p: Params): Oidb0x112aReq => ({
uin: BigInt(ctx.identity.uin),
profile: { tag: 102, value: String(p.longNick) },
});
export const deserialize = (_ctx: Deps, _: Oidb0x112aResp): void => {};
export const encode = (env: OidbBase<Oidb0x112aReq>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x112aReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x112aResp> =>
protobuf_decode<OidbBase<Oidb0x112aResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetSelfLongNick, params);
}
@@ -0,0 +1,72 @@
// 0x9084_1 — fetch per-emoji reaction summary on a group message.
//
// Server returns the full summary unconditionally; the emoji_id /
// emoji_type / count fields in the request body are ignored by the
// summary handler but kept to mirror the working 0x9083_1 request shape
// (same `Pick` of fields the wire format prefers).
//
// "Used" entries carry (lastReactionTime, count, emojiType, emojiId).
// Catalog-tail entries (available reactions the server suggests but
// nobody has reacted with) carry only emojiType + emojiId — filtered
// out here so callers see only the meaningful subset.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x9084Req, Oidb0x9084Resp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchReactionSummary {
export const command = 0x9084;
export const subCommand = 1;
export interface Params {
groupId: number;
sequence: number;
}
export interface ReactionSummaryEntry {
emojiId: string;
emojiType: number;
count: number;
/** Unix epoch seconds of the most recent reaction. */
lastReactionTime: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x9084Req => ({
groupId: BigInt(p.groupId),
sequence: BigInt(p.sequence),
emojiId: '',
emojiType: 0,
cookie: new Uint8Array(0),
count: 0,
field12: 1,
});
export const deserialize = (_ctx: Deps, body: Oidb0x9084Resp): ReactionSummaryEntry[] => {
const out: ReactionSummaryEntry[] = [];
for (const e of body.entries ?? []) {
const count = e.count ?? 0;
if (count <= 0) continue; // skip catalog-tail entries
out.push({
emojiId: e.emojiId ?? '',
emojiType: e.emojiType ?? 1,
count,
lastReactionTime: Number(e.lastReactionTime ?? 0n),
});
}
return out;
};
export const encode = (env: OidbBase<Oidb0x9084Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x9084Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x9084Resp> =>
protobuf_decode<OidbBase<Oidb0x9084Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<ReactionSummaryEntry[]> =>
invokeOidb(deps, FetchReactionSummary, params);
}
@@ -0,0 +1,71 @@
// 0x9083_1 — historic "fetch reactor user list" cmd. CONFIRMED to be
// a real server endpoint (errorCode=0, trace string echoes the cmd
// name), but its reply is always a 4-byte minimal ack `18 01 20 01`
// regardless of the message / emoji / whether the bot just set a
// reaction. The actual "who reacted" data is NOT served via SSO at
// all — NTQQ's own client uses a wrapper-internal cache. SnowLuma
// mirrors that with `ReactionStore` (fed from GroupMsgEmojiLikeEvent
// push) on the OneBot side.
//
// This namespace exists as a legacy stub so older callers don't crash
// — `invoke` always returns an empty user list. Newer code should
// query `ReactionStore` instead.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x9083Req, Oidb0x9083Resp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetEmojiLikes {
export const command = 0x9083;
export const subCommand = 1;
export interface Params {
groupId: number;
sequence: number;
emojiId: string;
emojiType?: number;
count?: number;
/** Base64-encoded continuation cookie from a previous page. */
cookie?: string;
}
export interface Result {
users: Array<{ uin: number }>;
/** Base64 cookie for next page (empty when on last page). */
cookie: string;
isLast: boolean;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x9083Req => ({
groupId: BigInt(p.groupId),
sequence: BigInt(p.sequence),
emojiId: p.emojiId,
emojiType: p.emojiType ?? 1,
cookie: p.cookie ? Buffer.from(p.cookie, 'base64') : new Uint8Array(0),
field7: 0,
count: p.count ?? 10,
field12: 1,
});
export const deserialize = (_ctx: Deps, body: Oidb0x9083Resp): Result => {
const users: Array<{ uin: number }> = (body.inner?.userInfo ?? [])
.map(u => ({ uin: Number(u?.uin ?? 0) }))
.filter(u => u.uin > 0);
const cookie = body.cookie ? Buffer.from(body.cookie).toString('base64') : '';
return { users, cookie, isLast: !cookie };
};
export const encode = (env: OidbBase<Oidb0x9083Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x9083Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x9083Resp> =>
protobuf_decode<OidbBase<Oidb0x9083Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetEmojiLikes, params);
}
@@ -0,0 +1,54 @@
// 0x9082 — set / unset emoji reaction on a group message.
// subCommand 1 = set, 2 = unset
//
// Cross-checked against LagrangeV2
// `Internal/Packets/Service/SetGroupReaction.cs`:
// field 2 groupUin (long)
// field 3 sequence (ulong)
// field 4 code (string) ← emoji id
// field 5 type (ulong) ← 1 for QQ-face short id, 2 for unicode codepoint
// (Heuristic on `code.length > 3` matches Lagrange's
// `GroupAddReactionEvent.IsEmoji` discriminator.)
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetReaction {
export const command = 0x9082;
export interface Params {
groupId: number;
sequence: number;
/** Emoji code. 1–3 digits → QQ face (type=1); longer → unicode (type=2). */
code: string;
/** true = set reaction (subCommand 1), false = unset (subCommand 2). */
isSet: boolean;
}
/** Only the wire-send capability is needed. */
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.isSet ? 1 : 2;
export const serialize = (_ctx: Deps, p: Params): OidbGroupReaction => ({
groupUin: p.groupId,
sequence: p.sequence,
code: p.code,
type: p.code.length > 3 ? 2 : 1,
field6: false,
field7: false,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbGroupReaction>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupReaction>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetReaction, params);
}
@@ -0,0 +1,28 @@
// Tiny helpers shared between OIDB namespaces — kept here instead of
// `@snowluma/core/bridge/apis/shared` to avoid a circular dep
// (services live in @snowluma/protocol, facades in @snowluma/core).
/** Coerce numbers, strings, and bigints to a plain integer. */
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
return 0;
}
/** Standard OIDB sub-response check: throw a typed Error if retCode != 0.
* Prefers `wording` over `msg` for the human-facing message. */
export function ensureRetCodeZero(
operation: string, code: unknown, msg: unknown, wording: unknown,
): void {
const retCode = toInt(code);
if (retCode === 0) return;
const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error';
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
}
@@ -0,0 +1,43 @@
// 0x102A_1 — fetch a fresh `clientKey` (consumed by the ptlogin2 jump
// URL flow that swaps it for cookie-jar entries on qq.com subdomains).
//
// The server's `keyIndex` field is occasionally empty in the wild;
// every NapCat-derived implementation falls back to the literal "19"
// in that case — origin unknown but the value works.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbClientKeyReq, OidbClientKeyResp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface ClientKeyInfo {
clientKey: string;
keyIndex: string;
expireTime: string;
}
export namespace ForceFetchClientKey {
export const command = 0x102A;
export const subCommand = 1;
export interface Params {}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, _: Params): OidbClientKeyReq => ({});
export const deserialize = (_ctx: Deps, body: OidbClientKeyResp): ClientKeyInfo => ({
clientKey: body.clientKey || '',
keyIndex: String(body.keyIndex || '19'),
expireTime: String(body.expireTime || '1800'),
});
export const encode = (env: OidbBase<OidbClientKeyReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbClientKeyReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbClientKeyResp> =>
protobuf_decode<OidbBase<OidbClientKeyResp>>(bytes);
export const invoke = (deps: Deps): Promise<ClientKeyInfo> =>
invokeOidb(deps, ForceFetchClientKey, {});
}
@@ -0,0 +1,48 @@
// 0x102A_0 — request p_skey cookies for a list of qq.com subdomains.
// Used as the fallback when ptlogin2 jump doesn't emit a p_skey on
// the cookie set (intermittent server behaviour).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGetPskeyReq, OidbGetPskeyResp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetPskey {
export const command = 0x102A;
export const subCommand = 0;
export interface Params {
domainList: string[];
}
export interface Result {
domainPskeyMap: Map<string, string>;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGetPskeyReq => ({
domainList: p.domainList,
});
export const deserialize = (_ctx: Deps, body: OidbGetPskeyResp): Result => {
const domainPskeyMap = new Map<string, string>();
if (body.pskeyItems && Array.isArray(body.pskeyItems)) {
for (const item of body.pskeyItems) {
if (item.domain && item.pskey) {
domainPskeyMap.set(item.domain, item.pskey);
}
}
}
return { domainPskeyMap };
};
export const encode = (env: OidbBase<OidbGetPskeyReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGetPskeyReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGetPskeyResp> =>
protobuf_decode<OidbBase<OidbGetPskeyResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetPskey, params);
}
+348
View File
@@ -0,0 +1,348 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { formatEvent } from './format';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { BridgeEventBus } from './event-bus';
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
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' }>;
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
/**
* Refresh group + member roster as a side-effect. Resolves with
* whether any refresh actually ran (false when the group is unknown
* and `refreshGroupList` was false).
*/
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
/**
* Resolve a stranger profile by UID — used to fill in the requester's
* uin + nickname on group-join-request and friend-request events
* where the push only carries a uid. Mirrors Lagrange's
* `FetchUserInfoEvent.Create(targetUid)` path
* (`dev/Lagrange.Core/.../MessagingLogic.cs:215-224`). Returns null
* on lookup failure so the dispatch path can proceed with the bare
* uid-only event.
*/
resolveStrangerProfile(uid: string): Promise<{ uin: number; nickname: string } | null>;
/**
* Resolve the verify message ("postscript") + server sequence number
* for a pending group-join / group-invite. The OIDB push only
* carries the requester's UID + group uin — the actual verify text
* the user typed ("你们好" etc.) lives on the pending-request queue
* fetched via OIDB 0x10C0. NapCat surfaces this as
* `notify.postscript` from `nodeIKernelGroupService.getGroupNotifies`;
* we mirror that with an `fetchGroupRequests` lookup matched on
* `(groupId, uid, subType)`. Returns null when no matching pending
* request exists (e.g. it was already handled by another client).
*/
resolveGroupJoinRequest(
groupId: number, uid: string, subType: 'add' | 'invite',
): Promise<{ comment: string; sequence: number } | null>;
}
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) {
// 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) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
}
process(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.deps.identity);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
} else if (this.needsStrangerResolve(event)) {
void this.dispatchAfterStrangerResolve(event).catch((err) => {
this.log.warn('dispatchAfterStrangerResolve failed: %s',
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
} else {
this.handleSideEffects(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
}
}
} catch (e) {
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private emit(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.deps.events.emit(event);
}
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);
}
/** Group join requests carry only the requester's UID (no UIN). We
* fire a UID-form FetchUserProfile to resolve UIN + nickname before
* dispatch so the OneBot layer's `user_id` field is populated and
* the consumer bot's follow-up `get_stranger_info` lookup succeeds.
* Mirrors Lagrange's `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
*
* Also catches the legacy cache-pollution case: pre-fix builds
* stored `<requester_uid> → <groupUin>` in the identity DB when
* the decoder's fallback was `ctx.fromUin` (= group's own uin on
* a group-scoped push). After upgrade, the decoder's
* `resolveUidToUin` hits that polluted mapping and returns the
* groupUin instead of 0, so the `fromUin <= 0` guard alone would
* silently skip the resolve and re-emit the bug. Treating
* `fromUin === groupId` as bogus forces the async resolve to
* overwrite the polluted entry on the next event. */
private needsStrangerResolve(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_invite' }> {
if (event.kind !== 'group_invite' || !event.fromUid) return false;
if (event.fromUin <= 0) return true;
// Pollution signature — a real requester's uin would never equal
// the group's own uin. Force a re-resolve so the cache self-heals.
if (event.groupId > 0 && event.fromUin === event.groupId) return true;
return false;
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
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(this.eventLog, this.deps.identity, event);
this.emit(event);
}
private async dispatchAfterStrangerResolve(event: Extract<QQEventVariant, { kind: 'group_invite' }>): Promise<void> {
const uid = event.fromUid;
if (uid) {
// Fire profile + pending-request lookups in PARALLEL — they're
// independent OIDB calls (0xFE1_2 stranger profile + 0x10C0
// pending request queue). Both `Promise.allSettled` so a flake
// on one path doesn't kill the other.
const subType = event.subType === 'invite' ? 'invite' : 'add';
const [profileR, requestR] = await Promise.allSettled([
this.deps.resolveStrangerProfile(uid),
this.deps.resolveGroupJoinRequest(event.groupId, uid, subType),
]);
if (profileR.status === 'fulfilled' && profileR.value && profileR.value.uin > 0) {
event.fromUin = profileR.value.uin;
} else if (profileR.status === 'rejected') {
this.log.warn('failed to resolve stranger profile: uid=%s err=%s',
uid, profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason));
}
if (requestR.status === 'fulfilled' && requestR.value) {
// NapCat surfaces the verify text as `comment` on the OneBot
// event (`postscript` server-side). Without this the bot's
// approval-prompt template renders an empty body line — see
// `dev/NapCatQQ/.../napcat-onebot/index.ts:496-498`.
event.message = requestR.value.comment;
} else if (requestR.status === 'rejected') {
this.log.warn('failed to resolve group join request: groupId=%d uid=%s err=%s',
event.groupId, uid,
requestR.reason instanceof Error ? requestR.reason.message : String(requestR.reason));
}
}
this.handleSideEffects(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
}
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.deps.refreshMemberCache(
event.groupId,
!this.deps.identity.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.deps.identity.findUinByUid(event.userUid, event.groupId);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.deps.identity.findUinByUid(event.operatorUid, event.groupId);
if (uin !== null) event.operatorUin = uin;
}
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.deps.identity.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
}
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.deps.identity.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
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);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.deps.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.deps.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite': {
// Defensive: never cache a uid→uin mapping where uin equals
// the group's own uin — that's the pollution signature the
// legacy decoder fallback produced. Pass 0 so `rememberUidUin`
// skips the map write (it short-circuits on uin <= 0) but the
// user row still gets upserted with the uid + group context.
const uinForCache = event.fromUin > 0 && event.fromUin !== event.groupId
? event.fromUin : 0;
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: uinForCache,
source: 'group_request',
});
break;
}
default:
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);
}
}
+63
View File
@@ -0,0 +1,63 @@
export interface UserProfileInfo {
uin: number;
uid: string;
nickname: string;
remark: string;
qid: string;
sex: string;
age: number;
sign: string;
avatar: string;
/** QQ 等级 — OIDB 0xFE1_2 number-property key 105.
* Already requested in `fetchUserProfile` keys[]; LagrangeV2
* `FetchStrangerService.cs` confirms `// Level`. */
level: number;
}
export interface FriendInfo {
uin: number;
uid: string;
nickname: string;
remark: string;
}
export interface GroupMemberInfo {
uin: number;
uid: string;
nickname: string;
card: string;
role: string; // 'owner' | 'admin' | 'member'
level: number;
title: string;
joinTime: number;
lastSentTime: number;
shutUpTime: number;
}
export interface QQGroupInfo {
groupId: number;
groupName: string;
remark: string;
memberCount: number;
memberMax: number;
members: Map<number, GroupMemberInfo>;
}
export interface GroupRequestInfo {
groupId: number;
groupName: string;
targetUid: string;
targetUin: number;
targetName: string;
invitorUid: string;
invitorUin: number;
invitorName: string;
operatorUid: string;
operatorUin: number;
operatorName: string;
sequence: number;
state: number;
eventType: number;
comment: string;
filtered: boolean;
}
+250
View File
@@ -0,0 +1,250 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { createHash } from 'crypto';
import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
import { basename, join } from 'path';
import { tmpdir } from 'os';
// 群相册信息
export interface GroupAlbumInfo {
id: string;
name: string;
picNum: number;
createTime: number;
[key: string]: any;
}
// 获取群相册列表返回
export interface GroupAlbumListRet {
album: GroupAlbumInfo[];
[key: string]: any;
}
// 相册媒体信息
export interface AlbumMediaInfo {
photoId: string;
url: string;
uploadTime: number;
[key: string]: any;
}
/**
* 获取群相册列表
*/
export async function getGroupAlbumList(
cookieObject: Record<string, string>,
groupId: string,
uin: string
): Promise<GroupAlbumListRet | undefined> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
}
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?${new URLSearchParams({
random: '7570',
g_tk: bkn,
format: 'json',
inCharset: 'utf-8',
outCharset: 'utf-8',
qua: 'V1_IPH_SQ_6.2.0_0_HDBM_T',
cmd: 'qunGetAlbumList',
qunId: groupId,
qunid: groupId,
start: '0',
num: '1000',
uin,
getMemberRole: '0',
}).toString()}`;
const ret = await RequestUtil.HttpGetJson<{ data: GroupAlbumListRet }>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
if (!ret || typeof ret !== 'object') {
throw new Error('invalid response from qzone api');
}
return ret.data;
}
/**
* 创建群相册上传会话
*/
async function createAlbumUploadSession(
groupId: string,
albumId: string,
albumName: string,
filePath: string,
skey: string,
pskey: string,
imgMd5: string,
uin: string
): Promise<string> {
const imgSize = statSync(filePath).size;
const imgName = basename(filePath);
const bkn = getBknFromCookie({ skey });
const timestamp = Math.floor(Date.now() / 1000);
const body = {
control_req: [{
uin,
token: { type: 4, data: pskey, appid: 5 },
appid: 'qun',
checksum: imgMd5,
check_type: 0,
file_len: imgSize,
env: { refer: 'qzone', deviceInfo: 'h5' },
model: 0,
biz_req: {
sPicTitle: imgName,
sPicDesc: '',
sAlbumName: albumName,
sAlbumID: albumId,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType: 0,
iUpPicType: 0,
iBatchID: timestamp,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iNeedFeeds: 1,
iUploadTime: timestamp,
mapExt: { appid: 'qun', userid: groupId },
stExtendInfo: { mapParams: { photo_num: '1', video_num: '0', batch_num: '1' } },
},
session: '',
asy_upload: 0,
cmd: 'FileUpload',
}],
};
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`;
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>(
api,
'POST',
body,
{ Cookie: cookie, 'Content-Type': 'application/json' }
);
if (response.ret !== 0 || !response.data?.session) {
throw new Error(`创建上传会话失败: ${response.msg}`);
}
return response.data.session;
}
/**
* 修复后的上传图片分片方法
*/
async function uploadAlbumSlice(
session: string,
filePath: string,
// 移除 offset 和 chunkSize 参数,改为在内部控制
imgMd5: string,
skey: string,
pskey: string,
uin: string
): Promise<void> {
const img_size = statSync(filePath).size;
const slice_size = 16384; // 严格使用 16KB
const bkn = getBknFromCookie({ skey });
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const stream = createReadStream(filePath, { highWaterMark: slice_size });
let seq = 0;
let offset = 0;
for await (const chunk of stream) {
const end = Math.min(offset + chunk.length, img_size);
// 使用原生的 FormData 构建安全的 multipart 请求
const form = new FormData();
form.append('uin', uin);
form.append('appid', 'qun');
form.append('session', session);
form.append('offset', offset.toString());
form.append('data', new Blob([chunk as Buffer], { type: 'application/octet-stream' }), 'blob');
form.append('checksum', '');
form.append('check_type', '0');
form.append('retry', '0');
form.append('seq', seq.toString());
form.append('end', end.toString());
form.append('cmd', 'FileUpload');
form.append('slice_size', slice_size.toString());
form.append('biz_req.iUploadType', '0');
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${bkn}`;
// 放弃使用 HttpGetJson,改用原生 fetch,它能完美处理 FormData 和边界
const response = await fetch(api, {
method: 'POST',
headers: {
Cookie: cookie,
// 注意:不要手动设置 Content-Type,fetch 会自动加上带有正确 boundary 的 multipart/form-data
},
body: form,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json() as { ret: number, msg: string };
if (post.ret !== 0) {
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
}
offset += chunk.length;
seq++;
}
}
/**
* 上传图片到群相册
*/
export async function uploadImageToGroupAlbum(
cookieObject: Record<string, string>,
groupId: string,
albumId: string,
albumName: string,
filePath: string,
uin: string
): Promise<void> {
const { loadBinarySource } = await import('../highway/utils');
const loaded = await loadBinarySource(filePath, 'album image');
let tempFile: string | null = null;
let actualPath = filePath;
if (/^(https?:\/\/|base64:\/\/)/i.test(filePath)) {
tempFile = join(tmpdir(), `album_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`);
writeFileSync(tempFile, loaded.bytes);
actualPath = tempFile;
}
try {
const imgMd5 = createHash('md5').update(loaded.bytes).digest('hex');
// const imgSize = loaded.bytes.length;
const skey = cookieObject.skey || '';
const pskey = cookieObject.p_skey || '';
const session = await createAlbumUploadSession(groupId, albumId, albumName, actualPath, skey, pskey, imgMd5, uin);
await uploadAlbumSlice(session, actualPath, imgMd5, skey, pskey, uin);
} finally {
if (tempFile) {
try { unlinkSync(tempFile); } catch { /* ignore */ }
}
}
}
@@ -0,0 +1,71 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('Bridge.Web');
// 定义接口返回类型
export interface GroupEssenceMsgRet {
retcode: number;
data: {
is_end: boolean;
msg_list: any[]; // 具体结构视需要补充
[key: string]: any;
};
[key: string]: any;
}
/**
* 分页获取群精华消息
*/
export async function getGroupEssenceMsg(
cookieObject: Record<string, string>,
groupCode: string,
pageStart: number = 0,
pageLimit: number = 50
): Promise<GroupEssenceMsgRet | undefined> {
const bkn = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
bkn: bkn,
page_start: pageStart.toString(),
page_limit: pageLimit.toString(),
group_code: groupCode,
}).toString()}`;
try {
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
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;
}
}
/**
* 获取所有群精华消息 (最多循环 20 页)
*/
export async function getGroupEssenceMsgAll(
cookieObject: Record<string, string>,
groupCode: string
): Promise<GroupEssenceMsgRet[]> {
const ret: GroupEssenceMsgRet[] = [];
for (let i = 0; i < 20; i++) {
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
if (!data) break;
ret.push(data);
if (data.data?.is_end) break;
}
return ret;
}
+53
View File
@@ -0,0 +1,53 @@
import { RequestUtil, cookieToString } from './request-util';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('Bridge.Web');
export enum WebHonorType {
TALKATIVE = 'talkative',
PERFORMER = 'performer',
LEGEND = 'legend',
EMOTION = 'emotion',
ALL = 'all',
}
async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number) {
let resJson;
try {
const res = await RequestUtil.HttpGetText(
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
gc: groupCode,
type: type.toString(),
}).toString()}`,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
if (match?.[1]) {
resJson = JSON.parse(match[1].trim());
}
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
} catch (e) {
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
}
}
export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number) {
try {
const data = await fetchHonorData(cookieObject, groupCode, type);
if (!data) return [];
return data.map((item: any) => ({
user_id: item?.uin,
nickname: item?.name,
avatar: item?.avatar,
description: item?.desc,
}));
} catch (e) {
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
}
}
+273
View File
@@ -0,0 +1,273 @@
import { RequestUtil, cookieToString } from './request-util';
import https from 'node:https';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('Bridge.Web');
export interface SetNoticeRetSuccess {
ec?: number;
em?: string;
[key: string]: any;
}
export interface UploadImageRetSuccess {
ec?: number;
id?: string;
[key: string]: any;
}
export interface WebApiGroupNoticeFeed {
fid: string;
u: number;
pubt: number;
msg: {
text: string;
pics?: Array<{ id: string; w: number; h: number }>;
};
settings: any;
read_num: number;
[key: string]: any;
}
export interface WebApiGroupNoticeRet {
ec: number;
em?: string;
feeds?: Record<string, WebApiGroupNoticeFeed>;
[key: string]: any;
}
export function calculateBkn(key: string): string {
let hash = 5381;
for (let i = 0; i < key.length; i++) {
const code = key.charCodeAt(i);
hash = hash + (hash << 5) + code;
}
return (hash & 0x7FFFFFFF).toString();
}
/**
* 发送群公告 Web API
*/
export async function setGroupNoticeWebAPI(
cookieObject: Record<string, string>,
groupCode: string,
content: string,
pinned: number = 0,
type: number = 1,
isShowEditCard: number = 1,
tipWindowType: number = 1,
confirmRequired: number = 1,
picId: string = '',
imgWidth: number = 540,
imgHeight: number = 300
): Promise<SetNoticeRetSuccess | undefined> {
try {
// 分别获取 skey 和 p_skey
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
//
// console.log(skey)
// console.log(pskey)
//
// console.log(urlBkn);
// console.log(bodyBkn)
const settings = JSON.stringify({
is_show_edit_card: isShowEditCard,
tip_window_type: tipWindowType,
confirm_required: confirmRequired,
});
const bodyParams: Record<string, string> = {
qid: groupCode,
bkn: bodyBkn,
text: content,
pinned: pinned.toString(),
type: type.toString(),
settings,
};
if (picId !== '') {
bodyParams.pic = picId;
bodyParams.imgWidth = imgWidth.toString();
bodyParams.imgHeight = imgHeight.toString();
}
// 注意这里:URL 必须使用 skey 算出来的 bkn
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret;
} catch (e) {
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
}
/**
* 获取群公告列表 Web API
*/
export async function getGroupNoticeWebAPI(
cookieObject: Record<string, string>,
groupCode: string,
start: number = -1, // -1 表示第一页
count: number = 20 // 抓包中是 10,你可以根据需要调整
): Promise<WebApiGroupNoticeRet | undefined> {
try {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
const bodyParams = new URLSearchParams({
qid: groupCode,
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
ft: '23',
s: start.toString(), // 分页游标
n: count.toString(), // 获取数量
i: '1',
ni: '1'
}).toString();
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
url,
'POST',
bodyParams,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
},
true,
false
);
// console.log(JSON.stringify(ret, null, 2));
return ret?.ec === 0 ? ret : undefined;
} catch (e) {
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
}
/**
* 上传群公告图片 Web API
*/
export async function uploadGroupNoticeImage(
cookieObject: Record<string, string>,
imageBuffer: Buffer
): Promise<{ id: string; width: number; height: number } | undefined> {
try {
const bkn = calculateBkn(cookieObject['skey']);
const boundary = `-----------------------------${Date.now()}`;
const parts: Buffer[] = [];
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
parts.push(imageBuffer);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
const body = Buffer.concat(parts);
const options = {
hostname: 'web.qun.qq.com',
path: '/cgi-bin/announce/upload_img',
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length,
'Cookie': cookieToString(cookieObject),
},
};
return new Promise((resolve) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
try {
const result = JSON.parse(data) as UploadImageRetSuccess;
if (result.ec === 0 && result.id) {
const unescapedIdStr = result.id.replace(/&quot;/g, '"');
const idObj = JSON.parse(unescapedIdStr);
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
} else {
resolve(undefined);
}
} catch {
resolve(undefined);
}
});
});
req.on('error', (err) => {
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
resolve(undefined);
});
req.write(body);
req.end();
});
} catch (e) {
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
}
/**
* 删除群公告 Web API
*/
export async function deleteGroupNotice(
cookieObject: Record<string, string>,
groupCode: string,
fid: string
): Promise<boolean> {
try {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
const params = new URLSearchParams({
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
fid: fid,
qid: groupCode,
}).toString();
// 注意这里:URL 拼接 urlBkn
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
params,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret?.ec === 0;
} catch (e) {
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
return false;
}
}
+127
View File
@@ -0,0 +1,127 @@
import https from 'node:https';
import http from 'node:http';
export class RequestUtil {
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
const client = url.startsWith('https') ? https : http;
return new Promise((resolve, reject) => {
const req = client.get(url, (res) => {
const cookies: { [key: string]: string; } = {};
res.on('data', () => { }); // 必须消耗流
res.on('end', () => {
this.handleRedirect(res, url, cookies)
.then(resolve)
.catch(reject);
});
if (res.headers['set-cookie']) {
this.extractCookies(res.headers['set-cookie'], cookies);
}
});
req.on('error', (error: Error) => {
reject(error);
});
});
}
private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
if (res.statusCode === 301 || res.statusCode === 302) {
if (res.headers.location) {
const redirectUrl = new URL(res.headers.location, url);
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
return { ...cookies, ...redirectCookies };
}
}
return cookies;
}
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
setCookieHeaders.forEach((cookie) => {
const parts = cookie.split(';')[0]?.split('=');
if (parts) {
const key = parts[0];
const value = parts[1];
if (key && value && key.length > 0 && value.length > 0) {
cookies[key] = value;
}
}
});
}
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: {
[key: string]: string;
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
const option = new URL(url);
const protocol = url.startsWith('https://') ? https : http;
const options = {
hostname: option.hostname,
port: option.port,
path: option.pathname + option.search,
method,
headers,
};
return new Promise((resolve, reject) => {
const req = protocol.request(options, (res: http.IncomingMessage) => {
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
if (maxRedirects <= 0) {
reject(new Error('Too many redirects'));
return;
}
const redirectUrl = new URL(res.headers.location, url).href;
this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
.then(resolve)
.catch(reject);
return;
}
let responseBody = '';
res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
res.on('end', () => {
try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
if (isJsonRet) {
resolve(JSON.parse(responseBody) as T);
} else {
resolve(responseBody as T);
}
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
}
} catch (parseError: any) {
reject(new Error(parseError.message));
}
});
});
req.on('error', (error: Error) => reject(error));
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
req.write(isArgJson ? JSON.stringify(data) : data);
}
req.end();
});
}
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
return this.HttpGetJson<string>(url, method, data, headers, false, false);
}
}
export function cookieToString(cookieObject: Record<string, string>): string {
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
export function getBknFromCookie(cookieObject: Record<string, string>): string {
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return (hash & 2147483647).toString();
}