refactor(bridge): extract protocol layer into @snowluma/bridge package
Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files — events / event-bus / identity-service / packet-pipeline / element- builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* + the bridge-side formatters — out of `packages/core/src/bridge/` into the new `@snowluma/bridge` workspace package. Everything that translates QQ wire bytes ↔ typed events/elements now lives there. Why --- - `packages/core/src/bridge/` was actually two layers: a low-level "protocol decoder + I/O" set (msg-push, highway, packet-pipeline, identity, element-builder) AND the Api-class host (bridge.ts + apis/*). The Api layer can't move without the protocol layer moving first, but the two had grown into one directory. - Bridge-internal consumers (highway uploaders, OIDB envelope helper, element-builder, msg-push parsers) only ever needed `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata cache. Splitting them out lets that minimal surface live in the bridge package as `BridgeContext` while the api-layer's extended context (with `apis: ApiHub`) stays in @snowluma/core. What stays in @snowluma/core (apis layer): - bridge.ts ── the god-class that composes the protocol building blocks + mounts apis - bridge-interface.ts ── public façade for OneBot consumers - manager.ts ── per-uin BridgeManager hub - apis/* ── the 13 typed Api classes - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim BridgeContext with `apis: ApiHub` so the 13 Api classes keep their typed `this.ctx.apis.X.method()` access. Layout ------ Moved via `git mv` (history preserved): events / event-bus / identity-service / packet-pipeline / element-builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* → @snowluma/bridge/<sub> utils/event-format.ts → @snowluma/bridge/format.ts (the last one renamed because the destination directory only has bridge-related files; `format.ts` reads cleaner than `event-format`. Listed as a rename in git's `RM` output — content unchanged.) Layering fixes (functionality preserved, just type signatures) -------------------------------------------------------------- - `element-builder.SendContext.bridge` → typed as `BridgeContext` instead of `Bridge`. Reads only `bridge.identity` and the upload-cache (both on BridgeContext); the concrete `Bridge` instance still passes via free upcast. - `bridge-oidb.runOidb` signature widened from `Bridge` to `BridgeContext` — same reason. - `highway/{highway-client,pipeline,image-upload,ptt-upload, video-upload}.ts` — same. - `format.ts::formatReply` parameter typed as a new local `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject | null }`) instead of `MessageStore` from @snowluma/onebot. The OneBot `MessageStore` is a structural superset; consumers pass it through unchanged. - JSON value types moved to a new `@snowluma/common/json` subpath (consumed by format.ts) — `onebot/types.ts` re-exports them so external `import { JsonValue } from '<…>/onebot/types'` paths keep working. - `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts` into `@snowluma/bridge/bridge-context.ts` — element-builder + the forward-builder both read the upload cache through BridgeContext, so the type has to live in @snowluma/bridge. `bridge.ts` keeps its re-export for back-compat. Changes ------- - New package `packages/bridge/` (package.json with per-file subpath exports mirroring legacy `core/src/bridge/<x>` layout 1:1, tsconfig.json, typecheck script). - 35 `.ts` files moved via `git mv` (3 files counted by git as RM — rename + modify because Bridge → BridgeContext type swap). - 150+ import sites rewritten across `packages/core/src` and `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`, `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`. - `@snowluma/core` depends on `@snowluma/bridge` (workspace:*). - `@snowluma/bridge` depends on `@snowluma/common`, `@snowluma/proto-defs`, `@snowluma/proton`. - `packages/core/src/utils/` directory removed (empty). Verification ------------ - Full workspace `pnpm -r typecheck`: all 10 projects clean. - core test suite: 552 passed / 552 total (pre-existing websocket-darwin-arm64.node addon failure unchanged — same baseline as the previous refactor commits). - Vite build (with stubbed native binary): clean — 143 modules, 2.84 MB bundle / 224 KB gzip, identical envelope to the pre-split build. Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The runnable `index.ts` stays in @snowluma/core as the application entry, importing `OneBotManager` from `@snowluma/onebot`.
This commit is contained in:
107 files changed
+467
-229
No files matched your search
@@ -33,7 +33,7 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { DownloadRKeyInfo } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type {
|
||||
FriendInfo,
|
||||
@@ -41,7 +41,7 @@ import type {
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '../qq-info';
|
||||
} from '@snowluma/bridge/qq-info';
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import type {
|
||||
import type { MediaIndexNode } from './shared';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
|
||||
@@ -23,9 +23,9 @@ import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/messa
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { buildSendElems } from '../element-builder';
|
||||
import type { ForwardNodePayload, MessageElement } from '../events';
|
||||
import { parseMsgPush } from '../msg-push';
|
||||
import { buildSendElems } from '@snowluma/bridge/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/events';
|
||||
import { parseMsgPush } from '@snowluma/bridge/msg-push';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
@@ -13,7 +13,7 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { getGroupAlbumList, uploadImageToGroupAlbum } from '../web/group-album';
|
||||
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/bridge/web/group-album';
|
||||
// `getCookies` is part of WebApi — go through the hub so we don't
|
||||
// duplicate the cookie acquisition flow.
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@ import { toHexUpper } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/bridge/highway/utils';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
|
||||
@@ -17,7 +17,7 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@ import type {
|
||||
GroupRecallRequest,
|
||||
SsoReadedReportReq,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { MessageElement } from '../events';
|
||||
import { buildSendElems } from '../element-builder';
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
import { buildSendElems } from '@snowluma/bridge/element-builder';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
// `Bridge` is imported as a type only so we can narrow `ctx` back to
|
||||
// the concrete Bridge instance when passing it to `buildSendElems`
|
||||
|
||||
@@ -17,7 +17,7 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
|
||||
@@ -22,9 +22,9 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
|
||||
import { computeHashes, loadBinarySource } from '../highway/utils';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/bridge/highway/utils';
|
||||
import { resolveSelfUid } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
@@ -14,16 +14,16 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '../web/group-essence';
|
||||
import { getHonorListWebAPI, WebHonorType } from '../web/group-honor';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '@snowluma/bridge/web/group-essence';
|
||||
import { getHonorListWebAPI, WebHonorType } from '@snowluma/bridge/web/group-honor';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
getGroupNoticeWebAPI,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
} from '../web/group-notice';
|
||||
import { RequestUtil } from '../web/request-util';
|
||||
} from '@snowluma/bridge/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/bridge/web/request-util';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
|
||||
@@ -1,67 +1,27 @@
|
||||
// BridgeContext — the surface that Api classes (and any external
|
||||
// consumer that doesn't need the full Bridge concrete class) see.
|
||||
// Api-layer extension of @snowluma/bridge's slim BridgeContext.
|
||||
//
|
||||
// Replaces the previous `BridgeInterface`, which had grown to ~170 lines
|
||||
// listing every Bridge method one-by-one and was a maintenance burden
|
||||
// (every new feature meant +1 signature here, +1 method on Bridge, +1
|
||||
// stub in `mockBridge`). The new design splits business methods OUT to
|
||||
// `apis.xxx.method()` — this interface now carries only the
|
||||
// "infrastructure" surface every Api class needs:
|
||||
// The slim interface in @snowluma/bridge has the protocol-layer
|
||||
// surface (identity / events / sendRawPacket / resolveUserUid / next*
|
||||
// sequence helpers / upload-metadata cache). This file extends it
|
||||
// with `apis: ApiHub` — the typed bag of Api classes that lives ONLY
|
||||
// in @snowluma/core, so the bridge package never sees it (avoiding
|
||||
// a bridge → core cycle).
|
||||
//
|
||||
// - state: identity / events / apis (per-instance)
|
||||
// - raw I/O: sendRawPacket, resolveUserUid
|
||||
// - protocol helpers: nextMessageRandom / nextClientSequence
|
||||
// - upload metadata cache: rememberUploadedFile / recallUploadedFile
|
||||
//
|
||||
// Anything beyond that lives in `apis.<area>.method()` — see
|
||||
// `bridge/apis/index.ts` for the ApiHub shape.
|
||||
//
|
||||
// The concrete `Bridge` class still `implements BridgeContext`, so
|
||||
// passing a `Bridge` where a `BridgeContext` is expected is a free
|
||||
// upcast. Test fakes go the other direction: build a small object that
|
||||
// only stubs the fields under test (instead of the previous 70+ method
|
||||
// `MockBridge` god-object) and pass it as `BridgeContext`.
|
||||
// The 13 Api classes (apis/<area>.ts) import `BridgeContext` from
|
||||
// here, which gives them `this.ctx.apis.message.sendGroup(...)` type-
|
||||
// safety alongside the protocol-layer fields. Highway uploaders,
|
||||
// element-builder, msg-push parsers (all in @snowluma/bridge) import
|
||||
// the slim version directly from `@snowluma/bridge/bridge-context`.
|
||||
|
||||
import type { IdentityService } from './identity-service';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import type { BridgeContext as BaseBridgeContext } from '@snowluma/bridge/bridge-context';
|
||||
import type { ApiHub } from './apis';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { UploadedFileMeta } from './bridge';
|
||||
|
||||
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;
|
||||
export interface BridgeContext extends BaseBridgeContext {
|
||||
readonly apis: ApiHub;
|
||||
|
||||
// ── Raw I/O ──
|
||||
/** Escape hatch for arbitrary protocol calls (used by Api classes
|
||||
* and by the `send_packet` OneBot action). Every typed wrapper on an
|
||||
* Api class eventually routes through here. */
|
||||
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
/** uin → uid lookup (cached in IdentityService). `groupId` is an
|
||||
* optional hint that lets the resolver fall back to a group-member
|
||||
* roster when the friend list doesn't have the uin. */
|
||||
resolveUserUid(uin: number, groupId?: number): Promise<string>;
|
||||
|
||||
// ── Send-side protocol helpers (Api classes that build a
|
||||
// `SendMessageRequest` need these monotonic generators to fill in
|
||||
// `clientSequence` and `random`). They were previously `private`
|
||||
// on Bridge — promoted to public so the new Api classes can call
|
||||
// them without `(bridge as any).nextXxx()`. ──
|
||||
nextMessageRandom(): number;
|
||||
nextClientSequence(): number;
|
||||
|
||||
// ── Uploaded-file metadata cache ──
|
||||
//
|
||||
// Bookkeeping shared between `GroupFileApi.upload*File` (writes the
|
||||
// tuple at upload time) and `MessageApi.sendPrivateMessage` (reads
|
||||
// it on later `send_msg` calls that carry only a file_id). Lives at
|
||||
// this layer rather than inside `GroupFileApi` because the message
|
||||
// send path is what queries the cache, and it shouldn't have to
|
||||
// reach into a different Api class for an infrastructure lookup.
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void;
|
||||
recallUploadedFile(fileId: string): UploadedFileMeta | undefined;
|
||||
}
|
||||
|
||||
// Re-export `UploadedFileMeta` from the slim package so existing
|
||||
// `import type { UploadedFileMeta } from '<…>/bridge-context'` (or
|
||||
// from bridge.ts via re-export) keeps working without callers having
|
||||
// to learn the new package path.
|
||||
export type { UploadedFileMeta } from '@snowluma/bridge/bridge-context';
|
||||
@@ -1,66 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { Bridge } from './bridge';
|
||||
import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb';
|
||||
|
||||
/**
|
||||
* Build the OidbBase<T>-shaped TS value. Pure helper, no protobuf
|
||||
* encoding happens here — pair with `encodeOidbEnv<T>` to produce the
|
||||
* wire bytes.
|
||||
*
|
||||
* The `isUid` flag sets the envelope `reserved` field to 1; despite the
|
||||
* name (kept for back-compat with the legacy API), `reserved = 1`
|
||||
* empirically signals the UIN-form variant of an OIDB call. Omit
|
||||
* (default false) for genuinely UID-keyed calls.
|
||||
*/
|
||||
export function makeOidbEnvelope<T>(
|
||||
oidbCmd: number,
|
||||
subCmd: number,
|
||||
body: T,
|
||||
isUid: boolean = false,
|
||||
): OidbBase<T> {
|
||||
return {
|
||||
command: oidbCmd,
|
||||
subCommand: subCmd,
|
||||
errorCode: 0,
|
||||
body,
|
||||
errorMsg: '',
|
||||
reserved: isUid ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Issue one OIDB request and return the raw response bytes.
|
||||
*
|
||||
* Typical usage:
|
||||
* const env = makeOidbEnvelope<MyReq>(0x1253, 1, value);
|
||||
* const buf = await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
|
||||
* const resp = decodeOidbEnv<MyResp>(buf).body;
|
||||
*
|
||||
* Fire-and-check (no body decode):
|
||||
* await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
|
||||
*
|
||||
* Always peeks at the envelope errorCode via the non-generic
|
||||
* `OidbBaseMeta` view so a server-side rejection cannot slip past
|
||||
* silently. Returns the raw response bytes (empty `Uint8Array` if the
|
||||
* packet carried no payload).
|
||||
*/
|
||||
export async function runOidb(
|
||||
bridge: Bridge,
|
||||
cmd: string,
|
||||
envelopeBytes: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<Uint8Array> {
|
||||
const result = await bridge.sendRawPacket(cmd, envelopeBytes, timeoutMs);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||
|
||||
const bytes = result.responseData ?? new Uint8Array(0);
|
||||
if (bytes.length > 0) {
|
||||
const meta = protobuf_decode<OidbBaseMeta>(bytes);
|
||||
const code = meta?.errorCode;
|
||||
if (code && code !== 0) {
|
||||
throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`);
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
import { IdentityService } from './identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
|
||||
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
|
||||
import { IdentityService } from '@snowluma/bridge/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/bridge/msg-push';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/bridge/packet-pipeline';
|
||||
// qq-info types are no longer used directly in this file — they live
|
||||
// inside the Api classes that own those fetches (apis/contacts.ts).
|
||||
import { type ApiHub, buildApiHub } from './apis';
|
||||
@@ -35,7 +35,7 @@ import type { GroupFilesResult } from './apis/group-file';
|
||||
// actions/profile.ts removed — moved to apis/profile.ts::ProfileApi.
|
||||
// `bridge-contacts.ts` removed — its 6 functions are now methods on
|
||||
// `apis.contacts` (see `apis/contacts.ts::ContactsApi`).
|
||||
import { BridgeEventBus } from './event-bus';
|
||||
import { BridgeEventBus } from '@snowluma/bridge/event-bus';
|
||||
// web-actions/* removed — moved to apis/web.ts::WebApi.
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
|
||||
@@ -1,452 +0,0 @@
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { Bridge } from './bridge';
|
||||
import type { MessageElement } from './events';
|
||||
import { uploadImageMsgInfo } from './highway/image-upload';
|
||||
import { hexToBytes } from './highway/pipeline';
|
||||
import { uploadPttMsgInfo } from './highway/ptt-upload';
|
||||
import { uploadVideoMsgInfo } from './highway/video-upload';
|
||||
import type {
|
||||
MarkdownData,
|
||||
MentionExtraSend,
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element';
|
||||
|
||||
type ProtoElem = Partial<Elem>;
|
||||
|
||||
export interface SendContext {
|
||||
bridge: Bridge;
|
||||
groupId?: number;
|
||||
userUid?: string;
|
||||
/**
|
||||
* Set by the forward-message upload path. When `true`, file segments
|
||||
* are encoded as receive-side wire shapes (group → `transElem(24)`,
|
||||
* c2c → caller writes `body.msgContent` separately) instead of being
|
||||
* dropped. The QQ-NT server rejects outgoing PbSendMsg with
|
||||
* `transElem(24)` (result=79), but the long-msg upload service does
|
||||
* NOT — it stores the gzipped protobuf verbatim, so the receiver
|
||||
* can walk it back through the regular decoder. Mirrors NapCat's
|
||||
* `PacketMsgFileElement.buildElement` + `buildContent` split (see
|
||||
* `dev/napcatQQ/.../packet/message/element.ts:530-610`).
|
||||
*/
|
||||
forwardFake?: boolean;
|
||||
}
|
||||
|
||||
function makeTextElem(text: string): ProtoElem {
|
||||
return {
|
||||
text: { str: text } as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFaceElem(faceId: number): ProtoElem {
|
||||
return {
|
||||
face: { index: faceId } as any,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
|
||||
if (!ctx || !targetUin) return '';
|
||||
if (ctx.groupId !== undefined) {
|
||||
const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin);
|
||||
return member?.card?.trim() || member?.nickname?.trim() || '';
|
||||
}
|
||||
const friend = ctx.bridge.identity.findFriend(targetUin);
|
||||
return friend?.remark?.trim() || friend?.nickname?.trim() || '';
|
||||
}
|
||||
|
||||
function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem {
|
||||
const mentionAll = element.uid === 'all' || element.targetUin === 0;
|
||||
const targetUin = element.targetUin ?? 0;
|
||||
|
||||
const extra = protobuf_encode<MentionExtraSend>({
|
||||
type: mentionAll ? 1 : 2,
|
||||
uin: mentionAll ? 0 : targetUin,
|
||||
field5: 0,
|
||||
uid: mentionAll ? 'all' : (element.uid ?? ''),
|
||||
});
|
||||
|
||||
// Prefer an explicit display string from the caller; otherwise look the
|
||||
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
|
||||
// Falls back to the bare uin when the roster doesn't know them yet.
|
||||
let str = element.text;
|
||||
if (!str) {
|
||||
if (mentionAll) {
|
||||
str = '@全体成员 ';
|
||||
} else {
|
||||
const name = resolveMentionDisplay(ctx, targetUin);
|
||||
str = name ? `@${name} ` : `@${targetUin} `;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text: {
|
||||
str,
|
||||
pbReserve: extra,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeReplyElem(element: MessageElement): ProtoElem {
|
||||
const seq = element.replySeq! & 0xFFFFFFFF;
|
||||
|
||||
const srcMsg: any = {
|
||||
origSeqs: [seq],
|
||||
};
|
||||
|
||||
// Add additional fields if available for better reply display
|
||||
if (element.replySenderUin) {
|
||||
srcMsg.senderUin = BigInt(element.replySenderUin);
|
||||
}
|
||||
if (element.replyTime) {
|
||||
srcMsg.time = element.replyTime;
|
||||
}
|
||||
|
||||
return { srcMsg };
|
||||
}
|
||||
|
||||
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 1,
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeXmlElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeMarkdownElem(element: MessageElement): ProtoElem {
|
||||
const data = protobuf_encode<MarkdownData>({ content: element.text ?? '' });
|
||||
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 45,
|
||||
pbElem: data,
|
||||
businessType: 1,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
const resId = (element.resId ?? '').trim();
|
||||
if (!resId) {
|
||||
throw new Error('forward resId is required');
|
||||
}
|
||||
|
||||
// Multi-msg preview bubble — modelled on the go-cqhttp / NapCat XML.
|
||||
// `source` becomes the bold header (e.g. "群聊的聊天记录"), `news`
|
||||
// entries become per-line previews ("nick: text"), `summary` is the
|
||||
// grey footer ("查看 N 条转发消息"), `prompt` is the chat-list brief.
|
||||
const source = element.forwardSource && element.forwardSource.length > 0
|
||||
? element.forwardSource
|
||||
: '聊天记录';
|
||||
const summary = element.forwardSummary && element.forwardSummary.length > 0
|
||||
? element.forwardSummary
|
||||
: '查看转发消息';
|
||||
const prompt = element.forwardPrompt && element.forwardPrompt.length > 0
|
||||
? element.forwardPrompt
|
||||
: '[聊天记录]';
|
||||
const news = Array.isArray(element.forwardNews) ? element.forwardNews : [];
|
||||
const tSum = element.forwardTSum && element.forwardTSum > 0
|
||||
? element.forwardTSum
|
||||
: Math.max(news.length, 1);
|
||||
|
||||
const newsTitles = news
|
||||
.map(n => `<title size="26" color="#777777">${escapeXml(n.text ?? '')}</title>`)
|
||||
.join('');
|
||||
|
||||
const resIdAttr = escapeXml(resId);
|
||||
const xml =
|
||||
`<?xml version="1.0" encoding="utf-8"?>` +
|
||||
`<msg templateID="1" action="viewMultiMsg" serviceID="35"` +
|
||||
` brief="${escapeXml(prompt)}"` +
|
||||
` m_resid="${resIdAttr}" m_fileName="${resIdAttr}" actionData="${resIdAttr}"` +
|
||||
` tSum="${tSum}" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0">` +
|
||||
`<item layout="1">` +
|
||||
`<title size="34" color="#000000">${escapeXml(source)}</title>` +
|
||||
newsTitles +
|
||||
`<hr hidden="false" style="0"/>` +
|
||||
`<summary size="26" color="#808080">${escapeXml(summary)}</summary>` +
|
||||
`</item>` +
|
||||
`<source name="${escapeXml(source)}" icon="" action="" appid="-1"/>` +
|
||||
`</msg>`;
|
||||
|
||||
const encodedXml = new TextEncoder().encode(xml);
|
||||
const payload = new Uint8Array(encodedXml.length + 1);
|
||||
payload[0] = 0x00;
|
||||
payload.set(encodedXml, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 35,
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function makeImageElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||
const isGroup = ctx.groupId !== undefined;
|
||||
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||
if (!isGroup && !targetIdOrUid) {
|
||||
throw new Error('private image target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: isGroup ? 20 : 10,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function makePttElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||
const isGroup = ctx.groupId !== undefined;
|
||||
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||
if (!isGroup && !targetIdOrUid) {
|
||||
throw new Error('private record target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
// commonElem.businessType is the QQ NT scene tag the receive-side
|
||||
// decoder pairs with: 12=c2c, 22=group. Sending the group tag on a
|
||||
// c2c message bounces with PbSendMsg result=79.
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: isGroup ? 22 : 12,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Receive-side group file element shape — `transElem(elemType=24,
|
||||
* elemValue: 0x01 | BE16(len) | GroupFileExtra)`.
|
||||
*
|
||||
* NOT used for outgoing PbSendMsg (the QQ-NT server rejects that with
|
||||
* result=79); the group-file send-side flow goes through dedicated
|
||||
* OIDB 0x6d9_4 via `bridge.apis.groupFile.publish`. This shape IS used
|
||||
* inside the long-msg upload (forward / multi-msg) — the long-msg
|
||||
* service stores the gzipped protobuf verbatim, and the receiver
|
||||
* decodes file entities from `transElem(24)` (see
|
||||
* `msg-push/rich-body-decoder.ts:169-187`).
|
||||
*
|
||||
* `ctx` is consulted to fill in size/name/md5/sha1 from the upload
|
||||
* metadata cache when the caller only threaded the file_id through.
|
||||
* Mirrors the c2c forward path in `apis/forward.ts::buildForwardPushBody`
|
||||
* which already does this lookup — without it the receiver sees a
|
||||
* "0 B" file with no name (OneBot11 `{type:'file', file_id}` segments
|
||||
* typically omit the metadata since the upload action returned only
|
||||
* the id).
|
||||
*/
|
||||
function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoElem {
|
||||
if (!element.fileId) throw new Error('file element missing fileId');
|
||||
const cached = ctx?.bridge.recallUploadedFile(element.fileId);
|
||||
const fileSize = element.fileSize ?? cached?.fileSize ?? 0;
|
||||
const fileName = element.fileName ?? cached?.fileName ?? '';
|
||||
const md5 = element.md5Hex
|
||||
? hexToBytes(element.md5Hex)
|
||||
: (cached?.fileMd5 ?? new Uint8Array(0));
|
||||
const sha1 = element.sha1Hex
|
||||
? hexToBytes(element.sha1Hex)
|
||||
: (cached?.fileSha1 ?? new Uint8Array(0));
|
||||
|
||||
// Outer field1 is hardcoded to 6 in NapCat's encoder
|
||||
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
|
||||
// busId=102 + the file_id + name + size + sha1/md5 hashes.
|
||||
const extraBytes = protobuf_encode<GroupFileExtra>({
|
||||
field1: 6,
|
||||
fileName,
|
||||
inner: {
|
||||
info: {
|
||||
busId: 102,
|
||||
fileId: element.fileId,
|
||||
fileSize: BigInt(fileSize),
|
||||
fileName,
|
||||
fileSha: sha1,
|
||||
extInfoString: '',
|
||||
fileMd5: md5,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (extraBytes.length > 0xFFFF) {
|
||||
// The 16-bit length prefix caps the payload at 64 KiB; even the
|
||||
// densest GroupFileExtra (fileId/name/two hashes) is well under.
|
||||
throw new Error(`group file extra too large (${extraBytes.length} > 65535)`);
|
||||
}
|
||||
const elemValue = new Uint8Array(3 + extraBytes.length);
|
||||
elemValue[0] = 0x01;
|
||||
elemValue[1] = (extraBytes.length >> 8) & 0xff;
|
||||
elemValue[2] = extraBytes.length & 0xff;
|
||||
elemValue.set(extraBytes, 3);
|
||||
|
||||
return {
|
||||
transElem: {
|
||||
elemType: 24,
|
||||
elemValue,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||
const isGroup = ctx.groupId !== undefined;
|
||||
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||
if (!isGroup && !targetIdOrUid) {
|
||||
throw new Error('private video target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
// commonElem.businessType is the QQ NT scene tag the receive-side
|
||||
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
|
||||
// c2c message bounces with PbSendMsg result=79.
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: isGroup ? 21 : 11,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build proto Elem objects from an array of MessageElements.
|
||||
* Supports: text, face, at, reply, json, xml, markdown, image, record, video, forward.
|
||||
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
|
||||
*/
|
||||
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
|
||||
const result: ProtoElem[] = [];
|
||||
|
||||
for (const elem of elements) {
|
||||
switch (elem.type) {
|
||||
case 'text':
|
||||
if (elem.text) result.push(makeTextElem(elem.text));
|
||||
break;
|
||||
|
||||
case 'face':
|
||||
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
|
||||
break;
|
||||
|
||||
case 'at':
|
||||
result.push(makeMentionElem(elem, ctx));
|
||||
break;
|
||||
|
||||
case 'reply':
|
||||
if (elem.replySeq) result.push(makeReplyElem(elem));
|
||||
break;
|
||||
|
||||
case 'json':
|
||||
if (elem.text) result.push(makeJsonElem(elem));
|
||||
break;
|
||||
|
||||
case 'xml':
|
||||
if (elem.text) result.push(makeXmlElem(elem));
|
||||
break;
|
||||
|
||||
case 'markdown':
|
||||
if (elem.text) result.push(makeMarkdownElem(elem));
|
||||
break;
|
||||
|
||||
case 'image':
|
||||
if (ctx) {
|
||||
result.push(await makeImageElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] image send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'forward':
|
||||
if (elem.resId) result.push(makeForwardElem(elem));
|
||||
break;
|
||||
|
||||
case 'record':
|
||||
if (ctx) {
|
||||
result.push(await makePttElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] record send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'video':
|
||||
if (ctx) {
|
||||
result.push(await makeVideoElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] video send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'file':
|
||||
// Files split into two routes depending on whether this is a
|
||||
// live send or a forward-message fake-send:
|
||||
//
|
||||
// 1. LIVE send (PbSendMsg / OIDB 0x6d9_4) — never carried on
|
||||
// elems[]. The OneBot layer splits file segments off before
|
||||
// calling buildSendElems:
|
||||
// * c2c (private): split → `bridge.sendC2cFileMessage`
|
||||
// (routingHead.trans0x211 + msgContent FileExtra).
|
||||
// * group: split → `bridge.sendGroupFileMessage`
|
||||
// (OIDB 0x6d9_4 publish).
|
||||
// The QQ-NT server REJECTS outgoing PbSendMsg with a
|
||||
// transElem(24) (result=79), so an element reaching here
|
||||
// in live-send mode is a routing bug — drop with a warn.
|
||||
//
|
||||
// 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`.
|
||||
// The long-msg service stores the gzipped protobuf verbatim
|
||||
// and the receiver decodes file entities from transElem(24)
|
||||
// + msgContent FileExtra. Mirror NapCat's split (see
|
||||
// `dev/napcatQQ/.../packet/message/element.ts:530-610`):
|
||||
// * group → emit transElem(24) via makeGroupFileElem
|
||||
// * c2c → emit NOTHING here; the forward-builder pulls
|
||||
// the file segment off and writes msgContent
|
||||
// separately (because RichText.notOnlineFile +
|
||||
// FileExtra both live outside elems[]).
|
||||
if (ctx && ctx.forwardFake) {
|
||||
if (ctx.groupId !== undefined) {
|
||||
result.push(makeGroupFileElem(elem, ctx));
|
||||
}
|
||||
// c2c forwardFake intentionally falls through — handled by
|
||||
// the forward-builder at the msgContent level.
|
||||
} else {
|
||||
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { QQEventVariant } from './events';
|
||||
|
||||
type EventKind = QQEventVariant['kind'];
|
||||
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;
|
||||
|
||||
export type EventHandler<K extends EventKind> = (event: EventOf<K>) => void | Promise<void>;
|
||||
export type AnyEventHandler = (event: QQEventVariant) => void | Promise<void>;
|
||||
|
||||
export interface EventBusOptions {
|
||||
/** Logger label for handler failures. Defaults to `Bridge.Events`. */
|
||||
loggerName?: string;
|
||||
/** Override the default error reporter (e.g. for tests). */
|
||||
onError?: (kind: EventKind | '*', err: unknown) => void;
|
||||
}
|
||||
|
||||
const DEFAULT_LOGGER = createLogger('Bridge.Events');
|
||||
|
||||
export class BridgeEventBus {
|
||||
// Per-kind subscribers are stored as `Set<unknown>` so the container
|
||||
// doesn't carry a contravariant function type that fights TS variance
|
||||
// rules. The runtime invariant is straightforward: handlers stored under
|
||||
// key `K` only ever see `EventOf<K>` events, which is what the single
|
||||
// narrowing cast at the dispatch site below relies on.
|
||||
private readonly handlers = new Map<EventKind, Set<unknown>>();
|
||||
private readonly anyHandlers = new Set<AnyEventHandler>();
|
||||
private readonly onError: (kind: EventKind | '*', err: unknown) => void;
|
||||
|
||||
constructor(opts: EventBusOptions = {}) {
|
||||
if (opts.onError) {
|
||||
this.onError = opts.onError;
|
||||
} else {
|
||||
const log = opts.loggerName ? createLogger(opts.loggerName) : DEFAULT_LOGGER;
|
||||
this.onError = (kind, err) => {
|
||||
log.error(
|
||||
'event handler error [%s]: %s',
|
||||
kind,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe to one kind. Returns an unsubscribe function. */
|
||||
on<K extends EventKind>(kind: K, handler: EventHandler<K>): () => void {
|
||||
let set = this.handlers.get(kind);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.handlers.set(kind, set);
|
||||
}
|
||||
set.add(handler);
|
||||
return () => {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
/** Subscribe to every kind (low-volume callers like loggers). */
|
||||
onAny(handler: AnyEventHandler): () => void {
|
||||
this.anyHandlers.add(handler);
|
||||
return () => {
|
||||
this.anyHandlers.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
off<K extends EventKind>(kind: K, handler: EventHandler<K>): void {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
}
|
||||
|
||||
has(kind: EventKind): boolean {
|
||||
return (this.handlers.get(kind)?.size ?? 0) + this.anyHandlers.size > 0;
|
||||
}
|
||||
|
||||
/** Drop every subscriber. Mostly useful for tests. */
|
||||
clear(): void {
|
||||
this.handlers.clear();
|
||||
this.anyHandlers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch an event in parallel to every subscriber for its kind plus every
|
||||
* onAny handler. Rejections are isolated per-handler — one bad subscriber
|
||||
* never blocks the others, and the returned promise resolves once every
|
||||
* subscriber settles.
|
||||
*/
|
||||
async emit<K extends EventKind>(event: EventOf<K>): Promise<void> {
|
||||
const kindHandlers = this.handlers.get(event.kind);
|
||||
if ((!kindHandlers || kindHandlers.size === 0) && this.anyHandlers.size === 0) {
|
||||
return;
|
||||
}
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
if (kindHandlers) {
|
||||
for (const handler of kindHandlers) {
|
||||
// Single narrowing cast — the only place we re-assert that handlers
|
||||
// stored under `event.kind` accept `EventOf<event.kind>` events.
|
||||
const typed = handler as EventHandler<K>;
|
||||
tasks.push(invoke(this.onError, event.kind, () => typed(event)));
|
||||
}
|
||||
}
|
||||
for (const handler of this.anyHandlers) {
|
||||
tasks.push(invoke(this.onError, '*', () => handler(event)));
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
}
|
||||
|
||||
async function invoke(
|
||||
onError: (kind: EventKind | '*', err: unknown) => void,
|
||||
kind: EventKind | '*',
|
||||
fn: () => unknown,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const ret = fn();
|
||||
if (ret && typeof (ret as Promise<unknown>).then === 'function') {
|
||||
await ret;
|
||||
}
|
||||
} catch (err) {
|
||||
onError(kind, err);
|
||||
}
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
export interface MessageElement {
|
||||
type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward'
|
||||
text?: string;
|
||||
faceId?: number;
|
||||
targetUin?: number;
|
||||
uid?: string;
|
||||
imageUrl?: string;
|
||||
fileId?: string;
|
||||
thumbFileId?: string;
|
||||
fileName?: string;
|
||||
fileSize?: number;
|
||||
replySeq?: number;
|
||||
replyMessageId?: number; // For reply: original message ID (for logging)
|
||||
replySenderUin?: number; // For reply: original sender's UIN
|
||||
replyTime?: number; // For reply: original message timestamp
|
||||
replyRandom?: number; // For reply: original message random/msgId
|
||||
url?: string;
|
||||
thumbUrl?: string;
|
||||
subType?: number;
|
||||
duration?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
summary?: string;
|
||||
flash?: boolean;
|
||||
resId?: string;
|
||||
fileHash?: string;
|
||||
// Preview-bubble metadata for the `forward` element. Drives the XML
|
||||
// template (brief/title/news/summary/tSum) the recipient renders before
|
||||
// they tap to expand. When unset, the element builder falls back to
|
||||
// generic defaults so old call sites keep working.
|
||||
forwardSource?: string;
|
||||
forwardSummary?: string;
|
||||
forwardPrompt?: string;
|
||||
forwardNews?: Array<{ text: string }>;
|
||||
forwardTSum?: number;
|
||||
// Server-side fingerprints carried from receive side so a forward can do a
|
||||
// pure md5/sha1 fast-upload without re-downloading the original bytes.
|
||||
// Set together with `noByteFallback: true` to make the upload modules throw
|
||||
// instead of falling back to fetch(url).
|
||||
md5Hex?: string;
|
||||
sha1Hex?: string;
|
||||
picFormat?: number;
|
||||
videoFormat?: number;
|
||||
voiceFormat?: number;
|
||||
noByteFallback?: boolean;
|
||||
mediaNode?: {
|
||||
fileUuid?: string;
|
||||
storeId?: number;
|
||||
uploadTime?: number;
|
||||
ttl?: number;
|
||||
subType?: number;
|
||||
info?: {
|
||||
fileSize?: number;
|
||||
fileHash?: string;
|
||||
fileSha1?: string;
|
||||
fileName?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
time?: number;
|
||||
original?: number;
|
||||
type?: {
|
||||
type?: number;
|
||||
picFormat?: number;
|
||||
videoFormat?: number;
|
||||
voiceFormat?: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export interface ForwardNodePayload {
|
||||
userUin: number;
|
||||
nickname: string;
|
||||
elements: MessageElement[];
|
||||
// Optional context preserved when known (download path or upload-via-id),
|
||||
// so `get_forward_msg` can emit OneBot11-compatible OB11Message objects.
|
||||
time?: number;
|
||||
msgId?: number;
|
||||
msgSeq?: number;
|
||||
groupId?: number;
|
||||
senderCard?: string;
|
||||
messageType?: 'group' | 'private';
|
||||
// When set, this node's `content` is a nested forward chain. The
|
||||
// upload pipeline (see `actions/forward.ts::uploadForwardNodes`)
|
||||
// recursively uploads the inner chain and replaces this node's
|
||||
// `elements` with an ARK preview element pointing at the inner
|
||||
// res_id. We also piggyback the inner chain's msgBody onto the
|
||||
// outer long-msg upload as an extra `actionCommand` slot so the
|
||||
// NapCat-compatible receiver can walk the whole tree from one
|
||||
// server fetch without resolving each layer's res_id separately
|
||||
// (modelled after `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`).
|
||||
// Caller never sets this on top-level OneBot input — `parseForward
|
||||
// Nodes` synthesises it when it detects a nested-node array.
|
||||
innerForward?: ForwardNodePayload[];
|
||||
}
|
||||
|
||||
export interface QQEvent {
|
||||
time: number;
|
||||
selfUin: number;
|
||||
}
|
||||
|
||||
export interface FriendMessage extends QQEvent {
|
||||
kind: 'friend_message';
|
||||
senderUin: number;
|
||||
senderNick: string;
|
||||
msgSeq: number;
|
||||
msgId: number;
|
||||
elements: MessageElement[];
|
||||
}
|
||||
|
||||
export interface GroupMessage extends QQEvent {
|
||||
kind: 'group_message';
|
||||
groupId: number;
|
||||
senderUin: number;
|
||||
senderNick: string;
|
||||
senderCard: string;
|
||||
senderRole: string;
|
||||
msgSeq: number;
|
||||
msgId: number;
|
||||
elements: MessageElement[];
|
||||
}
|
||||
|
||||
export interface TempMessage extends QQEvent {
|
||||
kind: 'temp_message';
|
||||
senderUin: number;
|
||||
groupId: number;
|
||||
senderNick: string;
|
||||
msgSeq: number;
|
||||
elements: MessageElement[];
|
||||
}
|
||||
|
||||
export interface GroupMemberJoin extends QQEvent {
|
||||
kind: 'group_member_join';
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
operatorUin: number;
|
||||
userUid?: string;
|
||||
operatorUid?: string;
|
||||
}
|
||||
|
||||
export interface GroupMemberLeave extends QQEvent {
|
||||
kind: 'group_member_leave';
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
operatorUin: number;
|
||||
userUid?: string;
|
||||
operatorUid?: string;
|
||||
isKick: boolean;
|
||||
}
|
||||
|
||||
export interface GroupMuteEvent extends QQEvent {
|
||||
kind: 'group_mute';
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
operatorUin: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export interface GroupAdminEvent extends QQEvent {
|
||||
kind: 'group_admin';
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
set: boolean;
|
||||
}
|
||||
|
||||
export interface FriendRecall extends QQEvent {
|
||||
kind: 'friend_recall';
|
||||
userUin: number;
|
||||
msgSeq: number;
|
||||
}
|
||||
|
||||
export interface GroupRecallEvent extends QQEvent {
|
||||
kind: 'group_recall';
|
||||
groupId: number;
|
||||
operatorUin: number;
|
||||
authorUin: number;
|
||||
msgSeq: number;
|
||||
}
|
||||
|
||||
export interface FriendRequestEvent extends QQEvent {
|
||||
kind: 'friend_request';
|
||||
fromUin: number;
|
||||
fromUid?: string;
|
||||
message: string;
|
||||
flag: string;
|
||||
}
|
||||
|
||||
export interface GroupInviteEvent extends QQEvent {
|
||||
kind: 'group_invite';
|
||||
groupId: number;
|
||||
fromUin: number;
|
||||
fromUid?: string;
|
||||
subType: string;
|
||||
message: string;
|
||||
flag: string;
|
||||
}
|
||||
|
||||
export interface FriendPokeEvent extends QQEvent {
|
||||
kind: 'friend_poke';
|
||||
userUin: number;
|
||||
targetUin: number;
|
||||
action: string;
|
||||
suffix: string;
|
||||
actionImgUrl: string;
|
||||
}
|
||||
|
||||
export interface GroupPokeEvent extends QQEvent {
|
||||
kind: 'group_poke';
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
targetUin: number;
|
||||
action: string;
|
||||
suffix: string;
|
||||
actionImgUrl: string;
|
||||
}
|
||||
|
||||
export interface GroupEssenceEvent extends QQEvent {
|
||||
kind: 'group_essence';
|
||||
groupId: number;
|
||||
senderUin: number;
|
||||
operatorUin: number;
|
||||
msgSeq: number;
|
||||
random: number;
|
||||
set: boolean;
|
||||
}
|
||||
|
||||
export interface GroupFileUploadEvent extends QQEvent {
|
||||
kind: 'group_file_upload';
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
fileId: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
busId: number;
|
||||
}
|
||||
|
||||
export interface FriendAddEvent extends QQEvent {
|
||||
kind: 'friend_add';
|
||||
userUin: number;
|
||||
}
|
||||
|
||||
export interface GroupMsgEmojiLikeEvent extends QQEvent {
|
||||
kind: 'group_msg_emoji_like';
|
||||
groupId: number;
|
||||
operatorUin: number;
|
||||
operatorUid: string;
|
||||
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
|
||||
msgSeq: number;
|
||||
/** Emoji ID. QQ system faces are short numeric strings; market faces
|
||||
* are alphanumeric. We keep the wire string verbatim. */
|
||||
emojiId: string;
|
||||
/** Multiplicity of the reaction event. Usually 1. */
|
||||
count: number;
|
||||
/** True when the reaction is being added; false when removed. */
|
||||
isAdd: boolean;
|
||||
}
|
||||
|
||||
export type QQEventVariant =
|
||||
| FriendMessage
|
||||
| GroupMessage
|
||||
| TempMessage
|
||||
| GroupMemberJoin
|
||||
| GroupMemberLeave
|
||||
| GroupMuteEvent
|
||||
| GroupAdminEvent
|
||||
| FriendRecall
|
||||
| GroupRecallEvent
|
||||
| FriendRequestEvent
|
||||
| GroupInviteEvent
|
||||
| FriendPokeEvent
|
||||
| GroupPokeEvent
|
||||
| GroupEssenceEvent
|
||||
| GroupFileUploadEvent
|
||||
| FriendAddEvent
|
||||
| GroupMsgEmojiLikeEvent;
|
||||
@@ -1,154 +0,0 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface FFmpegVideoInfo {
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
format: string;
|
||||
videoCodec: string;
|
||||
image: Buffer;
|
||||
}
|
||||
|
||||
interface FFmpegNativeAddon {
|
||||
convertFile(inputFile: string, outputFile: string, format: string): Promise<{ success: boolean }>;
|
||||
getVideoInfo(filePath: string, format?: 'bmp' | 'bmp24'): Promise<FFmpegVideoInfo>;
|
||||
getDuration(filePath: string): Promise<number>;
|
||||
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
|
||||
decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>;
|
||||
decodeAudioToFmt(filePath: string, pcmPath: string, format: string): Promise<{ channels: number; sampleRate: number; format: string }>;
|
||||
}
|
||||
|
||||
let cachedAddon: FFmpegNativeAddon | null = null;
|
||||
let cachedLoadError: string | null = null;
|
||||
|
||||
function addonFileName(): string {
|
||||
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
||||
}
|
||||
|
||||
function addonSearchDirs(): string[] {
|
||||
// Mirrors the hook injector's resolution strategy so the addon is found
|
||||
// regardless of whether we're running from:
|
||||
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
|
||||
// the dist root.
|
||||
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
|
||||
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
|
||||
// __dirname is `packages/core/src/bridge/highway` — four levels deep
|
||||
// under `packages/`. Note: the hook injector lives at
|
||||
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
|
||||
return [
|
||||
path.resolve(__dirname, 'native', 'ffmpeg'),
|
||||
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
|
||||
];
|
||||
}
|
||||
|
||||
function resolveAddonPath(): string | null {
|
||||
const fileName = addonFileName();
|
||||
for (const dir of addonSearchDirs()) {
|
||||
const full = path.join(dir, fileName);
|
||||
if (fs.existsSync(full)) return full;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the ffmpegAddon once and return a cached instance.
|
||||
* Throws on first-use failure; subsequent calls replay the same error message
|
||||
* so callers don't silently fall back.
|
||||
*/
|
||||
export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
if (cachedAddon) return cachedAddon;
|
||||
if (cachedLoadError) throw new Error(cachedLoadError);
|
||||
|
||||
const addonPath = resolveAddonPath();
|
||||
if (!addonPath) {
|
||||
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
|
||||
try {
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
|
||||
return cachedAddon;
|
||||
} catch (error) {
|
||||
cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${error instanceof Error ? error.message : String(error)}`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether `filePath` is already an NT SILK container. The addon can
|
||||
* read any input directly so the only reason we peek at the header is to
|
||||
* skip the conversion (and the temp file) when the caller already fed us
|
||||
* a ready-to-upload silk file.
|
||||
*/
|
||||
export function isSilkFile(filePath: string): boolean {
|
||||
try {
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(10);
|
||||
fs.readSync(fd, buf, 0, 10, 0);
|
||||
const header = buf.toString();
|
||||
return header.includes('#!SILK') || header.includes('\x02#!SILK');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface EncodeSilkResult {
|
||||
/** Absolute path to the silk file ready for highway upload. */
|
||||
path: string;
|
||||
/** Voice duration in whole seconds (>= 1). */
|
||||
duration: number;
|
||||
/** `true` if we wrote a new silk file and the caller should unlink it. */
|
||||
converted: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert `inputFile` to NT SILK when necessary and return the output path
|
||||
* + duration. The caller is responsible for unlinking the returned path
|
||||
* when `converted === true`.
|
||||
*/
|
||||
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
|
||||
const addon = getFFmpegAddon();
|
||||
|
||||
// Already silk — trust the file, just measure duration via the addon.
|
||||
if (isSilkFile(inputFile)) {
|
||||
let duration = 1;
|
||||
try {
|
||||
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
} catch {
|
||||
// getDuration on a silk file occasionally fails on certain encodings;
|
||||
// the upload path only needs a rough, non-zero value, so fall back
|
||||
// to the size-based heuristic used by NapCat's audio.ts.
|
||||
const stat = fs.statSync(inputFile);
|
||||
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
|
||||
}
|
||||
return { path: inputFile, duration, converted: false };
|
||||
}
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
const outPath = path.join(tempDir, crypto.randomUUID());
|
||||
await addon.convertToNTSilkTct(inputFile, outPath);
|
||||
if (!fs.existsSync(outPath)) {
|
||||
throw new Error('convertToNTSilkTct produced no output file');
|
||||
}
|
||||
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
return { path: outPath, duration, converted: true };
|
||||
}
|
||||
|
||||
/** Default location for temporary silk files. */
|
||||
export function defaultPttTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-ptt');
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import net from 'net';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type {
|
||||
HttpConn0x6FF501Request,
|
||||
HttpConn0x6FF501Response,
|
||||
NTV2RichMediaHighwayExt,
|
||||
ReqDataHighwayHead,
|
||||
RespDataHighwayHead,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
|
||||
|
||||
const HIGHWAY_APP_ID = 1600001604;
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
export const PRIVATE_IMAGE_CMD_ID = 1003;
|
||||
export const GROUP_IMAGE_CMD_ID = 1004;
|
||||
|
||||
export interface HighwaySession {
|
||||
sigSession: Uint8Array;
|
||||
sessionKey: Uint8Array;
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
function ipv4ToString(value: number): string {
|
||||
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
|
||||
}
|
||||
|
||||
export async function fetchHighwaySession(bridge: Bridge): Promise<HighwaySession> {
|
||||
const request = protobuf_encode<HttpConn0x6FF501Request>({
|
||||
httpConn: {
|
||||
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
|
||||
serviceTypes: [1, 5, 10, 21],
|
||||
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
|
||||
},
|
||||
});
|
||||
|
||||
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'HttpConn request failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
|
||||
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
|
||||
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
|
||||
throw new Error('HttpConn response missing sig_session');
|
||||
}
|
||||
|
||||
const session: HighwaySession = {
|
||||
sigSession: resp.httpConn.sigSession as Uint8Array,
|
||||
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
|
||||
host: 'htdata3.qq.com',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
for (const si of resp.httpConn.serverInfos ?? []) {
|
||||
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
|
||||
for (const addr of si.serverAddrs) {
|
||||
const ip = addr.ip ?? 0;
|
||||
const port = addr.port ?? 0;
|
||||
if (ip && port) {
|
||||
session.host = ipv4ToString(ip);
|
||||
session.port = port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
|
||||
return session;
|
||||
}
|
||||
|
||||
function makeHighwayHead(
|
||||
uin: string, commandId: number, fileSize: number, offset: number, length: number,
|
||||
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<ReqDataHighwayHead>({
|
||||
msgBaseHead: {
|
||||
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
|
||||
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
|
||||
},
|
||||
msgSegHead: {
|
||||
serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length,
|
||||
retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0,
|
||||
},
|
||||
bytesReqExtendInfo: extend,
|
||||
timestamp: 0n,
|
||||
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
|
||||
});
|
||||
}
|
||||
|
||||
export function buildHighwayExtend(
|
||||
uKey: string,
|
||||
msgInfo: any,
|
||||
ipv4s: any[],
|
||||
sha1: Uint8Array | Uint8Array[],
|
||||
fileIndex = 0,
|
||||
): Uint8Array {
|
||||
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
|
||||
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
|
||||
|
||||
const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0];
|
||||
const networkIpv4s: any[] = [];
|
||||
for (const ipv4 of ipv4s ?? []) {
|
||||
const ip = ipv4.outIp ?? 0;
|
||||
const port = ipv4.outPort ?? 0;
|
||||
if (ip && port) {
|
||||
networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port });
|
||||
}
|
||||
}
|
||||
|
||||
return protobuf_encode<NTV2RichMediaHighwayExt>({
|
||||
fileUuid: selected?.index?.fileUuid ?? '',
|
||||
uKey,
|
||||
network: { ipv4s: networkIpv4s },
|
||||
msgInfoBody: msgInfoBody.map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
})),
|
||||
blockSize: HIGHWAY_BLOCK_SIZE,
|
||||
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
|
||||
});
|
||||
}
|
||||
|
||||
// --- TCP-based HTTP highway upload ---
|
||||
|
||||
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const onTimeout = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
reject(new Error('TCP connect timeout'));
|
||||
};
|
||||
const onError = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(err);
|
||||
};
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
// Drop the connect-only listeners so subsequent IO errors / idle
|
||||
// timeouts don't try to reject this already-resolved promise.
|
||||
socket.setTimeout(0);
|
||||
socket.removeListener('timeout', onTimeout);
|
||||
socket.removeListener('error', onError);
|
||||
resolve(socket);
|
||||
});
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.once('timeout', onTimeout);
|
||||
socket.once('error', onError);
|
||||
});
|
||||
}
|
||||
|
||||
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.write(data, (err) => err ? reject(err) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let headerEnd = -1;
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
let settled = false;
|
||||
|
||||
const detach = () => {
|
||||
socket.off('data', onData);
|
||||
socket.off('error', onError);
|
||||
socket.off('close', onClose);
|
||||
};
|
||||
const finish = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
detach();
|
||||
fn();
|
||||
};
|
||||
const onData = (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd < 0) {
|
||||
const idx = buf.indexOf('\r\n\r\n');
|
||||
if (idx >= 0) {
|
||||
headerEnd = idx + 4;
|
||||
const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase();
|
||||
const clMatch = headerStr.match(/content-length:\s*(\d+)/);
|
||||
contentLength = clMatch ? parseInt(clMatch[1], 10) : 0;
|
||||
totalNeeded = headerEnd + contentLength;
|
||||
}
|
||||
}
|
||||
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
|
||||
}
|
||||
};
|
||||
const onError = (err: Error) => finish(() => reject(err));
|
||||
const onClose = () => finish(() => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
});
|
||||
|
||||
socket.on('data', onData);
|
||||
socket.on('error', onError);
|
||||
socket.on('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
async function httpPostFrame(
|
||||
socket: net.Socket, host: string, path: string, body: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||
if (body.length > 0) await socketWrite(socket, body);
|
||||
return readHttpResponseBody(socket);
|
||||
}
|
||||
|
||||
export async function uploadHighwayHttp(
|
||||
bridge: Bridge, session: HighwaySession, commandId: number,
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`highway upload error_code=${resp.errorCode}`);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
}
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Image');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
interface ImageData {
|
||||
/** Empty when the caller is forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
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,
|
||||
summary: element.summary || (element.subType === 0 ? '[image]' : '[sticker]'),
|
||||
subType: element.subType ?? 0,
|
||||
width: element.width ?? 0,
|
||||
height: element.height ?? 0,
|
||||
picFormat: element.picFormat ?? 1000,
|
||||
fastOnly: true,
|
||||
};
|
||||
}
|
||||
|
||||
function loadImage(element: MessageElement): Promise<ImageData> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
return Promise.reject(new Error('image fast-upload requires md5Hex + sha1Hex'));
|
||||
}
|
||||
return Promise.resolve(imageDataFromFingerprint(element));
|
||||
}
|
||||
return loadImageFromSource(
|
||||
element.url || element.fileId || '',
|
||||
element.fileName ?? '',
|
||||
element.subType ?? 0,
|
||||
element.summary ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
|
||||
const loaded = await loadBinarySource(source, 'image');
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fmt = detectImageFormat(loaded.bytes);
|
||||
|
||||
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
|
||||
const ext = extMap[fmt.format] ?? '.jpg';
|
||||
|
||||
let finalName = fileName || loaded.fileName;
|
||||
if (!finalName) finalName = hashes.md5Hex + ext;
|
||||
|
||||
return {
|
||||
bytes: loaded.bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: finalName,
|
||||
fileSize: loaded.bytes.length,
|
||||
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
|
||||
subType,
|
||||
width: fmt.width,
|
||||
height: fmt.height,
|
||||
picFormat: fmt.format,
|
||||
fastOnly: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an image and return the encoded MsgInfo bytes for the outgoing
|
||||
* commonElem.
|
||||
*/
|
||||
export async function uploadImageMsgInfo(
|
||||
bridge: Bridge,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID,
|
||||
bytes: image.bytes,
|
||||
md5: image.md5,
|
||||
sha1: image.sha1,
|
||||
fastOnlyError: 'image fast-upload not available (server requires bytes)',
|
||||
}];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: image.fileSize,
|
||||
fileHash: image.md5Hex,
|
||||
fileSha1: image.sha1Hex,
|
||||
fileName: image.fileName,
|
||||
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
time: 0,
|
||||
original: 1,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
pic: {
|
||||
bizType: image.subType,
|
||||
textSummary: image.summary,
|
||||
...(isGroup
|
||||
? { reserveTroop: { subType: image.subType } }
|
||||
: { reserveC2c: { subType: image.subType } }),
|
||||
},
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'image',
|
||||
});
|
||||
|
||||
return finalizeMediaMsgInfo(upload, { bizType: image.subType, textSummary: image.summary });
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import crypto from 'crypto';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope } from '../bridge-oidb';
|
||||
import type {
|
||||
EncodableMediaMsgInfo,
|
||||
NTV2UploadRichMediaReq,
|
||||
NTV2UploadRichMediaResp,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
|
||||
// ─────────────── public types ───────────────
|
||||
|
||||
/**
|
||||
* Highway upload spec for one sub-file of an NTV2 upload response.
|
||||
* The server returns 0..N sub-files; for each we either fast-path (skip)
|
||||
* or do an HTTP PUT.
|
||||
*/
|
||||
export interface MediaSubFileUpload {
|
||||
/**
|
||||
* Where to read uKey + ipv4s from on the OIDB response:
|
||||
* 'top' -> `upload.uKey` + `upload.ipv4s` (main file)
|
||||
* N (int) -> `upload.subFileInfos[N].uKey` + `.ipv4s` (sub-file)
|
||||
*
|
||||
* Image and PTT use 'top' only. Video uses 'top' (main) and 0 (thumb).
|
||||
*/
|
||||
source: 'top' | number;
|
||||
/** Highway command id for this sub-file. */
|
||||
cmdId: number;
|
||||
/** Bytes to upload. Empty when the caller is forwarding from cached
|
||||
* fingerprints; in that case set fastOnlyError so we throw with a
|
||||
* typed message when the server actually demands the bytes. */
|
||||
bytes: Uint8Array;
|
||||
/** md5 used for the highway request. */
|
||||
md5: Uint8Array;
|
||||
/** sha1 — single buffer or per-1MB block array. Passed verbatim to
|
||||
* buildHighwayExtend. */
|
||||
sha1: Uint8Array | Uint8Array[];
|
||||
/** subFileIndex argument for buildHighwayExtend. Defaults to 0;
|
||||
* video thumb passes 1. */
|
||||
subFileIndex?: number;
|
||||
/** Error message to throw when uKey is present but `bytes.length === 0`.
|
||||
* Omit if the caller guarantees bytes always exist (e.g. video thumb
|
||||
* always has FALLBACK_THUMB bytes). */
|
||||
fastOnlyError?: string;
|
||||
}
|
||||
|
||||
export interface NtV2UploadParams {
|
||||
bridge: Bridge;
|
||||
isGroup: boolean;
|
||||
/** Group uin when isGroup, otherwise the recipient's uid string. */
|
||||
targetIdOrUid: string | number;
|
||||
/** OIDB command id (e.g. 0x11C4 / 0x11C5 / 0x126E / 0x126D / 0x11EA / 0x11E9). */
|
||||
oidbCmd: number;
|
||||
/** Service cmd (e.g. 'OidbSvcTrpcTcp.0x11c4_100'). */
|
||||
serviceCmd: string;
|
||||
/** `reqHead.common.requestId`. NTV2 sub-protocols use different values
|
||||
* here (image=1, video=3, ptt = group:1 / c2c:4). */
|
||||
requestId: number;
|
||||
/** `reqHead.scene.businessType` (1=image, 3=voice, 2=video). */
|
||||
businessType: number;
|
||||
/** `upload.uploadInfo` array. Each entry is `{ fileInfo, subFileType }`. */
|
||||
uploadInfo: unknown[];
|
||||
/** `upload.compatQmsgSceneType`. */
|
||||
compatQmsgSceneType: number;
|
||||
/** `upload.extBizInfo` — type-specific bytes/flags. */
|
||||
extBizInfo: unknown;
|
||||
/** Sub-file Highway PUTs to perform after the OIDB response. */
|
||||
uploads: MediaSubFileUpload[];
|
||||
/** Used in error messages. Defaults to 'media'. */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
// ─────────────── helpers ───────────────
|
||||
|
||||
/**
|
||||
* 8 random bytes masked into the positive int64 range so the resulting
|
||||
* BigInt survives signed-int64 protobuf encoding without surprises.
|
||||
* Mirrors NapCat.
|
||||
*/
|
||||
export function makeClientRandomId(): bigint {
|
||||
const buf = crypto.randomBytes(8);
|
||||
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
|
||||
}
|
||||
|
||||
/** Hex string -> Uint8Array. Used by every format's fingerprint path. */
|
||||
export function hexToBytes(hex: string): Uint8Array {
|
||||
const clean = hex.length % 2 === 0 ? hex : '0' + hex;
|
||||
const out = new Uint8Array(clean.length / 2);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─────────────── main entrypoint ───────────────
|
||||
|
||||
/**
|
||||
* Send a NTV2UploadRichMediaReq and run any Highway PUTs the server asks
|
||||
* for. Returns the decoded `upload` object so the caller can pass it to
|
||||
* `finalizeMediaMsgInfo`.
|
||||
*
|
||||
* Sessions are cached across sub-file uploads — video does two PUTs but
|
||||
* only fetches the Highway session once.
|
||||
*/
|
||||
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
// Build the full body once. Pulling this in here means each format file
|
||||
// only specifies the seven fields that actually vary.
|
||||
const body: any = {
|
||||
reqHead: {
|
||||
common: { requestId: params.requestId, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: params.businessType,
|
||||
sceneType: isGroup ? 2 : 1,
|
||||
...(isGroup
|
||||
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
uploadInfo: params.uploadInfo,
|
||||
tryFastUploadCompleted: true,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
compatQmsgSceneType: params.compatQmsgSceneType,
|
||||
extBizInfo: params.extBizInfo,
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
|
||||
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
|
||||
|
||||
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || `${label} upload request failed`);
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
|
||||
if (!resp) throw new Error(`failed to decode ${label} upload response`);
|
||||
if (resp.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const uploadBody: any = resp.body;
|
||||
if (!uploadBody) throw new Error(`${label} upload response body missing`);
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
|
||||
}
|
||||
const upload = uploadBody.upload;
|
||||
if (!upload) throw new Error(`${label} upload response body missing`);
|
||||
|
||||
// Highway PUTs. Session is lazily fetched and cached — video does two
|
||||
// PUTs (main + thumb) and shouldn't pay for two sessions.
|
||||
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
|
||||
const getSession = async () => {
|
||||
session ??= await fetchHighwaySession(bridge);
|
||||
return session;
|
||||
};
|
||||
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
// Either the server fast-pathed this sub-file (no uKey) or msgInfo is
|
||||
// missing entirely; either way nothing to push.
|
||||
if (!uKey || !upload.msgInfo) continue;
|
||||
|
||||
if (sub.bytes.length === 0) {
|
||||
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
|
||||
continue;
|
||||
}
|
||||
|
||||
const extend = buildHighwayExtend(
|
||||
uKey,
|
||||
upload.msgInfo,
|
||||
target.ipv4s ?? [],
|
||||
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
|
||||
return upload;
|
||||
}
|
||||
|
||||
// ─────────────── shared finalize ───────────────
|
||||
|
||||
/**
|
||||
* Build the encoded MsgInfo bytes that go inside the outgoing commonElem.
|
||||
*
|
||||
* `defaultPic` is the image-only fall-back: image uploads inject
|
||||
* `bizType` + `textSummary` defaults when the server response omits the
|
||||
* `pic` ext-biz-info. PTT and video pass `undefined` here — they leave
|
||||
* pic alone unless the server populates it.
|
||||
*/
|
||||
export function finalizeMediaMsgInfo(
|
||||
upload: any,
|
||||
defaultPic?: { bizType: number; textSummary: string },
|
||||
): Uint8Array {
|
||||
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
|
||||
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
}));
|
||||
|
||||
const extBizInfo: any = {};
|
||||
if (upload.msgInfo.extBizInfo?.pic) {
|
||||
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
|
||||
if (defaultPic) {
|
||||
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? defaultPic.bizType;
|
||||
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? defaultPic.textSummary;
|
||||
}
|
||||
} else if (defaultPic) {
|
||||
extBizInfo.pic = { bizType: defaultPic.bizType, textSummary: defaultPic.textSummary };
|
||||
}
|
||||
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
|
||||
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
|
||||
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
|
||||
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
|
||||
}
|
||||
|
||||
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Ptt');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_PTT_CMD_ID = 1007;
|
||||
export const GROUP_PTT_CMD_ID = 1008;
|
||||
|
||||
interface PttPayload {
|
||||
/** Silk bytes uploaded to Highway. Empty when forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
/** Whole seconds, >= 1. */
|
||||
duration: number;
|
||||
voiceFormat: number;
|
||||
/** True when bytes is empty; pipeline throws fastOnlyError if the
|
||||
* server demands the bytes anyway. */
|
||||
fastOnly: boolean;
|
||||
/** Cleanup hooks for any temp silk files staged during loadPtt. */
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
function pttPayloadFromFingerprint(element: MessageElement): PttPayload {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'record'}.amr`,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
duration: element.duration ?? 1,
|
||||
// Voice format: 1 = silk (NTV2 standard). Honour any fingerprint that
|
||||
// declares a different format; legacy NTQQ paths all use 1.
|
||||
voiceFormat: element.voiceFormat || 1,
|
||||
fastOnly: true,
|
||||
cleanups: [],
|
||||
};
|
||||
}
|
||||
|
||||
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('record fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
return pttPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('record source is empty');
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
// Run all queued cleanups; called both on the success path (via the
|
||||
// returned `cleanups` array) and on the failure path (try/catch below).
|
||||
const runCleanups = () => {
|
||||
while (cleanups.length > 0) {
|
||||
const fn = cleanups.pop();
|
||||
if (!fn) continue;
|
||||
try { fn(); } catch { /* best-effort */ }
|
||||
}
|
||||
};
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
// Resolve the on-disk path the addon should read. Anything that isn't
|
||||
// already a local file (base64, HTTP) gets staged into the temp dir.
|
||||
let inputPath: string;
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
inputPath = local;
|
||||
} else {
|
||||
const loaded = await loadBinarySource(source, 'record');
|
||||
inputPath = path.join(tempDir, `snowluma-ptt-in-${crypto.randomUUID()}`);
|
||||
fs.writeFileSync(inputPath, Buffer.from(loaded.bytes));
|
||||
cleanups.push(() => { try { fs.unlinkSync(inputPath); } catch { /* ignore */ } });
|
||||
}
|
||||
|
||||
const silk = await encodeSilk(inputPath, tempDir);
|
||||
if (silk.converted) {
|
||||
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
||||
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
|
||||
|
||||
const hashes = computeHashes(silkBytes);
|
||||
return {
|
||||
bytes: silkBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: `${hashes.md5Hex}.amr`,
|
||||
fileSize: silkBytes.length,
|
||||
duration: silk.duration,
|
||||
voiceFormat: 1,
|
||||
fastOnly: false,
|
||||
cleanups: [...cleanups],
|
||||
};
|
||||
} catch (err) {
|
||||
runCleanups();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
|
||||
* a `commonElem { serviceType: 48, businessType: 22 }`.
|
||||
*/
|
||||
export async function uploadPttMsgInfo(
|
||||
bridge: Bridge,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const tempDir = defaultPttTempDir();
|
||||
const ptt = await loadPtt(element, tempDir);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
|
||||
ptt.fileSize,
|
||||
ptt.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
ptt.duration);
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID,
|
||||
bytes: ptt.bytes,
|
||||
md5: ptt.md5,
|
||||
sha1: ptt.sha1,
|
||||
fastOnlyError: 'record fast-upload not available (server requires bytes)',
|
||||
}];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x126E : 0x126D,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100',
|
||||
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
|
||||
requestId: isGroup ? 1 : 4,
|
||||
businessType: 3,
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: ptt.fileSize,
|
||||
fileHash: ptt.md5Hex,
|
||||
fileSha1: ptt.sha1Hex,
|
||||
fileName: ptt.fileName,
|
||||
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: ptt.voiceFormat },
|
||||
width: 0,
|
||||
height: 0,
|
||||
time: ptt.duration,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
// NapCat fills in a placeholder textSummary so the legacy compat
|
||||
// QMsg path still has something to render. Mirror it.
|
||||
pic: { textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array([0x08, 0x00, 0x38, 0x00]),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
// `bytesGeneralFlags` differs between group / c2c voice. Lifted
|
||||
// verbatim from NapCat (UploadGroupPtt.ts / UploadPrivatePtt.ts).
|
||||
bytesGeneralFlags: isGroup
|
||||
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
|
||||
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'ptt',
|
||||
});
|
||||
|
||||
return finalizeMediaMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of ptt.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default cap on a single binary load issued through this helper. Callers
|
||||
* that route here (image / voice via base64+HTTP, group/private file
|
||||
* uploads, avatar) get bounded reads. Not all callers route through here
|
||||
* — in particular `video-upload.stageVideoSource` reads local-video files
|
||||
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
|
||||
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
|
||||
* file protocol legitimately supports up to 4 GiB.
|
||||
*/
|
||||
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
}
|
||||
|
||||
export interface ImageFormat {
|
||||
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// --- Binary source loading ---
|
||||
|
||||
export function resolveLocalFilePath(source: string): string | null {
|
||||
if (!source) return null;
|
||||
if (/^base64:\/\//i.test(source)) return null;
|
||||
if (/^https?:\/\//i.test(source)) return null;
|
||||
|
||||
let filePath = source;
|
||||
if (/^file:\/\//i.test(source)) {
|
||||
try {
|
||||
filePath = fileURLToPath(source);
|
||||
} catch {
|
||||
filePath = source.replace(/^file:\/+/i, '/');
|
||||
try {
|
||||
filePath = decodeURIComponent(filePath);
|
||||
} catch {
|
||||
// Keep the original fallback path when percent decoding fails.
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform !== 'win32' && filePath.startsWith('//')) {
|
||||
filePath = filePath.replace(/^\/+/, '/');
|
||||
}
|
||||
}
|
||||
|
||||
// Windows-style paths can arrive from file:///C:/... as /C:/...
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
const bytes = Buffer.from(source.slice(9), 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName: '' };
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
// Stream the body incrementally so a server that omits or
|
||||
// understates Content-Length can't make us buffer a chunked response
|
||||
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
|
||||
// the entire payload before we get a chance to length-check it.
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw new Error(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.size > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`);
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
function guessFileNameFromUrl(url: string): string {
|
||||
const queryPos = url.search(/[?#]/);
|
||||
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
|
||||
}
|
||||
|
||||
// --- Hashing ---
|
||||
|
||||
export function computeHashes(data: Uint8Array): ImageHashes {
|
||||
const md5 = createHash('md5').update(data).digest();
|
||||
const sha1 = createHash('sha1').update(data).digest();
|
||||
return {
|
||||
md5: new Uint8Array(md5),
|
||||
sha1: new Uint8Array(sha1),
|
||||
md5Hex: md5.toString('hex'),
|
||||
sha1Hex: sha1.toString('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
export function computeMd5(data: Uint8Array): Uint8Array {
|
||||
return new Uint8Array(createHash('md5').update(data).digest());
|
||||
}
|
||||
|
||||
// --- Image format detection (port of C++ detect_image_format) ---
|
||||
|
||||
function readBE16(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 8) | data[offset + 1];
|
||||
}
|
||||
|
||||
function readBE32(data: Uint8Array, offset: number): number {
|
||||
return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
|
||||
}
|
||||
|
||||
function readLE16(data: Uint8Array, offset: number): number {
|
||||
return data[offset] | (data[offset + 1] << 8);
|
||||
}
|
||||
|
||||
function readLE32(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
|
||||
}
|
||||
|
||||
function readBE24(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
|
||||
}
|
||||
|
||||
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
|
||||
// PNG
|
||||
if (bytes.length >= 24 &&
|
||||
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||
width = readBE32(bytes, 16);
|
||||
height = readBE32(bytes, 20);
|
||||
return { format: 1001, width, height };
|
||||
}
|
||||
|
||||
// GIF
|
||||
if (bytes.length >= 10 &&
|
||||
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
|
||||
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
|
||||
width = readLE16(bytes, 6);
|
||||
height = readLE16(bytes, 8);
|
||||
return { format: 2000, width, height };
|
||||
}
|
||||
|
||||
// BMP
|
||||
if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) {
|
||||
width = readLE32(bytes, 18);
|
||||
height = readLE32(bytes, 22);
|
||||
return { format: 1005, width, height };
|
||||
}
|
||||
|
||||
// WebP
|
||||
if (bytes.length >= 30 &&
|
||||
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
|
||||
width = readLE16(bytes, 26);
|
||||
height = readLE16(bytes, 28);
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) {
|
||||
const bits = readLE32(bytes, 21);
|
||||
width = (bits & 0x3FFF) + 1;
|
||||
height = ((bits >> 14) & 0x3FFF) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) {
|
||||
width = readBE24(bytes, 24) + 1;
|
||||
height = readBE24(bytes, 27) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
}
|
||||
|
||||
// JPEG
|
||||
if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) {
|
||||
let offset = 2;
|
||||
while (offset + 9 <= bytes.length) {
|
||||
if (bytes[offset] !== 0xFF) { offset++; continue; }
|
||||
const marker = bytes[offset + 1];
|
||||
if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; }
|
||||
if (offset + 4 > bytes.length) break;
|
||||
const segLen = readBE16(bytes, offset + 2);
|
||||
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
|
||||
// Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC
|
||||
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
|
||||
// and friends, then misread Huffman table bytes as image dimensions.
|
||||
const isSof = marker >= 0xC0 && marker <= 0xCF
|
||||
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
|
||||
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
|
||||
height = readBE16(bytes, offset + 5);
|
||||
width = readBE16(bytes, offset + 7);
|
||||
return { format: 1000, width, height };
|
||||
}
|
||||
offset += 2 + segLen;
|
||||
}
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
// --- Highway frame packing/unpacking ---
|
||||
|
||||
export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array {
|
||||
const frame = new Uint8Array(9 + head.length + body.length + 1);
|
||||
frame[0] = 0x28;
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
dv.setUint32(1, head.length, false);
|
||||
dv.setUint32(5, body.length, false);
|
||||
frame.set(head, 9);
|
||||
frame.set(body, 9 + head.length);
|
||||
frame[frame.length - 1] = 0x29;
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } {
|
||||
if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) {
|
||||
throw new Error('invalid highway response frame');
|
||||
}
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
const headLen = dv.getUint32(1, false);
|
||||
const bodyLen = dv.getUint32(5, false);
|
||||
return {
|
||||
head: frame.subarray(9, 9 + headLen),
|
||||
body: frame.subarray(9 + headLen, 9 + headLen + bodyLen),
|
||||
};
|
||||
}
|
||||
@@ -1,541 +0,0 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { getFFmpegAddon } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import {
|
||||
computeHashes,
|
||||
detectImageFormat,
|
||||
loadBinarySource,
|
||||
resolveLocalFilePath,
|
||||
} from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Video');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_VIDEO_CMD_ID = 1001;
|
||||
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
|
||||
export const GROUP_VIDEO_CMD_ID = 1005;
|
||||
export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
|
||||
|
||||
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
|
||||
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
const FALLBACK_THUMB = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
|
||||
'base64',
|
||||
);
|
||||
|
||||
interface VideoPayload {
|
||||
/** Video bytes. Empty when forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
sha1Blocks: Uint8Array[];
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
videoFormat: number;
|
||||
thumb: ThumbPayload;
|
||||
/** When true, video bytes are empty; pipeline throws fastOnlyError
|
||||
* for the main file if the server demands the bytes. The thumb is
|
||||
* always present (FALLBACK_THUMB at worst) so its sub-file uploads
|
||||
* normally regardless. */
|
||||
fastOnly: boolean;
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
function makeFallbackThumb(): ThumbPayload {
|
||||
const bytes = new Uint8Array(FALLBACK_THUMB);
|
||||
const hashes = computeHashes(bytes);
|
||||
return {
|
||||
bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
}
|
||||
|
||||
function videoPayloadFromFingerprint(element: MessageElement): VideoPayload {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
sha1Blocks: [],
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'video'}.mp4`,
|
||||
filePath: '',
|
||||
fileSize: element.fileSize ?? 0,
|
||||
width: element.width ?? 0,
|
||||
height: element.height ?? 0,
|
||||
duration: element.duration ?? 1,
|
||||
videoFormat: element.videoFormat ?? 0,
|
||||
thumb: makeFallbackThumb(),
|
||||
fastOnly: true,
|
||||
cleanups: [],
|
||||
};
|
||||
}
|
||||
|
||||
interface ThumbPayload {
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
|
||||
|
||||
// Highway expects sha1 computed over each 1 MB block of the file, plus
|
||||
// the final overall sha1. This is a streaming implementation that doesn't
|
||||
// reuse Node's crypto because Node only exposes the final digest.
|
||||
|
||||
class Sha1StreamState {
|
||||
readonly blockSize = 64;
|
||||
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
|
||||
private readonly state = new Uint32Array(5);
|
||||
private readonly count = new Uint32Array(2);
|
||||
private readonly buffer = Buffer.allocUnsafe(this.blockSize);
|
||||
private readonly w = new Uint32Array(80);
|
||||
|
||||
constructor() {
|
||||
this.reset();
|
||||
}
|
||||
|
||||
private reset(): void {
|
||||
this.state[0] = 0x67452301;
|
||||
this.state[1] = 0xEFCDAB89;
|
||||
this.state[2] = 0x98BADCFE;
|
||||
this.state[3] = 0x10325476;
|
||||
this.state[4] = 0xC3D2E1F0;
|
||||
this.count[0] = 0;
|
||||
this.count[1] = 0;
|
||||
this.buffer.fill(0);
|
||||
}
|
||||
|
||||
private rotateLeft(value: number, offset: number): number {
|
||||
return ((value << offset) | (value >>> (32 - offset))) >>> 0;
|
||||
}
|
||||
|
||||
private transform(chunk: Uint8Array, offset: number): void {
|
||||
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize);
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
this.w[i] = view.getUint32(i * 4, false);
|
||||
}
|
||||
for (let i = 16; i < 80; i++) {
|
||||
this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1);
|
||||
}
|
||||
|
||||
let a = this.state[0];
|
||||
let b = this.state[1];
|
||||
let c = this.state[2];
|
||||
let d = this.state[3];
|
||||
let e = this.state[4];
|
||||
|
||||
for (let i = 0; i < 80; i++) {
|
||||
let temp: number;
|
||||
if (i < 20) {
|
||||
temp = ((b & c) | (~b & d)) + 0x5A827999;
|
||||
} else if (i < 40) {
|
||||
temp = (b ^ c ^ d) + 0x6ED9EBA1;
|
||||
} else if (i < 60) {
|
||||
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
|
||||
} else {
|
||||
temp = (b ^ c ^ d) + 0xCA62C1D6;
|
||||
}
|
||||
temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0;
|
||||
e = d;
|
||||
d = c;
|
||||
c = this.rotateLeft(b, 30);
|
||||
b = a;
|
||||
a = temp >>> 0;
|
||||
}
|
||||
|
||||
this.state[0] = (this.state[0] + a) >>> 0;
|
||||
this.state[1] = (this.state[1] + b) >>> 0;
|
||||
this.state[2] = (this.state[2] + c) >>> 0;
|
||||
this.state[3] = (this.state[3] + d) >>> 0;
|
||||
this.state[4] = (this.state[4] + e) >>> 0;
|
||||
}
|
||||
|
||||
update(data: Uint8Array): void {
|
||||
let index = (this.count[0] >>> 3) & 0x3F;
|
||||
const dataLen = data.length;
|
||||
this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0;
|
||||
if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
|
||||
this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0;
|
||||
|
||||
const partLen = this.blockSize - index;
|
||||
let i = 0;
|
||||
|
||||
if (dataLen >= partLen) {
|
||||
this.buffer.set(data.subarray(0, partLen), index);
|
||||
this.transform(this.buffer, 0);
|
||||
for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) {
|
||||
this.transform(data, i);
|
||||
}
|
||||
index = 0;
|
||||
}
|
||||
|
||||
if (i < dataLen) {
|
||||
this.buffer.set(data.subarray(i, dataLen), index);
|
||||
}
|
||||
}
|
||||
|
||||
hash(bigEndian = true): Uint8Array {
|
||||
const digest = Buffer.allocUnsafe(20);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4);
|
||||
else digest.writeUInt32LE(this.state[i], i * 4);
|
||||
}
|
||||
return new Uint8Array(digest);
|
||||
}
|
||||
|
||||
final(): Uint8Array {
|
||||
const bits = Buffer.allocUnsafe(8);
|
||||
bits.writeUInt32BE(this.count[1], 0);
|
||||
bits.writeUInt32BE(this.count[0], 4);
|
||||
|
||||
const index = (this.count[0] >>> 3) & 0x3F;
|
||||
const padLen = index < 56 ? 56 - index : 120 - index;
|
||||
this.update(this.padding.subarray(0, padLen));
|
||||
this.update(bits);
|
||||
return this.hash(true);
|
||||
}
|
||||
}
|
||||
|
||||
function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
|
||||
const sha1 = new Sha1StreamState();
|
||||
const blocks: Uint8Array[] = [];
|
||||
let bytesRead = 0;
|
||||
let offset = 0;
|
||||
|
||||
while (offset + sha1.blockSize <= bytes.length) {
|
||||
const block = bytes.subarray(offset, offset + sha1.blockSize);
|
||||
sha1.update(block);
|
||||
offset += sha1.blockSize;
|
||||
bytesRead += sha1.blockSize;
|
||||
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
|
||||
blocks.push(sha1.hash(false));
|
||||
}
|
||||
}
|
||||
|
||||
if (offset < bytes.length) sha1.update(bytes.subarray(offset));
|
||||
blocks.push(sha1.final());
|
||||
return blocks;
|
||||
}
|
||||
|
||||
// ─────────────── source staging + thumb extraction ───────────────
|
||||
|
||||
function defaultVideoTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-video');
|
||||
}
|
||||
|
||||
function sourceExtension(fileName: string, source: string): string {
|
||||
const fromName = path.extname(fileName);
|
||||
if (fromName) return fromName;
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
const fromSource = local ? path.extname(local) : '';
|
||||
return fromSource || '.mp4';
|
||||
}
|
||||
|
||||
async function stageVideoSource(element: MessageElement, tempDir: string, cleanups: Array<() => void>): Promise<{
|
||||
bytes: Uint8Array;
|
||||
filePath: string;
|
||||
fileName: string;
|
||||
}> {
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('video source is empty');
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
// Pre-check on disk size BEFORE reading bytes into memory. The later
|
||||
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
|
||||
// run after we'd already allocated the entire file (so a 10 GiB
|
||||
// local path still OOMs us before the check fires).
|
||||
const stat = fs.statSync(local);
|
||||
if (stat.size > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
return {
|
||||
bytes: new Uint8Array(fs.readFileSync(local)),
|
||||
filePath: local,
|
||||
fileName: element.fileName || path.basename(local),
|
||||
};
|
||||
}
|
||||
|
||||
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
|
||||
const fileName = element.fileName || loaded.fileName || '';
|
||||
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
|
||||
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
|
||||
cleanups.push(() => { try { fs.unlinkSync(stagedPath); } catch { /* ignore */ } });
|
||||
|
||||
return {
|
||||
bytes: loaded.bytes,
|
||||
filePath: stagedPath,
|
||||
fileName,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
thumb: ThumbPayload;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
}> {
|
||||
let width = element.width ?? 0;
|
||||
let height = element.height ?? 0;
|
||||
let duration = element.duration ?? 0;
|
||||
let thumbBytes: Uint8Array | null = null;
|
||||
|
||||
if (element.thumbUrl) {
|
||||
try {
|
||||
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
|
||||
} catch (err) {
|
||||
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbBytes) {
|
||||
try {
|
||||
const info = await getFFmpegAddon().getVideoInfo(videoPath);
|
||||
width = width || info.width || 0;
|
||||
height = height || info.height || 0;
|
||||
duration = duration || Math.max(1, Math.round(info.duration || 0));
|
||||
if (info.image && info.image.length > 0) {
|
||||
thumbBytes = new Uint8Array(info.image);
|
||||
}
|
||||
} catch (err) {
|
||||
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbBytes) {
|
||||
thumbBytes = new Uint8Array(FALLBACK_THUMB);
|
||||
}
|
||||
|
||||
const fmt = detectImageFormat(thumbBytes);
|
||||
width = width || fmt.width || 1;
|
||||
height = height || fmt.height || 1;
|
||||
duration = duration || 1;
|
||||
|
||||
const hashes = computeHashes(thumbBytes);
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
thumb: {
|
||||
bytes: thumbBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('video fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
return videoPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
const tempDir = defaultVideoTempDir();
|
||||
const cleanups: Array<() => void> = [];
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
const staged = await stageVideoSource(element, tempDir, cleanups);
|
||||
if (staged.bytes.length === 0) throw new Error('video file is empty');
|
||||
if (staged.bytes.length > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
|
||||
const hashes = computeHashes(staged.bytes);
|
||||
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
|
||||
|
||||
return {
|
||||
bytes: staged.bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
sha1Blocks: computeVideoSha1Blocks(staged.bytes),
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: staged.fileName || `${hashes.md5Hex}.mp4`,
|
||||
filePath: staged.filePath,
|
||||
fileSize: staged.bytes.length,
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
videoFormat: 0,
|
||||
thumb,
|
||||
fastOnly: false,
|
||||
cleanups: [...cleanups],
|
||||
};
|
||||
} catch (err) {
|
||||
for (const fn of cleanups.reverse()) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── exported entry ───────────────
|
||||
|
||||
/**
|
||||
* Upload a video and return the encoded MsgInfo bytes that go inside a
|
||||
* `commonElem { serviceType: 48, businessType: 21 }`.
|
||||
*
|
||||
* Two highway PUTs run when the server doesn't fast-path: the main video
|
||||
* (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`).
|
||||
*/
|
||||
export async function uploadVideoMsgInfo(
|
||||
bridge: Bridge,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const video = await loadVideo(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
video.fileSize,
|
||||
video.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
|
||||
bytes: video.bytes,
|
||||
md5: video.md5,
|
||||
sha1: video.sha1Blocks,
|
||||
subFileIndex: 0,
|
||||
fastOnlyError: 'video fast-upload not available (server requires bytes)',
|
||||
},
|
||||
{
|
||||
source: 0, // upload.subFileInfos[0]
|
||||
cmdId: isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID,
|
||||
bytes: video.thumb.bytes,
|
||||
md5: video.thumb.md5,
|
||||
sha1: video.thumb.sha1,
|
||||
subFileIndex: 1,
|
||||
// No fastOnlyError: thumb always has bytes (FALLBACK_THUMB at worst).
|
||||
},
|
||||
];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x11EA : 0x11E9,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100',
|
||||
requestId: 3,
|
||||
businessType: 2,
|
||||
uploadInfo: [
|
||||
{
|
||||
fileInfo: {
|
||||
fileSize: video.fileSize,
|
||||
fileHash: video.md5Hex,
|
||||
fileSha1: video.sha1Hex,
|
||||
fileName: 'nya.mp4',
|
||||
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
// Width/height kept at 0 — NapCat does the same and the QQ-NT
|
||||
// server has been observed to reject non-zero dimensions
|
||||
// here on c2c sends with a schema-mismatch error. acidify
|
||||
// *does* fill them (`payload.videoWidth/Height`) but we
|
||||
// leave that alone until c2c regression coverage exists.
|
||||
height: 0,
|
||||
width: 0,
|
||||
// `time` MUST be the real duration in seconds, otherwise
|
||||
// every receiving client renders "00:00" on the video.
|
||||
// NapCat ships `time: 0` because it sits on top of QQ-NT's
|
||||
// IPC layer, which the desktop client patches up before
|
||||
// the wire message goes out. We're a protocol-direct
|
||||
// client (same position as acidify), so we own this field.
|
||||
// acidify writes `payload.videoDuration` here for the same
|
||||
// reason — verified against `RichMediaUpload.kt::
|
||||
// buildVideoUploadInfoList` (2026-04 refactor).
|
||||
time: video.duration,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
},
|
||||
{
|
||||
fileInfo: {
|
||||
fileSize: video.thumb.bytes.length,
|
||||
fileHash: video.thumb.md5Hex,
|
||||
fileSha1: video.thumb.sha1Hex,
|
||||
fileName: 'nya.jpg',
|
||||
type: { type: 1, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
height: video.thumb.height,
|
||||
width: video.thumb.width,
|
||||
time: 0,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 100,
|
||||
},
|
||||
],
|
||||
// Hardcoded 2 even on c2c (matches NapCat). Image/PTT use
|
||||
// `isGroup ? 2 : 1` because their legacy compat elements differ
|
||||
// per scene (notOnlineImage vs customFace; ptt c2c vs group),
|
||||
// but the legacy `videoFile` element has no scene split — its
|
||||
// fromChatType/toChatType live inside the element itself — so
|
||||
// the server generates a single group-shaped compat payload
|
||||
// regardless. Setting 1 here makes the server emit a c2c-scene
|
||||
// shaped compat blob that old QQ clients fail to resolve,
|
||||
// showing the message as "视频已过期" on those receivers while
|
||||
// new clients (which only read the commonElem) display fine.
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: {
|
||||
pic: { bizType: 0, textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
|
||||
ptt: {
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'video',
|
||||
});
|
||||
|
||||
log.debug('video upload completed: md5=%s scene=%s', video.md5Hex, isGroup ? 'group' : 'c2c');
|
||||
return finalizeMediaMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of video.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,909 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
|
||||
const moduleLogger = createLogger('Identity');
|
||||
|
||||
/**
|
||||
* Hooks Identity uses when its read methods miss every cache layer. Wired in
|
||||
* after construction (Bridge owns these methods, but Bridge can't exist
|
||||
* before Identity does). Each call is expected to invoke the matching
|
||||
* remember* observation on this service as a side effect.
|
||||
*/
|
||||
export interface IdentityFetcher {
|
||||
fetchProfile(uin: number): Promise<UserProfileInfo>;
|
||||
fetchGroupMemberList?(groupId: number): Promise<unknown>;
|
||||
}
|
||||
|
||||
interface UserInput {
|
||||
uid?: string;
|
||||
uin?: number;
|
||||
nickname?: string;
|
||||
remark?: string;
|
||||
isFriend?: boolean;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
interface GroupInput {
|
||||
groupId: number;
|
||||
groupName?: string;
|
||||
remark?: string;
|
||||
memberCount?: number;
|
||||
memberMax?: number;
|
||||
}
|
||||
|
||||
interface MemberInput {
|
||||
groupId: number;
|
||||
uid?: string;
|
||||
uin?: number;
|
||||
nickname?: string;
|
||||
card?: string;
|
||||
role?: string;
|
||||
level?: number;
|
||||
title?: string;
|
||||
joinTime?: number;
|
||||
lastSentTime?: number;
|
||||
shutUpTime?: number;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
interface UserRow {
|
||||
id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
is_friend: number;
|
||||
source: string;
|
||||
}
|
||||
|
||||
interface MemberRow {
|
||||
id: number;
|
||||
group_id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
active: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authoritative store for everything we know about QQ actors observed
|
||||
* during this session: the bot's own identity, friends, groups, group
|
||||
* members, user profiles, plus the bidirectional UID↔UIN index that
|
||||
* powers all OIDB-bound translation.
|
||||
*
|
||||
* Two layers internally:
|
||||
* - In-memory state (this file) — O(1) for find* on the hot path.
|
||||
* - SQLite (optional, opened by openForUin) — survives restarts.
|
||||
*
|
||||
* Both layers are kept in sync by the remember* / refresh paths.
|
||||
* Callers should never reach below the public surface; the cascade and
|
||||
* storage details are intentionally hidden.
|
||||
*/
|
||||
export class IdentityService {
|
||||
// ─── Self identity ───
|
||||
private readonly uin_: string;
|
||||
private nickname_ = '';
|
||||
private selfProfile_: UserProfileInfo | null = null;
|
||||
|
||||
// ─── In-memory domain state ───
|
||||
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
|
||||
private friends_: FriendInfo[] = [];
|
||||
private readonly groups_ = new Map<number, QQGroupInfo>();
|
||||
|
||||
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
|
||||
private readonly uinByUid = new Map<string, number>();
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: DatabaseSync | null;
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(uin: string, dbPath: string | null) {
|
||||
this.uin_ = uin;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLogger.child({ uin: uinNum })
|
||||
: moduleLogger;
|
||||
|
||||
if (!dbPath) {
|
||||
this.db = null;
|
||||
return;
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
|
||||
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
|
||||
}
|
||||
|
||||
static memory(uin: string): IdentityService {
|
||||
return new IdentityService(uin, null);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db?.close();
|
||||
}
|
||||
|
||||
get persistent(): boolean {
|
||||
return this.db !== null;
|
||||
}
|
||||
|
||||
setFetcher(fetcher: IdentityFetcher): void {
|
||||
this.fetcher = fetcher;
|
||||
}
|
||||
|
||||
// ─── Self identity surface ───
|
||||
|
||||
get uin(): string { return this.uin_; }
|
||||
|
||||
get nickname(): string { return this.nickname_; }
|
||||
set nickname(v: string) { this.nickname_ = v; }
|
||||
|
||||
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
|
||||
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
|
||||
|
||||
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
|
||||
|
||||
// ─── Domain object reads ───
|
||||
|
||||
findUserProfile(uin: number): UserProfileInfo | null {
|
||||
return this.userProfiles_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
get friends(): FriendInfo[] { return this.friends_; }
|
||||
|
||||
findFriend(uin: number): FriendInfo | null {
|
||||
return this.friends_.find((f) => f.uin === uin) ?? null;
|
||||
}
|
||||
|
||||
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
|
||||
|
||||
findGroup(groupId: number): QQGroupInfo | null {
|
||||
return this.groups_.get(groupId) ?? null;
|
||||
}
|
||||
|
||||
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
|
||||
return this.groups_.get(groupId)?.members.get(uin) ?? null;
|
||||
}
|
||||
|
||||
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.set(member.uin, member);
|
||||
this.rememberUidUin(member.uid, member.uin);
|
||||
}
|
||||
|
||||
// ─── ID translation ───
|
||||
|
||||
/**
|
||||
* UIN → UID with network fallback. Returns cached value on hit; otherwise
|
||||
* invokes the registered fetcher (typically `bridge.fetchUserProfile`),
|
||||
* which is expected to write the result back through `rememberUserProfile`
|
||||
* before this method re-queries the cache. Throws if no UID can be
|
||||
* obtained from any layer.
|
||||
*/
|
||||
async resolveUid(uin: number, groupId?: number): Promise<string> {
|
||||
const normalized = normalizeUin(uin);
|
||||
if (normalized === null) throw new Error(`invalid uin: ${uin}`);
|
||||
|
||||
const cached = this.findUidByUin(normalized, groupId);
|
||||
if (cached) return cached;
|
||||
|
||||
if (groupId !== undefined && this.fetcher?.fetchGroupMemberList) {
|
||||
try { await this.fetcher.fetchGroupMemberList(groupId); } catch { /* ignore */ }
|
||||
const afterMembers = this.findUidByUin(normalized, groupId);
|
||||
if (afterMembers) return afterMembers;
|
||||
}
|
||||
|
||||
if (!this.fetcher) throw new Error(`failed to resolve UID for UIN ${normalized}: no fetcher`);
|
||||
|
||||
const profile = await this.fetcher.fetchProfile(normalized);
|
||||
if (profile.uid) return profile.uid;
|
||||
|
||||
throw new Error(`failed to resolve UID for UIN ${normalized}`);
|
||||
}
|
||||
|
||||
findUinByUid(uid: string, groupId?: number): number | null {
|
||||
const normalized = normalizeUid(uid);
|
||||
if (!normalized) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const member = this.findGroupMemberByUid(groupId, normalized);
|
||||
if (member) return member.uin;
|
||||
}
|
||||
const mapped = this.uinByUid.get(normalized);
|
||||
if (mapped !== undefined) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
`SELECT uin FROM group_members
|
||||
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uin: number | null } | undefined;
|
||||
const uin = normalizeUin(row?.uin);
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uin: number | null } | undefined;
|
||||
return normalizeUin(row?.uin);
|
||||
}
|
||||
|
||||
findUidByUin(uin: number, groupId?: number): string | null {
|
||||
const normalized = normalizeUin(uin);
|
||||
if (normalized === null) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const member = this.groups_.get(groupId)?.members.get(normalized);
|
||||
if (member?.uid) return member.uid;
|
||||
}
|
||||
const mapped = this.uidByUin.get(normalized);
|
||||
if (mapped) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
`SELECT uid FROM group_members
|
||||
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uid: string | null } | undefined;
|
||||
const uid = normalizeUid(row?.uid);
|
||||
if (uid) return uid;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uid: string | null } | undefined;
|
||||
return normalizeUid(row?.uid) || null;
|
||||
}
|
||||
|
||||
// ─── Observation (write side) ───
|
||||
|
||||
rememberFriends(friends: FriendInfo[]): void {
|
||||
this.friends_ = friends;
|
||||
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
|
||||
this.runWrite('friends', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
|
||||
.run(nowSeconds());
|
||||
for (const friend of friends) {
|
||||
this.upsertUser({
|
||||
uid: friend.uid,
|
||||
uin: friend.uin,
|
||||
nickname: friend.nickname,
|
||||
remark: friend.remark,
|
||||
isFriend: true,
|
||||
source: 'friend',
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberGroups(groups: QQGroupInfo[]): void {
|
||||
this.setGroupsInMemory(groups);
|
||||
this.runWrite('groups', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
.run(nowSeconds());
|
||||
for (const group of groups) {
|
||||
this.upsertGroup({
|
||||
groupId: group.groupId,
|
||||
groupName: group.groupName,
|
||||
remark: group.remark,
|
||||
memberCount: group.memberCount,
|
||||
memberMax: group.memberMax,
|
||||
});
|
||||
}
|
||||
}));
|
||||
this.hydrateActiveMembersForGroups(groups.map((group) => group.groupId));
|
||||
}
|
||||
|
||||
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||
this.setGroupMembersInMemory(groupId, members);
|
||||
for (const member of members) this.rememberUidUin(member.uid, member.uin);
|
||||
this.runWrite('group members', () => this.transaction(() => {
|
||||
this.upsertGroup({ groupId, memberCount: members.length });
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
|
||||
.run(nowSeconds(), groupId);
|
||||
for (const member of members) {
|
||||
this.upsertGroupMember({
|
||||
groupId,
|
||||
uid: member.uid,
|
||||
uin: member.uin,
|
||||
nickname: member.nickname,
|
||||
card: member.card,
|
||||
role: member.role,
|
||||
level: member.level,
|
||||
title: member.title,
|
||||
joinTime: member.joinTime,
|
||||
lastSentTime: member.lastSentTime,
|
||||
shutUpTime: member.shutUpTime,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberUserProfile(info: UserProfileInfo): void {
|
||||
this.userProfiles_.set(info.uin, info);
|
||||
const selfUin = parseInt(this.uin_, 10) || 0;
|
||||
if (info.uin === selfUin) this.selfProfile_ = info;
|
||||
this.rememberUidUin(info.uid, info.uin);
|
||||
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
|
||||
uid: info.uid,
|
||||
uin: info.uin,
|
||||
nickname: info.nickname,
|
||||
remark: info.remark,
|
||||
source: 'profile',
|
||||
})));
|
||||
}
|
||||
|
||||
rememberGroupRequests(requests: GroupRequestInfo[]): void {
|
||||
for (const request of requests) {
|
||||
this.rememberUidUin(request.targetUid, request.targetUin);
|
||||
this.rememberUidUin(request.invitorUid, request.invitorUin);
|
||||
this.rememberUidUin(request.operatorUid, request.operatorUin);
|
||||
}
|
||||
this.runWrite('group requests', () => this.transaction(() => {
|
||||
for (const request of requests) {
|
||||
this.upsertGroup({ groupId: request.groupId, groupName: request.groupName });
|
||||
this.upsertUser({
|
||||
uid: request.targetUid,
|
||||
uin: request.targetUin,
|
||||
nickname: request.targetName,
|
||||
source: 'group_request',
|
||||
});
|
||||
this.upsertUser({
|
||||
uid: request.invitorUid,
|
||||
uin: request.invitorUin,
|
||||
nickname: request.invitorName,
|
||||
source: 'group_request',
|
||||
});
|
||||
this.upsertUser({
|
||||
uid: request.operatorUid,
|
||||
uin: request.operatorUin,
|
||||
nickname: request.operatorName,
|
||||
source: 'group_request',
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberRequestIdentity(
|
||||
identity: { groupId?: number; uid?: string; uin?: number; nickname?: string; source?: string },
|
||||
): void {
|
||||
this.rememberUidUin(identity.uid, identity.uin);
|
||||
this.runWrite('request identity', () => this.transaction(() => {
|
||||
if (identity.groupId !== undefined) this.upsertGroup({ groupId: identity.groupId });
|
||||
this.upsertUser({
|
||||
uid: identity.uid,
|
||||
uin: identity.uin,
|
||||
nickname: identity.nickname,
|
||||
source: identity.source || 'request',
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
rememberGroupMemberIdentity(
|
||||
groupId: number,
|
||||
identity: { uid?: string; uin?: number; nickname?: string; card?: string },
|
||||
): void {
|
||||
this.rememberUidUin(identity.uid, identity.uin);
|
||||
this.runWrite('group member identity', () => this.transaction(() => this.upsertGroupMember({
|
||||
groupId,
|
||||
uid: identity.uid,
|
||||
uin: identity.uin,
|
||||
nickname: identity.nickname,
|
||||
card: identity.card,
|
||||
active: true,
|
||||
})));
|
||||
}
|
||||
|
||||
markGroupMemberInactive(groupId: number, identity: { uid?: string; uin?: number }): void {
|
||||
this.runWrite('group member inactive', () => {
|
||||
const uid = normalizeUid(identity.uid);
|
||||
const uin = normalizeUin(identity.uin);
|
||||
if (!uid && uin === null) return;
|
||||
const rows = this.findMemberRows(groupId, uid, uin);
|
||||
const updatedAt = nowSeconds();
|
||||
this.transaction(() => {
|
||||
for (const row of rows) {
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
|
||||
.run(updatedAt, row.id);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Private helpers ───
|
||||
|
||||
private rememberUidUin(uid: unknown, uin: unknown): void {
|
||||
const normalizedUid = normalizeUid(uid);
|
||||
const normalizedUin = normalizeUin(uin);
|
||||
if (!normalizedUid || normalizedUin === null) return;
|
||||
// Drop any stale mapping for the old partner first; otherwise the two
|
||||
// maps disagree (`findUinByUid(oldUid) -> uin` while
|
||||
// `findUidByUin(uin) -> newUid`) after a uid/uin re-binding.
|
||||
const oldUid = this.uidByUin.get(normalizedUin);
|
||||
if (oldUid && oldUid !== normalizedUid) this.uinByUid.delete(oldUid);
|
||||
const oldUin = this.uinByUid.get(normalizedUid);
|
||||
if (oldUin !== undefined && oldUin !== normalizedUin) this.uidByUin.delete(oldUin);
|
||||
this.uinByUid.set(normalizedUid, normalizedUin);
|
||||
this.uidByUin.set(normalizedUin, normalizedUid);
|
||||
}
|
||||
|
||||
private setGroupsInMemory(groups: QQGroupInfo[]): void {
|
||||
// Preserve existing member maps where possible so a roster refresh
|
||||
// doesn't blow away cached members for groups we already track.
|
||||
const previous = new Map(this.groups_);
|
||||
this.groups_.clear();
|
||||
for (const g of groups) {
|
||||
const existing = previous.get(g.groupId);
|
||||
this.groups_.set(g.groupId, {
|
||||
...g,
|
||||
members: existing?.members ?? g.members ?? new Map(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.clear();
|
||||
for (const m of members) {
|
||||
g.members.set(m.uin, m);
|
||||
}
|
||||
}
|
||||
|
||||
private findGroupMemberByUid(groupId: number, uid: string): GroupMemberInfo | null {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return null;
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uid === uid) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db!.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid TEXT UNIQUE,
|
||||
uin INTEGER UNIQUE,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
is_friend INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_users_uid ON users(uid);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_users_uin ON users(uin);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
group_id INTEGER PRIMARY KEY,
|
||||
group_name TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
member_count INTEGER NOT NULL DEFAULT 0,
|
||||
member_max INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS group_members (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
group_id INTEGER NOT NULL,
|
||||
uid TEXT,
|
||||
uin INTEGER,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
card TEXT NOT NULL DEFAULT '',
|
||||
role TEXT NOT NULL DEFAULT 'member',
|
||||
level INTEGER NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
join_time INTEGER NOT NULL DEFAULT 0,
|
||||
last_sent_time INTEGER NOT NULL DEFAULT 0,
|
||||
shut_up_time INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(group_id, uid),
|
||||
UNIQUE(group_id, uin)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_active
|
||||
ON group_members(group_id, active);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uid
|
||||
ON group_members(group_id, uid);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uin
|
||||
ON group_members(group_id, uin);
|
||||
`);
|
||||
}
|
||||
|
||||
private loadSnapshot(): void {
|
||||
const friendRows = this.db!.prepare(
|
||||
`SELECT uid, uin, nickname, remark
|
||||
FROM users
|
||||
WHERE is_friend = 1 AND uin IS NOT NULL`,
|
||||
).all() as Array<{ uid: string | null; uin: number | null; nickname: string; remark: string }>;
|
||||
this.friends_ = friendRows.map((row) => ({
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
remark: row.remark,
|
||||
}));
|
||||
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
|
||||
|
||||
const groups = this.db!.prepare(
|
||||
`SELECT group_id, group_name, remark, member_count, member_max
|
||||
FROM groups
|
||||
WHERE active = 1`,
|
||||
).all() as Array<{
|
||||
group_id: number;
|
||||
group_name: string;
|
||||
remark: string;
|
||||
member_count: number;
|
||||
member_max: number;
|
||||
}>;
|
||||
this.setGroupsInMemory(groups.map((row) => ({
|
||||
groupId: row.group_id,
|
||||
groupName: row.group_name,
|
||||
remark: row.remark,
|
||||
memberCount: row.member_count,
|
||||
memberMax: row.member_max,
|
||||
members: new Map(),
|
||||
})));
|
||||
this.hydrateActiveMembersForGroups(groups.map((row) => row.group_id));
|
||||
}
|
||||
|
||||
private hydrateActiveMembersForGroups(groupIds: number[]): void {
|
||||
if (!this.db || groupIds.length === 0) return;
|
||||
|
||||
const select = this.db.prepare(
|
||||
`SELECT group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND active = 1`,
|
||||
);
|
||||
for (const groupId of groupIds) {
|
||||
const rows = select.all(groupId) as Array<{
|
||||
group_id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
}>;
|
||||
const members = rows.map(rowToMemberInfo);
|
||||
this.setGroupMembersInMemory(groupId, members);
|
||||
for (const m of members) this.rememberUidUin(m.uid, m.uin);
|
||||
}
|
||||
}
|
||||
|
||||
private upsertUser(input: UserInput): void {
|
||||
if (!this.db) return;
|
||||
|
||||
const uid = normalizeUid(input.uid);
|
||||
const uin = normalizeUin(input.uin);
|
||||
if (!uid && uin === null) return;
|
||||
|
||||
const rows = this.findUserRows(uid, uin);
|
||||
const primary = rows[0];
|
||||
const merged = {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: normalizeText(input.nickname) || primary?.nickname || '',
|
||||
remark: normalizeText(input.remark) || primary?.remark || '',
|
||||
isFriend: input.isFriend === true ? 1 : (primary?.is_friend ?? 0),
|
||||
source: normalizeText(input.source) || primary?.source || '',
|
||||
updatedAt: nowSeconds(),
|
||||
};
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
`UPDATE users
|
||||
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.remark,
|
||||
merged.isFriend,
|
||||
merged.source,
|
||||
merged.updatedAt,
|
||||
primary.id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.remark,
|
||||
merged.isFriend,
|
||||
merged.source,
|
||||
merged.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
private upsertGroup(input: GroupInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const existing = this.db.prepare(
|
||||
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
|
||||
).get(input.groupId) as {
|
||||
group_name: string;
|
||||
remark: string;
|
||||
member_count: number;
|
||||
member_max: number;
|
||||
} | undefined;
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?)
|
||||
ON CONFLICT(group_id) DO UPDATE SET
|
||||
group_name = excluded.group_name,
|
||||
remark = excluded.remark,
|
||||
member_count = excluded.member_count,
|
||||
member_max = excluded.member_max,
|
||||
active = 1,
|
||||
updated_at = excluded.updated_at`,
|
||||
).run(
|
||||
input.groupId,
|
||||
normalizeText(input.groupName) || existing?.group_name || '',
|
||||
normalizeText(input.remark) || existing?.remark || '',
|
||||
normalizeNonNegative(input.memberCount, existing?.member_count ?? 0),
|
||||
normalizeNonNegative(input.memberMax, existing?.member_max ?? 0),
|
||||
nowSeconds(),
|
||||
);
|
||||
}
|
||||
|
||||
private upsertGroupMember(input: MemberInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const uid = normalizeUid(input.uid);
|
||||
const uin = normalizeUin(input.uin);
|
||||
if (!uid && uin === null) return;
|
||||
|
||||
this.upsertGroup({ groupId: input.groupId });
|
||||
this.upsertUser({
|
||||
uid,
|
||||
uin: uin ?? undefined,
|
||||
nickname: input.nickname,
|
||||
source: 'group_member',
|
||||
});
|
||||
|
||||
const rows = this.findMemberRows(input.groupId, uid, uin);
|
||||
const primary = rows[0];
|
||||
const merged = {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: normalizeText(input.nickname) || primary?.nickname || '',
|
||||
card: normalizeText(input.card) || primary?.card || '',
|
||||
role: normalizeText(input.role) || primary?.role || 'member',
|
||||
level: normalizeNonNegative(input.level, primary?.level ?? 0),
|
||||
title: normalizeText(input.title) || primary?.title || '',
|
||||
joinTime: normalizeNonNegative(input.joinTime, primary?.join_time ?? 0),
|
||||
lastSentTime: normalizeNonNegative(input.lastSentTime, primary?.last_sent_time ?? 0),
|
||||
shutUpTime: normalizeNonNegative(input.shutUpTime, primary?.shut_up_time ?? 0),
|
||||
active: input.active === false ? 0 : input.active === true ? 1 : (primary?.active ?? 1),
|
||||
updatedAt: nowSeconds(),
|
||||
};
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
`UPDATE group_members
|
||||
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
|
||||
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
merged.joinTime,
|
||||
merged.lastSentTime,
|
||||
merged.shutUpTime,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
primary.id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO group_members
|
||||
(group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
input.groupId,
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
merged.joinTime,
|
||||
merged.lastSentTime,
|
||||
merged.shutUpTime,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
private findUserRows(uid: string, uin: number | null): UserRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id',
|
||||
).all(uid, uin) as unknown as UserRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id',
|
||||
).all(uid) as unknown as UserRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
|
||||
).all(uin) as unknown as UserRow[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND (uid = ? OR uin = ?)
|
||||
ORDER BY id`,
|
||||
).all(groupId, uid, uin) as unknown as MemberRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND uid = ?
|
||||
ORDER BY id`,
|
||||
).all(groupId, uid) as unknown as MemberRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND uin = ?
|
||||
ORDER BY id`,
|
||||
).all(groupId, uin) as unknown as MemberRow[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private transaction<T>(fn: () => T): T {
|
||||
if (!this.db || this.inTransaction) return fn();
|
||||
this.inTransaction = true;
|
||||
this.db.exec('BEGIN');
|
||||
try {
|
||||
const result = fn();
|
||||
this.db.exec('COMMIT');
|
||||
return result;
|
||||
} catch (err) {
|
||||
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
|
||||
throw err;
|
||||
} finally {
|
||||
this.inTransaction = false;
|
||||
}
|
||||
}
|
||||
|
||||
private runWrite(label: string, fn: () => void): void {
|
||||
if (!this.db) return;
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rowToMemberInfo(row: {
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
}): GroupMemberInfo {
|
||||
return {
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
role: row.role || 'member',
|
||||
level: row.level,
|
||||
title: row.title,
|
||||
joinTime: row.join_time,
|
||||
lastSentTime: row.last_sent_time,
|
||||
shutUpTime: row.shut_up_time,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeUid(uid: unknown): string {
|
||||
return typeof uid === 'string' ? uid.trim() : '';
|
||||
}
|
||||
|
||||
function normalizeUin(uin: unknown): number | null {
|
||||
if (typeof uin === 'number' && Number.isFinite(uin)) {
|
||||
const n = Math.trunc(uin);
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
if (typeof uin === 'string' && uin.trim()) {
|
||||
const parsed = Number(uin);
|
||||
if (Number.isFinite(parsed)) {
|
||||
const n = Math.trunc(parsed);
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeText(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function normalizeNonNegative(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function nowSeconds(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { Bridge } from './bridge';
|
||||
import { IdentityService } from './identity-service';
|
||||
import { IdentityService } from '@snowluma/bridge/identity-service';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message';
|
||||
|
||||
export type PushMsgBody = MessageBody;
|
||||
export type PushMsgResponseHead = ResponseHead;
|
||||
export type PushMsgContentHead = ContentHead;
|
||||
|
||||
export interface MsgPushHead {
|
||||
readonly msgType: number;
|
||||
readonly subType: number;
|
||||
readonly sequence: number;
|
||||
readonly timestamp: number;
|
||||
readonly msgId: number;
|
||||
}
|
||||
|
||||
export interface MsgPushContext {
|
||||
readonly head: MsgPushHead;
|
||||
readonly fromUin: number;
|
||||
readonly fromUid: string;
|
||||
readonly selfUin: number;
|
||||
readonly content: Uint8Array;
|
||||
readonly body: PushMsgBody | undefined;
|
||||
readonly responseHead: PushMsgResponseHead | undefined;
|
||||
readonly identity: IdentityService;
|
||||
}
|
||||
|
||||
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
|
||||
if (pkt.body.length === 0) return null;
|
||||
|
||||
const push = protobuf_decode<PushMsg>(Buffer.from(pkt.body));
|
||||
if (!push?.message) return null;
|
||||
|
||||
const msg = push.message;
|
||||
if (!msg.contentHead) return null;
|
||||
|
||||
const head: MsgPushHead = {
|
||||
msgType: msg.contentHead.msgType ?? 0,
|
||||
subType: msg.contentHead.subType ?? 0,
|
||||
sequence: msg.contentHead.sequence ?? 0,
|
||||
timestamp: msg.contentHead.timestamp ?? 0,
|
||||
msgId: msg.contentHead.msgId ?? 0,
|
||||
};
|
||||
|
||||
let fromUin = 0;
|
||||
let fromUid = '';
|
||||
if (msg.responseHead) {
|
||||
fromUin = msg.responseHead.fromUin ?? 0;
|
||||
fromUid = msg.responseHead.fromUid ?? '';
|
||||
}
|
||||
|
||||
let selfUin = 0;
|
||||
if (pkt.uin) {
|
||||
const n = parseInt(pkt.uin, 10);
|
||||
if (!isNaN(n)) selfUin = n;
|
||||
}
|
||||
|
||||
const content = msg.body?.msgContent ?? new Uint8Array(0);
|
||||
|
||||
return {
|
||||
head,
|
||||
fromUin,
|
||||
fromUid,
|
||||
selfUin,
|
||||
content,
|
||||
body: msg.body,
|
||||
responseHead: msg.responseHead,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
FriendAddEvent,
|
||||
FriendPokeEvent,
|
||||
FriendRequestEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type {
|
||||
FriendRecall,
|
||||
FriendRequest,
|
||||
GeneralGrayTipInfo,
|
||||
NewFriend,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { MsgPushContext } from '../context';
|
||||
import { Event0x210SubType } from '../enums';
|
||||
import {
|
||||
buildTemplateMap, findTemplateValue,
|
||||
parseU64OrZero,
|
||||
resolveUidToUin,
|
||||
} from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x210SubType) {
|
||||
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
|
||||
// 138 (other-recalled) and 139 (self-recalled) share the same
|
||||
// FriendRecall wire shape; the helper picks the right uid side
|
||||
// based on the subType.
|
||||
case Event0x210SubType.FriendRecallNotice:
|
||||
case Event0x210SubType.FriendRecallSelfNotice:
|
||||
return decodeFriendRecall(ctx);
|
||||
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
|
||||
// 179 + 226 both carry the NewFriend payload — see enum comment.
|
||||
case Event0x210SubType.NewFriendNotice:
|
||||
case Event0x210SubType.NewFriendNoticeAlt:
|
||||
return decodeNewFriend(ctx);
|
||||
case Event0x210SubType.GroupAppStatePush:
|
||||
// QQ-client-internal troop shortcut bar / discussion app state
|
||||
// push — no OneBot-level event. See enum comment for the
|
||||
// decompiled-source breakdown of the sub_cmd dispatch.
|
||||
return [];
|
||||
case Event0x210SubType.UnmappedClientState380:
|
||||
// QQ-NT-era subType with no reference handler: the legacy QQ
|
||||
// Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26
|
||||
// through SubType0x146 under msgType0x210/, so 380 / 0x17C is
|
||||
// an NT-era addition. None of the NT clients (Lagrange.Core,
|
||||
// LagrangeGo, lagrange-python, mania) handle it either. See the
|
||||
// enum comment for the full investigation; acknowledge silently
|
||||
// until someone maps the schema.
|
||||
return [];
|
||||
}
|
||||
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const request = protobuf_decode<FriendRequest>(ctx.content);
|
||||
if (!request?.info) return [];
|
||||
const sourceUid = request.info.newSource || request.info.sourceUid || '';
|
||||
const ev: FriendRequestEvent = {
|
||||
kind: 'friend_request',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid, ctx.fromUin),
|
||||
fromUid: sourceUid,
|
||||
message: request.info.message ?? '',
|
||||
flag: sourceUid,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const recall = protobuf_decode<FriendRecall>(ctx.content);
|
||||
if (!recall?.info) return [];
|
||||
// 138 = friend recalled their own message sent to bot (peer = fromUid).
|
||||
// 139 = bot recalled own message sent to friend (peer = toUid). Same
|
||||
// ambiguity acidify handles in `parseFriendRecall:380`. Without this
|
||||
// split, self-recall events surface `userUin` as the bot itself which
|
||||
// confuses downstream OneBot consumers that key off `user_id`.
|
||||
const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice;
|
||||
const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? '';
|
||||
const ev: FriendRecallEvent = {
|
||||
kind: 'friend_recall',
|
||||
time: recall.info.time ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
|
||||
msgSeq: recall.info.clientSequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const nf = protobuf_decode<NewFriend>(ctx.content);
|
||||
if (!nf?.info) return [];
|
||||
const newFriendUid = nf.info.uid ?? '';
|
||||
const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin);
|
||||
if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot
|
||||
const ev: FriendAddEvent = {
|
||||
kind: 'friend_add',
|
||||
// proto field is `fixed32 Time` — already uint32 seconds epoch.
|
||||
// Fall back to head.timestamp if the field is missing (some
|
||||
// captures have it as 0).
|
||||
time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: newFriendUin,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
|
||||
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: FriendPokeEvent = {
|
||||
kind: 'friend_poke',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
GroupEssenceEvent,
|
||||
GroupMsgEmojiLikeEvent,
|
||||
GroupMuteEvent,
|
||||
GroupPokeEvent,
|
||||
GroupRecallEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type {
|
||||
GroupMute,
|
||||
GroupReactNotify,
|
||||
NotifyMessageBody,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { MsgPushContext } from '../context';
|
||||
import { Event0x2DCSubType } from '../enums';
|
||||
import {
|
||||
buildTemplateMap, findTemplateValue,
|
||||
parseU64OrZero,
|
||||
resolveUidToUin,
|
||||
unwrapGroupNotifyPayload,
|
||||
} from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x2DCSubType) {
|
||||
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
|
||||
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
|
||||
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
|
||||
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const mute = protobuf_decode<GroupMute>(ctx.content);
|
||||
if (!mute?.data?.state) return [];
|
||||
const duration = mute.data.state.duration ?? 0;
|
||||
const ev: GroupMuteEvent = {
|
||||
kind: 'group_mute',
|
||||
time: mute.data.timestamp ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: mute.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? '', ctx.fromUin),
|
||||
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
|
||||
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
|
||||
const recalled = notify.recall.recallMessages[0];
|
||||
const ev: GroupRecallEvent = {
|
||||
kind: 'group_recall',
|
||||
time: recalled.time ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0,
|
||||
notify.recall.operatorUid || notify.operatorUid || '', ctx.fromUin),
|
||||
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? '', ctx.fromUin),
|
||||
msgSeq: recalled.sequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: GroupPokeEvent = {
|
||||
kind: 'group_poke',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.essenceMessage) return [];
|
||||
const essence = notify.essenceMessage;
|
||||
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
|
||||
const ev: GroupEssenceEvent = {
|
||||
kind: 'group_essence',
|
||||
time: essence.timestamp ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: essence.groupUin ?? notify.groupUin ?? 0,
|
||||
senderUin: essence.memberUin ?? 0,
|
||||
operatorUin: essence.operatorUin ?? ctx.fromUin,
|
||||
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
|
||||
random: essence.random ?? 0,
|
||||
set: setFlag === 1,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
// Magic prefix QQ prepends to the GroupReactNotify payload inside
|
||||
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
|
||||
// (see api/group.ts: `msgContent?.slice(7)`).
|
||||
const GROUP_REACT_PREFIX_BYTES = 7;
|
||||
// Discriminator on GroupReactNotify.field13 — same subType is reused
|
||||
// for other notify variants, only 35 means "emoji react". Anything
|
||||
// else falls through to MsgPush.Unknown for protocol-drift visibility.
|
||||
const GROUP_REACT_DISCRIMINATOR = 35;
|
||||
|
||||
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
|
||||
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
|
||||
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
|
||||
const notify = protobuf_decode<GroupReactNotify>(payload);
|
||||
if (!notify) return [];
|
||||
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
|
||||
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
|
||||
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
|
||||
return [];
|
||||
}
|
||||
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
|
||||
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
|
||||
if (!content) return [];
|
||||
|
||||
const groupId = Number(notify.groupUin ?? 0n);
|
||||
const operatorUid = content.operatorUid ?? '';
|
||||
const emojiId = content.code ?? '';
|
||||
const count = content.count ?? 1;
|
||||
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
|
||||
// removed. Older payloads occasionally omit it; default to "add"
|
||||
// since most clients can only generate add events.
|
||||
const isAdd = (content.type ?? 1) === 1;
|
||||
const msgSeq = Number(target?.seq ?? 0n);
|
||||
|
||||
const ev: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
|
||||
operatorUid,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
count,
|
||||
isAdd,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { FriendMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: FriendMessage = {
|
||||
kind: 'friend_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||
elements: decodeRichBody(ctx.body, false),
|
||||
senderNick: '',
|
||||
};
|
||||
if (ctx.responseHead?.forward?.friendName) {
|
||||
ev.senderNick = ctx.responseHead.forward.friendName;
|
||||
}
|
||||
const friend = ctx.identity.findFriend(ctx.fromUin);
|
||||
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
|
||||
return [ev];
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupAdminEvent } from '../../events';
|
||||
import type { GroupAdmin } from '@snowluma/proto-defs/notify';
|
||||
import { resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
|
||||
const admin = protobuf_decode<GroupAdmin>(ctx.content);
|
||||
if (!admin?.body) return [];
|
||||
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
|
||||
if (!extra) return [];
|
||||
const ev: GroupAdminEvent = {
|
||||
kind: 'group_admin',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: admin.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(ctx.identity, admin.groupUin ?? 0, extra.adminUid ?? '', ctx.fromUin),
|
||||
set: admin.body.extraEnable !== undefined,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -1,60 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupInviteEvent } from '../../events';
|
||||
import type {
|
||||
GroupInvitation, GroupInvite,
|
||||
GroupJoin,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import { resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
|
||||
const join = protobuf_decode<GroupJoin>(ctx.content);
|
||||
if (!join) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: join.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', ctx.fromUin),
|
||||
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 ?? '', ctx.fromUin),
|
||||
fromUid: inner.invitorUid ?? '',
|
||||
subType: 'invite',
|
||||
message: '',
|
||||
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
|
||||
const invite = protobuf_decode<GroupInvite>(ctx.content);
|
||||
if (!invite) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: invite.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', ctx.fromUin),
|
||||
fromUid: invite.invitorUid ?? '',
|
||||
subType: 'invite',
|
||||
message: '',
|
||||
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -1,71 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
|
||||
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
|
||||
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
|
||||
const change = protobuf_decode<GroupChange>(ctx.content);
|
||||
if (!change) return [];
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
|
||||
const change = protobuf_decode<GroupChange>(ctx.content);
|
||||
if (!change) return [];
|
||||
const dt = change.decreaseType ?? 0;
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberLeave = {
|
||||
kind: 'group_member_leave',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
isKick: dt !== 0 && dt !== 130,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => {
|
||||
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
|
||||
if (!joined) return [];
|
||||
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
|
||||
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
|
||||
// — saturate to 0 on the unlikely overflow rather than letting
|
||||
// BigInt propagate downstream where consumers expect a number.
|
||||
const groupUinBig = joined.groupUin ?? 0n;
|
||||
const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0;
|
||||
const operatorUid = joined.operatorUid ?? '';
|
||||
// We're the one joining — surface the bot's own identity as userUin
|
||||
// so the existing converter's `notice.group_increase` shape works
|
||||
// unchanged.
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: ctx.selfUin,
|
||||
userUid: ctx.identity.selfUid ?? '',
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
operatorUid,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { GroupMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeGroupMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: GroupMessage = {
|
||||
kind: 'group_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||
elements: decodeRichBody(ctx.body, true),
|
||||
groupId: 0,
|
||||
senderNick: '',
|
||||
senderCard: '',
|
||||
senderRole: '',
|
||||
};
|
||||
if (ctx.responseHead?.grp) {
|
||||
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
|
||||
if (member) {
|
||||
if (!ev.senderNick) ev.senderNick = member.nickname;
|
||||
ev.senderCard = member.card;
|
||||
ev.senderRole = member.role;
|
||||
}
|
||||
return [ev];
|
||||
};
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { TempMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: TempMessage = {
|
||||
kind: 'temp_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
elements: decodeRichBody(ctx.body, false),
|
||||
groupId: 0,
|
||||
senderNick: '',
|
||||
};
|
||||
if (ctx.responseHead?.grp) {
|
||||
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
if (!ev.senderNick) {
|
||||
const friend = ctx.identity.findFriend(ctx.fromUin);
|
||||
if (friend) ev.senderNick = friend.nickname;
|
||||
}
|
||||
return [ev];
|
||||
};
|
||||
@@ -1,108 +0,0 @@
|
||||
export enum PkgType {
|
||||
ForwardFakePrivateMessage = 9,
|
||||
PrivateMessage = 166,
|
||||
GroupMessage = 82,
|
||||
TempMessage = 141,
|
||||
Event0x210 = 528,
|
||||
Event0x2DC = 732,
|
||||
PrivateRecordMessage = 208,
|
||||
PrivateFileMessage = 529,
|
||||
GroupRequestInvitationNotice = 525,
|
||||
GroupRequestJoinNotice = 84,
|
||||
/**
|
||||
* Self-join admittance — fires on the bot's session right after an
|
||||
* admin approves its `set_group_add_request` or an invite-accept
|
||||
* goes through. Ported from `lagrange-python`'s
|
||||
* `server_push/msg.py:108 case 85`. Maps to OneBot11
|
||||
* `notice.group_increase` with the bot itself as `user_id` —
|
||||
* existing 33 (GroupMemberIncreaseNotice) doesn't fire for the
|
||||
* bot's own join, so without this case the bot never knows it
|
||||
* just entered a group until the first message arrives.
|
||||
*/
|
||||
GroupSelfJoinedNotice = 85,
|
||||
GroupInviteNotice = 87,
|
||||
GroupAdminChangedNotice = 44,
|
||||
GroupMemberIncreaseNotice = 33,
|
||||
GroupMemberDecreaseNotice = 34,
|
||||
}
|
||||
|
||||
export enum Event0x2DCSubType {
|
||||
GroupMuteNotice = 12,
|
||||
GroupMsgEmojiLikeNotice = 16,
|
||||
GroupRecallNotice = 17,
|
||||
GroupGreyTipNotice = 20,
|
||||
GroupEssenceNotice = 21,
|
||||
}
|
||||
|
||||
export enum Event0x210SubType {
|
||||
FriendRequestNotice = 35,
|
||||
/**
|
||||
* Outgoing friend-message recall — bot recalled its own message that
|
||||
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
|
||||
* difference is direction (138 = friend recalled their own message
|
||||
* sent to bot, 139 = bot recalled own message sent to friend).
|
||||
* Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor`
|
||||
* registered for both 138 and 139) + acidify (`138, 139 ->
|
||||
* parseFriendRecall`). The decoder uses the subType to figure out
|
||||
* which UID side ends up as `userUin` on the emitted event.
|
||||
*/
|
||||
FriendRecallSelfNotice = 139,
|
||||
FriendRecallNotice = 138,
|
||||
FriendPokeNotice = 290,
|
||||
/**
|
||||
* Mutual-accept friend notice — 179 fires when bot sent a friend
|
||||
* request and the other side accepted; 226 fires for the opposite
|
||||
* direction. Both decode through the same `NewFriend` wire shape
|
||||
* (LagrangeGo registers them via a `case 226: case 179:` fallthrough
|
||||
* in `client/listener.go:248-258`). Maps to OneBot11
|
||||
* `notice.friend_add`.
|
||||
*/
|
||||
NewFriendNotice = 179,
|
||||
NewFriendNoticeAlt = 226,
|
||||
/**
|
||||
* Group-app state push (troop shortcut bar / discussion app).
|
||||
*
|
||||
* Sourced from the decompiled stock QQ Android client decoder at
|
||||
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
|
||||
* (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody`
|
||||
* dispatching on `uint32_sub_cmd`:
|
||||
*
|
||||
* - 0x1 → `UpdateAppUnreadNum`: a list of
|
||||
* `{group_code, app_id, unread_num}` entries the QQ client uses
|
||||
* to keep group-internal "mini-app" badges (e.g. `appId=101846662`
|
||||
* / `101896870` for the shortcut bar) in sync.
|
||||
* - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
|
||||
* for discussion-group app tips, routed to `getGAudioHandler()`.
|
||||
* - 0x4 → delegated to the troop online-push handler.
|
||||
*
|
||||
* None of these have a OneBot event mapping — they're QQ-client-UI
|
||||
* state pushes (unread badges, in-app tips), not user-visible
|
||||
* conversation events. Acknowledge the subType so it doesn't keep
|
||||
* showing up as "unknown" in debug logs and drop it silently.
|
||||
* Lagrange V2 / lagrange-python / LagrangeGo / acidify all also
|
||||
* fall through on this one because they don't surface the shortcut
|
||||
* bar either.
|
||||
*/
|
||||
GroupAppStatePush = 38,
|
||||
/**
|
||||
* Unmapped QQ-NT-internal subType — first seen as a recurring
|
||||
* "Event0x210 unknown subType=380" debug log in production captures.
|
||||
*
|
||||
* The tsuzcx/qq_apk decompile of the legacy QQ Android client only
|
||||
* enumerates SubType0x26 (38) through SubType0x146 (326) under
|
||||
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` —
|
||||
* `SubType0x17c.java` (380) literally doesn't exist in that tree, so
|
||||
* 380 is a QQ-NT-era addition rather than a missed legacy subType.
|
||||
*
|
||||
* The NT-era reference clients also don't handle it: Lagrange.Core
|
||||
* (`PushMessageService.cs`), LagrangeGo (`client/listener.go`),
|
||||
* lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`)
|
||||
* each enumerate explicit 0x210 subtypes and none include 380 / 0x17C.
|
||||
*
|
||||
* Most likely a QQ-NT-client-UI state push (similar to 38) that
|
||||
* doesn't map to any OneBot event. Acknowledge silently to keep the
|
||||
* unknown log clean; if a real OneBot event ends up depending on it,
|
||||
* revisit with whichever NT-era project finally maps the schema.
|
||||
*/
|
||||
UnmappedClientState380 = 380,
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { inflateSync } from 'zlib';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import type { OperatorInfo } from '@snowluma/proto-defs/notify';
|
||||
|
||||
export function makeImageUrl(origUrl: string): string {
|
||||
if (!origUrl) return '';
|
||||
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
|
||||
return 'http://gchat.qpic.cn' + origUrl;
|
||||
}
|
||||
|
||||
export function decompressData(data: Uint8Array): string {
|
||||
if (!data || data.length === 0) return '';
|
||||
if (data[0] === 0x01 && data.length > 1) {
|
||||
try {
|
||||
const inflated = inflateSync(Buffer.from(data.subarray(1)));
|
||||
return inflated.toString('utf8');
|
||||
} catch { return ''; }
|
||||
}
|
||||
if (data[0] === 0x00 && data.length > 1) {
|
||||
return Buffer.from(data.subarray(1)).toString('utf8');
|
||||
}
|
||||
return Buffer.from(data).toString('utf8');
|
||||
}
|
||||
|
||||
export function isNumericUin(value: string): boolean {
|
||||
return value.length > 0 && /^\d+$/.test(value);
|
||||
}
|
||||
|
||||
export function parseU64OrZero(value: string): number {
|
||||
if (!value) return 0;
|
||||
const n = parseInt(value, 10);
|
||||
return isNaN(n) ? 0 : n;
|
||||
}
|
||||
|
||||
// Cascades group-scoped lookup → in-memory map → SQLite.
|
||||
// No network fallback on the parse hot path: missing identities fall back to
|
||||
// `fallback` and downstream events drive a roster refresh asynchronously.
|
||||
export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number {
|
||||
if (!uid) return fallback;
|
||||
if (isNumericUin(uid)) {
|
||||
const n = parseInt(uid, 10);
|
||||
if (!isNaN(n)) return n;
|
||||
}
|
||||
const uin = identity.findUinByUid(uid, groupId || undefined);
|
||||
if (uin !== null) return uin;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function decodeOperatorUid(bytes: Uint8Array): string {
|
||||
if (!bytes || bytes.length === 0) return '';
|
||||
const info = protobuf_decode<OperatorInfo>(bytes);
|
||||
if (info?.operatorField?.uid) return info.operatorField.uid;
|
||||
return Buffer.from(bytes).toString('utf8');
|
||||
}
|
||||
|
||||
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const p of params) {
|
||||
if (p.name !== undefined) map.set(p.name, p.value ?? '');
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
|
||||
for (const k of keys) {
|
||||
const v = map.get(k);
|
||||
if (v) return v;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
|
||||
if (content.length <= 7) return null;
|
||||
const lenBe = (content[5] << 8) | content[6];
|
||||
const lenLe = content[5] | (content[6] << 8);
|
||||
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
|
||||
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
|
||||
return content.subarray(7);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { QQEventVariant } from '../events';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import { buildContext } from './context';
|
||||
import { decodeEvent0x210 } from './decoders/event-0x210';
|
||||
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
|
||||
import { decodeFriendMessage } from './decoders/friend-message';
|
||||
import { decodeGroupAdmin } from './decoders/group-admin';
|
||||
import {
|
||||
decodeGroupInvitation, decodeGroupInvite,
|
||||
decodeGroupJoinRequest,
|
||||
} from './decoders/group-join-request';
|
||||
import {
|
||||
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
|
||||
} from './decoders/group-member-change';
|
||||
import { decodeGroupMessage } from './decoders/group-message';
|
||||
import { decodeTempMessage } from './decoders/temp-message';
|
||||
import { PkgType } from './enums';
|
||||
import { MsgPushRegistry } from './registry';
|
||||
|
||||
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
const registry = new MsgPushRegistry();
|
||||
registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin);
|
||||
registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave);
|
||||
registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined);
|
||||
registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin);
|
||||
registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest);
|
||||
registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation);
|
||||
registry.register(PkgType.GroupInviteNotice, decodeGroupInvite);
|
||||
registry.register(PkgType.Event0x210, decodeEvent0x210);
|
||||
registry.register(PkgType.Event0x2DC, decodeEvent0x2DC);
|
||||
registry.register(PkgType.GroupMessage, decodeGroupMessage);
|
||||
registry.register(PkgType.TempMessage, decodeTempMessage);
|
||||
registry.register([
|
||||
PkgType.PrivateMessage,
|
||||
PkgType.ForwardFakePrivateMessage,
|
||||
PkgType.PrivateRecordMessage,
|
||||
PkgType.PrivateFileMessage,
|
||||
], decodeFriendMessage);
|
||||
|
||||
export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
|
||||
const ctx = buildContext(pkt, identity);
|
||||
if (!ctx) return [];
|
||||
return registry.decode(ctx);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { QQEventVariant } from '../events';
|
||||
import type { MsgPushContext } from './context';
|
||||
import type { PkgType } from './enums';
|
||||
|
||||
const log = createLogger('MsgPush');
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
|
||||
|
||||
export class MsgPushRegistry {
|
||||
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
|
||||
|
||||
register(pkgType: PkgType | PkgType[], decoder: MsgPushDecoder): void {
|
||||
const list = Array.isArray(pkgType) ? pkgType : [pkgType];
|
||||
for (const t of list) {
|
||||
if (this.decoders_.has(t)) {
|
||||
throw new Error(`MsgPushRegistry: PkgType ${t} already registered`);
|
||||
}
|
||||
this.decoders_.set(t, decoder);
|
||||
}
|
||||
}
|
||||
|
||||
decode(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
|
||||
if (!decoder) {
|
||||
// Unrecognized PkgType: either we don't care about this notify, or
|
||||
// the QQ NT client added a new variant. Surface at debug so a
|
||||
// protocol change can be spotted without spamming production logs.
|
||||
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return decoder(ctx);
|
||||
} catch (e) {
|
||||
log.error('decoder error for PkgType=%d subType=%d: %s',
|
||||
ctx.head.msgType, ctx.head.subType,
|
||||
e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,452 +0,0 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import type { MessageElement } from '../events';
|
||||
import type {
|
||||
Elem,
|
||||
GroupFileExtra,
|
||||
MentionExtra,
|
||||
MsgInfo,
|
||||
NotOnlineImage,
|
||||
QFaceExtra,
|
||||
QSmallFaceExtra,
|
||||
} from '@snowluma/proto-defs/element';
|
||||
import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
|
||||
import { decompressData, makeImageUrl } from './helpers';
|
||||
|
||||
type ElemDecoded = Elem;
|
||||
type RichTextDecoded = RichText;
|
||||
export type PushMsgBody = MessageBody;
|
||||
|
||||
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
|
||||
const elements: MessageElement[] = [];
|
||||
if (body?.richText) {
|
||||
const rt = body.richText;
|
||||
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
|
||||
extractRichtextExtras(rt, elements, isGroup);
|
||||
}
|
||||
if (body?.msgContent && body.msgContent.length > 0) {
|
||||
extractMsgContent(body.msgContent, elements);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
const result: MessageElement[] = [];
|
||||
let skipNext = false;
|
||||
|
||||
for (const elem of elems) {
|
||||
if (skipNext) { skipNext = false; continue; }
|
||||
|
||||
// Reply / quote
|
||||
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
|
||||
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
|
||||
}
|
||||
|
||||
// Text (with possible @ detection)
|
||||
if (elem.text) {
|
||||
const t = elem.text;
|
||||
let mention: MentionExtra | null = null;
|
||||
if (t.pbReserve && t.pbReserve.length > 0) {
|
||||
mention = protobuf_decode<MentionExtra>(t.pbReserve);
|
||||
}
|
||||
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
|
||||
const hasMention = mention && (mention.type === 1 || mention.type === 2);
|
||||
|
||||
if (hasAttr6 || hasMention) {
|
||||
const me: MessageElement = { type: 'at', text: t.str ?? '' };
|
||||
if (hasAttr6) {
|
||||
const buf = t.attr6Buf!;
|
||||
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
|
||||
}
|
||||
if (hasMention && mention) {
|
||||
me.uid = mention.uid ?? '';
|
||||
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
|
||||
}
|
||||
result.push(me);
|
||||
} else {
|
||||
const text = t.str ?? '';
|
||||
if (text) result.push({ type: 'text', text });
|
||||
}
|
||||
}
|
||||
|
||||
// Face
|
||||
if (elem.face) {
|
||||
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
|
||||
}
|
||||
|
||||
// MarketFace
|
||||
if (elem.marketFace) {
|
||||
result.push({
|
||||
type: 'mface',
|
||||
text: elem.marketFace.faceName ?? '',
|
||||
faceId: elem.marketFace.tabId ?? 0,
|
||||
subType: elem.marketFace.subType ?? 0,
|
||||
});
|
||||
}
|
||||
|
||||
// NotOnlineImage (C2C image)
|
||||
if (elem.notOnlineImage) {
|
||||
const img = elem.notOnlineImage;
|
||||
if (img.picMd5 && img.picMd5.length > 0) {
|
||||
const urlPath = img.origUrl || img.bigUrl || '';
|
||||
result.push({
|
||||
type: 'image',
|
||||
imageUrl: makeImageUrl(urlPath),
|
||||
fileId: img.filePath ?? '',
|
||||
fileSize: img.fileLen ?? 0,
|
||||
width: img.picWidth ?? 0,
|
||||
height: img.picHeight ?? 0,
|
||||
subType: img.pbRes?.subType ?? 0,
|
||||
summary: img.pbRes?.summary ?? '[image]',
|
||||
md5Hex: toHexUpper(img.picMd5),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// CustomFace (group image)
|
||||
if (elem.customFace) {
|
||||
const img = elem.customFace;
|
||||
if (img.md5 && img.md5.length > 0) {
|
||||
result.push({
|
||||
type: 'image',
|
||||
imageUrl: makeImageUrl(img.origUrl ?? ''),
|
||||
fileId: img.filePath ?? '',
|
||||
fileSize: img.size ?? 0,
|
||||
width: img.width ?? 0,
|
||||
height: img.height ?? 0,
|
||||
subType: img.pbRes?.subType ?? 0,
|
||||
summary: img.pbRes?.summary ?? '[image]',
|
||||
md5Hex: toHexUpper(img.md5),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// VideoFile
|
||||
if (elem.videoFile) {
|
||||
const v = elem.videoFile;
|
||||
result.push({
|
||||
type: 'video',
|
||||
fileId: v.fileUuid ?? '',
|
||||
fileName: v.fileName ?? '',
|
||||
fileSize: v.fileSize ?? 0,
|
||||
duration: v.fileTime ?? 0,
|
||||
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
|
||||
mediaNode: {
|
||||
fileUuid: v.fileUuid ?? '',
|
||||
info: {
|
||||
fileSize: v.fileSize ?? 0,
|
||||
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
|
||||
fileName: v.fileName ?? '',
|
||||
width: v.fileWidth ?? 0,
|
||||
height: v.fileHeight ?? 0,
|
||||
time: v.fileTime ?? 0,
|
||||
type: {
|
||||
type: 2,
|
||||
videoFormat: v.fileFormat ?? 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// GroupFile
|
||||
if (elem.groupFile) {
|
||||
const f = elem.groupFile;
|
||||
result.push({
|
||||
type: 'file',
|
||||
fileId: f.fileId ?? '',
|
||||
fileName: f.filename ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
});
|
||||
}
|
||||
|
||||
// TransElem type=24 (group file via transport)
|
||||
if (elem.transElem) {
|
||||
const te = elem.transElem;
|
||||
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
|
||||
const val = te.elemValue;
|
||||
const len = (val[1] << 8) | val[2];
|
||||
if (val.length >= 3 + len) {
|
||||
const extra = protobuf_decode<GroupFileExtra>(val.subarray(3, 3 + len));
|
||||
if (extra?.inner?.info) {
|
||||
const info = extra.inner.info;
|
||||
result.push({
|
||||
type: 'file',
|
||||
fileName: info.fileName ?? '',
|
||||
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
|
||||
fileId: info.fileId ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RichMsg
|
||||
if (elem.richMsg) {
|
||||
const rm = elem.richMsg;
|
||||
if (rm.template1 && rm.template1.length > 0) {
|
||||
const content = decompressData(rm.template1);
|
||||
if (content) {
|
||||
const svcId = rm.serviceId ?? 0;
|
||||
if (svcId === 35) {
|
||||
const pos = content.indexOf('m_resid="');
|
||||
if (pos !== -1) {
|
||||
const start = pos + 9;
|
||||
const end = content.indexOf('"', start);
|
||||
if (end !== -1) {
|
||||
result.push({ type: 'forward', resId: content.substring(start, end) });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
} else if (svcId === 1) {
|
||||
result.push({ type: 'json', text: content });
|
||||
} else {
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LightApp
|
||||
if (elem.lightApp) {
|
||||
const la = elem.lightApp;
|
||||
if (la.data && la.data.length > 0) {
|
||||
const content = decompressData(la.data);
|
||||
if (content) result.push({ type: 'json', text: content });
|
||||
}
|
||||
}
|
||||
|
||||
// CommonElem
|
||||
if (elem.commonElem) {
|
||||
const ce = elem.commonElem;
|
||||
const svcType = ce.serviceType ?? 0;
|
||||
const bizType = ce.businessType ?? 0;
|
||||
|
||||
if (svcType === 2) {
|
||||
// Poke
|
||||
result.push({ type: 'poke', subType: bizType });
|
||||
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
|
||||
// Flash image
|
||||
const pb = ce.pbElem;
|
||||
let pos = 1;
|
||||
let length = 0, shift = 0;
|
||||
while (pos < pb.length) {
|
||||
const b = pb[pos++];
|
||||
length |= (b & 0x7f) << shift;
|
||||
shift += 7;
|
||||
if ((b & 0x80) === 0) break;
|
||||
}
|
||||
if (pos + length <= pb.length) {
|
||||
const img = protobuf_decode<NotOnlineImage>(pb.subarray(pos, pos + length));
|
||||
if (img) {
|
||||
const me: MessageElement = {
|
||||
type: 'image', fileId: img.filePath ?? '',
|
||||
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
|
||||
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
|
||||
};
|
||||
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
|
||||
if (img.picMd5 && img.picMd5.length > 0) {
|
||||
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + toHexUpper(img.picMd5) + '/0';
|
||||
}
|
||||
result.push(me);
|
||||
}
|
||||
}
|
||||
skipNext = true;
|
||||
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
|
||||
// NTQQ new protocol image/record/video
|
||||
const info = protobuf_decode<MsgInfo>(ce.pbElem);
|
||||
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
|
||||
const body = info.msgInfoBody[0];
|
||||
if (body.index?.info) {
|
||||
const idx = body.index;
|
||||
const fi = idx.info!;
|
||||
|
||||
if (bizType === 10 || bizType === 20) {
|
||||
// Image
|
||||
let url = '';
|
||||
if (body.picture) {
|
||||
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
|
||||
const path = body.picture.urlPath ?? '';
|
||||
if (path) {
|
||||
url = 'https://' + domain + path;
|
||||
if (body.picture.ext?.originalParameter) {
|
||||
url += body.picture.ext.originalParameter;
|
||||
}
|
||||
}
|
||||
}
|
||||
const me: MessageElement = {
|
||||
type: 'image', fileId: fi.fileName ?? '',
|
||||
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
|
||||
height: fi.height ?? 0, imageUrl: url,
|
||||
};
|
||||
if (fi.fileHash) me.md5Hex = fi.fileHash;
|
||||
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
|
||||
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
|
||||
if (info.extBizInfo?.pic) {
|
||||
me.subType = info.extBizInfo.pic.bizType ?? 0;
|
||||
me.summary = info.extBizInfo.pic.textSummary || '[image]';
|
||||
}
|
||||
result.push(me);
|
||||
} else if (bizType === 12 || bizType === 22) {
|
||||
// Record
|
||||
result.push({
|
||||
type: 'record', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
fileSize: fi.fileSize ?? 0,
|
||||
md5Hex: fi.fileHash ?? '',
|
||||
sha1Hex: fi.fileSha1 ?? '',
|
||||
voiceFormat: fi.type?.voiceFormat ?? 0,
|
||||
mediaNode: {
|
||||
fileUuid: idx.fileUuid,
|
||||
storeId: idx.storeId,
|
||||
uploadTime: idx.uploadTime,
|
||||
ttl: idx.ttl,
|
||||
subType: idx.subType,
|
||||
info: {
|
||||
fileSize: fi.fileSize,
|
||||
fileHash: fi.fileHash,
|
||||
fileSha1: fi.fileSha1,
|
||||
fileName: fi.fileName,
|
||||
width: fi.width,
|
||||
height: fi.height,
|
||||
time: fi.time,
|
||||
original: fi.original,
|
||||
type: {
|
||||
type: fi.type?.type,
|
||||
picFormat: fi.type?.picFormat,
|
||||
videoFormat: fi.type?.videoFormat,
|
||||
voiceFormat: fi.type?.voiceFormat,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (bizType === 11 || bizType === 21) {
|
||||
// Video
|
||||
result.push({
|
||||
type: 'video', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
|
||||
duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
width: fi.width ?? 0,
|
||||
height: fi.height ?? 0,
|
||||
md5Hex: fi.fileHash ?? '',
|
||||
sha1Hex: fi.fileSha1 ?? '',
|
||||
videoFormat: fi.type?.videoFormat ?? 0,
|
||||
mediaNode: {
|
||||
fileUuid: idx.fileUuid,
|
||||
storeId: idx.storeId,
|
||||
uploadTime: idx.uploadTime,
|
||||
ttl: idx.ttl,
|
||||
subType: idx.subType,
|
||||
info: {
|
||||
fileSize: fi.fileSize,
|
||||
fileHash: fi.fileHash,
|
||||
fileSha1: fi.fileSha1,
|
||||
fileName: fi.fileName,
|
||||
width: fi.width,
|
||||
height: fi.height,
|
||||
time: fi.time,
|
||||
original: fi.original,
|
||||
type: {
|
||||
type: fi.type?.type,
|
||||
picFormat: fi.type?.picFormat,
|
||||
videoFormat: fi.type?.videoFormat,
|
||||
voiceFormat: fi.type?.voiceFormat,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (svcType === 33 && ce.pbElem) {
|
||||
// Small face
|
||||
const extra = protobuf_decode<QSmallFaceExtra>(ce.pbElem);
|
||||
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
|
||||
} else if (svcType === 37 && ce.pbElem) {
|
||||
// Big face
|
||||
const extra = protobuf_decode<QFaceExtra>(ce.pbElem);
|
||||
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
|
||||
skipNext = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function extractRichtextExtras(
|
||||
rt: RichTextDecoded,
|
||||
elements: MessageElement[],
|
||||
isGroup = false
|
||||
): void {
|
||||
// Ptt (voice)
|
||||
if (rt.ptt) {
|
||||
const p = rt.ptt;
|
||||
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '';
|
||||
const me: MessageElement = {
|
||||
type: 'record', fileName: p.fileName ?? '',
|
||||
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
|
||||
fileHash: md5Hex,
|
||||
md5Hex,
|
||||
voiceFormat: p.format ?? 0,
|
||||
};
|
||||
if (isGroup && (p.fileId ?? 0n) !== 0n) {
|
||||
me.fileId = p.groupFileKey ?? '';
|
||||
} else {
|
||||
if (p.fileUuid && p.fileUuid.length > 0) {
|
||||
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
|
||||
}
|
||||
}
|
||||
me.mediaNode = {
|
||||
fileUuid: me.fileId ?? '',
|
||||
info: {
|
||||
fileSize: p.fileSize ?? 0,
|
||||
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '',
|
||||
fileName: p.fileName ?? '',
|
||||
time: p.time ?? 0,
|
||||
type: {
|
||||
type: 3,
|
||||
voiceFormat: p.format ?? 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
elements.push(me);
|
||||
}
|
||||
|
||||
// NotOnlineFile (C2C file)
|
||||
if (rt.notOnlineFile) {
|
||||
const f = rt.notOnlineFile;
|
||||
elements.push({
|
||||
type: 'file', fileId: f.fileUuid ?? '',
|
||||
fileName: f.fileName ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
fileHash: f.fileHash ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
|
||||
// `MessageBody.msgContent` is where the QQ-NT server actually puts
|
||||
// c2c file metadata — serialised `FileExtra { file: NotOnlineFile }`
|
||||
// bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/
|
||||
// fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire
|
||||
// shape — every field landed at the wrong tag, so the four-field
|
||||
// truthiness check below filtered out every real c2c file push as
|
||||
// "incomplete metadata". After consolidating FileExtra to wrap
|
||||
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
|
||||
// this reads the right tags.
|
||||
const extra = protobuf_decode<FileExtra>(msgContent);
|
||||
if (!extra?.file) return;
|
||||
const f = extra.file;
|
||||
if (!f.fileUuid) return;
|
||||
elements.push({
|
||||
type: 'file',
|
||||
fileId: f.fileUuid,
|
||||
fileName: f.fileName ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
fileHash: f.fileHash ?? '',
|
||||
});
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { formatEvent } from '../utils/event-format';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { IdentityService } from './identity-service';
|
||||
|
||||
const moduleLog = createLogger('Bridge');
|
||||
const moduleEventLog = createLogger('Event');
|
||||
|
||||
// Notice kinds that get logged as a warning (operationally important
|
||||
// state changes that an operator probably wants to see at default
|
||||
// info level). Everything else falls through to info.
|
||||
const WARN_EVENT_KINDS = new Set([
|
||||
'group_recall',
|
||||
'friend_recall',
|
||||
'group_member_leave',
|
||||
'group_mute',
|
||||
'friend_request',
|
||||
'group_invite',
|
||||
]);
|
||||
|
||||
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
|
||||
|
||||
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
|
||||
|
||||
export interface PacketPipelineDeps {
|
||||
identity: IdentityService;
|
||||
events: BridgeEventBus;
|
||||
/**
|
||||
* Refresh group + member roster as a side-effect. Resolves with
|
||||
* whether any refresh actually ran (false when the group is unknown
|
||||
* and `refreshGroupList` was false).
|
||||
*/
|
||||
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
|
||||
}
|
||||
|
||||
export class IncomingPacketPipeline {
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
private readonly log: Logger;
|
||||
private readonly eventLog: Logger;
|
||||
|
||||
constructor(private readonly deps: PacketPipelineDeps) {
|
||||
// Tag every line we emit with this Bridge's UIN so per-account file
|
||||
// routing works. Unparseable uin (shouldn't happen) falls back to
|
||||
// the module-level logger so we still log, just without the slot.
|
||||
const uinNum = Number.parseInt(deps.identity.uin, 10);
|
||||
const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null;
|
||||
this.log = bind ? moduleLog.child(bind) : moduleLog;
|
||||
this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog;
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
const arr = this.cmdHandlers_.get(cmd) ?? [];
|
||||
arr.push(parser);
|
||||
this.cmdHandlers_.set(cmd, arr);
|
||||
}
|
||||
|
||||
handlesCmd(cmd: string): boolean {
|
||||
return this.cmdHandlers_.has(cmd);
|
||||
}
|
||||
|
||||
process(pkt: PacketInfo): void {
|
||||
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
|
||||
if (!handlers) return;
|
||||
|
||||
for (const handler of handlers) {
|
||||
try {
|
||||
const events = handler(pkt, this.deps.identity);
|
||||
for (const event of events) {
|
||||
if (this.needsPreDispatchIdentityRefresh(event)) {
|
||||
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
|
||||
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
} else {
|
||||
this.handleSideEffects(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private emit(event: QQEventVariant): void {
|
||||
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
|
||||
// own onError hook so one bad listener never blocks the others.
|
||||
void this.deps.events.emit(event);
|
||||
}
|
||||
|
||||
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
|
||||
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
|
||||
}
|
||||
|
||||
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
|
||||
let refreshed = false;
|
||||
try {
|
||||
refreshed = await this.prepareGroupMemberJoinIdentity(event);
|
||||
} catch (e) {
|
||||
this.log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
this.handleSideEffects(event, refreshed);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
|
||||
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
|
||||
this.resolveMemberIdentityFromCache(event);
|
||||
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
|
||||
|
||||
const refreshed = await this.deps.refreshMemberCache(
|
||||
event.groupId,
|
||||
!this.deps.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
|
||||
true,
|
||||
);
|
||||
this.resolveMemberIdentityFromCache(event);
|
||||
return refreshed;
|
||||
}
|
||||
|
||||
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
|
||||
if (event.groupId <= 0) return;
|
||||
if (event.userUin <= 0 && event.userUid) {
|
||||
const uin = this.deps.identity.findUinByUid(event.userUid, event.groupId);
|
||||
if (uin !== null) event.userUin = uin;
|
||||
}
|
||||
if (event.operatorUin <= 0 && event.operatorUid) {
|
||||
const uin = this.deps.identity.findUinByUid(event.operatorUid, event.groupId);
|
||||
if (uin !== null) event.operatorUin = uin;
|
||||
}
|
||||
}
|
||||
|
||||
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
|
||||
const selfUin = Number(this.deps.identity.uin);
|
||||
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
|
||||
}
|
||||
|
||||
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
|
||||
this.rememberEventIdentity(event);
|
||||
if (alreadyRefreshed) return;
|
||||
|
||||
let groupId = 0;
|
||||
let reason = '';
|
||||
let refreshGroupList = false;
|
||||
switch (event.kind) {
|
||||
case 'group_member_join':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_member_join';
|
||||
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_member_leave';
|
||||
break;
|
||||
case 'group_admin':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_admin';
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
if (groupId <= 0) return;
|
||||
if (this.memberRefreshTasks_.has(groupId)) return;
|
||||
if (event.kind === 'group_member_join' && !this.deps.identity.findGroup(groupId)) {
|
||||
refreshGroupList = true;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
|
||||
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
} catch (e) {
|
||||
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
groupId, reason, e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
this.memberRefreshTasks_.delete(groupId);
|
||||
}
|
||||
})();
|
||||
|
||||
this.memberRefreshTasks_.set(groupId, task);
|
||||
}
|
||||
|
||||
private rememberEventIdentity(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_member_join':
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.userUid,
|
||||
uin: event.userUin,
|
||||
});
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.operatorUid,
|
||||
uin: event.operatorUin,
|
||||
});
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
this.deps.identity.markGroupMemberInactive(event.groupId, {
|
||||
uid: event.userUid,
|
||||
uin: event.userUin,
|
||||
});
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.operatorUid,
|
||||
uin: event.operatorUin,
|
||||
});
|
||||
break;
|
||||
case 'group_admin':
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uin: event.userUin,
|
||||
});
|
||||
break;
|
||||
case 'friend_request':
|
||||
this.deps.identity.rememberRequestIdentity({
|
||||
uid: event.fromUid,
|
||||
uin: event.fromUin,
|
||||
source: 'friend_request',
|
||||
});
|
||||
break;
|
||||
case 'group_invite':
|
||||
this.deps.identity.rememberRequestIdentity({
|
||||
groupId: event.groupId,
|
||||
uid: event.fromUid,
|
||||
uin: event.fromUin,
|
||||
source: 'group_request',
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function printEvent(log: Logger, identity: IdentityService, event: QQEventVariant): void {
|
||||
// Message-class events (group/friend/temp message) get rendered by the
|
||||
// OneBot layer's logReceivedMessage — its output already includes the
|
||||
// assigned message ID, which the raw packet doesn't have. Returning
|
||||
// null here is the formatter's signal to skip.
|
||||
const message = formatEvent(identity, event);
|
||||
if (!message) return;
|
||||
if (WARN_EVENT_KINDS.has(event.kind)) {
|
||||
log.warn('%s', message);
|
||||
} else {
|
||||
log.info('%s', message);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
export interface UserProfileInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
qid: string;
|
||||
sex: string;
|
||||
age: number;
|
||||
sign: string;
|
||||
avatar: string;
|
||||
}
|
||||
|
||||
export interface FriendInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export interface GroupMemberInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string; // 'owner' | 'admin' | 'member'
|
||||
level: number;
|
||||
title: string;
|
||||
joinTime: number;
|
||||
lastSentTime: number;
|
||||
shutUpTime: number;
|
||||
}
|
||||
|
||||
export interface QQGroupInfo {
|
||||
groupId: number;
|
||||
groupName: string;
|
||||
remark: string;
|
||||
memberCount: number;
|
||||
memberMax: number;
|
||||
members: Map<number, GroupMemberInfo>;
|
||||
}
|
||||
|
||||
export interface GroupRequestInfo {
|
||||
groupId: number;
|
||||
groupName: string;
|
||||
targetUid: string;
|
||||
targetUin: number;
|
||||
targetName: string;
|
||||
invitorUid: string;
|
||||
invitorUin: number;
|
||||
invitorName: string;
|
||||
operatorUid: string;
|
||||
operatorUin: number;
|
||||
operatorName: string;
|
||||
sequence: number;
|
||||
state: number;
|
||||
eventType: number;
|
||||
comment: string;
|
||||
filtered: boolean;
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createHash } from 'crypto';
|
||||
import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
|
||||
import { basename, join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
|
||||
// 群相册信息
|
||||
export interface GroupAlbumInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
picNum: number;
|
||||
createTime: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 获取群相册列表返回
|
||||
export interface GroupAlbumListRet {
|
||||
album: GroupAlbumInfo[];
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 相册媒体信息
|
||||
export interface AlbumMediaInfo {
|
||||
photoId: string;
|
||||
url: string;
|
||||
uploadTime: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取群相册列表
|
||||
*/
|
||||
export async function getGroupAlbumList(
|
||||
cookieObject: Record<string, string>,
|
||||
groupId: string,
|
||||
uin: string
|
||||
): Promise<GroupAlbumListRet | undefined> {
|
||||
if (!cookieObject || typeof cookieObject !== 'object') {
|
||||
throw new Error('cookieObject is required');
|
||||
}
|
||||
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?${new URLSearchParams({
|
||||
random: '7570',
|
||||
g_tk: bkn,
|
||||
format: 'json',
|
||||
inCharset: 'utf-8',
|
||||
outCharset: 'utf-8',
|
||||
qua: 'V1_IPH_SQ_6.2.0_0_HDBM_T',
|
||||
cmd: 'qunGetAlbumList',
|
||||
qunId: groupId,
|
||||
qunid: groupId,
|
||||
start: '0',
|
||||
num: '1000',
|
||||
uin,
|
||||
getMemberRole: '0',
|
||||
}).toString()}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<{ data: GroupAlbumListRet }>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
|
||||
if (!ret || typeof ret !== 'object') {
|
||||
throw new Error('invalid response from qzone api');
|
||||
}
|
||||
|
||||
return ret.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建群相册上传会话
|
||||
*/
|
||||
async function createAlbumUploadSession(
|
||||
groupId: string,
|
||||
albumId: string,
|
||||
albumName: string,
|
||||
filePath: string,
|
||||
skey: string,
|
||||
pskey: string,
|
||||
imgMd5: string,
|
||||
uin: string
|
||||
): Promise<string> {
|
||||
const imgSize = statSync(filePath).size;
|
||||
const imgName = basename(filePath);
|
||||
const bkn = getBknFromCookie({ skey });
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
|
||||
const body = {
|
||||
control_req: [{
|
||||
uin,
|
||||
token: { type: 4, data: pskey, appid: 5 },
|
||||
appid: 'qun',
|
||||
checksum: imgMd5,
|
||||
check_type: 0,
|
||||
file_len: imgSize,
|
||||
env: { refer: 'qzone', deviceInfo: 'h5' },
|
||||
model: 0,
|
||||
biz_req: {
|
||||
sPicTitle: imgName,
|
||||
sPicDesc: '',
|
||||
sAlbumName: albumName,
|
||||
sAlbumID: albumId,
|
||||
iAlbumTypeID: 0,
|
||||
iBitmap: 0,
|
||||
iUploadType: 0,
|
||||
iUpPicType: 0,
|
||||
iBatchID: timestamp,
|
||||
sPicPath: '',
|
||||
iPicWidth: 0,
|
||||
iPicHight: 0,
|
||||
iWaterType: 0,
|
||||
iDistinctUse: 0,
|
||||
iNeedFeeds: 1,
|
||||
iUploadTime: timestamp,
|
||||
mapExt: { appid: 'qun', userid: groupId },
|
||||
stExtendInfo: { mapParams: { photo_num: '1', video_num: '0', batch_num: '1' } },
|
||||
},
|
||||
session: '',
|
||||
asy_upload: 0,
|
||||
cmd: 'FileUpload',
|
||||
}],
|
||||
};
|
||||
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`;
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
|
||||
const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>(
|
||||
api,
|
||||
'POST',
|
||||
body,
|
||||
{ Cookie: cookie, 'Content-Type': 'application/json' }
|
||||
);
|
||||
|
||||
if (response.ret !== 0 || !response.data?.session) {
|
||||
throw new Error(`创建上传会话失败: ${response.msg}`);
|
||||
}
|
||||
|
||||
return response.data.session;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 修复后的上传图片分片方法
|
||||
*/
|
||||
async function uploadAlbumSlice(
|
||||
session: string,
|
||||
filePath: string,
|
||||
// 移除 offset 和 chunkSize 参数,改为在内部控制
|
||||
imgMd5: string,
|
||||
skey: string,
|
||||
pskey: string,
|
||||
uin: string
|
||||
): Promise<void> {
|
||||
const img_size = statSync(filePath).size;
|
||||
const slice_size = 16384; // 严格使用 16KB
|
||||
const bkn = getBknFromCookie({ skey });
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
|
||||
const stream = createReadStream(filePath, { highWaterMark: slice_size });
|
||||
let seq = 0;
|
||||
let offset = 0;
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const end = Math.min(offset + chunk.length, img_size);
|
||||
|
||||
// 使用原生的 FormData 构建安全的 multipart 请求
|
||||
const form = new FormData();
|
||||
form.append('uin', uin);
|
||||
form.append('appid', 'qun');
|
||||
form.append('session', session);
|
||||
form.append('offset', offset.toString());
|
||||
form.append('data', new Blob([chunk as Buffer], { type: 'application/octet-stream' }), 'blob');
|
||||
form.append('checksum', '');
|
||||
form.append('check_type', '0');
|
||||
form.append('retry', '0');
|
||||
form.append('seq', seq.toString());
|
||||
form.append('end', end.toString());
|
||||
form.append('cmd', 'FileUpload');
|
||||
form.append('slice_size', slice_size.toString());
|
||||
form.append('biz_req.iUploadType', '0');
|
||||
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${bkn}`;
|
||||
|
||||
// 放弃使用 HttpGetJson,改用原生 fetch,它能完美处理 FormData 和边界
|
||||
const response = await fetch(api, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Cookie: cookie,
|
||||
// 注意:不要手动设置 Content-Type,fetch 会自动加上带有正确 boundary 的 multipart/form-data
|
||||
},
|
||||
body: form,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const post = await response.json() as { ret: number, msg: string };
|
||||
if (post.ret !== 0) {
|
||||
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
|
||||
}
|
||||
|
||||
offset += chunk.length;
|
||||
seq++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片到群相册
|
||||
*/
|
||||
export async function uploadImageToGroupAlbum(
|
||||
cookieObject: Record<string, string>,
|
||||
groupId: string,
|
||||
albumId: string,
|
||||
albumName: string,
|
||||
filePath: string,
|
||||
uin: string
|
||||
): Promise<void> {
|
||||
const { loadBinarySource } = await import('../highway/utils');
|
||||
const loaded = await loadBinarySource(filePath, 'album image');
|
||||
|
||||
let tempFile: string | null = null;
|
||||
let actualPath = filePath;
|
||||
|
||||
if (/^(https?:\/\/|base64:\/\/)/i.test(filePath)) {
|
||||
tempFile = join(tmpdir(), `album_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`);
|
||||
writeFileSync(tempFile, loaded.bytes);
|
||||
actualPath = tempFile;
|
||||
}
|
||||
|
||||
try {
|
||||
const imgMd5 = createHash('md5').update(loaded.bytes).digest('hex');
|
||||
// const imgSize = loaded.bytes.length;
|
||||
const skey = cookieObject.skey || '';
|
||||
const pskey = cookieObject.p_skey || '';
|
||||
|
||||
const session = await createAlbumUploadSession(groupId, albumId, albumName, actualPath, skey, pskey, imgMd5, uin);
|
||||
|
||||
await uploadAlbumSlice(session, actualPath, imgMd5, skey, pskey, uin);
|
||||
|
||||
} finally {
|
||||
if (tempFile) {
|
||||
try { unlinkSync(tempFile); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
// 定义接口返回类型
|
||||
export interface GroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
data: {
|
||||
is_end: boolean;
|
||||
msg_list: any[]; // 具体结构视需要补充
|
||||
[key: string]: any;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
export async function getGroupEssenceMsg(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
pageStart: number = 0,
|
||||
pageLimit: number = 50
|
||||
): Promise<GroupEssenceMsgRet | undefined> {
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
|
||||
bkn: bkn,
|
||||
page_start: pageStart.toString(),
|
||||
page_limit: pageLimit.toString(),
|
||||
group_code: groupCode,
|
||||
}).toString()}`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息 (最多循环 20 页)
|
||||
*/
|
||||
export async function getGroupEssenceMsgAll(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
): Promise<GroupEssenceMsgRet[]> {
|
||||
const ret: GroupEssenceMsgRet[] = [];
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
|
||||
|
||||
if (!data) break;
|
||||
|
||||
ret.push(data);
|
||||
|
||||
if (data.data?.is_end) break;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export enum WebHonorType {
|
||||
TALKATIVE = 'talkative',
|
||||
PERFORMER = 'performer',
|
||||
LEGEND = 'legend',
|
||||
EMOTION = 'emotion',
|
||||
ALL = 'all',
|
||||
}
|
||||
|
||||
|
||||
async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
let resJson;
|
||||
try {
|
||||
const res = await RequestUtil.HttpGetText(
|
||||
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
|
||||
gc: groupCode,
|
||||
type: type.toString(),
|
||||
}).toString()}`,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
|
||||
if (match?.[1]) {
|
||||
resJson = JSON.parse(match[1].trim());
|
||||
}
|
||||
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
|
||||
} catch (e) {
|
||||
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
try {
|
||||
const data = await fetchHonorData(cookieObject, groupCode, type);
|
||||
if (!data) return [];
|
||||
|
||||
return data.map((item: any) => ({
|
||||
user_id: item?.uin,
|
||||
nickname: item?.name,
|
||||
avatar: item?.avatar,
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
|
||||
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import https from 'node:https';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec?: number;
|
||||
em?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface UploadImageRetSuccess {
|
||||
ec?: number;
|
||||
id?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeFeed {
|
||||
fid: string;
|
||||
u: number;
|
||||
pubt: number;
|
||||
msg: {
|
||||
text: string;
|
||||
pics?: Array<{ id: string; w: number; h: number }>;
|
||||
};
|
||||
settings: any;
|
||||
read_num: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeRet {
|
||||
ec: number;
|
||||
em?: string;
|
||||
feeds?: Record<string, WebApiGroupNoticeFeed>;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export function calculateBkn(key: string): string {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
const code = key.charCodeAt(i);
|
||||
hash = hash + (hash << 5) + code;
|
||||
}
|
||||
return (hash & 0x7FFFFFFF).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送群公告 Web API
|
||||
*/
|
||||
export async function setGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
content: string,
|
||||
pinned: number = 0,
|
||||
type: number = 1,
|
||||
isShowEditCard: number = 1,
|
||||
tipWindowType: number = 1,
|
||||
confirmRequired: number = 1,
|
||||
picId: string = '',
|
||||
imgWidth: number = 540,
|
||||
imgHeight: number = 300
|
||||
): Promise<SetNoticeRetSuccess | undefined> {
|
||||
try {
|
||||
// 分别获取 skey 和 p_skey
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey);
|
||||
const urlBkn = calculateBkn(pskey);
|
||||
//
|
||||
// console.log(skey)
|
||||
// console.log(pskey)
|
||||
//
|
||||
// console.log(urlBkn);
|
||||
// console.log(bodyBkn)
|
||||
|
||||
const settings = JSON.stringify({
|
||||
is_show_edit_card: isShowEditCard,
|
||||
tip_window_type: tipWindowType,
|
||||
confirm_required: confirmRequired,
|
||||
});
|
||||
|
||||
const bodyParams: Record<string, string> = {
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn,
|
||||
text: content,
|
||||
pinned: pinned.toString(),
|
||||
type: type.toString(),
|
||||
settings,
|
||||
};
|
||||
|
||||
if (picId !== '') {
|
||||
bodyParams.pic = picId;
|
||||
bodyParams.imgWidth = imgWidth.toString();
|
||||
bodyParams.imgHeight = imgHeight.toString();
|
||||
}
|
||||
|
||||
// 注意这里:URL 必须使用 skey 算出来的 bkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
|
||||
const body = new URLSearchParams(bodyParams).toString();
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
body,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取群公告列表 Web API
|
||||
*/
|
||||
export async function getGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
start: number = -1, // -1 表示第一页
|
||||
count: number = 20 // 抓包中是 10,你可以根据需要调整
|
||||
): Promise<WebApiGroupNoticeRet | undefined> {
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
|
||||
|
||||
const bodyParams = new URLSearchParams({
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
|
||||
ft: '23',
|
||||
s: start.toString(), // 分页游标
|
||||
n: count.toString(), // 获取数量
|
||||
i: '1',
|
||||
ni: '1'
|
||||
}).toString();
|
||||
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
||||
url,
|
||||
'POST',
|
||||
bodyParams,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
// console.log(JSON.stringify(ret, null, 2));
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 上传群公告图片 Web API
|
||||
*/
|
||||
export async function uploadGroupNoticeImage(
|
||||
cookieObject: Record<string, string>,
|
||||
imageBuffer: Buffer
|
||||
): Promise<{ id: string; width: number; height: number } | undefined> {
|
||||
try {
|
||||
const bkn = calculateBkn(cookieObject['skey']);
|
||||
const boundary = `-----------------------------${Date.now()}`;
|
||||
|
||||
const parts: Buffer[] = [];
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
|
||||
parts.push(imageBuffer);
|
||||
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
|
||||
|
||||
const body = Buffer.concat(parts);
|
||||
|
||||
const options = {
|
||||
hostname: 'web.qun.qq.com',
|
||||
path: '/cgi-bin/announce/upload_img',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
||||
'Content-Length': body.length,
|
||||
'Cookie': cookieToString(cookieObject),
|
||||
},
|
||||
};
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const req = https.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const result = JSON.parse(data) as UploadImageRetSuccess;
|
||||
if (result.ec === 0 && result.id) {
|
||||
const unescapedIdStr = result.id.replace(/"/g, '"');
|
||||
|
||||
const idObj = JSON.parse(unescapedIdStr);
|
||||
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
|
||||
} else {
|
||||
resolve(undefined);
|
||||
}
|
||||
} catch {
|
||||
resolve(undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', (err) => {
|
||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
||||
resolve(undefined);
|
||||
});
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
} catch (e) {
|
||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除群公告 Web API
|
||||
*/
|
||||
export async function deleteGroupNotice(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
fid: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
|
||||
|
||||
const params = new URLSearchParams({
|
||||
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
|
||||
fid: fid,
|
||||
qid: groupCode,
|
||||
}).toString();
|
||||
|
||||
// 注意这里:URL 拼接 urlBkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
params,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret?.ec === 0;
|
||||
} catch (e) {
|
||||
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import https from 'node:https';
|
||||
import http from 'node:http';
|
||||
|
||||
export class RequestUtil {
|
||||
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
|
||||
const client = url.startsWith('https') ? https : http;
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = client.get(url, (res) => {
|
||||
const cookies: { [key: string]: string; } = {};
|
||||
|
||||
res.on('data', () => { }); // 必须消耗流
|
||||
res.on('end', () => {
|
||||
this.handleRedirect(res, url, cookies)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
|
||||
if (res.headers['set-cookie']) {
|
||||
this.extractCookies(res.headers['set-cookie'], cookies);
|
||||
}
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
|
||||
if (res.statusCode === 301 || res.statusCode === 302) {
|
||||
if (res.headers.location) {
|
||||
const redirectUrl = new URL(res.headers.location, url);
|
||||
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
|
||||
return { ...cookies, ...redirectCookies };
|
||||
}
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
|
||||
setCookieHeaders.forEach((cookie) => {
|
||||
const parts = cookie.split(';')[0]?.split('=');
|
||||
if (parts) {
|
||||
const key = parts[0];
|
||||
const value = parts[1];
|
||||
if (key && value && key.length > 0 && value.length > 0) {
|
||||
cookies[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: {
|
||||
[key: string]: string;
|
||||
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
|
||||
const option = new URL(url);
|
||||
const protocol = url.startsWith('https://') ? https : http;
|
||||
const options = {
|
||||
hostname: option.hostname,
|
||||
port: option.port,
|
||||
path: option.pathname + option.search,
|
||||
method,
|
||||
headers,
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = protocol.request(options, (res: http.IncomingMessage) => {
|
||||
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
|
||||
if (maxRedirects <= 0) {
|
||||
reject(new Error('Too many redirects'));
|
||||
return;
|
||||
}
|
||||
const redirectUrl = new URL(res.headers.location, url).href;
|
||||
this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
let responseBody = '';
|
||||
res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
|
||||
|
||||
res.on('end', () => {
|
||||
try {
|
||||
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
|
||||
if (isJsonRet) {
|
||||
resolve(JSON.parse(responseBody) as T);
|
||||
} else {
|
||||
resolve(responseBody as T);
|
||||
}
|
||||
} else {
|
||||
reject(new Error(`Unexpected status code: ${res.statusCode}`));
|
||||
}
|
||||
} catch (parseError: any) {
|
||||
reject(new Error(parseError.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => reject(error));
|
||||
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
|
||||
req.write(isArgJson ? JSON.stringify(data) : data);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
|
||||
return this.HttpGetJson<string>(url, method, data, headers, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
export function cookieToString(cookieObject: Record<string, string>): string {
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
|
||||
export function getBknFromCookie(cookieObject: Record<string, string>): string {
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return (hash & 2147483647).toString();
|
||||
}
|
||||
Reference in new issue
Block a user