This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+49 -45
View File
@@ -27,55 +27,59 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender';
* 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;
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;
// ── 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>;
// ── 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;
// ── 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;
// ── 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;
}
+12 -13
View File
@@ -11,18 +11,17 @@ import type { OidbBase } from '@snowluma/proto-defs/oidb';
* (default false) for genuinely UID-keyed calls.
*/
export function makeOidbEnvelope<T>(
oidbCmd: number,
subCmd: number,
body: T,
isUid: boolean = false,
oidbCmd: number,
subCmd: number,
body: T,
isUid: boolean = false,
): OidbBase<T> {
return {
command: oidbCmd,
subCommand: subCmd,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
};
return {
command: oidbCmd,
subCommand: subCmd,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
};
}
+106 -75
View File
@@ -1,8 +1,5 @@
import { toHex } from '@snowluma/common/hex';
import type {
DatalineMsgBody,
DatalineTextMsg,
} from '@snowluma/proto-defs/dataline';
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MessageElement } from '../events';
import { appIdForTerType, DATALINE_SELF_TER_TYPE } from './device-contacts';
@@ -16,90 +13,124 @@ const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
export function encodeDatalineText(params: {
selfUin: number;
srcTerType?: number;
dstTerType: number;
text: string;
selfUin: number;
srcTerType?: number;
dstTerType: number;
text: string;
}): Uint8Array {
const srcTerType = params.srcTerType ?? DATALINE_SELF_TER_TYPE;
const textBytes = textEncoder.encode(params.text);
const buf = protobuf_encode<DatalineTextMsg>({
items: [{ type: DATALINE_TEXT_ITEM, text: textBytes }],
});
const selfUin = BigInt(params.selfUin);
return protobuf_encode<DatalineMsgBody>({
subCmd: DATALINE_SUBCMD_GENERIC,
header: {
srcAppId: appIdForTerType(srcTerType),
srcInstId: 1,
dstAppId: appIdForTerType(params.dstTerType),
dstInstId: 1,
dstUin: selfUin,
srcUin: selfUin,
srcTerType,
dstTerType: params.dstTerType,
},
generic: {
sessionId: BigInt(Date.now()),
size: 1,
index: 0,
type: DATALINE_GENERIC_TEXT,
buf,
},
});
const srcTerType = params.srcTerType ?? DATALINE_SELF_TER_TYPE;
const textBytes = textEncoder.encode(params.text);
const buf = protobuf_encode<DatalineTextMsg>({
items: [{ type: DATALINE_TEXT_ITEM, text: textBytes }],
});
const selfUin = BigInt(params.selfUin);
return protobuf_encode<DatalineMsgBody>({
subCmd: DATALINE_SUBCMD_GENERIC,
header: {
srcAppId: appIdForTerType(srcTerType),
srcInstId: 1,
dstAppId: appIdForTerType(params.dstTerType),
dstInstId: 1,
dstUin: selfUin,
srcUin: selfUin,
srcTerType,
dstTerType: params.dstTerType,
},
generic: {
sessionId: BigInt(Date.now()),
size: 1,
index: 0,
type: DATALINE_GENERIC_TEXT,
buf,
},
});
}
export function decodeDatalineMsgBody(bytes: Uint8Array): DatalineMsgBody | undefined {
return protobuf_decode<DatalineMsgBody>(bytes);
return protobuf_decode<DatalineMsgBody>(bytes);
}
export function elementsFromDatalineBody(body: DatalineMsgBody): MessageElement[] {
const elements: MessageElement[] = [];
if (body.subCmd === DATALINE_SUBCMD_GENERIC || body.generic) {
const genericType = body.generic?.type ?? 0;
if (genericType === 0 || genericType === DATALINE_GENERIC_TEXT) {
const text = decodeGenericText(body.generic?.buf);
if (text.length > 0) elements.push({ type: 'text', text });
const elements: MessageElement[] = [];
if (body.subCmd === DATALINE_SUBCMD_GENERIC || body.generic) {
const genericType = body.generic?.type ?? 0;
if (genericType === 0 || genericType === DATALINE_GENERIC_TEXT) {
const text = decodeGenericText(body.generic?.buf);
if (text.length > 0) {
elements.push({ type: 'text', text });
}
}
}
}
if (body.subCmd === DATALINE_SUBCMD_FTN || (body.ftn && body.ftn.length > 0)) {
for (const notify of body.ftn ?? []) {
const fileName = notify.fileName?.trim();
if (!fileName && notify.fileIndex == null && notify.sessionId == null) continue;
const fileSize = notify.fileLen != null ? Number(notify.fileLen) : undefined;
elements.push({
type: 'file',
fileId: notify.fileIndex || (notify.sessionId != null ? String(notify.sessionId) : undefined),
fileName: fileName || undefined,
fileSize: fileSize != null && Number.isFinite(fileSize) ? fileSize : undefined,
md5Hex: notify.fileMd5 && notify.fileMd5.length > 0 ? toHex(notify.fileMd5) : undefined,
});
if (body.subCmd === DATALINE_SUBCMD_FTN || (body.ftn && body.ftn.length > 0)) {
for (const notify of body.ftn ?? []) {
const fileName = notify.fileName?.trim();
if (!fileName && notify.fileIndex == null && notify.sessionId == null) {
continue;
}
const fileSize = notify.fileLen != null ? Number(notify.fileLen) : undefined;
elements.push({
type: 'file',
fileId:
notify.fileIndex ||
(notify.sessionId != null ? String(notify.sessionId) : undefined),
fileName: fileName || undefined,
fileSize: fileSize != null && Number.isFinite(fileSize) ? fileSize : undefined,
md5Hex:
notify.fileMd5 && notify.fileMd5.length > 0 ? toHex(notify.fileMd5) : undefined,
});
}
}
}
return elements;
return elements;
}
function decodeGenericText(buf: Uint8Array | undefined): string {
if (!buf || buf.length === 0) return '';
const parsed = protobuf_decode<DatalineTextMsg>(buf);
const parts: string[] = [];
for (const item of parsed?.items ?? []) {
if (!item.text || item.text.length === 0) continue;
parts.push(textDecoder.decode(item.text));
}
return parts.join('');
if (!buf || buf.length === 0) {
return '';
}
const parsed = protobuf_decode<DatalineTextMsg>(buf);
const parts: string[] = [];
for (const item of parsed?.items ?? []) {
if (!item.text || item.text.length === 0) {
continue;
}
parts.push(textDecoder.decode(item.text));
}
return parts.join('');
}
export function datalineTextFromElements(elements: readonly MessageElement[]): string {
if (elements.length === 0) throw new Error('message is empty');
const unsupported = elements.find((element) => element.type !== 'text');
if (unsupported) {
throw new Error(`this contact only accepts text messages, got ${unsupported.type}`);
}
const text = elements
.filter((element): element is Extract<MessageElement, { type: 'text' }> => element.type === 'text')
.map((element) => element.text)
.join('');
if (text.length === 0) throw new Error('message is empty');
return text;
if (elements.length === 0) {
throw new Error('message is empty');
}
const unsupported = elements.find((element) => element.type !== 'text');
if (unsupported) {
throw new Error(`this contact only accepts text messages, got ${unsupported.type}`);
}
const text = elements
.filter(
(element): element is Extract<MessageElement, { type: 'text' }> =>
element.type === 'text',
)
.map((element) => element.text)
.join('');
if (text.length === 0) {
throw new Error('message is empty');
}
return text;
}
+56 -42
View File
@@ -1,10 +1,7 @@
import type { FriendMessage } from '../events';
import type { MsgPushContext } from '../msg-push/context';
import { decodeDatalineMsgBody, elementsFromDatalineBody } from './codec';
import {
DATALINE_SELF_TER_TYPE,
findDatalineDeviceByTerType,
} from './device-contacts';
import { DATALINE_SELF_TER_TYPE, findDatalineDeviceByTerType } from './device-contacts';
/**
* Incoming my-device chats reuse the private-file push type but carry a
@@ -12,47 +9,64 @@ import {
* contact — both sides of the wire use the logged-in account number.
*/
export function tryDecodeDatalineFriendMessage(ctx: MsgPushContext): FriendMessage | null {
if (ctx.head.msgType !== 529 || ctx.head.subType !== 7) return null;
const raw = ctx.body?.msgContent;
if (!raw || raw.length === 0) return null;
const body = decodeDatalineMsgBody(raw);
if (!body) return null;
if (
body.subCmd == null
&& !body.header
&& !body.generic
&& !(body.ftn && body.ftn.length > 0)
) {
return null;
}
if (ctx.head.msgType !== 529 || ctx.head.subType !== 7) {
return null;
}
const elements = elementsFromDatalineBody(body);
const srcTer = body.header?.srcTerType ?? 0;
const dstTer = body.header?.dstTerType ?? 0;
const sentBySelf = srcTer === DATALINE_SELF_TER_TYPE;
const peerTer = peerTerType(srcTer, dstTer);
const peer = findDatalineDeviceByTerType(peerTer);
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
const raw = ctx.body?.msgContent;
return {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: sentBySelf ? ctx.selfUin : (peer?.uin ?? ctx.fromUin),
senderUid: sentBySelf ? ctx.fromUid : (peer?.uid ?? ctx.fromUid),
...(peer ? { peerUin: peer.uin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
senderNick: sentBySelf ? '' : (peer?.name ?? ''),
};
if (!raw || raw.length === 0) {
return null;
}
const body = decodeDatalineMsgBody(raw);
if (!body) {
return null;
}
if (
body.subCmd == null &&
!body.header &&
!body.generic &&
!(body.ftn && body.ftn.length > 0)
) {
return null;
}
const elements = elementsFromDatalineBody(body);
const srcTer = body.header?.srcTerType ?? 0;
const dstTer = body.header?.dstTerType ?? 0;
const sentBySelf = srcTer === DATALINE_SELF_TER_TYPE;
const peerTer = peerTerType(srcTer, dstTer);
const peer = findDatalineDeviceByTerType(peerTer);
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
return {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: sentBySelf ? ctx.selfUin : (peer?.uin ?? ctx.fromUin),
senderUid: sentBySelf ? ctx.fromUid : (peer?.uid ?? ctx.fromUid),
...(peer ? { peerUin: peer.uin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7fffffff,
elements,
senderNick: sentBySelf ? '' : (peer?.name ?? ''),
};
}
function peerTerType(srcTer: number, dstTer: number): number {
if (srcTer !== DATALINE_SELF_TER_TYPE && srcTer > 0) return srcTer;
if (dstTer !== DATALINE_SELF_TER_TYPE && dstTer > 0) return dstTer;
return dstTer || srcTer || DATALINE_SELF_TER_TYPE;
if (srcTer !== DATALINE_SELF_TER_TYPE && srcTer > 0) {
return srcTer;
}
if (dstTer !== DATALINE_SELF_TER_TYPE && dstTer > 0) {
return dstTer;
}
return dstTer || srcTer || DATALINE_SELF_TER_TYPE;
}
@@ -7,75 +7,75 @@ export const DATALINE_TER_PHONE = 2;
export const DATALINE_TER_PAD = 3;
/** Stable OneBot user_ids reserved for the three official device peers. */
export const DATALINE_UIN_PC = 0x7E000001;
export const DATALINE_UIN_PHONE = 0x7E000002;
export const DATALINE_UIN_PAD = 0x7E000003;
export const DATALINE_UIN_PC = 0x7e000001;
export const DATALINE_UIN_PHONE = 0x7e000002;
export const DATALINE_UIN_PAD = 0x7e000003;
export interface DatalineDeviceContact {
readonly terType: number;
readonly uid: string;
readonly name: string;
readonly uin: number;
readonly terType: number;
readonly uid: string;
readonly name: string;
readonly uin: number;
}
export interface DatalineFriendEntry {
user_id: number;
nickname: string;
remark: string;
user_id: number;
nickname: string;
remark: string;
}
export const DATALINE_DEVICES: readonly DatalineDeviceContact[] = [
{
terType: DATALINE_TER_PC,
uid: 'u_rK7NMsbv2ZjEGPdCuOiCfw',
name: '我的电脑',
uin: DATALINE_UIN_PC,
},
{
terType: DATALINE_TER_PHONE,
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
name: '我的手机',
uin: DATALINE_UIN_PHONE,
},
{
terType: DATALINE_TER_PAD,
uid: 'u_l7jpPIZxQo0mzJwoEt-SKw',
name: '我的Pad',
uin: DATALINE_UIN_PAD,
},
{
terType: DATALINE_TER_PC,
uid: 'u_rK7NMsbv2ZjEGPdCuOiCfw',
name: '我的电脑',
uin: DATALINE_UIN_PC,
},
{
terType: DATALINE_TER_PHONE,
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
name: '我的手机',
uin: DATALINE_UIN_PHONE,
},
{
terType: DATALINE_TER_PAD,
uid: 'u_l7jpPIZxQo0mzJwoEt-SKw',
name: '我的Pad',
uin: DATALINE_UIN_PAD,
},
];
const BY_UIN = new Map(DATALINE_DEVICES.map((device) => [device.uin, device]));
const BY_TER = new Map(DATALINE_DEVICES.map((device) => [device.terType, device]));
export function findDatalineDeviceByUin(uin: number): DatalineDeviceContact | undefined {
return BY_UIN.get(uin);
return BY_UIN.get(uin);
}
export function findDatalineDeviceByTerType(terType: number): DatalineDeviceContact | undefined {
return BY_TER.get(terType);
return BY_TER.get(terType);
}
export function isDatalineDeviceUin(uin: number): boolean {
return BY_UIN.has(uin);
return BY_UIN.has(uin);
}
export function datalineFriendListEntries(): DatalineFriendEntry[] {
return DATALINE_DEVICES.map((device) => ({
user_id: device.uin,
nickname: device.name,
remark: device.name,
}));
return DATALINE_DEVICES.map((device) => ({
user_id: device.uin,
nickname: device.name,
remark: device.name,
}));
}
export function appendDatalineFriendEntries<T extends { user_id: number }>(
friends: readonly T[],
friends: readonly T[],
): Array<T | DatalineFriendEntry> {
const occupied = new Set(friends.map((friend) => friend.user_id));
const extras = datalineFriendListEntries().filter((entry) => !occupied.has(entry.user_id));
return extras.length === 0 ? [...friends] : [...friends, ...extras];
const occupied = new Set(friends.map((friend) => friend.user_id));
const extras = datalineFriendListEntries().filter((entry) => !occupied.has(entry.user_id));
return extras.length === 0 ? [...friends] : [...friends, ...extras];
}
export function appIdForTerType(terType: number): number {
return terType === DATALINE_TER_PC ? 1 : 1001;
return terType === DATALINE_TER_PC ? 1 : 1001;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+100 -89
View File
@@ -8,112 +8,123 @@ export type EventHandler<K extends EventKind> = (event: EventOf<K>) => void | Pr
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;
/** 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;
// 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),
);
};
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);
/** 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);
};
}
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);
};
}
/** Subscribe to every kind (low-volume callers like loggers). */
onAny(handler: AnyEventHandler): () => void {
this.anyHandlers.add(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;
return () => {
this.anyHandlers.delete(handler);
};
}
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)));
}
off<K extends EventKind>(kind: K, handler: EventHandler<K>): void {
this.handlers.get(kind)?.delete(handler);
}
for (const handler of this.anyHandlers) {
tasks.push(invoke(this.onError, '*', () => handler(event)));
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);
}
await Promise.allSettled(tasks);
}
}
async function invoke(
onError: (kind: EventKind | '*', err: unknown) => void,
kind: EventKind | '*',
fn: () => unknown,
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;
try {
const ret = fn();
if (ret && typeof (ret as Promise<unknown>).then === 'function') {
await ret;
}
} catch (err) {
onError(kind, err);
}
} catch (err) {
onError(kind, err);
}
}
File diff suppressed because it is too large. Load diff
+302 -196
View File
@@ -11,7 +11,7 @@ import type { JsonObject, JsonValue } from '@snowluma/common/json';
* callers pass it through with zero adaptation.
*/
export interface ReplyEventLookup {
findEvent(messageId: number): JsonObject | null;
findEvent(messageId: number): JsonObject | null;
}
const MAX_TEXT_PREVIEW = 50;
@@ -20,14 +20,17 @@ const MAX_CARD_TITLE_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);
}
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);
}
}
/**
@@ -37,25 +40,36 @@ export function formatGroup(identity: IdentityService, groupId: number): string
* someone — better than logging "0".
*/
export function formatUser(
identity: IdentityService,
groupId: number | undefined,
uin: number,
uid?: string,
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})]`;
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);
}
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);
}
}
/**
@@ -65,77 +79,107 @@ export function formatUser(
* (json / xml / markdown / forward / poke / file).
*/
export function formatMessageSegments(message: JsonValue): string {
try {
if (typeof message === 'string') {
return truncate(message, MAX_TEXT_PREVIEW) || '[空消息]';
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 '[消息渲染异常]';
}
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);
// Market faces (商城表情) are surfaced as `image` segments carrying an
// `emoji_id` marker (+ `summary` = face name). Keep the sticker readable in
// previews instead of collapsing it to a generic "[图片]".
case 'image':
return data.emoji_id
? (data.summary ? `[${String(data.summary)}]` : '[表情]')
: '[图片]';
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': {
// OneBot file segments carry the filename under `data.name`
// (see to-segment.ts). Keep `data.file` as a fallback for any
// upstream that still uses the older field name.
const fileName = data.name ?? data.file;
return fileName ? `[文件:${truncate(String(fileName), 20)}]` : '[文件]';
switch (type) {
case 'text':
return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW);
// Market faces (商城表情) are surfaced as `image` segments carrying an
// `emoji_id` marker (+ `summary` = face name). Keep the sticker readable in
// previews instead of collapsing it to a generic "[图片]".
case 'image':
return data.emoji_id
? data.summary
? `[${String(data.summary)}]`
: '[表情]'
: '[图片]';
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': {
// OneBot file segments carry the filename under `data.name`
// (see to-segment.ts). Keep `data.file` as a fallback for any
// upstream that still uses the older field name.
const fileName = data.name ?? data.file;
return fileName ? `[文件:${truncate(String(fileName), 20)}]` : '[文件]';
}
case 'json': {
// OneBot json segments carry Tencent's ARK / mini-program / share card
// payload as a JSON string under data.data. For the log preview we try
// to surface a human-readable title — "[卡片:某某分享]" instead of just
// "[JSON]". The full payload stays intact in the OneBot segment for any
// downstream consumer that wants to parse it.
// For QQ's server-side fallback (e.g. cardId -896954183 "当前QQ版本不支持
// 此应用,请升级"), the `prompt` field carries that message — surfaces it
// so the operator sees the actual reason instead of "[JSON]".
const title = extractCardTitle(data.data);
return title ? `[卡片:${truncate(title, MAX_CARD_TITLE_PREVIEW)}]` : '[JSON]';
}
case 'xml':
return '[XML]';
case 'markdown':
return '[Markdown]';
case 'inline_keyboard':
return '[交互按钮]';
case 'forward':
return '[聊天记录]';
case 'poke':
return '[窗口抖动]';
case 'flash_file': {
const title = data.title ? String(data.title) : '';
return title ? `[闪传文件:${truncate(title, 20)}]` : '[闪传文件]';
}
default:
return `[${type}]`;
}
case 'json': {
// OneBot json segments carry Tencent's ARK / mini-program / share card
// payload as a JSON string under data.data. For the log preview we try
// to surface a human-readable title — "[卡片:某某分享]" instead of just
// "[JSON]". The full payload stays intact in the OneBot segment for any
// downstream consumer that wants to parse it.
// For QQ's server-side fallback (e.g. cardId -896954183 "当前QQ版本不支持
// 此应用,请升级"), the `prompt` field carries that message — surfaces it
// so the operator sees the actual reason instead of "[JSON]".
const title = extractCardTitle(data.data);
return title ? `[卡片:${truncate(title, MAX_CARD_TITLE_PREVIEW)}]` : '[JSON]';
}
case 'xml': return '[XML]';
case 'markdown': return '[Markdown]';
case 'inline_keyboard': return '[交互按钮]';
case 'forward': return '[聊天记录]';
case 'poke': return '[窗口抖动]';
case 'flash_file': {
const title = data.title ? String(data.title) : '';
return title ? `[闪传文件:${truncate(title, 20)}]` : '[闪传文件]';
}
default: return `[${type}]`;
}
}
function truncate(s: string, max: number): string {
return s.length > max ? `${s.slice(0, max)}...` : s;
return s.length > max ? `${s.slice(0, max)}...` : s;
}
/**
@@ -157,43 +201,74 @@ function truncate(s: string, max: number): string {
* "[JSON]". Pure best-effort: this is a log-preview hint, not a contract.
*/
function extractCardTitle(raw: unknown): string | null {
if (typeof raw !== 'string' || raw.length === 0) return null;
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
if (typeof raw !== 'string' || raw.length === 0) {
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null;
}
const root = parsed as Record<string, unknown>;
const meta = root.meta;
if (meta && typeof meta === 'object' && !Array.isArray(meta)) {
const m = meta as Record<string, unknown>;
const sections = ['detail_1', 'detail', 'news', 'mannounce', 'music', 'video'];
for (const key of sections) {
const t = readTitle(m[key]);
if (t) {
return t;
}
}
// Fallback: meta has exactly one section — use its title.
const keys = Object.keys(m);
if (keys.length === 1) {
const t = readTitle(m[keys[0]]);
if (t) {
return t;
}
}
}
if (typeof root.prompt === 'string' && root.prompt.trim()) {
return root.prompt.trim();
}
if (typeof root.desc === 'string' && root.desc.trim()) {
return root.desc.trim();
}
return null;
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
const root = parsed as Record<string, unknown>;
const meta = root.meta;
if (meta && typeof meta === 'object' && !Array.isArray(meta)) {
const m = meta as Record<string, unknown>;
const sections = ['detail_1', 'detail', 'news', 'mannounce', 'music', 'video'];
for (const key of sections) {
const t = readTitle(m[key]);
if (t) return t;
}
// Fallback: meta has exactly one section — use its title.
const keys = Object.keys(m);
if (keys.length === 1) {
const t = readTitle(m[keys[0]]);
if (t) return t;
}
}
if (typeof root.prompt === 'string' && root.prompt.trim()) return root.prompt.trim();
if (typeof root.desc === 'string' && root.desc.trim()) return root.desc.trim();
return null;
}
function readTitle(node: unknown): string | null {
if (!node || typeof node !== 'object' || Array.isArray(node)) return null;
const t = (node as Record<string, unknown>).title;
if (typeof t !== 'string') return null;
const trimmed = t.trim();
return trimmed.length > 0 ? trimmed : null;
if (!node || typeof node !== 'object' || Array.isArray(node)) {
return null;
}
const t = (node as Record<string, unknown>).title;
if (typeof t !== 'string') {
return null;
}
const trimmed = t.trim();
return trimmed.length > 0 ? trimmed : null;
}
/**
@@ -208,44 +283,65 @@ function readTitle(node: unknown): string | null {
* to" questions.
*/
export function formatReply(
messageStore: ReplyEventLookup,
identity: IdentityService,
replyId: number,
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;
try {
if (!replyId) {
return '[回复:0]';
}
// 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 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}]`;
}
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;
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;
}
/**
@@ -255,48 +351,58 @@ function toIntOrZero(v: unknown): number {
* 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': {
const leaveAction = event.leaveType === 'disband' ? '随群解散' : event.leaveType === 'kick' ? '被踢出' : '退出';
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${leaveAction} ${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.peerUin)} | ${formatUser(identity, undefined, event.senderUin)} -> ${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': {
const invitee = event.invitedUin && event.invitedUin > 0
? ` 邀 ${formatUser(identity, event.groupId, event.invitedUin, event.invitedUid)}`
: '';
return `群邀请 ${formatUser(identity, undefined, event.fromUin)}${invitee} -> ${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:
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': {
const leaveAction =
event.leaveType === 'disband'
? '随群解散'
: event.leaveType === 'kick'
? '被踢出'
: '退出';
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${leaveAction} ${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.peerUin)} | ${formatUser(identity, undefined, event.senderUin)} -> ${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': {
const invitee =
event.invitedUin && event.invitedUin > 0
? ` 邀 ${formatUser(identity, event.groupId, event.invitedUin, event.invitedUid)}`
: '';
return `群邀请 ${formatUser(identity, undefined, event.fromUin)}${invitee} -> ${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;
}
} catch {
return null;
}
}
+207 -152
View File
@@ -10,63 +10,76 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const log = createLogger('Highway.Audio');
export interface FFmpegVideoInfo {
width: number;
height: number;
duration: number;
format: string;
videoCodec: string;
image: Buffer;
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,
outputPath: string,
format: string,
): Promise<{ result: boolean; channels: number; sampleRate: number; format: string }>;
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,
outputPath: string,
format: string,
): Promise<{ result: boolean; channels: number; sampleRate: number; format: string }>;
}
let cachedAddon: FFmpegNativeAddon | null = null;
let cachedLoadError: string | null = null;
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
return error instanceof Error ? error.message : String(error);
}
function addonFileName(): string {
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
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'),
];
// 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;
const fileName = addonFileName();
for (const dir of addonSearchDirs()) {
const full = path.join(dir, fileName);
if (fs.existsSync(full)) {
return full;
}
}
return null;
}
/**
@@ -75,24 +88,30 @@ function resolveAddonPath(): string | null {
* so callers don't silently fall back.
*/
export function getFFmpegAddon(): FFmpegNativeAddon {
if (cachedAddon) return cachedAddon;
if (cachedLoadError) throw new Error(cachedLoadError);
if (cachedAddon) {
return cachedAddon;
}
const addonPath = resolveAddonPath();
if (!addonPath) {
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
throw new Error(cachedLoadError);
}
if (cachedLoadError) {
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}): ${errorMessage(error)}`;
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}): ${errorMessage(error)}`;
throw new Error(cachedLoadError);
}
}
/**
@@ -102,28 +121,29 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
* 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);
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;
}
} 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;
/** 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;
}
/**
@@ -132,36 +152,40 @@ export interface EncodeSilkResult {
* when `converted === true`.
*/
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
const addon = getFFmpegAddon();
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));
// 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 };
}
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 };
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(), 'audio-upload');
return path.join(os.tmpdir(), 'audio-upload');
}
// ── audio transcode (get_record out_format, #165) ──
@@ -172,8 +196,9 @@ export function defaultPttTempDir(): string {
/** Output formats accepted by `out_format` (mirrors NapCat's allowlist). */
export const AUDIO_OUT_FORMATS = ['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac'] as const;
export type AudioOutFormat = (typeof AUDIO_OUT_FORMATS)[number];
export function isAudioOutFormat(s: string): s is AudioOutFormat {
return (AUDIO_OUT_FORMATS as readonly string[]).includes(s);
return (AUDIO_OUT_FORMATS as readonly string[]).includes(s);
}
/** Minimal addon surface the transcode needs — lets tests inject a fake. */
@@ -192,15 +217,20 @@ const SILK_V3_SIGNATURE = Buffer.from('#!SILK_V3', 'ascii');
* transcode boundary. Copy before rewriting to preserve caller-owned bytes.
*/
function normalizeQqAiSilkContainer(bytes: Uint8Array): Uint8Array {
if (bytes.length < SILK_V3_SIGNATURE.length + 1 || bytes[0] !== 0x03) return bytes;
for (let index = 0; index < SILK_V3_SIGNATURE.length; index += 1) {
if (bytes[index + 1] !== SILK_V3_SIGNATURE[index]) return bytes;
}
if (bytes.length < SILK_V3_SIGNATURE.length + 1 || bytes[0] !== 0x03) {
return bytes;
}
const normalized = Uint8Array.from(bytes);
normalized[0] = 0x02;
log.debug('normalized QQ AI SILK container for audio transcoding');
return normalized;
for (let index = 0; index < SILK_V3_SIGNATURE.length; index += 1) {
if (bytes[index + 1] !== SILK_V3_SIGNATURE[index]) {
return bytes;
}
}
const normalized = Uint8Array.from(bytes);
normalized[0] = 0x02;
log.debug('normalized QQ AI SILK container for audio transcoding');
return normalized;
}
/**
@@ -211,54 +241,79 @@ function normalizeQqAiSilkContainer(bytes: Uint8Array): Uint8Array {
* conversion (e.g. the binary lacks SILK decode).
*/
export async function convertAudioBytes(
bytes: Uint8Array,
format: string,
deps: { addon?: AudioConvertAddon; tmpDir?: string; maxOutputBytes?: number } = {},
bytes: Uint8Array,
format: string,
deps: { addon?: AudioConvertAddon; tmpDir?: string; maxOutputBytes?: number } = {},
): Promise<{ base64: string; size: number }> {
if (!isAudioOutFormat(format)) {
throw new Error(`unsupported out_format: ${format} (expected one of ${AUDIO_OUT_FORMATS.join(', ')})`);
}
const addon = deps.addon ?? getFFmpegAddon();
const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT;
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'audio-transcode');
fs.mkdirSync(dir, { recursive: true });
const id = crypto.randomBytes(8).toString('hex');
const inPath = path.join(dir, `${id}.in`);
const outPath = path.join(dir, `${id}.${format}`);
let outcome: PromiseSettledResult<{ base64: string; size: number }>;
try {
await fs.promises.writeFile(inPath, normalizeQqAiSilkContainer(bytes));
await addon.decodeAudioToFmt(inPath, outPath, format);
if (!fs.existsSync(outPath)) throw new Error('audio conversion failed: no output file');
// Bound the output before reading it into memory (decompressing direction).
const stat = await fs.promises.stat(outPath);
if (stat.size > maxOut) throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`);
const out = await fs.promises.readFile(outPath);
outcome = { status: 'fulfilled', value: { base64: out.toString('base64'), size: out.length } };
} catch (reason) {
outcome = { status: 'rejected', reason };
}
// `force` makes missing files harmless. Any remaining rejection is a real
// permission/I/O failure and must stay observable instead of leaking voice
// data silently. Preserve the conversion error too when both phases fail.
const cleanupResults = await Promise.allSettled([
fs.promises.rm(inPath, { force: true }),
fs.promises.rm(outPath, { force: true }),
]);
const cleanupErrors = cleanupResults
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
.map((result) => result.reason);
if (cleanupErrors.length > 0) {
const cleanupMessage = cleanupErrors.map(errorMessage).join('; ');
if (outcome.status === 'rejected') {
throw new AggregateError(
[outcome.reason, ...cleanupErrors],
`audio conversion failed: ${errorMessage(outcome.reason)}; temporary audio file cleanup failed: ${cleanupMessage}`,
);
if (!isAudioOutFormat(format)) {
throw new Error(
`unsupported out_format: ${format} (expected one of ${AUDIO_OUT_FORMATS.join(', ')})`,
);
}
throw new AggregateError(cleanupErrors, `temporary audio file cleanup failed: ${cleanupMessage}`);
}
if (outcome.status === 'rejected') throw outcome.reason;
return outcome.value;
const addon = deps.addon ?? getFFmpegAddon();
const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT;
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'audio-transcode');
fs.mkdirSync(dir, { recursive: true });
const id = crypto.randomBytes(8).toString('hex');
const inPath = path.join(dir, `${id}.in`);
const outPath = path.join(dir, `${id}.${format}`);
let outcome: PromiseSettledResult<{ base64: string; size: number }>;
try {
await fs.promises.writeFile(inPath, normalizeQqAiSilkContainer(bytes));
await addon.decodeAudioToFmt(inPath, outPath, format);
if (!fs.existsSync(outPath)) {
throw new Error('audio conversion failed: no output file');
}
// Bound the output before reading it into memory (decompressing direction).
const stat = await fs.promises.stat(outPath);
if (stat.size > maxOut) {
throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`);
}
const out = await fs.promises.readFile(outPath);
outcome = {
status: 'fulfilled',
value: { base64: out.toString('base64'), size: out.length },
};
} catch (reason) {
outcome = { status: 'rejected', reason };
}
// `force` makes missing files harmless. Any remaining rejection is a real
// permission/I/O failure and must stay observable instead of leaking voice
// data silently. Preserve the conversion error too when both phases fail.
const cleanupResults = await Promise.allSettled([
fs.promises.rm(inPath, { force: true }),
fs.promises.rm(outPath, { force: true }),
]);
const cleanupErrors = cleanupResults
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
.map((result) => result.reason);
if (cleanupErrors.length > 0) {
const cleanupMessage = cleanupErrors.map(errorMessage).join('; ');
if (outcome.status === 'rejected') {
throw new AggregateError(
[outcome.reason, ...cleanupErrors],
`audio conversion failed: ${errorMessage(outcome.reason)}; temporary audio file cleanup failed: ${cleanupMessage}`,
);
}
throw new AggregateError(
cleanupErrors,
`temporary audio file cleanup failed: ${cleanupMessage}`,
);
}
if (outcome.status === 'rejected') {
throw outcome.reason;
}
return outcome.value;
}
+122 -111
View File
@@ -19,18 +19,18 @@ import { Sha1Stream } from './sha1-stream';
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
export interface StreamedFileHashes {
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
/** Per-1 MiB intermediate SHA1 states (little-endian, un-finalized) plus a
* final entry that is the finalized whole-file SHA1 — the exact shape
* `computeVideoSha1Blocks` returns. Only meaningful for video; file uploads
* ignore it. */
sha1Blocks: Uint8Array[];
/** md5 of the first `headLimit` bytes — the offline-file `md510MCheckSum`.
* Present only when `headLimit` was passed. */
headMd5?: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
/** Per-1 MiB intermediate SHA1 states (little-endian, un-finalized) plus a
* final entry that is the finalized whole-file SHA1 — the exact shape
* `computeVideoSha1Blocks` returns. Only meaningful for video; file uploads
* ignore it. */
sha1Blocks: Uint8Array[];
/** md5 of the first `headLimit` bytes — the offline-file `md510MCheckSum`.
* Present only when `headLimit` was passed. */
headMd5?: Uint8Array;
}
/**
@@ -39,73 +39,78 @@ export interface StreamedFileHashes {
* when `headLimit` is given) over the file's bytes, without buffering the file.
*/
export async function hashFileStreaming(
filePath: string,
opts?: { headLimit?: number },
filePath: string,
opts?: { headLimit?: number },
): Promise<StreamedFileHashes> {
const { size } = await fsp.stat(filePath);
const src = await FileChunkSource.open(filePath, size);
try {
const md5 = createHash('md5');
const sha1 = createHash('sha1');
const headLimit = opts?.headLimit;
const headMd5 = headLimit !== undefined ? createHash('md5') : null;
let headRemaining = headLimit ?? 0;
const { size } = await fsp.stat(filePath);
const src = await FileChunkSource.open(filePath, size);
// Running SHA1 state fed only full 1 MiB chunks, snapshotted at each 1 MiB
// boundary — mirrors computeVideoSha1Blocks (which feeds 64-byte blocks and
// snapshots at 1 MiB; identical result since 1 MiB is a multiple of 64 and
// Sha1Stream buffers internally). The sub-1 MiB tail is never snapshotted,
// so it need not be fed to the block-sha1 at all.
const blockSha1 = new Sha1Stream();
const sha1Blocks: Uint8Array[] = [];
try {
const md5 = createHash('md5');
const sha1 = createHash('sha1');
const headLimit = opts?.headLimit;
const headMd5 = headLimit !== undefined ? createHash('md5') : null;
let headRemaining = headLimit ?? 0;
let offset = 0;
while (offset < size) {
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
const chunk = await src.read(offset, len);
md5.update(chunk);
sha1.update(chunk);
if (headMd5 && headRemaining > 0) {
const take = Math.min(headRemaining, chunk.length);
headMd5.update(chunk.subarray(0, take));
headRemaining -= take;
}
if (len === SHA1_STREAM_BLOCK_SIZE) {
blockSha1.update(chunk);
sha1Blocks.push(blockSha1.hash(true)); // little-endian intermediate state
}
offset += len;
// Running SHA1 state fed only full 1 MiB chunks, snapshotted at each 1 MiB
// boundary — mirrors computeVideoSha1Blocks (which feeds 64-byte blocks and
// snapshots at 1 MiB; identical result since 1 MiB is a multiple of 64 and
// Sha1Stream buffers internally). The sub-1 MiB tail is never snapshotted,
// so it need not be fed to the block-sha1 at all.
const blockSha1 = new Sha1Stream();
const sha1Blocks: Uint8Array[] = [];
let offset = 0;
while (offset < size) {
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
const chunk = await src.read(offset, len);
md5.update(chunk);
sha1.update(chunk);
if (headMd5 && headRemaining > 0) {
const take = Math.min(headRemaining, chunk.length);
headMd5.update(chunk.subarray(0, take));
headRemaining -= take;
}
if (len === SHA1_STREAM_BLOCK_SIZE) {
blockSha1.update(chunk);
sha1Blocks.push(blockSha1.hash(true)); // little-endian intermediate state
}
offset += len;
}
const sha1Digest = sha1.digest();
// Final entry: the finalized whole-file SHA1 — the last element
// computeVideoSha1Blocks pushes.
sha1Blocks.push(new Uint8Array(sha1Digest));
const md5Digest = md5.digest();
return {
md5: new Uint8Array(md5Digest),
sha1: new Uint8Array(sha1Digest),
md5Hex: md5Digest.toString('hex'),
sha1Hex: sha1Digest.toString('hex'),
sha1Blocks,
headMd5: headMd5 ? new Uint8Array(headMd5.digest()) : undefined,
};
} finally {
await src.close();
}
const sha1Digest = sha1.digest();
// Final entry: the finalized whole-file SHA1 — the last element
// computeVideoSha1Blocks pushes.
sha1Blocks.push(new Uint8Array(sha1Digest));
const md5Digest = md5.digest();
return {
md5: new Uint8Array(md5Digest),
sha1: new Uint8Array(sha1Digest),
md5Hex: md5Digest.toString('hex'),
sha1Hex: sha1Digest.toString('hex'),
sha1Blocks,
headMd5: headMd5 ? new Uint8Array(headMd5.digest()) : undefined,
};
} finally {
await src.close();
}
}
export interface StreamedFlashHashes {
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
/** Flash sliceupload Sha1StateV — un-finalized little-endian state after
* every full 1 MiB slice except the last; the last entry is the finalized
* whole-file SHA1. Same shape as `computeSha1StateV`, not `sha1Blocks`. */
sha1StateV: Uint8Array[];
sliceCount: number;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
/** Flash sliceupload Sha1StateV — un-finalized little-endian state after
* every full 1 MiB slice except the last; the last entry is the finalized
* whole-file SHA1. Same shape as `computeSha1StateV`, not `sha1Blocks`. */
sha1StateV: Uint8Array[];
sliceCount: number;
}
/**
@@ -118,45 +123,51 @@ export interface StreamedFlashHashes {
* state that flash's Sha1StateV must not carry.
*/
export async function hashFlashFileStreaming(filePath: string): Promise<StreamedFlashHashes> {
const { size } = await fsp.stat(filePath);
const sliceCount = Math.ceil(size / SHA1_STREAM_BLOCK_SIZE);
const src = await FileChunkSource.open(filePath, size);
try {
const md5 = createHash('md5');
const sha1 = createHash('sha1');
const blockSha1 = new Sha1Stream();
const sha1StateV: Uint8Array[] = [];
const { size } = await fsp.stat(filePath);
const sliceCount = Math.ceil(size / SHA1_STREAM_BLOCK_SIZE);
const src = await FileChunkSource.open(filePath, size);
let offset = 0;
let sliceIndex = 0;
while (offset < size) {
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
const chunk = await src.read(offset, len);
md5.update(chunk);
sha1.update(chunk);
blockSha1.update(chunk);
if (sliceIndex !== sliceCount - 1) {
sha1StateV.push(blockSha1.hash(true));
}
offset += len;
sliceIndex += 1;
try {
const md5 = createHash('md5');
const sha1 = createHash('sha1');
const blockSha1 = new Sha1Stream();
const sha1StateV: Uint8Array[] = [];
let offset = 0;
let sliceIndex = 0;
while (offset < size) {
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
const chunk = await src.read(offset, len);
md5.update(chunk);
sha1.update(chunk);
blockSha1.update(chunk);
if (sliceIndex !== sliceCount - 1) {
sha1StateV.push(blockSha1.hash(true));
}
offset += len;
sliceIndex += 1;
}
const sha1Digest = sha1.digest();
if (sliceCount > 0) {
sha1StateV.push(new Uint8Array(sha1Digest));
}
const md5Digest = md5.digest();
return {
md5: new Uint8Array(md5Digest),
sha1: new Uint8Array(sha1Digest),
md5Hex: md5Digest.toString('hex'),
sha1Hex: sha1Digest.toString('hex'),
sha1StateV,
sliceCount,
};
} finally {
await src.close();
}
const sha1Digest = sha1.digest();
if (sliceCount > 0) {
sha1StateV.push(new Uint8Array(sha1Digest));
}
const md5Digest = md5.digest();
return {
md5: new Uint8Array(md5Digest),
sha1: new Uint8Array(sha1Digest),
md5Hex: md5Digest.toString('hex'),
sha1Hex: sha1Digest.toString('hex'),
sha1StateV,
sliceCount,
};
} finally {
await src.close();
}
}
File diff suppressed because it is too large. Load diff
+181 -150
View File
@@ -5,106 +5,122 @@ 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,
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;
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;
/** 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,
};
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'));
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 Promise.resolve(imageDataFromFingerprint(element));
}
return loadImageFromSource(
element.url || element.imageUrl || element.fileId || '',
element.fileName ?? '',
element.subType ?? 0,
element.summary ?? '',
);
return loadImageFromSource(
element.url || element.imageUrl || 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);
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';
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;
let finalName = fileName || loaded.fileName;
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,
};
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,
};
}
/**
@@ -112,82 +128,97 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu
* commonElem.
*/
export async function uploadImageMsgInfo(
bridge: BridgeContext,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
tempGroupId?: number,
bridge: BridgeContext,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
tempGroupId?: number,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const image = await loadImage(element);
const pic: PicExtBizInfo = {
bizType: image.subType,
textSummary: image.summary,
...(isGroup
? { extData: { subType: image.subType, textSummary: image.summary } }
: { bytesPbReserveC2c: protobuf_encode<NotOnlineImagePbReserve>({
subType: image.subType, summary: image.summary,
}) }),
};
log.debug('uploading %d bytes md5=%s... → %s %s%s',
image.fileSize,
image.md5Hex.slice(0, 8),
isGroup ? 'group' : tempGroupId !== undefined ? 'group-temp' : 'c2c',
String(targetIdOrUid),
tempGroupId !== undefined ? ` sourceGroup=${tempGroupId}` : '');
const log = loggerFor(bridge);
const image = await loadImage(element);
const pic: PicExtBizInfo = {
bizType: image.subType,
textSummary: image.summary,
...(isGroup
? { extData: { subType: image.subType, textSummary: image.summary } }
: {
bytesPbReserveC2c: protobuf_encode<NotOnlineImagePbReserve>({
subType: image.subType,
summary: image.summary,
}),
}),
};
log.debug(
'uploading %d bytes md5=%s... → %s %s%s',
image.fileSize,
image.md5Hex.slice(0, 8),
isGroup ? 'group' : tempGroupId !== undefined ? 'group-temp' : 'c2c',
String(targetIdOrUid),
tempGroupId !== undefined ? ` sourceGroup=${tempGroupId}` : '',
);
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 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,
tempGroupId,
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
requestId: 1,
businessType: 1,
uploadInfo: [{
fileInfo: {
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
tempGroupId,
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,
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array(0),
bytesPbReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
uploads,
label: 'image',
});
const encoded = finalizeMediaMsgInfo(upload, pic);
// Retain successful upload metadata for the caller's self-sent history.
Object.assign(element, {
md5Hex: image.md5Hex,
sha1Hex: image.sha1Hex,
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,
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array(0),
bytesPbReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
uploads,
label: 'image',
});
const encoded = finalizeMediaMsgInfo(upload, pic);
// Retain successful upload metadata for the caller's self-sent history.
Object.assign(element, {
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, fileSize: image.fileSize,
fileName: image.fileName, width: image.width, height: image.height,
picFormat: image.picFormat, subType: image.subType, summary: image.summary,
});
return encoded;
picFormat: image.picFormat,
subType: image.subType,
summary: image.summary,
});
return encoded;
}
+339 -288
View File
@@ -1,14 +1,10 @@
import {
createLogger,
renderTraceBytes,
runWithTraceRequest,
} from '@snowluma/common/logger';
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
import type {
EncodableMediaMsgInfo,
HighwayMsgInfoBody,
NTV2ExtBizInfo,
NTV2UploadInfo,
NTV2UploadRespBody,
EncodableMediaMsgInfo,
HighwayMsgInfoBody,
NTV2ExtBizInfo,
NTV2UploadInfo,
NTV2UploadRespBody,
} from '@snowluma/proto-defs/highway';
import { protobuf_encode } from '@snowluma/proton';
import type { PicExtBizInfo } from '@snowluma/proto-defs/element';
@@ -16,7 +12,13 @@ import crypto from 'crypto';
import type { BridgeContext } from '../bridge-context';
import { OidbError } from '../oidb-service';
import { Ntv2UploadRequest } from '../oidb-services/highway/ntv2-upload-request';
import { BufferChunkSource, FileChunkSource, buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
import {
BufferChunkSource,
FileChunkSource,
buildHighwayExtend,
fetchHighwaySession,
uploadHighwayHttp,
} from './highway-client';
const moduleLog = createLogger('Highway');
@@ -28,65 +30,65 @@ const moduleLog = createLogger('Highway');
* 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. Also empty
* when `fileSource` is set (the bytes are streamed from disk instead). */
bytes: Uint8Array;
/** When set, this sub-file streams from a disk file instead of `bytes`
* (which should be empty). runPuts opens a `FileChunkSource`; all size /
* data-presence decisions use `fileSource.fileSize`, not `bytes.length`. */
fileSource?: { filePath: string; fileSize: number };
/** 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;
/**
* 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. Also empty
* when `fileSource` is set (the bytes are streamed from disk instead). */
bytes: Uint8Array;
/** When set, this sub-file streams from a disk file instead of `bytes`
* (which should be empty). runPuts opens a `FileChunkSource`; all size /
* data-presence decisions use `fileSource.fileSize`, not `bytes.length`. */
fileSource?: { filePath: string; fileSize: number };
/** 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;
/** Existing passive group temp session; never creates or refreshes a session. */
tempGroupId?: 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: NTV2UploadInfo[];
/** `upload.compatQmsgSceneType`. */
compatQmsgSceneType: number;
/** `upload.extBizInfo` — type-specific bytes/flags. */
extBizInfo: NTV2ExtBizInfo;
/** Sub-file Highway PUTs to perform after the OIDB response. */
uploads: MediaSubFileUpload[];
/** Used in error messages. Defaults to 'media'. */
label?: string;
bridge: BridgeContext;
isGroup: boolean;
/** Group uin when isGroup, otherwise the recipient's uid string. */
targetIdOrUid: string | number;
/** Existing passive group temp session; never creates or refreshes a session. */
tempGroupId?: 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: NTV2UploadInfo[];
/** `upload.compatQmsgSceneType`. */
compatQmsgSceneType: number;
/** `upload.extBizInfo` — type-specific bytes/flags. */
extBizInfo: NTV2ExtBizInfo;
/** Sub-file Highway PUTs to perform after the OIDB response. */
uploads: MediaSubFileUpload[];
/** Used in error messages. Defaults to 'media'. */
label?: string;
}
// ─────────────── helpers ───────────────
@@ -97,39 +99,45 @@ export interface NtV2UploadParams {
* Mirrors NapCat.
*/
export function makeClientRandomId(): bigint {
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
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;
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;
}
function sha1TraceValue(value: Uint8Array | Uint8Array[]): string {
const values = Array.isArray(value) ? value : [value];
return `[${values.map((item) => renderTraceBytes(item)).join(',')}]`;
const values = Array.isArray(value) ? value : [value];
return `[${values.map((item) => renderTraceBytes(item)).join(',')}]`;
}
function uploadDescriptors(uploads: MediaSubFileUpload[]): string {
return `[${uploads.map((sub) => [
`source:${JSON.stringify(String(sub.source))}`,
`cmdId:${sub.cmdId}`,
`size:${sub.fileSource ? sub.fileSource.fileSize : sub.bytes.byteLength}`,
`storage:${JSON.stringify(sub.fileSource ? 'disk' : 'buffer')}`,
`md5:${renderTraceBytes(sub.md5)}`,
`sha1:${sha1TraceValue(sub.sha1)}`,
`subFileIndex:${sub.subFileIndex ?? 0}`,
].join(',')).join(';')}]`;
return `[${uploads
.map((sub) =>
[
`source:${JSON.stringify(String(sub.source))}`,
`cmdId:${sub.cmdId}`,
`size:${sub.fileSource ? sub.fileSource.fileSize : sub.bytes.byteLength}`,
`storage:${JSON.stringify(sub.fileSource ? 'disk' : 'buffer')}`,
`md5:${renderTraceBytes(sub.md5)}`,
`sha1:${sha1TraceValue(sub.sha1)}`,
`subFileIndex:${sub.subFileIndex ?? 0}`,
].join(','),
)
.join(';')}]`;
}
function mediaErrorText(error: unknown): string {
return error instanceof Error ? error.message : String(error);
return error instanceof Error ? error.message : String(error);
}
// ─────────────── main entrypoint ───────────────
@@ -143,203 +151,233 @@ function mediaErrorText(error: unknown): string {
* only fetches the Highway session once.
*/
export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespBody> {
const startedAt = Date.now();
const label = params.label ?? 'media';
let failureReason = 'unexpected_failure';
let didPut = false;
return runWithTraceRequest(async () => {
moduleLog.trace(() => [
'highway_media_start label=%j scope=%s target=%j sourceGroup=%s oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
label,
params.isGroup ? 'group' : params.tempGroupId !== undefined ? 'group-temp' : 'private',
String(params.targetIdOrUid),
params.tempGroupId === undefined ? '-' : String(params.tempGroupId),
params.oidbCmd,
params.serviceCmd,
params.requestId,
params.businessType,
uploadDescriptors(params.uploads),
]);
try {
const result = await runNtv2UploadOperation(params, (reason, put) => {
failureReason = reason;
if (put !== undefined) didPut = put;
});
moduleLog.trace(
'highway_media_terminal label=%j outcome=completed reason=%s uploads=%d elapsedMs=%d',
label,
didPut ? 'put_complete' : 'fast_upload',
params.uploads.length,
Date.now() - startedAt,
);
return result;
} catch (error) {
moduleLog.trace(() => [
'highway_media_terminal label=%j outcome=failed reason=%s uploads=%d error=%j elapsedMs=%d',
label,
failureReason,
params.uploads.length,
mediaErrorText(error),
Date.now() - startedAt,
]);
throw error;
}
});
const startedAt = Date.now();
const label = params.label ?? 'media';
let failureReason = 'unexpected_failure';
let didPut = false;
return runWithTraceRequest(async () => {
moduleLog.trace(() => [
'highway_media_start label=%j scope=%s target=%j sourceGroup=%s oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
label,
params.isGroup ? 'group' : params.tempGroupId !== undefined ? 'group-temp' : 'private',
String(params.targetIdOrUid),
params.tempGroupId === undefined ? '-' : String(params.tempGroupId),
params.oidbCmd,
params.serviceCmd,
params.requestId,
params.businessType,
uploadDescriptors(params.uploads),
]);
try {
const result = await runNtv2UploadOperation(params, (reason, put) => {
failureReason = reason;
if (put !== undefined) {
didPut = put;
}
});
moduleLog.trace(
'highway_media_terminal label=%j outcome=completed reason=%s uploads=%d elapsedMs=%d',
label,
didPut ? 'put_complete' : 'fast_upload',
params.uploads.length,
Date.now() - startedAt,
);
return result;
} catch (error) {
moduleLog.trace(() => [
'highway_media_terminal label=%j outcome=failed reason=%s uploads=%d error=%j elapsedMs=%d',
label,
failureReason,
params.uploads.length,
mediaErrorText(error),
Date.now() - startedAt,
]);
throw error;
}
});
}
async function runNtv2UploadOperation(
params: NtV2UploadParams,
setState: (failureReason: string, didPut?: boolean) => void,
params: NtV2UploadParams,
setState: (failureReason: string, didPut?: boolean) => void,
): Promise<NTV2UploadRespBody> {
const { bridge, isGroup, targetIdOrUid, oidbCmd, 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;
const { bridge, isGroup, targetIdOrUid, oidbCmd, 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;
// Send one OIDB request and return its decoded `upload` body. `tryFast`
// toggles `tryFastUploadCompleted`: true asks the server to reuse a
// cached resource (skip the bytes); false forces it to allocate a fresh
// upload session and hand back a uKey. NOTE: proton only emits a plain
// `pb<bool>` when it's `true`, so `tryFast === false` omits field 2 —
// the server reads that as "don't fast-upload" (the opt-in default).
const requestUpload = async (tryFast: boolean): Promise<NTV2UploadRespBody> => {
setState('request_failed');
try {
return await Ntv2UploadRequest.invoke(bridge, {
oidbCmd,
isGroup,
targetIdOrUid,
tempGroupId: params.tempGroupId,
requestId: params.requestId,
businessType: params.businessType,
uploadInfo: params.uploadInfo,
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
tryFast,
clientRandomId: makeClientRandomId(),
label,
});
} catch (error) {
if (error instanceof OidbError) setState('oidb_rejected');
else if (error instanceof Error && error.message.includes('missing msgInfo')) setState('response_invalid');
else if (error instanceof Error && error.message.includes('upload failed')) setState('business_rejected');
log.trace(() => [
'highway_media_branch branch=oidb_response error=%j',
error instanceof Error ? error.message : String(error),
]);
throw error;
}
};
// Send one OIDB request and return its decoded `upload` body. `tryFast`
// toggles `tryFastUploadCompleted`: true asks the server to reuse a
// cached resource (skip the bytes); false forces it to allocate a fresh
// upload session and hand back a uKey. NOTE: proton only emits a plain
// `pb<bool>` when it's `true`, so `tryFast === false` omits field 2 —
// the server reads that as "don't fast-upload" (the opt-in default).
const requestUpload = async (tryFast: boolean): Promise<NTV2UploadRespBody> => {
setState('request_failed');
// Highway PUTs. Session is lazily fetched and cached — video does two
// PUTs (main + thumb) and shouldn't pay for two sessions, and a forced
// retry shouldn't re-fetch it either.
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
setState('session_failed');
session ??= await fetchHighwaySession(bridge);
return session;
};
try {
return await Ntv2UploadRequest.invoke(bridge, {
oidbCmd,
isGroup,
targetIdOrUid,
tempGroupId: params.tempGroupId,
requestId: params.requestId,
businessType: params.businessType,
uploadInfo: params.uploadInfo,
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
tryFast,
clientRandomId: makeClientRandomId(),
label,
});
} catch (error) {
if (error instanceof OidbError) {
setState('oidb_rejected');
} else if (error instanceof Error && error.message.includes('missing msgInfo')) {
setState('response_invalid');
} else if (error instanceof Error && error.message.includes('upload failed')) {
setState('business_rejected');
}
// Run whatever PUTs the given `upload` response asks for.
const runPuts = async (upload: NTV2UploadRespBody): Promise<void> => {
const msgInfo = upload.msgInfo;
if (!msgInfo) throw new Error('upload response missing msgInfo');
let didPut = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
// Data size / presence comes from fileSource (streamed) when set, else
// from the in-memory bytes — a streamed sub-file has empty `bytes`, so
// keying the checks below on `bytes.length` would wrongly treat it as a
// fast-only / empty sub-file.
const subSize = sub.fileSource ? sub.fileSource.fileSize : sub.bytes.length;
// No uKey: the server fast-pathed this sub-file — it already holds
// (or claims to hold) the resource, so there are no bytes to push.
if (!uKey) {
if (subSize > 0) {
log.trace(
'highway_media_branch branch=fast_upload source=%j cmdId=%d size=%d',
String(sub.source),
sub.cmdId,
subSize,
);
log.debug('%s fast-upload hit for sub=%s (server reusing cached resource)', label, String(sub.source));
log.trace(() => [
'highway_media_branch branch=oidb_response error=%j',
error instanceof Error ? error.message : String(error),
]);
throw error;
}
continue;
}
};
if (subSize === 0) {
log.trace(
'highway_media_branch branch=empty_source source=%j cmdId=%d hasFastOnlyError=%s',
String(sub.source),
sub.cmdId,
Boolean(sub.fastOnlyError),
);
if (sub.fastOnlyError) {
setState('source_unavailable');
throw new Error(sub.fastOnlyError);
// Highway PUTs. Session is lazily fetched and cached — video does two
// PUTs (main + thumb) and shouldn't pay for two sessions, and a forced
// retry shouldn't re-fetch it either.
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
setState('session_failed');
session ??= await fetchHighwaySession(bridge);
return session;
};
// Run whatever PUTs the given `upload` response asks for.
const runPuts = async (upload: NTV2UploadRespBody): Promise<void> => {
const msgInfo = upload.msgInfo;
if (!msgInfo) {
throw new Error('upload response missing msgInfo');
}
continue;
}
if (!target) continue;
let didPut = false;
log.trace(
'highway_media_branch branch=put_required source=%j cmdId=%d size=%d uKey=%j storage=%s',
String(sub.source),
sub.cmdId,
subSize,
uKey,
sub.fileSource ? 'disk' : 'buffer',
);
setState('extend_build_failed');
const extend = buildHighwayExtend(
uKey,
msgInfo,
target.ipv4s ?? [],
sub.sha1,
sub.subFileIndex ?? 0,
);
// Resolve the (lazy, cached) session BEFORE opening the ChunkSource, so
// there is no fallible await between opening the FileChunkSource handle
// and the uploadHighwayHttp call that owns closing it — otherwise a
// session-fetch failure on the first PUT would leak the open handle.
const putSession = await getSession();
// uploadHighwayHttp owns the ChunkSource and closes it exactly once.
setState('source_open_failed');
const chunkSource = sub.fileSource
? await FileChunkSource.open(sub.fileSource.filePath, sub.fileSource.fileSize)
: new BufferChunkSource(sub.bytes);
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, subSize, String(sub.source));
const t0 = Date.now();
setState('put_failed');
await uploadHighwayHttp(bridge, putSession, sub.cmdId, chunkSource, sub.md5, extend);
log.debug('%s PUT done in %dms', label, Date.now() - t0);
didPut = true;
setState('unexpected_failure', true);
}
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
// Data size / presence comes from fileSource (streamed) when set, else
// from the in-memory bytes — a streamed sub-file has empty `bytes`, so
// keying the checks below on `bytes.length` would wrongly treat it as a
// fast-only / empty sub-file.
const subSize = sub.fileSource ? sub.fileSource.fileSize : sub.bytes.length;
if (!didPut) {
log.debug('%s fast-upload hit (server already had bytes)', label);
}
};
// No uKey: the server fast-pathed this sub-file — it already holds
// (or claims to hold) the resource, so there are no bytes to push.
if (!uKey) {
if (subSize > 0) {
log.trace(
'highway_media_branch branch=fast_upload source=%j cmdId=%d size=%d',
String(sub.source),
sub.cmdId,
subSize,
);
log.debug(
'%s fast-upload hit for sub=%s (server reusing cached resource)',
label,
String(sub.source),
);
}
// NOTE: a previous attempt re-issued the request with
// `tryFastUploadCompleted: false` when the server fast-pathed the main video,
// on the theory it would force a fresh upload of a possibly-expired resource.
// Real-machine testing + kernel RE proved that ineffective — the server's
// fast-path is driven by md5-metadata existence and ignores the flag, and the
// QQ NT kernel itself does no validity check either (HandleRspUploadV3 trusts
// `fileExist` and reports success). An expired-but-still-indexed video
// resource is a platform-level limitation, not something the upload flow can
// refresh. See #145.
const upload = await requestUpload(true);
await runPuts(upload);
return upload;
continue;
}
if (subSize === 0) {
log.trace(
'highway_media_branch branch=empty_source source=%j cmdId=%d hasFastOnlyError=%s',
String(sub.source),
sub.cmdId,
Boolean(sub.fastOnlyError),
);
if (sub.fastOnlyError) {
setState('source_unavailable');
throw new Error(sub.fastOnlyError);
}
continue;
}
if (!target) {
continue;
}
log.trace(
'highway_media_branch branch=put_required source=%j cmdId=%d size=%d uKey=%j storage=%s',
String(sub.source),
sub.cmdId,
subSize,
uKey,
sub.fileSource ? 'disk' : 'buffer',
);
setState('extend_build_failed');
const extend = buildHighwayExtend(
uKey,
msgInfo,
target.ipv4s ?? [],
sub.sha1,
sub.subFileIndex ?? 0,
);
// Resolve the (lazy, cached) session BEFORE opening the ChunkSource, so
// there is no fallible await between opening the FileChunkSource handle
// and the uploadHighwayHttp call that owns closing it — otherwise a
// session-fetch failure on the first PUT would leak the open handle.
const putSession = await getSession();
// uploadHighwayHttp owns the ChunkSource and closes it exactly once.
setState('source_open_failed');
const chunkSource = sub.fileSource
? await FileChunkSource.open(sub.fileSource.filePath, sub.fileSource.fileSize)
: new BufferChunkSource(sub.bytes);
log.debug(
'%s OIDB requires bytes, PUT %d bytes (sub=%s)',
label,
subSize,
String(sub.source),
);
const t0 = Date.now();
setState('put_failed');
await uploadHighwayHttp(bridge, putSession, sub.cmdId, chunkSource, sub.md5, extend);
log.debug('%s PUT done in %dms', label, Date.now() - t0);
didPut = true;
setState('unexpected_failure', true);
}
if (!didPut) {
log.debug('%s fast-upload hit (server already had bytes)', label);
}
};
// NOTE: a previous attempt re-issued the request with
// `tryFastUploadCompleted: false` when the server fast-pathed the main video,
// on the theory it would force a fresh upload of a possibly-expired resource.
// Real-machine testing + kernel RE proved that ineffective — the server's
// fast-path is driven by md5-metadata existence and ignores the flag, and the
// QQ NT kernel itself does no validity check either (HandleRspUploadV3 trusts
// `fileExist` and reports success). An expired-but-still-indexed video
// resource is a platform-level limitation, not something the upload flow can
// refresh. See #145.
const upload = await requestUpload(true);
await runPuts(upload);
return upload;
}
// ─────────────── shared finalize ───────────────
@@ -351,26 +389,39 @@ async function runNtv2UploadOperation(
* scene-specific compatibility reserve. PTT and video omit it.
*/
export function finalizeMediaMsgInfo(
upload: NTV2UploadRespBody,
requestedPic?: PicExtBizInfo,
upload: NTV2UploadRespBody,
requestedPic?: PicExtBizInfo,
): Uint8Array {
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
if (!upload?.msgInfo) {
throw new Error('upload response missing msgInfo');
}
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: HighwayMsgInfoBody) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: HighwayMsgInfoBody) => ({
index: b.index,
picture: b.picture,
fileExist: b.fileExist,
hashSum: b.hashSum,
}));
const extBizInfo: NonNullable<EncodableMediaMsgInfo['extBizInfo']> = {};
if (upload.msgInfo.extBizInfo?.pic || requestedPic) {
// Upload responses can reuse cached image metadata. Presentation belongs
// to this send, so retain resource metadata but apply the requested style.
extBizInfo.pic = { ...upload.msgInfo.extBizInfo?.pic, ...requestedPic };
}
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;
}
const extBizInfo: NonNullable<EncodableMediaMsgInfo['extBizInfo']> = {};
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
if (upload.msgInfo.extBizInfo?.pic || requestedPic) {
// Upload responses can reuse cached image metadata. Presentation belongs
// to this send, so retain resource metadata but apply the requested style.
extBizInfo.pic = { ...upload.msgInfo.extBizInfo?.pic, ...requestedPic };
}
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 });
}
+274 -204
View File
@@ -7,155 +7,204 @@ import type { BridgeContext } from '../bridge-context';
import type { MessageElement } from '../events';
import { defaultPttTempDir, encodeSilk, getFFmpegAddon } from './ffmpeg-addon';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import {
amplitudesFromPcmS16le,
encodePttWaveform,
mergePttWaveform,
pcmS16leFromWav,
amplitudesFromPcmS16le,
encodePttWaveform,
mergePttWaveform,
pcmS16leFromWav,
} from './ptt-waveform';
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;
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>;
/** Encoded `PttWaveform` for private-chat progress / peaks. Omitted on fingerprint. */
waveform?: Uint8Array;
/** 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>;
/** Encoded `PttWaveform` for private-chat progress / peaks. Omitted on fingerprint. */
waveform?: Uint8Array;
}
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: [],
};
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);
}
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
throw new Error('record fast-upload requires md5Hex + sha1Hex');
}
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 */ } });
return pttPayloadFromFingerprint(element);
}
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 source = element.url || element.fileId || '';
if (!source) {
throw new Error('record source is empty');
}
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
const cleanups: Array<() => void> = [];
const hashes = computeHashes(silkBytes);
const waveform = await tryPttWaveform(silk.path, tempDir, cleanups);
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],
waveform,
// 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 */
}
}
};
} catch (err) {
runCleanups();
throw err;
}
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);
const waveform = await tryPttWaveform(silk.path, tempDir, cleanups);
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],
waveform,
};
} catch (err) {
runCleanups();
throw err;
}
}
async function tryPttWaveform(
silkPath: string,
tempDir: string,
cleanups: Array<() => void>,
silkPath: string,
tempDir: string,
cleanups: Array<() => void>,
): Promise<Uint8Array | undefined> {
const wavPath = path.join(tempDir, `snowluma-ptt-wave-${crypto.randomUUID()}.wav`);
cleanups.push(() => { try { fs.unlinkSync(wavPath); } catch { /* ignore */ } });
try {
const decoded = await getFFmpegAddon().decodeAudioToFmt(silkPath, wavPath, 'wav');
if (!decoded.result || !fs.existsSync(wavPath)) return undefined;
const wav = new Uint8Array(fs.readFileSync(wavPath));
const { pcm, channels } = pcmS16leFromWav(wav);
return encodePttWaveform(amplitudesFromPcmS16le(pcm, { channels }));
} catch (err) {
moduleLog.debug('ptt waveform skipped: %s', err instanceof Error ? err.message : String(err));
return undefined;
}
const wavPath = path.join(tempDir, `snowluma-ptt-wave-${crypto.randomUUID()}.wav`);
cleanups.push(() => {
try {
fs.unlinkSync(wavPath);
} catch {
/* ignore */
}
});
try {
const decoded = await getFFmpegAddon().decodeAudioToFmt(silkPath, wavPath, 'wav');
if (!decoded.result || !fs.existsSync(wavPath)) {
return undefined;
}
const wav = new Uint8Array(fs.readFileSync(wavPath));
const { pcm, channels } = pcmS16leFromWav(wav);
return encodePttWaveform(amplitudesFromPcmS16le(pcm, { channels }));
} catch (err) {
moduleLog.debug(
'ptt waveform skipped: %s',
err instanceof Error ? err.message : String(err),
);
return undefined;
}
}
/**
@@ -163,94 +212,115 @@ async function tryPttWaveform(
* a `commonElem { serviceType: 48, businessType: 22 }`.
*/
export async function uploadPttMsgInfo(
bridge: BridgeContext,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
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 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,
);
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` is the group blob lifted verbatim from NapCat
// (UploadGroupPtt.ts). Private chat must send **none**: with the
// NapCat c2c blob (UploadPrivatePtt.ts) present the receiving client
// draws the voice bubble without its progress bar, and the waveform
// we ship is silently dropped. Confirmed by A/B-ing this single field
// against an otherwise identical send (present → flat, absent → drawn).
...(isGroup
? {
bytesGeneralFlags: new Uint8Array([
0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00,
]),
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` is the group blob lifted verbatim from NapCat
// (UploadGroupPtt.ts). Private chat must send **none**: with the
// NapCat c2c blob (UploadPrivatePtt.ts) present the receiving client
// draws the voice bubble without its progress bar, and the waveform
// we ship is silently dropped. Confirmed by A/B-ing this single field
// against an otherwise identical send (present → flat, absent → drawn).
...(isGroup
? {
bytesGeneralFlags: new Uint8Array([
0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00,
]),
}
: {}),
...(ptt.waveform ? { waveform: ptt.waveform } : {}),
},
},
uploads,
label: 'ptt',
});
mergePttWaveform(upload, ptt.waveform);
const encoded = finalizeMediaMsgInfo(upload);
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
Object.assign(element, {
md5Hex: ptt.md5Hex,
sha1Hex: ptt.sha1Hex,
fileSize: ptt.fileSize,
fileName: ptt.fileName,
duration: ptt.duration,
voiceFormat: ptt.voiceFormat,
fileId: mediaNode?.fileUuid,
mediaNode,
});
return encoded;
} finally {
for (const fn of ptt.cleanups) {
try {
fn();
} catch {
/* best-effort cleanup */
}
: {}),
...(ptt.waveform ? { waveform: ptt.waveform } : {}),
},
},
uploads,
label: 'ptt',
});
mergePttWaveform(upload, ptt.waveform);
const encoded = finalizeMediaMsgInfo(upload);
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
Object.assign(element, {
md5Hex: ptt.md5Hex, sha1Hex: ptt.sha1Hex, fileSize: ptt.fileSize,
fileName: ptt.fileName, duration: ptt.duration, voiceFormat: ptt.voiceFormat,
fileId: mediaNode?.fileUuid, mediaNode,
});
return encoded;
} finally {
for (const fn of ptt.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
}
}
}
}
+151 -96
View File
@@ -8,28 +8,30 @@ export const PTT_WAVEFORM_BINS = 30;
export const PTT_WAVEFORM_SILENCE = 25;
function u16le(bytes: Uint8Array, offset: number): number {
return bytes[offset]! | (bytes[offset + 1]! << 8);
return bytes[offset]! | (bytes[offset + 1]! << 8);
}
function u32le(bytes: Uint8Array, offset: number): number {
return bytes[offset]!
| (bytes[offset + 1]! << 8)
| (bytes[offset + 2]! << 16)
| (bytes[offset + 3]! << 24);
return (
bytes[offset]! |
(bytes[offset + 1]! << 8) |
(bytes[offset + 2]! << 16) |
(bytes[offset + 3]! << 24)
);
}
function fourcc(bytes: Uint8Array, offset: number): string {
return String.fromCharCode(
bytes[offset]!,
bytes[offset + 1]!,
bytes[offset + 2]!,
bytes[offset + 3]!,
);
return String.fromCharCode(
bytes[offset]!,
bytes[offset + 1]!,
bytes[offset + 2]!,
bytes[offset + 3]!,
);
}
function s16le(bytes: Uint8Array, offset: number): number {
const raw = u16le(bytes, offset);
return raw >= 0x8000 ? raw - 0x10000 : raw;
const raw = u16le(bytes, offset);
return raw >= 0x8000 ? raw - 0x10000 : raw;
}
/**
@@ -37,48 +39,71 @@ function s16le(bytes: Uint8Array, offset: number): number {
* Rejects non-PCM / non-16-bit so a botched transcode cannot invent bars.
*/
export function pcmS16leFromWav(wav: Uint8Array): {
pcm: Uint8Array;
channels: number;
sampleRate: number;
pcm: Uint8Array;
channels: number;
sampleRate: number;
} {
if (wav.length < 12) throw new Error('wav is truncated');
if (fourcc(wav, 0) !== 'RIFF' || fourcc(wav, 8) !== 'WAVE') {
throw new Error('wav is not a RIFF/WAVE file');
}
let offset = 12;
let channels = 0;
let sampleRate = 0;
let bitsPerSample = 0;
let audioFormat = 0;
let data: Uint8Array | undefined;
while (offset + 8 <= wav.length) {
const id = fourcc(wav, offset);
const size = u32le(wav, offset + 4);
const start = offset + 8;
if (start + size > wav.length) throw new Error('wav chunk is truncated');
if (id === 'fmt ') {
if (size < 16) throw new Error('wav fmt chunk is short');
audioFormat = u16le(wav, start);
channels = u16le(wav, start + 2);
sampleRate = u32le(wav, start + 4);
bitsPerSample = u16le(wav, start + 14);
} else if (id === 'data') {
data = wav.subarray(start, start + size);
if (wav.length < 12) {
throw new Error('wav is truncated');
}
offset = start + size + (size & 1);
}
if (!data) throw new Error('wav has no data chunk');
if (audioFormat !== 1) throw new Error(`wav format ${audioFormat} is not PCM`);
if (channels < 1) throw new Error('wav channel count is invalid');
if (bitsPerSample !== 16) throw new Error(`wav bits ${bitsPerSample} is not s16`);
return { pcm: data, channels, sampleRate };
if (fourcc(wav, 0) !== 'RIFF' || fourcc(wav, 8) !== 'WAVE') {
throw new Error('wav is not a RIFF/WAVE file');
}
let offset = 12;
let channels = 0;
let sampleRate = 0;
let bitsPerSample = 0;
let audioFormat = 0;
let data: Uint8Array | undefined;
while (offset + 8 <= wav.length) {
const id = fourcc(wav, offset);
const size = u32le(wav, offset + 4);
const start = offset + 8;
if (start + size > wav.length) {
throw new Error('wav chunk is truncated');
}
if (id === 'fmt ') {
if (size < 16) {
throw new Error('wav fmt chunk is short');
}
audioFormat = u16le(wav, start);
channels = u16le(wav, start + 2);
sampleRate = u32le(wav, start + 4);
bitsPerSample = u16le(wav, start + 14);
} else if (id === 'data') {
data = wav.subarray(start, start + size);
}
offset = start + size + (size & 1);
}
if (!data) {
throw new Error('wav has no data chunk');
}
if (audioFormat !== 1) {
throw new Error(`wav format ${audioFormat} is not PCM`);
}
if (channels < 1) {
throw new Error('wav channel count is invalid');
}
if (bitsPerSample !== 16) {
throw new Error(`wav bits ${bitsPerSample} is not s16`);
}
return { pcm: data, channels, sampleRate };
}
function silentWaveform(bins: number): Uint8Array {
return new Uint8Array(bins).fill(PTT_WAVEFORM_SILENCE);
return new Uint8Array(bins).fill(PTT_WAVEFORM_SILENCE);
}
/**
@@ -87,66 +112,96 @@ function silentWaveform(bins: number): Uint8Array {
* so private-chat clients still draw a progress track.
*/
export function amplitudesFromPcmS16le(
pcm: Uint8Array,
options: { channels?: number; bins?: number } = {},
pcm: Uint8Array,
options: { channels?: number; bins?: number } = {},
): Uint8Array {
const channels = options.channels ?? 1;
const bins = options.bins ?? PTT_WAVEFORM_BINS;
if (channels < 1 || bins < 1) throw new Error('waveform channels/bins must be >= 1');
const channels = options.channels ?? 1;
const bins = options.bins ?? PTT_WAVEFORM_BINS;
const frameSize = channels * 2;
const frames = Math.floor(pcm.length / frameSize);
if (frames === 0) return silentWaveform(bins);
const out = new Uint8Array(bins);
let any = false;
for (let bin = 0; bin < bins; bin += 1) {
const start = Math.floor((bin * frames) / bins);
let end = Math.floor(((bin + 1) * frames) / bins);
if (end <= start) end = start + 1;
let peak = 0;
for (let frame = start; frame < end && frame < frames; frame += 1) {
const base = frame * frameSize;
for (let channel = 0; channel < channels; channel += 1) {
const sample = Math.abs(s16le(pcm, base + channel * 2));
if (sample > peak) peak = sample;
}
if (channels < 1 || bins < 1) {
throw new Error('waveform channels/bins must be >= 1');
}
const amplitude = Math.min(255, Math.round((peak * 255) / 32767));
if (amplitude > 0) any = true;
out[bin] = amplitude;
}
return any ? out : silentWaveform(bins);
const frameSize = channels * 2;
const frames = Math.floor(pcm.length / frameSize);
if (frames === 0) {
return silentWaveform(bins);
}
const out = new Uint8Array(bins);
let any = false;
for (let bin = 0; bin < bins; bin += 1) {
const start = Math.floor((bin * frames) / bins);
let end = Math.floor(((bin + 1) * frames) / bins);
if (end <= start) {
end = start + 1;
}
let peak = 0;
for (let frame = start; frame < end && frame < frames; frame += 1) {
const base = frame * frameSize;
for (let channel = 0; channel < channels; channel += 1) {
const sample = Math.abs(s16le(pcm, base + channel * 2));
if (sample > peak) {
peak = sample;
}
}
}
const amplitude = Math.min(255, Math.round((peak * 255) / 32767));
if (amplitude > 0) {
any = true;
}
out[bin] = amplitude;
}
return any ? out : silentWaveform(bins);
}
/** Encode amplitudes as the blob `ParsePttWave` accepts (count == bytes). */
export function encodePttWaveform(amplitudes: Uint8Array): Uint8Array {
if (amplitudes.length === 0) throw new Error('ptt waveform amplitudes are empty');
return protobuf_encode<PttWaveform>({
size: amplitudes.length,
amplitudes,
});
if (amplitudes.length === 0) {
throw new Error('ptt waveform amplitudes are empty');
}
return protobuf_encode<PttWaveform>({
size: amplitudes.length,
amplitudes,
});
}
export function decodePttWaveform(bytes: Uint8Array): { size: number; amplitudes: Uint8Array } {
const decoded = protobuf_decode<PttWaveform>(bytes);
const amplitudes = decoded.amplitudes ?? new Uint8Array(0);
const size = decoded.size ?? 0;
if (size !== amplitudes.length) {
throw new Error(`ptt waveform count ${size} != amplitudes ${amplitudes.length}`);
}
return { size, amplitudes };
const decoded = protobuf_decode<PttWaveform>(bytes);
const amplitudes = decoded.amplitudes ?? new Uint8Array(0);
const size = decoded.size ?? 0;
if (size !== amplitudes.length) {
throw new Error(`ptt waveform count ${size} != amplitudes ${amplitudes.length}`);
}
return { size, amplitudes };
}
/** Stamp computed waveform onto the upload response so finalize cannot drop it. */
export function mergePttWaveform(
upload: NTV2UploadRespBody,
waveform: Uint8Array | undefined,
upload: NTV2UploadRespBody,
waveform: Uint8Array | undefined,
): void {
if (!waveform || waveform.length === 0 || !upload.msgInfo) return;
const ext = upload.msgInfo.extBizInfo ?? {};
upload.msgInfo.extBizInfo = {
...ext,
ptt: { ...ext.ptt, waveform },
};
if (!waveform || waveform.length === 0 || !upload.msgInfo) {
return;
}
const ext = upload.msgInfo.extBizInfo ?? {};
upload.msgInfo.extBizInfo = {
...ext,
ptt: { ...ext.ptt, waveform },
};
}
+125 -81
View File
@@ -8,82 +8,119 @@ const SHA1_BLOCK_SIZE = 64;
const SHA1_DIGEST_SIZE = 20;
function rotl(x: number, n: number): number {
return ((x << n) | (x >>> (32 - n))) >>> 0;
return ((x << n) | (x >>> (32 - n))) >>> 0;
}
export class Sha1Stream {
private readonly state = new Uint32Array(5);
private readonly count = new Uint32Array(2); // [low, high] bit count
private readonly buffer = new Uint8Array(SHA1_BLOCK_SIZE);
private readonly state = new Uint32Array(5);
private readonly count = new Uint32Array(2); // [low, high] bit count
private readonly buffer = new Uint8Array(SHA1_BLOCK_SIZE);
constructor() { this.reset(); }
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;
}
private transform(data: Uint8Array, offset: number): void {
const w = new Uint32Array(80);
const dv = new DataView(data.buffer, data.byteOffset + offset, 64);
for (let i = 0; i < 16; i++) w[i] = dv.getUint32(i * 4, false); // big-endian
for (let i = 16; i < 80; i++) {
w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
constructor() {
this.reset();
}
let a = this.state[0], b = this.state[1], c = this.state[2], d = this.state[3], 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 = (temp + rotl(a, 5) + e + w[i]) >>> 0;
e = d; d = c; c = rotl(b, 30); b = a; a = temp;
}
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 {
const len = data.length;
let index = (this.count[0] >>> 3) & 0x3F;
this.count[0] = (this.count[0] + (len << 3)) >>> 0;
if (this.count[0] < (len << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
this.count[1] = (this.count[1] + (len >>> 29)) >>> 0;
let partLen = SHA1_BLOCK_SIZE - index;
let i = 0;
if (len >= partLen) {
this.buffer.set(data.subarray(0, partLen), index);
this.transform(this.buffer, 0);
i = partLen;
while (i + SHA1_BLOCK_SIZE <= len) {
this.transform(data, i);
i += SHA1_BLOCK_SIZE;
}
index = 0;
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.set(data.subarray(i), index);
}
/** 输出当前 state(20B)。littleEndian=true 小端,false 大端。不 finalize。 */
hash(littleEndian: boolean): Uint8Array {
const digest = new Uint8Array(SHA1_DIGEST_SIZE);
const dv = new DataView(digest.buffer);
for (let i = 0; i < 5; i++) {
if (littleEndian) dv.setUint32(i * 4, this.state[i], true);
else dv.setUint32(i * 4, this.state[i], false);
private transform(data: Uint8Array, offset: number): void {
const w = new Uint32Array(80);
const dv = new DataView(data.buffer, data.byteOffset + offset, 64);
for (let i = 0; i < 16; i++) {
w[i] = dv.getUint32(i * 4, false);
} // big-endian
for (let i = 16; i < 80; i++) {
w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
}
let a = this.state[0],
b = this.state[1],
c = this.state[2],
d = this.state[3],
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 = (temp + rotl(a, 5) + e + w[i]) >>> 0;
e = d;
d = c;
c = rotl(b, 30);
b = a;
a = temp;
}
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 {
const len = data.length;
let index = (this.count[0] >>> 3) & 0x3f;
this.count[0] = (this.count[0] + (len << 3)) >>> 0;
if (this.count[0] < len << 3) {
this.count[1] = (this.count[1] + 1) >>> 0;
}
this.count[1] = (this.count[1] + (len >>> 29)) >>> 0;
let partLen = SHA1_BLOCK_SIZE - index;
let i = 0;
if (len >= partLen) {
this.buffer.set(data.subarray(0, partLen), index);
this.transform(this.buffer, 0);
i = partLen;
while (i + SHA1_BLOCK_SIZE <= len) {
this.transform(data, i);
i += SHA1_BLOCK_SIZE;
}
index = 0;
}
this.buffer.set(data.subarray(i), index);
}
/** 输出当前 state(20B)。littleEndian=true 小端,false 大端。不 finalize。 */
hash(littleEndian: boolean): Uint8Array {
const digest = new Uint8Array(SHA1_DIGEST_SIZE);
const dv = new DataView(digest.buffer);
for (let i = 0; i < 5; i++) {
if (littleEndian) {
dv.setUint32(i * 4, this.state[i], true);
} else {
dv.setUint32(i * 4, this.state[i], false);
}
}
return digest;
}
return digest;
}
}
/**
@@ -94,19 +131,26 @@ export class Sha1Stream {
* 用单个 Sha1Stream 增量 update:每片只喂新增的 sliceSize 字节再快照,O(n)。
* (sliceSize=1MB 是 SHA1 块大小 64B 的整数倍,增量 update 不会残留半块。)
*/
export function computeSha1StateV(bytes: Uint8Array, sliceCount: number, sliceSize: number): Uint8Array[] {
const states: Uint8Array[] = [];
const sha1 = new Sha1Stream();
for (let i = 0; i < sliceCount; i++) {
const start = i * sliceSize;
const end = Math.min(start + sliceSize, bytes.length);
sha1.update(bytes.subarray(start, end));
if (i !== sliceCount - 1) {
states.push(sha1.hash(true)); // 小端中间 state,不 finalize
} else {
// 最后一片:标准整文件 SHA1(有 finalize)
states.push(new Uint8Array(createHash('sha1').update(Buffer.from(bytes)).digest()));
export function computeSha1StateV(
bytes: Uint8Array,
sliceCount: number,
sliceSize: number,
): Uint8Array[] {
const states: Uint8Array[] = [];
const sha1 = new Sha1Stream();
for (let i = 0; i < sliceCount; i++) {
const start = i * sliceSize;
const end = Math.min(start + sliceSize, bytes.length);
sha1.update(bytes.subarray(start, end));
if (i !== sliceCount - 1) {
states.push(sha1.hash(true)); // 小端中间 state,不 finalize
} else {
// 最后一片:标准整文件 SHA1(有 finalize)
states.push(new Uint8Array(createHash('sha1').update(Buffer.from(bytes)).digest()));
}
}
}
return states;
return states;
}
+255 -162
View File
@@ -24,10 +24,10 @@ import path from 'path';
import { randomUUID } from 'crypto';
import { createLogger } from '@snowluma/common/logger';
import {
downloadHttp,
inlineBase64Payload,
resolveLocalFilePath,
type DownloadSink,
downloadHttp,
inlineBase64Payload,
resolveLocalFilePath,
type DownloadSink,
} from './utils';
const log = createLogger('Highway.Stage');
@@ -44,109 +44,155 @@ const REAPER_INTERVAL_MS = 5 * 60 * 1000;
const active = new Set<string>();
export interface StagedSource {
/** Local disk path the uploader reads from. */
filePath: string;
fileSize: number;
/** Caller-facing name (URL basename / original local basename); '' for base64. */
fileName: string;
/** Remove the staged temp (our hardlink/copy/downloaded file). Idempotent,
* best-effort; never throws. Never touches the caller's original file. */
cleanup(): Promise<void>;
/** Local disk path the uploader reads from. */
filePath: string;
fileSize: number;
/** Caller-facing name (URL basename / original local basename); '' for base64. */
fileName: string;
/** Remove the staged temp (our hardlink/copy/downloaded file). Idempotent,
* best-effort; never throws. Never touches the caller's original file. */
cleanup(): Promise<void>;
}
let reaperTimer: NodeJS.Timeout | null = null;
function ensureReaper(): void {
if (reaperTimer) return;
reaperTimer = setInterval(() => { void sweepStagedUploads(); }, REAPER_INTERVAL_MS);
reaperTimer.unref(); // never pin the event loop
void sweepStagedUploads(); // startup sweep of crash orphans
if (reaperTimer) {
return;
}
reaperTimer = setInterval(() => {
void sweepStagedUploads();
}, REAPER_INTERVAL_MS);
reaperTimer.unref(); // never pin the event loop
void sweepStagedUploads(); // startup sweep of crash orphans
}
/** Reap staged temps older than the TTL, skipping any path currently in use.
* Best-effort; never throws. Exposed for an explicit startup/interval hook. */
export async function sweepStagedUploads(now: number = Date.now()): Promise<number> {
let removed = 0;
let names: string[];
try {
names = await fsp.readdir(STAGE_DIR);
} catch {
return 0; // dir not created yet
}
await Promise.all(names.map(async (n) => {
const p = path.join(STAGE_DIR, n);
if (active.has(p)) return; // in-flight — never reap
let removed = 0;
let names: string[];
try {
const s = await fsp.stat(p);
if (now - s.mtimeMs > STAGE_TTL_MS) {
await fsp.rm(p, { force: true });
removed += 1;
}
} catch { /* vanished / racing cleanup */ }
}));
if (removed > 0) log.debug('reaped %d stale staged upload temp(s)', removed);
return removed;
names = await fsp.readdir(STAGE_DIR);
} catch {
return 0; // dir not created yet
}
await Promise.all(
names.map(async (n) => {
const p = path.join(STAGE_DIR, n);
if (active.has(p)) {
return;
} // in-flight — never reap
try {
const s = await fsp.stat(p);
if (now - s.mtimeMs > STAGE_TTL_MS) {
await fsp.rm(p, { force: true });
removed += 1;
}
} catch {
/* vanished / racing cleanup */
}
}),
);
if (removed > 0) {
log.debug('reaped %d stale staged upload temp(s)', removed);
}
return removed;
}
function tempPaths(ext: string): { partPath: string; finalPath: string } {
const id = randomUUID();
const base = path.join(STAGE_DIR, `stage-${id}${ext}`);
return { partPath: `${base}.part`, finalPath: base };
const id = randomUUID();
const base = path.join(STAGE_DIR, `stage-${id}${ext}`);
return { partPath: `${base}.part`, finalPath: base };
}
/** fsync the file's directory entry so the rename survives a crash (POSIX). */
async function fsyncDir(): Promise<void> {
try {
const dh = await fsp.open(STAGE_DIR, 'r');
try { await dh.sync(); } finally { await dh.close(); }
} catch { /* some platforms reject directory fsync — best effort */ }
try {
const dh = await fsp.open(STAGE_DIR, 'r');
try {
await dh.sync();
} finally {
await dh.close();
}
} catch {
/* some platforms reject directory fsync — best effort */
}
}
async function finalizeRename(partPath: string, finalPath: string): Promise<void> {
await fsp.rename(partPath, finalPath);
await fsyncDir();
await fsp.rename(partPath, finalPath);
await fsyncDir();
}
function registerStaged(filePath: string, fileSize: number, fileName: string): StagedSource {
active.add(filePath);
let done = false;
return {
filePath,
fileSize,
fileName,
async cleanup() {
if (done) return;
done = true;
active.delete(filePath);
await fsp.unlink(filePath).catch(() => { /* best-effort */ });
},
};
active.add(filePath);
let done = false;
return {
filePath,
fileSize,
fileName,
async cleanup() {
if (done) {
return;
}
done = true;
active.delete(filePath);
await fsp.unlink(filePath).catch(() => {
/* best-effort */
});
},
};
}
/** Disk sink for `downloadHttp`: streams chunks to a FileHandle, fsyncs on
* success, and closes-before-unlink on failure. Backpressure comes from
* awaiting each `fh.write`. */
function fileSink(partPath: string): DownloadSink<void> {
let opened: Promise<import('fs').promises.FileHandle> | null = null;
const open = () => (opened ??= fsp.open(partPath, 'w'));
return {
async write(chunk) { const fh = await open(); await fh.write(chunk); },
async done() {
const fh = await open(); // create even for an empty body
await fh.sync();
await fh.close();
},
async discard() {
if (opened) { try { const fh = await opened; await fh.close(); } catch { /* already closed */ } }
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
},
};
let opened: Promise<import('fs').promises.FileHandle> | null = null;
const open = () => (opened ??= fsp.open(partPath, 'w'));
return {
async write(chunk) {
const fh = await open();
await fh.write(chunk);
},
async done() {
const fh = await open(); // create even for an empty body
await fh.sync();
await fh.close();
},
async discard() {
if (opened) {
try {
const fh = await opened;
await fh.close();
} catch {
/* already closed */
}
}
await fsp.unlink(partPath).catch(() => {
/* best-effort */
});
},
};
}
/** base64 decoded byte length without allocating the buffer. */
function base64DecodedLength(b64: string): number {
const clean = b64.replace(/[^A-Za-z0-9+/=]/g, '');
const pad = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;
return Math.floor((clean.length * 3) / 4) - pad;
const clean = b64.replace(/[^A-Za-z0-9+/=]/g, '');
const pad = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;
return Math.floor((clean.length * 3) / 4) - pad;
}
/**
@@ -156,99 +202,146 @@ function base64DecodedLength(b64: string): number {
* upload is done (or fails) to remove the staged temp.
*/
export async function stageSourceToDisk(source: string, maxBytes: number): Promise<StagedSource> {
if (!source) throw new Error('stage source is empty');
ensureReaper();
await fsp.mkdir(STAGE_DIR, { recursive: true });
if (!source) {
throw new Error('stage source is empty');
}
// ── inline Base64 (`base64://` or RFC 2397 `data:`) ────────────────────
const b64 = inlineBase64Payload(source);
if (b64 !== null) {
const decodedLen = base64DecodedLength(b64);
if (decodedLen > maxBytes) {
throw new Error(`stage source too large: ${decodedLen} > ${maxBytes}`);
ensureReaper();
await fsp.mkdir(STAGE_DIR, { recursive: true });
// ── inline Base64 (`base64://` or RFC 2397 `data:`) ────────────────────
const b64 = inlineBase64Payload(source);
if (b64 !== null) {
const decodedLen = base64DecodedLength(b64);
if (decodedLen > maxBytes) {
throw new Error(`stage source too large: ${decodedLen} > ${maxBytes}`);
}
const bytes = Buffer.from(b64, 'base64');
if (bytes.length > maxBytes) {
throw new Error(`stage source too large: ${bytes.length} > ${maxBytes}`);
}
const { partPath, finalPath } = tempPaths('.bin');
active.add(partPath);
try {
const fh = await fsp.open(partPath, 'w');
try {
await fh.write(bytes);
await fh.sync();
} finally {
await fh.close();
}
await finalizeRename(partPath, finalPath);
} catch (e) {
await fsp.unlink(partPath).catch(() => {
/* best-effort */
});
throw e;
} finally {
active.delete(partPath);
}
log.debug('staged inline base64 source (%d bytes)', bytes.length);
return registerStaged(finalPath, bytes.length, '');
}
const bytes = Buffer.from(b64, 'base64');
if (bytes.length > maxBytes) {
throw new Error(`stage source too large: ${bytes.length} > ${maxBytes}`);
// ── http(s):// ─────────────────────────────────────────────────────────
if (/^https?:\/\//i.test(source)) {
const { partPath, finalPath } = tempPaths('.bin');
active.add(partPath);
let fileName = '';
try {
const r = await downloadHttp<void>(source, 'stage', maxBytes, () => fileSink(partPath));
fileName = r.fileName;
await finalizeRename(partPath, finalPath);
} catch (e) {
await fsp.unlink(partPath).catch(() => {
/* best-effort */
});
throw e;
} finally {
active.delete(partPath);
}
const { size } = await fsp.stat(finalPath);
log.debug('staged http source %s (%d bytes)', fileName || '(unnamed)', size);
return registerStaged(finalPath, size, fileName);
}
const { partPath, finalPath } = tempPaths('.bin');
active.add(partPath);
// ── local path / file:// ───────────────────────────────────────────────
const local = resolveLocalFilePath(source);
if (!local) {
throw new Error('stage source is not a local file');
}
const real = await fsp.realpath(local); // resolve symlinks — hardlink the target, not the link
const st = await fsp.stat(real);
if (!st.isFile()) {
throw new Error(`stage source is not a regular file: ${local}`);
}
if (st.size > maxBytes) {
throw new Error(`stage source too large: ${st.size} > ${maxBytes}`);
}
const fileName = path.basename(local); // caller-facing name (before symlink resolution)
const { partPath, finalPath } = tempPaths(path.extname(local) || '.bin');
// Reserve finalPath in `active` BEFORE it exists on disk. A hardlink inherits
// the source's (often old) mtime, so — unlike the fresh-mtime http/base64/copy
// temps whose TTL saves them during the pre-register gap — only the active-set
// can keep the age reaper from deleting this live staged file in the window
// between link and registerStaged.
active.add(finalPath);
let staged: 'link' | 'copy';
try {
const fh = await fsp.open(partPath, 'w');
try { await fh.write(bytes); await fh.sync(); } finally { await fh.close(); }
await finalizeRename(partPath, finalPath);
try {
await fsp.link(real, finalPath); // O(1) hardlink; pins the inode against caller-side unlink
staged = 'link';
} catch {
// Any link() failure (cross-fs EXDEV, hardlink protection, permissions,
// link-count/platform limits) — fall back to a streamed copy of the
// readable source (disk-to-disk, never buffered in RAM).
active.add(partPath);
try {
await fsp.copyFile(real, partPath);
const fh = await fsp.open(partPath, 'r+'); // fsync copied data before rename
try {
await fh.sync();
} finally {
await fh.close();
}
await finalizeRename(partPath, finalPath);
staged = 'copy';
} finally {
active.delete(partPath);
}
}
} catch (e) {
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
throw e;
} finally {
active.delete(partPath);
active.delete(finalPath);
await fsp.unlink(finalPath).catch(() => {
/* best-effort */
});
await fsp.unlink(partPath).catch(() => {
/* best-effort */
});
throw e;
}
log.debug('staged inline base64 source (%d bytes)', bytes.length);
return registerStaged(finalPath, bytes.length, '');
}
// ── http(s):// ─────────────────────────────────────────────────────────
if (/^https?:\/\//i.test(source)) {
const { partPath, finalPath } = tempPaths('.bin');
active.add(partPath);
let fileName = '';
try {
const r = await downloadHttp<void>(source, 'stage', maxBytes, () => fileSink(partPath));
fileName = r.fileName;
await finalizeRename(partPath, finalPath);
} catch (e) {
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
throw e;
} finally {
active.delete(partPath);
}
const { size } = await fsp.stat(finalPath);
log.debug('staged http source %s (%d bytes)', fileName || '(unnamed)', size);
return registerStaged(finalPath, size, fileName);
}
// ── local path / file:// ───────────────────────────────────────────────
const local = resolveLocalFilePath(source);
if (!local) throw new Error('stage source is not a local file');
const real = await fsp.realpath(local); // resolve symlinks — hardlink the target, not the link
const st = await fsp.stat(real);
if (!st.isFile()) throw new Error(`stage source is not a regular file: ${local}`);
if (st.size > maxBytes) throw new Error(`stage source too large: ${st.size} > ${maxBytes}`);
const fileName = path.basename(local); // caller-facing name (before symlink resolution)
const { partPath, finalPath } = tempPaths(path.extname(local) || '.bin');
// Reserve finalPath in `active` BEFORE it exists on disk. A hardlink inherits
// the source's (often old) mtime, so — unlike the fresh-mtime http/base64/copy
// temps whose TTL saves them during the pre-register gap — only the active-set
// can keep the age reaper from deleting this live staged file in the window
// between link and registerStaged.
active.add(finalPath);
let staged: 'link' | 'copy';
try {
try {
await fsp.link(real, finalPath); // O(1) hardlink; pins the inode against caller-side unlink
staged = 'link';
} catch {
// Any link() failure (cross-fs EXDEV, hardlink protection, permissions,
// link-count/platform limits) — fall back to a streamed copy of the
// readable source (disk-to-disk, never buffered in RAM).
active.add(partPath);
try {
await fsp.copyFile(real, partPath);
const fh = await fsp.open(partPath, 'r+'); // fsync copied data before rename
try { await fh.sync(); } finally { await fh.close(); }
await finalizeRename(partPath, finalPath);
staged = 'copy';
} finally {
active.delete(partPath);
}
}
} catch (e) {
active.delete(finalPath);
await fsp.unlink(finalPath).catch(() => { /* best-effort */ });
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
throw e;
}
log.debug('staged local source %s via %s (%d bytes)', fileName, staged, st.size);
return registerStaged(finalPath, st.size, fileName);
log.debug('staged local source %s via %s (%d bytes)', fileName, staged, st.size);
return registerStaged(finalPath, st.size, fileName);
}
+397 -265
View File
@@ -4,8 +4,8 @@ import path from 'path';
import { fileURLToPath } from 'url';
export interface LoadedBinary {
bytes: Uint8Array;
fileName: string;
bytes: Uint8Array;
fileName: string;
}
/**
@@ -40,19 +40,19 @@ const FETCH_TIMEOUT_MS = 60_000;
* `dev/napcatQQInside/packages/napcat-common/src/file.ts:101-142,359-369`.
*/
const DOWNLOAD_USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
export interface ImageHashes {
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
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;
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
width: number;
height: number;
}
// --- Binary source loading ---
@@ -66,45 +66,68 @@ export interface ImageFormat {
* the local-file path.
*/
export function inlineBase64Payload(source: string): string | null {
if (/^base64:\/\//i.test(source)) return source.slice(9);
if (!/^data:/i.test(source)) return null;
if (/^base64:\/\//i.test(source)) {
return source.slice(9);
}
const comma = source.indexOf(',');
if (comma < 0) throw new Error('data URL source is missing its payload separator');
if (!/^data:/i.test(source)) {
return null;
}
const metadata = source.slice(5, comma);
if (!/;base64$/i.test(metadata)) {
throw new Error('data URL source must use base64 encoding');
}
return source.slice(comma + 1);
const comma = source.indexOf(',');
if (comma < 0) {
throw new Error('data URL source is missing its payload separator');
}
const metadata = source.slice(5, comma);
if (!/;base64$/i.test(metadata)) {
throw new Error('data URL source must use base64 encoding');
}
return source.slice(comma + 1);
}
export function resolveLocalFilePath(source: string): string | null {
if (!source) return null;
if (/^(?:base64:\/\/|data:)/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 (!source) {
return null;
}
if (process.platform !== 'win32' && filePath.startsWith('//')) {
filePath = filePath.replace(/^\/+/, '/');
if (/^(?:base64:\/\/|data:)/i.test(source)) {
return null;
}
}
// Windows-style paths can arrive from file:///C:/... as /C:/...
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
return filePath;
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;
}
/**
@@ -112,7 +135,7 @@ export function resolveLocalFilePath(source: string): string | null {
* a too-large response just re-downloads the same oversized body.
*/
export function tooLarge(message: string): Error {
return Object.assign(new Error(message), { noRetry: true });
return Object.assign(new Error(message), { noRetry: true });
}
/**
@@ -121,9 +144,9 @@ export function tooLarge(message: string): Error {
* attempt and `discard()`ed on failure so a Referer retry starts clean.
*/
export interface DownloadSink<T> {
write(chunk: Uint8Array): Promise<void> | void;
done(): Promise<T> | T;
discard(): Promise<void> | void;
write(chunk: Uint8Array): Promise<void> | void;
done(): Promise<T> | T;
discard(): Promise<void> | void;
}
/**
@@ -136,285 +159,394 @@ export interface DownloadSink<T> {
* or disk.
*/
export async function downloadHttp<T>(
source: string,
resourceName: string,
maxBytes: number,
makeSink: () => DownloadSink<T>,
source: string,
resourceName: string,
maxBytes: number,
makeSink: () => DownloadSink<T>,
): Promise<{ result: T; fileName: string }> {
const fileName = guessFileNameFromUrl(source);
const fileName = guessFileNameFromUrl(source);
const attempt = async (headers: Record<string, string>): Promise<T> => {
const resp = await fetch(source, {
headers,
redirect: 'follow',
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 tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
}
const attempt = async (headers: Record<string, string>): Promise<T> => {
const resp = await fetch(source, {
headers,
redirect: 'follow',
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
const sink = makeSink();
try {
const reader = resp.body?.getReader();
if (!reader) {
const buf = new Uint8Array(await resp.arrayBuffer());
if (buf.length > maxBytes) {
throw tooLarge(`${resourceName} too large: ${buf.length} > ${maxBytes}`);
if (!resp.ok) {
throw new Error(`HTTP download failed: ${resp.status}`);
}
await sink.write(buf);
} else {
let total = 0;
const declared = Number(resp.headers.get('content-length') ?? '0');
if (Number.isFinite(declared) && declared > maxBytes) {
throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
}
const sink = makeSink();
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 tooLarge(`${resourceName} too large: > ${maxBytes}`);
}
await sink.write(value);
}
} finally {
reader.releaseLock();
}
}
return await sink.done();
} catch (e) {
await sink.discard();
throw e;
}
};
const reader = resp.body?.getReader();
if (!reader) {
const buf = new Uint8Array(await resp.arrayBuffer());
if (buf.length > maxBytes) {
throw tooLarge(`${resourceName} too large: ${buf.length} > ${maxBytes}`);
}
await sink.write(buf);
} else {
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 tooLarge(`${resourceName} too large: > ${maxBytes}`);
}
await sink.write(value);
}
} finally {
reader.releaseLock();
}
}
return await sink.done();
} catch (e) {
await sink.discard();
throw e;
}
};
// First try with a browser UA only. On any non-size failure — a
// network-level `fetch failed` (connection reset by an anti-bot front-end)
// or a 403/4xx from anti-hotlink — retry once with a Referer pointing at the
// resource itself, the common bypass for same-origin hotlink checks.
const baseHeaders: Record<string, string> = {
'User-Agent': DOWNLOAD_USER_AGENT,
Accept: '*/*',
};
// First try with a browser UA only. On any non-size failure — a
// network-level `fetch failed` (connection reset by an anti-bot front-end)
// or a 403/4xx from anti-hotlink — retry once with a Referer pointing at the
// resource itself, the common bypass for same-origin hotlink checks.
const baseHeaders: Record<string, string> = {
'User-Agent': DOWNLOAD_USER_AGENT,
Accept: '*/*',
};
try {
return { result: await attempt(baseHeaders), fileName };
} catch (err) {
if ((err as { noRetry?: boolean } | null)?.noRetry) throw err;
try {
return { result: await attempt({ ...baseHeaders, Referer: source }), fileName };
} catch {
throw err;
return { result: await attempt(baseHeaders), fileName };
} catch (err) {
if ((err as { noRetry?: boolean } | null)?.noRetry) {
throw err;
}
try {
return { result: await attempt({ ...baseHeaders, Referer: source }), fileName };
} catch {
throw err;
}
}
}
}
export async function loadBinarySource(
source: string,
resourceName: string,
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
source: string,
resourceName: string,
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
): Promise<LoadedBinary> {
if (!source) throw new Error(`${resourceName} source is empty`);
const inlinePayload = inlineBase64Payload(source);
if (inlinePayload !== null) {
const bytes = Buffer.from(inlinePayload, 'base64');
if (bytes.length > maxBytes) {
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
if (!source) {
throw new Error(`${resourceName} source is empty`);
}
return { bytes, fileName: '' };
}
if (/^https?:\/\//i.test(source)) {
// Buffered sink: accumulate the streamed chunks and assemble them into one
// contiguous buffer. The shared `downloadHttp` owns the transport, the
// incremental length check, and the Referer retry.
const memorySink = (): DownloadSink<Uint8Array> => {
const chunks: Uint8Array[] = [];
let total = 0;
return {
write(chunk) { chunks.push(chunk); total += chunk.byteLength; },
done() {
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
return bytes;
},
discard() { chunks.length = 0; },
};
};
const { result, fileName } = await downloadHttp(source, resourceName, maxBytes, memorySink);
return { bytes: result, fileName };
}
const inlinePayload = inlineBase64Payload(source);
const filePath = resolveLocalFilePath(source);
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
if (inlinePayload !== null) {
const bytes = Buffer.from(inlinePayload, 'base64');
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 };
if (bytes.length > maxBytes) {
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
}
return { bytes, fileName: '' };
}
if (/^https?:\/\//i.test(source)) {
// Buffered sink: accumulate the streamed chunks and assemble them into one
// contiguous buffer. The shared `downloadHttp` owns the transport, the
// incremental length check, and the Referer retry.
const memorySink = (): DownloadSink<Uint8Array> => {
const chunks: Uint8Array[] = [];
let total = 0;
return {
write(chunk) {
chunks.push(chunk);
total += chunk.byteLength;
},
done() {
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return bytes;
},
discard() {
chunks.length = 0;
},
};
};
const { result, fileName } = await downloadHttp(source, resourceName, maxBytes, memorySink);
return { bytes: result, 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 };
}
export function guessFileNameFromUrl(url: string): string {
const queryPos = url.search(/[?#]/);
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
const lastSlash = pathPart.lastIndexOf('/');
const raw = lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
if (!raw) return '';
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
const queryPos = url.search(/[?#]/);
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
const lastSlash = pathPart.lastIndexOf('/');
const raw = lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
if (!raw) {
return '';
}
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
}
// --- 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'),
};
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());
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];
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;
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);
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;
return (
(data[offset] |
(data[offset + 1] << 8) |
(data[offset + 2] << 16) |
(data[offset + 3] << 24)) >>>
0
);
}
function readLE24(data: Uint8Array, offset: number): number {
return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16);
return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16);
}
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
let width = 0;
let height = 0;
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 };
// 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 };
}
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) {
// VP8X canvas width/height are 24-bit LITTLE-endian (Minus-One). Reading
// them big-endian inflated dims to absurd values (e.g. 1920×1080 →
// 8324865×3605505), cropping the QQ thumbnail. (issue #112)
width = readLE24(bytes, 24) + 1;
height = readLE24(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;
// 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) {
// VP8X canvas width/height are 24-bit LITTLE-endian (Minus-One). Reading
// them big-endian inflated dims to absurd values (e.g. 1920×1080 →
// 8324865×3605505), cropping the QQ thumbnail. (issue #112)
width = readLE24(bytes, 24) + 1;
height = readLE24(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 };
}
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;
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),
};
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),
};
}
+381 -338
View File
@@ -6,17 +6,12 @@ import type { BridgeContext } from '../bridge-context';
import type { MessageElement } from '../events';
import { getFFmpegAddon } from './ffmpeg-addon';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import {
computeHashes,
detectImageFormat,
loadBinarySource,
resolveLocalFilePath,
} from './utils';
import { computeHashes, detectImageFormat, loadBinarySource, resolveLocalFilePath } from './utils';
import { stageSourceToDisk } from './stage';
import { hashFileStreaming } from './hash-file';
import { Sha1Stream } from './sha1-stream';
@@ -24,9 +19,9 @@ import { Sha1Stream } from './sha1-stream';
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;
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;
@@ -47,19 +42,28 @@ const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
const SHA1_BLOCK_SIZE = 64;
export function getVideoSourceSize(element: MessageElement): number | null {
if (element.fileSize && element.fileSize > 0) return element.fileSize;
const source = element.url || element.fileId || '';
if (!source) return null;
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
return fs.statSync(local).size;
}
return null;
if (element.fileSize && element.fileSize > 0) {
return element.fileSize;
}
const source = element.url || element.fileId || '';
if (!source) {
return null;
}
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
return fs.statSync(local).size;
}
return null;
}
const FALLBACK_THUMB = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAtAAAAUACAIAAADhrPJqAAAACXBIWXMAAAABAAAAAQBPJcTWAAAQAElEQVR4nO3WQQkAMAzAwOqYf6FVEQblTkGemQcAEJvfAQDAfYYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEALine truncated
'base64',
'iVBORw0KGgoAAAANSUhEUgAAAtAAAAUACAIAAADhrPJqAAAACXBIWXMAAAABAAAAAQBPJcTWAAAQAElEQVR4nO3WQQkAMAzAwOqYf6FVEQblTkGemQcAEJvfAQDAfYYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOLine truncated
'base64',
);
// [#145] The fast-upload (fingerprint / forward) path has no video bytes to
@@ -75,84 +79,86 @@ const FAST_UPLOAD_FALLBACK_WIDTH = FALLBACK_THUMB_FORMAT.width || 720;
const FAST_UPLOAD_FALLBACK_HEIGHT = FALLBACK_THUMB_FORMAT.height || 1280;
interface VideoPayload {
/** Main-file bytes. Empty on the normal path (streamed from `fileSource`)
* and when forwarding from cached fingerprints (fastOnly). */
bytes: Uint8Array;
/** Normal path: the staged video streams from this disk file instead of
* buffering `bytes`. Absent for the fingerprint fast path. */
fileSource?: { filePath: string; fileSize: number };
md5: Uint8Array;
sha1: Uint8Array;
sha1Blocks: Uint8Array[];
md5Hex: string;
sha1Hex: string;
fileName: 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;
/** Baseline stat of the staged file captured before hashing; re-checked
* before the upload to fail cleanly if the source was mutated mid-send.
* Absent for the fingerprint fast path. */
guard?: { size: number; mtimeMs: number };
/** Release the staged temp (hardlink / download). Best-effort, idempotent. */
cleanup: () => Promise<void>;
/** Main-file bytes. Empty on the normal path (streamed from `fileSource`)
* and when forwarding from cached fingerprints (fastOnly). */
bytes: Uint8Array;
/** Normal path: the staged video streams from this disk file instead of
* buffering `bytes`. Absent for the fingerprint fast path. */
fileSource?: { filePath: string; fileSize: number };
md5: Uint8Array;
sha1: Uint8Array;
sha1Blocks: Uint8Array[];
md5Hex: string;
sha1Hex: string;
fileName: 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;
/** Baseline stat of the staged file captured before hashing; re-checked
* before the upload to fail cleanly if the source was mutated mid-send.
* Absent for the fingerprint fast path. */
guard?: { size: number; mtimeMs: number };
/** Release the staged temp (hardlink / download). Best-effort, idempotent. */
cleanup: () => Promise<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,
// Declared cover dims == FALLBACK_THUMB's real pixels (same source as the
// video fallback), so content and declared size always agree.
width: FAST_UPLOAD_FALLBACK_WIDTH,
height: FAST_UPLOAD_FALLBACK_HEIGHT,
};
const bytes = new Uint8Array(FALLBACK_THUMB);
const hashes = computeHashes(bytes);
return {
bytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
// Declared cover dims == FALLBACK_THUMB's real pixels (same source as the
// video fallback), so content and declared size always agree.
width: FAST_UPLOAD_FALLBACK_WIDTH,
height: FAST_UPLOAD_FALLBACK_HEIGHT,
};
}
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`,
fileSize: element.fileSize ?? 0,
// Zero-trust on the fast-upload path (no bytes to probe): `|| fallback` not
// `??`, so a cached-but-zero value is replaced too. width/height=0 → the
// receiver shows 文件已过期; duration=0 → every client renders 00:00 (#145).
width: element.width || FAST_UPLOAD_FALLBACK_WIDTH,
height: element.height || FAST_UPLOAD_FALLBACK_HEIGHT,
duration: element.duration || 1,
videoFormat: element.videoFormat ?? 0,
thumb: makeFallbackThumb(),
fastOnly: true,
cleanup: async () => { /* nothing staged */ },
};
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`,
fileSize: element.fileSize ?? 0,
// Zero-trust on the fast-upload path (no bytes to probe): `|| fallback` not
// `??`, so a cached-but-zero value is replaced too. width/height=0 → the
// receiver shows 文件已过期; duration=0 → every client renders 00:00 (#145).
width: element.width || FAST_UPLOAD_FALLBACK_WIDTH,
height: element.height || FAST_UPLOAD_FALLBACK_HEIGHT,
duration: element.duration || 1,
videoFormat: element.videoFormat ?? 0,
thumb: makeFallbackThumb(),
fastOnly: true,
cleanup: async () => {
/* nothing staged */
},
};
}
interface ThumbPayload {
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
width: number;
height: number;
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
width: number;
height: number;
}
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
@@ -163,140 +169,160 @@ interface ThumbPayload {
// split as computeSha1StateV), replacing a ~110-line hand-rolled, untested
// SHA1 duplicate.
export function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
const sha1 = new Sha1Stream();
const blocks: Uint8Array[] = [];
let bytesRead = 0;
let offset = 0;
while (offset + SHA1_BLOCK_SIZE <= bytes.length) {
sha1.update(bytes.subarray(offset, offset + SHA1_BLOCK_SIZE));
offset += SHA1_BLOCK_SIZE;
bytesRead += SHA1_BLOCK_SIZE;
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
blocks.push(sha1.hash(true)); // little-endian intermediate state
const sha1 = new Sha1Stream();
const blocks: Uint8Array[] = [];
let bytesRead = 0;
let offset = 0;
while (offset + SHA1_BLOCK_SIZE <= bytes.length) {
sha1.update(bytes.subarray(offset, offset + SHA1_BLOCK_SIZE));
offset += SHA1_BLOCK_SIZE;
bytesRead += SHA1_BLOCK_SIZE;
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
blocks.push(sha1.hash(true)); // little-endian intermediate state
}
}
}
// Overall SHA1 (finalized) via Node crypto — the reference impl.
blocks.push(new Uint8Array(crypto.createHash('sha1').update(Buffer.from(bytes)).digest()));
return blocks;
// Overall SHA1 (finalized) via Node crypto — the reference impl.
blocks.push(new Uint8Array(crypto.createHash('sha1').update(Buffer.from(bytes)).digest()));
return blocks;
}
// ─────────────── thumb extraction ───────────────
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
thumb: ThumbPayload;
width: number;
height: number;
duration: number;
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;
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 (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) {
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);
}
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 fmt = detectImageFormat(thumbBytes);
width = width || fmt.width || 1;
height = height || fmt.height || 1;
duration = duration || 1;
// The cover sub-file must declare its OWN pixel size, which can be smaller
// than the video: the ffmpeg addon downscales large frames (4K/8K → ≤1080p)
// so the JPEG cover stays under QQ's 1 MiB cover limit. Fall back to the video
// dims when the format can't be read. For 1080p and custom-thumb sends the
// cover already equals the video size, so this is a no-op there.
const thumbWidth = fmt.width || width;
const thumbHeight = fmt.height || height;
// The cover sub-file must declare its OWN pixel size, which can be smaller
// than the video: the ffmpeg addon downscales large frames (4K/8K → ≤1080p)
// so the JPEG cover stays under QQ's 1 MiB cover limit. Fall back to the video
// dims when the format can't be read. For 1080p and custom-thumb sends the
// cover already equals the video size, so this is a no-op there.
const thumbWidth = fmt.width || width;
const thumbHeight = fmt.height || height;
const hashes = computeHashes(thumbBytes);
return {
width,
height,
duration,
thumb: {
bytes: thumbBytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
width: thumbWidth,
height: thumbHeight,
},
};
const hashes = computeHashes(thumbBytes);
return {
width,
height,
duration,
thumb: {
bytes: thumbBytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
width: thumbWidth,
height: thumbHeight,
},
};
}
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
throw new Error('video fast-upload requires md5Hex + sha1Hex');
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
throw new Error('video fast-upload requires md5Hex + sha1Hex');
}
return videoPayloadFromFingerprint(element);
}
return videoPayloadFromFingerprint(element);
}
const source = element.url || element.fileId || '';
if (!source) throw new Error('video source is empty');
const source = element.url || element.fileId || '';
// Stage onto a local disk path (hardlink / streamed download) and hash it in
// one streaming pass — the video is never fully buffered in RAM. maxBytes =
// MAX_VIDEO_SIZE; oversize sources throw here and the OneBot layer re-routes
// them to the file pipeline (matches the message-actions size fallback).
const staged = await stageSourceToDisk(source, MAX_VIDEO_SIZE);
try {
if (staged.fileSize === 0) throw new Error('video file is empty');
if (!source) {
throw new Error('video source is empty');
}
// Baseline stat captured BEFORE hashing; re-checked before the upload so a
// source mutated mid-send fails cleanly (see uploadVideoMsgInfo).
const g = await fsp.stat(staged.filePath);
const hashes = await hashFileStreaming(staged.filePath);
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
// Stage onto a local disk path (hardlink / streamed download) and hash it in
// one streaming pass — the video is never fully buffered in RAM. maxBytes =
// MAX_VIDEO_SIZE; oversize sources throw here and the OneBot layer re-routes
// them to the file pipeline (matches the message-actions size fallback).
const staged = await stageSourceToDisk(source, MAX_VIDEO_SIZE);
return {
bytes: new Uint8Array(0),
fileSource: { filePath: staged.filePath, fileSize: staged.fileSize },
md5: hashes.md5,
sha1: hashes.sha1,
sha1Blocks: hashes.sha1Blocks,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: (element.fileName || staged.fileName) || `${hashes.md5Hex}.mp4`,
fileSize: staged.fileSize,
width,
height,
duration,
videoFormat: 0,
thumb,
fastOnly: false,
guard: { size: g.size, mtimeMs: g.mtimeMs },
cleanup: staged.cleanup,
};
} catch (err) {
await staged.cleanup();
throw err;
}
try {
if (staged.fileSize === 0) {
throw new Error('video file is empty');
}
// Baseline stat captured BEFORE hashing; re-checked before the upload so a
// source mutated mid-send fails cleanly (see uploadVideoMsgInfo).
const g = await fsp.stat(staged.filePath);
const hashes = await hashFileStreaming(staged.filePath);
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
return {
bytes: new Uint8Array(0),
fileSource: { filePath: staged.filePath, fileSize: staged.fileSize },
md5: hashes.md5,
sha1: hashes.sha1,
sha1Blocks: hashes.sha1Blocks,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: element.fileName || staged.fileName || `${hashes.md5Hex}.mp4`,
fileSize: staged.fileSize,
width,
height,
duration,
videoFormat: 0,
thumb,
fastOnly: false,
guard: { size: g.size, mtimeMs: g.mtimeMs },
cleanup: staged.cleanup,
};
} catch (err) {
await staged.cleanup();
throw err;
}
}
// ─────────────── exported entry ───────────────
@@ -309,143 +335,160 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
* (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,
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,
fileSource: video.fileSource, // streamed from disk (undefined on the fingerprint fast path)
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 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),
);
// Mutation guard: the streaming path reads the staged file twice (hash pass
// in loadVideo, then the highway PUT). For a hardlinked local source a
// concurrent in-place write would make the uploaded bytes disagree with the
// hashes we already sent. Re-stat before the PUT and fail cleanly if the
// file changed since the baseline (the server's per-chunk md5 check is the
// backstop during the PUT itself).
if (video.guard && video.fileSource) {
const now = await fsp.stat(video.fileSource.filePath);
if (now.size !== video.guard.size || now.mtimeMs !== video.guard.mtimeMs) {
throw new Error('video source changed during send (mutated between hashing and upload)');
}
}
try {
const uploads: MediaSubFileUpload[] = [
{
source: 'top',
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
bytes: video.bytes,
fileSource: video.fileSource, // streamed from disk (undefined on the fingerprint fast path)
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: {
// Mutation guard: the streaming path reads the staged file twice (hash pass
// in loadVideo, then the highway PUT). For a hardlinked local source a
// concurrent in-place write would make the uploaded bytes disagree with the
// hashes we already sent. Re-stat before the PUT and fail cleanly if the
// file changed since the baseline (the server's per-chunk md5 check is the
// backstop during the PUT itself).
if (video.guard && video.fileSource) {
const now = await fsp.stat(video.fileSource.filePath);
if (now.size !== video.guard.size || now.mtimeMs !== video.guard.mtimeMs) {
throw new Error(
'video source changed during send (mutated between hashing and upload)',
);
}
}
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 },
// [#145] Group video MUST carry real width/height. A real QQ
// group video's MsgInfo has them (e.g. 296x640); sending 0x0
// makes QQ-NT receivers (Android especially) fail to lay out
// the video tile and render 文件已过期 even though the resource
// is fresh and downloadable (iOS is lenient — shows expired but
// still opens). c2c is left at 0 because the QQ-NT server has
// been observed to reject non-zero dimensions there with a
// schema-mismatch error (no c2c regression coverage yet).
height: isGroup ? video.height : 0,
width: isGroup ? video.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',
);
const encoded = finalizeMediaMsgInfo(upload);
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
Object.assign(element, {
md5Hex: video.md5Hex,
sha1Hex: video.sha1Hex,
fileSize: video.fileSize,
fileHash: video.md5Hex,
fileSha1: video.sha1Hex,
fileName: 'nya.mp4',
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
// [#145] Group video MUST carry real width/height. A real QQ
// group video's MsgInfo has them (e.g. 296x640); sending 0x0
// makes QQ-NT receivers (Android especially) fail to lay out
// the video tile and render 文件已过期 even though the resource
// is fresh and downloadable (iOS is lenient — shows expired but
// still opens). c2c is left at 0 because the QQ-NT server has
// been observed to reject non-zero dimensions there with a
// schema-mismatch error (no c2c regression coverage yet).
height: isGroup ? video.height : 0,
width: isGroup ? video.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');
const encoded = finalizeMediaMsgInfo(upload);
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
Object.assign(element, {
md5Hex: video.md5Hex, sha1Hex: video.sha1Hex, fileSize: video.fileSize,
fileName: 'nya.mp4', duration: video.duration, width: video.width, height: video.height, videoFormat: 0,
fileId: mediaNode?.fileUuid, mediaNode,
});
return encoded;
} finally {
await video.cleanup();
}
duration: video.duration,
width: video.width,
height: video.height,
videoFormat: 0,
fileId: mediaNode?.fileUuid,
mediaNode,
});
return encoded;
} finally {
await video.cleanup();
}
}
File diff suppressed because it is too large. Load diff
+15 -11
View File
@@ -19,15 +19,19 @@ export const KICK_NT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.KickNT';
type BotOfflineEvent = Extract<QQEventVariant, { kind: 'bot_offline' }>;
export function parseKickNT(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
const resp = protobuf_decode<KickNTResponse>(pkt.body);
if (!resp) return [];
const ev: BotOfflineEvent = {
kind: 'bot_offline',
// KickNT carries no timestamp — stamp with receive time.
time: Math.floor(Date.now() / 1000),
selfUin: Number(pkt.uin) || Number(identity.uin) || 0,
tag: resp.title ?? '', // tips_title — the short title
message: resp.tips ?? '', // tips_content — the description / reason
};
return [ev];
const resp = protobuf_decode<KickNTResponse>(pkt.body);
if (!resp) {
return [];
}
const ev: BotOfflineEvent = {
kind: 'bot_offline',
// KickNT carries no timestamp — stamp with receive time.
time: Math.floor(Date.now() / 1000),
selfUin: Number(pkt.uin) || Number(identity.uin) || 0,
tag: resp.title ?? '', // tips_title — the short title
message: resp.tips ?? '', // tips_content — the description / reason
};
return [ev];
}
+90 -62
View File
@@ -18,7 +18,8 @@ const C2C_CONTROL_TYPES = new Set<number>([141, 166, 167]);
// phantom (#102) is one of them.
const C2C_CONTROL_CMDS = new Set<number>([1, 73, 75, 129, 131, 133, 135, 192]);
export type MessageSurvival = 'drop-control' | 'drop-receipt' | 'drop-blank' | 'keep-undecoded' | 'keep';
export type MessageSurvival =
'drop-control' | 'drop-receipt' | 'drop-blank' | 'keep-undecoded' | 'keep';
/**
* Whether a push is a C2C control/system signal that QQ NT never renders as a
@@ -29,7 +30,7 @@ export type MessageSurvival = 'drop-control' | 'drop-receipt' | 'drop-blank' | '
* the post-decode filter still returns `drop-control` for the same decision.
*/
export function isC2cControlPush(head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>): boolean {
return C2C_CONTROL_TYPES.has(head.msgType) && C2C_CONTROL_CMDS.has(head.c2cCmd);
return C2C_CONTROL_TYPES.has(head.msgType) && C2C_CONTROL_CMDS.has(head.c2cCmd);
}
/**
@@ -37,10 +38,10 @@ export function isC2cControlPush(head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>):
* decoded to zero elements AND its body carried nothing decodable.
*/
export function isBlankMessage(
elements: readonly unknown[],
body: PushMsgBody | undefined,
elements: readonly unknown[],
body: PushMsgBody | undefined,
): boolean {
return elements.length === 0 && !hasDecodableContent(body);
return elements.length === 0 && !hasDecodableContent(body);
}
/**
@@ -50,76 +51,103 @@ export function isBlankMessage(
* elements is keep-undecoded, not blank.
*/
export function classifyMessageSurvival(
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
): MessageSurvival {
if (isC2cControlPush(head)) return 'drop-control';
if (isOfflineFileReceipt(body)) return 'drop-receipt';
if (elements.length !== 0) return 'keep';
if (hasDecodableContent(body)) return 'keep-undecoded';
return 'drop-blank';
if (isC2cControlPush(head)) {
return 'drop-control';
}
if (isOfflineFileReceipt(body)) {
return 'drop-receipt';
}
if (elements.length !== 0) {
return 'keep';
}
if (hasDecodableContent(body)) {
return 'keep-undecoded';
}
return 'drop-blank';
}
/** Summarise a body that decoded to zero elements despite carrying content. */
export function describeUndecodedBody(body: PushMsgBody | undefined): string {
const elems = (body?.richText?.elems ?? []) as Elem[];
const parts = elems.map((e) => {
if (e.commonElem) {
const ce = e.commonElem;
const pb = ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : '';
return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`;
const elems = (body?.richText?.elems ?? []) as Elem[];
const parts = elems.map((e) => {
if (e.commonElem) {
const ce = e.commonElem;
const pb =
ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : '';
return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`;
}
const keys = Object.keys(e).filter((k) => (e as Record<string, unknown>)[k] != null);
return keys.join('+') || '(empty)';
});
const extras: string[] = [];
if (body?.richText?.ptt) {
extras.push('ptt');
}
const keys = Object.keys(e).filter((k) => (e as Record<string, unknown>)[k] != null);
return keys.join('+') || '(empty)';
});
const extras: string[] = [];
if (body?.richText?.ptt) extras.push('ptt');
if (body?.richText?.notOnlineFile) extras.push('notOnlineFile');
if (body?.msgContent && body.msgContent.length > 0) {
extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`);
}
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
if (body?.richText?.notOnlineFile) {
extras.push('notOnlineFile');
}
if (body?.msgContent && body.msgContent.length > 0) {
extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`);
}
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
}
/** Keep when the message should appear as a bubble. Warns on keep-undecoded. */
export function keepDecodedMessage(
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd' | 'sequence' | 'subType'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
kind: string,
fromUin: number,
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd' | 'sequence' | 'subType'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
kind: string,
fromUin: number,
): boolean {
const survival = classifyMessageSurvival(head, elements, body);
if (survival === 'drop-control' || survival === 'drop-receipt' || survival === 'drop-blank') return false;
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind,
sequence: head.sequence,
fromUin,
msgType: head.msgType,
subType: head.subType,
body,
});
}
return true;
const survival = classifyMessageSurvival(head, elements, body);
if (survival === 'drop-control' || survival === 'drop-receipt' || survival === 'drop-blank') {
return false;
}
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind,
sequence: head.sequence,
fromUin,
msgType: head.msgType,
subType: head.subType,
body,
});
}
return true;
}
export function warnUndecodedMessage(info: {
kind: string;
sequence: number;
fromUin: number;
msgType: number;
subType: number;
body: PushMsgBody | undefined;
kind: string;
sequence: number;
fromUin: number;
msgType: number;
subType: number;
body: PushMsgBody | undefined;
}): void {
log.warn(
'message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
info.kind,
info.sequence,
info.fromUin,
info.msgType,
info.subType,
describeUndecodedBody(info.body),
);
log.warn(
'message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
info.kind,
info.sequence,
info.fromUin,
info.msgType,
info.subType,
describeUndecodedBody(info.body),
);
}
+89 -71
View File
@@ -1,60 +1,75 @@
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, PushMsgBody as ProtoMessage, ResponseHead } from '@snowluma/proto-defs/message';
import type {
ContentHead,
MessageBody,
PushMsg,
PushMsgBody as ProtoMessage,
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;
/** C2C command (`contentHead` field 3). Discriminates control pushes — see
* `isC2cControlPush` in ./blank-filter. */
readonly c2cCmd: number;
/** Sender-local C2C client sequence (field 5), or the group sequence. */
readonly sequence: number;
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
readonly ntMsgSeq: number;
readonly timestamp: number;
readonly msgId: number;
readonly msgType: number;
readonly subType: number;
/** C2C command (`contentHead` field 3). Discriminates control pushes — see
* `isC2cControlPush` in ./blank-filter. */
readonly c2cCmd: number;
/** Sender-local C2C client sequence (field 5), or the group sequence. */
readonly sequence: number;
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
readonly ntMsgSeq: 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;
/**
* Historical messages reuse the live decoder but must not replay
* live-only identity observations.
*/
readonly isHistorical: boolean;
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;
/**
* Historical messages reuse the live decoder but must not replay
* live-only identity observations.
*/
readonly isHistorical: boolean;
}
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
if (pkt.body.length === 0) return 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;
// `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);
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
if (!push?.message) {
return null;
}
return buildContextFromMessage(push.message, selfUin, identity, false);
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) {
selfUin = n;
}
}
return buildContextFromMessage(push.message, selfUin, identity, false);
}
/**
@@ -65,41 +80,44 @@ export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPus
* regular msg-push decoders parse fetched history unchanged.
*/
export function buildContextFromMessage(
msg: ProtoMessage,
selfUin: number,
identity: IdentityService,
isHistorical = true,
msg: ProtoMessage,
selfUin: number,
identity: IdentityService,
isHistorical = true,
): MsgPushContext | null {
if (!msg.contentHead) return null;
if (!msg.contentHead) {
return null;
}
const head: MsgPushHead = {
msgType: msg.contentHead.msgType ?? 0,
subType: msg.contentHead.subType ?? 0,
c2cCmd: msg.contentHead.c2cCmd ?? 0,
sequence: msg.contentHead.sequence ?? 0,
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 0,
timestamp: msg.contentHead.timestamp ?? 0,
msgId: msg.contentHead.msgId ?? 0,
};
const head: MsgPushHead = {
msgType: msg.contentHead.msgType ?? 0,
subType: msg.contentHead.subType ?? 0,
c2cCmd: msg.contentHead.c2cCmd ?? 0,
sequence: msg.contentHead.sequence ?? 0,
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 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 fromUin = 0;
let fromUid = '';
const content = msg.body?.msgContent ?? new Uint8Array(0);
if (msg.responseHead) {
fromUin = msg.responseHead.fromUin ?? 0;
fromUid = msg.responseHead.fromUid ?? '';
}
return {
head,
fromUin,
fromUid,
selfUin,
content,
body: msg.body,
responseHead: msg.responseHead,
identity,
isHistorical,
};
const content = msg.body?.msgContent ?? new Uint8Array(0);
return {
head,
fromUin,
fromUid,
selfUin,
content,
body: msg.body,
responseHead: msg.responseHead,
identity,
isHistorical,
};
}
@@ -1,30 +1,27 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type {
FriendAddEvent,
FriendPokeEvent,
FriendRequestEvent,
OnlineDeviceInfo,
OnlineDeviceKind,
QQEventVariant,
FriendAddEvent,
FriendPokeEvent,
FriendRequestEvent,
OnlineDeviceInfo,
OnlineDeviceKind,
QQEventVariant,
} from '../../events';
import type {
FriendRecall,
FriendRemarkChangedNotify,
FriendRequest,
GeneralGrayTipInfo,
InputStatusNotify,
NewFriend,
OnlineDeviceNotify,
ProfileLikeTip,
FriendRecall,
FriendRemarkChangedNotify,
FriendRequest,
GeneralGrayTipInfo,
InputStatusNotify,
NewFriend,
OnlineDeviceNotify,
ProfileLikeTip,
} from '@snowluma/proto-defs/notify';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
buildTemplateMap, c2cRoutingUin, findTemplateValue,
resolveUidToUin,
} from '../helpers';
import { buildTemplateMap, c2cRoutingUin, findTemplateValue, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
@@ -34,67 +31,86 @@ type FriendProfileLikeEvent = Extract<QQEventVariant, { kind: 'friend_profile_li
const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.PttTransResult: return decodePttTransResult(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);
case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx);
case Event0x210SubType.OnlineDevicesNotice: return decodeOnlineDevices(ctx);
case Event0x210SubType.FriendRemarkChangedNotice: return decodeFriendRemarkChanged(ctx);
case Event0x210SubType.ProfileLikeNotice: return decodeProfileLike(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 [];
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice:
return decodeFriendRequest(ctx);
case Event0x210SubType.PttTransResult:
return decodePttTransResult(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);
case Event0x210SubType.InputStatusNotice:
return decodeInputStatus(ctx);
case Event0x210SubType.OnlineDevicesNotice:
return decodeOnlineDevices(ctx);
case Event0x210SubType.FriendRemarkChangedNotice:
return decodeFriendRemarkChanged(ctx);
case Event0x210SubType.ProfileLikeNotice:
return decodeProfileLike(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 decodeFriendRemarkChanged(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<FriendRemarkChangedNotify>(ctx.content);
const change = notify?.change;
const uid = change?.target?.uid?.trim() ?? '';
const rawUin = change?.target?.uin;
const uin = rawUin === undefined ? 0 : Number(rawUin);
if (rawUin !== undefined && (!Number.isSafeInteger(uin) || uin <= 0)) {
throw new Error(`friend remark synchronization has invalid UIN ${rawUin}`);
}
if (!uid && uin <= 0) {
throw new Error('friend remark synchronization is missing both UID and UIN');
}
if (change?.remark === undefined) {
throw new Error(`friend remark synchronization is missing the remark value (uid=${uid} uin=${uin})`);
}
if (ctx.isHistorical) return [];
return [{
kind: 'friend_remark_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUid: uid,
userUin: uin,
remark: change.remark,
}];
const notify = protobuf_decode<FriendRemarkChangedNotify>(ctx.content);
const change = notify?.change;
const uid = change?.target?.uid?.trim() ?? '';
const rawUin = change?.target?.uin;
const uin = rawUin === undefined ? 0 : Number(rawUin);
if (rawUin !== undefined && (!Number.isSafeInteger(uin) || uin <= 0)) {
throw new Error(`friend remark synchronization has invalid UIN ${rawUin}`);
}
if (!uid && uin <= 0) {
throw new Error('friend remark synchronization is missing both UID and UIN');
}
if (change?.remark === undefined) {
throw new Error(
`friend remark synchronization is missing the remark value (uid=${uid} uin=${uin})`,
);
}
if (ctx.isHistorical) {
return [];
}
return [
{
kind: 'friend_remark_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUid: uid,
userUin: uin,
remark: change.remark,
},
];
}
const COMPUTER_CLIENT_TYPES = new Set([1, 5, 15]);
@@ -102,56 +118,79 @@ const PHONE_CLIENT_TYPES = new Set([2, 3, 4, 6, 7, 12]);
const PAD_CLIENT_TYPES = new Set([8, 9, 10, 11, 13]);
function onlineDeviceKind(clientType: number): OnlineDeviceKind {
if (COMPUTER_CLIENT_TYPES.has(clientType)) return 'computer';
if (PHONE_CLIENT_TYPES.has(clientType)) return 'phone';
if (PAD_CLIENT_TYPES.has(clientType)) return 'pad';
unknownLog.warn('online-device snapshot contains unknown clientType=%d', clientType);
return 'unknown';
if (COMPUTER_CLIENT_TYPES.has(clientType)) {
return 'computer';
}
if (PHONE_CLIENT_TYPES.has(clientType)) {
return 'phone';
}
if (PAD_CLIENT_TYPES.has(clientType)) {
return 'pad';
}
unknownLog.warn('online-device snapshot contains unknown clientType=%d', clientType);
return 'unknown';
}
function onlineDeviceClientType(rawClientType: number): number {
// QQ's OnRecvSysMsg path stores this wire field as an unsigned byte before
// it reaches DecodeOnLineDev. Higher bits carry terminal metadata and must
// not participate in device classification (live examples: 0x14702 -> 2,
// 0x10107 -> 7).
return rawClientType & 0xff;
// QQ's OnRecvSysMsg path stores this wire field as an unsigned byte before
// it reaches DecodeOnLineDev. Higher bits carry terminal metadata and must
// not participate in device classification (live examples: 0x14702 -> 2,
// 0x10107 -> 7).
return rawClientType & 0xff;
}
function decodeOnlineDevices(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<OnlineDeviceNotify>(ctx.content);
if (!notify) return [];
const devices: OnlineDeviceInfo[] = [];
const seenDeviceKinds = new Set<OnlineDeviceKind>();
for (const [index, item] of (notify.devices ?? []).entries()) {
const appId = item.appId ?? 0;
const rawClientType = item.clientType ?? 0;
if (appId <= 0 || rawClientType <= 0) {
throw new Error(
`online-device entry ${index} is missing appId or clientType `
+ `(appIdPresent=${item.appId != null} clientTypePresent=${item.clientType != null})`,
);
const notify = protobuf_decode<OnlineDeviceNotify>(ctx.content);
if (!notify) {
return [];
}
const clientType = onlineDeviceClientType(rawClientType);
const deviceKind = onlineDeviceKind(clientType);
// QQ's DecodeOnLineDevList exposes one entry per derived devUid
// (computer/pad/phone), retaining the first item in each category.
if (seenDeviceKinds.has(deviceKind)) continue;
seenDeviceKinds.add(deviceKind);
devices.push({
appId,
instanceId: item.instanceId ?? 0,
clientType,
platform: item.platform ?? 0,
deviceName: item.deviceName ?? '',
deviceKind,
});
}
return [{
kind: 'online_devices_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
devices,
}];
const devices: OnlineDeviceInfo[] = [];
const seenDeviceKinds = new Set<OnlineDeviceKind>();
for (const [index, item] of (notify.devices ?? []).entries()) {
const appId = item.appId ?? 0;
const rawClientType = item.clientType ?? 0;
if (appId <= 0 || rawClientType <= 0) {
throw new Error(
`online-device entry ${index} is missing appId or clientType ` +
`(appIdPresent=${item.appId != null} clientTypePresent=${item.clientType != null})`,
);
}
const clientType = onlineDeviceClientType(rawClientType);
const deviceKind = onlineDeviceKind(clientType);
// QQ's DecodeOnLineDevList exposes one entry per derived devUid
// (computer/pad/phone), retaining the first item in each category.
if (seenDeviceKinds.has(deviceKind)) {
continue;
}
seenDeviceKinds.add(deviceKind);
devices.push({
appId,
instanceId: item.instanceId ?? 0,
clientType,
platform: item.platform ?? 0,
deviceName: item.deviceName ?? '',
deviceKind,
});
}
return [
{
kind: 'online_devices_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
devices,
},
];
}
// Voice-to-text async result push. Wire shape (live-verified):
@@ -159,69 +198,95 @@ function decodeOnlineDevices(ctx: MsgPushContext): QQEventVariant[] {
// `msgId` is the correlation key a pending fetch_ptt_text waits on; we surface
// it + the recognised text as an internal `ptt_trans_result` event.
function decodePttTransResult(ctx: MsgPushContext): QQEventVariant[] {
const push = protobuf_decode<PttTransPush>(ctx.content);
const item = push?.item;
if (!item) return [];
const msgId = Number(item.msgId ?? 0n);
const text = item.text ?? '';
if (!msgId || !text) return [];
return [{ kind: 'ptt_trans_result', time: ctx.head.timestamp, selfUin: ctx.selfUin, msgId, text }];
const push = protobuf_decode<PttTransPush>(ctx.content);
const item = push?.item;
if (!item) {
return [];
}
const msgId = Number(item.msgId ?? 0n);
const text = item.text ?? '';
if (!msgId || !text) {
return [];
}
return [
{ kind: 'ptt_trans_result', time: ctx.head.timestamp, selfUin: ctx.selfUin, msgId, text },
];
}
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),
fromUid: sourceUid,
message: request.info.message ?? '',
flag: sourceUid,
};
return [ev];
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),
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),
msgSeq: recall.info.clientSequence ?? 0,
clientSeq: recall.info.clientSequence ?? 0,
recalledBySelf: isSelfRecall,
};
return [ev];
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),
msgSeq: recall.info.clientSequence ?? 0,
clientSeq: recall.info.clientSequence ?? 0,
recalledBySelf: isSelfRecall,
};
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 = c2cRoutingUin(ctx.identity, 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];
const nf = protobuf_decode<NewFriend>(ctx.content);
if (!nf?.info) {
return [];
}
const newFriendUid = nf.info.uid ?? '';
const newFriendUin = c2cRoutingUin(ctx.identity, 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];
}
// C2C "对方正在输入…" input-status push. Body (`InputStatusNotify`) rides in
@@ -231,25 +296,29 @@ function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
// synthesises the status text from that type, so we do the same for OneBot
// parity (NapCat's `onInputStatusPush` → `notice/notify` `input_status`).
function decodeInputStatus(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<InputStatusNotify>(ctx.content);
const fromUid = notify?.fromUid ?? '';
if (!fromUid) return [];
const eventType = notify.notifyItem?.eventType ?? 1;
const ev: FriendInputStatusEvent = {
kind: 'friend_input_status',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, fromUid),
userUid: fromUid,
eventType,
statusText: inputStatusText(eventType),
};
return [ev];
const notify = protobuf_decode<InputStatusNotify>(ctx.content);
const fromUid = notify?.fromUid ?? '';
if (!fromUid) {
return [];
}
const eventType = notify.notifyItem?.eventType ?? 1;
const ev: FriendInputStatusEvent = {
kind: 'friend_input_status',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, fromUid),
userUid: fromUid,
eventType,
statusText: inputStatusText(eventType),
};
return [ev];
}
// The client's own strings (wrapper.linux.node @0xB8FFE0 / @0xB90000).
function inputStatusText(eventType: number): string {
return eventType === 3 ? '对方正在讲话...' : '对方正在输入...';
return eventType === 3 ? '对方正在讲话...' : '对方正在输入...';
}
// subType 39 is multiplexed; body.msgContent decodes as ProfileLikeTip and is a
@@ -258,61 +327,71 @@ function inputStatusText(eventType: number): string {
// `times` is the like count parsed out of `detail.txt` ("赞了我的资料卡N次").
// Field layout confirmed byte-exact against real on-wire captures.
function decodeProfileLike(ctx: MsgPushContext): QQEventVariant[] {
const tip = protobuf_decode<ProfileLikeTip>(ctx.content);
// msgType 0 is the proto default → omitted on the wire → decodes as undefined,
// so treat missing as 0 (matches NapCat's `msgType !== 0` check).
if (!tip || (tip.msgType ?? 0) !== 0 || (tip.subType ?? 0) !== 203) return [];
const msg = tip.content?.msg;
const detail = msg?.detail;
const operatorUin = Number(detail?.uin ?? 0n);
if (!operatorUin) return [];
const times = Number.parseInt((detail?.txt ?? '').match(/\d+/)?.[0] ?? '0', 10) || 0;
const ev: FriendProfileLikeEvent = {
kind: 'friend_profile_like',
time: msg?.time || ctx.head.timestamp,
selfUin: ctx.selfUin,
operatorUin,
operatorNick: detail?.nickname ?? '',
times,
};
return [ev];
const tip = protobuf_decode<ProfileLikeTip>(ctx.content);
// msgType 0 is the proto default → omitted on the wire → decodes as undefined,
// so treat missing as 0 (matches NapCat's `msgType !== 0` check).
if (!tip || (tip.msgType ?? 0) !== 0 || (tip.subType ?? 0) !== 203) {
return [];
}
const msg = tip.content?.msg;
const detail = msg?.detail;
const operatorUin = Number(detail?.uin ?? 0n);
if (!operatorUin) {
return [];
}
const times = Number.parseInt((detail?.txt ?? '').match(/\d+/)?.[0] ?? '0', 10) || 0;
const ev: FriendProfileLikeEvent = {
kind: 'friend_profile_like',
time: msg?.time || ctx.head.timestamp,
selfUin: ctx.selfUin,
operatorUin,
operatorNick: detail?.nickname ?? '',
times,
};
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 senderUin = resolveUidToUin(ctx.identity, 0, actor);
const routeFromUin = c2cRoutingUin(ctx.identity, ctx.fromUid, ctx.fromUin);
// The gray-tip template only identifies the two poke endpoints. The C2C
// routing head owns the conversation peer: outbound notices use `to`,
// while inbound notices use `from`, just like ordinary friend messages.
const sentBySelf = routeFromUin > 0 && routeFromUin === ctx.selfUin;
const peerUin = sentBySelf
? c2cRoutingUin(
ctx.identity,
ctx.responseHead?.toUid ?? '',
ctx.responseHead?.toUin ?? 0,
)
: routeFromUin;
if (peerUin <= 0) {
throw new Error(
'friend poke conversation peer is missing '
+ `(fromUin=${ctx.fromUin} toUin=${ctx.responseHead?.toUin ?? 0} sentBySelf=${sentBySelf})`,
);
}
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
peerUin,
senderUin,
targetUin: resolveUidToUin(ctx.identity, 0, target),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
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 senderUin = resolveUidToUin(ctx.identity, 0, actor);
const routeFromUin = c2cRoutingUin(ctx.identity, ctx.fromUid, ctx.fromUin);
// The gray-tip template only identifies the two poke endpoints. The C2C
// routing head owns the conversation peer: outbound notices use `to`,
// while inbound notices use `from`, just like ordinary friend messages.
const sentBySelf = routeFromUin > 0 && routeFromUin === ctx.selfUin;
const peerUin = sentBySelf
? c2cRoutingUin(ctx.identity, ctx.responseHead?.toUid ?? '', ctx.responseHead?.toUin ?? 0)
: routeFromUin;
if (peerUin <= 0) {
throw new Error(
'friend poke conversation peer is missing ' +
`(fromUin=${ctx.fromUin} toUin=${ctx.responseHead?.toUin ?? 0} sentBySelf=${sentBySelf})`,
);
}
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
peerUin,
senderUin,
targetUin: resolveUidToUin(ctx.identity, 0, target),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
@@ -1,121 +1,159 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type {
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupNameChangeEvent,
GroupTitleChangeEvent,
GroupPokeEvent,
GroupRecallEvent,
QQEventVariant,
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupNameChangeEvent,
GroupTitleChangeEvent,
GroupPokeEvent,
GroupRecallEvent,
QQEventVariant,
} from '../../events';
import type {
GroupMute,
GroupNameChange,
GroupSpecialTitleChange,
GroupReactNotify,
NotifyMessageBody,
GroupMute,
GroupNameChange,
GroupSpecialTitleChange,
GroupReactNotify,
NotifyMessageBody,
} from '@snowluma/proto-defs/notify';
import type { MsgPushContext } from '../context';
import { Event0x2DCSubType } from '../enums';
import {
buildTemplateMap, findTemplateValue,
resolveUidToUin,
unwrapGroupNotifyPayload,
buildTemplateMap,
findTemplateValue,
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 decodeSubType16(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 [];
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice:
return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice:
return decodeSubType16(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 ?? ''),
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? ''),
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
};
return [ev];
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 ?? ''),
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? ''),
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 || ''),
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? ''),
msgSeq: recalled.sequence ?? 0,
};
return [ev];
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 || '',
),
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? ''),
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),
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
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),
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, 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 ?? 0,
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
random: essence.random ?? 0,
set: setFlag === 1,
};
return [ev];
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 ?? 0,
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
@@ -134,16 +172,25 @@ const SUBTYPE16_SPECIAL_TITLE = 6;
const SUBTYPE16_GROUP_NAME_CHANGE = 12;
function decodeSubType16(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const field13 = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES))?.field13 ?? 0;
switch (field13) {
case SUBTYPE16_SPECIAL_TITLE: return decodeGroupTitle(ctx);
case SUBTYPE16_GROUP_NAME_CHANGE: return decodeGroupName(ctx);
case GROUP_REACT_DISCRIMINATOR: return decodeGroupMsgEmojiLike(ctx);
default:
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d', field13);
return [];
}
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) {
return [];
}
const field13 =
protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES))
?.field13 ?? 0;
switch (field13) {
case SUBTYPE16_SPECIAL_TITLE:
return decodeGroupTitle(ctx);
case SUBTYPE16_GROUP_NAME_CHANGE:
return decodeGroupName(ctx);
case GROUP_REACT_DISCRIMINATOR:
return decodeGroupMsgEmojiLike(ctx);
default:
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d', field13);
return [];
}
}
// field13 == 6: a member was granted a special title. eventParam carries the
@@ -151,95 +198,128 @@ function decodeSubType16(ctx: MsgPushContext): QQEventVariant[] {
// `<{"…","text":TITLE,…}>` rich token in that string (on-wire captured shape —
// the kernel resolves the template to a clean string, we parse it here).
function decodeGroupTitle(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES));
const param = notify?.eventParam
? protobuf_decode<GroupSpecialTitleChange>(notify.eventParam)
: undefined;
const userUin = param?.memberUin ?? 0;
const title = extractTitleFromTip(param?.tipText ?? '');
if (!userUin || !title) return [];
const ev: GroupTitleChangeEvent = {
kind: 'group_title_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify?.groupUin ?? 0,
userUin,
title,
};
return [ev];
const notify = protobuf_decode<NotifyMessageBody>(
ctx.content.subarray(GROUP_REACT_PREFIX_BYTES),
);
const param = notify?.eventParam
? protobuf_decode<GroupSpecialTitleChange>(notify.eventParam)
: undefined;
const userUin = param?.memberUin ?? 0;
const title = extractTitleFromTip(param?.tipText ?? '');
if (!userUin || !title) {
return [];
}
const ev: GroupTitleChangeEvent = {
kind: 'group_title_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify?.groupUin ?? 0,
userUin,
title,
};
return [ev];
}
// The tip text is "恭喜<{member}>获得群主授予的<{…"text":TITLE…}>头衔" — the title is
// the `text` of the LAST `<{…}>` rich token (the one just before "头衔"). Tokens
// are flat JSON with no `<`/`>` inside, so a non-greedy scan is safe.
function extractTitleFromTip(text: string): string {
const tokens = text.match(/<\{[^<>]*\}>/g);
if (!tokens || tokens.length === 0) return '';
const last = tokens[tokens.length - 1];
try {
const parsed = JSON.parse(last.slice(1, -1)) as { text?: string };
return parsed.text ?? '';
} catch {
return '';
}
const tokens = text.match(/<\{[^<>]*\}>/g);
if (!tokens || tokens.length === 0) {
return '';
}
const last = tokens[tokens.length - 1];
try {
const parsed = JSON.parse(last.slice(1, -1)) as { text?: string };
return parsed.text ?? '';
} catch {
return '';
}
}
// field13 == 12: group renamed. New name is nested in `eventParam` as a
// `GroupNameChange` (field 2); operator is `NotifyMessageBody.operatorUid`.
function decodeGroupName(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES));
const name = notify?.eventParam ? (protobuf_decode<GroupNameChange>(notify.eventParam)?.name ?? '') : '';
if (!name) return [];
const groupId = notify?.groupUin ?? 0;
const ev: GroupNameChangeEvent = {
kind: 'group_name_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
// Operator is a group member → resolves from the roster. Fall back to 0
// (not ctx.fromUin, which on a 0x2DC push is the group id) so an
// unresolved operator never surfaces the group id as user_id.
operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? ''),
name,
};
return [ev];
const notify = protobuf_decode<NotifyMessageBody>(
ctx.content.subarray(GROUP_REACT_PREFIX_BYTES),
);
const name = notify?.eventParam
? (protobuf_decode<GroupNameChange>(notify.eventParam)?.name ?? '')
: '';
if (!name) {
return [];
}
const groupId = notify?.groupUin ?? 0;
const ev: GroupNameChangeEvent = {
kind: 'group_name_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
// Operator is a group member → resolves from the roster. Fall back to 0
// (not ctx.fromUin, which on a 0x2DC push is the group id) so an
// unresolved operator never surfaces the group id as user_id.
operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? ''),
name,
};
return [ev];
}
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 [];
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) {
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 payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
const notify = protobuf_decode<GroupReactNotify>(payload);
const ev: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
operatorUid,
msgSeq,
emojiId,
count,
isAdd,
};
return [ev];
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),
operatorUid,
msgSeq,
emojiId,
count,
isAdd,
};
return [ev];
}
@@ -12,56 +12,86 @@ import { decodeRichBody } from '../rich-body-decoder';
* use it. See issue #125.
*/
function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: number } | null {
if (!jsonText.includes('group/invite_join')) return null;
const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/);
if (!m) return null;
const query = m[0].split('?')[1] ?? '';
const params = new URLSearchParams(query);
const groupUin = Number(params.get('groupcode') ?? 0);
const sequence = Number(params.get('msgseq') ?? 0);
if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) return null;
if (groupUin <= 0 || sequence <= 0) return null;
return { groupUin, sequence };
if (!jsonText.includes('group/invite_join')) {
return null;
}
const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/);
if (!m) {
return null;
}
const query = m[0].split('?')[1] ?? '';
const params = new URLSearchParams(query);
const groupUin = Number(params.get('groupcode') ?? 0);
const sequence = Number(params.get('msgseq') ?? 0);
if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) {
return null;
}
if (groupUin <= 0 || sequence <= 0) {
return null;
}
return { groupUin, sequence };
}
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const dataline = tryDecodeDatalineFriendMessage(ctx);
if (dataline) return [dataline];
const dataline = tryDecodeDatalineFriendMessage(ctx);
const elements = decodeRichBody(ctx.body, false);
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
let inviteCard: { groupUin: number; sequence: number } | null = null;
for (const el of elements) {
if (el.type === 'json' && typeof el.text === 'string') {
inviteCard = parseGroupInviteCard(el.text);
if (inviteCard) break;
if (dataline) {
return [dataline];
}
}
const ev: FriendMessage = {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
senderUid: ctx.fromUid,
...(peerUin > 0 ? { peerUin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
senderNick: '',
...(inviteCard ? {
inviteCardGroupUin: inviteCard.groupUin,
inviteCardSequence: inviteCard.sequence,
} : {}),
};
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];
const elements = decodeRichBody(ctx.body, false);
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
let inviteCard: { groupUin: number; sequence: number } | null = null;
for (const el of elements) {
if (el.type === 'json' && typeof el.text === 'string') {
inviteCard = parseGroupInviteCard(el.text);
if (inviteCard) {
break;
}
}
}
const ev: FriendMessage = {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
senderUid: ctx.fromUid,
...(peerUin > 0 ? { peerUin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7fffffff,
elements,
senderNick: '',
...(inviteCard
? {
inviteCardGroupUin: inviteCard.groupUin,
inviteCardSequence: inviteCard.sequence,
}
: {}),
};
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];
};
@@ -5,29 +5,37 @@ 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 [];
// proton materializes an *absent* embedded-message field as an empty
// `{}` rather than leaving it undefined, so the old
// `extraEnable !== undefined` promote/demote test was always true and
// every demote got reported as a promotion (with a fallback userUin).
// The live sub-message is the one that actually carries an `adminUid`
// — key off that instead.
const enableUid = admin.body.extraEnable?.adminUid;
const disableUid = admin.body.extraDisable?.adminUid;
const adminUid = enableUid || disableUid;
if (!adminUid) return [];
const groupId = admin.groupUin ?? 0;
const set = !!enableUid;
const userUin = resolveUidToUin(ctx.identity, groupId, adminUid);
const admin = protobuf_decode<GroupAdmin>(ctx.content);
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
set,
};
return [ev];
if (!admin?.body) {
return [];
}
// proton materializes an *absent* embedded-message field as an empty
// `{}` rather than leaving it undefined, so the old
// `extraEnable !== undefined` promote/demote test was always true and
// every demote got reported as a promotion (with a fallback userUin).
// The live sub-message is the one that actually carries an `adminUid`
// — key off that instead.
const enableUid = admin.body.extraEnable?.adminUid;
const disableUid = admin.body.extraDisable?.adminUid;
const adminUid = enableUid || disableUid;
if (!adminUid) {
return [];
}
const groupId = admin.groupUin ?? 0;
const set = !!enableUid;
const userUin = resolveUidToUin(ctx.identity, groupId, adminUid);
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
set,
};
return [ev];
};
@@ -1,64 +1,73 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupInviteEvent } from '../../events';
import type {
GroupInvitation, GroupInvite,
GroupJoin,
} from '@snowluma/proto-defs/notify';
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 stay unresolved here. Pipeline fills UIN via Identity.resolveUin.
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? ''),
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
return [ev];
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 stay unresolved here. Pipeline fills UIN via Identity.resolveUin.
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? ''),
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 ?? ''),
fromUid: inner.invitorUid ?? '',
invitedUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.targetUid ?? ''),
invitedUid: inner.targetUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
return [ev];
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 ?? ''),
fromUid: inner.invitorUid ?? '',
invitedUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.targetUid ?? ''),
invitedUid: inner.targetUid ?? '',
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 ?? ''),
fromUid: invite.invitorUid ?? '',
invitedUin: ctx.selfUin,
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
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 ?? ''),
fromUid: invite.invitorUid ?? '',
invitedUin: ctx.selfUin,
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
};
@@ -1,43 +1,43 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
import {
decodeGroupChangeOperatorUid,
decodeNestedOperatorUid,
resolveUidToUin,
} from '../helpers';
import { decodeGroupChangeOperatorUid, decodeNestedOperatorUid, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
function joinTypeFromOperationType(raw: number): NonNullable<GroupMemberJoin['joinType']> {
// QQ uses bit 0x80 as a flag on the PkgType=33 operation code. Clear only
// that bit: other high bits remain significant in the native handler. The
// normalized code 3 means an invitation; all other values mean approval.
// Do not use the nested `join_type`: that is an invitation-source enum.
const normalized = raw - (raw & 0x80);
return normalized === 3 ? 'invite' : 'approve';
// QQ uses bit 0x80 as a flag on the PkgType=33 operation code. Clear only
// that bit: other high bits remain significant in the native handler. The
// normalized code 3 means an invitation; all other values mean approval.
// Do not use the nested `join_type`: that is an invitation-source enum.
const normalized = raw - (raw & 0x80);
return normalized === 3 ? 'invite' : 'approve';
}
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 = decodeGroupChangeOperatorUid(
change.operatorBytes ?? new Uint8Array(0),
'group member increase',
);
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
userUid,
operatorUid,
joinType: joinTypeFromOperationType(change.decreaseType ?? 0),
};
return [ev];
const change = protobuf_decode<GroupChange>(ctx.content);
if (!change) {
return [];
}
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeGroupChangeOperatorUid(
change.operatorBytes ?? new Uint8Array(0),
'group member increase',
);
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
userUid,
operatorUid,
joinType: joinTypeFromOperationType(change.decreaseType ?? 0),
};
return [ev];
};
// QQ's GroupChange.decreaseType (proto field 4) on a member-decrease push:
@@ -49,78 +49,89 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
// The kick → kick_me distinction (was it us?) is decided downstream in the
// OneBot converter via selfId; here we only resolve the protocol-level reason.
function leaveTypeFromDecreaseType(dt: number): GroupMemberLeave['leaveType'] {
switch (dt) {
case 129:
return 'disband';
case 0:
case 130:
return 'leave';
default:
return 'kick';
}
switch (dt) {
case 129:
return 'disband';
case 0:
case 130:
return 'leave';
default:
return 'kick';
}
}
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 userUin = resolveUidToUin(ctx.identity, groupId, userUid);
const change = protobuf_decode<GroupChange>(ctx.content);
let operatorUid: string;
let operatorUin: number;
if (dt === 130) {
// A voluntary leave has no independent operator. QQ may place structured
// metadata in field 5, so it must not be decoded as a UID. OneBot models
// the leaving member as the operator for this event.
operatorUid = userUid;
operatorUin = userUin;
} else {
const operatorBytes = change.operatorBytes ?? new Uint8Array(0);
// Self-kick always uses OperatorInfo. Ordinary removals vary between a raw
// UTF-8 UID and the same envelope, so discriminate by its field-1 wire tag.
operatorUid = dt === 3
? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3')
: decodeGroupChangeOperatorUid(operatorBytes, `group member decrease type=${dt}`);
operatorUin = resolveUidToUin(ctx.identity, groupId, operatorUid);
}
const ev: GroupMemberLeave = {
kind: 'group_member_leave',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
operatorUin,
userUid,
operatorUid,
leaveType: leaveTypeFromDecreaseType(dt),
};
return [ev];
if (!change) {
return [];
}
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const userUin = resolveUidToUin(ctx.identity, groupId, userUid);
let operatorUid: string;
let operatorUin: number;
if (dt === 130) {
// A voluntary leave has no independent operator. QQ may place structured
// metadata in field 5, so it must not be decoded as a UID. OneBot models
// the leaving member as the operator for this event.
operatorUid = userUid;
operatorUin = userUin;
} else {
const operatorBytes = change.operatorBytes ?? new Uint8Array(0);
// Self-kick always uses OperatorInfo. Ordinary removals vary between a raw
// UTF-8 UID and the same envelope, so discriminate by its field-1 wire tag.
operatorUid =
dt === 3
? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3')
: decodeGroupChangeOperatorUid(operatorBytes, `group member decrease type=${dt}`);
operatorUin = resolveUidToUin(ctx.identity, groupId, operatorUid);
}
const ev: GroupMemberLeave = {
kind: 'group_member_leave',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
operatorUin,
userUid,
operatorUid,
leaveType: leaveTypeFromDecreaseType(dt),
};
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),
operatorUid,
};
return [ev];
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),
operatorUid,
};
return [ev];
};
@@ -3,50 +3,58 @@ 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,
groupName: '',
senderNick: '',
senderCard: '',
senderRole: '',
};
const grp = ctx.responseHead?.grp;
if (grp) {
ev.groupId = grp.groupUin ?? 0;
// Sender name priority (#201): the group-history fetch fills `memberName`
// (field 2); the local member cache gives a clean nickname/card split; and
// live pushes + merged-forward nodes carry the display name in `memberCard`
// (field 4). Prefer the explicit field-2 name, then the cache, then field 4
// — the last is what lets a forward node from a group the bot isn't in keep
// its per-node sender name without a member-list lookup.
ev.senderNick = 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;
// [#1] field 4 (memberCard) is the sender's CURRENT display name (group card
// if set, else base nickname). When it differs from the base nickname it's an
// up-to-date group card — fresher than the cache, which nothing refreshes on
// a card change (no push; a quiet group can freeze at warmup for months).
// Prefer it. (Self-healed back into the cache in packet-pipeline side effects.)
if (grp?.memberCard && grp.memberCard !== ev.senderNick) {
ev.senderCard = grp.memberCard;
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,
groupName: '',
senderNick: '',
senderCard: '',
senderRole: '',
};
const grp = ctx.responseHead?.grp;
if (grp) {
ev.groupId = grp.groupUin ?? 0;
// Sender name priority (#201): the group-history fetch fills `memberName`
// (field 2); the local member cache gives a clean nickname/card split; and
// live pushes + merged-forward nodes carry the display name in `memberCard`
// (field 4). Prefer the explicit field-2 name, then the cache, then field 4
// — the last is what lets a forward node from a group the bot isn't in keep
// its per-node sender name without a member-list lookup.
ev.senderNick = grp.memberName ?? '';
}
} else if (!ev.senderNick && grp?.memberCard) {
ev.senderNick = grp.memberCard;
}
// Group name: prefer the message's own wire field (ResponseGrp field 7 —
// fresh even right after a rename), fall back to the cached group list, else
// leave it empty. `ev.groupId` is set above from grp.groupUin.
ev.groupName = grp?.groupName || ctx.identity.findGroup?.(ev.groupId)?.groupName || '';
return [ev];
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;
// [#1] field 4 (memberCard) is the sender's CURRENT display name (group card
// if set, else base nickname). When it differs from the base nickname it's an
// up-to-date group card — fresher than the cache, which nothing refreshes on
// a card change (no push; a quiet group can freeze at warmup for months).
// Prefer it. (Self-healed back into the cache in packet-pipeline side effects.)
if (grp?.memberCard && grp.memberCard !== ev.senderNick) {
ev.senderCard = grp.memberCard;
}
} else if (!ev.senderNick && grp?.memberCard) {
ev.senderNick = grp.memberCard;
}
// Group name: prefer the message's own wire field (ResponseGrp field 7 —
// fresh even right after a rename), fall back to the cached group list, else
// leave it empty. `ev.groupId` is set above from grp.groupUin.
ev.groupName = grp?.groupName || ctx.identity.findGroup?.(ev.groupId)?.groupName || '';
return [ev];
};
@@ -3,31 +3,38 @@ import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
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 ?? '';
}
// A group temp session carries its source group in responseHead.forward.
if (ctx.responseHead?.forward?.tempGroupUin) {
ev.groupId = ctx.responseHead.forward.tempGroupUin;
}
if (!ev.senderNick) {
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend) ev.senderNick = friend.nickname;
}
return [ev];
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
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 ?? '';
}
// A group temp session carries its source group in responseHead.forward.
if (ctx.responseHead?.forward?.tempGroupUin) {
ev.groupId = ctx.responseHead.forward.tempGroupUin;
}
if (!ev.senderNick) {
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend) {
ev.senderNick = friend.nickname;
}
}
return [ev];
};
+133 -133
View File
@@ -1,141 +1,141 @@
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,
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,
GroupMuteNotice = 12,
GroupMsgEmojiLikeNotice = 16,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
export enum Event0x210SubType {
FriendRequestNotice = 35,
/**
* Voice-to-text (语音转文字) async result push, fired after a
* `pttTrans.Trans{C2C,Group}PttReq` once the server finishes transcribing.
* Live-verified body: `{ f1:uint, f2:{ f1=msgId, f8=text, ... } }`. There's
* no static sys_msg_0x210_0x3d handler — the ptt-trans subsystem registers
* it dynamically; we decode it into an internal `ptt_trans_result` event.
*/
PttTransResult = 61,
/**
* 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,
/**
* Multiplexed subType (Lagrange calls it FriendDeleteOrPinChanged=39). One of
* its variants is the profile-like ("名片赞") push: body.msgContent decodes as
* `ProfileLikeTip` and is a like only when inner msgType==0 && subType==203.
* NapCat routes 528/39 → parseLikeEvent (`api/msg.ts:1547`); other 39 variants
* (multi-device sync etc.) fall through.
*/
ProfileLikeNotice = 39,
/**
* C2C input-status notify — the "对方正在输入…" push. subMsgType 0x115 (277).
* RE-confirmed against `wrapper.linux.node`
* `aio_input_state_worker.cc::IsInputStateNotifySysMsg`, which matches exactly
* `(msg_type ^ 0x210) | (sub_msg_type ^ 0x115) == 0`. The payload
* (`InputStatusNotify`) rides in `body.msgContent`. Mirrors NapCat's
* `onInputStatusPush`.
*/
InputStatusNotice = 277,
/**
* QQ NT online-device cache update. The payload is a snapshot with repeated
* device entries; the kernel's getOnLineDev call only replays this cache and
* does not issue a separate network request.
*/
OnlineDevicesNotice = 349,
/** Server-authoritative friend/stranger remark synchronization push. */
FriendRemarkChangedNotice = 364,
/**
* 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,
FriendRequestNotice = 35,
/**
* Voice-to-text (语音转文字) async result push, fired after a
* `pttTrans.Trans{C2C,Group}PttReq` once the server finishes transcribing.
* Live-verified body: `{ f1:uint, f2:{ f1=msgId, f8=text, ... } }`. There's
* no static sys_msg_0x210_0x3d handler — the ptt-trans subsystem registers
* it dynamically; we decode it into an internal `ptt_trans_result` event.
*/
PttTransResult = 61,
/**
* 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,
/**
* Multiplexed subType (Lagrange calls it FriendDeleteOrPinChanged=39). One of
* its variants is the profile-like ("名片赞") push: body.msgContent decodes as
* `ProfileLikeTip` and is a like only when inner msgType==0 && subType==203.
* NapCat routes 528/39 → parseLikeEvent (`api/msg.ts:1547`); other 39 variants
* (multi-device sync etc.) fall through.
*/
ProfileLikeNotice = 39,
/**
* C2C input-status notify — the "对方正在输入…" push. subMsgType 0x115 (277).
* RE-confirmed against `wrapper.linux.node`
* `aio_input_state_worker.cc::IsInputStateNotifySysMsg`, which matches exactly
* `(msg_type ^ 0x210) | (sub_msg_type ^ 0x115) == 0`. The payload
* (`InputStatusNotify`) rides in `body.msgContent`. Mirrors NapCat's
* `onInputStatusPush`.
*/
InputStatusNotice = 277,
/**
* QQ NT online-device cache update. The payload is a snapshot with repeated
* device entries; the kernel's getOnLineDev call only replays this cache and
* does not issue a separate network request.
*/
OnlineDevicesNotice = 349,
/** Server-authoritative friend/stranger remark synchronization push. */
FriendRemarkChangedNotice = 364,
/**
* 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,
}
@@ -2,10 +2,10 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
SsoGetC2cMsg,
SsoGetC2cMsgResponse,
SsoGetRoamMsg,
SsoGetRoamMsgResponse,
SsoGetC2cMsg,
SsoGetC2cMsgResponse,
SsoGetRoamMsg,
SsoGetRoamMsgResponse,
} from '@snowluma/proto-defs/get-c2c-msg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import type { QQEventVariant } from '../events';
@@ -23,40 +23,58 @@ const log = createLogger('MsgPush.C2CHistory');
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
}
export interface C2cRoamPage {
messages: FriendMessage[];
cursor: { time: number; random: number };
messages: FriendMessage[];
cursor: { time: number; random: number };
}
function decodeC2cMessages(
messages: readonly PushMsgBody[],
identity: IdentityService,
selfUin: number,
source: string,
messages: readonly PushMsgBody[],
identity: IdentityService,
selfUin: number,
source: string,
): FriendMessage[] {
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(`${source} response contains a message without a content head`);
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(`${source} response contains a message without a content head`);
}
if (isC2cControlPush(ctx.head)) {
continue;
}
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message') {
continue;
}
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) {
continue;
}
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
throw new Error(
`${source} message is missing the canonical NT sequence ` +
`(clientSeq=${ev.clientSeq ?? ev.msgSeq} from=${ev.senderUin} time=${ev.time})`,
);
}
out.push(ev);
}
}
if (isC2cControlPush(ctx.head)) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message') continue;
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue;
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
throw new Error(
`${source} message is missing the canonical NT sequence `
+ `(clientSeq=${ev.clientSeq ?? ev.msgSeq} from=${ev.senderUin} time=${ev.time})`,
);
}
out.push(ev);
}
}
return out;
return out;
}
/**
@@ -67,40 +85,44 @@ function decodeC2cMessages(
* owns chunking/throttling.
*/
export async function fetchC2cMessageRange(
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
startSeq: number,
endSeq: number,
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
startSeq: number,
endSeq: number,
): Promise<FriendMessage[]> {
if (!friendUid || !(endSeq > 0) || startSeq > endSeq) return [];
if (!friendUid || !(endSeq > 0) || startSeq > endSeq) {
return [];
}
const req = protobuf_encode<SsoGetC2cMsg>({
friendUid,
startSequence: startSeq,
endSequence: endSeq,
});
const req = protobuf_encode<SsoGetC2cMsg>({
friendUid,
startSequence: startSeq,
endSequence: endSeq,
});
const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(res, 'SsoGetC2cMsg'),
);
if (decoded.friendUid && decoded.friendUid !== friendUid) {
throw new Error(`SsoGetC2cMsg response friend uid mismatch: ${decoded.friendUid}`);
}
const messages = decoded?.messages ?? [];
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
log.debug(
'SsoGetC2cMsg decoded friend=%s range=%d-%d wire=%d usable=%d',
friendUid,
startSeq,
endSeq,
messages.length,
out.length,
);
return out;
const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(res, 'SsoGetC2cMsg'),
);
if (decoded.friendUid && decoded.friendUid !== friendUid) {
throw new Error(`SsoGetC2cMsg response friend uid mismatch: ${decoded.friendUid}`);
}
const messages = decoded?.messages ?? [];
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
log.debug(
'SsoGetC2cMsg decoded friend=%s range=%d-%d wire=%d usable=%d',
friendUid,
startSeq,
endSeq,
messages.length,
out.length,
);
return out;
}
/**
@@ -108,54 +130,60 @@ export async function fetchC2cMessageRange(
* for an unanchored latest page; it returns messages from both participants.
*/
export async function fetchC2cRoamMessagePage(
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
beforeTime: number,
count: number,
beforeRandom = 0,
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
beforeTime: number,
count: number,
beforeRandom = 0,
): Promise<C2cRoamPage> {
if (!friendUid) throw new Error('SsoGetRoamMsg friend uid is required');
if (!Number.isSafeInteger(beforeTime) || beforeTime < 0 || beforeTime > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor time is invalid: ${String(beforeTime)}`);
}
if (!Number.isSafeInteger(beforeRandom) || beforeRandom < 0 || beforeRandom > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor random is invalid: ${String(beforeRandom)}`);
}
if (!Number.isSafeInteger(count) || count < 1 || count > 200) {
throw new Error(`SsoGetRoamMsg count is invalid: ${String(count)}`);
}
if (!friendUid) {
throw new Error('SsoGetRoamMsg friend uid is required');
}
const req = protobuf_encode<SsoGetRoamMsg>({
friendUid,
time: beforeTime,
random: beforeRandom,
count,
direction: true,
});
const result = await sender.sendRawPacket(SSO_GET_ROAM_MSG_CMD, req);
const response = protobuf_decode<SsoGetRoamMsgResponse>(
requirePacketResponse(result, 'SsoGetRoamMsg'),
);
if (response.friendUid && response.friendUid !== friendUid) {
throw new Error(`SsoGetRoamMsg response friend uid mismatch: ${response.friendUid}`);
}
if (!Number.isSafeInteger(beforeTime) || beforeTime < 0 || beforeTime > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor time is invalid: ${String(beforeTime)}`);
}
const wireMessages = response.messages ?? [];
const messages = decodeC2cMessages(wireMessages, identity, selfUin, 'SsoGetRoamMsg');
messages.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
const cursor = { time: response.timestamp ?? 0, random: response.random ?? 0 };
log.debug(
'SsoGetRoamMsg decoded friend=%s before=%d/%d count=%d wire=%d usable=%d next=%d/%d',
friendUid,
beforeTime,
beforeRandom,
count,
wireMessages.length,
messages.length,
cursor.time,
cursor.random,
);
return { messages, cursor };
if (!Number.isSafeInteger(beforeRandom) || beforeRandom < 0 || beforeRandom > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor random is invalid: ${String(beforeRandom)}`);
}
if (!Number.isSafeInteger(count) || count < 1 || count > 200) {
throw new Error(`SsoGetRoamMsg count is invalid: ${String(count)}`);
}
const req = protobuf_encode<SsoGetRoamMsg>({
friendUid,
time: beforeTime,
random: beforeRandom,
count,
direction: true,
});
const result = await sender.sendRawPacket(SSO_GET_ROAM_MSG_CMD, req);
const response = protobuf_decode<SsoGetRoamMsgResponse>(
requirePacketResponse(result, 'SsoGetRoamMsg'),
);
if (response.friendUid && response.friendUid !== friendUid) {
throw new Error(`SsoGetRoamMsg response friend uid mismatch: ${response.friendUid}`);
}
const wireMessages = response.messages ?? [];
const messages = decodeC2cMessages(wireMessages, identity, selfUin, 'SsoGetRoamMsg');
messages.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
const cursor = { time: response.timestamp ?? 0, random: response.random ?? 0 };
log.debug(
'SsoGetRoamMsg decoded friend=%s before=%d/%d count=%d wire=%d usable=%d next=%d/%d',
friendUid,
beforeTime,
beforeRandom,
count,
wireMessages.length,
messages.length,
cursor.time,
cursor.random,
);
return { messages, cursor };
}
@@ -16,7 +16,11 @@ type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
const log = createLogger('MsgPush.GroupHistory');
interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
}
/**
@@ -28,75 +32,88 @@ interface RawSender {
* chunking/throttling so the server's frequency limits aren't tripped.
*/
export async function fetchGroupMessageRange(
sender: RawSender,
identity: IdentityService,
selfUin: number,
groupUin: number,
startSeq: number,
endSeq: number,
sender: RawSender,
identity: IdentityService,
selfUin: number,
groupUin: number,
startSeq: number,
endSeq: number,
): Promise<GroupMessage[]> {
if (!(groupUin > 0) || !(endSeq > 0) || startSeq > endSeq) return [];
const req = protobuf_encode<SsoGetGroupMsg>({
info: { groupUin, startSequence: startSeq, endSequence: endSeq },
direction: true,
});
const res = await sender.sendRawPacket(SSO_GET_GROUP_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetGroupMsgResponse>(
requirePacketResponse(res, 'SsoGetGroupMsg'),
);
const messages = decoded?.body?.messages ?? [];
const out: GroupMessage[] = [];
for (let index = 0; index < messages.length; index += 1) {
const msg = messages[index];
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(
`SsoGetGroupMsg response message ${index} has no content head `
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
);
if (!(groupUin > 0) || !(endSeq > 0) || startSeq > endSeq) {
return [];
}
// QQ NT turns deleted/body-null roam entries into MsgType::kNull and its
// FilterBlankSeqsMsg pass removes them before exposing history to callers.
// SsoGetGroupMsg still carries a localized placeholder body for some of
// those entries (for example "[已删除]"), so the ordinary content-less
// filter below cannot recognize them. On the wire these null records have
// neither a sender nor a timestamp; require both structural absences rather
// than matching localized text so a real message is never language-filtered.
if (ctx.fromUin <= 0 && ctx.head.timestamp <= 0) {
log.debug(
'dropping QQ null roam record: group=%d seq=%d msgId=%d',
groupUin,
ctx.head.sequence,
ctx.head.msgId,
);
continue;
const req = protobuf_encode<SsoGetGroupMsg>({
info: { groupUin, startSequence: startSeq, endSequence: endSeq },
direction: true,
});
const res = await sender.sendRawPacket(SSO_GET_GROUP_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetGroupMsgResponse>(
requirePacketResponse(res, 'SsoGetGroupMsg'),
);
const messages = decoded?.body?.messages ?? [];
const out: GroupMessage[] = [];
for (let index = 0; index < messages.length; index += 1) {
const msg = messages[index];
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(
`SsoGetGroupMsg response message ${index} has no content head ` +
`(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
// QQ NT turns deleted/body-null roam entries into MsgType::kNull and its
// FilterBlankSeqsMsg pass removes them before exposing history to callers.
// SsoGetGroupMsg still carries a localized placeholder body for some of
// those entries (for example "[已删除]"), so the ordinary content-less
// filter below cannot recognize them. On the wire these null records have
// neither a sender nor a timestamp; require both structural absences rather
// than matching localized text so a real message is never language-filtered.
if (ctx.fromUin <= 0 && ctx.head.timestamp <= 0) {
log.debug(
'dropping QQ null roam record: group=%d seq=%d msgId=%d',
groupUin,
ctx.head.sequence,
ctx.head.msgId,
);
continue;
}
for (const ev of decodeGroupMessage(ctx)) {
if (ev.kind !== 'group_message') {
throw new Error(
`SsoGetGroupMsg response message ${index} decoded as ${ev.kind} ` +
`(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!Number.isSafeInteger(ev.msgSeq) || ev.msgSeq <= 0) {
throw new Error(
`SsoGetGroupMsg response message ${index} has invalid sequence ${String(ev.msgSeq)} ` +
`(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (ev.groupId !== groupUin) {
throw new Error(
`SsoGetGroupMsg response message ${index} belongs to group ${ev.groupId} ` +
`(expected=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) {
continue;
}
out.push(ev);
}
}
for (const ev of decodeGroupMessage(ctx)) {
if (ev.kind !== 'group_message') {
throw new Error(
`SsoGetGroupMsg response message ${index} decoded as ${ev.kind} `
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!Number.isSafeInteger(ev.msgSeq) || ev.msgSeq <= 0) {
throw new Error(
`SsoGetGroupMsg response message ${index} has invalid sequence ${String(ev.msgSeq)} `
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (ev.groupId !== groupUin) {
throw new Error(
`SsoGetGroupMsg response message ${index} belongs to group ${ev.groupId} `
+ `(expected=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue;
out.push(ev);
}
}
out.sort((a, b) => a.msgSeq - b.msgSeq);
return out;
out.sort((a, b) => a.msgSeq - b.msgSeq);
return out;
}
+207 -121
View File
@@ -8,89 +8,125 @@ export const MAX_RICH_CARD_OUTPUT_BYTES = 4 * 1024 * 1024;
export const MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES = 8 * 1024 * 1024;
export type DecompressDataResult =
| { ok: true; text: string; outputBytes: number }
| { ok: false; reason: string };
{ ok: true; text: string; outputBytes: number } | { ok: false; reason: string };
export function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
if (/^https?:\/\//i.test(origUrl)) return origUrl;
// Compatibility faces sometimes carry a query fragment without a path.
// Prefixing the host onto that produces an unusable URL.
if (!origUrl.startsWith('/')) return '';
if (origUrl.includes('rkey') || origUrl.includes('fileid')) {
return 'https://multimedia.nt.qq.com.cn' + origUrl;
}
return 'http://gchat.qpic.cn' + origUrl;
if (!origUrl) {
return '';
}
if (/^https?:\/\//i.test(origUrl)) {
return origUrl;
}
// Compatibility faces sometimes carry a query fragment without a path.
// Prefixing the host onto that produces an unusable URL.
if (!origUrl.startsWith('/')) {
return '';
}
if (origUrl.includes('rkey') || origUrl.includes('fileid')) {
return 'https://multimedia.nt.qq.com.cn' + origUrl;
}
return 'http://gchat.qpic.cn' + origUrl;
}
/** Classic group-pic URL used when the wire carries an MD5 and no download path. */
export function imageUrlFromMd5(md5Hex: string): string {
if (!/^[0-9a-fA-F]{32}$/.test(md5Hex)) return '';
return `http://gchat.qpic.cn/gchatpic_new/0/0-0-${md5Hex.toUpperCase()}/0`;
if (!/^[0-9a-fA-F]{32}$/.test(md5Hex)) {
return '';
}
return `http://gchat.qpic.cn/gchatpic_new/0/0-0-${md5Hex.toUpperCase()}/0`;
}
/** NT multimedia download URL reconstructed from a file id when the path is omitted. */
export function ntImageUrlFromFileId(fileId: string, isGroup: boolean): string {
if (!fileId) return '';
const appid = isGroup ? 1407 : 1406;
return `https://multimedia.nt.qq.com.cn/download?appid=${appid}&fileid=${encodeURIComponent(fileId)}`;
if (!fileId) {
return '';
}
const appid = isGroup ? 1407 : 1406;
return `https://multimedia.nt.qq.com.cn/download?appid=${appid}&fileid=${encodeURIComponent(fileId)}`;
}
export function decompressData(
data: Uint8Array,
maxOutputBytes = MAX_RICH_CARD_OUTPUT_BYTES,
data: Uint8Array,
maxOutputBytes = MAX_RICH_CARD_OUTPUT_BYTES,
): DecompressDataResult {
if (!data || data.length === 0) return { ok: false, reason: 'empty_payload' };
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0) {
throw new Error(`invalid decompression output limit: ${maxOutputBytes}`);
}
if ((data[0] === 0x00 || data[0] === 0x01) && data.length === 1) {
return { ok: false, reason: 'marker_without_payload' };
}
if (data[0] === 0x01) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)), {
maxOutputLength: maxOutputBytes,
});
return inflated.length > 0
? { ok: true, text: inflated.toString('utf8'), outputBytes: inflated.length }
: { ok: false, reason: 'empty_output' };
} catch (error) {
const code = typeof error === 'object' && error !== null && 'code' in error
? String(error.code)
: '';
return {
ok: false,
reason: code === 'ERR_BUFFER_TOO_LARGE'
? 'output_limit_exceeded'
: code
? `inflate_failed:${code}`
: 'inflate_failed',
};
if (!data || data.length === 0) {
return { ok: false, reason: 'empty_payload' };
}
}
if (data[0] === 0x00) {
if (data.length - 1 > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' };
return {
ok: true,
text: Buffer.from(data.subarray(1)).toString('utf8'),
outputBytes: data.length - 1,
};
}
if (data.length > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' };
return { ok: true, text: Buffer.from(data).toString('utf8'), outputBytes: data.length };
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0) {
throw new Error(`invalid decompression output limit: ${maxOutputBytes}`);
}
if ((data[0] === 0x00 || data[0] === 0x01) && data.length === 1) {
return { ok: false, reason: 'marker_without_payload' };
}
if (data[0] === 0x01) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)), {
maxOutputLength: maxOutputBytes,
});
return inflated.length > 0
? { ok: true, text: inflated.toString('utf8'), outputBytes: inflated.length }
: { ok: false, reason: 'empty_output' };
} catch (error) {
const code =
typeof error === 'object' && error !== null && 'code' in error
? String(error.code)
: '';
return {
ok: false,
reason:
code === 'ERR_BUFFER_TOO_LARGE'
? 'output_limit_exceeded'
: code
? `inflate_failed:${code}`
: 'inflate_failed',
};
}
}
if (data[0] === 0x00) {
if (data.length - 1 > maxOutputBytes) {
return { ok: false, reason: 'output_limit_exceeded' };
}
return {
ok: true,
text: Buffer.from(data.subarray(1)).toString('utf8'),
outputBytes: data.length - 1,
};
}
if (data.length > maxOutputBytes) {
return { ok: false, reason: 'output_limit_exceeded' };
}
return { ok: true, text: Buffer.from(data).toString('utf8'), outputBytes: data.length };
}
export function parseU64OrZero(value: string): number {
if (!value) return 0;
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
if (!value) {
return 0;
}
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
}
/** Sync Identity lookup. Miss is unresolved (0). Decoder must not invent a UIN. */
export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string): number {
if (!uid) return 0;
return identity.findUinByUid(uid, groupId || undefined) ?? 0;
if (!uid) {
return 0;
}
return identity.findUinByUid(uid, groupId || undefined) ?? 0;
}
/**
@@ -99,94 +135,144 @@ export function resolveUidToUin(identity: IdentityService, groupId: number, uid:
* to a different UID.
*/
export function c2cRoutingUin(identity: IdentityService, uid: string, wireUin: number): number {
const resolved = resolveUidToUin(identity, 0, uid);
if (resolved > 0) return resolved;
return wireUin > 0 ? wireUin : 0;
const resolved = resolveUidToUin(identity, 0, uid);
if (resolved > 0) {
return resolved;
}
return wireUin > 0 ? wireUin : 0;
}
const OPERATOR_BYTES_PREVIEW_LENGTH = 32;
function describeOperatorBytes(bytes: Uint8Array): string {
return `bytes=${bytes.length} preview=${hexPreview(bytes, OPERATOR_BYTES_PREVIEW_LENGTH)}`;
return `bytes=${bytes.length} preview=${hexPreview(bytes, OPERATOR_BYTES_PREVIEW_LENGTH)}`;
}
function hasControlCharacter(value: string): boolean {
for (const char of value) {
const codePoint = char.codePointAt(0);
if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) return true;
}
return false;
for (const char of value) {
const codePoint = char.codePointAt(0);
if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) {
return true;
}
}
return false;
}
function assertOperatorUid(uid: string, context: string, bytes: Uint8Array): string {
if (hasControlCharacter(uid)) {
throw new Error(`${context} operator UID contains control characters (${describeOperatorBytes(bytes)})`);
}
return uid;
if (hasControlCharacter(uid)) {
throw new Error(
`${context} operator UID contains control characters (${describeOperatorBytes(bytes)})`,
);
}
return uid;
}
export function decodeRawOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
let uid: string;
try {
uid = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch (error) {
throw new Error(
`${context} operator UID is not valid UTF-8 (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
return assertOperatorUid(uid, context, bytes);
if (!bytes || bytes.length === 0) {
return '';
}
let uid: string;
try {
uid = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch (error) {
throw new Error(
`${context} operator UID is not valid UTF-8 (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
return assertOperatorUid(uid, context, bytes);
}
export function decodeNestedOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
let info: OperatorInfo | null;
try {
info = protobuf_decode<OperatorInfo>(bytes);
} catch (error) {
throw new Error(
`${context} operator info decode failed (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
const uid = info?.operatorField?.uid;
if (!uid) {
throw new Error(`${context} operator info is missing UID (${describeOperatorBytes(bytes)})`);
}
return assertOperatorUid(uid, context, bytes);
if (!bytes || bytes.length === 0) {
return '';
}
let info: OperatorInfo | null;
try {
info = protobuf_decode<OperatorInfo>(bytes);
} catch (error) {
throw new Error(
`${context} operator info decode failed (${describeOperatorBytes(bytes)})`,
{
cause: error,
},
);
}
const uid = info?.operatorField?.uid;
if (!uid) {
throw new Error(
`${context} operator info is missing UID (${describeOperatorBytes(bytes)})`,
);
}
return assertOperatorUid(uid, context, bytes);
}
const OPERATOR_INFO_FIELD_TAG = 0x0a;
export function decodeGroupChangeOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
return bytes[0] === OPERATOR_INFO_FIELD_TAG
? decodeNestedOperatorUid(bytes, context)
: decodeRawOperatorUid(bytes, context);
if (!bytes || bytes.length === 0) {
return '';
}
return bytes[0] === OPERATOR_INFO_FIELD_TAG
? decodeNestedOperatorUid(bytes, context)
: decodeRawOperatorUid(bytes, context);
}
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 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 '';
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);
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);
}
+172 -160
View File
@@ -9,34 +9,31 @@ import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeFriendMessage } from './decoders/friend-message';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
decodeGroupInvitation, decodeGroupInvite,
decodeGroupJoinRequest,
decodeGroupInvitation,
decodeGroupInvite,
decodeGroupJoinRequest,
} from './decoders/group-join-request';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
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';
import {
deriveSysMsgDedupIdentity,
SysMsgDedup,
} from './sysmsg-dedup';
import { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export {
deriveSysMsgDedupIdentity,
SysMsgDedup,
} from './sysmsg-dedup';
export { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export type { SysMsgDedupIdentity } from './sysmsg-dedup';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export {
SSO_GET_C2C_MSG_CMD,
SSO_GET_ROAM_MSG_CMD,
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
type C2cRoamPage,
SSO_GET_C2C_MSG_CMD,
SSO_GET_ROAM_MSG_CMD,
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
type C2cRoamPage,
} from './fetch-c2c-history';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
@@ -53,171 +50,186 @@ 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);
registry.register(
[
PkgType.PrivateMessage,
PkgType.ForwardFakePrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
],
decodeFriendMessage,
);
const log = createLogger('MsgPush');
function messageElements(ev: QQEventVariant): readonly unknown[] | undefined {
if (ev.kind === 'friend_message' || ev.kind === 'group_message' || ev.kind === 'temp_message') {
return ev.elements;
}
return undefined;
if (ev.kind === 'friend_message' || ev.kind === 'group_message' || ev.kind === 'temp_message') {
return ev.elements;
}
return undefined;
}
function warnMissingC2cSequence(ev: QQEventVariant, fromUin: number): void {
if (
(ev.kind === 'friend_message' || ev.kind === 'temp_message')
&& ev.sequenceAuthoritative === false
) {
log.warn(
'c2c message omitted NT sequence; keeping non-authoritative client sequence (kind=%s from=%d clientSeq=%d time=%d)',
ev.kind,
fromUin,
ev.clientSeq ?? ev.msgSeq,
ev.time,
);
}
if (
(ev.kind === 'friend_message' || ev.kind === 'temp_message') &&
ev.sequenceAuthoritative === false
) {
log.warn(
'c2c message omitted NT sequence; keeping non-authoritative client sequence (kind=%s from=%d clientSeq=%d time=%d)',
ev.kind,
fromUin,
ev.clientSeq ?? ev.msgSeq,
ev.time,
);
}
}
export function parseMsgPush(
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
): QQEventVariant[] {
return parseMsgPushInternal(
pkt,
identity,
dedup,
false,
);
return parseMsgPushInternal(pkt, identity, dedup, false);
}
export function parseMsgPushOrThrow(
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
): QQEventVariant[] {
return parseMsgPushInternal(
pkt,
identity,
dedup,
true,
);
return parseMsgPushInternal(pkt, identity, dedup, true);
}
function parseMsgPushInternal(
pkt: PacketInfo,
identity: IdentityService,
dedup: SysMsgDedup | undefined,
throwDecoderErrors: boolean,
pkt: PacketInfo,
identity: IdentityService,
dedup: SysMsgDedup | undefined,
throwDecoderErrors: boolean,
): QQEventVariant[] {
const ctx = buildContext(pkt, identity);
if (!ctx) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=push_context_invalid',
pkt.serviceCmd,
pkt.seqId,
]);
return [];
}
const ctx = buildContext(pkt, identity);
// #137/#266: mirror QQ NT `sys_msg_mgr.cc::ProcessRecvSysMsg` before
// dispatch. Its static routing table is the scope boundary: listed routes
// use the native global key, while unlisted routes fail open. Running this
// before registry decode also covers native system packets whose outer type
// SnowLuma otherwise interprets as a chat message or does not decode at all.
if (dedup) {
const dedupIdentity = deriveSysMsgDedupIdentity(ctx);
if (dedupIdentity && dedup.seenDuplicate(dedupIdentity)) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=duplicate_system_push peer=%j chatType=%d messageSeq=%d messageRandom=%d',
pkt.serviceCmd,
pkt.seqId,
dedupIdentity.peerUid,
dedupIdentity.chatType,
dedupIdentity.sequence,
dedupIdentity.random,
]);
log.debug(
'dropped duplicate system push (peer=%s chatType=%d seq=%d msgType=%d/%d msgId=%d)',
dedupIdentity.peerUid,
dedupIdentity.chatType,
ctx.head.sequence,
ctx.head.msgType,
ctx.head.subType,
ctx.head.msgId,
);
return [];
if (!ctx) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=push_context_invalid',
pkt.serviceCmd,
pkt.seqId,
]);
return [];
}
}
const events = throwDecoderErrors
? registry.decodeOrThrow(ctx)
: registry.decode(ctx);
const out = events.filter((ev) => {
const elements = messageElements(ev);
if (elements === undefined) return true;
const survival = classifyMessageSurvival(ctx.head, elements, ctx.body);
if (survival === 'drop-control') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=c2c_control_push msgType=%d subType=%d c2cCmd=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.c2cCmd,
ctx.head.sequence,
]);
if (elements.length > 0) {
log.debug('dropped c2c control push that carried %d element(s) (kind=%s seq=%d from=%d msgType=%d cmd=%d)',
elements.length, ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.c2cCmd);
}
return false;
}
if (survival === 'drop-receipt') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=offline_file_receipt msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
log.debug(
'dropped offline file receipt (kind=%s seq=%d from=%d msgType=%d)',
ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType,
);
return false;
}
if (survival === 'drop-blank') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
return false;
}
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind: ev.kind,
sequence: ctx.head.sequence,
fromUin: ctx.fromUin,
msgType: ctx.head.msgType,
subType: ctx.head.subType,
body: ctx.body,
});
}
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
});
// #137/#266: mirror QQ NT `sys_msg_mgr.cc::ProcessRecvSysMsg` before
// dispatch. Its static routing table is the scope boundary: listed routes
// use the native global key, while unlisted routes fail open. Running this
// before registry decode also covers native system packets whose outer type
// SnowLuma otherwise interprets as a chat message or does not decode at all.
if (dedup) {
const dedupIdentity = deriveSysMsgDedupIdentity(ctx);
return out;
if (dedupIdentity && dedup.seenDuplicate(dedupIdentity)) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=duplicate_system_push peer=%j chatType=%d messageSeq=%d messageRandom=%d',
pkt.serviceCmd,
pkt.seqId,
dedupIdentity.peerUid,
dedupIdentity.chatType,
dedupIdentity.sequence,
dedupIdentity.random,
]);
log.debug(
'dropped duplicate system push (peer=%s chatType=%d seq=%d msgType=%d/%d msgId=%d)',
dedupIdentity.peerUid,
dedupIdentity.chatType,
ctx.head.sequence,
ctx.head.msgType,
ctx.head.subType,
ctx.head.msgId,
);
return [];
}
}
const events = throwDecoderErrors ? registry.decodeOrThrow(ctx) : registry.decode(ctx);
const out = events.filter((ev) => {
const elements = messageElements(ev);
if (elements === undefined) {
return true;
}
const survival = classifyMessageSurvival(ctx.head, elements, ctx.body);
if (survival === 'drop-control') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=c2c_control_push msgType=%d subType=%d c2cCmd=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.c2cCmd,
ctx.head.sequence,
]);
if (elements.length > 0) {
log.debug(
'dropped c2c control push that carried %d element(s) (kind=%s seq=%d from=%d msgType=%d cmd=%d)',
elements.length,
ev.kind,
ctx.head.sequence,
ctx.fromUin,
ctx.head.msgType,
ctx.head.c2cCmd,
);
}
return false;
}
if (survival === 'drop-receipt') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=offline_file_receipt msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
log.debug(
'dropped offline file receipt (kind=%s seq=%d from=%d msgType=%d)',
ev.kind,
ctx.head.sequence,
ctx.fromUin,
ctx.head.msgType,
);
return false;
}
if (survival === 'drop-blank') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
return false;
}
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind: ev.kind,
sequence: ctx.head.sequence,
fromUin: ctx.fromUin,
msgType: ctx.head.msgType,
subType: ctx.head.subType,
body: ctx.body,
});
}
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
});
return out;
}
@@ -1,16 +1,15 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
export function requirePacketResponse(
result: SendPacketResult,
command: string,
): Uint8Array {
if (!result.success) {
throw new Error(
`${command} transport failed: ${result.errorMessage || 'unknown transport error'}`,
);
}
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
throw new Error(`${command} response is empty`);
}
return result.responseData;
export function requirePacketResponse(result: SendPacketResult, command: string): Uint8Array {
if (!result.success) {
throw new Error(
`${command} transport failed: ${result.errorMessage || 'unknown transport error'}`,
);
}
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
throw new Error(`${command} response is empty`);
}
return result.responseData;
}
+62 -54
View File
@@ -9,67 +9,75 @@ const unknownLog = createLogger('MsgPush.Unknown');
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
export class MsgPushRegistry {
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
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);
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[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, 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 [];
decode(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, 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 [];
}
}
}
decodeOrThrow(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
throw e;
decodeOrThrow(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
throw e;
}
}
}
private runDecoder(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) {
unknownLog.trace(() => [
'packet_branch branch=decoder_unregistered msgType=%d subType=%d messageSeq=%d',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
// 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 [];
private runDecoder(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) {
unknownLog.trace(() => [
'packet_branch branch=decoder_unregistered msgType=%d subType=%d messageSeq=%d',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
// 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 [];
}
return decoder(ctx);
}
return decoder(ctx);
}
private traceDecoderException(
ctx: MsgPushContext,
error: unknown,
): void {
log.trace(() => [
'packet_branch branch=decoder_exception msgType=%d subType=%d messageSeq=%d error=%j',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
error instanceof Error ? error.message : String(error),
]);
}
private traceDecoderException(ctx: MsgPushContext, error: unknown): void {
log.trace(() => [
'packet_branch branch=decoder_exception msgType=%d subType=%d messageSeq=%d error=%j',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
error instanceof Error ? error.message : String(error),
]);
}
}
File diff suppressed because it is too large. Load diff
+77 -43
View File
@@ -3,20 +3,37 @@ import type { MsgPushContext } from './context';
export type SysMsgChatType = 1 | 2;
export interface SysMsgDedupIdentity {
readonly peerUid: string;
readonly chatType: SysMsgChatType;
readonly sequence: number;
readonly random: number;
readonly peerUid: string;
readonly chatType: SysMsgChatType;
readonly sequence: number;
readonly random: number;
}
function getNativeSysMsgChatType(msgType: number, subType: number): SysMsgChatType | null {
if (msgType === 528 && subType === 290) return 1;
if (msgType === 166 && (subType === 75 || subType === 129 || subType === 131 || subType === 133 || subType === 135)) return 1;
if (msgType === 167 && subType === 133) return 1;
if (msgType === 528 && subType === 290) {
return 1;
}
if (msgType === 732 && (subType === 12 || subType === 16 || subType === 20)) return 2;
if ((msgType === 33 || msgType === 34 || msgType === 85) && subType === 0) return 2;
return null;
if (
msgType === 166 &&
(subType === 75 || subType === 129 || subType === 131 || subType === 133 || subType === 135)
) {
return 1;
}
if (msgType === 167 && subType === 133) {
return 1;
}
if (msgType === 732 && (subType === 12 || subType === 16 || subType === 20)) {
return 2;
}
if ((msgType === 33 || msgType === 34 || msgType === 85) && subType === 0) {
return 2;
}
return null;
}
/**
@@ -25,24 +42,30 @@ function getNativeSysMsgChatType(msgType: number, subType: number): SysMsgChatTy
* routes fail open rather than risking suppression of unrelated events.
*/
export function deriveSysMsgDedupIdentity(
ctx: Pick<MsgPushContext, 'head' | 'fromUin' | 'fromUid'>,
ctx: Pick<MsgPushContext, 'head' | 'fromUin' | 'fromUid'>,
): SysMsgDedupIdentity | null {
const { head } = ctx;
const chatType = getNativeSysMsgChatType(head.msgType, head.subType);
// Decoded zero is also the protobuf default for an absent field. Without a
// complete server identity, prefer a duplicate event over suppressing two
// unrelated pushes that collapse to the same default-valued key.
if (chatType === null || head.sequence === 0 || head.msgId === 0) return null;
const { head } = ctx;
const chatType = getNativeSysMsgChatType(head.msgType, head.subType);
const peerUid = chatType === 1 ? ctx.fromUid : String(ctx.fromUin);
if (!peerUid || (chatType === 2 && ctx.fromUin === 0)) return null;
// Decoded zero is also the protobuf default for an absent field. Without a
// complete server identity, prefer a duplicate event over suppressing two
// unrelated pushes that collapse to the same default-valued key.
if (chatType === null || head.sequence === 0 || head.msgId === 0) {
return null;
}
return {
peerUid,
chatType,
sequence: head.sequence,
random: head.msgId,
};
const peerUid = chatType === 1 ? ctx.fromUid : String(ctx.fromUin);
if (!peerUid || (chatType === 2 && ctx.fromUin === 0)) {
return null;
}
return {
peerUid,
chatType,
sequence: head.sequence,
random: head.msgId,
};
}
/**
@@ -60,24 +83,35 @@ export function deriveSysMsgDedupIdentity(
* groups. {@link deriveSysMsgDedupIdentity} mirrors those routes exactly.
*/
export class SysMsgDedup {
private readonly seen = new Set<string>();
private readonly ring: (string | undefined)[];
private cursor = 0;
private readonly seen = new Set<string>();
private readonly ring: (string | undefined)[];
private cursor = 0;
constructor(private readonly capacity = 1024) {
this.ring = new Array<string | undefined>(capacity);
}
constructor(private readonly capacity = 1024) {
this.ring = new Array<string | undefined>(capacity);
}
/** Returns true when this native system-message identity was already seen. */
seenDuplicate(identity: SysMsgDedupIdentity): boolean {
if (identity.sequence === 0 || identity.random === 0 || !identity.peerUid) return false;
const key = `${identity.peerUid}_${identity.chatType}_${identity.sequence}_${identity.random}`;
if (this.seen.has(key)) return true;
const evicted = this.ring[this.cursor];
if (evicted !== undefined) this.seen.delete(evicted);
this.ring[this.cursor] = key;
this.seen.add(key);
this.cursor = (this.cursor + 1) % this.capacity;
return false;
}
/** Returns true when this native system-message identity was already seen. */
seenDuplicate(identity: SysMsgDedupIdentity): boolean {
if (identity.sequence === 0 || identity.random === 0 || !identity.peerUid) {
return false;
}
const key = `${identity.peerUid}_${identity.chatType}_${identity.sequence}_${identity.random}`;
if (this.seen.has(key)) {
return true;
}
const evicted = this.ring[this.cursor];
if (evicted !== undefined) {
this.seen.delete(evicted);
}
this.ring[this.cursor] = key;
this.seen.add(key);
this.cursor = (this.cursor + 1) % this.capacity;
return false;
}
}
+117 -106
View File
@@ -40,7 +40,11 @@ import { makeOidbEnvelope } from './bridge-oidb';
* `Pick<BridgeContext, 'identity' | …>` and intersects with this.
*/
export interface OidbSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
}
/**
@@ -57,63 +61,64 @@ export interface OidbSender {
* are given. `resolveCommand` likewise wins over static `command`.
*/
export interface OidbCallSpec<TCtx extends OidbSender, TReq, TResp, TParams, TResult> {
command: number;
resolveCommand?(params: TParams, ctx: TCtx): number;
subCommand?: number;
resolveSubCommand?(params: TParams, ctx: TCtx): number;
/** Packet and body envelope codes treated as success in addition to 0. */
acceptedEnvelopeCodes?: readonly 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>;
command: number;
resolveCommand?(params: TParams, ctx: TCtx): number;
subCommand?: number;
resolveSubCommand?(params: TParams, ctx: TCtx): number;
/** Packet and body envelope codes treated as success in addition to 0. */
acceptedEnvelopeCodes?: readonly 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>;
}
function resolveOidbCall<TCtx extends OidbSender, TReq, TResp, TParams, TResult>(
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
params: TParams,
ctx: TCtx,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
params: TParams,
ctx: TCtx,
): { command: number; subCommand: number } {
const command = spec.resolveCommand
? spec.resolveCommand(params, ctx)
: spec.command;
const subCommand = spec.resolveSubCommand
? spec.resolveSubCommand(params, ctx)
: spec.subCommand!;
return { command, subCommand };
const command = spec.resolveCommand ? spec.resolveCommand(params, ctx) : spec.command;
const subCommand = spec.resolveSubCommand
? spec.resolveSubCommand(params, ctx)
: spec.subCommand!;
return { command, subCommand };
}
function isAcceptedEnvelopeCode<TCtx extends OidbSender, TReq, TResp, TParams, TResult>(
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
code: number | null | undefined,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
code: number | null | undefined,
): boolean {
if (code == null || code === 0) return true;
return spec.acceptedEnvelopeCodes?.includes(code) === true;
if (code == null || code === 0) {
return true;
}
return spec.acceptedEnvelopeCodes?.includes(code) === true;
}
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';
}
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';
}
}
/**
@@ -127,57 +132,63 @@ export class OidbError extends Error {
* 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,
ctx: TCtx,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
params: TParams,
timeoutMs?: number,
): Promise<TResult> {
const { command, subCommand } = resolveOidbCall(spec, params, ctx);
const reqBody = await spec.serialize(ctx, params);
const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false);
const reqBytes = spec.encode(env);
const wireName = spec.wireName
? spec.wireName(command, subCommand)
: `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`;
const { command, subCommand } = resolveOidbCall(spec, params, ctx);
const reqBody = await spec.serialize(ctx, params);
const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false);
const reqBytes = spec.encode(env);
const wireName = spec.wireName
? spec.wireName(command, subCommand)
: `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`;
const result = timeoutMs === undefined
? await ctx.sendRawPacket(wireName, reqBytes)
: await ctx.sendRawPacket(wireName, reqBytes, timeoutMs);
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
const result =
timeoutMs === undefined
? await ctx.sendRawPacket(wireName, reqBytes)
: await ctx.sendRawPacket(wireName, reqBytes, timeoutMs);
if (!result.success) {
if (result.errorCode && result.errorCode !== 0) {
if (!isAcceptedEnvelopeCode(spec, result.errorCode)) {
throw new OidbError(
result.errorCode,
result.errorMessage || '',
command,
subCommand
);
}
} else {
// success=false without an OIDB error code = the packet send itself failed;
// surface it instead of silently resolving with an undecoded response.
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 && !isAcceptedEnvelopeCode(spec, code)) {
throw new OidbError(code, meta?.errorMsg ?? '', command, subCommand);
if (!result.success) {
if (result.errorCode && result.errorCode !== 0) {
if (!isAcceptedEnvelopeCode(spec, result.errorCode)) {
throw new OidbError(
result.errorCode,
result.errorMessage || '',
command,
subCommand,
);
}
} else {
// success=false without an OIDB error code = the packet send itself failed;
// surface it instead of silently resolving with an undecoded response.
throw new Error(result.errorMessage || 'packet send failed');
}
}
}
// 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);
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 && !isAcceptedEnvelopeCode(spec, code)) {
throw new OidbError(code, meta?.errorMsg ?? '', 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);
}
/**
@@ -187,18 +198,18 @@ export async function invokeOidb<TCtx extends OidbSender, TReq, TResp, TParams,
* 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,
ctx: TCtx,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
params: TParams,
): Promise<{ wireName: string; bytes: Uint8Array }> {
const { command, subCommand } = resolveOidbCall(spec, params, ctx);
const reqBody = await spec.serialize(ctx, params);
const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false);
const bytes = spec.encode(env);
const wireName = spec.wireName
? spec.wireName(command, subCommand)
: `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`;
return { wireName, bytes };
const { command, subCommand } = resolveOidbCall(spec, params, ctx);
const reqBody = await spec.serialize(ctx, params);
const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false);
const bytes = spec.encode(env);
const wireName = spec.wireName
? spec.wireName(command, subCommand)
: `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`;
return { wireName, bytes };
}
/**
@@ -206,9 +217,9 @@ export async function buildOidbRequest<TCtx extends OidbSender, TReq, TResp, TPa
* 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,
ctx: TCtx,
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
bytes: Uint8Array,
): TResult {
return spec.deserialize(ctx, spec.decode(bytes).body ?? ({} as TResp));
return spec.deserialize(ctx, spec.decode(bytes).body ?? ({} as TResp));
}
@@ -13,41 +13,42 @@ const GROUP_IMAGE = 20;
const FALLBACK_IMAGE = 2;
export namespace FetchDownloadRkeys {
export const command = 0x9067;
export const subCommand = 202;
export const uinForm = true;
export const command = 0x9067;
export const subCommand = 202;
export const uinForm = true;
export interface Params {}
export interface Params {}
export type Deps = OidbSender;
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 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 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');
}
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
return body;
};
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
export const invoke = (deps: Deps): Promise<NTV2RichMediaResp> =>
invokeOidb(deps, FetchDownloadRkeys, {});
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
export const invoke = (deps: Deps): Promise<NTV2RichMediaResp> =>
invokeOidb(deps, FetchDownloadRkeys, {});
}
@@ -5,101 +5,115 @@
// while-loop until the server stops emitting a cookie and
// concatenates results into the public FriendInfo[] shape.
import type { OidbBase, OidbFriend, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
import type {
OidbBase,
OidbFriend,
OidbSvcTrpcTcp0xFD4_1Response,
} from '@snowluma/proto-defs/oidb';
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FriendInfo } from '../../qq-info';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface FriendListPageEntry {
friend: FriendInfo;
categoryId: number;
friend: FriendInfo;
categoryId: number;
}
export interface FriendListPageCategory {
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
}
export interface FriendListPage {
entries: FriendListPageEntry[];
categories: FriendListPageCategory[];
cookie?: Uint8Array;
entries: FriendListPageEntry[];
categories: FriendListPageCategory[];
cookie?: Uint8Array;
}
function friendProperties(raw: OidbFriend): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) {
continue;
}
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
}
}
}
return props;
return props;
}
function mapFriend(raw: OidbFriend): FriendListPageEntry {
const props = friendProperties(raw);
return {
categoryId: raw.customGroup ?? 0,
friend: {
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
},
};
const props = friendProperties(raw);
return {
categoryId: raw.customGroup ?? 0,
friend: {
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
},
};
}
export namespace FetchFriendListPage {
export const command = 0xFD4;
export const subCommand = 1;
export const command = 0xfd4;
export const subCommand = 1;
export interface Params {
/** Opaque cookie returned by the previous page. Omit on page one. */
cookie?: Uint8Array;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbFriendListRequest => {
const body: OidbFriendListRequest = {
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.cookie?.length) {
body.cookie = p.cookie;
export interface Params {
/** Opaque cookie returned by the previous page. Omit on page one. */
cookie?: Uint8Array;
}
return body;
};
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFD4_1Response): FriendListPage => ({
entries: (body.friends ?? []).map(mapFriend),
categories: (body.categories ?? []).map((raw) => ({
categoryId: raw.categoryId ?? 0,
categoryName: raw.categoryName ?? '',
memberCount: raw.memberCount ?? 0,
sortId: raw.sortId ?? 0,
})),
cookie: body.cookie?.length ? Uint8Array.from(body.cookie) : undefined,
});
export type Deps = OidbSender;
export const encode = (env: OidbBase<OidbFriendListRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbFriendListRequest>>(env);
export const serialize = (_ctx: Deps, p: Params): OidbFriendListRequest => {
const body: OidbFriendListRequest = {
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,
};
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFD4_1Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>(bytes);
if (p.cookie?.length) {
body.cookie = p.cookie;
}
export const invoke = (deps: Deps, params: Params): Promise<FriendListPage> =>
invokeOidb(deps, FetchFriendListPage, params);
return body;
};
export const deserialize = (
_ctx: Deps,
body: OidbSvcTrpcTcp0xFD4_1Response,
): FriendListPage => ({
entries: (body.friends ?? []).map(mapFriend),
categories: (body.categories ?? []).map((raw) => ({
categoryId: raw.categoryId ?? 0,
categoryName: raw.categoryName ?? '',
memberCount: raw.memberCount ?? 0,
sortId: raw.sortId ?? 0,
})),
cookie: body.cookie?.length ? Uint8Array.from(body.cookie) : undefined,
});
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<FriendListPage> =>
invokeOidb(deps, FetchFriendListPage, params);
}
@@ -13,40 +13,59 @@ import type { OidbGroupDetailRequest } from '@snowluma/proto-defs/oidb-actions/b
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchGroupDetail {
export const command = 0x88D;
export const subCommand = 0;
// NOTE: deliberately no `uinForm` — Lagrange sends this with reserved=0.
export const command = 0x88d;
export const subCommand = 0;
// NOTE: deliberately no `uinForm` — Lagrange sends this with reserved=0.
export interface Params { groupUin: number; }
export interface Params {
groupUin: number;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
const on = true;
const on = true;
export const serialize = (_ctx: Deps, p: Params): OidbGroupDetailRequest => ({
field1: 537099973,
config: {
uin: BigInt(p.groupUin),
// Mirror Lagrange's flag set so the server returns the full detail block.
flags: {
ownerUid: on, createTime: on, maxMemberCount: on, memberCount: on,
level: on, name: '', noticePreview: '', uin: on, lastSequence: on,
lastMessageTime: on, question: '', answer: '', maxAdminCount: '',
// Tag 45 (not Lagrange's 59): official request mask for 60027.
shutUpAllTimestamp: on, addType: on, privilegeFlag: on, groupFlagExt4: on,
noFingerOpen: on, noCodeFingerOpen: on,
},
},
});
export const serialize = (_ctx: Deps, p: Params): OidbGroupDetailRequest => ({
field1: 537099973,
config: {
uin: BigInt(p.groupUin),
// Mirror Lagrange's flag set so the server returns the full detail block.
flags: {
ownerUid: on,
createTime: on,
maxMemberCount: on,
memberCount: on,
level: on,
name: '',
noticePreview: '',
uin: on,
lastSequence: on,
lastMessageTime: on,
question: '',
answer: '',
maxAdminCount: '',
// Tag 45 (not Lagrange's 59): official request mask for 60027.
shutUpAllTimestamp: on,
addType: on,
privilegeFlag: on,
groupFlagExt4: on,
noFingerOpen: on,
noCodeFingerOpen: on,
},
},
});
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0x88D_0Response): OidbSvcTrpcTcp0x88D_0Response => body;
export const deserialize = (
_ctx: Deps,
body: OidbSvcTrpcTcp0x88D_0Response,
): OidbSvcTrpcTcp0x88D_0Response => body;
export const encode = (env: OidbBase<OidbGroupDetailRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupDetailRequest>>(env);
export const encode = (env: OidbBase<OidbGroupDetailRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupDetailRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0x88D_0Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0x88D_0Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>(bytes);
export const invoke = (deps: Deps, p: Params): Promise<OidbSvcTrpcTcp0x88D_0Response> =>
invokeOidb(deps, FetchGroupDetail, p);
export const invoke = (deps: Deps, p: Params): Promise<OidbSvcTrpcTcp0x88D_0Response> =>
invokeOidb(deps, FetchGroupDetail, p);
}
@@ -15,44 +15,77 @@ import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/bas
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchGroupList {
export const command = 0xFE5;
export const subCommand = 2;
export const uinForm = true;
export const command = 0xfe5;
export const subCommand = 2;
export const uinForm = true;
export interface Params {}
export interface Params {}
export type Deps = OidbSender;
export type Deps = OidbSender;
const allTrue = true;
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, remark: true, field4: false,
field5: false, field6: false, field7: false, field8: false,
},
config3: { field5: allTrue, field6: allTrue },
},
});
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,
remark: true,
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 deserialize = (
_ctx: Deps,
body: OidbSvcTrpcTcp0xFE5_2Response,
): OidbSvcTrpcTcp0xFE5_2Response => body;
export const encode = (env: OidbBase<OidbGroupListRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupListRequest>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFE5_2Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(bytes);
export const invoke = (deps: Deps): Promise<OidbSvcTrpcTcp0xFE5_2Response> =>
invokeOidb(deps, FetchGroupList, {});
export const invoke = (deps: Deps): Promise<OidbSvcTrpcTcp0xFE5_2Response> =>
invokeOidb(deps, FetchGroupList, {});
}
@@ -13,71 +13,95 @@ import type { GroupMemberInfo } from '../../qq-info';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupMemberListPage {
members: GroupMemberInfo[];
token: string;
members: GroupMemberInfo[];
token: string;
}
function permissionToRole(permission: number): string {
switch (permission) {
case 1: return 'owner';
case 2: return 'admin';
default: return 'member';
}
switch (permission) {
case 1:
return 'owner';
case 2:
return 'admin';
default:
return 'member';
}
}
export namespace FetchGroupMemberListPage {
export const command = 0xFE7;
export const subCommand = 3;
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 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 type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupMemberListRequest => {
const body: OidbGroupMemberListRequest = {
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,
},
export const serialize = (_ctx: Deps, p: Params): OidbGroupMemberListRequest => {
const body: OidbGroupMemberListRequest = {
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;
};
if (p.token) body.token = p.token;
return body;
};
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFE7_3Response): GroupMemberListPage => ({
members: (body.members ?? []).map((raw) => ({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
isRobot: false,
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
})),
token: body.token ?? '',
});
export const deserialize = (
_ctx: Deps,
body: OidbSvcTrpcTcp0xFE7_3Response,
): GroupMemberListPage => ({
members: (body.members ?? []).map((raw) => ({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
isRobot: false,
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
})),
token: body.token ?? '',
});
export const encode = (env: OidbBase<OidbGroupMemberListRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupMemberListRequest>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFE7_3Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupMemberListPage> =>
invokeOidb(deps, FetchGroupMemberListPage, params);
export const invoke = (deps: Deps, params: Params): Promise<GroupMemberListPage> =>
invokeOidb(deps, FetchGroupMemberListPage, params);
}
@@ -8,13 +8,13 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
OidbBase,
OidbSvcTrpcTcp0x10C0Response,
OidbSvcTrpcTcp0x10C0ResponseByUin,
OidbSvcTrpcTcp0x10C0ResponseRequest,
OidbSvcTrpcTcp0x10C0ResponseRequestByUin,
OidbSvcTrpcTcp0x10C0ResponseUser,
OidbSvcTrpcTcp0x10C0ResponseUserByUin,
OidbBase,
OidbSvcTrpcTcp0x10C0Response,
OidbSvcTrpcTcp0x10C0ResponseByUin,
OidbSvcTrpcTcp0x10C0ResponseRequest,
OidbSvcTrpcTcp0x10C0ResponseRequestByUin,
OidbSvcTrpcTcp0x10C0ResponseUser,
OidbSvcTrpcTcp0x10C0ResponseUserByUin,
} from '@snowluma/proto-defs/oidb';
import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
@@ -24,166 +24,196 @@ import { invokeOidb, type OidbSender } from '../../oidb-service';
// the current Linux client; keeping the distinction prevents list type 7
// (join request) from being incorrectly sent back as operation type 7.
const GROUP_REQUEST_OPERATION_TYPE = new Map<number, number>([
[0, 0], [1, 2], [2, 10], [3, 11], [4, 12], [5, 22],
[6, 35], [7, 1], [8, 3], [9, 6], [10, 7], [11, 13],
[12, 15], [13, 16], [14, 17], [15, 19], [16, 8], [17, 100],
[0, 0],
[1, 2],
[2, 10],
[3, 11],
[4, 12],
[5, 22],
[6, 35],
[7, 1],
[8, 3],
[9, 6],
[10, 7],
[11, 13],
[12, 15],
[13, 16],
[14, 17],
[15, 19],
[16, 8],
[17, 100],
]);
const GROUP_REQUEST_OPERATION_OUTPUT = new Set(GROUP_REQUEST_OPERATION_TYPE.values());
export function groupRequestOperationType(notifyType: number): number | null {
const mapped = GROUP_REQUEST_OPERATION_TYPE.get(notifyType);
if (mapped !== undefined) return mapped;
// Some list replies already carry the mapped discriminator (e.g. 22).
if (GROUP_REQUEST_OPERATION_OUTPUT.has(notifyType)) return notifyType;
return null;
const mapped = GROUP_REQUEST_OPERATION_TYPE.get(notifyType);
if (mapped !== undefined) {
return mapped;
}
// Some list replies already carry the mapped discriminator (e.g. 22).
if (GROUP_REQUEST_OPERATION_OUTPUT.has(notifyType)) {
return notifyType;
}
return null;
}
export interface DecodedGroupRequestUser {
uid: string;
uin: number;
name: string;
uid: string;
uin: number;
name: string;
}
export interface DecodedGroupRequest {
sequence?: bigint;
eventType?: number;
state?: number;
group?: { groupUin?: number; groupName?: string };
target?: DecodedGroupRequestUser;
invitor?: DecodedGroupRequestUser;
operatorUser?: DecodedGroupRequestUser;
comment?: string;
operateTransInfo?: Uint8Array;
sequence?: bigint;
eventType?: number;
state?: number;
group?: { groupUin?: number; groupName?: string };
target?: DecodedGroupRequestUser;
invitor?: DecodedGroupRequestUser;
operatorUser?: DecodedGroupRequestUser;
comment?: string;
operateTransInfo?: Uint8Array;
}
export interface DecodedGroupRequestList {
requests?: DecodedGroupRequest[];
field2?: bigint;
newLatestSeq?: bigint;
field4?: number;
field5?: bigint;
field6?: number;
requests?: DecodedGroupRequest[];
field2?: bigint;
newLatestSeq?: bigint;
field4?: number;
field5?: bigint;
field6?: number;
}
function mergeRequestUser(
byUin?: OidbSvcTrpcTcp0x10C0ResponseUserByUin,
byUid?: OidbSvcTrpcTcp0x10C0ResponseUser,
byUin?: OidbSvcTrpcTcp0x10C0ResponseUserByUin,
byUid?: OidbSvcTrpcTcp0x10C0ResponseUser,
): DecodedGroupRequestUser {
return {
uid: byUid?.uid ?? '',
uin: byUin?.uin ?? 0,
name: (byUin?.name || byUid?.name) ?? '',
};
return {
uid: byUid?.uid ?? '',
uin: byUin?.uin ?? 0,
name: (byUin?.name || byUid?.name) ?? '',
};
}
function mergeRequestItem(
byUin?: OidbSvcTrpcTcp0x10C0ResponseRequestByUin,
byUid?: OidbSvcTrpcTcp0x10C0ResponseRequest,
byUin?: OidbSvcTrpcTcp0x10C0ResponseRequestByUin,
byUid?: OidbSvcTrpcTcp0x10C0ResponseRequest,
): DecodedGroupRequest {
const src = byUin ?? byUid;
return {
sequence: src?.sequence,
eventType: src?.eventType,
state: src?.state,
group: src?.group,
target: mergeRequestUser(byUin?.target, byUid?.target),
invitor: mergeRequestUser(byUin?.invitor, byUid?.invitor),
operatorUser: mergeRequestUser(byUin?.operatorUser, byUid?.operatorUser),
comment: src?.comment ?? '',
operateTransInfo: src?.operateTransInfo,
};
const src = byUin ?? byUid;
return {
sequence: src?.sequence,
eventType: src?.eventType,
state: src?.state,
group: src?.group,
target: mergeRequestUser(byUin?.target, byUid?.target),
invitor: mergeRequestUser(byUin?.invitor, byUid?.invitor),
operatorUser: mergeRequestUser(byUin?.operatorUser, byUid?.operatorUser),
comment: src?.comment ?? '',
operateTransInfo: src?.operateTransInfo,
};
}
function mergeRequestList(
byUin?: OidbSvcTrpcTcp0x10C0ResponseByUin,
byUid?: OidbSvcTrpcTcp0x10C0Response,
byUin?: OidbSvcTrpcTcp0x10C0ResponseByUin,
byUid?: OidbSvcTrpcTcp0x10C0Response,
): DecodedGroupRequestList {
const src = byUin ?? byUid;
const uinItems = byUin?.requests ?? [];
const uidItems = byUid?.requests ?? [];
const count = Math.max(uinItems.length, uidItems.length);
const requests: DecodedGroupRequest[] = [];
for (let i = 0; i < count; i++) {
requests.push(mergeRequestItem(uinItems[i], uidItems[i]));
}
return {
requests,
field2: src?.field2,
newLatestSeq: src?.newLatestSeq,
field4: src?.field4,
field5: src?.field5,
field6: src?.field6,
};
const src = byUin ?? byUid;
const uinItems = byUin?.requests ?? [];
const uidItems = byUid?.requests ?? [];
const count = Math.max(uinItems.length, uidItems.length);
const requests: DecodedGroupRequest[] = [];
for (let i = 0; i < count; i++) {
requests.push(mergeRequestItem(uinItems[i], uidItems[i]));
}
return {
requests,
field2: src?.field2,
newLatestSeq: src?.newLatestSeq,
field4: src?.field4,
field5: src?.field5,
field6: src?.field6,
};
}
export namespace FetchGroupRequests {
export const command = 0x10C0;
export const uinForm = true;
export const command = 0x10c0;
export const uinForm = true;
export interface Params {
/** false → subCmd 1 (main inbox), true → subCmd 2 (filtered). */
filtered: boolean;
/** Maximum records in this screen. QQ's own default is 50. */
count?: number;
/** Cursor returned by response field 2; zero starts at the newest screen. */
cursor?: bigint;
}
export interface Params {
/** false → subCmd 1 (main inbox), true → subCmd 2 (filtered). */
filtered: boolean;
/** Maximum records in this screen. QQ's own default is 50. */
count?: number;
/** Cursor returned by response field 2; zero starts at the newest screen. */
cursor?: bigint;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1;
export const resolveSubCommand = (p: Params): number => (p.filtered ? 2 : 1);
export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestList => ({
count: p.count ?? 50,
field2: p.cursor ?? 0n,
});
export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestList => ({
count: p.count ?? 50,
field2: p.cursor ?? 0n,
});
export const deserialize = (_ctx: Deps, body: DecodedGroupRequestList): DecodedGroupRequestList => body;
export const deserialize = (
_ctx: Deps,
body: DecodedGroupRequestList,
): DecodedGroupRequestList => body;
export const encode = (env: OidbBase<OidbGroupRequestList>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupRequestList>>(env);
export const encode = (env: OidbBase<OidbGroupRequestList>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupRequestList>>(env);
export const decode = (bytes: Uint8Array): OidbBase<DecodedGroupRequestList> => {
const byUin = protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0ResponseByUin>>(bytes);
const byUid = protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(bytes);
return {
...byUin,
body: mergeRequestList(byUin.body, byUid.body),
export const decode = (bytes: Uint8Array): OidbBase<DecodedGroupRequestList> => {
const byUin = protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0ResponseByUin>>(bytes);
const byUid = protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(bytes);
return {
...byUin,
body: mergeRequestList(byUin.body, byUid.body),
};
};
};
export const invoke = (deps: Deps, params: Params): Promise<DecodedGroupRequestList> =>
invokeOidb(deps, FetchGroupRequests, params);
export const invoke = (deps: Deps, params: Params): Promise<DecodedGroupRequestList> =>
invokeOidb(deps, FetchGroupRequests, params);
}
/** UID-form compatibility path used only when an incoming push supplies UID
* but no UIN. It intentionally leaves the envelope's reserved field unset. */
export namespace FetchGroupRequestsByUid {
export const command = 0x10C0;
export const command = 0x10c0;
export interface Params {
filtered: boolean;
count?: number;
cursor?: bigint;
}
export interface Params {
filtered: boolean;
count?: number;
cursor?: bigint;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1;
export const resolveSubCommand = (p: Params): number => (p.filtered ? 2 : 1);
export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestList => ({
count: p.count ?? 50,
field2: p.cursor ?? 0n,
});
export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestList => ({
count: p.count ?? 50,
field2: p.cursor ?? 0n,
});
export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0x10C0Response): OidbSvcTrpcTcp0x10C0Response => body;
export const deserialize = (
_ctx: Deps,
body: OidbSvcTrpcTcp0x10C0Response,
): OidbSvcTrpcTcp0x10C0Response => body;
export const encode = (env: OidbBase<OidbGroupRequestList>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupRequestList>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0x10C0Response> =>
protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0x10C0Response> =>
invokeOidb(deps, FetchGroupRequestsByUid, params);
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0x10C0Response> =>
invokeOidb(deps, FetchGroupRequestsByUid, params);
}
@@ -11,76 +11,86 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface RobotUinRange {
minUin: number;
maxUin: number;
minUin: number;
maxUin: number;
}
export interface RobotUinRangeSnapshot {
version: number;
ranges: RobotUinRange[];
version: number;
ranges: RobotUinRange[];
}
function decodeUin(value: bigint | number | undefined, label: string): number {
const decoded = Number(value ?? 0);
if (!Number.isSafeInteger(decoded) || decoded <= 0 || decoded > 0xFFFF_FFFF) {
throw new Error(`0x496_0 response has invalid ${label}: ${String(value)}`);
}
return decoded;
const decoded = Number(value ?? 0);
if (!Number.isSafeInteger(decoded) || decoded <= 0 || decoded > 0xffff_ffff) {
throw new Error(`0x496_0 response has invalid ${label}: ${String(value)}`);
}
return decoded;
}
export namespace FetchRobotUinRanges {
export const command = 0x496;
export const subCommand = 0;
export const command = 0x496;
export const subCommand = 0;
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (): OidbRobotUinRangeRequest => ({
justFetchMsgConfig: 1,
type: 1,
version: 0,
aioKeywordVersion: 0,
});
export const deserialize = (
_ctx: Deps,
body: OidbRobotUinRangeResponse,
): RobotUinRangeSnapshot => {
const config = body.robotConfig;
if (!config) {
throw new Error('0x496_0 response missing robot range config');
}
if (config.version === undefined) {
throw new Error('0x496_0 response missing robot range config version');
}
const version = Number(config.version);
if (!Number.isSafeInteger(version) || version < 0) {
throw new Error(`0x496_0 response has invalid config version: ${String(config.version)}`);
}
if (!config.ranges || config.ranges.length === 0) {
throw new Error('0x496_0 response has no robot UIN ranges');
}
const ranges = config.ranges.map((range, index) => {
const minUin = decodeUin(range.minUin, `range[${index}].minUin`);
const maxUin = decodeUin(range.maxUin, `range[${index}].maxUin`);
if (minUin > maxUin) {
throw new Error(
`0x496_0 response has inverted range[${index}]: ${minUin}-${maxUin}`,
);
}
return { minUin, maxUin };
export const serialize = (): OidbRobotUinRangeRequest => ({
justFetchMsgConfig: 1,
type: 1,
version: 0,
aioKeywordVersion: 0,
});
return { version, ranges };
};
export const deserialize = (
_ctx: Deps,
body: OidbRobotUinRangeResponse,
): RobotUinRangeSnapshot => {
const config = body.robotConfig;
export const encode = (env: OidbBase<OidbRobotUinRangeRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbRobotUinRangeRequest>>(env);
if (!config) {
throw new Error('0x496_0 response missing robot range config');
}
export const decode = (bytes: Uint8Array): OidbBase<OidbRobotUinRangeResponse> =>
protobuf_decode<OidbBase<OidbRobotUinRangeResponse>>(bytes);
if (config.version === undefined) {
throw new Error('0x496_0 response missing robot range config version');
}
export const invoke = (deps: Deps): Promise<RobotUinRangeSnapshot> =>
invokeOidb(deps, FetchRobotUinRanges, undefined);
const version = Number(config.version);
if (!Number.isSafeInteger(version) || version < 0) {
throw new Error(
`0x496_0 response has invalid config version: ${String(config.version)}`,
);
}
if (!config.ranges || config.ranges.length === 0) {
throw new Error('0x496_0 response has no robot UIN ranges');
}
const ranges = config.ranges.map((range, index) => {
const minUin = decodeUin(range.minUin, `range[${index}].minUin`);
const maxUin = decodeUin(range.maxUin, `range[${index}].maxUin`);
if (minUin > maxUin) {
throw new Error(
`0x496_0 response has inverted range[${index}]: ${minUin}-${maxUin}`,
);
}
return { minUin, maxUin };
});
return { version, ranges };
};
export const encode = (env: OidbBase<OidbRobotUinRangeRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbRobotUinRangeRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbRobotUinRangeResponse> =>
protobuf_decode<OidbBase<OidbRobotUinRangeResponse>>(bytes);
export const invoke = (deps: Deps): Promise<RobotUinRangeSnapshot> =>
invokeOidb(deps, FetchRobotUinRanges, undefined);
}
@@ -17,93 +17,112 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
AvatarInfo,
OidbUserInfoByUidRequest,
OidbUserInfoResponse,
AvatarInfo,
OidbUserInfoByUidRequest,
OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { UserProfileInfo } from '../../qq-info';
import { applyOnlineStatus, applyProfileDetails } from './fetch-user-profile';
import { invokeOidb, type OidbSender } from '../../oidb-service';
const REQUESTED_KEYS = [
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026,
105, 27372, 27406, 20037,
41756, 41757, 42241,
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
40410, 42031,
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037, 41756,
41757, 42241,
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
40410, 42031,
];
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 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,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 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;
applyOnlineStatus(info, bytesMap, numMap);
applyProfileDetails(info, numMap);
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
info.qidianMasterFlag = numMap.get(42031) ?? 0;
info.qidianCrewFlag = numMap.get(40410) ?? 0;
export interface Params {
uid: string;
}
return info;
};
export type Deps = OidbSender;
export const encode = (env: OidbBase<OidbUserInfoByUidRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbUserInfoByUidRequest>>(env);
export const serialize = (_ctx: Deps, p: Params): OidbUserInfoByUidRequest => ({
uid: p.uid,
keys: REQUESTED_KEYS.map((k) => ({ key: k })),
});
export const decode = (bytes: Uint8Array): OidbBase<OidbUserInfoResponse> =>
protobuf_decode<OidbBase<OidbUserInfoResponse>>(bytes);
export const deserialize = (_ctx: Deps, body: OidbUserInfoResponse): UserProfileInfo => {
if (!body.body) {
throw new Error('user info response body missing');
}
export const invoke = (deps: Deps, params: Params): Promise<UserProfileInfo> =>
invokeOidb(deps, FetchUserProfileByUid, params);
const info: UserProfileInfo = {
uin: body.body.uin ?? 0,
uid: body.body.uid ?? '',
nickname: '',
remark: '',
qid: '',
sex: 'unknown',
age: 0,
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 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;
applyOnlineStatus(info, bytesMap, numMap);
applyProfileDetails(info, numMap);
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
info.qidianMasterFlag = numMap.get(42031) ?? 0;
info.qidianCrewFlag = numMap.get(40410) ?? 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);
}
@@ -20,149 +20,187 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
AvatarInfo,
OidbCustomStatus,
OidbUserInfoRequest,
OidbUserInfoResponse,
AvatarInfo,
OidbCustomStatus,
OidbUserInfoRequest,
OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { UserProfileInfo } from '../../qq-info';
import { unpackStatusWord } from '../extras/get-stranger-status';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export function applyOnlineStatus(
info: UserProfileInfo,
bytesMap: Map<number, Uint8Array>,
numMap: Map<number, number>,
info: UserProfileInfo,
bytesMap: Map<number, Uint8Array>,
numMap: Map<number, number>,
): void {
const statusRaw = numMap.get(27372);
if (statusRaw !== undefined) {
const unpacked = unpackStatusWord(statusRaw);
info.status = unpacked.status;
info.extStatus = unpacked.ext_status;
info.batteryStatus = 0;
}
const customBytes = bytesMap.get(27406);
if (customBytes && customBytes.length > 0) {
const custom = protobuf_decode<OidbCustomStatus>(customBytes);
info.customStatus = {
faceId: custom.faceId ?? 0,
wording: custom.msg ?? '',
};
info.customStatusDesc = custom.msg ?? '';
}
const statusRaw = numMap.get(27372);
if (statusRaw !== undefined) {
const unpacked = unpackStatusWord(statusRaw);
info.status = unpacked.status;
info.extStatus = unpacked.ext_status;
info.batteryStatus = 0;
}
const customBytes = bytesMap.get(27406);
if (customBytes && customBytes.length > 0) {
const custom = protobuf_decode<OidbCustomStatus>(customBytes);
info.customStatus = {
faceId: custom.faceId ?? 0,
wording: custom.msg ?? '',
};
info.customStatusDesc = custom.msg ?? '';
}
}
export function applyProfileDetails(info: UserProfileInfo, numMap: Map<number, number>): void {
const registered = numMap.get(20026);
if (registered !== undefined && registered > 0) info.regTime = registered;
const flags = numMap.get(41756);
if (flags !== undefined) {
info.vipFlag = (flags & 1) !== 0;
info.yearVipFlag = (flags & 2) !== 0;
info.svipFlag = (flags & 0x100) !== 0;
}
const level = numMap.get(41757);
if (level !== undefined) {
const mask = level & 0xFFF;
if (mask !== 0) info.vipLevel = 33 - Math.clz32(mask);
else if (info.vipFlag || info.yearVipFlag || info.svipFlag || numMap.get(42241) === 1) {
info.vipLevel = 1;
} else if (flags !== undefined && numMap.has(42241)) info.vipLevel = 0;
}
const registered = numMap.get(20026);
if (registered !== undefined && registered > 0) {
info.regTime = registered;
}
const flags = numMap.get(41756);
if (flags !== undefined) {
info.vipFlag = (flags & 1) !== 0;
info.yearVipFlag = (flags & 2) !== 0;
info.svipFlag = (flags & 0x100) !== 0;
}
const level = numMap.get(41757);
if (level !== undefined) {
const mask = level & 0xfff;
if (mask !== 0) {
info.vipLevel = 33 - Math.clz32(mask);
} else if (info.vipFlag || info.yearVipFlag || info.svipFlag || numMap.get(42241) === 1) {
info.vipLevel = 1;
} else if (flags !== undefined && numMap.has(42241)) {
info.vipLevel = 0;
}
}
}
const REQUESTED_KEYS = [
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026,
105, 27372, 27406, 20037,
41756, 41757, 42241,
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
40410, 42031,
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037, 41756,
41757, 42241,
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
40410, 42031,
];
export namespace FetchUserProfile {
export const command = 0xFE1;
export const subCommand = 2;
export const uinForm = true;
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,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 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;
applyOnlineStatus(info, bytesMap, numMap);
applyProfileDetails(info, numMap);
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
info.qidianMasterFlag = numMap.get(42031) ?? 0;
info.qidianCrewFlag = numMap.get(40410) ?? 0;
export interface Params {
uin: number;
}
return info;
};
export type Deps = OidbSender;
// 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 serialize = (_ctx: Deps, p: Params): OidbUserInfoRequest => ({
uin: p.uin,
keys: REQUESTED_KEYS.map((k) => ({ key: k })),
});
export const encode = (env: OidbBase<OidbUserInfoRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbUserInfoRequest>>(env);
/** 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');
}
export const decode = (bytes: Uint8Array): OidbBase<OidbUserInfoResponse> =>
protobuf_decode<OidbBase<OidbUserInfoResponse>>(bytes);
const info: UserProfileInfo = {
uin: body.body.uin ?? requestedUin,
uid: body.body.uid ?? '',
nickname: '',
remark: '',
qid: '',
sex: 'unknown',
age: 0,
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 0,
};
export const invoke = (deps: Deps, params: Params): Promise<UserProfileInfo> =>
invokeOidb(deps, {
...FetchUserProfile,
deserialize: (_ctx, body) => deserializeWithFallback(body, params.uin),
}, params);
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;
applyOnlineStatus(info, bytesMap, numMap);
applyProfileDetails(info, numMap);
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
info.qidianMasterFlag = numMap.get(42031) ?? 0;
info.qidianCrewFlag = numMap.get(40410) ?? 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,
);
}
@@ -6,34 +6,39 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbBuddyRecommendArkReq, OidbBuddyRecommendArkResp,
OidbBuddyRecommendArkReq,
OidbBuddyRecommendArkResp,
} from '@snowluma/proto-defs/oidb-actions/contact-ark';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetBuddyRecommendArk {
export const command = 0x12B6;
export const subCommand = 0;
export const uinForm = false;
export const command = 0x12b6;
export const subCommand = 0;
export const uinForm = false;
export interface Params { userId: number; phoneNumber?: string }
export type Deps = OidbSender;
export interface Params {
userId: number;
phoneNumber?: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbBuddyRecommendArkReq => ({
uin: p.userId,
phoneNumber: p.phoneNumber || '-',
// Client-side jump_url the kernel hard-codes alongside the uin; the
// server echoes it into the card. Mirrors the NT template exactly.
jumpUrl: `mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=${p.userId}`,
});
export const serialize = (_ctx: Deps, p: Params): OidbBuddyRecommendArkReq => ({
uin: p.userId,
phoneNumber: p.phoneNumber || '-',
// Client-side jump_url the kernel hard-codes alongside the uin; the
// server echoes it into the card. Mirrors the NT template exactly.
jumpUrl: `mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=${p.userId}`,
});
export const deserialize = (_ctx: Deps, body: OidbBuddyRecommendArkResp): string => body.ark ?? '';
export const deserialize = (_ctx: Deps, body: OidbBuddyRecommendArkResp): string =>
body.ark ?? '';
export const encode = (env: OidbBase<OidbBuddyRecommendArkReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbBuddyRecommendArkReq>>(env);
export const encode = (env: OidbBase<OidbBuddyRecommendArkReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbBuddyRecommendArkReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbBuddyRecommendArkResp> =>
protobuf_decode<OidbBase<OidbBuddyRecommendArkResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbBuddyRecommendArkResp> =>
protobuf_decode<OidbBase<OidbBuddyRecommendArkResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetBuddyRecommendArk, params);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetBuddyRecommendArk, params);
}
@@ -8,33 +8,37 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupRecommendArkReq, OidbGroupRecommendArkResp,
OidbGroupRecommendArkReq,
OidbGroupRecommendArkResp,
} from '@snowluma/proto-defs/oidb-actions/contact-ark';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetGroupRecommendArk {
export const command = 0x8B7;
export const subCommand = 5;
export const uinForm = true;
export const command = 0x8b7;
export const subCommand = 5;
export const uinForm = true;
export interface Params { groupId: number }
export type Deps = OidbSender;
export interface Params {
groupId: number;
}
export type Deps = OidbSender;
// reqType and flag are constants the NT encoder always sends (1 and 1).
export const serialize = (_ctx: Deps, p: Params): OidbGroupRecommendArkReq => ({
reqType: 1,
groupCode: p.groupId,
flag: 1,
});
// reqType and flag are constants the NT encoder always sends (1 and 1).
export const serialize = (_ctx: Deps, p: Params): OidbGroupRecommendArkReq => ({
reqType: 1,
groupCode: p.groupId,
flag: 1,
});
export const deserialize = (_ctx: Deps, body: OidbGroupRecommendArkResp): string => body.arkJson ?? '';
export const deserialize = (_ctx: Deps, body: OidbGroupRecommendArkResp): string =>
body.arkJson ?? '';
export const encode = (env: OidbBase<OidbGroupRecommendArkReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupRecommendArkReq>>(env);
export const encode = (env: OidbBase<OidbGroupRecommendArkReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupRecommendArkReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupRecommendArkResp> =>
protobuf_decode<OidbBase<OidbGroupRecommendArkResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupRecommendArkResp> =>
protobuf_decode<OidbBase<OidbGroupRecommendArkResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetGroupRecommendArk, params);
export const invoke = (deps: Deps, params: Params): Promise<string> =>
invokeOidb(deps, GetGroupRecommendArk, params);
}
@@ -7,61 +7,61 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0xdc2_34Req,
Oidb0xdc2_34Resp,
Oidb0xdc2_34Req,
Oidb0xdc2_34Resp,
} from '@snowluma/proto-defs/oidb-actions/contact-ark';
import { invokeOidb, type OidbSender } from '../../oidb-service';
const TUWEN_ARK_APPID = 100446242;
export type SendTuwenArkParams = {
targetId: number;
peerType: 0 | 1;
title: string;
desc: string;
summary: string;
jumpUrl: string;
previewUrl: string;
targetId: number;
peerType: 0 | 1;
title: string;
desc: string;
summary: string;
jumpUrl: string;
previewUrl: string;
};
export namespace SendTuwenArk {
export const command = 0xDC2;
export const subCommand = 34;
export const uinForm = false;
export const command = 0xdc2;
export const subCommand = 34;
export const uinForm = false;
export type Params = SendTuwenArkParams;
export type Deps = OidbSender;
export type Params = SendTuwenArkParams;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0xdc2_34Req => ({
appInfo: {
appId: TUWEN_ARK_APPID,
field2: 1,
field3: 0,
field5: { field1: 1 },
targetId: p.targetId,
content: {
flag: 1,
title: p.title,
desc: p.desc,
summary: p.summary,
jumpUrl: p.jumpUrl,
previewUrl: p.previewUrl,
},
},
meta: {
peerType: p.peerType,
targetId: p.targetId,
},
});
export const serialize = (_ctx: Deps, p: Params): Oidb0xdc2_34Req => ({
appInfo: {
appId: TUWEN_ARK_APPID,
field2: 1,
field3: 0,
field5: { field1: 1 },
targetId: p.targetId,
content: {
flag: 1,
title: p.title,
desc: p.desc,
summary: p.summary,
jumpUrl: p.jumpUrl,
previewUrl: p.previewUrl,
},
},
meta: {
peerType: p.peerType,
targetId: p.targetId,
},
});
export const deserialize = (_ctx: Deps, _body: Oidb0xdc2_34Resp): void => undefined;
export const deserialize = (_ctx: Deps, _body: Oidb0xdc2_34Resp): void => undefined;
export const encode = (env: OidbBase<Oidb0xdc2_34Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0xdc2_34Req>>(env);
export const encode = (env: OidbBase<Oidb0xdc2_34Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0xdc2_34Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0xdc2_34Resp> =>
protobuf_decode<OidbBase<Oidb0xdc2_34Resp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0xdc2_34Resp> =>
protobuf_decode<OidbBase<Oidb0xdc2_34Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SendTuwenArk, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SendTuwenArk, params);
}
@@ -9,32 +9,32 @@ import { invokeOidb, type OidbSender } from '../../oidb-service';
* The desktop client treats 2001002 as an idempotent success result.
*/
export namespace SetFriendCategory {
export const command = 0x1255;
export const subCommand = 0;
export const uinForm = true;
export const alreadyAppliedCode = 2_001_002;
export const acceptedEnvelopeCodes = [alreadyAppliedCode] as const;
export const command = 0x1255;
export const subCommand = 0;
export const uinForm = true;
export const alreadyAppliedCode = 2_001_002;
export const acceptedEnvelopeCodes = [alreadyAppliedCode] as const;
export interface Params {
uid: string;
categoryId: number;
}
export interface Params {
uid: string;
categoryId: number;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, params: Params): OidbSetFriendCategoryRequest => ({
uid: params.uid,
categoryId: params.categoryId,
});
export const serialize = (_ctx: Deps, params: Params): OidbSetFriendCategoryRequest => ({
uid: params.uid,
categoryId: params.categoryId,
});
export const deserialize = (): void => undefined;
export const deserialize = (): void => undefined;
export const encode = (env: OidbBase<OidbSetFriendCategoryRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetFriendCategoryRequest>>(env);
export const encode = (env: OidbBase<OidbSetFriendCategoryRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetFriendCategoryRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbSetFriendCategoryRequest> =>
protobuf_decode<OidbBase<OidbSetFriendCategoryRequest>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbSetFriendCategoryRequest> =>
protobuf_decode<OidbBase<OidbSetFriendCategoryRequest>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetFriendCategory, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetFriendCategory, params);
}
@@ -10,112 +10,131 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
BDHExpressionRoamReq,
BDHExpressionRoamResp,
FavEmojiHighwayHead,
BDHExpressionRoamReq,
BDHExpressionRoamResp,
FavEmojiHighwayHead,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { BridgeContext } from '../../bridge-context';
import { fetchHighwaySession } from '../../highway/highway-client';
import { computeMd5, packHighwayFrame } from '../../highway/utils';
export namespace AddCustomFace {
const BDH_SERVICE = 'ImgStore.BDHExpressionRoam';
const BDH_SERVICE = 'ImgStore.BDHExpressionRoam';
export interface Params {
uin: string;
imageBytes: Uint8Array;
}
export interface Params {
uin: string;
imageBytes: Uint8Array;
}
// fetchHighwaySession 需要 sendRawPacket + identity,所以 Deps 比纯 OidbSender 多 identity。
export type Deps = Pick<BridgeContext, 'sendRawPacket' | 'identity'>;
// fetchHighwaySession 需要 sendRawPacket + identity,所以 Deps 比纯 OidbSender 多 identity。
export type Deps = Pick<BridgeContext, 'sendRawPacket' | 'identity'>;
function md5Hex(md5: Uint8Array): string {
let s = '';
for (const b of md5) s += b.toString(16).padStart(2, '0');
return s;
}
function md5Hex(md5: Uint8Array): string {
let s = '';
export async function invoke(deps: Deps, params: Params): Promise<string> {
const { uin, imageBytes } = params;
const md5 = computeMd5(imageBytes);
const emojiId = `${uin}_0_0_0_${md5Hex(md5).toUpperCase()}_0_0`;
for (const b of md5) {
s += b.toString(16).padStart(2, '0');
}
// 1. fetchHighwaySession 拿上传节点 host:port(复用 SnowLuma highway-client)
const session = await fetchHighwaySession(deps as unknown as BridgeContext);
const host = session.host;
const port = session.port;
return s;
}
// 2. BDHExpressionRoam 申请上传 token
const reqBody = protobuf_encode<BDHExpressionRoamReq>({
field1: 3,
field2: 1,
inner: {
field1: 0,
uin: BigInt(uin),
field3: 0,
md5,
filesize: imageBytes.length,
field7: 2,
field8: 0,
field9: 1,
ver: '1.0.0',
field16: 1,
},
field7: 9,
tail: { inner: { field1: 0, field2: 0, field3: '0' }, field2: 1 },
});
const result = await deps.sendRawPacket(BDH_SERVICE, reqBody);
if (!result.gotResponse) throw new Error(result.errorMessage || 'BDHExpressionRoam: no response');
if (!result.success) throw new Error(result.errorMessage || 'BDHExpressionRoam: send failed');
const resp = protobuf_decode<BDHExpressionRoamResp>(result.responseData ?? new Uint8Array(0));
const token = resp.inner?.token;
if (!token) throw new Error('BDHExpressionRoam: response missing token (field8)');
export async function invoke(deps: Deps, params: Params): Promise<string> {
const { uin, imageBytes } = params;
const md5 = computeMd5(imageBytes);
const emojiId = `${uin}_0_0_0_${md5Hex(md5).toUpperCase()}_0_0`;
// 3. 构造 highway head。serviceTicket = BDHExpressionRoam token。
const head = protobuf_encode<FavEmojiHighwayHead>({
baseHead: {
version: 1,
uin,
command: 'PicUp.DataUp',
seq: 1,
retryTimes: 0,
filesize: BigInt(imageBytes.length),
dataFlag: 16,
commandId: 9,
},
segHead: {
serviceId: 0,
filesize: BigInt(imageBytes.length),
dataOffset: 0n,
dataLength: BigInt(imageBytes.length),
serviceTicket: token,
md5,
fileMd5: md5,
},
emojiIdWrap: { emojiId },
field4: 0,
field8: 9,
// field5 (82B) 抓包见过但非必需,不填
});
// 1. fetchHighwaySession 拿上传节点 host:port(复用 SnowLuma highway-client)
const session = await fetchHighwaySession(deps as unknown as BridgeContext);
const host = session.host;
const port = session.port;
// 4. highway 帧(复用 SnowLuma packHighwayFrame,结构和抓包一致)
const frame = packHighwayFrame(head, imageBytes);
// 2. BDHExpressionRoam 申请上传 token
const reqBody = protobuf_encode<BDHExpressionRoamReq>({
field1: 3,
field2: 1,
inner: {
field1: 0,
uin: BigInt(uin),
field3: 0,
md5,
filesize: imageBytes.length,
field7: 2,
field8: 0,
field9: 1,
ver: '1.0.0',
field16: 1,
},
field7: 9,
tail: { inner: { field1: 0, field2: 0, field3: '0' }, field2: 1 },
});
const result = await deps.sendRawPacket(BDH_SERVICE, reqBody);
// 5. HTTP POST 上传。端口用 fetchHighwaySession 的 port(抓包确认 httpconn 端口 80)。
const url = `http://${host}:${port}/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${uin}`;
const httpResp = await fetch(url, {
method: 'POST',
body: frame,
headers: {
Accept: '*/*',
Connection: 'Keep-Alive',
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)',
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
},
});
if (!httpResp.ok) throw new Error(`highway upload failed: HTTP ${httpResp.status}`);
if (!result.gotResponse) {
throw new Error(result.errorMessage || 'BDHExpressionRoam: no response');
}
return emojiId;
}
if (!result.success) {
throw new Error(result.errorMessage || 'BDHExpressionRoam: send failed');
}
const resp = protobuf_decode<BDHExpressionRoamResp>(
result.responseData ?? new Uint8Array(0),
);
const token = resp.inner?.token;
if (!token) {
throw new Error('BDHExpressionRoam: response missing token (field8)');
}
// 3. 构造 highway head。serviceTicket = BDHExpressionRoam token。
const head = protobuf_encode<FavEmojiHighwayHead>({
baseHead: {
version: 1,
uin,
command: 'PicUp.DataUp',
seq: 1,
retryTimes: 0,
filesize: BigInt(imageBytes.length),
dataFlag: 16,
commandId: 9,
},
segHead: {
serviceId: 0,
filesize: BigInt(imageBytes.length),
dataOffset: 0n,
dataLength: BigInt(imageBytes.length),
serviceTicket: token,
md5,
fileMd5: md5,
},
emojiIdWrap: { emojiId },
field4: 0,
field8: 9,
// field5 (82B) 抓包见过但非必需,不填
});
// 4. highway 帧(复用 SnowLuma packHighwayFrame,结构和抓包一致)
const frame = packHighwayFrame(head, imageBytes);
// 5. HTTP POST 上传。端口用 fetchHighwaySession 的 port(抓包确认 httpconn 端口 80)。
const url = `http://${host}:${port}/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${uin}`;
const httpResp = await fetch(url, {
method: 'POST',
body: frame,
headers: {
Accept: '*/*',
Connection: 'Keep-Alive',
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)',
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
},
});
if (!httpResp.ok) {
throw new Error(`highway upload failed: HTTP ${httpResp.status}`);
}
return emojiId;
}
}
@@ -14,29 +14,34 @@ import type { OidbSender } from '../../oidb-service';
import { FACEROAM_SERVICE, makeInner } from './shared';
export namespace DeleteCustomFace {
export interface Params {
/** 当前账号 UIN,写入 field2。 */
uin: string;
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
}
export interface Params {
/** 当前账号 UIN,写入 field2。 */
uin: string;
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FaceroamOpReq => ({
inner: makeInner(false),
uin: BigInt(p.uin),
field3: 2,
body: { emojiId: p.emojiId },
});
export const serialize = (_ctx: Deps, p: Params): FaceroamOpReq => ({
inner: makeInner(false),
uin: BigInt(p.uin),
field3: 2,
body: { emojiId: p.emojiId },
});
export const encode = (req: FaceroamOpReq): Uint8Array =>
protobuf_encode<FaceroamOpReq>(req);
export const encode = (req: FaceroamOpReq): Uint8Array => protobuf_encode<FaceroamOpReq>(req);
export async function invoke(deps: Deps, params: Params): Promise<void> {
const body = encode(serialize(deps, params));
const result = await deps.sendRawPacket(FACEROAM_SERVICE, body);
if (!result.gotResponse) throw new Error(result.errorMessage || 'Faceroam.OpReq delete: no response');
if (!result.success) throw new Error(result.errorMessage || 'Faceroam.OpReq delete: send failed');
}
export async function invoke(deps: Deps, params: Params): Promise<void> {
const body = encode(serialize(deps, params));
const result = await deps.sendRawPacket(FACEROAM_SERVICE, body);
if (!result.gotResponse) {
throw new Error(result.errorMessage || 'Faceroam.OpReq delete: no response');
}
if (!result.success) {
throw new Error(result.errorMessage || 'Faceroam.OpReq delete: send failed');
}
}
}
@@ -4,73 +4,78 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
CustomFaceModifyResp,
CustomFaceMoveBody,
CustomFaceModifyResp,
CustomFaceMoveBody,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { CLIENT_VERSION } from './shared';
export namespace FetchCustomFaceDetail {
export const command = 0x902e;
export const subCommand = 1;
export const uinForm = true;
export const command = 0x902e;
export const subCommand = 1;
export const uinForm = true;
export interface EmojiItem {
emojiId: string;
md5: string;
}
export interface Params {
emojis: EmojiItem[];
}
export interface Detail {
emojiId: string;
desc: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): CustomFaceMoveBody => ({
field1: 1,
osVersion: CLIENT_VERSION,
opType: 2,
emojis: p.emojis.map((emoji) => ({
emojiId: emoji.emojiId,
md5: emoji.md5,
})),
});
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): Detail[] => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`fetch custom face detail error: ${body.errMsg || body.retCode}`);
export interface EmojiItem {
emojiId: string;
md5: string;
}
const seen = new Set<string>();
return (body.entries ?? []).map((entry, index) => {
const emojiId = entry.emoji?.emojiId;
if (!emojiId) {
throw new Error(`fetch custom face detail response entry ${index} has no emoji id`);
}
if (seen.has(emojiId)) {
throw new Error(`fetch custom face detail response has duplicate emoji id: ${emojiId}`);
}
seen.add(emojiId);
return {
emojiId,
// Current builds use tag 3. Older builds use tag 2 when tag 3 is empty.
desc: entry.desc || entry.legacyDesc || '',
};
export interface Params {
emojis: EmojiItem[];
}
export interface Detail {
emojiId: string;
desc: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): CustomFaceMoveBody => ({
field1: 1,
osVersion: CLIENT_VERSION,
opType: 2,
emojis: p.emojis.map((emoji) => ({
emojiId: emoji.emojiId,
md5: emoji.md5,
})),
});
};
export const encode = (env: OidbBase<CustomFaceMoveBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceMoveBody>>(env);
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): Detail[] => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`fetch custom face detail error: ${body.errMsg || body.retCode}`);
}
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
const seen = new Set<string>();
return (body.entries ?? []).map((entry, index) => {
const emojiId = entry.emoji?.emojiId;
export const invoke = (deps: Deps, params: Params): Promise<Detail[]> =>
invokeOidb(deps, FetchCustomFaceDetail, params);
if (!emojiId) {
throw new Error(`fetch custom face detail response entry ${index} has no emoji id`);
}
if (seen.has(emojiId)) {
throw new Error(
`fetch custom face detail response has duplicate emoji id: ${emojiId}`,
);
}
seen.add(emojiId);
return {
emojiId,
// Current builds use tag 3. Older builds use tag 2 when tag 3 is empty.
desc: entry.desc || entry.legacyDesc || '',
};
});
};
export const encode = (env: OidbBase<CustomFaceMoveBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceMoveBody>>(env);
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<Detail[]> =>
invokeOidb(deps, FetchCustomFaceDetail, params);
}
@@ -9,36 +9,39 @@ import type { OidbSender } from '../../oidb-service';
import { FACEROAM_SERVICE, makeInner } from './shared';
export namespace FetchCustomFaceList {
export interface Params {
/** 当前账号 UIN,写入 field2。 */
uin: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FaceroamOpReq => ({
inner: makeInner(true),
uin: BigInt(p.uin),
field3: 1,
field6: 1,
});
export const encode = (req: FaceroamOpReq): Uint8Array =>
protobuf_encode<FaceroamOpReq>(req);
export const decode = (bytes: Uint8Array): FaceroamOpResp =>
protobuf_decode<FaceroamOpResp>(bytes);
export async function invoke(deps: Deps, params: Params): Promise<string[]> {
const body = encode(serialize(deps, params));
const result = await deps.sendRawPacket(FACEROAM_SERVICE, body);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
export interface Params {
/** 当前账号 UIN,写入 field2。 */
uin: string;
}
const resp = decode(result.responseData);
if (!resp || (resp.retCode ?? 0) !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FaceroamOpReq => ({
inner: makeInner(true),
uin: BigInt(p.uin),
field3: 1,
field6: 1,
});
export const encode = (req: FaceroamOpReq): Uint8Array => protobuf_encode<FaceroamOpReq>(req);
export const decode = (bytes: Uint8Array): FaceroamOpResp =>
protobuf_decode<FaceroamOpResp>(bytes);
export async function invoke(deps: Deps, params: Params): Promise<string[]> {
const body = encode(serialize(deps, params));
const result = await deps.sendRawPacket(FACEROAM_SERVICE, body);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = decode(result.responseData);
if (!resp || (resp.retCode ?? 0) !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
return resp.item?.faceIds || [];
}
return resp.item?.faceIds || [];
}
}
@@ -14,51 +14,51 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
CustomFaceModifyBody,
CustomFaceModifyResp,
CustomFaceModifyBody,
CustomFaceModifyResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { CLIENT_VERSION } from './shared';
export namespace ModifyCustomFace {
export const command = 0x902e;
export const subCommand = 1;
export const command = 0x902e;
export const subCommand = 1;
export interface Params {
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
/** 32 位大写 hex MD5,emoji_id 中段。 */
md5: string;
/** 新备注(可为空字符串清空备注)。 */
desc: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): CustomFaceModifyBody => ({
field1: 1,
osVersion: CLIENT_VERSION,
opType: 3,
entry: {
emoji: { emojiId: p.emojiId, md5: p.md5 },
desc: p.desc,
},
field12: 1,
});
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): void => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`modify custom face error: ${body.errMsg || body.retCode}`);
export interface Params {
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
/** 32 位大写 hex MD5,emoji_id 中段。 */
md5: string;
/** 新备注(可为空字符串清空备注)。 */
desc: string;
}
};
export const encode = (env: OidbBase<CustomFaceModifyBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceModifyBody>>(env);
export type Deps = OidbSender;
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
export const serialize = (_ctx: Deps, p: Params): CustomFaceModifyBody => ({
field1: 1,
osVersion: CLIENT_VERSION,
opType: 3,
entry: {
emoji: { emojiId: p.emojiId, md5: p.md5 },
desc: p.desc,
},
field12: 1,
});
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ModifyCustomFace, params);
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): void => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`modify custom face error: ${body.errMsg || body.retCode}`);
}
};
export const encode = (env: OidbBase<CustomFaceModifyBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceModifyBody>>(env);
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ModifyCustomFace, params);
}
@@ -12,52 +12,52 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
CustomFaceModifyResp,
CustomFaceMoveBody,
CustomFaceModifyResp,
CustomFaceMoveBody,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { CLIENT_VERSION } from './shared';
export namespace MoveCustomFace {
export const command = 0x902e;
export const subCommand = 1;
/** envelope reserved=1(UIN-form),抓包见信封 f12=1。不发则服务端不改顺序。 */
export const uinForm = true;
export const command = 0x902e;
export const subCommand = 1;
/** envelope reserved=1(UIN-form),抓包见信封 f12=1。不发则服务端不改顺序。 */
export const uinForm = true;
export interface EmojiItem {
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
/** 32 位大写 hex MD5,emoji_id 中段。 */
md5: string;
}
export interface Params {
/** 完整且有序的 emoji 列表,整表上传。 */
emojis: EmojiItem[];
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): CustomFaceMoveBody => ({
field1: 1,
osVersion: CLIENT_VERSION,
opType: 2,
emojis: p.emojis.map((e) => ({ emojiId: e.emojiId, md5: e.md5 })),
});
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): void => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`move custom face error: ${body.errMsg || body.retCode}`);
export interface EmojiItem {
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
/** 32 位大写 hex MD5,emoji_id 中段。 */
md5: string;
}
};
export const encode = (env: OidbBase<CustomFaceMoveBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceMoveBody>>(env);
export interface Params {
/** 完整且有序的 emoji 列表,整表上传。 */
emojis: EmojiItem[];
}
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
export type Deps = OidbSender;
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MoveCustomFace, params);
export const serialize = (_ctx: Deps, p: Params): CustomFaceMoveBody => ({
field1: 1,
osVersion: CLIENT_VERSION,
opType: 2,
emojis: p.emojis.map((e) => ({ emojiId: e.emojiId, md5: e.md5 })),
});
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): void => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`move custom face error: ${body.errMsg || body.retCode}`);
}
};
export const encode = (env: OidbBase<CustomFaceMoveBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceMoveBody>>(env);
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MoveCustomFace, params);
}
@@ -11,8 +11,8 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
CustomFaceModifyResp,
CustomFaceOrderBody,
CustomFaceModifyResp,
CustomFaceOrderBody,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import { invokeOidb, type OidbSender } from '../../oidb-service';
@@ -22,38 +22,38 @@ import { CLIENT_VERSION } from './shared';
const BUILD_VERSION_SHORT = '9.9.26';
export namespace OrderCustomFace {
export const command = 0x902f;
export const subCommand = 1;
/** envelope reserved=1(UIN-form),抓包见信封 f12=1。 */
export const uinForm = true;
export const command = 0x902f;
export const subCommand = 1;
/** envelope reserved=1(UIN-form),抓包见信封 f12=1。 */
export const uinForm = true;
export interface Params {
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
/** 目标位置(从 1 开始,1=最前)。 */
position: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): CustomFaceOrderBody => ({
env: { field1: 1024, osVersion: CLIENT_VERSION, buildVersion: BUILD_VERSION_SHORT },
emojiId: p.emojiId,
position: p.position,
});
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): void => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`order custom face error: ${body.errMsg || body.retCode}`);
export interface Params {
/** 形如 `<UIN>_0_0_0_<MD5>_0_0`,来自 fetch 响应。 */
emojiId: string;
/** 目标位置(从 1 开始,1=最前)。 */
position: number;
}
};
export const encode = (env: OidbBase<CustomFaceOrderBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceOrderBody>>(env);
export type Deps = OidbSender;
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
export const serialize = (_ctx: Deps, p: Params): CustomFaceOrderBody => ({
env: { field1: 1024, osVersion: CLIENT_VERSION, buildVersion: BUILD_VERSION_SHORT },
emojiId: p.emojiId,
position: p.position,
});
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, OrderCustomFace, params);
export const deserialize = (_ctx: Deps, body: CustomFaceModifyResp): void => {
if (body.retCode && body.retCode !== 0) {
throw new Error(`order custom face error: ${body.errMsg || body.retCode}`);
}
};
export const encode = (env: OidbBase<CustomFaceOrderBody>): Uint8Array =>
protobuf_encode<OidbBase<CustomFaceOrderBody>>(env);
export const decode = (bytes: Uint8Array): OidbBase<CustomFaceModifyResp> =>
protobuf_decode<OidbBase<CustomFaceModifyResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, OrderCustomFace, params);
}
@@ -23,7 +23,11 @@ const LIST_QQ_VERSION = '9.9.28-46928';
* 这不是随手写的,是 wire dump 里两者 inner 长度差 14 字节的直接来源。
*/
export function makeInner(withQqVersion: boolean): FaceroamOpReqInner {
const inner: FaceroamOpReqInner = { field1: 1, osVersion: CLIENT_VERSION };
if (withQqVersion) inner.qqVersion = LIST_QQ_VERSION;
return inner;
const inner: FaceroamOpReqInner = { field1: 1, osVersion: CLIENT_VERSION };
if (withQqVersion) {
inner.qqVersion = LIST_QQ_VERSION;
}
return inner;
}
@@ -5,46 +5,47 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbAiVoiceListReq, OidbAiVoiceListResp,
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;
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
category: string;
voices: AiVoiceItem[];
}
export namespace FetchAiVoiceList {
export const command = 0x929D;
export const subCommand = 0;
export const command = 0x929d;
export const subCommand = 0;
export interface Params {
groupId: number;
chatType: number;
}
export interface Params {
groupId: number;
chatType: number;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbAiVoiceListReq => ({
groupUin: p.groupId,
chatType: p.chatType,
});
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 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 encode = (env: OidbBase<OidbAiVoiceListReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbAiVoiceListReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbAiVoiceListResp> =>
protobuf_decode<OidbBase<OidbAiVoiceListResp>>(bytes);
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);
export const invoke = (deps: Deps, params: Params): Promise<AiVoiceCategory[]> =>
invokeOidb(deps, FetchAiVoiceList, params);
}
@@ -11,9 +11,7 @@
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 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)
@@ -21,48 +19,48 @@ import { invokeOidb, type OidbSender } from '../../oidb-service';
* 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;
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 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 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 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 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 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 encode = (env: OidbBase<OidbAiVoiceReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbAiVoiceReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbAiVoiceResp> =>
protobuf_decode<OidbBase<OidbAiVoiceResp>>(bytes);
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);
export const invoke = (deps: Deps, params: Params): Promise<AiVoiceMediaIndex | null> =>
invokeOidb(deps, FetchAiVoice, params);
}
@@ -8,25 +8,25 @@
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbOnlineBanner,
OidbQueryGroupTopBannersReq,
OidbQueryGroupTopBannersResp,
OidbOnlineBanner,
OidbQueryGroupTopBannersReq,
OidbQueryGroupTopBannersResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupTodoListItem {
sourceId: string;
sequence: number;
random: number;
text: string;
createdAt: number;
updatedAt: number;
sourceId: string;
sequence: number;
random: number;
text: string;
createdAt: number;
updatedAt: number;
}
interface MessageIdentity {
sequence: number;
random: number;
sequence: number;
random: number;
}
const TODO_BANNER_FLAG = 1;
@@ -34,116 +34,142 @@ const SOURCE_ID_PATTERN = /^([1-9]\d*)_(-?\d+)$/;
const utf8 = new TextDecoder('utf-8', { fatal: true });
function decodeUtf8(bytes: Uint8Array, description: string): string {
try {
return utf8.decode(bytes);
} catch {
throw new Error(`invalid group todo ${description}`);
}
try {
return utf8.decode(bytes);
} catch {
throw new Error(`invalid group todo ${description}`);
}
}
function parseSafeInteger(value: unknown, description: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
throw new Error(`invalid group todo ${description}`);
}
return value;
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
throw new Error(`invalid group todo ${description}`);
}
return value;
}
function parseSourceIdentity(bytes: Uint8Array | undefined): MessageIdentity & { sourceId: string } {
if (!bytes || bytes.length === 0) {
throw new Error('invalid group todo message identity');
}
const sourceId = decodeUtf8(bytes, 'message identity');
const match = SOURCE_ID_PATTERN.exec(sourceId);
if (!match) throw new Error('invalid group todo message identity');
function parseSourceIdentity(
bytes: Uint8Array | undefined,
): MessageIdentity & { sourceId: string } {
if (!bytes || bytes.length === 0) {
throw new Error('invalid group todo message identity');
}
const sequence = Number(match[1]);
const random = Number(match[2]);
if (!Number.isSafeInteger(sequence) || sequence <= 0 || !Number.isSafeInteger(random)) {
throw new Error('invalid group todo message identity');
}
return { sourceId, sequence, random };
const sourceId = decodeUtf8(bytes, 'message identity');
const match = SOURCE_ID_PATTERN.exec(sourceId);
if (!match) {
throw new Error('invalid group todo message identity');
}
const sequence = Number(match[1]);
const random = Number(match[2]);
if (!Number.isSafeInteger(sequence) || sequence <= 0 || !Number.isSafeInteger(random)) {
throw new Error('invalid group todo message identity');
}
return { sourceId, sequence, random };
}
function parseJumpIdentity(bytes: Uint8Array | undefined): MessageIdentity | null {
if (!bytes || bytes.length === 0) return null;
if (!bytes || bytes.length === 0) {
return null;
}
let decoded: unknown;
try {
decoded = JSON.parse(decodeUtf8(bytes, 'jump identity'));
} catch (error) {
if (error instanceof Error && error.message.startsWith('invalid group todo')) throw error;
throw new Error('invalid group todo jump identity');
}
if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {
throw new Error('invalid group todo jump identity');
}
let decoded: unknown;
const record = decoded as Record<string, unknown>;
const sequence = parseSafeInteger(record.seq, 'jump identity');
const random = parseSafeInteger(record.random, 'jump identity');
if (sequence <= 0) throw new Error('invalid group todo jump identity');
return { sequence, random };
try {
decoded = JSON.parse(decodeUtf8(bytes, 'jump identity'));
} catch (error) {
if (error instanceof Error && error.message.startsWith('invalid group todo')) {
throw error;
}
throw new Error('invalid group todo jump identity');
}
if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {
throw new Error('invalid group todo jump identity');
}
const record = decoded as Record<string, unknown>;
const sequence = parseSafeInteger(record.seq, 'jump identity');
const random = parseSafeInteger(record.random, 'jump identity');
if (sequence <= 0) {
throw new Error('invalid group todo jump identity');
}
return { sequence, random };
}
function parseTimestamp(value: bigint | number | null | undefined, description: string): number {
if (value === undefined || value === null) return 0;
const timestamp = typeof value === 'bigint' ? Number(value) : value;
if (!Number.isSafeInteger(timestamp) || timestamp < 0) {
throw new Error(`invalid group todo ${description}`);
}
return timestamp;
if (value === undefined || value === null) {
return 0;
}
const timestamp = typeof value === 'bigint' ? Number(value) : value;
if (!Number.isSafeInteger(timestamp) || timestamp < 0) {
throw new Error(`invalid group todo ${description}`);
}
return timestamp;
}
function parseBanner(banner: OidbOnlineBanner): GroupTodoListItem {
const source = parseSourceIdentity(banner.msgId);
const jump = parseJumpIdentity(banner.commonBanner?.jumpInfo?.jumpParam);
if (jump && (jump.sequence !== source.sequence || jump.random !== source.random)) {
throw new Error('group todo message identity mismatch');
}
const source = parseSourceIdentity(banner.msgId);
const jump = parseJumpIdentity(banner.commonBanner?.jumpInfo?.jumpParam);
return {
sourceId: source.sourceId,
sequence: source.sequence,
random: source.random,
text: banner.commonBanner?.ui?.text ?? banner.todoBanner?.text ?? '',
createdAt: parseTimestamp(banner.commonBanner?.createTime, 'create time'),
updatedAt: parseTimestamp(banner.commonBanner?.updateTime, 'update time'),
};
if (jump && (jump.sequence !== source.sequence || jump.random !== source.random)) {
throw new Error('group todo message identity mismatch');
}
return {
sourceId: source.sourceId,
sequence: source.sequence,
random: source.random,
text: banner.commonBanner?.ui?.text ?? banner.todoBanner?.text ?? '',
createdAt: parseTimestamp(banner.commonBanner?.createTime, 'create time'),
updatedAt: parseTimestamp(banner.commonBanner?.updateTime, 'update time'),
};
}
export namespace GetGroupTodoList {
export const command = 0x9474;
export const subCommand = 0;
export const command = 0x9474;
export const subCommand = 0;
export interface Params {
groupId: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbQueryGroupTopBannersReq => {
if (!Number.isSafeInteger(p.groupId) || p.groupId <= 0) {
throw new Error('invalid group id');
export interface Params {
groupId: number;
}
return {
groupId: BigInt(p.groupId),
bannerFlag: TODO_BANNER_FLAG,
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbQueryGroupTopBannersReq => {
if (!Number.isSafeInteger(p.groupId) || p.groupId <= 0) {
throw new Error('invalid group id');
}
return {
groupId: BigInt(p.groupId),
bannerFlag: TODO_BANNER_FLAG,
};
};
};
export const deserialize = (
_ctx: Deps,
body: OidbQueryGroupTopBannersResp,
): GroupTodoListItem[] => (body.banners ?? [])
.filter((banner) => banner.isDisappear !== true)
.map(parseBanner);
export const deserialize = (
_ctx: Deps,
body: OidbQueryGroupTopBannersResp,
): GroupTodoListItem[] =>
(body.banners ?? []).filter((banner) => banner.isDisappear !== true).map(parseBanner);
export const encode = (env: OidbBase<OidbQueryGroupTopBannersReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbQueryGroupTopBannersReq>>(env);
export const encode = (env: OidbBase<OidbQueryGroupTopBannersReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbQueryGroupTopBannersReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbQueryGroupTopBannersResp> =>
protobuf_decode<OidbBase<OidbQueryGroupTopBannersResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbQueryGroupTopBannersResp> =>
protobuf_decode<OidbBase<OidbQueryGroupTopBannersResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupTodoListItem[]> =>
invokeOidb(deps, GetGroupTodoList, params);
export const invoke = (deps: Deps, params: Params): Promise<GroupTodoListItem[]> =>
invokeOidb(deps, GetGroupTodoList, params);
}
@@ -7,56 +7,68 @@
// invaild`. Same flag fetchUserProfile uses.
//
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbStrangerStatusReq, OidbStrangerStatusResp } from '@snowluma/proto-defs/oidb-actions/base';
import type {
OidbStrangerStatusReq,
OidbStrangerStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface StrangerStatus {
status: number;
ext_status: number;
status: number;
ext_status: number;
}
export function unpackStatusWord(raw: bigint | number): { status: number; ext_status: number } {
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
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 };
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
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 };
}
const STATUS_PROPERTY_KEY = 27372;
export namespace GetStrangerStatus {
export const command = 0xFE1;
export const subCommand = 2;
export const uinForm = true;
export const command = 0xfe1;
export const subCommand = 2;
export const uinForm = true;
export interface Params {
uin: number;
}
export interface Params {
uin: number;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbStrangerStatusReq => ({
uin: p.uin,
key: [{ key: STATUS_PROPERTY_KEY }],
});
export const serialize = (_ctx: Deps, p: Params): OidbStrangerStatusReq => ({
uin: p.uin,
key: [{ key: STATUS_PROPERTY_KEY }],
});
export const deserialize = (_ctx: Deps, body: OidbStrangerStatusResp): StrangerStatus | null => {
const raw = body.data?.properties?.entries
?.find((entry) => entry.key === STATUS_PROPERTY_KEY)
?.value;
if (raw === undefined || raw === null) return null;
return unpackStatusWord(raw);
};
export const deserialize = (
_ctx: Deps,
body: OidbStrangerStatusResp,
): StrangerStatus | null => {
const raw = body.data?.properties?.entries?.find(
(entry) => entry.key === STATUS_PROPERTY_KEY,
)?.value;
export const encode = (env: OidbBase<OidbStrangerStatusReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbStrangerStatusReq>>(env);
if (raw === undefined || raw === null) {
return null;
}
export const decode = (bytes: Uint8Array): OidbBase<OidbStrangerStatusResp> =>
protobuf_decode<OidbBase<OidbStrangerStatusResp>>(bytes);
return unpackStatusWord(raw);
};
export const invoke = (deps: Deps, params: Params): Promise<StrangerStatus | null> =>
invokeOidb(deps, GetStrangerStatus, params);
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);
}
@@ -12,37 +12,37 @@ 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,
set: 1,
complete: 2,
cancel: 3,
};
export namespace GroupTodo {
export const command = 0xF90;
export const command = 0xf90;
export interface Params {
groupId: number;
msgSeq: bigint;
action: GroupTodoAction;
}
export interface Params {
groupId: number;
msgSeq: bigint;
action: GroupTodoAction;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => ACTION_TO_SUBCMD[p.action];
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 serialize = (_ctx: Deps, p: Params): OidbGroupTodo => ({
groupUin: p.groupId,
msgSeq: p.msgSeq,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbGroupTodo>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupTodo>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, GroupTodo, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, GroupTodo, params);
}
@@ -6,61 +6,62 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashApplyFilesetReq,
FlashApplyFilesetResp,
FlashApplyFilesetReq,
FlashApplyFilesetResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface FlashUploaderInfo {
uin: string;
nickname: string;
uid: string;
uin: string;
nickname: string;
uid: string;
}
export namespace ApplyFileset {
export const command = 0x93cf;
export const subCommand = 1;
export const command = 0x93cf;
export const subCommand = 1;
export interface Params {
fileName: string;
origName: string;
fileSize: number;
/** 文件类型码:rar=2, png/mp4=7。 */
typeCode: number;
uploader: FlashUploaderInfo;
}
export interface Params {
fileName: string;
origName: string;
fileSize: number;
/** 文件类型码:rar=2, png/mp4=7。 */
typeCode: number;
uploader: FlashUploaderInfo;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashApplyFilesetReq => ({
field1: 1,
fileInfo: {
fileName: p.fileName,
origName: p.origName,
fileType: 1,
fileSize: BigInt(p.fileSize),
uploader: {
uin: p.uploader.uin,
nickname: p.uploader.nickname,
uid: p.uploader.uid,
field4: {},
},
field16: 1,
field20: 0,
field21: 0,
},
typeCode: p.typeCode,
field12: 1,
});
export const serialize = (_ctx: Deps, p: Params): FlashApplyFilesetReq => ({
field1: 1,
fileInfo: {
fileName: p.fileName,
origName: p.origName,
fileType: 1,
fileSize: BigInt(p.fileSize),
uploader: {
uin: p.uploader.uin,
nickname: p.uploader.nickname,
uid: p.uploader.uid,
field4: {},
},
field16: 1,
field20: 0,
field21: 0,
},
typeCode: p.typeCode,
field12: 1,
});
export const deserialize = (_ctx: Deps, body: FlashApplyFilesetResp): FlashApplyFilesetResp => body;
export const deserialize = (_ctx: Deps, body: FlashApplyFilesetResp): FlashApplyFilesetResp =>
body;
export const encode = (env: OidbBase<FlashApplyFilesetReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashApplyFilesetReq>>(env);
export const encode = (env: OidbBase<FlashApplyFilesetReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashApplyFilesetReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashApplyFilesetResp> =>
protobuf_decode<OidbBase<FlashApplyFilesetResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashApplyFilesetResp> =>
protobuf_decode<OidbBase<FlashApplyFilesetResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<FlashApplyFilesetResp> =>
invokeOidb(deps, ApplyFileset, params);
export const invoke = (deps: Deps, params: Params): Promise<FlashApplyFilesetResp> =>
invokeOidb(deps, ApplyFileset, params);
}
@@ -4,95 +4,105 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashApplyUploadReq,
FlashApplyUploadResp,
FlashApplyUploadReq,
FlashApplyUploadResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
let seqCounter = 100;
export namespace ApplyUpload {
export const command = 0x12a9;
export const subCommand = 103;
export const uinForm = true;
export const command = 0x12a9;
export const subCommand = 103;
export const uinForm = true;
export interface Params {
filesetUuid: string;
fileUuid: string;
fileId: string; // 来自 sub=100 响应
fileName: string;
fileSize: number;
md5: string; // 32 hex
sha1: string; // 40 hex
/** fileset 内序号(1,2,3...),与 0x93d0 commit f6 一致。 */
fileIndex: number;
/** 格式码:与 commit f7 一致(mp4=2, rar/zip=4)。主文件 filesetWrap.f7 用此值;
* 缩略图固定 png=26/jpg=2。 */
formatCode: number;
/** 缩略图类型:undefined=主文件, 'png'=png 缩略图, 'jpg'=jpg 缩略图。 */
thumbType?: 'png' | 'jpg';
width?: number;
height?: number;
}
export type Deps = OidbSender;
export interface Params {
filesetUuid: string;
fileUuid: string;
fileId: string; // 来自 sub=100 响应
fileName: string;
fileSize: number;
md5: string; // 32 hex
sha1: string; // 40 hex
/** fileset 内序号(1,2,3...),与 0x93d0 commit f6 一致。 */
fileIndex: number;
/** 格式码:与 commit f7 一致(mp4=2, rar/zip=4)。主文件 filesetWrap.f7 用此值;
* 缩略图固定 png=26/jpg=2。 */
formatCode: number;
/** 缩略图类型:undefined=主文件, 'png'=png 缩略图, 'jpg'=jpg 缩略图。 */
thumbType?: 'png' | 'jpg';
width?: number;
height?: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashApplyUploadReq => {
// 缩略图与主文件字段差异:config.f103、FileInfo.f5.f1/f6/f7/f9、
// filesetWrap.f4/f5/f6/f7/f9。filesetWrap.f4 统一用 fileIndex。
const isThumb = p.thumbType !== undefined;
const isJpg = p.thumbType === 'jpg';
return {
head: {
sub: { seq: seqCounter++, sub: 103 },
config: { field101: 2, field102: 4, field103: isThumb ? (isJpg ? 24 : 23) : 22, field200: 5 },
field3: { field1: 1 },
},
payload: {
wrapper: {
fileInfo: {
fileSize: p.fileSize,
md5: p.md5,
sha1: p.sha1,
fileName: p.fileName,
field5: { field1: isJpg ? 1 : 0, field2: 0, field3: 0, field4: 0 },
field6: p.width ?? 0,
field7: p.height ?? 0,
field8: 0,
field9: isJpg ? 0 : 1,
},
fileId: p.fileId,
field3: 1,
field4: Math.floor(Date.now() / 1000),
field5: 1209600, // TTL 14 天
field6: 0,
},
flag2: { field1: 2 },
field3: { field1: 0, field2: 0, field3: 0, field4: {} },
filesetWrap: {
filesetUuid: p.filesetUuid,
uploadKey: p.filesetUuid,
fileUuid: p.fileUuid,
field4: p.fileIndex,
field5: isThumb && !isJpg ? 1 : 0, // png=1, jpg/mp4=0
field6: isThumb ? (isJpg ? 1 : 0) : 0, // png缩略图=0, jpg缩略图=1, 主文件=0
field7: isThumb ? (isJpg ? 2 : 26) : p.formatCode, // 主文件=formatCode(mp4=2), png缩略图=26, jpg缩略图=2
field8: {},
field9: 1, field10: 0, field11: 0, field12: 0, field13: 0, field14: 0,
},
},
export const serialize = (_ctx: Deps, p: Params): FlashApplyUploadReq => {
// 缩略图与主文件字段差异:config.f103、FileInfo.f5.f1/f6/f7/f9、
// filesetWrap.f4/f5/f6/f7/f9。filesetWrap.f4 统一用 fileIndex。
const isThumb = p.thumbType !== undefined;
const isJpg = p.thumbType === 'jpg';
return {
head: {
sub: { seq: seqCounter++, sub: 103 },
config: {
field101: 2,
field102: 4,
field103: isThumb ? (isJpg ? 24 : 23) : 22,
field200: 5,
},
field3: { field1: 1 },
},
payload: {
wrapper: {
fileInfo: {
fileSize: p.fileSize,
md5: p.md5,
sha1: p.sha1,
fileName: p.fileName,
field5: { field1: isJpg ? 1 : 0, field2: 0, field3: 0, field4: 0 },
field6: p.width ?? 0,
field7: p.height ?? 0,
field8: 0,
field9: isJpg ? 0 : 1,
},
fileId: p.fileId,
field3: 1,
field4: Math.floor(Date.now() / 1000),
field5: 1209600, // TTL 14 天
field6: 0,
},
flag2: { field1: 2 },
field3: { field1: 0, field2: 0, field3: 0, field4: {} },
filesetWrap: {
filesetUuid: p.filesetUuid,
uploadKey: p.filesetUuid,
fileUuid: p.fileUuid,
field4: p.fileIndex,
field5: isThumb && !isJpg ? 1 : 0, // png=1, jpg/mp4=0
field6: isThumb ? (isJpg ? 1 : 0) : 0, // png缩略图=0, jpg缩略图=1, 主文件=0
field7: isThumb ? (isJpg ? 2 : 26) : p.formatCode, // 主文件=formatCode(mp4=2), png缩略图=26, jpg缩略图=2
field8: {},
field9: 1,
field10: 0,
field11: 0,
field12: 0,
field13: 0,
field14: 0,
},
},
};
};
};
export const deserialize = (_ctx: Deps, _body: FlashApplyUploadResp): void => {
// sub=103 resp f12={f1:filesetWrap}(注册确认,无 rkey)。rkey 来自 sub=100。
};
export const deserialize = (_ctx: Deps, _body: FlashApplyUploadResp): void => {
// sub=103 resp f12={f1:filesetWrap}(注册确认,无 rkey)。rkey 来自 sub=100。
};
export const encode = (env: OidbBase<FlashApplyUploadReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashApplyUploadReq>>(env);
export const encode = (env: OidbBase<FlashApplyUploadReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashApplyUploadReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashApplyUploadResp> =>
protobuf_decode<OidbBase<FlashApplyUploadResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashApplyUploadResp> =>
protobuf_decode<OidbBase<FlashApplyUploadResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ApplyUpload, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ApplyUpload, params);
}
@@ -6,65 +6,65 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashCommitFileReq,
FlashCommitFileResp,
FlashCommitFileReq,
FlashCommitFileResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace CommitFile {
export const command = 0x93d0;
export const subCommand = 1;
export const command = 0x93d0;
export const subCommand = 1;
/** 单个文件的 commit 元数据。fileIndex 为 fileset 内序号(从 1 递增)。 */
export interface CommitEntry {
fileUuid: string;
fileName: string;
origName: string;
fileSize: number;
/** 格式码:rar=4, mp4=2。 */
formatCode: number;
/** fileset 内序号(1,2,3...),与 0x12a9 filesetWrap.f4 一致。 */
fileIndex: number;
}
/** 单个文件的 commit 元数据。fileIndex 为 fileset 内序号(从 1 递增)。 */
export interface CommitEntry {
fileUuid: string;
fileName: string;
origName: string;
fileSize: number;
/** 格式码:rar=4, mp4=2。 */
formatCode: number;
/** fileset 内序号(1,2,3...),与 0x12a9 filesetWrap.f4 一致。 */
fileIndex: number;
}
export interface Params {
filesetUuid: string;
/** fileset 内全部文件条目;一次 0x93d0 请求同时上报。 */
entries: CommitEntry[];
}
export interface Params {
filesetUuid: string;
/** fileset 内全部文件条目;一次 0x93d0 请求同时上报。 */
entries: CommitEntry[];
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashCommitFileReq => ({
field1: 1,
filesetUuid: p.filesetUuid,
uploadKey: p.filesetUuid,
commitInfo: p.entries.map((e) => ({
filesetUuid: p.filesetUuid,
fileUuid: e.fileUuid,
field3: 0,
field4: {},
field5: 1,
field6: e.fileIndex,
formatCode: e.formatCode,
fileName: e.fileName,
origName: e.origName,
field10: 0,
fileSize: BigInt(e.fileSize),
field12: 0,
field24: {},
})),
field5: 1,
field6: 1,
});
export const deserialize = (_ctx: Deps, body: FlashCommitFileResp): FlashCommitFileResp => body;
export const serialize = (_ctx: Deps, p: Params): FlashCommitFileReq => ({
field1: 1,
filesetUuid: p.filesetUuid,
uploadKey: p.filesetUuid,
commitInfo: p.entries.map((e) => ({
filesetUuid: p.filesetUuid,
fileUuid: e.fileUuid,
field3: 0,
field4: {},
field5: 1,
field6: e.fileIndex,
formatCode: e.formatCode,
fileName: e.fileName,
origName: e.origName,
field10: 0,
fileSize: BigInt(e.fileSize),
field12: 0,
field24: {},
})),
field5: 1,
field6: 1,
});
export const deserialize = (_ctx: Deps, body: FlashCommitFileResp): FlashCommitFileResp => body;
export const encode = (env: OidbBase<FlashCommitFileReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashCommitFileReq>>(env);
export const encode = (env: OidbBase<FlashCommitFileReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashCommitFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashCommitFileResp> =>
protobuf_decode<OidbBase<FlashCommitFileResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashCommitFileResp> =>
protobuf_decode<OidbBase<FlashCommitFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<FlashCommitFileResp> =>
invokeOidb(deps, CommitFile, params);
export const invoke = (deps: Deps, params: Params): Promise<FlashCommitFileResp> =>
invokeOidb(deps, CommitFile, params);
}
@@ -3,36 +3,36 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashCompleteFilesetReq,
FlashCompleteFilesetResp,
FlashCompleteFilesetReq,
FlashCompleteFilesetResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace CompleteFileset {
export const command = 0x93db;
export const subCommand = 1;
export const command = 0x93db;
export const subCommand = 1;
export interface Params {
filesetUuid: string;
}
export interface Params {
filesetUuid: string;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashCompleteFilesetReq => ({
filesetUuid: p.filesetUuid,
field2: '',
});
export const serialize = (_ctx: Deps, p: Params): FlashCompleteFilesetReq => ({
filesetUuid: p.filesetUuid,
field2: '',
});
export const deserialize = (_ctx: Deps, _body: FlashCompleteFilesetResp): void => {
// 成功靠 envelope errorCode=0。
};
export const deserialize = (_ctx: Deps, _body: FlashCompleteFilesetResp): void => {
// 成功靠 envelope errorCode=0。
};
export const encode = (env: OidbBase<FlashCompleteFilesetReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashCompleteFilesetReq>>(env);
export const encode = (env: OidbBase<FlashCompleteFilesetReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashCompleteFilesetReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashCompleteFilesetResp> =>
protobuf_decode<OidbBase<FlashCompleteFilesetResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashCompleteFilesetResp> =>
protobuf_decode<OidbBase<FlashCompleteFilesetResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, CompleteFileset, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, CompleteFileset, params);
}
@@ -4,37 +4,37 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashDeleteFileReq,
FlashDeleteFileResp,
FlashDeleteFileReq,
FlashDeleteFileResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace DeleteFlashFile {
export const command = 0x9407;
export const subCommand = 1;
export const command = 0x9407;
export const subCommand = 1;
export interface Params {
filesetUuid: string;
}
export interface Params {
filesetUuid: string;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashDeleteFileReq => ({
filesetUuid: p.filesetUuid,
field2: '',
field3: 7,
});
export const serialize = (_ctx: Deps, p: Params): FlashDeleteFileReq => ({
filesetUuid: p.filesetUuid,
field2: '',
field3: 7,
});
export const deserialize = (_ctx: Deps, _body: FlashDeleteFileResp): void => {
// 成功靠 envelope errorCode=0(invokeOidb 已校验),业务体空。
};
export const deserialize = (_ctx: Deps, _body: FlashDeleteFileResp): void => {
// 成功靠 envelope errorCode=0(invokeOidb 已校验),业务体空。
};
export const encode = (env: OidbBase<FlashDeleteFileReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashDeleteFileReq>>(env);
export const encode = (env: OidbBase<FlashDeleteFileReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashDeleteFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashDeleteFileResp> =>
protobuf_decode<OidbBase<FlashDeleteFileResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashDeleteFileResp> =>
protobuf_decode<OidbBase<FlashDeleteFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteFlashFile, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteFlashFile, params);
}
@@ -7,72 +7,72 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashGetDownloadUrlReq,
FlashGetDownloadUrlResp,
FlashGetDownloadUrlReq,
FlashGetDownloadUrlResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetDownloadUrl {
export const command = 0x93d4;
export const subCommand = 1;
export const command = 0x93d4;
export const subCommand = 1;
export interface Params {
filesetUuid: string;
/** 指定下载 fileset 内第几个文件(1-based)。默认 1(主文件)。 */
fileIndex?: number;
}
/** 单个文件的下载元信息;无主文件 fileId 时该条目 null。 */
export type FileMeta = {
fileIndex: number;
fileId: string;
filesetUuid: string;
fileUuid: string;
fileName: string;
fileSize: number;
};
/** fileset 内所有文件元信息(按 fileIndex 升序)。 */
export type Result = FileMeta[];
export interface Params {
filesetUuid: string;
/** 指定下载 fileset 内第几个文件(1-based)。默认 1(主文件)。 */
fileIndex?: number;
}
/** 单个文件的下载元信息;无主文件 fileId 时该条目 null。 */
export type FileMeta = {
fileIndex: number;
fileId: string;
filesetUuid: string;
fileUuid: string;
fileName: string;
fileSize: number;
};
/** fileset 内所有文件元信息(按 fileIndex 升序)。 */
export type Result = FileMeta[];
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashGetDownloadUrlReq => ({
filesetUuid: p.filesetUuid,
inner: {
field1: '',
field2: 1,
field3: 18,
field4: '',
field5: { field1: 0 },
field6: { field1: 0, field2: 0 },
},
field3: 7,
field4: 1,
});
export const deserialize = (_ctx: Deps, body: FlashGetDownloadUrlResp): Result => {
// f1.f3 是 repeated fileInfo,多文件 fileset 时每个文件一条(f6=序号,f14=主文件 fileId)。
// f13 是缩略图(appid=14902),主文件下载 URL 需 0x12a9 sub=200 拿。
const infos = body.entry?.fileInfo ?? [];
return infos.map((info, idx) => {
const fileId = info?.mainFile?.fileId ?? '';
const fileIndex = info?.field6 ?? idx + 1;
return {
fileIndex,
fileId,
filesetUuid: info?.filesetUuid ?? '',
fileUuid: info?.fileUuid ?? '',
fileName: info?.fileName ?? '',
fileSize: Number(info?.fileSize ?? 0),
};
export const serialize = (_ctx: Deps, p: Params): FlashGetDownloadUrlReq => ({
filesetUuid: p.filesetUuid,
inner: {
field1: '',
field2: 1,
field3: 18,
field4: '',
field5: { field1: 0 },
field6: { field1: 0, field2: 0 },
},
field3: 7,
field4: 1,
});
};
export const encode = (env: OidbBase<FlashGetDownloadUrlReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashGetDownloadUrlReq>>(env);
export const deserialize = (_ctx: Deps, body: FlashGetDownloadUrlResp): Result => {
// f1.f3 是 repeated fileInfo,多文件 fileset 时每个文件一条(f6=序号,f14=主文件 fileId)。
// f13 是缩略图(appid=14902),主文件下载 URL 需 0x12a9 sub=200 拿。
const infos = body.entry?.fileInfo ?? [];
return infos.map((info, idx) => {
const fileId = info?.mainFile?.fileId ?? '';
const fileIndex = info?.field6 ?? idx + 1;
return {
fileIndex,
fileId,
filesetUuid: info?.filesetUuid ?? '',
fileUuid: info?.fileUuid ?? '',
fileName: info?.fileName ?? '',
fileSize: Number(info?.fileSize ?? 0),
};
});
};
export const decode = (bytes: Uint8Array): OidbBase<FlashGetDownloadUrlResp> =>
protobuf_decode<OidbBase<FlashGetDownloadUrlResp>>(bytes);
export const encode = (env: OidbBase<FlashGetDownloadUrlReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashGetDownloadUrlReq>>(env);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetDownloadUrl, params);
export const decode = (bytes: Uint8Array): OidbBase<FlashGetDownloadUrlResp> =>
protobuf_decode<OidbBase<FlashGetDownloadUrlResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetDownloadUrl, params);
}
@@ -6,37 +6,36 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashGetDetailReq,
FlashGetDetailResp,
FlashFileEntry,
FlashGetDetailReq,
FlashGetDetailResp,
FlashFileEntry,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetFilesetDetail {
export const command = 0x93d3;
export const subCommand = 1;
export const command = 0x93d3;
export const subCommand = 1;
export interface Params {
filesetUuid: string;
}
export type Result = FlashFileEntry[];
export interface Params {
filesetUuid: string;
}
export type Result = FlashFileEntry[];
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashGetDetailReq => ({
filesetUuid: p.filesetUuid,
field2: 7,
});
export const serialize = (_ctx: Deps, p: Params): FlashGetDetailReq => ({
filesetUuid: p.filesetUuid,
field2: 7,
});
export const deserialize = (_ctx: Deps, body: FlashGetDetailResp): Result =>
body.entries ?? [];
export const deserialize = (_ctx: Deps, body: FlashGetDetailResp): Result => body.entries ?? [];
export const encode = (env: OidbBase<FlashGetDetailReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashGetDetailReq>>(env);
export const encode = (env: OidbBase<FlashGetDetailReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashGetDetailReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashGetDetailResp> =>
protobuf_decode<OidbBase<FlashGetDetailResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashGetDetailResp> =>
protobuf_decode<OidbBase<FlashGetDetailResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetFilesetDetail, params);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetFilesetDetail, params);
}
@@ -7,76 +7,100 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashGetDownloadReq,
FlashGetDownloadResp,
FlashGetDownloadReq,
FlashGetDownloadResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
let seqCounter = 300;
export namespace GetFlashDownload {
export const command = 0x12a9;
export const subCommand = 200;
export const uinForm = true;
export const command = 0x12a9;
export const subCommand = 200;
export const uinForm = true;
export interface Params {
filesetUuid: string;
fileUuid: string; // 主文件 fileUuid(0x93d4 f1.f3.f2)
fileId: string; // 主文件 fileId(0x93d4 f14.f1)
fileName: string;
}
export type Result = string | null; // 主文件下载 URL
export interface Params {
filesetUuid: string;
fileUuid: string; // 主文件 fileUuid(0x93d4 f1.f3.f2)
fileId: string; // 主文件 fileId(0x93d4 f14.f1)
fileName: string;
}
export type Result = string | null; // 主文件下载 URL
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashGetDownloadReq => ({
head: {
sub: { seq: seqCounter++, sub: 200 },
config: { field101: 2, field102: 4, field103: 22, field200: 5 }, // mp4 f103=22
field3: { field1: 1 },
},
payload: {
wrapper: {
fileInfo: {
field1: 0,
field4: p.fileName,
field5: { field1: 0, field2: 0, field3: 0, field4: 0 },
field6: 0, field7: 0, field8: 0, field9: 0,
export const serialize = (_ctx: Deps, p: Params): FlashGetDownloadReq => ({
head: {
sub: { seq: seqCounter++, sub: 200 },
config: { field101: 2, field102: 4, field103: 22, field200: 5 }, // mp4 f103=22
field3: { field1: 1 },
},
fileId: p.fileId,
field3: 0, field4: 0, field5: 0, field6: 0,
},
field2: {
// 固定下载参数(QQ 客户端实测值,未观察到随文件变化)。
field2: { field1: 4294967294, field3: 4294967295, field5: 111, field6: { field1: 3403722988 } },
field4: { field1: 0 },
// field3 必须是主文件类型码 26;用 2 会被服务端拒(170019002 Service Failure)。
filesetWrap: { filesetUuid: p.filesetUuid, fileUuid: p.fileUuid, field3: 26, field4: p.fileUuid },
},
field3: 0,
},
});
payload: {
wrapper: {
fileInfo: {
field1: 0,
field4: p.fileName,
field5: { field1: 0, field2: 0, field3: 0, field4: 0 },
field6: 0,
field7: 0,
field8: 0,
field9: 0,
},
fileId: p.fileId,
field3: 0,
field4: 0,
field5: 0,
field6: 0,
},
field2: {
// 固定下载参数(QQ 客户端实测值,未观察到随文件变化)。
field2: {
field1: 4294967294,
field3: 4294967295,
field5: 111,
field6: { field1: 3403722988 },
},
field4: { field1: 0 },
// field3 必须是主文件类型码 26;用 2 会被服务端拒(170019002 Service Failure)。
filesetWrap: {
filesetUuid: p.filesetUuid,
fileUuid: p.fileUuid,
field3: 26,
field4: p.fileUuid,
},
},
field3: 0,
},
});
export const deserialize = (_ctx: Deps, body: FlashGetDownloadResp): Result => {
// 响应 f3 含 rkey + host(multimedia.qfile.qq.com)+ path(/download?appid=14901...&fldc=...)。
// rkey 在 f3 单独字段(path 不含 rkey),拼完整 URL 需拼接 &rkey=。
const raw = body.body;
if (!raw || raw.length === 0) return null;
const text = Buffer.from(raw).toString('latin1');
const host = /multimedia\.qfile\.qq\.com/.exec(text);
const path = /\/download\?appid=14901[\x20-\x7e]*/.exec(text);
const rkey = /rkey=([A-Za-z0-9_-]+)/.exec(text);
if (!host || !path) return null;
const base = `https://${host[0]}${path[0]}`;
return rkey ? `${base}&${rkey[0]}` : base;
};
export const deserialize = (_ctx: Deps, body: FlashGetDownloadResp): Result => {
// 响应 f3 含 rkey + host(multimedia.qfile.qq.com)+ path(/download?appid=14901...&fldc=...)。
// rkey 在 f3 单独字段(path 不含 rkey),拼完整 URL 需拼接 &rkey=。
const raw = body.body;
export const encode = (env: OidbBase<FlashGetDownloadReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashGetDownloadReq>>(env);
if (!raw || raw.length === 0) {
return null;
}
export const decode = (bytes: Uint8Array): OidbBase<FlashGetDownloadResp> =>
protobuf_decode<OidbBase<FlashGetDownloadResp>>(bytes);
const text = Buffer.from(raw).toString('latin1');
const host = /multimedia\.qfile\.qq\.com/.exec(text);
const path = /\/download\?appid=14901[\x20-\x7e]*/.exec(text);
const rkey = /rkey=([A-Za-z0-9_-]+)/.exec(text);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetFlashDownload, params);
if (!host || !path) {
return null;
}
const base = `https://${host[0]}${path[0]}`;
return rkey ? `${base}&${rkey[0]}` : base;
};
export const encode = (env: OidbBase<FlashGetDownloadReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashGetDownloadReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashGetDownloadResp> =>
protobuf_decode<OidbBase<FlashGetDownloadResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetFlashDownload, params);
}
@@ -4,39 +4,39 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashListFilesetsReq,
FlashListFilesetsResp,
FlashFileEntry,
FlashListFilesetsReq,
FlashListFilesetsResp,
FlashFileEntry,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace ListFilesets {
export const command = 0x93d2;
export const subCommand = 1;
export const command = 0x93d2;
export const subCommand = 1;
export interface Params {
field1?: number; // 默认 3
field3?: number; // 默认 10
}
export type Result = FlashFileEntry[];
export interface Params {
field1?: number; // 默认 3
field3?: number; // 默认 10
}
export type Result = FlashFileEntry[];
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashListFilesetsReq => ({
field1: p.field1 ?? 3,
field2: '',
field3: p.field3 ?? 10,
});
export const serialize = (_ctx: Deps, p: Params): FlashListFilesetsReq => ({
field1: p.field1 ?? 3,
field2: '',
field3: p.field3 ?? 10,
});
export const deserialize = (_ctx: Deps, body: FlashListFilesetsResp): Result =>
body.entries ?? [];
export const deserialize = (_ctx: Deps, body: FlashListFilesetsResp): Result =>
body.entries ?? [];
export const encode = (env: OidbBase<FlashListFilesetsReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashListFilesetsReq>>(env);
export const encode = (env: OidbBase<FlashListFilesetsReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashListFilesetsReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashListFilesetsResp> =>
protobuf_decode<OidbBase<FlashListFilesetsResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashListFilesetsResp> =>
protobuf_decode<OidbBase<FlashListFilesetsResp>>(bytes);
export const invoke = (deps: Deps, params: Params = {}): Promise<Result> =>
invokeOidb(deps, ListFilesets, params);
export const invoke = (deps: Deps, params: Params = {}): Promise<Result> =>
invokeOidb(deps, ListFilesets, params);
}
@@ -4,101 +4,111 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashPrepareUploadReq,
FlashPrepareUploadResp,
FlashPrepareUploadReq,
FlashPrepareUploadResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
let seqCounter = 200;
export namespace PrepareUpload {
export const command = 0x12a9;
export const subCommand = 100;
export const uinForm = true;
export const command = 0x12a9;
export const subCommand = 100;
export const uinForm = true;
export interface Params {
filesetUuid: string;
fileUuid: string;
fileName: string;
fileSize: number;
sha1: string; // 40 hex
/** fileset 内序号(1,2,3...),与 0x93d0 commit f6 一致。缩略图序号在主文件之后递增。 */
fileIndex: number;
/** 格式码:与 commit f7 一致(mp4=2, rar/zip=4)。主文件 filesetWrap.f7 用此值;
* 缩略图固定 png=26/jpg=2。 */
formatCode: number;
/** 缩略图类型:undefined=主文件, 'png'=png 缩略图, 'jpg'=jpg 缩略图。
* 主文件下载入口需要缩略图关联才会被服务端填充,缩略图字段差异据此切换。 */
thumbType?: 'png' | 'jpg';
width?: number; // 缩略图宽(主文件=0)
height?: number; // 缩略图高(主文件=0)
}
export type Deps = OidbSender;
export interface Params {
filesetUuid: string;
fileUuid: string;
fileName: string;
fileSize: number;
sha1: string; // 40 hex
/** fileset 内序号(1,2,3...),与 0x93d0 commit f6 一致。缩略图序号在主文件之后递增。 */
fileIndex: number;
/** 格式码:与 commit f7 一致(mp4=2, rar/zip=4)。主文件 filesetWrap.f7 用此值;
* 缩略图固定 png=26/jpg=2。 */
formatCode: number;
/** 缩略图类型:undefined=主文件, 'png'=png 缩略图, 'jpg'=jpg 缩略图。
* 主文件下载入口需要缩略图关联才会被服务端填充,缩略图字段差异据此切换。 */
thumbType?: 'png' | 'jpg';
width?: number; // 缩略图宽(主文件=0)
height?: number; // 缩略图高(主文件=0)
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashPrepareUploadReq => {
// 缩略图与主文件字段差异:config.f103、FileInfo.f5.f1/f6/f7/f9、filesetWrap.f6/f7。
// filesetWrap.f4 统一用 fileIndex(主文件和缩略图都从 facade 传入,保证与 commit f6 一致)。
const isThumb = p.thumbType !== undefined;
const isJpg = p.thumbType === 'jpg';
return {
head: {
sub: { seq: seqCounter++, sub: 100 },
config: { field101: 2, field102: 4, field103: isThumb ? (isJpg ? 24 : 23) : 22, field200: 5 },
field3: { field1: 1 },
},
payload: {
wrapper: {
fileInfo: {
fileSize: p.fileSize,
md5: '', // sub=100 不带 MD5
sha1: p.sha1,
fileName: p.fileName,
field5: { field1: isJpg ? 1 : 0, field2: 0, field3: 0, field4: 0 },
field6: p.width ?? 0,
field7: p.height ?? 0,
field8: 0,
field9: isJpg ? 0 : 1,
},
field2: 0, // wrapper.f2=0(varint,不是 fileId)
},
field2: 1,
field3: 0,
field4: 0,
field5: 0,
field6: {
field1: { field1: 0, field2: {} },
field2: { field3: {} },
field3: { field11: {}, field12: {} },
field10: 0,
},
field7: 0,
field8: 0,
filesetWrap: {
filesetUuid: p.filesetUuid,
uploadKey: p.filesetUuid,
fileUuid: p.fileUuid,
field4: p.fileIndex,
field5: 0,
field6: isThumb ? 1 : 0, // 缩略图=1, 主文件=0
field7: isThumb ? (isJpg ? 2 : 26) : p.formatCode, // 主文件=formatCode(mp4=2), png缩略图=26, jpg缩略图=2
field8: {},
field9: 1, field10: 0, field11: 0, field12: 0, field13: 0, field14: 0,
},
},
export const serialize = (_ctx: Deps, p: Params): FlashPrepareUploadReq => {
// 缩略图与主文件字段差异:config.f103、FileInfo.f5.f1/f6/f7/f9、filesetWrap.f6/f7。
// filesetWrap.f4 统一用 fileIndex(主文件和缩略图都从 facade 传入,保证与 commit f6 一致)。
const isThumb = p.thumbType !== undefined;
const isJpg = p.thumbType === 'jpg';
return {
head: {
sub: { seq: seqCounter++, sub: 100 },
config: {
field101: 2,
field102: 4,
field103: isThumb ? (isJpg ? 24 : 23) : 22,
field200: 5,
},
field3: { field1: 1 },
},
payload: {
wrapper: {
fileInfo: {
fileSize: p.fileSize,
md5: '', // sub=100 不带 MD5
sha1: p.sha1,
fileName: p.fileName,
field5: { field1: isJpg ? 1 : 0, field2: 0, field3: 0, field4: 0 },
field6: p.width ?? 0,
field7: p.height ?? 0,
field8: 0,
field9: isJpg ? 0 : 1,
},
field2: 0, // wrapper.f2=0(varint,不是 fileId)
},
field2: 1,
field3: 0,
field4: 0,
field5: 0,
field6: {
field1: { field1: 0, field2: {} },
field2: { field3: {} },
field3: { field11: {}, field12: {} },
field10: 0,
},
field7: 0,
field8: 0,
filesetWrap: {
filesetUuid: p.filesetUuid,
uploadKey: p.filesetUuid,
fileUuid: p.fileUuid,
field4: p.fileIndex,
field5: 0,
field6: isThumb ? 1 : 0, // 缩略图=1, 主文件=0
field7: isThumb ? (isJpg ? 2 : 26) : p.formatCode, // 主文件=formatCode(mp4=2), png缩略图=26, jpg缩略图=2
field8: {},
field9: 1,
field10: 0,
field11: 0,
field12: 0,
field13: 0,
field14: 0,
},
},
};
};
};
export const deserialize = (_ctx: Deps, body: FlashPrepareUploadResp): string | null => {
// sub-100 resp f2={f1:rkey}(正常上传,CAES/CAIS/CAQS/CAMS)。
// 秒传(文件已在服务端)时 f2 无 f1(rkey),返回 null,调用方仍要 apply,
// 只跳过 sliceupload。
return body.rkeyWrap?.rkey ?? null;
};
export const deserialize = (_ctx: Deps, body: FlashPrepareUploadResp): string | null => {
// sub-100 resp f2={f1:rkey}(正常上传,CAES/CAIS/CAQS/CAMS)。
// 秒传(文件已在服务端)时 f2 无 f1(rkey),返回 null,调用方仍要 apply,
// 只跳过 sliceupload。
return body.rkeyWrap?.rkey ?? null;
};
export const encode = (env: OidbBase<FlashPrepareUploadReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashPrepareUploadReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashPrepareUploadResp> =>
protobuf_decode<OidbBase<FlashPrepareUploadResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string | null> =>
invokeOidb(deps, PrepareUpload, params);
export const encode = (env: OidbBase<FlashPrepareUploadReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashPrepareUploadReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashPrepareUploadResp> =>
protobuf_decode<OidbBase<FlashPrepareUploadResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<string | null> =>
invokeOidb(deps, PrepareUpload, params);
}
@@ -6,40 +6,40 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashRenameFileReq,
FlashRenameFileResp,
FlashRenameFileReq,
FlashRenameFileResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace RenameFlashFile {
export const command = 0x9427;
export const subCommand = 0;
export const uinForm = true;
export const command = 0x9427;
export const subCommand = 0;
export const uinForm = true;
export interface Params {
filesetUuid: string;
/** 新文件名(同时用作显示名,与 QQ 面板行为一致)。 */
newName: string;
}
export interface Params {
filesetUuid: string;
/** 新文件名(同时用作显示名,与 QQ 面板行为一致)。 */
newName: string;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashRenameFileReq => ({
filesetUuid: p.filesetUuid,
name: { newName: p.newName, displayName: p.newName },
flag: { field1: 0 },
});
export const serialize = (_ctx: Deps, p: Params): FlashRenameFileReq => ({
filesetUuid: p.filesetUuid,
name: { newName: p.newName, displayName: p.newName },
flag: { field1: 0 },
});
export const deserialize = (_ctx: Deps, _body: FlashRenameFileResp): void => {
// 成功靠 envelope errorCode=0。
};
export const deserialize = (_ctx: Deps, _body: FlashRenameFileResp): void => {
// 成功靠 envelope errorCode=0。
};
export const encode = (env: OidbBase<FlashRenameFileReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashRenameFileReq>>(env);
export const encode = (env: OidbBase<FlashRenameFileReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashRenameFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashRenameFileResp> =>
protobuf_decode<OidbBase<FlashRenameFileResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashRenameFileResp> =>
protobuf_decode<OidbBase<FlashRenameFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, RenameFlashFile, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, RenameFlashFile, params);
}
@@ -5,48 +5,46 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashSendReq,
FlashSendResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import type { FlashSendReq, FlashSendResp } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SendFlashMsg {
export const command = 0x93d7;
export const subCommand = 1;
export const command = 0x93d7;
export const subCommand = 1;
export interface Params {
targetUid?: string; // 私聊(与 groupId 二选一)
groupId?: number; // 群聊
filesetUuid: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashSendReq => {
// 群聊:f1={f1:2, f3:{f1:groupId}}(groupId 直接用群号,无需转 uid)。
if (p.groupId !== undefined) {
return {
target: { field1: 2, targetGroup: { groupId: p.groupId } },
filesetUuid: p.filesetUuid,
};
export interface Params {
targetUid?: string; // 私聊(与 groupId 二选一)
groupId?: number; // 群聊
filesetUuid: string;
}
// 私聊:f1={f1:1, f2:{f1:targetUid}}。
return {
target: { field1: 1, targetUid: { targetUid: p.targetUid! } },
filesetUuid: p.filesetUuid,
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashSendReq => {
// 群聊:f1={f1:2, f3:{f1:groupId}}(groupId 直接用群号,无需转 uid)。
if (p.groupId !== undefined) {
return {
target: { field1: 2, targetGroup: { groupId: p.groupId } },
filesetUuid: p.filesetUuid,
};
}
// 私聊:f1={f1:1, f2:{f1:targetUid}}。
return {
target: { field1: 1, targetUid: { targetUid: p.targetUid! } },
filesetUuid: p.filesetUuid,
};
};
};
export const deserialize = (_ctx: Deps, _body: FlashSendResp): void => {
// 响应仅回显目标 uid,无 message_id。
};
export const deserialize = (_ctx: Deps, _body: FlashSendResp): void => {
// 响应仅回显目标 uid,无 message_id。
};
export const encode = (env: OidbBase<FlashSendReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashSendReq>>(env);
export const encode = (env: OidbBase<FlashSendReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashSendReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashSendResp> =>
protobuf_decode<OidbBase<FlashSendResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashSendResp> =>
protobuf_decode<OidbBase<FlashSendResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SendFlashMsg, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SendFlashMsg, params);
}
@@ -3,37 +3,37 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FlashSetStatusReq,
FlashSetStatusResp,
FlashSetStatusReq,
FlashSetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetFilesetStatus {
export const command = 0x93d1;
export const subCommand = 1;
export const command = 0x93d1;
export const subCommand = 1;
export interface Params {
filesetUuid: string;
status?: number; // 默认 6
}
export interface Params {
filesetUuid: string;
status?: number; // 默认 6
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FlashSetStatusReq => ({
filesetUuid: p.filesetUuid,
status: p.status ?? 6,
});
export const serialize = (_ctx: Deps, p: Params): FlashSetStatusReq => ({
filesetUuid: p.filesetUuid,
status: p.status ?? 6,
});
export const deserialize = (_ctx: Deps, _body: FlashSetStatusResp): void => {
// 成功靠 envelope errorCode=0。
};
export const deserialize = (_ctx: Deps, _body: FlashSetStatusResp): void => {
// 成功靠 envelope errorCode=0。
};
export const encode = (env: OidbBase<FlashSetStatusReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashSetStatusReq>>(env);
export const encode = (env: OidbBase<FlashSetStatusReq>): Uint8Array =>
protobuf_encode<OidbBase<FlashSetStatusReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<FlashSetStatusResp> =>
protobuf_decode<OidbBase<FlashSetStatusResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<FlashSetStatusResp> =>
protobuf_decode<OidbBase<FlashSetStatusResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetFilesetStatus, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetFilesetStatus, params);
}
@@ -8,33 +8,42 @@ import { invokeOidb, type OidbSender } from '../../oidb-service';
import { resolveSelfUid } from '../../self-uid';
export namespace ApproveDoubtBuddyReq {
export const command = 0xD72;
export const subCommand = 0;
export const uinForm = false;
export const command = 0xd72;
export const subCommand = 0;
export const uinForm = false;
export interface Params { uid: string }
export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
export interface Params {
uid: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbDoubtApprovalReq> => {
if (!p.uid.trim()) throw new Error('cannot approve doubt request: applicant uid is unavailable');
const selfUid = await resolveSelfUid(ctx);
if (!selfUid.trim()) throw new Error('cannot approve doubt request: self uid is unavailable');
return {
selfUid,
targetUid: p.uid,
field3: 0,
field4: '',
export const serialize = async (ctx: Deps, p: Params): Promise<OidbDoubtApprovalReq> => {
if (!p.uid.trim()) {
throw new Error('cannot approve doubt request: applicant uid is unavailable');
}
const selfUid = await resolveSelfUid(ctx);
if (!selfUid.trim()) {
throw new Error('cannot approve doubt request: self uid is unavailable');
}
return {
selfUid,
targetUid: p.uid,
field3: 0,
field4: '',
};
};
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbDoubtApprovalReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbDoubtApprovalReq>>(env);
export const encode = (env: OidbBase<OidbDoubtApprovalReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbDoubtApprovalReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ApproveDoubtBuddyReq, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ApproveDoubtBuddyReq, params);
}
@@ -9,27 +9,27 @@ import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace ClearFriendRemark {
export const command = 0x912F;
export const subCommand = 0;
export const command = 0x912f;
export const subCommand = 0;
export interface Params {
userId: number;
}
export interface Params {
userId: number;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = async (ctx: Deps, p: Params): Promise<OidbClearFriendRemark> => ({
target: { targetUid: await ctx.resolveUserUid(p.userId) },
});
export const serialize = async (ctx: Deps, p: Params): Promise<OidbClearFriendRemark> => ({
target: { targetUid: await ctx.resolveUserUid(p.userId) },
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbClearFriendRemark>): Uint8Array =>
protobuf_encode<OidbBase<OidbClearFriendRemark>>(env);
export const encode = (env: OidbBase<OidbClearFriendRemark>): Uint8Array =>
protobuf_encode<OidbBase<OidbClearFriendRemark>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ClearFriendRemark, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ClearFriendRemark, params);
}
@@ -16,39 +16,39 @@ 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 const command = 0x126b;
export const subCommand = 0;
export interface Params {
userId: number;
/** Also block (拉黑) the user. Default false. */
block?: boolean;
}
export interface Params {
userId: number;
/** Also block (拉黑) the user. Default false. */
block?: boolean;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
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 },
},
// DelBuddyWorker receives both booleans explicitly from current QQ.
block: p.block ?? false,
field4: true,
},
});
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 },
},
// DelBuddyWorker receives both booleans explicitly from current QQ.
block: p.block ?? false,
field4: true,
},
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbDeleteFriend>): Uint8Array =>
protobuf_encode<OidbBase<OidbDeleteFriend>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteFriend, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteFriend, params);
}
@@ -11,79 +11,85 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDoubtGetReq, OidbDoubtGetResp,
OidbDoubtGetReq,
OidbDoubtGetResp,
} from '@snowluma/proto-defs/oidb-actions/doubt-buddy';
import { invokeOidb, type OidbSender } from '../../oidb-service';
interface OidbDoubtItemAccountOnTag1 {
uin?: pb<1, uint_64>;
uin?: pb<1, uint_64>;
}
interface OidbDoubtGetRespAccountOnTag1Body {
list?: pb_repeated<1, OidbDoubtItemAccountOnTag1>;
list?: pb_repeated<1, OidbDoubtItemAccountOnTag1>;
}
interface OidbDoubtGetRespAccountOnTag1 {
status?: pb<1, uint_32>;
body?: pb<2, OidbDoubtGetRespAccountOnTag1Body>;
status?: pb<1, uint_32>;
body?: pb<2, OidbDoubtGetRespAccountOnTag1Body>;
}
type DecodedDoubtItem = NonNullable<NonNullable<OidbDoubtGetResp['body']>['list']>[number] & {
uin?: bigint;
uin?: bigint;
};
interface DecodedDoubtGetResp extends Omit<OidbDoubtGetResp, 'body'> {
body?: Omit<NonNullable<OidbDoubtGetResp['body']>, 'list'> & { list?: DecodedDoubtItem[] };
body?: Omit<NonNullable<OidbDoubtGetResp['body']>, 'list'> & { list?: DecodedDoubtItem[] };
}
export interface DoubtBuddyRequest {
[key: string]: import('@snowluma/common/json').JsonValue;
/** Opaque uid — pass back as `flag` to set_doubt_friends_add_request. */
uid: string;
user_id: number;
nick: string;
source: string;
reason: string;
msg: string;
group_code: string;
reqTime: number;
[key: string]: import('@snowluma/common/json').JsonValue;
/** Opaque uid — pass back as `flag` to set_doubt_friends_add_request. */
uid: string;
user_id: number;
nick: string;
source: string;
reason: string;
msg: string;
group_code: string;
reqTime: number;
}
export namespace GetDoubtBuddyReq {
export const command = 0xD69;
export const subCommand = 0;
export const uinForm = true;
export const command = 0xd69;
export const subCommand = 0;
export const uinForm = true;
export interface Params { count: number; cookie?: string }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbDoubtGetReq => ({
field1: 1,
inner: { num: p.count, uk: p.cookie ?? '' },
});
export const deserialize = (_ctx: Deps, body: DecodedDoubtGetResp): DoubtBuddyRequest[] =>
(body.body?.list ?? []).map((it) => ({
uid: it.uid ?? '',
user_id: Number(it.uin ?? 0),
nick: it.nick ?? '',
source: it.source ?? '',
reason: it.reason ?? '',
msg: it.msg ?? '',
group_code: it.groupCode ? String(it.groupCode) : '',
reqTime: Number(it.reqTime ?? 0),
}));
export const encode = (env: OidbBase<OidbDoubtGetReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbDoubtGetReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<DecodedDoubtGetResp> => {
const decoded = protobuf_decode<OidbBase<OidbDoubtGetResp>>(bytes);
const numeric = protobuf_decode<OidbBase<OidbDoubtGetRespAccountOnTag1>>(bytes);
const items = decoded.body?.body?.list ?? [];
const numericItems = numeric.body?.body?.list ?? [];
for (let i = 0; i < items.length; i++) {
(items[i] as DecodedDoubtItem).uin = numericItems[i]?.uin;
export interface Params {
count: number;
cookie?: string;
}
return decoded as OidbBase<DecodedDoubtGetResp>;
};
export type Deps = OidbSender;
export const invoke = (deps: Deps, params: Params): Promise<DoubtBuddyRequest[]> =>
invokeOidb(deps, GetDoubtBuddyReq, params);
export const serialize = (_ctx: Deps, p: Params): OidbDoubtGetReq => ({
field1: 1,
inner: { num: p.count, uk: p.cookie ?? '' },
});
export const deserialize = (_ctx: Deps, body: DecodedDoubtGetResp): DoubtBuddyRequest[] =>
(body.body?.list ?? []).map((it) => ({
uid: it.uid ?? '',
user_id: Number(it.uin ?? 0),
nick: it.nick ?? '',
source: it.source ?? '',
reason: it.reason ?? '',
msg: it.msg ?? '',
group_code: it.groupCode ? String(it.groupCode) : '',
reqTime: Number(it.reqTime ?? 0),
}));
export const encode = (env: OidbBase<OidbDoubtGetReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbDoubtGetReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<DecodedDoubtGetResp> => {
const decoded = protobuf_decode<OidbBase<OidbDoubtGetResp>>(bytes);
const numeric = protobuf_decode<OidbBase<OidbDoubtGetRespAccountOnTag1>>(bytes);
const items = decoded.body?.body?.list ?? [];
const numericItems = numeric.body?.body?.list ?? [];
for (let i = 0; i < items.length; i++) {
(items[i] as DecodedDoubtItem).uin = numericItems[i]?.uin;
}
return decoded as OidbBase<DecodedDoubtGetResp>;
};
export const invoke = (deps: Deps, params: Params): Promise<DoubtBuddyRequest[]> =>
invokeOidb(deps, GetDoubtBuddyReq, params);
}
@@ -11,37 +11,37 @@ 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 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 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 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 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 deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbFriendRequestAction>): Uint8Array =>
protobuf_encode<OidbBase<OidbFriendRequestAction>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, HandleFriendRequest, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, HandleFriendRequest, params);
}
@@ -11,26 +11,28 @@ import type { OidbDoubtDelReq } from '@snowluma/proto-defs/oidb-actions/doubt-bu
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace RejectDoubtBuddyReq {
export const command = 0xD69;
export const subCommand = 0;
export const uinForm = true;
export const command = 0xd69;
export const subCommand = 0;
export const uinForm = true;
export interface Params { uid: string }
export type Deps = OidbSender;
export interface Params {
uid: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbDoubtDelReq => ({
field1: 3,
inner: { uid: p.uid },
});
export const serialize = (_ctx: Deps, p: Params): OidbDoubtDelReq => ({
field1: 3,
inner: { uid: p.uid },
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbDoubtDelReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbDoubtDelReq>>(env);
export const encode = (env: OidbBase<OidbDoubtDelReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbDoubtDelReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, RejectDoubtBuddyReq, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, RejectDoubtBuddyReq, params);
}
@@ -6,8 +6,8 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbSetFriendRemark,
OidbSetFriendRemarkResponse,
OidbSetFriendRemark,
OidbSetFriendRemarkResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, OidbError, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
@@ -15,91 +15,111 @@ import type { BridgeContext } from '../../bridge-context';
const log = createLogger('Bridge.Friend');
export namespace SetFriendRemark {
export const command = 0x912E;
export const subCommand = 0;
export const command = 0x912e;
export const subCommand = 0;
export interface Params {
userId: number;
remark: string;
}
interface WireParams {
targetUid: string;
remark: string;
}
export interface Result {
targetUid: string;
targetUin: number;
remark: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
export const serialize = (_ctx: Deps, p: WireParams): OidbSetFriendRemark => ({
change: {
target: { targetUid: p.targetUid },
remark: p.remark,
},
scene: 0,
});
export const deserialize = (_ctx: Deps, response: OidbSetFriendRemarkResponse): Result => {
if (response.error) {
const code = response.error.code ?? 0;
const message = response.error.message ?? '';
if (code !== 0) throw new OidbError(code, message, command, subCommand);
throw new Error(`invalid friend remark response: error result has no failure code${message ? ` (${message})` : ''}`);
export interface Params {
userId: number;
remark: string;
}
const result = response.result;
if (!result) throw new Error('invalid friend remark response: missing result');
const targetUid = result?.target?.targetUid ?? '';
const rawTargetUin = result?.target?.targetUin ?? '';
const targetUin = rawTargetUin ? Number(rawTargetUin) : 0;
if (rawTargetUin && (!Number.isSafeInteger(targetUin) || targetUin <= 0)) {
throw new Error(`invalid friend remark response: invalid target UIN ${rawTargetUin}`);
interface WireParams {
targetUid: string;
remark: string;
}
return { targetUid, targetUin, remark: result?.remark ?? '' };
};
export const encode = (env: OidbBase<OidbSetFriendRemark>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetFriendRemark>>(env);
export interface Result {
targetUid: string;
targetUin: number;
remark: string;
}
export const decode = (bytes: Uint8Array): OidbBase<OidbSetFriendRemarkResponse> =>
protobuf_decode<OidbBase<OidbSetFriendRemarkResponse>>(bytes);
export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
const targetUid = await deps.resolveUserUid(params.userId);
const result = await invokeOidb(deps, SetFriendRemark, {
targetUid,
remark: params.remark,
export const serialize = (_ctx: Deps, p: WireParams): OidbSetFriendRemark => ({
change: {
target: { targetUid: p.targetUid },
remark: p.remark,
},
scene: 0,
});
if (result.targetUid !== targetUid) {
throw new Error(`friend remark response target mismatch: expected UID ${targetUid}, got ${result.targetUid || '(missing)'}`);
}
if (result.targetUin > 0 && result.targetUin !== params.userId) {
throw new Error(`friend remark response target mismatch: expected UIN ${params.userId}, got ${result.targetUin}`);
}
if (result.remark !== params.remark) {
throw new Error('friend remark response value does not match the requested remark');
}
// The server-side mutation has already completed. A local cache failure
// must remain observable, but reporting the Action as failed here would
// encourage callers to repeat an operation that QQ already accepted.
try {
deps.identity.updateFriendRemark(
result.targetUid,
result.targetUin || params.userId,
result.remark,
);
} catch (error: unknown) {
log.error(
'local identity synchronization failed after confirmed friend remark update: uid=%s uin=%d: %s',
result.targetUid,
result.targetUin || params.userId,
error instanceof Error ? error.message : String(error),
);
}
};
export const deserialize = (_ctx: Deps, response: OidbSetFriendRemarkResponse): Result => {
if (response.error) {
const code = response.error.code ?? 0;
const message = response.error.message ?? '';
if (code !== 0) {
throw new OidbError(code, message, command, subCommand);
}
throw new Error(
`invalid friend remark response: error result has no failure code${message ? ` (${message})` : ''}`,
);
}
const result = response.result;
if (!result) {
throw new Error('invalid friend remark response: missing result');
}
const targetUid = result?.target?.targetUid ?? '';
const rawTargetUin = result?.target?.targetUin ?? '';
const targetUin = rawTargetUin ? Number(rawTargetUin) : 0;
if (rawTargetUin && (!Number.isSafeInteger(targetUin) || targetUin <= 0)) {
throw new Error(`invalid friend remark response: invalid target UIN ${rawTargetUin}`);
}
return { targetUid, targetUin, remark: result?.remark ?? '' };
};
export const encode = (env: OidbBase<OidbSetFriendRemark>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetFriendRemark>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbSetFriendRemarkResponse> =>
protobuf_decode<OidbBase<OidbSetFriendRemarkResponse>>(bytes);
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
const targetUid = await deps.resolveUserUid(params.userId);
const result = await invokeOidb(deps, SetFriendRemark, {
targetUid,
remark: params.remark,
});
if (result.targetUid !== targetUid) {
throw new Error(
`friend remark response target mismatch: expected UID ${targetUid}, got ${result.targetUid || '(missing)'}`,
);
}
if (result.targetUin > 0 && result.targetUin !== params.userId) {
throw new Error(
`friend remark response target mismatch: expected UIN ${params.userId}, got ${result.targetUin}`,
);
}
if (result.remark !== params.remark) {
throw new Error('friend remark response value does not match the requested remark');
}
// The server-side mutation has already completed. A local cache failure
// must remain observable, but reporting the Action as failed here would
// encourage callers to repeat an operation that QQ already accepted.
try {
deps.identity.updateFriendRemark(
result.targetUid,
result.targetUin || params.userId,
result.remark,
);
} catch (error: unknown) {
log.error(
'local identity synchronization failed after confirmed friend remark update: uid=%s uin=%d: %s',
result.targetUid,
result.targetUin || params.userId,
error instanceof Error ? error.message : String(error),
);
}
};
}
@@ -4,36 +4,39 @@ import type { OidbChangeGroupCategoryTag } from '@snowluma/proto-defs/oidb-actio
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace AddGroupCategoryTag {
export const command = 0x967D;
export const subCommand = 0;
export const command = 0x967d;
export const subCommand = 0;
export interface Params {
groupClass: number;
name: string;
}
export interface Params {
groupClass: number;
name: string;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbChangeGroupCategoryTag => {
assertTagChange(p.groupClass, p.name);
return { groupClass: p.groupClass, name: p.name };
};
export const serialize = (_ctx: Deps, p: Params): OidbChangeGroupCategoryTag => {
assertTagChange(p.groupClass, p.name);
return { groupClass: p.groupClass, name: p.name };
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbChangeGroupCategoryTag>): Uint8Array =>
protobuf_encode<OidbBase<OidbChangeGroupCategoryTag>>(env);
export const encode = (env: OidbBase<OidbChangeGroupCategoryTag>): Uint8Array =>
protobuf_encode<OidbBase<OidbChangeGroupCategoryTag>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, AddGroupCategoryTag, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, AddGroupCategoryTag, params);
}
function assertTagChange(groupClass: number, name: string): void {
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xFFFFFFFF) {
throw new Error(`group class ${groupClass} is out of range`);
}
if (name.length === 0) throw new Error('tag name must not be empty');
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xffffffff) {
throw new Error(`group class ${groupClass} is out of range`);
}
if (name.length === 0) {
throw new Error('tag name must not be empty');
}
}
@@ -4,36 +4,39 @@ import type { OidbChangeGroupCategoryTag } from '@snowluma/proto-defs/oidb-actio
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace DeleteGroupCategoryTag {
export const command = 0x967E;
export const subCommand = 0;
export const command = 0x967e;
export const subCommand = 0;
export interface Params {
groupClass: number;
name: string;
}
export interface Params {
groupClass: number;
name: string;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbChangeGroupCategoryTag => {
assertTagChange(p.groupClass, p.name);
return { groupClass: p.groupClass, name: p.name };
};
export const serialize = (_ctx: Deps, p: Params): OidbChangeGroupCategoryTag => {
assertTagChange(p.groupClass, p.name);
return { groupClass: p.groupClass, name: p.name };
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbChangeGroupCategoryTag>): Uint8Array =>
protobuf_encode<OidbBase<OidbChangeGroupCategoryTag>>(env);
export const encode = (env: OidbBase<OidbChangeGroupCategoryTag>): Uint8Array =>
protobuf_encode<OidbBase<OidbChangeGroupCategoryTag>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteGroupCategoryTag, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteGroupCategoryTag, params);
}
function assertTagChange(groupClass: number, name: string): void {
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xFFFFFFFF) {
throw new Error(`group class ${groupClass} is out of range`);
}
if (name.length === 0) throw new Error('tag name must not be empty');
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xffffffff) {
throw new Error(`group class ${groupClass} is out of range`);
}
if (name.length === 0) {
throw new Error('tag name must not be empty');
}
}
@@ -15,44 +15,46 @@ 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;
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 const command = 0x8a7;
export const subCommand = 0;
export interface Params { groupId: number; }
export interface Params {
groupId: number;
}
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
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 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 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 encode = (env: OidbBase<Oidb0x8a7Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x8a7Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x8a7Resp> =>
protobuf_decode<OidbBase<Oidb0x8a7Resp>>(bytes);
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);
export const invoke = (deps: Deps, params: Params): Promise<AtAllRemain> =>
invokeOidb(deps, GetAtAllRemain, params);
}
@@ -1,60 +1,60 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGetGroupCategoryTags,
OidbGetGroupCategoryTagsResp,
OidbGroupCategoryTag,
OidbGetGroupCategoryTags,
OidbGetGroupCategoryTagsResp,
OidbGroupCategoryTag,
} from '@snowluma/proto-defs/oidb-actions/group-category-tag';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupCategoryTag {
id: number;
name: string;
type: number;
id: number;
name: string;
type: number;
}
export namespace GetGroupCategoryTags {
export const command = 0x967C;
export const subCommand = 0;
export const command = 0x967c;
export const subCommand = 0;
export interface Params {
groupClass: number;
}
export interface Params {
groupClass: number;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGetGroupCategoryTags => {
assertGroupClass(p.groupClass);
return { groupClass: p.groupClass };
};
export const serialize = (_ctx: Deps, p: Params): OidbGetGroupCategoryTags => {
assertGroupClass(p.groupClass);
return { groupClass: p.groupClass };
};
export const deserialize = (
_ctx: Deps,
body: OidbGetGroupCategoryTagsResp,
): { tags: GroupCategoryTag[] } => ({
tags: (body.tags ?? []).map(toTag),
});
export const deserialize = (
_ctx: Deps,
body: OidbGetGroupCategoryTagsResp,
): { tags: GroupCategoryTag[] } => ({
tags: (body.tags ?? []).map(toTag),
});
export const encode = (env: OidbBase<OidbGetGroupCategoryTags>): Uint8Array =>
protobuf_encode<OidbBase<OidbGetGroupCategoryTags>>(env);
export const encode = (env: OidbBase<OidbGetGroupCategoryTags>): Uint8Array =>
protobuf_encode<OidbBase<OidbGetGroupCategoryTags>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGetGroupCategoryTagsResp> =>
protobuf_decode<OidbBase<OidbGetGroupCategoryTagsResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbGetGroupCategoryTagsResp> =>
protobuf_decode<OidbBase<OidbGetGroupCategoryTagsResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<{ tags: GroupCategoryTag[] }> =>
invokeOidb(deps, GetGroupCategoryTags, params);
export const invoke = (deps: Deps, params: Params): Promise<{ tags: GroupCategoryTag[] }> =>
invokeOidb(deps, GetGroupCategoryTags, params);
}
function assertGroupClass(groupClass: number): void {
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xFFFFFFFF) {
throw new Error(`group class ${groupClass} is out of range`);
}
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xffffffff) {
throw new Error(`group class ${groupClass} is out of range`);
}
}
function toTag(tag: OidbGroupCategoryTag): GroupCategoryTag {
return {
id: tag.id ?? 0,
name: tag.name ?? '',
type: tag.type ?? 0,
};
return {
id: tag.id ?? 0,
name: tag.name ?? '',
type: tag.type ?? 0,
};
}
@@ -3,50 +3,58 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGetGroupExtReq, OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
import type {
OidbGetGroupExtReq,
OidbGetGroupExtResp,
} from '@snowluma/proto-defs/oidb-actions/group-ext';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupExtRobotOption {
robotMemberSwitch: number;
robotMemberExamine: number;
robotMemberSwitch: number;
robotMemberExamine: number;
}
export namespace FetchGroupExtInfo {
export const command = 0xEF0;
export const subCommand = 1;
export const uinForm = true;
export const command = 0xef0;
export const subCommand = 1;
export const uinForm = true;
export interface Params { groupId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGetGroupExtReq => ({
groupCodes: [BigInt(p.groupId)],
filter: {
inviteRobotMemberSwitch: 1,
inviteRobotMemberExamine: 1,
},
});
export const deserialize = (_ctx: Deps, body: OidbGetGroupExtResp): GroupExtRobotOption => {
const item = body.items?.[0];
if (!item) {
throw new Error('unable to read group robot-add option');
export interface Params {
groupId: number;
}
if (item.resultCode && item.resultCode !== 0) {
throw new Error(`unable to read group robot-add option: result=${item.resultCode}`);
}
return {
robotMemberSwitch: item.ext?.inviteRobotMemberSwitch ?? 0,
robotMemberExamine: item.ext?.inviteRobotMemberExamine ?? 0,
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGetGroupExtReq => ({
groupCodes: [BigInt(p.groupId)],
filter: {
inviteRobotMemberSwitch: 1,
inviteRobotMemberExamine: 1,
},
});
export const deserialize = (_ctx: Deps, body: OidbGetGroupExtResp): GroupExtRobotOption => {
const item = body.items?.[0];
if (!item) {
throw new Error('unable to read group robot-add option');
}
if (item.resultCode && item.resultCode !== 0) {
throw new Error(`unable to read group robot-add option: result=${item.resultCode}`);
}
return {
robotMemberSwitch: item.ext?.inviteRobotMemberSwitch ?? 0,
robotMemberExamine: item.ext?.inviteRobotMemberExamine ?? 0,
};
};
};
export const encode = (env: OidbBase<OidbGetGroupExtReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGetGroupExtReq>>(env);
export const encode = (env: OidbBase<OidbGetGroupExtReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGetGroupExtReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGetGroupExtResp> =>
protobuf_decode<OidbBase<OidbGetGroupExtResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbGetGroupExtResp> =>
protobuf_decode<OidbBase<OidbGetGroupExtResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupExtRobotOption> =>
invokeOidb(deps, FetchGroupExtInfo, params);
export const invoke = (deps: Deps, params: Params): Promise<GroupExtRobotOption> =>
invokeOidb(deps, FetchGroupExtInfo, params);
}
@@ -5,48 +5,49 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbKickMember,
OidbKickMemberResponse,
OidbKickMember,
OidbKickMemberResponse,
} 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 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, body: OidbKickMemberResponse): void => {
for (const item of body.results ?? []) {
const code = item.result ?? 0;
if (code !== 0) {
throw new Error(`kick member failed: result=${code}`);
}
export interface Params {
groupId: number;
userId: number;
/** Reject the kicked user's future join requests. */
reject: boolean;
reason?: string;
}
};
export const encode = (env: OidbBase<OidbKickMember>): Uint8Array =>
protobuf_encode<OidbBase<OidbKickMember>>(env);
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const decode = (bytes: Uint8Array): OidbBase<OidbKickMemberResponse> =>
protobuf_decode<OidbBase<OidbKickMemberResponse>>(bytes);
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 invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, KickMember, params);
export const deserialize = (_ctx: Deps, body: OidbKickMemberResponse): void => {
for (const item of body.results ?? []) {
const code = item.result ?? 0;
if (code !== 0) {
throw new Error(`kick member failed: result=${code}`);
}
}
};
export const encode = (env: OidbBase<OidbKickMember>): Uint8Array =>
protobuf_encode<OidbBase<OidbKickMember>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbKickMemberResponse> =>
protobuf_decode<OidbBase<OidbKickMemberResponse>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, KickMember, params);
}
@@ -4,48 +4,46 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x8a0Req,
OidbKickMemberResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { Oidb0x8a0Req, OidbKickMemberResponse } 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 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, body: OidbKickMemberResponse): void => {
for (const item of body.results ?? []) {
const code = item.result ?? 0;
if (code !== 0) {
throw new Error(`kick members failed: result=${code}`);
}
export interface Params {
groupId: number;
userIds: number[];
reject: boolean;
}
};
export const encode = (env: OidbBase<Oidb0x8a0Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x8a0Req>>(env);
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const decode = (bytes: Uint8Array): OidbBase<OidbKickMemberResponse> =>
protobuf_decode<OidbBase<OidbKickMemberResponse>>(bytes);
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 invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, KickMembers, params);
export const deserialize = (_ctx: Deps, body: OidbKickMemberResponse): void => {
for (const item of body.results ?? []) {
const code = item.result ?? 0;
if (code !== 0) {
throw new Error(`kick members failed: result=${code}`);
}
}
};
export const encode = (env: OidbBase<Oidb0x8a0Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x8a0Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbKickMemberResponse> =>
protobuf_decode<OidbBase<OidbKickMemberResponse>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, KickMembers, params);
}
@@ -6,18 +6,22 @@ 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 const command = 0x1097;
export const subCommand = 1;
export interface Params { groupId: number; }
export type Deps = OidbSender;
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);
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);
}
@@ -8,51 +8,61 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbModifyGroupExtReq, OidbModifyGroupExtResp, OidbGroupExtBody,
OidbModifyGroupExtReq,
OidbModifyGroupExtResp,
OidbGroupExtBody,
} from '@snowluma/proto-defs/oidb-actions/group-ext';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace ModifyGroupExtInfo {
export const command = 0xF00;
export const subCommand = 3;
export const uinForm = true;
export const command = 0xf00;
export const subCommand = 3;
export const uinForm = true;
export interface Params {
groupId: number;
/** undefined → leave unchanged (field not emitted). */
robotMemberSwitch?: number;
robotMemberExamine?: number;
}
export type Deps = OidbSender;
export interface Params {
groupId: number;
/** undefined → leave unchanged (field not emitted). */
robotMemberSwitch?: number;
robotMemberExamine?: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbModifyGroupExtReq => {
const ext: OidbGroupExtBody = {};
if (p.robotMemberSwitch !== undefined) ext.inviteRobotMemberSwitch = p.robotMemberSwitch;
if (p.robotMemberExamine !== undefined) ext.inviteRobotMemberExamine = p.robotMemberExamine;
return {
groupCode: p.groupId,
info: { groupCode: p.groupId, ext },
export const serialize = (_ctx: Deps, p: Params): OidbModifyGroupExtReq => {
const ext: OidbGroupExtBody = {};
if (p.robotMemberSwitch !== undefined) {
ext.inviteRobotMemberSwitch = p.robotMemberSwitch;
}
if (p.robotMemberExamine !== undefined) {
ext.inviteRobotMemberExamine = p.robotMemberExamine;
}
return {
groupCode: p.groupId,
info: { groupCode: p.groupId, ext },
};
};
};
export const deserialize = (_ctx: Deps, body: OidbModifyGroupExtResp): void => {
// Envelope-level OIDB errors are already thrown by invokeOidb; this is the
// body-level ack. 0 (or absent) = success.
if (body.result && body.result !== 0) {
throw new Error(`modifyGroupExtInfo failed: result=${body.result}`);
}
};
export const deserialize = (_ctx: Deps, body: OidbModifyGroupExtResp): void => {
// Envelope-level OIDB errors are already thrown by invokeOidb; this is the
// body-level ack. 0 (or absent) = success.
if (body.result && body.result !== 0) {
throw new Error(`modifyGroupExtInfo failed: result=${body.result}`);
}
};
export const encode = (env: OidbBase<OidbModifyGroupExtReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbModifyGroupExtReq>>(env);
export const encode = (env: OidbBase<OidbModifyGroupExtReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbModifyGroupExtReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbModifyGroupExtResp> =>
protobuf_decode<OidbBase<OidbModifyGroupExtResp>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbModifyGroupExtResp> =>
protobuf_decode<OidbBase<OidbModifyGroupExtResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> => {
if (params.robotMemberSwitch === undefined && params.robotMemberExamine === undefined) {
return Promise.resolve();
}
return invokeOidb(deps, ModifyGroupExtInfo, params);
};
export const invoke = (deps: Deps, params: Params): Promise<void> => {
if (params.robotMemberSwitch === undefined && params.robotMemberExamine === undefined) {
return Promise.resolve();
}
return invokeOidb(deps, ModifyGroupExtInfo, params);
};
}
@@ -9,26 +9,29 @@ 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 const command = 0x89a;
export const subCommand = 0;
export interface Params { groupId: number; enable: boolean; }
export interface Params {
groupId: number;
enable: boolean;
}
export type Deps = OidbSender;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbMuteAll => ({
groupUin: p.groupId,
muteState: { state: p.enable ? 0xFFFFFFFF : 0 },
});
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 deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbMuteAll>): Uint8Array =>
protobuf_encode<OidbBase<OidbMuteAll>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MuteAll, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MuteAll, params);
}
@@ -8,29 +8,34 @@ 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 const command = 0x1253;
export const subCommand = 1;
export interface Params { groupId: number; userId: number; duration: number; }
export interface Params {
groupId: number;
userId: number;
duration: number;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
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 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 deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbMuteMember>): Uint8Array =>
protobuf_encode<OidbBase<OidbMuteMember>>(env);
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 decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MuteMember, params);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, MuteMember, params);
}
Loaded 100 of 977 files, more files were not shown because too many files have changed in this diff. Show more