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`.
346 lines
13 KiB
TypeScript
346 lines
13 KiB
TypeScript
// MessageApi — send / recall / mark-read operations.
|
|
//
|
|
// Folds together the previous shapes:
|
|
// - `Bridge.sendGroupMessage` / `sendPrivateMessage` / `sendC2cFileMessage`
|
|
// (formerly inline on the Bridge class).
|
|
// - `actions/group-message.ts` (recallGroup / recallPrivate /
|
|
// markGroupRead / markPrivateRead).
|
|
//
|
|
// All implementations are inlined here — the previous indirection
|
|
// through `actions/group-message.ts` exported functions was just
|
|
// `(bridge, args) → method body`; once methods live on a typed Api
|
|
// class the wrapper layer doesn't earn its keep.
|
|
|
|
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
|
import type {
|
|
SendMessageRequest,
|
|
SendMessageResponse,
|
|
} from '@snowluma/proto-defs/action';
|
|
import type { FileExtra } from '@snowluma/proto-defs/message';
|
|
import type {
|
|
C2CRecallRequest,
|
|
GroupRecallRequest,
|
|
SsoReadedReportReq,
|
|
} from '@snowluma/proto-defs/oidb-actions/base';
|
|
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`
|
|
// (which still takes `Bridge` because the highway upload helpers it
|
|
// transitively calls each take `Bridge` — refactoring those is a
|
|
// separate concern that doesn't need to land alongside the Api split).
|
|
//
|
|
// At runtime `ctx` IS the Bridge instance that constructed this
|
|
// MessageApi — `buildApiHub(ctx)` passes the Bridge itself.
|
|
import type { Bridge, SendMessageReceipt } from '../bridge';
|
|
|
|
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
|
|
|
export class MessageApi {
|
|
constructor(private readonly ctx: BridgeContext) {}
|
|
|
|
/**
|
|
* Send a message to a QQ group.
|
|
*
|
|
* Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`.
|
|
* Media elements (image / record / video) trigger highway uploads
|
|
* inside `buildSendElems` — see `element-builder.ts`.
|
|
*
|
|
* Returns a `SendMessageReceipt` carrying the assigned messageId,
|
|
* group sequence, and timestamps; callers cache this for later
|
|
* `recall` / reply lookups.
|
|
*/
|
|
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
|
if (elements.length === 0) throw new Error('message is empty');
|
|
|
|
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, groupId });
|
|
const random = this.ctx.nextMessageRandom();
|
|
|
|
const request = protobuf_encode<SendMessageRequest>({
|
|
routingHead: {
|
|
grp: { groupCode: BigInt(groupId) },
|
|
},
|
|
contentHead: {
|
|
type: 1,
|
|
},
|
|
messageBody: {
|
|
richText: {
|
|
elems: protoElems,
|
|
},
|
|
} as any,
|
|
clientSequence: 0,
|
|
random,
|
|
syncCookie: new Uint8Array(0),
|
|
via: 0,
|
|
dataStatist: 0,
|
|
multiSendSeq: 0,
|
|
});
|
|
|
|
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
|
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
|
|
}
|
|
|
|
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
|
if (!response) throw new Error('failed to decode SendMessageResponse');
|
|
if (response.result != null && response.result !== 0) {
|
|
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
|
}
|
|
|
|
const seq = response.groupSequence ?? 0;
|
|
const messageId = (random & 0x7FFFFFFF) || seq;
|
|
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
|
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
|
|
}
|
|
|
|
/**
|
|
* Send a c2c (private) message.
|
|
*
|
|
* Resolves the recipient's UID only when the message carries media
|
|
* — text-only messages skip the lookup. Routes through `c2c.uin`
|
|
* (and optionally `c2c.uid` for the media case).
|
|
*/
|
|
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
|
if (elements.length === 0) throw new Error('message is empty');
|
|
|
|
let userUid = '';
|
|
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
|
if (hasMedia) {
|
|
userUid = await this.ctx.resolveUserUid(userUin);
|
|
}
|
|
|
|
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
|
|
const random = this.ctx.nextMessageRandom();
|
|
const clientSeq = this.ctx.nextClientSequence();
|
|
|
|
const request = protobuf_encode<SendMessageRequest>({
|
|
routingHead: {
|
|
c2c: {
|
|
uin: userUin,
|
|
...(userUid ? { uid: userUid } : {}),
|
|
},
|
|
},
|
|
contentHead: {
|
|
type: 1,
|
|
subType: 0,
|
|
c2cCmd: 11,
|
|
},
|
|
messageBody: {
|
|
richText: {
|
|
elems: protoElems,
|
|
},
|
|
} as any,
|
|
clientSequence: clientSeq,
|
|
random,
|
|
syncCookie: new Uint8Array(0),
|
|
via: 0,
|
|
dataStatist: 0,
|
|
ctrl: {
|
|
msgFlag: Math.floor(Date.now() / 1000),
|
|
},
|
|
multiSendSeq: 0,
|
|
});
|
|
|
|
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
|
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
|
|
}
|
|
|
|
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
|
if (!response) throw new Error('failed to decode SendMessageResponse');
|
|
if (response.result != null && response.result !== 0) {
|
|
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
|
}
|
|
|
|
const seq = response.privateSequence ?? 0;
|
|
const messageId = (random & 0x7FFFFFFF) || seq;
|
|
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
|
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
|
}
|
|
|
|
/**
|
|
* Send a c2c file as a chat message.
|
|
*
|
|
* The wire shape isn't the same as a regular c2c message — the c2c
|
|
* file path uses three slots that differ from a normal text/image
|
|
* send (verified against `dev/Lagrange.Core/.../MessagePacker.cs:
|
|
* BuildPacketBase` + `FileEntity.PackMessageContent`):
|
|
*
|
|
* 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of
|
|
* `routingHead.c2c { uin, uid }`. The server rejects c2c file
|
|
* messages routed through the regular c2c slot.
|
|
* 2. `messageBody.msgContent` carries the serialised
|
|
* `FileExtra { file: NotOnlineFile }` bytes. NOT
|
|
* `richText.notOnlineFile` — the receiver doesn't read that
|
|
* slot for file metadata.
|
|
* 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The
|
|
* previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT
|
|
* server doesn't recognise.
|
|
*
|
|
* NotOnlineFile carries three required-on-send fields the receiver
|
|
* itself ignores but the server's intake validator checks:
|
|
* - `subcmd: 1` — c2c file send command code
|
|
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
|
|
* - `expireTime` — 7 days from now (Lagrange convention)
|
|
*/
|
|
async sendC2cFile(
|
|
userUin: number,
|
|
userUid: string,
|
|
info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string },
|
|
): Promise<SendMessageReceipt> {
|
|
const random = this.ctx.nextMessageRandom();
|
|
const clientSeq = this.ctx.nextClientSequence();
|
|
|
|
const nowSec = Math.floor(Date.now() / 1000);
|
|
const sevenDaysSec = 7 * 24 * 60 * 60;
|
|
const fileExtraBytes = protobuf_encode<FileExtra>({
|
|
file: {
|
|
fileType: 0,
|
|
fileUuid: info.fileId,
|
|
fileMd5: info.fileMd5,
|
|
fileName: info.fileName,
|
|
fileSize: BigInt(info.fileSize),
|
|
subcmd: 1,
|
|
dangerEvel: 0,
|
|
expireTime: nowSec + sevenDaysSec,
|
|
fileHash: info.fileHash ?? '',
|
|
},
|
|
});
|
|
|
|
const request = protobuf_encode<SendMessageRequest>({
|
|
routingHead: {
|
|
trans0x211: { ccCmd: 4, uid: userUid },
|
|
},
|
|
contentHead: {
|
|
type: 1,
|
|
subType: 0,
|
|
},
|
|
messageBody: {
|
|
msgContent: fileExtraBytes,
|
|
},
|
|
clientSequence: clientSeq,
|
|
random,
|
|
syncCookie: new Uint8Array(0),
|
|
via: 0,
|
|
dataStatist: 0,
|
|
ctrl: { msgFlag: nowSec },
|
|
multiSendSeq: 0,
|
|
});
|
|
|
|
// `userUin` is part of the public contract (the OneBot layer
|
|
// threads it through for symmetry with `sendPrivate`) but the
|
|
// wire shape only needs the uid. Silence the unused-parameter
|
|
// lint without changing the signature.
|
|
void userUin;
|
|
|
|
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
|
throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`);
|
|
}
|
|
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
|
if (!response) throw new Error('failed to decode SendMessageResponse');
|
|
if (response.result != null && response.result !== 0) {
|
|
throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
|
}
|
|
const seq = response.privateSequence ?? 0;
|
|
const messageId = (random & 0x7FFFFFFF) || seq;
|
|
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
|
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
|
}
|
|
|
|
/**
|
|
* Recall (revoke) a group message by sequence number. Server-side
|
|
* the message ages out after the standard 2-minute window unless
|
|
* the user is an admin/owner.
|
|
*/
|
|
async recallGroup(groupId: number, sequence: number): Promise<void> {
|
|
const request = protobuf_encode<GroupRecallRequest>({
|
|
type: 1,
|
|
groupUin: groupId,
|
|
info: { sequence, random: 0, field3: 0 },
|
|
settings: { field1: 0 },
|
|
});
|
|
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
|
|
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
|
|
}
|
|
|
|
/**
|
|
* Recall a c2c (private) message. Needs more positional info than
|
|
* the group variant because c2c messages are identified by the
|
|
* `(clientSequence, msgSequence, random, timestamp)` tuple rather
|
|
* than a single group-side sequence.
|
|
*/
|
|
async recallPrivate(
|
|
userUin: number,
|
|
clientSeq: number,
|
|
msgSeq: number,
|
|
random: number,
|
|
timestamp: number,
|
|
): Promise<void> {
|
|
const targetUid = await this.ctx.resolveUserUid(userUin);
|
|
const request = protobuf_encode<C2CRecallRequest>({
|
|
type: 1,
|
|
targetUid,
|
|
info: {
|
|
clientSequence: clientSeq,
|
|
random,
|
|
messageId: BigInt((0x01000000 * 0x100000000) + random),
|
|
timestamp,
|
|
field5: 0,
|
|
messageSequence: msgSeq,
|
|
},
|
|
settings: { field1: false, field2: false },
|
|
field6: false,
|
|
});
|
|
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
|
|
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
|
|
}
|
|
|
|
/**
|
|
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
|
|
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
|
|
* NT client's own "scrolled to bottom" behaviour so subsequent
|
|
* sync packets don't replay messages we've already processed.
|
|
*/
|
|
async markGroupRead(groupId: number, sequence: number): Promise<void> {
|
|
const request = protobuf_encode<SsoReadedReportReq>({
|
|
groupList: [
|
|
{
|
|
groupUin: BigInt(groupId),
|
|
lastReadSeq: BigInt(sequence),
|
|
},
|
|
],
|
|
});
|
|
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
|
if (!result.success) {
|
|
throw new Error(result.errorMessage || 'mark group message read failed');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Push a c2c read-report. Same wire-cmd as the group variant but
|
|
* keyed by friend uid (resolved from uin via IdentityService).
|
|
* `lastReadTime` defaults to "now" — matches the QQ NT client
|
|
* which also uses wall-clock seconds rather than the read-message
|
|
* timestamp.
|
|
*/
|
|
async markPrivateRead(userId: number, sequence: number): Promise<void> {
|
|
const uid = await this.ctx.resolveUserUid(userId);
|
|
const request = protobuf_encode<SsoReadedReportReq>({
|
|
c2cList: [
|
|
{
|
|
uid,
|
|
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
|
|
lastReadSeq: BigInt(sequence),
|
|
},
|
|
],
|
|
});
|
|
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
|
if (!result.success) {
|
|
throw new Error(result.errorMessage || 'mark private message read failed');
|
|
}
|
|
}
|
|
}
|
|
|