Merge pull request #323 from SnowLuma/dev
chore: promote dev → main (4d958eb)
This commit is contained in:
84 files changed
+3931
-200
No files matched your search
@@ -143,6 +143,9 @@ jobs:
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Verify release layout
|
||||
run: pnpm check:release-layout
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
|
||||
|
||||
@@ -96,6 +96,9 @@ jobs:
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Verify release layout
|
||||
run: pnpm check:release-layout
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
|
||||
|
||||
+2
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -11,6 +11,7 @@
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:mcp": "pnpm --filter @snowluma/mcp build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter @snowluma/ui build && pnpm --filter webui build",
|
||||
"check:release-layout": "node tools/check-release-layout.mjs",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -293,6 +293,7 @@ export class ContactsApi {
|
||||
// is not in the list (0x88D_0 detail only), so it stays undefined here.
|
||||
createTime: raw.info?.createdTime ?? 0,
|
||||
memo: raw.info?.announcement || raw.info?.description || '',
|
||||
allMuted: (raw.info?.shutUpAllTimestamp ?? 0) > 0,
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
@@ -323,6 +324,7 @@ export class ContactsApi {
|
||||
createTime: Number(r.createTime ?? 0n),
|
||||
level: Number(r.level ?? 0n),
|
||||
memo: r.noticePreview ?? '',
|
||||
allMuted: (r.shutUpAllTimestamp ?? 0) > 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { MiscApi } from './misc';
|
||||
import { ProfileApi } from './profile';
|
||||
import { QzoneApi } from './qzone';
|
||||
import { WebApi } from './web';
|
||||
import { SystemFaceApi } from './system-face';
|
||||
|
||||
export interface ApiHub {
|
||||
/** Personal QQ collections: authenticated list retrieval and pagination. */
|
||||
@@ -46,6 +47,8 @@ export interface ApiHub {
|
||||
readonly extras: ExtrasApi;
|
||||
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
|
||||
readonly web: WebApi;
|
||||
/** QQ system-face directory: durable catalog, id lookup, and search. */
|
||||
readonly systemFace: SystemFaceApi;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,6 +76,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
misc: new MiscApi(ctx),
|
||||
extras: new ExtrasApi(ctx),
|
||||
web: new WebApi(ctx),
|
||||
systemFace: new SystemFaceApi(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -101,3 +105,4 @@ export { ProfileApi } from './profile';
|
||||
export { QzoneApi } from './qzone';
|
||||
export { FlashTransferApi, type FlashFileInfo } from './flash-transfer';
|
||||
export { WebApi } from './web';
|
||||
export { SystemFaceApi } from './system-face';
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
sysFaceStore,
|
||||
type SysFaceEntry,
|
||||
type SysFacePackEntry,
|
||||
} from '@snowluma/protocol/sys-face-store';
|
||||
import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/** QQ's account-independent system-face directory. The shared store owns
|
||||
* persistence and refresh coalescing; this API binds it to one live sender. */
|
||||
export class SystemFaceApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
fetchCatalog(refresh = false): Promise<SysFacePackEntry[]> {
|
||||
return sysFaceStore.getCatalog(this.ctx, refresh);
|
||||
}
|
||||
|
||||
async fetchFace(faceId: number, refresh = false): Promise<SysFaceEntry | null> {
|
||||
if (refresh) {
|
||||
await sysFaceStore.refresh(this.ctx);
|
||||
return sysFaceStore.lookup(faceId);
|
||||
}
|
||||
return sysFaceStore.resolve(this.ctx, faceId);
|
||||
}
|
||||
|
||||
async search(query: string): Promise<SysFaceEntry[]> {
|
||||
await sysFaceStore.ensureReady(this.ctx);
|
||||
return sysFaceStore.search(query);
|
||||
}
|
||||
|
||||
async isSuper(faceId: number, refresh = false): Promise<boolean> {
|
||||
const face = await this.fetchFace(faceId, refresh);
|
||||
return face !== null && isSuperFaceEntry(face);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { workerData } from 'node:worker_threads';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { createNotificationManager } from './notifications/manager';
|
||||
import { createStateWiring } from './webui/state-wiring';
|
||||
import { bindSystemFaceCatalog } from './sys-face-catalog';
|
||||
|
||||
const log = createLogger('App');
|
||||
|
||||
@@ -57,6 +58,7 @@ async function main() {
|
||||
cleanupInvalidPerUinConfigs();
|
||||
|
||||
const bridgeManager = new BridgeManager();
|
||||
bindSystemFaceCatalog(bridgeManager);
|
||||
const oneBotManager = new OneBotManager();
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import path from 'node:path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
SysFaceStore,
|
||||
sysFaceStore,
|
||||
type SysFaceCatalogStorage,
|
||||
} from '@snowluma/protocol/sys-face-store';
|
||||
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
|
||||
import type { BridgeManager } from './bridge/manager';
|
||||
|
||||
const log = createLogger('SysFace');
|
||||
|
||||
export interface SystemFaceCatalogBindingOptions {
|
||||
store?: SysFaceStore;
|
||||
storage?: SysFaceCatalogStorage;
|
||||
dataRoot?: string;
|
||||
}
|
||||
|
||||
/** Attach the shared system-face catalog to Bridge login edges. The first
|
||||
* account restores + refreshes it; later accounts reuse the same result. */
|
||||
export function bindSystemFaceCatalog(
|
||||
manager: BridgeManager,
|
||||
options: SystemFaceCatalogBindingOptions = {},
|
||||
): void {
|
||||
const store = options.store ?? sysFaceStore;
|
||||
const storage = options.storage ?? new JsonSysFaceCatalogStorage(
|
||||
path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'),
|
||||
);
|
||||
store.configureStorage(storage);
|
||||
|
||||
manager.addSessionStartedListener((uin, bridge) => {
|
||||
void store.prewarm(bridge).catch((error) => {
|
||||
log.error(
|
||||
'system face catalog login prewarm failed: uin=%s error=%s',
|
||||
uin,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import { traceWebuiMutationRequestChunk } from './mutation-trace';
|
||||
|
||||
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
|
||||
* kept distinct so the two cleanup stories don't entangle. */
|
||||
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload');
|
||||
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'webui-upload');
|
||||
|
||||
/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */
|
||||
export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
OidbFriend,
|
||||
OidbFriendCategory,
|
||||
OidbRobotUinRangeResponse,
|
||||
OidbSvcTrpcTcp0x88D_0Response,
|
||||
OidbSvcTrpcTcp0xFD4_1Response,
|
||||
OidbSvcTrpcTcp0xFE5_2Response,
|
||||
OidbSvcTrpcTcp0xFE7_3Response,
|
||||
@@ -99,6 +100,18 @@ function groupListPacket(body: OidbSvcTrpcTcp0xFE5_2Response): SendPacketResult
|
||||
};
|
||||
}
|
||||
|
||||
function groupDetailPacket(body: OidbSvcTrpcTcp0x88D_0Response): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({ body }),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) {
|
||||
let index = 0;
|
||||
const sendRawPacket = vi.fn(async (
|
||||
@@ -150,7 +163,12 @@ describe('apis/contacts / group roster', () => {
|
||||
const sendRawPacket = vi.fn(async () => groupListPacket({
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: { groupName: 'Project', memberCount: 42, memberMax: 500 },
|
||||
info: {
|
||||
groupName: 'Project',
|
||||
memberCount: 42,
|
||||
memberMax: 500,
|
||||
shutUpAllTimestamp: 4_294_967_295,
|
||||
},
|
||||
customInfo: { remark: ' My Project ' },
|
||||
}],
|
||||
}));
|
||||
@@ -167,9 +185,31 @@ describe('apis/contacts / group roster', () => {
|
||||
remark: ' My Project ',
|
||||
memberCount: 42,
|
||||
memberMax: 500,
|
||||
allMuted: true,
|
||||
})]);
|
||||
expect(rememberGroups).toHaveBeenCalledWith(groups);
|
||||
});
|
||||
|
||||
it('maps the group-wide mute timestamp from a single-group detail', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupDetailPacket({
|
||||
groupInfo: {
|
||||
uin: 123456789n,
|
||||
results: {
|
||||
name: 'Muted Group',
|
||||
shutUpAllTimestamp: 4_294_967_295,
|
||||
},
|
||||
},
|
||||
}));
|
||||
const api = new ContactsApi({ sendRawPacket, identity: {} } as any);
|
||||
|
||||
const detail = await api.fetchGroupDetail(123456789);
|
||||
|
||||
expect(detail).toEqual(expect.objectContaining({
|
||||
groupId: 123456789,
|
||||
groupName: 'Muted Group',
|
||||
allMuted: true,
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
describe('apis/contacts / categorized friend roster', () => {
|
||||
|
||||
@@ -30,6 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
|
||||
import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload';
|
||||
|
||||
const fakeBridge = {} as any;
|
||||
|
||||
@@ -168,6 +169,63 @@ describe('element-builder / commonElem.businessType per scene', () => {
|
||||
});
|
||||
|
||||
describe('element-builder / all-message validation preflight', () => {
|
||||
it('rejects hidden siblings and duplicate videos before uploading', async () => {
|
||||
vi.mocked(uploadVideoMsgInfo).mockClear();
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'video', url: 'file:///tmp/clip.mp4' },
|
||||
{ type: 'text', text: 'must not become hidden content' },
|
||||
], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
message: expect.stringContaining('only segment'),
|
||||
});
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'video', url: 'file:///tmp/first.mp4' },
|
||||
{ type: 'video', url: 'file:///tmp/second.mp4' },
|
||||
], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
message: expect.stringContaining('only once'),
|
||||
});
|
||||
|
||||
expect(uploadVideoMsgInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps empty canonical text invalid instead of sending it beside a video', async () => {
|
||||
vi.mocked(uploadVideoMsgInfo).mockClear();
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'text', text: '' },
|
||||
{ type: 'video', url: 'file:///tmp/clip.mp4' },
|
||||
], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
|
||||
code: 'INVALID_FIELD',
|
||||
elementType: 'text',
|
||||
});
|
||||
|
||||
expect(uploadVideoMsgInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies standalone-video validation to forward nodes', async () => {
|
||||
vi.mocked(uploadVideoMsgInfo).mockClear();
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'video', url: 'file:///tmp/clip.mp4' },
|
||||
{ type: 'text', text: 'must not survive bot forwarding' },
|
||||
], {
|
||||
bridge: fakeBridge,
|
||||
groupId: 12345,
|
||||
forwardFake: true,
|
||||
scene: 'forward',
|
||||
})).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
});
|
||||
|
||||
expect(uploadVideoMsgInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not upload an early image when a later segment is unsendable', async () => {
|
||||
vi.mocked(uploadImageMsgInfo).mockClear();
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { SysFaceStore, type SysFaceCatalogStorage } from '@snowluma/protocol/sys-face-store';
|
||||
import { BridgeManager } from '../src/bridge/manager';
|
||||
import { bindSystemFaceCatalog } from '../src/sys-face-catalog';
|
||||
|
||||
const storage: SysFaceCatalogStorage = {
|
||||
load: async () => null,
|
||||
save: async () => {},
|
||||
};
|
||||
|
||||
describe('bindSystemFaceCatalog', () => {
|
||||
it('starts one shared catalog prewarm from the first logged-in account', async () => {
|
||||
let fetches = 0;
|
||||
const store = new SysFaceStore({
|
||||
fetchCatalog: async () => {
|
||||
fetches += 1;
|
||||
return [{
|
||||
packName: '经典',
|
||||
emojis: [{
|
||||
qSid: '14', qDes: '/微笑', emCode: '14', qCid: null,
|
||||
aniStickerType: null, aniStickerPackId: null, aniStickerId: null,
|
||||
url: null, emojiNameAlias: [],
|
||||
aniStickerWidth: null, aniStickerHeight: null,
|
||||
}],
|
||||
}];
|
||||
},
|
||||
});
|
||||
const manager = new BridgeManager();
|
||||
bindSystemFaceCatalog(manager, { store, storage });
|
||||
|
||||
const packetSender = { sendPacket: vi.fn() } as never;
|
||||
manager.onHookLogin(101, '10001', packetSender);
|
||||
manager.onHookLogin(202, '20002', packetSender);
|
||||
|
||||
await vi.waitFor(() => expect(fetches).toBe(1));
|
||||
expect(store.lookup(14)?.qDes).toBe('/微笑');
|
||||
});
|
||||
});
|
||||
@@ -51,6 +51,10 @@ describe('safeUploadName', () => {
|
||||
});
|
||||
|
||||
describe('uploadDestPath', () => {
|
||||
it('uses a neutral temporary directory name', () => {
|
||||
expect(path.basename(DEBUG_UPLOAD_DIR)).toBe('webui-upload');
|
||||
});
|
||||
|
||||
it('produces a unique path inside the upload dir', () => {
|
||||
const a = uploadDestPath('pic.png');
|
||||
const b = uploadDestPath('pic.png');
|
||||
|
||||
@@ -56,7 +56,7 @@ reported as MCP errors because they mean no complete stream result was committed
|
||||
| `SNOWLUMA_MCP_TOKEN` | Access token (sent as `Authorization: Bearer …`), if the endpoint requires one. |
|
||||
| `SNOWLUMA_MCP_TIMEOUT_MS` | Ordinary-action request timeout; for Stream Actions, connection timeout **and per-read idle timeout** (the idle deadline resets after every body read). Default `30000`. Invalid values fail startup. |
|
||||
| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. Invalid values fail startup. |
|
||||
| `SNOWLUMA_MCP_STREAM_DIR` | Directory on the MCP host for completed Stream Action downloads. Created and validated at startup. Default: `os.tmpdir()/snowluma-mcp/downloads`. |
|
||||
| `SNOWLUMA_MCP_STREAM_DIR` | Directory on the MCP host for completed Stream Action downloads. Created and validated at startup. Default: `os.tmpdir()/onebot-mcp-downloads`. |
|
||||
| `SNOWLUMA_MCP_UPLOAD_ROOT` | Existing directory on the MCP host from which automatic uploads may read. Automatic upload is disabled when absent. |
|
||||
| `SNOWLUMA_MCP_MAX_STREAM_BYTES` | Per-file download/upload ceiling in bytes. Positive integer up to 4 GiB; default `4294967296`. Invalid values fail server startup. |
|
||||
|
||||
@@ -90,7 +90,7 @@ groups, etc.). Enable deliberately:
|
||||
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
|
||||
"SNOWLUMA_MCP_TOKEN": "your-access-token",
|
||||
"SNOWLUMA_MCP_MODE": "write",
|
||||
"SNOWLUMA_MCP_STREAM_DIR": "/var/tmp/snowluma-mcp-downloads",
|
||||
"SNOWLUMA_MCP_STREAM_DIR": "/var/tmp/onebot-mcp-downloads",
|
||||
"SNOWLUMA_MCP_UPLOAD_ROOT": "/home/me/mcp-share"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -15,7 +15,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_STREAM_BYTES = 4 * 1024 * 1024 * 1024;
|
||||
const DEFAULT_STREAM_DIR = path.join(os.tmpdir(), 'snowluma-mcp', 'downloads');
|
||||
const DEFAULT_STREAM_DIR = path.join(os.tmpdir(), 'onebot-mcp-downloads');
|
||||
const MAX_GENERIC_FRAMES = 256;
|
||||
const MAX_GENERIC_TEXT_BYTES = 256 * 1024;
|
||||
// OneBot permits a 16 MiB decoded download chunk. Base64 expands that to
|
||||
|
||||
@@ -2030,6 +2030,147 @@
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "fetch_face_entity",
|
||||
"aliases": [],
|
||||
"summary": "按编号查询 QQ 系统表情",
|
||||
"returns": "表情详情;编号不存在时返回 null。",
|
||||
"returnsSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"q_sid": {
|
||||
"type": "string",
|
||||
"description": "表情编号"
|
||||
},
|
||||
"q_des": {
|
||||
"type": "string",
|
||||
"description": "表情描述"
|
||||
},
|
||||
"em_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"q_cid": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_type": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_pack_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"emoji_name_alias": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ani_sticker_width": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_height": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"is_super": {
|
||||
"type": "boolean",
|
||||
"description": "是否使用超级表情格式"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"q_sid",
|
||||
"q_des",
|
||||
"em_code",
|
||||
"q_cid",
|
||||
"ani_sticker_type",
|
||||
"ani_sticker_pack_id",
|
||||
"ani_sticker_id",
|
||||
"url",
|
||||
"emoji_name_alias",
|
||||
"ani_sticker_width",
|
||||
"ani_sticker_height",
|
||||
"is_super"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "face_id",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"role": "face_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"desc": "QQ 系统表情编号"
|
||||
},
|
||||
{
|
||||
"name": "refresh",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false,
|
||||
"desc": "是否强制从 QQ 刷新目录"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"face_id": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"description": "QQ 系统表情编号",
|
||||
"x-role": "face_id"
|
||||
},
|
||||
"refresh": {
|
||||
"type": "boolean",
|
||||
"description": "是否强制从 QQ 刷新目录",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"face_id"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "fetch_ptt_text",
|
||||
"aliases": [
|
||||
@@ -2077,6 +2218,209 @@
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "fetch_super_face_id",
|
||||
"aliases": [],
|
||||
"summary": "判断 QQ 系统表情是否使用超级表情格式",
|
||||
"returns": "是否使用超级表情格式。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"is_super": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"is_super"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "face_id",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"role": "face_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"desc": "QQ 系统表情编号"
|
||||
},
|
||||
{
|
||||
"name": "refresh",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false,
|
||||
"desc": "是否强制从 QQ 刷新目录"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"face_id": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"description": "QQ 系统表情编号",
|
||||
"x-role": "face_id"
|
||||
},
|
||||
"refresh": {
|
||||
"type": "boolean",
|
||||
"description": "是否强制从 QQ 刷新目录",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"face_id"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "fetch_sys_faces",
|
||||
"aliases": [],
|
||||
"summary": "获取 QQ 系统表情目录",
|
||||
"returns": "按分组返回完整的 QQ 系统表情映射。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"packs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pack_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"emojis": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"q_sid": {
|
||||
"type": "string",
|
||||
"description": "表情编号"
|
||||
},
|
||||
"q_des": {
|
||||
"type": "string",
|
||||
"description": "表情描述"
|
||||
},
|
||||
"em_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"q_cid": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_type": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_pack_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"emoji_name_alias": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ani_sticker_width": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_height": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"is_super": {
|
||||
"type": "boolean",
|
||||
"description": "是否使用超级表情格式"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"q_sid",
|
||||
"q_des",
|
||||
"em_code",
|
||||
"q_cid",
|
||||
"ani_sticker_type",
|
||||
"ani_sticker_pack_id",
|
||||
"ani_sticker_id",
|
||||
"url",
|
||||
"emoji_name_alias",
|
||||
"ani_sticker_width",
|
||||
"ani_sticker_height",
|
||||
"is_super"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pack_name",
|
||||
"emojis"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"packs"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "refresh",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false,
|
||||
"desc": "是否强制从 QQ 刷新目录"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"refresh": {
|
||||
"type": "boolean",
|
||||
"description": "是否强制从 QQ 刷新目录",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "forward_friend_single_msg",
|
||||
"aliases": [],
|
||||
@@ -3799,6 +4143,59 @@
|
||||
"name": "get_group_detail_info",
|
||||
"aliases": [],
|
||||
"summary": "获取群详细信息",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"description": "群号"
|
||||
},
|
||||
"group_name": {
|
||||
"type": "string",
|
||||
"description": "群名"
|
||||
},
|
||||
"group_remark": {
|
||||
"type": "string",
|
||||
"description": "当前账号设置的群备注"
|
||||
},
|
||||
"member_count": {
|
||||
"type": "integer",
|
||||
"description": "当前成员数"
|
||||
},
|
||||
"max_member_count": {
|
||||
"type": "integer",
|
||||
"description": "成员上限"
|
||||
},
|
||||
"group_create_time": {
|
||||
"type": "integer",
|
||||
"description": "建群时间戳(秒)"
|
||||
},
|
||||
"group_level": {
|
||||
"type": "integer",
|
||||
"description": "群等级"
|
||||
},
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_id",
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
@@ -3810,6 +4207,15 @@
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "no_cache",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -3820,6 +4226,10 @@
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"no_cache": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4371,6 +4781,14 @@
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4378,7 +4796,8 @@
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count"
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
@@ -4430,6 +4849,59 @@
|
||||
"name": "get_group_info_ex",
|
||||
"aliases": [],
|
||||
"summary": "获取群信息(扩展)",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"description": "群号"
|
||||
},
|
||||
"group_name": {
|
||||
"type": "string",
|
||||
"description": "群名"
|
||||
},
|
||||
"group_remark": {
|
||||
"type": "string",
|
||||
"description": "当前账号设置的群备注"
|
||||
},
|
||||
"member_count": {
|
||||
"type": "integer",
|
||||
"description": "当前成员数"
|
||||
},
|
||||
"max_member_count": {
|
||||
"type": "integer",
|
||||
"description": "成员上限"
|
||||
},
|
||||
"group_create_time": {
|
||||
"type": "integer",
|
||||
"description": "建群时间戳(秒)"
|
||||
},
|
||||
"group_level": {
|
||||
"type": "integer",
|
||||
"description": "群等级"
|
||||
},
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_id",
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
@@ -4441,6 +4913,15 @@
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "no_cache",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -4451,6 +4932,10 @@
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"no_cache": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4501,6 +4986,14 @@
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4508,7 +5001,8 @@
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count"
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -4586,6 +5080,10 @@
|
||||
"type": "integer",
|
||||
"description": "最后发言时间戳(秒)"
|
||||
},
|
||||
"shut_up_timestamp": {
|
||||
"type": "integer",
|
||||
"description": "禁言结束时间戳(秒,未禁言时为 0)"
|
||||
},
|
||||
"level": {
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
@@ -4741,6 +5239,10 @@
|
||||
"type": "integer",
|
||||
"description": "最后发言时间戳(秒)"
|
||||
},
|
||||
"shut_up_timestamp": {
|
||||
"type": "integer",
|
||||
"description": "禁言结束时间戳(秒,未禁言时为 0)"
|
||||
},
|
||||
"level": {
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
@@ -7373,6 +7875,134 @@
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "search_sys_faces",
|
||||
"aliases": [],
|
||||
"summary": "搜索 QQ 系统表情",
|
||||
"returns": "匹配编号、名称、别名或分组名的表情列表。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"faces": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"q_sid": {
|
||||
"type": "string",
|
||||
"description": "表情编号"
|
||||
},
|
||||
"q_des": {
|
||||
"type": "string",
|
||||
"description": "表情描述"
|
||||
},
|
||||
"em_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"q_cid": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_type": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_pack_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"emoji_name_alias": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ani_sticker_width": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_height": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"is_super": {
|
||||
"type": "boolean",
|
||||
"description": "是否使用超级表情格式"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"q_sid",
|
||||
"q_des",
|
||||
"em_code",
|
||||
"q_cid",
|
||||
"ani_sticker_type",
|
||||
"ani_sticker_pack_id",
|
||||
"ani_sticker_id",
|
||||
"url",
|
||||
"emoji_name_alias",
|
||||
"ani_sticker_width",
|
||||
"ani_sticker_height",
|
||||
"is_super"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"faces"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "query",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "编号、名称、别名或分组名"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "编号、名称、别名或分组名"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"query"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "send_ark_share",
|
||||
"aliases": [],
|
||||
@@ -11049,6 +11679,10 @@
|
||||
"category": "空间",
|
||||
"count": 9
|
||||
},
|
||||
{
|
||||
"category": "系统表情",
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"category": "流式接口",
|
||||
"count": 6
|
||||
|
||||
@@ -2033,6 +2033,147 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "fetch_face_entity",
|
||||
"aliases": [],
|
||||
"summary": "按编号查询 QQ 系统表情",
|
||||
"returns": "表情详情;编号不存在时返回 null。",
|
||||
"returnsSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"q_sid": {
|
||||
"type": "string",
|
||||
"description": "表情编号"
|
||||
},
|
||||
"q_des": {
|
||||
"type": "string",
|
||||
"description": "表情描述"
|
||||
},
|
||||
"em_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"q_cid": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_type": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_pack_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"emoji_name_alias": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ani_sticker_width": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_height": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"is_super": {
|
||||
"type": "boolean",
|
||||
"description": "是否使用超级表情格式"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"q_sid",
|
||||
"q_des",
|
||||
"em_code",
|
||||
"q_cid",
|
||||
"ani_sticker_type",
|
||||
"ani_sticker_pack_id",
|
||||
"ani_sticker_id",
|
||||
"url",
|
||||
"emoji_name_alias",
|
||||
"ani_sticker_width",
|
||||
"ani_sticker_height",
|
||||
"is_super"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "face_id",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"role": "face_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"desc": "QQ 系统表情编号"
|
||||
},
|
||||
{
|
||||
"name": "refresh",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false,
|
||||
"desc": "是否强制从 QQ 刷新目录"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"face_id": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"description": "QQ 系统表情编号",
|
||||
"x-role": "face_id"
|
||||
},
|
||||
"refresh": {
|
||||
"type": "boolean",
|
||||
"description": "是否强制从 QQ 刷新目录",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"face_id"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "fetch_ptt_text",
|
||||
"aliases": [
|
||||
@@ -2080,6 +2221,209 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "fetch_super_face_id",
|
||||
"aliases": [],
|
||||
"summary": "判断 QQ 系统表情是否使用超级表情格式",
|
||||
"returns": "是否使用超级表情格式。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"is_super": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"is_super"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "face_id",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"role": "face_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"desc": "QQ 系统表情编号"
|
||||
},
|
||||
{
|
||||
"name": "refresh",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false,
|
||||
"desc": "是否强制从 QQ 刷新目录"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"face_id": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"description": "QQ 系统表情编号",
|
||||
"x-role": "face_id"
|
||||
},
|
||||
"refresh": {
|
||||
"type": "boolean",
|
||||
"description": "是否强制从 QQ 刷新目录",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"face_id"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "fetch_sys_faces",
|
||||
"aliases": [],
|
||||
"summary": "获取 QQ 系统表情目录",
|
||||
"returns": "按分组返回完整的 QQ 系统表情映射。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"packs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pack_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"emojis": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"q_sid": {
|
||||
"type": "string",
|
||||
"description": "表情编号"
|
||||
},
|
||||
"q_des": {
|
||||
"type": "string",
|
||||
"description": "表情描述"
|
||||
},
|
||||
"em_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"q_cid": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_type": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_pack_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"emoji_name_alias": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ani_sticker_width": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_height": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"is_super": {
|
||||
"type": "boolean",
|
||||
"description": "是否使用超级表情格式"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"q_sid",
|
||||
"q_des",
|
||||
"em_code",
|
||||
"q_cid",
|
||||
"ani_sticker_type",
|
||||
"ani_sticker_pack_id",
|
||||
"ani_sticker_id",
|
||||
"url",
|
||||
"emoji_name_alias",
|
||||
"ani_sticker_width",
|
||||
"ani_sticker_height",
|
||||
"is_super"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pack_name",
|
||||
"emojis"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"packs"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "refresh",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false,
|
||||
"desc": "是否强制从 QQ 刷新目录"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"refresh": {
|
||||
"type": "boolean",
|
||||
"description": "是否强制从 QQ 刷新目录",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "forward_friend_single_msg",
|
||||
"aliases": [],
|
||||
@@ -3802,6 +4146,59 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"name": "get_group_detail_info",
|
||||
"aliases": [],
|
||||
"summary": "获取群详细信息",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"description": "群号"
|
||||
},
|
||||
"group_name": {
|
||||
"type": "string",
|
||||
"description": "群名"
|
||||
},
|
||||
"group_remark": {
|
||||
"type": "string",
|
||||
"description": "当前账号设置的群备注"
|
||||
},
|
||||
"member_count": {
|
||||
"type": "integer",
|
||||
"description": "当前成员数"
|
||||
},
|
||||
"max_member_count": {
|
||||
"type": "integer",
|
||||
"description": "成员上限"
|
||||
},
|
||||
"group_create_time": {
|
||||
"type": "integer",
|
||||
"description": "建群时间戳(秒)"
|
||||
},
|
||||
"group_level": {
|
||||
"type": "integer",
|
||||
"description": "群等级"
|
||||
},
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_id",
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
@@ -3813,6 +4210,15 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "no_cache",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -3823,6 +4229,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"no_cache": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4374,6 +4784,14 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4381,7 +4799,8 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count"
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
@@ -4433,6 +4852,59 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"name": "get_group_info_ex",
|
||||
"aliases": [],
|
||||
"summary": "获取群信息(扩展)",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"description": "群号"
|
||||
},
|
||||
"group_name": {
|
||||
"type": "string",
|
||||
"description": "群名"
|
||||
},
|
||||
"group_remark": {
|
||||
"type": "string",
|
||||
"description": "当前账号设置的群备注"
|
||||
},
|
||||
"member_count": {
|
||||
"type": "integer",
|
||||
"description": "当前成员数"
|
||||
},
|
||||
"max_member_count": {
|
||||
"type": "integer",
|
||||
"description": "成员上限"
|
||||
},
|
||||
"group_create_time": {
|
||||
"type": "integer",
|
||||
"description": "建群时间戳(秒)"
|
||||
},
|
||||
"group_level": {
|
||||
"type": "integer",
|
||||
"description": "群等级"
|
||||
},
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_id",
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
@@ -4444,6 +4916,15 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "no_cache",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": false
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -4454,6 +4935,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"no_cache": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4504,6 +4989,14 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"group_memo": {
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
-1,
|
||||
0
|
||||
],
|
||||
"description": "是否开启全员禁言(-1 开启,0 关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -4511,7 +5004,8 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"group_name",
|
||||
"group_remark",
|
||||
"member_count",
|
||||
"max_member_count"
|
||||
"max_member_count",
|
||||
"group_all_shut"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -4589,6 +5083,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"description": "最后发言时间戳(秒)"
|
||||
},
|
||||
"shut_up_timestamp": {
|
||||
"type": "integer",
|
||||
"description": "禁言结束时间戳(秒,未禁言时为 0)"
|
||||
},
|
||||
"level": {
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
@@ -4744,6 +5242,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"description": "最后发言时间戳(秒)"
|
||||
},
|
||||
"shut_up_timestamp": {
|
||||
"type": "integer",
|
||||
"description": "禁言结束时间戳(秒,未禁言时为 0)"
|
||||
},
|
||||
"level": {
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
@@ -7376,6 +7878,134 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "search_sys_faces",
|
||||
"aliases": [],
|
||||
"summary": "搜索 QQ 系统表情",
|
||||
"returns": "匹配编号、名称、别名或分组名的表情列表。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"faces": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"q_sid": {
|
||||
"type": "string",
|
||||
"description": "表情编号"
|
||||
},
|
||||
"q_des": {
|
||||
"type": "string",
|
||||
"description": "表情描述"
|
||||
},
|
||||
"em_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"q_cid": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_type": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_pack_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_id": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"emoji_name_alias": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ani_sticker_width": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"ani_sticker_height": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"is_super": {
|
||||
"type": "boolean",
|
||||
"description": "是否使用超级表情格式"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"q_sid",
|
||||
"q_des",
|
||||
"em_code",
|
||||
"q_cid",
|
||||
"ani_sticker_type",
|
||||
"ani_sticker_pack_id",
|
||||
"ani_sticker_id",
|
||||
"url",
|
||||
"emoji_name_alias",
|
||||
"ani_sticker_width",
|
||||
"ani_sticker_height",
|
||||
"is_super"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"faces"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "query",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "编号、名称、别名或分组名"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "编号、名称、别名或分组名"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"query"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "系统表情"
|
||||
},
|
||||
{
|
||||
"name": "send_ark_share",
|
||||
"aliases": [],
|
||||
@@ -11053,6 +11683,10 @@ export const CATEGORIES: CatalogCategory[] = [
|
||||
"category": "空间",
|
||||
"count": 9
|
||||
},
|
||||
{
|
||||
"category": "系统表情",
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"category": "流式接口",
|
||||
"count": 6
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
type MessageMeta,
|
||||
} from '../types';
|
||||
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
|
||||
import { groupInfoReturnsSchema } from './group-info';
|
||||
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
|
||||
|
||||
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
|
||||
@@ -1852,10 +1853,14 @@ export const actions = [
|
||||
name: 'get_group_info_ex',
|
||||
summary: '获取群信息(扩展)',
|
||||
readOnly: true,
|
||||
params: { group_id: f.groupId() },
|
||||
returnsSchema: groupInfoReturnsSchema,
|
||||
params: {
|
||||
group_id: f.groupId(),
|
||||
no_cache: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if (ctx.getGroupInfo) {
|
||||
return okResponse(await ctx.getGroupInfo(p.group_id));
|
||||
return okResponse(await ctx.getGroupInfo(p.group_id, p.no_cache));
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
},
|
||||
@@ -1865,10 +1870,14 @@ export const actions = [
|
||||
name: 'get_group_detail_info',
|
||||
summary: '获取群详细信息',
|
||||
readOnly: true,
|
||||
params: { group_id: f.groupId() },
|
||||
returnsSchema: groupInfoReturnsSchema,
|
||||
params: {
|
||||
group_id: f.groupId(),
|
||||
no_cache: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if (ctx.getGroupInfo) {
|
||||
return okResponse(await ctx.getGroupInfo(p.group_id));
|
||||
return okResponse(await ctx.getGroupInfo(p.group_id, p.no_cache));
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
},
|
||||
|
||||
@@ -49,7 +49,30 @@ export const actions = [
|
||||
upload_file: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.bridge.apis.groupFile.uploadPrivate(p.user_id, p.file, p.name, p.upload_file);
|
||||
const result = await ctx.bridge.apis.groupFile.uploadPrivate(
|
||||
p.user_id,
|
||||
p.file,
|
||||
p.name,
|
||||
p.upload_file,
|
||||
false,
|
||||
);
|
||||
if (p.upload_file) {
|
||||
if (!result.fileId) throw new Error('private file upload returned no file_id');
|
||||
const uploaded = ctx.bridge.recallUploadedFile(result.fileId);
|
||||
if (!uploaded || uploaded.scope !== 'private' || uploaded.userId !== p.user_id) {
|
||||
throw new Error(`private file upload metadata missing for file_id ${result.fileId}`);
|
||||
}
|
||||
await ctx.sendPrivateMessage(p.user_id, [{
|
||||
type: 'file',
|
||||
data: {
|
||||
file_id: result.fileId,
|
||||
name: uploaded.fileName,
|
||||
file_size: uploaded.fileSize,
|
||||
md5: Buffer.from(uploaded.fileMd5).toString('hex'),
|
||||
file_hash: result.fileHash ?? uploaded.fileHash ?? '',
|
||||
},
|
||||
}], false);
|
||||
}
|
||||
return okResponse({ file_id: result.fileId });
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -3,6 +3,25 @@ import { asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
|
||||
|
||||
export const groupInfoReturnsSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
group_id: { type: 'integer', description: '群号' },
|
||||
group_name: { type: 'string', description: '群名' },
|
||||
group_remark: { type: 'string', description: '当前账号设置的群备注' },
|
||||
member_count: { type: 'integer', description: '当前成员数' },
|
||||
max_member_count: { type: 'integer', description: '成员上限' },
|
||||
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
|
||||
group_level: { type: 'integer', description: '群等级' },
|
||||
group_memo: { type: 'string', description: '群简介 / 公告预览' },
|
||||
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
|
||||
},
|
||||
required: [
|
||||
'group_id', 'group_name', 'group_remark', 'member_count',
|
||||
'max_member_count', 'group_all_shut',
|
||||
],
|
||||
};
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'get_group_list',
|
||||
@@ -22,8 +41,12 @@ export const actions = [
|
||||
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
|
||||
group_level: { type: 'integer', description: '群等级(列表批量场景恒 0,详见 get_group_info)' },
|
||||
group_memo: { type: 'string', description: '群简介 / 公告预览' },
|
||||
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
|
||||
},
|
||||
required: ['group_id', 'group_name', 'group_remark', 'member_count', 'max_member_count'],
|
||||
required: [
|
||||
'group_id', 'group_name', 'group_remark', 'member_count',
|
||||
'max_member_count', 'group_all_shut',
|
||||
],
|
||||
},
|
||||
},
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
@@ -41,20 +64,7 @@ export const actions = [
|
||||
summary: '获取群信息',
|
||||
readOnly: true,
|
||||
returns: '群信息对象。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
group_id: { type: 'integer', description: '群号' },
|
||||
group_name: { type: 'string', description: '群名' },
|
||||
group_remark: { type: 'string', description: '当前账号设置的群备注' },
|
||||
member_count: { type: 'integer', description: '当前成员数' },
|
||||
max_member_count: { type: 'integer', description: '成员上限' },
|
||||
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
|
||||
group_level: { type: 'integer', description: '群等级' },
|
||||
group_memo: { type: 'string', description: '群简介 / 公告预览' },
|
||||
},
|
||||
required: ['group_id', 'group_name', 'group_remark', 'member_count', 'max_member_count'],
|
||||
},
|
||||
returnsSchema: groupInfoReturnsSchema,
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
@@ -68,6 +78,7 @@ export const actions = [
|
||||
group_create_time: 0,
|
||||
group_level: 0,
|
||||
group_memo: '',
|
||||
group_all_shut: 0,
|
||||
};
|
||||
if (ctx.getGroupInfo) {
|
||||
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||
@@ -96,6 +107,7 @@ export const actions = [
|
||||
age: { type: 'integer', description: '年龄' },
|
||||
join_time: { type: 'integer', description: '入群时间戳(秒)' },
|
||||
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
|
||||
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
|
||||
level: { type: 'string', description: '群等级' },
|
||||
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
|
||||
title: { type: 'string', description: '专属头衔' },
|
||||
@@ -135,6 +147,7 @@ export const actions = [
|
||||
age: { type: 'integer', description: '年龄' },
|
||||
join_time: { type: 'integer', description: '入群时间戳(秒)' },
|
||||
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
|
||||
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
|
||||
level: { type: 'string', description: '群等级' },
|
||||
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
|
||||
title: { type: 'string', description: '专属头衔' },
|
||||
@@ -156,6 +169,7 @@ export const actions = [
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
is_robot: false,
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
shut_up_timestamp: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
}
|
||||
@@ -163,6 +177,7 @@ export const actions = [
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
is_robot: false,
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
shut_up_timestamp: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
},
|
||||
|
||||
@@ -20,6 +20,7 @@ import { actions as groupAlbumActions } from './group-album';
|
||||
import { actions as qzoneActions } from './qzone';
|
||||
import { actions as streamFileActions } from './stream-file';
|
||||
import { actions as streamDownloadActions } from './stream-download';
|
||||
import { actions as systemFaceActions } from './system-face';
|
||||
|
||||
export interface ActionGroup {
|
||||
/** Domain category (= source file), surfaced to the MCP / UI for grouping. */
|
||||
@@ -196,6 +197,7 @@ export const ACTION_GROUPS: readonly ActionGroup[] = [
|
||||
{ category: '扩展', actions: extendedActions },
|
||||
{ category: '群相册', actions: groupAlbumActions },
|
||||
{ category: '空间', actions: qzoneActions },
|
||||
{ category: '系统表情', actions: systemFaceActions },
|
||||
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces';
|
||||
import type { SysFaceEntry } from '@snowluma/protocol/sys-face-store';
|
||||
import { defineAction, f } from '../action-kit';
|
||||
import { okResponse, type JsonObject } from '../types';
|
||||
|
||||
function faceEntry(face: SysFaceEntry): JsonObject {
|
||||
return {
|
||||
q_sid: face.qSid,
|
||||
q_des: face.qDes,
|
||||
em_code: face.emCode,
|
||||
q_cid: face.qCid,
|
||||
ani_sticker_type: face.aniStickerType,
|
||||
ani_sticker_pack_id: face.aniStickerPackId,
|
||||
ani_sticker_id: face.aniStickerId,
|
||||
url: face.url,
|
||||
emoji_name_alias: face.emojiNameAlias,
|
||||
ani_sticker_width: face.aniStickerWidth,
|
||||
ani_sticker_height: face.aniStickerHeight,
|
||||
is_super: isSuperFaceEntry(face),
|
||||
};
|
||||
}
|
||||
|
||||
const refreshField = () => f.bool().default(false).describe('是否强制从 QQ 刷新目录');
|
||||
const faceIdField = () => f.faceId().describe('QQ 系统表情编号');
|
||||
const nullableInteger = { type: ['integer', 'null'] };
|
||||
const nullableString = { type: ['string', 'null'] };
|
||||
const faceSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
q_sid: { type: 'string', description: '表情编号' },
|
||||
q_des: { type: 'string', description: '表情描述' },
|
||||
em_code: { type: 'string' },
|
||||
q_cid: nullableInteger,
|
||||
ani_sticker_type: nullableInteger,
|
||||
ani_sticker_pack_id: nullableInteger,
|
||||
ani_sticker_id: nullableInteger,
|
||||
url: nullableString,
|
||||
emoji_name_alias: { type: 'array', items: { type: 'string' } },
|
||||
ani_sticker_width: nullableInteger,
|
||||
ani_sticker_height: nullableInteger,
|
||||
is_super: { type: 'boolean', description: '是否使用超级表情格式' },
|
||||
},
|
||||
required: [
|
||||
'q_sid', 'q_des', 'em_code', 'q_cid', 'ani_sticker_type',
|
||||
'ani_sticker_pack_id', 'ani_sticker_id', 'url', 'emoji_name_alias',
|
||||
'ani_sticker_width', 'ani_sticker_height', 'is_super',
|
||||
],
|
||||
};
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'fetch_sys_faces',
|
||||
summary: '获取 QQ 系统表情目录',
|
||||
readOnly: true,
|
||||
returns: '按分组返回完整的 QQ 系统表情映射。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
packs: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
pack_name: { type: 'string' },
|
||||
emojis: { type: 'array', items: faceSchema },
|
||||
},
|
||||
required: ['pack_name', 'emojis'],
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['packs'],
|
||||
},
|
||||
params: { refresh: refreshField() },
|
||||
run: async (params, ctx) => {
|
||||
const packs = await ctx.bridge.apis.systemFace.fetchCatalog(params.refresh);
|
||||
return okResponse({
|
||||
packs: packs.map((pack) => ({
|
||||
pack_name: pack.packName,
|
||||
emojis: pack.emojis.map(faceEntry),
|
||||
})),
|
||||
});
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'fetch_face_entity',
|
||||
summary: '按编号查询 QQ 系统表情',
|
||||
readOnly: true,
|
||||
returns: '表情详情;编号不存在时返回 null。',
|
||||
returnsSchema: { anyOf: [faceSchema, { type: 'null' }] },
|
||||
params: {
|
||||
face_id: faceIdField(),
|
||||
refresh: refreshField(),
|
||||
},
|
||||
run: async (params, ctx) => {
|
||||
const face = await ctx.bridge.apis.systemFace.fetchFace(params.face_id, params.refresh);
|
||||
return okResponse(face ? faceEntry(face) : null);
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'search_sys_faces',
|
||||
summary: '搜索 QQ 系统表情',
|
||||
readOnly: true,
|
||||
returns: '匹配编号、名称、别名或分组名的表情列表。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: { faces: { type: 'array', items: faceSchema } },
|
||||
required: ['faces'],
|
||||
},
|
||||
params: {
|
||||
query: f.string({ allowEmpty: false }).describe('编号、名称、别名或分组名'),
|
||||
},
|
||||
run: async (params, ctx) => okResponse({
|
||||
faces: (await ctx.bridge.apis.systemFace.search(params.query)).map(faceEntry),
|
||||
}),
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'fetch_super_face_id',
|
||||
summary: '判断 QQ 系统表情是否使用超级表情格式',
|
||||
readOnly: true,
|
||||
returns: '是否使用超级表情格式。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: { is_super: { type: 'boolean' } },
|
||||
required: ['is_super'],
|
||||
},
|
||||
params: {
|
||||
face_id: faceIdField(),
|
||||
refresh: refreshField(),
|
||||
},
|
||||
run: async (params, ctx) => okResponse({
|
||||
is_super: await ctx.bridge.apis.systemFace.isSuper(params.face_id, params.refresh),
|
||||
}),
|
||||
}),
|
||||
];
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import {
|
||||
assertVideoSendPolicy,
|
||||
assertWindowShakeSendPolicy,
|
||||
assertValidMessageElement,
|
||||
ELEMENT_MANIFEST,
|
||||
@@ -68,9 +69,22 @@ function normalizeSegmentType(type: string): string {
|
||||
return type.toLowerCase();
|
||||
}
|
||||
|
||||
function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): string[] {
|
||||
interface OutboundInputSegmentSummary {
|
||||
rawTypes: string[];
|
||||
effectiveVideoTypes: string[];
|
||||
}
|
||||
|
||||
function isExplicitEmptyTextPlaceholder(segment: MessageSegment): boolean {
|
||||
return normalizeSegmentType(segment.type) === 'text'
|
||||
&& segmentPayload(segment).text === '';
|
||||
}
|
||||
|
||||
function outboundInputSegmentSummary(
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): OutboundInputSegmentSummary {
|
||||
if (typeof message === 'string') {
|
||||
if (autoEscape) return ['text'];
|
||||
if (autoEscape) return { rawTypes: ['text'], effectiveVideoTypes: ['text'] };
|
||||
const types: string[] = [];
|
||||
let lastIndex = 0;
|
||||
for (const match of message.matchAll(CQ_REGEX)) {
|
||||
@@ -79,34 +93,48 @@ function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): str
|
||||
lastIndex = match.index! + match[0].length;
|
||||
}
|
||||
if (lastIndex < message.length) types.push('text');
|
||||
return types;
|
||||
return { rawTypes: types, effectiveVideoTypes: types };
|
||||
}
|
||||
if (Array.isArray(message)) {
|
||||
return message.flatMap((item) => {
|
||||
if (typeof item !== 'object' || item === null || Array.isArray(item)) return [];
|
||||
const rawTypes: string[] = [];
|
||||
const effectiveVideoTypes: string[] = [];
|
||||
for (const item of message) {
|
||||
if (typeof item !== 'object' || item === null || Array.isArray(item)) continue;
|
||||
const type = (item as { type?: unknown }).type;
|
||||
return typeof type === 'string' ? [normalizeSegmentType(type)] : [];
|
||||
});
|
||||
if (typeof type !== 'string') continue;
|
||||
const normalizedType = normalizeSegmentType(type);
|
||||
rawTypes.push(normalizedType);
|
||||
if (!isExplicitEmptyTextPlaceholder(item as MessageSegment)) {
|
||||
effectiveVideoTypes.push(normalizedType);
|
||||
}
|
||||
}
|
||||
return { rawTypes, effectiveVideoTypes };
|
||||
}
|
||||
if (typeof message === 'object' && message !== null) {
|
||||
const type = (message as { type?: unknown }).type;
|
||||
return typeof type === 'string' ? [normalizeSegmentType(type)] : [];
|
||||
const types = typeof type === 'string' ? [normalizeSegmentType(type)] : [];
|
||||
return { rawTypes: types, effectiveVideoTypes: types };
|
||||
}
|
||||
return [];
|
||||
return { rawTypes: [], effectiveVideoTypes: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject unsupported window-shake inputs before parsers can resolve identities,
|
||||
* fetch cards, sign music, or perform any other externally visible work.
|
||||
* Reject unsupported message combinations before parsers can resolve
|
||||
* identities, fetch cards, sign music, or perform any other externally
|
||||
* visible work.
|
||||
*/
|
||||
export function assertWindowShakeMessageInput(
|
||||
export function assertOutboundMessageInput(
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
scene: OutboundMessageScene,
|
||||
): void {
|
||||
const types = outboundInputSegmentTypes(message, autoEscape);
|
||||
const shakeCount = types.filter((type) => type === 'poke' || type === 'shake').length;
|
||||
assertWindowShakeSendPolicy(shakeCount, types.length, scene);
|
||||
const { rawTypes, effectiveVideoTypes } = outboundInputSegmentSummary(message, autoEscape);
|
||||
assertVideoSendPolicy(
|
||||
effectiveVideoTypes.filter((type) => type === 'video').length,
|
||||
effectiveVideoTypes.length,
|
||||
);
|
||||
const shakeCount = rawTypes.filter((type) => type === 'poke' || type === 'shake').length;
|
||||
assertWindowShakeSendPolicy(shakeCount, rawTypes.length, scene);
|
||||
}
|
||||
|
||||
function invalidMessageShape(message: string): MessageElementValidationError {
|
||||
@@ -415,7 +443,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
|
||||
// Some OneBot clients insert empty text between media as a separator.
|
||||
// Only the exact empty string is a no-op; malformed and whitespace text
|
||||
// must still pass through strict element validation.
|
||||
if (normalizeSegmentType(seg.type) === 'text' && data.text === '') {
|
||||
if (isExplicitEmptyTextPlaceholder(seg)) {
|
||||
log.debug('ignored explicit empty text placeholder in message segment array');
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -68,8 +68,13 @@ export async function getGroupList(
|
||||
if (noCache || bridge.identity.groups.length === 0) {
|
||||
await bridge.apis.contacts.fetchGroupList();
|
||||
}
|
||||
} catch {
|
||||
// Use cached data.
|
||||
} catch (err) {
|
||||
if (noCache) throw err;
|
||||
log.warn(
|
||||
'group list refresh failed, using cached roster: uin=%s err=%s',
|
||||
bridge.identity.uin,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
}
|
||||
return bridge.identity.groups.map(g => ({
|
||||
group_id: g.groupId,
|
||||
@@ -83,24 +88,36 @@ export async function getGroupList(
|
||||
group_create_time: g.createTime ?? 0,
|
||||
group_level: g.level ?? 0,
|
||||
group_memo: g.memo ?? '',
|
||||
group_all_shut: g.allMuted ? -1 : 0,
|
||||
}));
|
||||
}
|
||||
|
||||
// group_level lives only in the 0x88D_0 detail. Memoize it (short TTL) so a
|
||||
// joined-group get_group_info doesn't fetch the detail on every call (#197).
|
||||
// group_level lives only in the per-group detail response. Keep its existing
|
||||
// short cache, but read mutable group state from the roster refreshed above.
|
||||
const GROUP_LEVEL_TTL_MS = 5 * 60 * 1000;
|
||||
const groupLevelCache = new Map<number, { level: number; at: number }>();
|
||||
async function getGroupLevel(bridge: BridgeInterface, groupId: number, noCache?: boolean): Promise<number> {
|
||||
async function getGroupLevel(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<number> {
|
||||
if (!noCache) {
|
||||
const c = groupLevelCache.get(groupId);
|
||||
if (c && Date.now() - c.at < GROUP_LEVEL_TTL_MS) return c.level;
|
||||
const cached = groupLevelCache.get(groupId);
|
||||
if (cached && Date.now() - cached.at < GROUP_LEVEL_TTL_MS) return cached.level;
|
||||
}
|
||||
try {
|
||||
const detail = await bridge.apis.contacts.fetchGroupDetail(groupId);
|
||||
const level = detail?.level ?? 0;
|
||||
groupLevelCache.set(groupId, { level, at: Date.now() });
|
||||
return level;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
if (noCache) throw err;
|
||||
log.warn(
|
||||
'group detail refresh failed, using roster metadata: uin=%s group=%d err=%s',
|
||||
bridge.identity.uin,
|
||||
groupId,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -110,7 +127,11 @@ async function getGroupLevel(bridge: BridgeInterface, groupId: number, noCache?:
|
||||
// here; this only memoizes the per-id server query so a burst of invites for the
|
||||
// same group doesn't hammer 0x88D_0 (which would risk a rate-limit / kick).
|
||||
const NON_MEMBER_GROUP_TTL_MS = 5 * 60 * 1000;
|
||||
const nonMemberGroupCache = new Map<number, { info: JsonObject; at: number }>();
|
||||
const nonMemberGroupCache = new Map<string, { info: JsonObject; at: number }>();
|
||||
|
||||
function nonMemberGroupCacheKey(bridge: BridgeInterface, groupId: number): string {
|
||||
return `${bridge.identity.uin}:${groupId}`;
|
||||
}
|
||||
|
||||
export async function getGroupInfo(
|
||||
bridge: BridgeInterface,
|
||||
@@ -120,8 +141,14 @@ export async function getGroupInfo(
|
||||
if (noCache || !bridge.identity.findGroup(groupId)) {
|
||||
try {
|
||||
await bridge.apis.contacts.fetchGroupList();
|
||||
} catch {
|
||||
// Use cached data.
|
||||
} catch (err) {
|
||||
if (noCache) throw err;
|
||||
log.warn(
|
||||
'group list refresh failed, using cached roster: uin=%s group=%d err=%s',
|
||||
bridge.identity.uin,
|
||||
groupId,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
const g = bridge.identity.findGroup(groupId);
|
||||
@@ -135,13 +162,15 @@ export async function getGroupInfo(
|
||||
group_create_time: g.createTime ?? 0,
|
||||
group_level: await getGroupLevel(bridge, groupId, noCache),
|
||||
group_memo: g.memo ?? '',
|
||||
group_all_shut: g.allMuted ? -1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Not a joined group — fall back to the by-id server lookup so a group invite
|
||||
// can still resolve its name. Cached with a short TTL (skipped when noCache).
|
||||
const cacheKey = nonMemberGroupCacheKey(bridge, groupId);
|
||||
if (!noCache) {
|
||||
const cached = nonMemberGroupCache.get(groupId);
|
||||
const cached = nonMemberGroupCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.at < NON_MEMBER_GROUP_TTL_MS) return { ...cached.info };
|
||||
}
|
||||
try {
|
||||
@@ -156,12 +185,19 @@ export async function getGroupInfo(
|
||||
group_create_time: detail.createTime ?? 0,
|
||||
group_level: detail.level ?? 0,
|
||||
group_memo: detail.memo ?? '',
|
||||
group_all_shut: detail.allMuted ? -1 : 0,
|
||||
};
|
||||
nonMemberGroupCache.set(groupId, { info, at: Date.now() });
|
||||
nonMemberGroupCache.set(cacheKey, { info, at: Date.now() });
|
||||
return { ...info };
|
||||
}
|
||||
} catch {
|
||||
// Server lookup failed (no such group / denied) — fall through to null.
|
||||
} catch (err) {
|
||||
if (noCache) throw err;
|
||||
log.warn(
|
||||
'non-member group lookup failed: uin=%s group=%d err=%s',
|
||||
bridge.identity.uin,
|
||||
groupId,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -395,6 +431,7 @@ function formatGroupMember(
|
||||
age: 0,
|
||||
join_time: member.joinTime,
|
||||
last_sent_time: member.lastSentTime,
|
||||
shut_up_timestamp: member.shutUpTime,
|
||||
level: String(member.level),
|
||||
role: member.role,
|
||||
title: member.title,
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
privateMessageEventName,
|
||||
} from '../message-id';
|
||||
import {
|
||||
assertWindowShakeMessageInput,
|
||||
assertOutboundMessageInput,
|
||||
MessageElementValidationError,
|
||||
parseMessage,
|
||||
} from '../message-parser';
|
||||
@@ -797,7 +797,7 @@ export async function sendPrivateMessage(
|
||||
if (tempGroupId !== undefined && !isTempReply) {
|
||||
throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`);
|
||||
}
|
||||
assertWindowShakeMessageInput(
|
||||
assertOutboundMessageInput(
|
||||
message,
|
||||
autoEscape,
|
||||
tempGroupId === undefined ? 'direct-private' : 'group-temp',
|
||||
@@ -1034,7 +1034,7 @@ export async function sendGroupMessage(
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
assertWindowShakeMessageInput(message, autoEscape, 'group');
|
||||
assertOutboundMessageInput(message, autoEscape, 'group');
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
@@ -1232,6 +1232,7 @@ export async function forwardSingleMessage(
|
||||
if (!event) throw new Error(`message not found: ${messageId}`);
|
||||
|
||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||
assertOutboundMessageInput(content, false, 'forward');
|
||||
const parsed = await parseMessage(content, false);
|
||||
if (parsed.length === 0) throw new Error('message has no content');
|
||||
|
||||
@@ -1528,7 +1529,7 @@ function assertForwardNodeMetadataIsScalar(
|
||||
}
|
||||
}
|
||||
|
||||
function assertNoWindowShakeInForwardInput(
|
||||
function assertForwardMessageInputPolicies(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
depth = 0,
|
||||
@@ -1544,7 +1545,7 @@ function assertNoWindowShakeInForwardInput(
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
if (event) {
|
||||
assertWindowShakeMessageInput(
|
||||
assertOutboundMessageInput(
|
||||
(event.message ?? event.raw_message ?? '') as JsonValue,
|
||||
false,
|
||||
'forward',
|
||||
@@ -1555,9 +1556,9 @@ function assertNoWindowShakeInForwardInput(
|
||||
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
if (isNestedNodeArray(content)) {
|
||||
assertNoWindowShakeInForwardInput(ref, content, depth + 1);
|
||||
assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
} else {
|
||||
assertWindowShakeMessageInput(content, false, 'forward');
|
||||
assertOutboundMessageInput(content, false, 'forward');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1655,9 +1656,10 @@ async function parseForwardNodes(
|
||||
});
|
||||
|
||||
// Scan the complete raw tree before parsing any earlier node. Some segment
|
||||
// codecs perform identity lookups or HTTP signing, so discovering a later
|
||||
// window-shake segment during the normal loop would already be too late.
|
||||
assertNoWindowShakeInForwardInput(ref, messages, depth);
|
||||
// codecs perform identity lookups or HTTP signing, so discovering an
|
||||
// unsupported message combination during the normal loop would already be
|
||||
// too late.
|
||||
assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
for (const { nodeData } of prepared) {
|
||||
|
||||
@@ -131,9 +131,6 @@ export function normalizePath(pathValue: string | undefined): string {
|
||||
}
|
||||
|
||||
export function parseRequestPath(urlValue: string): string {
|
||||
try {
|
||||
return new URL(urlValue, 'ws://127.0.0.1').pathname;
|
||||
} catch {
|
||||
return '/';
|
||||
}
|
||||
const queryIndex = urlValue.indexOf('?');
|
||||
return queryIndex === -1 ? urlValue : urlValue.slice(0, queryIndex);
|
||||
}
|
||||
@@ -4,8 +4,11 @@ import type { IncomingMessage } from 'node:http';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, WsServerNetwork } from '../types';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { normalizePath } from './utils';
|
||||
import { WsServerConnections } from './ws-server-connections';
|
||||
import { normalizePath, parseRequestPath } from './utils';
|
||||
import {
|
||||
WsServerConnections,
|
||||
type WsServerConnectionConfig,
|
||||
} from './ws-server-connections';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
|
||||
@@ -17,7 +20,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx, moduleLog);
|
||||
this.connections = new WsServerConnections(name, config, ctx, this.log, {
|
||||
this.connections = new WsServerConnections(name, standaloneConnectionConfig(config), ctx, this.log, {
|
||||
frame: (event, options) => this.metaFrame(event, options),
|
||||
bootstrap: (options) => this.bootstrapMetaFrames(options),
|
||||
});
|
||||
@@ -90,7 +93,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
|
||||
protected override onConfigReplaced(next: WsServerNetwork): void {
|
||||
this.connections.updateConfig(next);
|
||||
this.connections.updateConfig(standaloneConnectionConfig(next));
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
@@ -105,9 +108,22 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
wss = new WebSocketServer({
|
||||
host: this.config.host ?? '0.0.0.0',
|
||||
port: this.config.port,
|
||||
path: normalizePath(this.config.path),
|
||||
verifyClient: ({ req }: { req: IncomingMessage }) =>
|
||||
this.connections.authorizeUpgrade(req),
|
||||
verifyClient: (
|
||||
{ req }: { req: IncomingMessage },
|
||||
done: (allow: boolean, code?: number, message?: string) => void,
|
||||
) => {
|
||||
const requestPath = parseRequestPath(req.url ?? '/');
|
||||
if (!this.connections.acceptsUpgradePath(requestPath)) {
|
||||
this.log.debug('[%s] rejected unknown WebSocket path %s', this.name, requestPath);
|
||||
done(false, 400, 'Bad path for WebSocket');
|
||||
return;
|
||||
}
|
||||
if (!this.connections.authorizeUpgrade(req)) {
|
||||
done(false, 401, 'Unauthorized');
|
||||
return;
|
||||
}
|
||||
done(true);
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
this.recordTransportFailure(error);
|
||||
@@ -170,3 +186,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
function isAlreadyClosedError(error: Error): boolean {
|
||||
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
|
||||
}
|
||||
|
||||
function standaloneConnectionConfig(config: WsServerNetwork): WsServerConnectionConfig {
|
||||
return { ...config, role: config.role ?? 'Universal' };
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import type { JsonObject, NetworkBase, WsRole } from '../types';
|
||||
import type { NetworkAdapterContext } from './adapter';
|
||||
import {
|
||||
isAuthorized,
|
||||
normalizePath,
|
||||
parseRequestPath,
|
||||
rawDataToString,
|
||||
safeClose,
|
||||
@@ -27,7 +28,7 @@ const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const HEARTBEAT_MAX_MISSED = 2;
|
||||
const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000;
|
||||
|
||||
export type WsServerConnectionConfig = NetworkBase & { role?: WsRole };
|
||||
export type WsServerConnectionConfig = NetworkBase & { path?: string; role?: WsRole };
|
||||
|
||||
interface ForwardConnection {
|
||||
socket: WebSocket;
|
||||
@@ -100,6 +101,10 @@ export class WsServerConnections {
|
||||
if (tokenChanged) this.disconnectAll(1008, 'access token changed');
|
||||
}
|
||||
|
||||
acceptsUpgradePath(requestPath: string): boolean {
|
||||
return resolveForwardRole(requestPath, this.config) !== null;
|
||||
}
|
||||
|
||||
onEvent(payload: DispatchPayload): void {
|
||||
if (!this.acceptingActions || this.connections.size === 0) return;
|
||||
for (const connection of this.connections.values()) {
|
||||
@@ -128,7 +133,13 @@ export class WsServerConnections {
|
||||
return;
|
||||
}
|
||||
|
||||
const role = this.config.role ?? classifyForwardRole(request);
|
||||
const requestPath = parseRequestPath(request.url ?? '/');
|
||||
const role = resolveForwardRole(requestPath, this.config);
|
||||
if (role === null) {
|
||||
this.log.warn('[%s] rejected WebSocket path after upgrade', this.name);
|
||||
safeClose(socket, 1008, 'invalid path');
|
||||
return;
|
||||
}
|
||||
const stopHeartbeat = startHeartbeat(
|
||||
socket,
|
||||
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
|
||||
@@ -252,8 +263,24 @@ export class WsServerConnections {
|
||||
}
|
||||
}
|
||||
|
||||
function classifyForwardRole(request: IncomingMessage): WsRole {
|
||||
const path = parseRequestPath(request.url ?? '/');
|
||||
function resolveForwardRole(requestPath: string, config: WsServerConnectionConfig): WsRole | null {
|
||||
if (
|
||||
config.role !== undefined
|
||||
&& (!requestPath.startsWith('/') || requestPath.startsWith('//'))
|
||||
) return null;
|
||||
|
||||
const path = normalizePath(requestPath);
|
||||
if (config.role === undefined) return classifyForwardRole(path);
|
||||
|
||||
const basePath = normalizePath(config.path);
|
||||
if (path === basePath) return config.role;
|
||||
if (config.role !== 'Universal' || basePath !== '/') return null;
|
||||
if (path === '/api') return 'Api';
|
||||
if (path === '/event') return 'Event';
|
||||
return null;
|
||||
}
|
||||
|
||||
function classifyForwardRole(path: string): WsRole {
|
||||
if (path.endsWith('/api')) return 'Api';
|
||||
if (path.endsWith('/event')) return 'Event';
|
||||
return 'Universal';
|
||||
|
||||
@@ -273,7 +273,7 @@ function resolveManagedRoot(input: string): string {
|
||||
return path.join(fs.realpathSync(parent), path.basename(absolute));
|
||||
}
|
||||
|
||||
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'snowluma-stream'));
|
||||
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'onebot-stream'));
|
||||
export const STREAM_ROOT = streamStorage.root;
|
||||
export const STREAM_UPLOAD_DIR = streamStorage.uploadDir;
|
||||
export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir;
|
||||
|
||||
@@ -90,9 +90,9 @@ describe('compileActionRegistry namespace conflicts', () => {
|
||||
});
|
||||
|
||||
describe('compiled production Action registry', () => {
|
||||
it('preserves all 181 canonical Action docs', () => {
|
||||
expect(ACTION_REGISTRY.actions).toHaveLength(181);
|
||||
expect(collectActionDocs()).toHaveLength(181);
|
||||
it('preserves all 185 canonical Action docs', () => {
|
||||
expect(ACTION_REGISTRY.actions).toHaveLength(185);
|
||||
expect(collectActionDocs()).toHaveLength(185);
|
||||
});
|
||||
|
||||
it('resolves every executable name to exactly one canonical doc', () => {
|
||||
|
||||
@@ -202,7 +202,7 @@ describe('onebot/contact-actions / getGroupFiles', () => {
|
||||
|
||||
describe('onebot/contact-actions / getGroupList', () => {
|
||||
it('triggers fetch when the in-memory roster is empty', async () => {
|
||||
const fetched = [{ ...makeGroup(100, 'Group A'), remark: '工作群' }];
|
||||
const fetched = [{ ...makeGroup(100, 'Group A'), remark: '工作群', allMuted: true }];
|
||||
// `groups` starts empty; the fetch callback flips it to mimic
|
||||
// bridge.apis.contacts.fetchGroupList writing back through identity.rememberGroups.
|
||||
let groups: QQGroupInfo[] = [];
|
||||
@@ -219,6 +219,7 @@ describe('onebot/contact-actions / getGroupList', () => {
|
||||
group_remark: '工作群',
|
||||
member_count: 0, max_member_count: 500,
|
||||
group_create_time: 0, group_level: 0, group_memo: '',
|
||||
group_all_shut: -1,
|
||||
}]);
|
||||
});
|
||||
|
||||
@@ -242,14 +243,13 @@ describe('onebot/contact-actions / getGroupList', () => {
|
||||
expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('serves the stale cache when the fetch path throws', async () => {
|
||||
it('propagates fetch failures when noCache=true', async () => {
|
||||
const cached = [makeGroup(400, 'Group D')];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => { throw new Error('boom'); }),
|
||||
identity: fakeIdentity({ groups: cached }),
|
||||
});
|
||||
const out = await getGroupList(bridge, true);
|
||||
expect(out[0]).toMatchObject({ group_id: 400, group_name: 'Group D' });
|
||||
await expect(getGroupList(bridge, true)).rejects.toThrow('boom');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -259,6 +259,7 @@ describe('onebot/contact-actions / getGroupInfo', () => {
|
||||
const findGroup = vi.fn((groupId: number) => groupId === 500 ? cached : null);
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
fetchGroupDetail: vi.fn(async () => cached),
|
||||
identity: fakeIdentity({ findGroup }),
|
||||
});
|
||||
const out = await getGroupInfo(bridge, 500);
|
||||
@@ -270,6 +271,38 @@ describe('onebot/contact-actions / getGroupInfo', () => {
|
||||
expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps joined-group mute state on the roster source across level-cache hits', async () => {
|
||||
const cached = { ...makeGroup(510, 'Muted Group'), allMuted: true };
|
||||
const fetchGroupDetail = vi.fn(async () => ({
|
||||
...cached,
|
||||
level: 6,
|
||||
allMuted: false,
|
||||
}));
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
fetchGroupDetail,
|
||||
identity: fakeIdentity({ findGroup: (groupId: number) => groupId === 510 ? cached : null }),
|
||||
});
|
||||
|
||||
const first = await getGroupInfo(bridge, 510);
|
||||
const second = await getGroupInfo(bridge, 510);
|
||||
|
||||
expect(first).toMatchObject({ group_level: 6, group_all_shut: -1 });
|
||||
expect(second).toMatchObject({ group_level: 6, group_all_shut: -1 });
|
||||
expect(fetchGroupDetail).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('propagates detail refresh failures when noCache=true', async () => {
|
||||
const cached = makeGroup(520, 'Refresh Group');
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => [cached]),
|
||||
fetchGroupDetail: vi.fn(async () => { throw new Error('detail unavailable'); }),
|
||||
identity: fakeIdentity({ findGroup: (groupId: number) => groupId === 520 ? cached : null }),
|
||||
});
|
||||
|
||||
await expect(getGroupInfo(bridge, 520, true)).rejects.toThrow('detail unavailable');
|
||||
});
|
||||
|
||||
it('triggers fetch when the group is unknown to the cache', async () => {
|
||||
const cached = makeGroup(600, 'Group F');
|
||||
let known = false;
|
||||
@@ -277,6 +310,7 @@ describe('onebot/contact-actions / getGroupInfo', () => {
|
||||
const fetchGroupList = vi.fn(async () => { known = true; return [cached]; });
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList,
|
||||
fetchGroupDetail: vi.fn(async () => cached),
|
||||
identity: fakeIdentity({ findGroup }),
|
||||
});
|
||||
const out = await getGroupInfo(bridge, 600);
|
||||
@@ -294,7 +328,10 @@ describe('onebot/contact-actions / getGroupInfo', () => {
|
||||
});
|
||||
|
||||
it('resolves a non-member group via the by-id server lookup (e.g. a group invite name)', async () => {
|
||||
const fetchGroupDetail = vi.fn(async () => makeGroup(7100, '邀请来的群'));
|
||||
const fetchGroupDetail = vi.fn(async () => ({
|
||||
...makeGroup(7100, '邀请来的群'),
|
||||
allMuted: true,
|
||||
}));
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
fetchGroupDetail,
|
||||
@@ -306,6 +343,7 @@ describe('onebot/contact-actions / getGroupInfo', () => {
|
||||
group_id: 7100,
|
||||
group_name: '邀请来的群',
|
||||
group_remark: '',
|
||||
group_all_shut: -1,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -334,6 +372,36 @@ describe('onebot/contact-actions / getGroupInfo', () => {
|
||||
await getGroupInfo(bridge, 7300, true);
|
||||
expect(fetchGroupDetail).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('isolates non-member group details between accounts', async () => {
|
||||
const groupId = 7400;
|
||||
const firstFetch = vi.fn(async () => ({
|
||||
...makeGroup(groupId, 'Account A View'),
|
||||
allMuted: true,
|
||||
}));
|
||||
const secondFetch = vi.fn(async () => ({
|
||||
...makeGroup(groupId, 'Account B View'),
|
||||
allMuted: false,
|
||||
}));
|
||||
const firstBridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
fetchGroupDetail: firstFetch,
|
||||
identity: fakeIdentity({ uin: '10001', findGroup: () => null }),
|
||||
});
|
||||
const secondBridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
fetchGroupDetail: secondFetch,
|
||||
identity: fakeIdentity({ uin: '10002', findGroup: () => null }),
|
||||
});
|
||||
|
||||
const first = await getGroupInfo(firstBridge, groupId);
|
||||
const second = await getGroupInfo(secondBridge, groupId);
|
||||
|
||||
expect(first).toMatchObject({ group_name: 'Account A View', group_all_shut: -1 });
|
||||
expect(second).toMatchObject({ group_name: 'Account B View', group_all_shut: 0 });
|
||||
expect(firstFetch).toHaveBeenCalledOnce();
|
||||
expect(secondFetch).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getGroupMemberList', () => {
|
||||
|
||||
@@ -17,6 +17,7 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import {
|
||||
forwardSingleMessage,
|
||||
sendGroupForwardMessage,
|
||||
sendPrivateForwardMessage,
|
||||
} from '../src/modules/message-actions';
|
||||
@@ -209,6 +210,58 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]);
|
||||
});
|
||||
|
||||
it('rejects video with hidden siblings before uploading a forward', async () => {
|
||||
const uploadForwardNodes = vi.fn(async () => 'RES');
|
||||
const sendGroupMessage = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await expect(sendGroupForwardMessage(ctx, 12345, [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 111,
|
||||
nickname: 'mixed-video',
|
||||
content: [
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: 'must not survive bot forwarding' } },
|
||||
],
|
||||
},
|
||||
}] as any)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
});
|
||||
|
||||
expect(uploadForwardNodes).not.toHaveBeenCalled();
|
||||
expect(sendGroupMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects hidden siblings before forwarding a cached video message', async () => {
|
||||
const sendGroupMessage = vi.fn();
|
||||
const findVideo = vi.fn();
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
findEvent: () => ({
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'cached-video-id' } },
|
||||
{ type: 'text', data: { text: 'must not survive bot forwarding' } },
|
||||
],
|
||||
}),
|
||||
};
|
||||
(ctx as any).mediaStore = { findVideo };
|
||||
|
||||
await expect(forwardSingleMessage(ctx, 77, { groupId: 12345 }))
|
||||
.rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
});
|
||||
|
||||
expect(findVideo).not.toHaveBeenCalled();
|
||||
expect(sendGroupMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an unknown top-level entry before uploading valid siblings', async () => {
|
||||
const uploadForwardNodes = vi.fn(async () => 'RES');
|
||||
const sendGroupMessage = vi.fn();
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { GroupMemberInfo } from '@snowluma/protocol/qq-info';
|
||||
|
||||
import { ACTION_REGISTRY } from '../src/actions';
|
||||
import {
|
||||
getGroupMemberInfo as readGroupMemberInfo,
|
||||
getGroupMemberList as readGroupMemberList,
|
||||
} from '../src/modules/contact-actions';
|
||||
|
||||
const getGroupInfo = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_info')?.spec;
|
||||
const getGroupList = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_list')?.spec;
|
||||
const getGroupInfoEx = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_info_ex')?.spec;
|
||||
const getGroupDetailInfo = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_detail_info')?.spec;
|
||||
const getGroupMemberList = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_member_list')?.spec;
|
||||
const getGroupMemberInfo = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_member_info')?.spec;
|
||||
if (
|
||||
!getGroupInfo || !getGroupList || !getGroupInfoEx || !getGroupDetailInfo
|
||||
|| !getGroupMemberList || !getGroupMemberInfo
|
||||
) {
|
||||
throw new Error('group info actions missing');
|
||||
}
|
||||
|
||||
function makeMember(overrides: Partial<GroupMemberInfo>): GroupMemberInfo {
|
||||
return {
|
||||
uin: 654321,
|
||||
uid: 'u_member',
|
||||
nickname: 'Member',
|
||||
card: '',
|
||||
isRobot: false,
|
||||
role: 'member',
|
||||
level: 1,
|
||||
title: '',
|
||||
joinTime: 0,
|
||||
lastSentTime: 0,
|
||||
shutUpTime: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('group information actions', () => {
|
||||
it('returns and documents the group-wide mute state', async () => {
|
||||
const response = await getGroupInfo.toHandler({} as any)({ group_id: 123456 });
|
||||
const infoSchema = getGroupInfo.describe().returnsSchema;
|
||||
const listSchema = getGroupList.describe().returnsSchema;
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { group_id: 123456, group_all_shut: 0 },
|
||||
});
|
||||
expect(infoSchema?.properties).toHaveProperty('group_all_shut');
|
||||
expect(infoSchema?.required).toContain('group_all_shut');
|
||||
expect(listSchema?.items?.properties).toHaveProperty('group_all_shut');
|
||||
expect(listSchema?.items?.required).toContain('group_all_shut');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['get_group_info_ex', getGroupInfoEx],
|
||||
['get_group_detail_info', getGroupDetailInfo],
|
||||
])('%s exposes the shared group information result', async (_name, action) => {
|
||||
const getGroupInfoResult = {
|
||||
group_id: 123456,
|
||||
group_name: 'Muted Group',
|
||||
group_all_shut: -1,
|
||||
};
|
||||
const getGroupInfoProvider = vi.fn(async () => getGroupInfoResult);
|
||||
const response = await action.toHandler({
|
||||
getGroupInfo: getGroupInfoProvider,
|
||||
} as any)({ group_id: 123456, no_cache: true });
|
||||
|
||||
expect(response).toMatchObject({ status: 'ok', data: getGroupInfoResult });
|
||||
expect(getGroupInfoProvider).toHaveBeenCalledWith(123456, true);
|
||||
expect(action.describe().returnsSchema?.properties).toHaveProperty('group_all_shut');
|
||||
});
|
||||
|
||||
it('returns and documents member mute expiry across member actions', async () => {
|
||||
const mutedUntil = 2_000_000_000;
|
||||
const member = makeMember({ nickname: 'Muted Member', shutUpTime: mutedUntil });
|
||||
const bridge = {
|
||||
identity: {
|
||||
uin: '123456',
|
||||
findGroupMember: (groupId: number, userId: number) =>
|
||||
groupId === 123456 && userId === member.uin ? member : null,
|
||||
},
|
||||
apis: { contacts: { fetchGroupMemberList: vi.fn(async () => [member]) } },
|
||||
} as any;
|
||||
const listResponse = await getGroupMemberList.toHandler({
|
||||
getGroupMemberList: (groupId: number, noCache?: boolean) =>
|
||||
readGroupMemberList(bridge, groupId, noCache),
|
||||
} as any)({ group_id: 123456 });
|
||||
const infoResponse = await getGroupMemberInfo.toHandler({
|
||||
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) =>
|
||||
readGroupMemberInfo(bridge, groupId, userId, noCache),
|
||||
} as any)({ group_id: 123456, user_id: member.uin });
|
||||
|
||||
expect(listResponse).toMatchObject({
|
||||
status: 'ok',
|
||||
data: [{ user_id: member.uin, shut_up_timestamp: mutedUntil }],
|
||||
});
|
||||
expect(infoResponse).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { user_id: member.uin, shut_up_timestamp: mutedUntil },
|
||||
});
|
||||
expect(getGroupMemberList.describe().returnsSchema?.items?.properties)
|
||||
.toHaveProperty('shut_up_timestamp');
|
||||
expect(getGroupMemberInfo.describe().returnsSchema?.properties)
|
||||
.toHaveProperty('shut_up_timestamp');
|
||||
});
|
||||
|
||||
it('returns a zero mute expiry when the member is unavailable', async () => {
|
||||
const response = await getGroupMemberInfo.toHandler({
|
||||
getGroupMemberInfo: vi.fn(async () => null),
|
||||
} as any)({ group_id: 123456, user_id: 654323 });
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { user_id: 654323, shut_up_timestamp: 0 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,12 +2,20 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import { deleteMessage, sendGroupMessage, setEssenceMessage } from '../src/modules/message-actions';
|
||||
import {
|
||||
deleteMessage,
|
||||
sendGroupMessage,
|
||||
sendPrivateMessage,
|
||||
setEssenceMessage,
|
||||
} from '../src/modules/message-actions';
|
||||
import type { MessageMeta } from '../src/types';
|
||||
|
||||
function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceContext {
|
||||
function instanceContext(
|
||||
sendGroup: ReturnType<typeof vi.fn>,
|
||||
sendPrivate: ReturnType<typeof vi.fn> = vi.fn(),
|
||||
): OneBotInstanceContext {
|
||||
const bridge = {
|
||||
apis: { message: { sendGroup } },
|
||||
apis: { message: { sendGroup, sendPrivate } },
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
} as unknown as BridgeInterface;
|
||||
|
||||
@@ -27,6 +35,14 @@ function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceCon
|
||||
}
|
||||
|
||||
describe('outbound message validation at the Action boundary', () => {
|
||||
const sendReceipt = {
|
||||
messageId: 1,
|
||||
sequence: 100,
|
||||
clientSequence: 0,
|
||||
random: 1,
|
||||
timestamp: 1700000000,
|
||||
};
|
||||
|
||||
it('returns BAD_REQUEST and performs no send when a later segment is unknown', async () => {
|
||||
const bridgeSend = vi.fn();
|
||||
const ref = instanceContext(bridgeSend);
|
||||
@@ -95,6 +111,140 @@ describe('outbound message validation at the Action boundary', () => {
|
||||
});
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects video mixed with other visible content before sending', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
const ref = instanceContext(bridgeSend);
|
||||
const api = new ApiHandler({
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_group_msg', {
|
||||
group_id: 12345,
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: 'must not become hidden content' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: expect.stringContaining('video'),
|
||||
});
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects mixed video content before resolving a later segment', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
const getGroupRecommendArk = vi.fn(async () => '{"app":"contact"}');
|
||||
const ref = instanceContext(bridgeSend);
|
||||
(ref.bridge.apis as any).contacts = { getGroupRecommendArk };
|
||||
const api = new ApiHandler({
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_group_msg', {
|
||||
group_id: 12345,
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'contact', data: { type: 'group', id: 67890 } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(getGroupRecommendArk).not.toHaveBeenCalled();
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects multiple video segments before sending', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
const ref = instanceContext(bridgeSend);
|
||||
const api = new ApiHandler({
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_group_msg', {
|
||||
group_id: 12345,
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'https://example.com/first.mp4' } },
|
||||
{ type: 'video', data: { file: 'https://example.com/second.mp4' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: expect.stringContaining('video'),
|
||||
});
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects hidden content after a video in CQ string form', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
const ref = instanceContext(bridgeSend);
|
||||
const api = new ApiHandler({
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_group_msg', {
|
||||
group_id: 12345,
|
||||
message: '[CQ:video,file=https://example.com/video.mp4]hidden text',
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects video mixed with private-chat content before sending', async () => {
|
||||
const privateSend = vi.fn(async () => sendReceipt);
|
||||
const ref = instanceContext(vi.fn(), privateSend);
|
||||
const api = new ApiHandler({
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) =>
|
||||
sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_private_msg', {
|
||||
user_id: 67890,
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: 'must not become hidden content' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: expect.stringContaining('only segment'),
|
||||
});
|
||||
expect(privateSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps exact empty text placeholders compatible with a single video', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
const ref = instanceContext(bridgeSend);
|
||||
const api = new ApiHandler({
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_group_msg', {
|
||||
group_id: 12345,
|
||||
message: [
|
||||
{ type: 'text', data: { text: '' } },
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: '' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
expect(bridgeSend).toHaveBeenCalledOnce();
|
||||
expect(bridgeSend.mock.calls[0]?.[1]).toMatchObject([{ type: 'video' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('server-sequence action validation', () => {
|
||||
|
||||
@@ -81,6 +81,22 @@ describe('private window shake messages', () => {
|
||||
expect(sendPrivate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps empty text significant for the standalone window-shake policy', async () => {
|
||||
const sendPrivate = vi.fn(async () => ({ ...receipt, clientSequence: 9 }));
|
||||
const ctx = makeContext({ sendPrivate });
|
||||
|
||||
await expect(sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'poke', data: { type: 1 } },
|
||||
{ type: 'text', data: { text: '' } },
|
||||
], false)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
message: expect.stringContaining('only segment'),
|
||||
});
|
||||
|
||||
expect(sendPrivate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects group window shakes before resolving an earlier segment', async () => {
|
||||
const sendGroup = vi.fn(async () => receipt);
|
||||
const ctx = makeContext({ sendGroup });
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '../../core/src/bridge/bridge-interface';
|
||||
import { ApiHandler } from '../src/api-handler';
|
||||
import { OneBotInstance } from '../src/instance';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
|
||||
import { hashMessageIdInt32, PRIVATE_NT_MESSAGE_EVENT } from '../src/message-id';
|
||||
@@ -158,6 +159,89 @@ function privateSentEvent(overrides: JsonObject = {}): JsonObject {
|
||||
}
|
||||
|
||||
describe('OneBot self-sent events', () => {
|
||||
it('reports upload_private_file as a private self-sent message', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
const handler = new ApiHandler(buildApiContext(ctx));
|
||||
|
||||
const response = await handler.handle('upload_private_file', {
|
||||
user_id: PEER_ID,
|
||||
file: 'base64://AQID',
|
||||
name: 'inline.txt',
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { file_id: 'uploaded-file-uuid' },
|
||||
});
|
||||
expect(ctx.bridge.apis.groupFile.uploadPrivate).toHaveBeenCalledWith(
|
||||
PEER_ID,
|
||||
'base64://AQID',
|
||||
'inline.txt',
|
||||
true,
|
||||
false,
|
||||
);
|
||||
expect(ctx.bridge.apis.message.sendC2cFile).toHaveBeenCalledOnce();
|
||||
expect(dispatchEvent).toHaveBeenCalledOnce();
|
||||
expect(dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({
|
||||
post_type: 'message_sent',
|
||||
message_type: 'private',
|
||||
self_id: SELF_ID,
|
||||
user_id: SELF_ID,
|
||||
target_id: PEER_ID,
|
||||
message_seq: RECEIPT.clientSequence,
|
||||
message: [{
|
||||
type: 'file',
|
||||
data: expect.objectContaining({
|
||||
file_id: 'uploaded-file-uuid',
|
||||
file: 'inline.txt',
|
||||
file_size: 3,
|
||||
}),
|
||||
}],
|
||||
}), 'send');
|
||||
});
|
||||
|
||||
it('fails upload_private_file when publishing the private file fails', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
vi.mocked(ctx.bridge.apis.message.sendC2cFile).mockRejectedValueOnce(
|
||||
new Error('private file publication rejected'),
|
||||
);
|
||||
const handler = new ApiHandler(buildApiContext(ctx));
|
||||
|
||||
const response = await handler.handle('upload_private_file', {
|
||||
user_id: PEER_ID,
|
||||
file: 'base64://AQID',
|
||||
name: 'inline.txt',
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 100,
|
||||
wording: 'private file publication rejected',
|
||||
});
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not report upload_private_file when upload_file is disabled', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
const handler = new ApiHandler(buildApiContext(ctx));
|
||||
|
||||
const response = await handler.handle('upload_private_file', {
|
||||
user_id: PEER_ID,
|
||||
file: 'base64://AQID',
|
||||
name: 'inline.txt',
|
||||
upload_file: false,
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { file_id: 'uploaded-file-uuid' },
|
||||
});
|
||||
expect(ctx.bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a private message sent through an action', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
const api = buildApiContext(ctx);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
|
||||
const FACE = {
|
||||
qSid: '392', qDes: '/龙年快乐', emCode: '10392', qCid: 392,
|
||||
aniStickerType: 3, aniStickerPackId: 1, aniStickerId: 38,
|
||||
url: 'https://example.invalid/392', emojiNameAlias: ['dragon'],
|
||||
aniStickerWidth: 200, aniStickerHeight: 200,
|
||||
};
|
||||
|
||||
function handler(systemFace: Record<string, unknown>): ApiHandler {
|
||||
const bridge = { apis: { systemFace } } as unknown as BridgeInterface;
|
||||
return new ApiHandler({ bridge } as ApiActionContext);
|
||||
}
|
||||
|
||||
describe('system face actions', () => {
|
||||
it('returns the full pack mapping and supports an explicit server refresh', async () => {
|
||||
const fetchCatalog = vi.fn(async () => [{ packName: '超级表情', emojis: [FACE] }]);
|
||||
const response = await handler({ fetchCatalog }).handle('fetch_sys_faces', { refresh: true });
|
||||
|
||||
expect(fetchCatalog).toHaveBeenCalledWith(true);
|
||||
expect(response).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
packs: [{
|
||||
pack_name: '超级表情',
|
||||
emojis: [{ q_sid: '392', q_des: '/龙年快乐', is_super: true }],
|
||||
}],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('looks up one id without redownloading a fresh catalog', async () => {
|
||||
const fetchFace = vi.fn(async () => FACE);
|
||||
const response = await handler({ fetchFace }).handle('fetch_face_entity', { face_id: '392' });
|
||||
|
||||
expect(fetchFace).toHaveBeenCalledWith(392, false);
|
||||
expect(response).toMatchObject({ status: 'ok', data: { q_sid: '392', q_des: '/龙年快乐' } });
|
||||
});
|
||||
|
||||
it('accepts face id 0', async () => {
|
||||
const fetchFace = vi.fn(async () => ({ ...FACE, qSid: '0', qDes: '/惊讶' }));
|
||||
const response = await handler({ fetchFace }).handle('fetch_face_entity', { face_id: 0 });
|
||||
|
||||
expect(fetchFace).toHaveBeenCalledWith(0, false);
|
||||
expect(response).toMatchObject({ status: 'ok', data: { q_sid: '0', q_des: '/惊讶' } });
|
||||
});
|
||||
|
||||
it('searches descriptions and aliases through the shared local catalog', async () => {
|
||||
const search = vi.fn(async () => [FACE]);
|
||||
const response = await handler({ search }).handle('search_sys_faces', { query: 'dragon' });
|
||||
|
||||
expect(search).toHaveBeenCalledWith('dragon');
|
||||
expect(response).toMatchObject({ status: 'ok', data: { faces: [{ q_sid: '392' }] } });
|
||||
});
|
||||
|
||||
it('reports whether an id uses the super-face wire shape', async () => {
|
||||
const isSuper = vi.fn(async () => true);
|
||||
const response = await handler({ isSuper }).handle('fetch_super_face_id', { face_id: 392 });
|
||||
|
||||
expect(isSuper).toHaveBeenCalledWith(392, false);
|
||||
expect(response).toMatchObject({ status: 'ok', data: { is_super: true } });
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,10 @@ const { FakeWebSocketServer, servers } = vi.hoisted(() => {
|
||||
class FakeWebSocketServer extends EventEmitter {
|
||||
closeCallback: ((error?: Error) => void) | null = null;
|
||||
readonly options: {
|
||||
verifyClient?: (info: { req: { headers: Record<string, string>; url?: string } }) => boolean;
|
||||
verifyClient?: (
|
||||
info: { req: { headers: Record<string, string>; url?: string } },
|
||||
done: (allow: boolean, code?: number, message?: string) => void,
|
||||
) => void;
|
||||
};
|
||||
constructor(options: unknown) {
|
||||
super();
|
||||
@@ -86,8 +89,13 @@ describe('WsServerAdapter bind/release lifecycle promises', () => {
|
||||
const verify = servers[0].options.verifyClient;
|
||||
|
||||
expect(verify).toBeTypeOf('function');
|
||||
expect(verify?.({ req: { headers: {}, url: '/?access_token=wrong-token' } })).toBe(false);
|
||||
expect(verify?.({ req: { headers: {}, url: '/?access_token=expected-token' } })).toBe(true);
|
||||
const denied = vi.fn();
|
||||
verify?.({ req: { headers: {}, url: '/?access_token=wrong-token' } }, denied);
|
||||
expect(denied).toHaveBeenCalledWith(false, 401, 'Unauthorized');
|
||||
|
||||
const accepted = vi.fn();
|
||||
verify?.({ req: { headers: {}, url: '/?access_token=expected-token' } }, accepted);
|
||||
expect(accepted).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('rejects bind errors and exposes them as degraded', async () => {
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { getLogLevel, getRecentLogs, setLogLevel } from '@snowluma/common/logger';
|
||||
import { WebSocket, type WebSocketServer } from '@snowluma/websocket';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
import { WsServerAdapter } from '../src/network/ws-server-adapter';
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import type { JsonObject, WsServerNetwork } from '../src/types';
|
||||
|
||||
function waitForOpen(socket: WebSocket): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once('open', resolve);
|
||||
socket.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForMessage(socket: WebSocket): Promise<JsonObject> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once('message', (raw: Buffer) => {
|
||||
try {
|
||||
resolve(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
socket.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForHandshakeError(socket: WebSocket): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once('open', () => reject(new Error('unexpected WebSocket upgrade')));
|
||||
socket.once('error', (error: Error) => resolve(error.message));
|
||||
});
|
||||
}
|
||||
|
||||
function context(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
api: {
|
||||
isAcceptingActions: true,
|
||||
processStreamRequest: vi.fn(async (text: string, send: (frame: string) => Promise<void>) => {
|
||||
const request = JSON.parse(text) as { echo?: unknown };
|
||||
await send(JSON.stringify({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { transport: 'websocket' },
|
||||
echo: request.echo,
|
||||
}));
|
||||
}),
|
||||
} as never,
|
||||
buildLifecycleEvent: (subType) => ({
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: subType,
|
||||
}),
|
||||
buildHeartbeatEvent: () => ({
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'heartbeat',
|
||||
interval: 5000,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function config(): WsServerNetwork {
|
||||
return {
|
||||
name: 'ws-routing',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
role: 'Universal',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe('WsServerAdapter — OneBot forward WebSocket routes', () => {
|
||||
let adapter: WsServerAdapter | null = null;
|
||||
let socket: WebSocket | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
await adapter?.close();
|
||||
adapter = null;
|
||||
socket?.terminate();
|
||||
socket = null;
|
||||
});
|
||||
|
||||
it('serves actions without event frames on /api', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'api-route' }));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'api-route')).toBe(true);
|
||||
});
|
||||
expect(frames.filter((frame) => frame.post_type === 'meta_event')).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts the standard trailing slash on /api/', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
const frames: JsonObject[] = [];
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api/`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'api-slash' }));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'api-slash')).toBe(true);
|
||||
});
|
||||
expect(frames.filter((frame) => frame.post_type === 'meta_event')).toEqual([]);
|
||||
});
|
||||
|
||||
it('pushes events without accepting actions on /event', async () => {
|
||||
const ctx = context();
|
||||
const api = ctx.api as unknown as { processStreamRequest: ReturnType<typeof vi.fn> };
|
||||
adapter = new WsServerAdapter('ws-routing', config(), ctx);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/event`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.map((frame) => frame.meta_event_type)).toEqual([
|
||||
'lifecycle',
|
||||
'lifecycle',
|
||||
'heartbeat',
|
||||
]);
|
||||
});
|
||||
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'event-route' }));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(api.processStreamRequest).not.toHaveBeenCalled();
|
||||
|
||||
const event = { post_type: 'notice', notice_type: 'test' };
|
||||
adapter.onEvent(event, buildDispatchPayload(event));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.at(-1)).toEqual(event);
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts the standard trailing slash on /event/', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/event/`);
|
||||
const firstFrame = waitForMessage(socket);
|
||||
await waitForOpen(socket);
|
||||
|
||||
await expect(firstFrame).resolves.toMatchObject({
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: 'connect',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps / bidirectional', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
await vi.waitFor(() => {
|
||||
expect(frames).toHaveLength(3);
|
||||
});
|
||||
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'universal-route' }));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'universal-route')).toBe(true);
|
||||
});
|
||||
|
||||
const event = { post_type: 'notice', notice_type: 'universal-test' };
|
||||
adapter.onEvent(event, buildDispatchPayload(event));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.at(-1)).toEqual(event);
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects paths outside the configured OneBot endpoints', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/unknown`);
|
||||
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
});
|
||||
|
||||
it('does not include query-string credentials in rejected-path logs', async () => {
|
||||
const previousLevel = getLogLevel();
|
||||
setLogLevel('debug');
|
||||
try {
|
||||
adapter = new WsServerAdapter(
|
||||
'ws-routing',
|
||||
{ ...config(), accessToken: 'expected-secret' },
|
||||
context(),
|
||||
);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(
|
||||
`ws://127.0.0.1:${String(address.port)}/unknown?access_token=log-secret`,
|
||||
);
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
|
||||
const rejection = getRecentLogs(20).find((entry) =>
|
||||
entry.scope === 'OneBot.WS-Server'
|
||||
&& entry.message.includes('rejected unknown WebSocket path /unknown'));
|
||||
expect(rejection).toBeDefined();
|
||||
expect(rejection?.message).not.toContain('log-secret');
|
||||
} finally {
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not normalize a protocol-relative path into the root endpoint', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}//unknown`);
|
||||
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
});
|
||||
|
||||
it('does not normalize a double-slash path into the root endpoint', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}//`);
|
||||
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
});
|
||||
|
||||
it('accepts standard routes with query-string authentication', async () => {
|
||||
adapter = new WsServerAdapter(
|
||||
'ws-routing',
|
||||
{ ...config(), accessToken: 'query-secret' },
|
||||
context(),
|
||||
);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(
|
||||
`ws://127.0.0.1:${String(address.port)}/api?access_token=query-secret`,
|
||||
);
|
||||
|
||||
await expect(waitForOpen(socket)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('treats an omitted standalone role as Universal', async () => {
|
||||
adapter = new WsServerAdapter(
|
||||
'ws-routing',
|
||||
{ ...config(), role: undefined },
|
||||
context(),
|
||||
);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`);
|
||||
await waitForOpen(socket);
|
||||
const response = waitForMessage(socket);
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'default-role' }));
|
||||
|
||||
await expect(response).resolves.toMatchObject({ echo: 'default-role' });
|
||||
});
|
||||
|
||||
it('keeps a non-root configured Universal endpoint bidirectional', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', { ...config(), path: '/api' }, context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.map((frame) => frame.meta_event_type)).toEqual([
|
||||
'lifecycle',
|
||||
'lifecycle',
|
||||
'heartbeat',
|
||||
]);
|
||||
});
|
||||
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'custom-universal' }));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'custom-universal')).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
|
||||
|
||||
@@ -18,11 +18,8 @@ export interface ResponseGrp {
|
||||
groupName?: pb<7, string>;
|
||||
}
|
||||
|
||||
// ResponseHead field 7 is multi-purpose: a forward message carries
|
||||
// `friendName` (field 6); a group temp-session push carries the source group
|
||||
// (field 4). Subfields don't collide, so one interface covers both.
|
||||
export interface ResponseForward {
|
||||
tempGroupUin?: pb<4, uint_32>;
|
||||
tempGroupUin?: pb<5, uint_32>;
|
||||
friendName?: pb<6, string>;
|
||||
}
|
||||
|
||||
|
||||
@@ -315,6 +315,7 @@ export interface OidbGroupDetailFlags {
|
||||
question?: pb<24, bool>;
|
||||
answer?: pb<25, string>;
|
||||
maxAdminCount?: pb<29, string>;
|
||||
shutUpAllTimestamp?: pb<59, bool>;
|
||||
}
|
||||
export interface OidbGroupDetailConfig {
|
||||
uin?: pb<1, uint_64>;
|
||||
|
||||
@@ -82,6 +82,7 @@ export interface OidbSvcTrpcTcp0xFE5_2GroupInfo {
|
||||
description?: pb<18, string>;
|
||||
question?: pb<19, string>;
|
||||
announcement?: pb<30, string>;
|
||||
shutUpAllTimestamp?: pb<31, uint_32>;
|
||||
}
|
||||
|
||||
export interface OidbSvcTrpcTcp0xFE5_2CustomInfo {
|
||||
@@ -115,6 +116,7 @@ export interface OidbSvcTrpcTcp0x88D_0Results {
|
||||
question?: pb<24, string>;
|
||||
answer?: pb<25, string>;
|
||||
maxAdminCount?: pb<29, uint_64>;
|
||||
shutUpAllTimestamp?: pb<59, uint_32>;
|
||||
}
|
||||
export interface OidbSvcTrpcTcp0x88D_0ResponseGroupInfo {
|
||||
uin?: pb<1, uint_64>;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
@@ -44,6 +44,14 @@
|
||||
"types": "./src/self-uid.ts",
|
||||
"default": "./src/self-uid.ts"
|
||||
},
|
||||
"./sys-face-store": {
|
||||
"types": "./src/sys-face-store.ts",
|
||||
"default": "./src/sys-face-store.ts"
|
||||
},
|
||||
"./sys-face-storage": {
|
||||
"types": "./src/sys-face-storage.ts",
|
||||
"default": "./src/sys-face-storage.ts"
|
||||
},
|
||||
"./bridge-oidb": {
|
||||
"types": "./src/bridge-oidb.ts",
|
||||
"default": "./src/bridge-oidb.ts"
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { BridgeContext } from './bridge-context';
|
||||
import { sysFaceStore } from './sys-face-store';
|
||||
import type { MessageElement } from './events';
|
||||
import {
|
||||
assertVideoSendPolicy,
|
||||
assertWindowShakeSendPolicy,
|
||||
assertValidMessageElements,
|
||||
MessageElementValidationError,
|
||||
@@ -55,12 +56,12 @@ function makeTextElem(text: string): ProtoElem {
|
||||
// super (animated, aniSticker not pack (1,1)) → CommonElem 37 + QFaceExtra
|
||||
// other id ≥ 260 → CommonElem 33 + QSmallFaceExtra
|
||||
// classic id < 260 → legacy FaceElem
|
||||
function makeFaceElem(faceId: number, ctx?: SendContext): ProtoElem {
|
||||
// Keep the catalog warm so subsequent super-face sends are classified even if
|
||||
// this one raced ahead of the first fetch.
|
||||
if (ctx) sysFaceStore.ensureWarm(ctx.bridge);
|
||||
|
||||
const wire = sysFaceStore.classify(faceId);
|
||||
async function makeFaceElem(faceId: number, ctx?: SendContext): Promise<ProtoElem> {
|
||||
// With a live bridge, wait for the authoritative catalog. Login normally
|
||||
// preloads it, while this await closes the reconnect / first-send race.
|
||||
const wire = ctx
|
||||
? await sysFaceStore.resolveWire(ctx.bridge, faceId)
|
||||
: sysFaceStore.classify(faceId);
|
||||
if (wire.kind === 'super') {
|
||||
return {
|
||||
commonElem: {
|
||||
@@ -458,6 +459,13 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
// preserves all-or-nothing semantics: a malformed later segment cannot make
|
||||
// an earlier media segment perform side effects before the send is rejected.
|
||||
assertValidMessageElements(elements, 'W');
|
||||
// Canonical MessageElements cannot contain empty text. OneBot's explicit
|
||||
// empty-text compatibility placeholders are removed before this boundary,
|
||||
// so the array length here is the effective on-wire segment count.
|
||||
assertVideoSendPolicy(
|
||||
elements.filter((element) => element.type === 'video').length,
|
||||
elements.length,
|
||||
);
|
||||
assertWindowShakeSendPolicy(
|
||||
elements.filter((element) => element.type === 'poke').length,
|
||||
elements.length,
|
||||
@@ -495,7 +503,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
break;
|
||||
|
||||
case 'face':
|
||||
result.push(makeFaceElem(elem.faceId, ctx));
|
||||
result.push(await makeFaceElem(elem.faceId, ctx));
|
||||
break;
|
||||
|
||||
case 'poke':
|
||||
|
||||
@@ -67,6 +67,33 @@ export function assertWindowShakeSendPolicy(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* QQ clients treat a video as a standalone message: sibling elements remain
|
||||
* on the wire but are not rendered, and additional videos cannot be opened.
|
||||
* Reject that ambiguous wire shape instead of reporting a successful send
|
||||
* whose visible content differs from the caller's request.
|
||||
*/
|
||||
export function assertVideoSendPolicy(
|
||||
videoCount: number,
|
||||
effectiveSegmentCount: number,
|
||||
): void {
|
||||
if (videoCount === 0) return;
|
||||
if (videoCount !== 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'message element "video" may appear only once in a message',
|
||||
'video',
|
||||
);
|
||||
}
|
||||
if (effectiveSegmentCount !== 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'message element "video" must be the only segment in a message',
|
||||
'video',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
type ElementField<T extends MessageElementType> = Exclude<keyof MessageElementOf<T>, 'type'> & string;
|
||||
|
||||
export interface ElementSpec<T extends MessageElementType> {
|
||||
|
||||
@@ -161,7 +161,7 @@ export async function encodeSilk(inputFile: string, tempDir: string): Promise<En
|
||||
|
||||
/** Default location for temporary silk files. */
|
||||
export function defaultPttTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-ptt');
|
||||
return path.join(os.tmpdir(), 'audio-upload');
|
||||
}
|
||||
|
||||
// ── audio transcode (get_record out_format, #165) ──
|
||||
@@ -220,7 +220,7 @@ export async function convertAudioBytes(
|
||||
}
|
||||
const addon = deps.addon ?? getFFmpegAddon();
|
||||
const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT;
|
||||
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'snowluma-rec');
|
||||
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'audio-transcode');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
const inPath = path.join(dir, `${id}.in`);
|
||||
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
|
||||
const log = createLogger('Highway.Stage');
|
||||
|
||||
export const STAGE_DIR = path.join(os.tmpdir(), 'snowluma-stage');
|
||||
export const STAGE_DIR = path.join(os.tmpdir(), 'media-stage');
|
||||
// Must comfortably exceed the slowest plausible single upload (a 1.5 GiB PUT at
|
||||
// a few MB/s is ~5-10 min). Only unregistered (crash-orphaned) temps are reaped.
|
||||
const STAGE_TTL_MS = 30 * 60 * 1000;
|
||||
|
||||
@@ -33,6 +33,7 @@ export namespace FetchGroupDetail {
|
||||
ownerUid: on, createTime: on, maxMemberCount: on, memberCount: on,
|
||||
level: on, name: '', noticePreview: '', uin: on, lastSequence: on,
|
||||
lastMessageTime: on, question: on, answer: '', maxAdminCount: '',
|
||||
shutUpAllTimestamp: on,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -57,6 +57,8 @@ export interface QQGroupInfo {
|
||||
level?: number;
|
||||
/** Group memo / announcement preview. '' when unknown (#197). */
|
||||
memo?: string;
|
||||
/** Whether the group currently has group-wide mute enabled. */
|
||||
allMuted?: boolean;
|
||||
}
|
||||
|
||||
export interface GroupRequestInfo {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import type { SysFaceCatalogSnapshot, SysFaceCatalogStorage } from './sys-face-store';
|
||||
|
||||
function isErrno(error: unknown, code: string): boolean {
|
||||
return typeof error === 'object'
|
||||
&& error !== null
|
||||
&& 'code' in error
|
||||
&& (error as { code?: unknown }).code === code;
|
||||
}
|
||||
|
||||
/** Atomic JSON persistence for the process-wide system-face catalog. */
|
||||
export class JsonSysFaceCatalogStorage implements SysFaceCatalogStorage {
|
||||
constructor(readonly filePath: string) {}
|
||||
|
||||
async load(): Promise<SysFaceCatalogSnapshot | null> {
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(this.filePath, 'utf8');
|
||||
} catch (error) {
|
||||
if (isErrno(error, 'ENOENT')) return null;
|
||||
throw new Error(`failed to read system face catalog ${this.filePath}`, { cause: error });
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(text) as SysFaceCatalogSnapshot;
|
||||
} catch (error) {
|
||||
throw new Error(`failed to parse system face catalog ${this.filePath}`, { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
async save(snapshot: SysFaceCatalogSnapshot): Promise<void> {
|
||||
await mkdir(dirname(this.filePath), { recursive: true });
|
||||
const temporaryPath = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
try {
|
||||
await writeFile(temporaryPath, JSON.stringify(snapshot, null, 2), 'utf8');
|
||||
await rename(temporaryPath, this.filePath);
|
||||
} catch (error) {
|
||||
try {
|
||||
await unlink(temporaryPath);
|
||||
} catch (cleanupError) {
|
||||
if (!isErrno(cleanupError, 'ENOENT')) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
`failed to persist system face catalog ${this.filePath} and remove its temporary file`,
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new Error(`failed to persist system face catalog ${this.filePath}`, { cause: error });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
// Process-wide cache of QQ's system-face catalog (fetched once via 0x9154_1),
|
||||
// used by the send path to pick a face id's wire encoding. The catalog is the
|
||||
// same for every account, so a single shared store is fetched lazily and reused.
|
||||
//
|
||||
// `classify` is synchronous (the element builder is sync); a face sent before
|
||||
// the catalog is warm falls back to an id-range guess. `ensureWarm` kicks off
|
||||
// the one-shot fetch — call it proactively at login so the first super-face
|
||||
// send is already classified.
|
||||
// Process-wide catalog of QQ system faces. QQ publishes the mapping through
|
||||
// 0x9154_1; this store makes that catalog durable, queryable, and safe to use
|
||||
// from the asynchronous send path.
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
@@ -16,77 +11,337 @@ import {
|
||||
} from './oidb-services/sys-faces/fetch-sys-faces';
|
||||
import type { OidbSender } from './oidb-service';
|
||||
|
||||
export type { SysFaceEntry, SysFacePackEntry } from './oidb-services/sys-faces/fetch-sys-faces';
|
||||
|
||||
const log = createLogger('SysFace');
|
||||
|
||||
/** Wire encoding a face id maps to. `classic` → legacy FaceElem; `small` →
|
||||
* CommonElem serviceType 33 (QSmallFaceExtra); `super` → CommonElem
|
||||
* serviceType 37 (QFaceExtra) for animated/super faces. */
|
||||
/** Wire encoding a face id maps to. `classic` -> legacy FaceElem; `small` ->
|
||||
* CommonElem serviceType 33; `super` -> CommonElem serviceType 37. */
|
||||
export type FaceWire =
|
||||
| { kind: 'classic' }
|
||||
| { kind: 'small' }
|
||||
| { kind: 'super'; packId: string; stickerId: string; stickerType: number };
|
||||
|
||||
/** Pure classification: a super face (per the catalog entry) → `super` with its
|
||||
* pack/sticker ids; otherwise an id-range guess (`< 260` = classic, else
|
||||
* small). Used both warm (entry from the catalog) and cold (entry undefined). */
|
||||
export interface SysFaceCatalogSnapshot {
|
||||
schemaVersion: 1;
|
||||
fetchedAt: number;
|
||||
packs: SysFacePackEntry[];
|
||||
}
|
||||
|
||||
export interface SysFaceCatalogStorage {
|
||||
load(): Promise<SysFaceCatalogSnapshot | null>;
|
||||
save(snapshot: SysFaceCatalogSnapshot): Promise<void>;
|
||||
}
|
||||
|
||||
export interface SysFaceStoreOptions {
|
||||
storage?: SysFaceCatalogStorage;
|
||||
fetchCatalog?: (sender: OidbSender) => Promise<SysFacePackEntry[]>;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
interface IndexedCatalog {
|
||||
packs: SysFacePackEntry[];
|
||||
byId: Map<string, SysFaceEntry>;
|
||||
packNameById: Map<string, string>;
|
||||
}
|
||||
|
||||
/** Pure classification once an authoritative entry is known. */
|
||||
export function faceWireFor(entry: SysFaceEntry | null | undefined, faceId: number): FaceWire {
|
||||
if (entry && isSuperFaceEntry(entry)) {
|
||||
if (!entry) {
|
||||
throw new Error(`QQ system face id ${faceId} is absent from the current catalog`);
|
||||
}
|
||||
if (isSuperFaceEntry(entry)) {
|
||||
if (entry.aniStickerPackId == null
|
||||
|| entry.aniStickerId == null
|
||||
|| entry.aniStickerType == null) {
|
||||
throw new Error(`QQ system face id ${faceId} has incomplete super-face metadata`);
|
||||
}
|
||||
return {
|
||||
kind: 'super',
|
||||
packId: String(entry.aniStickerPackId ?? 1),
|
||||
stickerId: String(entry.aniStickerId ?? 0),
|
||||
stickerType: entry.aniStickerType ?? 0,
|
||||
packId: String(entry.aniStickerPackId),
|
||||
stickerId: String(entry.aniStickerId),
|
||||
stickerType: entry.aniStickerType,
|
||||
};
|
||||
}
|
||||
return faceId < 260 ? { kind: 'classic' } : { kind: 'small' };
|
||||
}
|
||||
|
||||
const RETRY_COOLDOWN_MS = 30_000;
|
||||
export class SysFaceStore {
|
||||
private catalog: IndexedCatalog | null = null;
|
||||
private storage: SysFaceCatalogStorage | null;
|
||||
private readonly fetchCatalog: (sender: OidbSender) => Promise<SysFacePackEntry[]>;
|
||||
private readonly now: () => number;
|
||||
private cacheLoadCompleted = false;
|
||||
private cacheLoadInflight: Promise<boolean> | null = null;
|
||||
private refreshInflight: Promise<SysFacePackEntry[]> | null = null;
|
||||
private refreshedInProcess = false;
|
||||
private prewarmInflight: Promise<void> | null = null;
|
||||
private prewarmed = false;
|
||||
|
||||
class SysFaceStore {
|
||||
private byId: Map<string, SysFaceEntry> | null = null;
|
||||
private inflight: Promise<void> | null = null;
|
||||
private lastFailedAt = 0;
|
||||
constructor(options: SysFaceStoreOptions = {}) {
|
||||
this.storage = options.storage ?? null;
|
||||
this.fetchCatalog = options.fetchCatalog ?? ((sender) => FetchSysFaces.invoke(sender));
|
||||
this.now = options.now ?? Date.now;
|
||||
}
|
||||
|
||||
/** Index a fetched catalog (also used by tests to seed without a network). */
|
||||
/** Configure persistence before the shared store has been used. */
|
||||
configureStorage(storage: SysFaceCatalogStorage): void {
|
||||
if (this.cacheLoadCompleted || this.cacheLoadInflight || this.catalog || this.refreshInflight) {
|
||||
throw new Error('system face catalog storage must be configured before first use');
|
||||
}
|
||||
this.storage = storage;
|
||||
}
|
||||
|
||||
/** Index a trusted catalog. Kept public for protocol consumers that already
|
||||
* obtained a full catalog and want to reuse the same query/send semantics. */
|
||||
load(packs: SysFacePackEntry[]): void {
|
||||
this.byId = buildIndex(packs);
|
||||
this.catalog = indexCatalog(validateCatalog(packs));
|
||||
}
|
||||
|
||||
/** Synchronous classification. Falls back to an id-range guess when the
|
||||
* catalog isn't warm yet or the id is unknown. */
|
||||
lookup(faceId: number): SysFaceEntry | null {
|
||||
return this.catalog?.byId.get(String(faceId)) ?? null;
|
||||
}
|
||||
|
||||
/** Case-insensitive query over id, description, aliases, and pack name. */
|
||||
search(query: string): SysFaceEntry[] {
|
||||
const needle = query.trim().toLocaleLowerCase();
|
||||
if (!needle || !this.catalog) return [];
|
||||
|
||||
const matches: SysFaceEntry[] = [];
|
||||
for (const [id, face] of this.catalog.byId) {
|
||||
const haystacks = [
|
||||
id,
|
||||
face.qDes,
|
||||
face.emCode,
|
||||
this.catalog.packNameById.get(id) ?? '',
|
||||
...face.emojiNameAlias,
|
||||
];
|
||||
if (haystacks.some((value) => value.toLocaleLowerCase().includes(needle))) {
|
||||
matches.push(face);
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
/** Synchronous classification for callers that already established catalog
|
||||
* readiness. Unknown ids fail instead of guessing a QQ wire shape. */
|
||||
classify(faceId: number): FaceWire {
|
||||
return faceWireFor(this.byId?.get(String(faceId)), faceId);
|
||||
return faceWireFor(this.lookup(faceId), faceId);
|
||||
}
|
||||
|
||||
/** Fire-and-forget one-shot warm. Coalesces concurrent callers; backs off
|
||||
* briefly after a failure so a flaky fetch isn't hammered per message. */
|
||||
ensureWarm(sender: OidbSender): void {
|
||||
if (this.byId || this.inflight) return;
|
||||
if (Date.now() - this.lastFailedAt < RETRY_COOLDOWN_MS) return;
|
||||
this.inflight = FetchSysFaces.invoke(sender)
|
||||
.then((packs) => {
|
||||
this.load(packs);
|
||||
log.info('system face catalog loaded: %d faces', this.byId?.size ?? 0);
|
||||
/** Load durable state, fetching only when no usable catalog exists. */
|
||||
async ensureReady(sender: OidbSender): Promise<void> {
|
||||
if (this.refreshInflight) {
|
||||
await this.refreshInflight;
|
||||
return;
|
||||
}
|
||||
if (this.catalog) return;
|
||||
const loaded = await this.loadCache();
|
||||
if (!loaded) await this.refresh(sender);
|
||||
}
|
||||
|
||||
/** Login hook: restore the durable snapshot for immediate reads, then refresh
|
||||
* from QQ exactly once per process. Multiple accounts share the same job. */
|
||||
prewarm(sender: OidbSender): Promise<void> {
|
||||
if (this.prewarmed) return Promise.resolve();
|
||||
if (this.prewarmInflight) return this.prewarmInflight;
|
||||
|
||||
this.prewarmInflight = (async () => {
|
||||
try {
|
||||
await this.loadCache();
|
||||
} catch {
|
||||
// loadCache already emitted the path and failure. A fresh server fetch
|
||||
// is the authoritative repair for a corrupt rebuildable snapshot.
|
||||
}
|
||||
await this.refresh(sender);
|
||||
this.prewarmed = true;
|
||||
})().finally(() => {
|
||||
this.prewarmInflight = null;
|
||||
});
|
||||
return this.prewarmInflight;
|
||||
}
|
||||
|
||||
/** Fetch the current authoritative catalog. Concurrent callers share one
|
||||
* request and one atomic persistence operation. */
|
||||
refresh(sender: OidbSender): Promise<SysFacePackEntry[]> {
|
||||
if (this.refreshInflight) return this.refreshInflight;
|
||||
|
||||
const startedAt = this.now();
|
||||
this.refreshInflight = this.fetchCatalog(sender)
|
||||
.then(async (packs) => {
|
||||
const validated = validateCatalog(packs);
|
||||
const snapshot: SysFaceCatalogSnapshot = {
|
||||
schemaVersion: 1,
|
||||
fetchedAt: this.now(),
|
||||
packs: validated,
|
||||
};
|
||||
this.catalog = indexCatalog(validated);
|
||||
this.refreshedInProcess = true;
|
||||
if (this.storage) await this.storage.save(snapshot);
|
||||
log.info(
|
||||
'system face catalog refreshed: faces=%d packs=%d elapsedMs=%d',
|
||||
this.catalog.byId.size,
|
||||
validated.length,
|
||||
this.now() - startedAt,
|
||||
);
|
||||
return validated;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.lastFailedAt = Date.now();
|
||||
log.warn('failed to load system face catalog: %s', err instanceof Error ? err.message : String(err));
|
||||
.catch((error) => {
|
||||
log.error(
|
||||
'system face catalog refresh failed: elapsedMs=%d error=%s',
|
||||
this.now() - startedAt,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
this.inflight = null;
|
||||
this.refreshInflight = null;
|
||||
});
|
||||
return this.refreshInflight;
|
||||
}
|
||||
|
||||
/** Resolve one id. A miss from a persisted snapshot causes exactly one
|
||||
* authoritative refresh; a miss from that fresh catalog remains null. */
|
||||
async resolve(sender: OidbSender, faceId: number): Promise<SysFaceEntry | null> {
|
||||
await this.ensureReady(sender);
|
||||
const cached = this.lookup(faceId);
|
||||
if (cached || this.refreshedInProcess) return cached;
|
||||
|
||||
await this.refresh(sender);
|
||||
return this.lookup(faceId);
|
||||
}
|
||||
|
||||
async resolveWire(sender: OidbSender, faceId: number): Promise<FaceWire> {
|
||||
const entry = await this.resolve(sender, faceId);
|
||||
if (!entry) {
|
||||
throw new Error(`QQ system face id ${faceId} is absent from the current catalog`);
|
||||
}
|
||||
return faceWireFor(entry, faceId);
|
||||
}
|
||||
|
||||
async getCatalog(sender: OidbSender, refresh = false): Promise<SysFacePackEntry[]> {
|
||||
if (refresh) await this.refresh(sender);
|
||||
else await this.ensureReady(sender);
|
||||
if (!this.catalog) {
|
||||
throw new Error('system face catalog is unavailable after readiness completed');
|
||||
}
|
||||
return this.catalog.packs;
|
||||
}
|
||||
|
||||
private loadCache(): Promise<boolean> {
|
||||
if (this.catalog) return Promise.resolve(true);
|
||||
if (this.cacheLoadCompleted) return Promise.resolve(false);
|
||||
if (this.cacheLoadInflight) return this.cacheLoadInflight;
|
||||
|
||||
if (!this.storage) {
|
||||
this.cacheLoadCompleted = true;
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
const startedAt = this.now();
|
||||
this.cacheLoadInflight = this.storage.load()
|
||||
.then((snapshot) => {
|
||||
this.cacheLoadCompleted = true;
|
||||
if (!snapshot) return false;
|
||||
validateSnapshot(snapshot);
|
||||
this.catalog = indexCatalog(snapshot.packs);
|
||||
log.info(
|
||||
'system face catalog restored: faces=%d packs=%d fetchedAt=%d elapsedMs=%d',
|
||||
this.catalog.byId.size,
|
||||
snapshot.packs.length,
|
||||
snapshot.fetchedAt,
|
||||
this.now() - startedAt,
|
||||
);
|
||||
return true;
|
||||
})
|
||||
.catch((error) => {
|
||||
this.cacheLoadCompleted = true;
|
||||
log.error(
|
||||
'system face catalog restore failed: elapsedMs=%d error=%s',
|
||||
this.now() - startedAt,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
this.cacheLoadInflight = null;
|
||||
});
|
||||
return this.cacheLoadInflight;
|
||||
}
|
||||
}
|
||||
|
||||
function buildIndex(packs: SysFacePackEntry[]): Map<string, SysFaceEntry> {
|
||||
const map = new Map<string, SysFaceEntry>();
|
||||
for (const pack of packs) {
|
||||
for (const emoji of pack.emojis) {
|
||||
if (emoji.qSid) map.set(emoji.qSid, emoji);
|
||||
function validateSnapshot(snapshot: SysFaceCatalogSnapshot): void {
|
||||
if (typeof snapshot !== 'object' || snapshot === null) {
|
||||
throw new Error('invalid system face catalog snapshot root');
|
||||
}
|
||||
if (snapshot.schemaVersion !== 1) {
|
||||
throw new Error(`unsupported system face catalog schema version: ${String(snapshot.schemaVersion)}`);
|
||||
}
|
||||
if (!Number.isSafeInteger(snapshot.fetchedAt) || snapshot.fetchedAt < 0) {
|
||||
throw new Error(`invalid system face catalog fetchedAt: ${String(snapshot.fetchedAt)}`);
|
||||
}
|
||||
validateCatalog(snapshot.packs);
|
||||
}
|
||||
|
||||
function validateCatalog(packs: SysFacePackEntry[]): SysFacePackEntry[] {
|
||||
if (!Array.isArray(packs) || packs.length === 0) {
|
||||
throw new Error('system face catalog is empty');
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
let faceCount = 0;
|
||||
for (const [packIndex, pack] of packs.entries()) {
|
||||
if (!pack || typeof pack.packName !== 'string' || !Array.isArray(pack.emojis)) {
|
||||
throw new Error(`invalid system face pack at index ${packIndex}`);
|
||||
}
|
||||
for (const [faceIndex, face] of pack.emojis.entries()) {
|
||||
if (!face || typeof face.qSid !== 'string' || !/^(?:0|[1-9]\d*)$/.test(face.qSid)
|
||||
|| !Number.isSafeInteger(Number(face.qSid)) || Number(face.qSid) < 0) {
|
||||
throw new Error(`invalid system face id at pack ${packIndex}, face ${faceIndex}`);
|
||||
}
|
||||
if (seen.has(face.qSid)) {
|
||||
throw new Error(`duplicate system face id ${face.qSid}`);
|
||||
}
|
||||
if (!Array.isArray(face.emojiNameAlias)
|
||||
|| face.emojiNameAlias.some((alias) => typeof alias !== 'string')) {
|
||||
throw new Error(`invalid aliases for system face id ${face.qSid}`);
|
||||
}
|
||||
if (typeof face.qDes !== 'string' || typeof face.emCode !== 'string') {
|
||||
throw new Error(`invalid text metadata for system face id ${face.qSid}`);
|
||||
}
|
||||
for (const [name, value] of [
|
||||
['qCid', face.qCid],
|
||||
['aniStickerType', face.aniStickerType],
|
||||
['aniStickerPackId', face.aniStickerPackId],
|
||||
['aniStickerId', face.aniStickerId],
|
||||
['aniStickerWidth', face.aniStickerWidth],
|
||||
['aniStickerHeight', face.aniStickerHeight],
|
||||
] as const) {
|
||||
if (value !== null && !Number.isSafeInteger(value)) {
|
||||
throw new Error(`invalid ${name} for system face id ${face.qSid}`);
|
||||
}
|
||||
}
|
||||
if (face.url !== null && typeof face.url !== 'string') {
|
||||
throw new Error(`invalid url for system face id ${face.qSid}`);
|
||||
}
|
||||
seen.add(face.qSid);
|
||||
faceCount += 1;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
if (faceCount === 0) throw new Error('system face catalog contains no faces');
|
||||
return packs;
|
||||
}
|
||||
|
||||
function indexCatalog(packs: SysFacePackEntry[]): IndexedCatalog {
|
||||
const byId = new Map<string, SysFaceEntry>();
|
||||
const packNameById = new Map<string, string>();
|
||||
for (const pack of packs) {
|
||||
for (const emoji of pack.emojis) {
|
||||
byId.set(emoji.qSid, emoji);
|
||||
packNameById.set(emoji.qSid, pack.packName);
|
||||
}
|
||||
}
|
||||
return { packs, byId, packNameById };
|
||||
}
|
||||
|
||||
/** Shared, process-wide catalog (the face set is account-independent). */
|
||||
|
||||
@@ -221,8 +221,15 @@ export async function uploadImageToGroupAlbum(
|
||||
filePath: string,
|
||||
uin: string
|
||||
): Promise<void> {
|
||||
const { loadBinarySource } = await import('../highway/utils');
|
||||
const { detectImageFormat, loadBinarySource } = await import('../highway/utils');
|
||||
const loaded = await loadBinarySource(filePath, 'album image');
|
||||
const format = detectImageFormat(loaded.bytes);
|
||||
const isJpeg = loaded.bytes.length >= 2
|
||||
&& loaded.bytes[0] === 0xFF
|
||||
&& loaded.bytes[1] === 0xD8;
|
||||
if (format.format === 1000 && !isJpeg) {
|
||||
throw new Error('群相册上传仅支持 JPEG、PNG、GIF、WebP 或 BMP 图片');
|
||||
}
|
||||
|
||||
let tempFile: string | null = null;
|
||||
let actualPath = filePath;
|
||||
|
||||
@@ -41,6 +41,16 @@ export interface GroupEssenceMsgRet {
|
||||
};
|
||||
}
|
||||
|
||||
interface RawGroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
retmsg?: string;
|
||||
data?: {
|
||||
is_end?: unknown;
|
||||
msg_list?: Array<GroupEssenceMessage | null> | null;
|
||||
group_role?: number;
|
||||
config_page_url?: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
@@ -61,7 +71,7 @@ export async function getGroupEssenceMsg(
|
||||
}).toString()}`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
|
||||
const ret = await RequestUtil.HttpGetJson<RawGroupEssenceMsgRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
@@ -72,12 +82,35 @@ export async function getGroupEssenceMsg(
|
||||
`group essence request failed with retcode ${ret.retcode}: ${ret.retmsg ?? 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
if (ret.data?.is_end === true && ret.data.msg_list == null) {
|
||||
log.debug(
|
||||
'normalized empty group essence response (group=%s page=%d/%d)',
|
||||
groupCode,
|
||||
pageStart,
|
||||
pageLimit,
|
||||
);
|
||||
return {
|
||||
...ret,
|
||||
data: {
|
||||
...ret.data,
|
||||
is_end: true,
|
||||
msg_list: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
if (!ret.data
|
||||
|| typeof ret.data.is_end !== 'boolean'
|
||||
|| !Array.isArray(ret.data.msg_list)) {
|
||||
throw new Error('invalid group essence response: data.is_end or data.msg_list is missing');
|
||||
}
|
||||
return ret;
|
||||
return {
|
||||
...ret,
|
||||
data: {
|
||||
...ret.data,
|
||||
is_end: ret.data.is_end,
|
||||
msg_list: ret.data.msg_list,
|
||||
},
|
||||
};
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import {
|
||||
protobuf_encode,
|
||||
type pb,
|
||||
type pb_repeated,
|
||||
type string,
|
||||
type uint_32,
|
||||
} from '@snowluma/proton';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { IdentityService } from '../../src/identity-service';
|
||||
import { parseMsgPush } from '../../src/msg-push';
|
||||
|
||||
interface TextFixture {
|
||||
str?: pb<1, string>;
|
||||
}
|
||||
|
||||
interface ElemFixture {
|
||||
text?: pb<1, TextFixture>;
|
||||
}
|
||||
|
||||
interface RichTextFixture {
|
||||
elems?: pb_repeated<2, ElemFixture>;
|
||||
}
|
||||
|
||||
interface MessageBodyFixture {
|
||||
richText?: pb<1, RichTextFixture>;
|
||||
}
|
||||
|
||||
interface TempSessionFixture {
|
||||
previousGroup?: pb<4, uint_32>;
|
||||
sourceGroup?: pb<5, uint_32>;
|
||||
}
|
||||
|
||||
interface ResponseHeadFixture {
|
||||
fromUin?: pb<1, uint_32>;
|
||||
fromUid?: pb<2, string>;
|
||||
tempSession?: pb<7, TempSessionFixture>;
|
||||
}
|
||||
|
||||
interface ContentHeadFixture {
|
||||
msgType?: pb<1, uint_32>;
|
||||
sequence?: pb<5, uint_32>;
|
||||
timestamp?: pb<6, uint_32>;
|
||||
ntMsgSeq?: pb<11, uint_32>;
|
||||
}
|
||||
|
||||
interface PushBodyFixture {
|
||||
responseHead?: pb<1, ResponseHeadFixture>;
|
||||
contentHead?: pb<2, ContentHeadFixture>;
|
||||
body?: pb<3, MessageBodyFixture>;
|
||||
}
|
||||
|
||||
interface PushFixture {
|
||||
message?: pb<1, PushBodyFixture>;
|
||||
}
|
||||
|
||||
const identity = { findFriend: () => undefined } as unknown as IdentityService;
|
||||
|
||||
function tempMessagePacket(previousGroup: number, sourceGroup: number): PacketInfo {
|
||||
return {
|
||||
pid: 1,
|
||||
uin: '2000000001',
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
seqId: 1,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: protobuf_encode<PushFixture>({
|
||||
message: {
|
||||
responseHead: {
|
||||
fromUin: 10001,
|
||||
fromUid: 'u_peer',
|
||||
tempSession: { previousGroup, sourceGroup },
|
||||
},
|
||||
contentHead: {
|
||||
msgType: 141,
|
||||
sequence: 7,
|
||||
timestamp: 1_710_000_000,
|
||||
ntMsgSeq: 8,
|
||||
},
|
||||
body: { richText: { elems: [{ text: { str: 'hello' } }] } },
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe('parseMsgPush — temporary-session source (#308)', () => {
|
||||
it('keeps a passive reply bound to the group that opened the current session', () => {
|
||||
const events = parseMsgPush(tempMessagePacket(11111, 22222), identity);
|
||||
|
||||
expect(events).toMatchObject([{
|
||||
kind: 'temp_message',
|
||||
senderUin: 10001,
|
||||
groupId: 22222,
|
||||
elements: [{ type: 'text', text: 'hello' }],
|
||||
}]);
|
||||
});
|
||||
});
|
||||
@@ -3,13 +3,33 @@
|
||||
// matching Lagrange's GetGroupInfoService) and the response decode.
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import {
|
||||
protobuf_decode,
|
||||
protobuf_encode,
|
||||
type pb,
|
||||
type uint_32,
|
||||
type uint_64,
|
||||
} from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupDetailRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchGroupDetail } from '../../../src/oidb-services/contacts/fetch-group-detail';
|
||||
|
||||
interface GroupDetailResultsFixture {
|
||||
name?: pb<15, string>;
|
||||
shutUpAllTimestamp?: pb<59, uint_32>;
|
||||
}
|
||||
|
||||
interface GroupDetailInfoFixture {
|
||||
uin?: pb<1, uint_64>;
|
||||
results?: pb<3, GroupDetailResultsFixture>;
|
||||
}
|
||||
|
||||
interface GroupDetailResponseFixture {
|
||||
groupInfo?: pb<1, GroupDetailInfoFixture>;
|
||||
}
|
||||
|
||||
function makeSender(body?: OidbSvcTrpcTcp0x88D_0Response) {
|
||||
const responseData = body !== undefined
|
||||
? Buffer.from(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({ body }))
|
||||
@@ -33,6 +53,8 @@ describe('FetchGroupDetail namespace', () => {
|
||||
expect(out.config?.flags?.name).toBe(''); // string mask → request the name
|
||||
expect(out.config?.flags?.memberCount).toBe(true);
|
||||
expect(out.config?.flags?.maxMemberCount).toBe(true);
|
||||
expect((out.config?.flags as { shutUpAllTimestamp?: boolean })?.shutUpAllTimestamp)
|
||||
.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,5 +88,28 @@ describe('FetchGroupDetail namespace', () => {
|
||||
expect(out.groupInfo?.results?.memberCount).toBe(42n);
|
||||
expect(out.groupInfo?.results?.maxMemberCount).toBe(500n);
|
||||
});
|
||||
|
||||
it('decodes the group-wide mute timestamp from a detail response', async () => {
|
||||
const responseData = Buffer.from(protobuf_encode<OidbBase<GroupDetailResponseFixture>>({
|
||||
body: {
|
||||
groupInfo: {
|
||||
uin: 601692726n,
|
||||
results: { name: 'Muted Group', shutUpAllTimestamp: 4_294_967_295 },
|
||||
},
|
||||
},
|
||||
}));
|
||||
const sender = makeSender();
|
||||
sender.sendRawPacket.mockResolvedValue({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData,
|
||||
});
|
||||
|
||||
const out = await FetchGroupDetail.invoke(sender, { groupUin: 601692726 });
|
||||
|
||||
expect(out.groupInfo?.results?.shutUpAllTimestamp).toBe(4_294_967_295);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,31 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import {
|
||||
protobuf_decode,
|
||||
protobuf_encode,
|
||||
type pb,
|
||||
type pb_repeated,
|
||||
type uint_32,
|
||||
} from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchGroupList } from '../../../src/oidb-services/contacts/fetch-group-list';
|
||||
|
||||
interface GroupInfoFixture {
|
||||
groupName?: pb<5, string>;
|
||||
shutUpAllTimestamp?: pb<31, uint_32>;
|
||||
}
|
||||
|
||||
interface GroupFixture {
|
||||
groupUin?: pb<3, uint_32>;
|
||||
info?: pb<4, GroupInfoFixture>;
|
||||
}
|
||||
|
||||
interface GroupListFixture {
|
||||
groups?: pb_repeated<2, GroupFixture>;
|
||||
}
|
||||
|
||||
function makeSender() {
|
||||
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
@@ -35,6 +55,7 @@ describe('FetchGroupList namespace', () => {
|
||||
const env = protobuf_decode<OidbBase<OidbGroupListRequest>>(bytes);
|
||||
expect(env.body?.config?.config1?.groupName).toBe(true);
|
||||
expect(env.body?.config?.config1?.memberCount).toBe(true);
|
||||
expect(env.body?.config?.config1?.field31).toBe(true);
|
||||
expect(env.body?.config?.config2?.remark).toBe(true);
|
||||
for (const field of ['field1', 'field2', 'field4', 'field5', 'field6', 'field7', 'field8'] as const) {
|
||||
expect(env.body?.config?.config2?.[field] ?? false, field).toBe(false);
|
||||
@@ -43,5 +64,28 @@ describe('FetchGroupList namespace', () => {
|
||||
expect(env.body?.config?.config1?.field5002 ?? false).toBe(false);
|
||||
expect(env.body?.config?.config1?.field5003 ?? false).toBe(false);
|
||||
});
|
||||
|
||||
it('decodes the group-wide mute timestamp returned with the joined roster', async () => {
|
||||
const responseData = Buffer.from(protobuf_encode<OidbBase<GroupListFixture>>({
|
||||
body: {
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: { groupName: 'Muted Group', shutUpAllTimestamp: 4_294_967_295 },
|
||||
}],
|
||||
},
|
||||
}));
|
||||
const sender = makeSender();
|
||||
sender.sendRawPacket.mockResolvedValue({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData,
|
||||
});
|
||||
|
||||
const out = await FetchGroupList.invoke(sender);
|
||||
|
||||
expect(out.groups?.[0]?.info?.shutUpAllTimestamp).toBe(4_294_967_295);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { JsonSysFaceCatalogStorage } from '../src/sys-face-storage';
|
||||
import type { SysFaceCatalogSnapshot } from '../src/sys-face-store';
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
async function fixturePath(): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'snowluma-sys-face-'));
|
||||
roots.push(root);
|
||||
return join(root, 'nested', 'sys-faces.json');
|
||||
}
|
||||
|
||||
const SNAPSHOT: SysFaceCatalogSnapshot = {
|
||||
schemaVersion: 1,
|
||||
fetchedAt: 123,
|
||||
packs: [{
|
||||
packName: '经典',
|
||||
emojis: [{
|
||||
qSid: '14', qDes: '/微笑', emCode: '14', qCid: null,
|
||||
aniStickerType: null, aniStickerPackId: null, aniStickerId: null,
|
||||
url: null, emojiNameAlias: ['smile'],
|
||||
aniStickerWidth: null, aniStickerHeight: null,
|
||||
}],
|
||||
}],
|
||||
};
|
||||
|
||||
describe('JsonSysFaceCatalogStorage', () => {
|
||||
it('returns null for a missing cache and round-trips an atomic save', async () => {
|
||||
const file = await fixturePath();
|
||||
const storage = new JsonSysFaceCatalogStorage(file);
|
||||
|
||||
await expect(storage.load()).resolves.toBeNull();
|
||||
await storage.save(SNAPSHOT);
|
||||
await expect(storage.load()).resolves.toEqual(SNAPSHOT);
|
||||
expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(SNAPSHOT);
|
||||
});
|
||||
|
||||
it('surfaces malformed JSON with the cache path instead of ignoring it', async () => {
|
||||
const file = await fixturePath();
|
||||
const storage = new JsonSysFaceCatalogStorage(file);
|
||||
await storage.save(SNAPSHOT);
|
||||
await writeFile(file, '{broken', 'utf8');
|
||||
|
||||
await expect(storage.load()).rejects.toThrow(file);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbFetchSysFacesResp } from '@snowluma/proto-defs/oidb-actions/sys-faces';
|
||||
import {
|
||||
FetchSysFaces,
|
||||
findFaceEntity,
|
||||
@@ -9,27 +11,54 @@ import {
|
||||
type SysFaceEntry,
|
||||
type SysFacePackEntry,
|
||||
} from '../src/oidb-services/sys-faces/fetch-sys-faces';
|
||||
import { faceWireFor, sysFaceStore } from '../src/sys-face-store';
|
||||
import {
|
||||
faceWireFor,
|
||||
SysFaceStore,
|
||||
sysFaceStore,
|
||||
type SysFaceCatalogSnapshot,
|
||||
type SysFaceCatalogStorage,
|
||||
} from '../src/sys-face-store';
|
||||
import { buildSendElems } from '../src/element-builder';
|
||||
|
||||
function entry(qSid: string, aniStickerType: number | null, aniStickerPackId: number | null, aniStickerId: number | null): SysFaceEntry {
|
||||
function entry(
|
||||
qSid: string,
|
||||
aniStickerType: number | null,
|
||||
aniStickerPackId: number | null,
|
||||
aniStickerId: number | null,
|
||||
qDes = '',
|
||||
emojiNameAlias: string[] = [],
|
||||
): SysFaceEntry {
|
||||
return {
|
||||
qSid, qDes: '', emCode: '', qCid: null,
|
||||
qSid, qDes, emCode: '', qCid: null,
|
||||
aniStickerType, aniStickerPackId, aniStickerId,
|
||||
url: null, emojiNameAlias: [], aniStickerWidth: null, aniStickerHeight: null,
|
||||
url: null, emojiNameAlias, aniStickerWidth: null, aniStickerHeight: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 392 is a real non-(1,1) super face; 424 is a real (1,1) "new small" face.
|
||||
const CATALOG: SysFacePackEntry[] = [
|
||||
{ packName: '经典', emojis: [entry('14', null, null, null)] },
|
||||
{ packName: '经典', emojis: [entry('14', null, null, null, '/微笑', ['smile'])] },
|
||||
{ packName: '超级表情', emojis: [
|
||||
entry('392', 3, 2, 38), // super → CommonElem 37
|
||||
entry('392', 3, 2, 38, '/龙年快乐'), // super → CommonElem 37
|
||||
entry('424', 1, 1, 52), // (1,1) → small → CommonElem 33
|
||||
entry('358', 2, 1, 33), // super (packId 1 but type 2) → CommonElem 37
|
||||
] },
|
||||
];
|
||||
|
||||
class MemoryCatalogStorage implements SysFaceCatalogStorage {
|
||||
saved: SysFaceCatalogSnapshot[] = [];
|
||||
|
||||
constructor(private readonly initial: SysFaceCatalogSnapshot | null = null) {}
|
||||
|
||||
async load(): Promise<SysFaceCatalogSnapshot | null> {
|
||||
return this.initial;
|
||||
}
|
||||
|
||||
async save(snapshot: SysFaceCatalogSnapshot): Promise<void> {
|
||||
this.saved.push(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
describe('isSuperFaceEntry / isSuperFaceId — the (1,1) rule', () => {
|
||||
it('treats only non-(1,1) aniSticker faces as super', () => {
|
||||
expect(isSuperFaceEntry(entry('x', 3, 2, 1))).toBe(true);
|
||||
@@ -58,13 +87,16 @@ describe('faceWireFor — classification', () => {
|
||||
kind: 'super', packId: '2', stickerId: '38', stickerType: 3,
|
||||
});
|
||||
});
|
||||
it('rejects incomplete super-face metadata instead of filling guessed ids', () => {
|
||||
expect(() => faceWireFor(entry('392', 3, 2, null), 392))
|
||||
.toThrow(/incomplete super-face metadata/);
|
||||
});
|
||||
it('(1,1) face → small/classic by id range, not super', () => {
|
||||
expect(faceWireFor(entry('424', 1, 1, 52), 424)).toEqual({ kind: 'small' });
|
||||
});
|
||||
it('cold (no catalog entry) → id-range guess', () => {
|
||||
expect(faceWireFor(undefined, 14)).toEqual({ kind: 'classic' }); // < 260
|
||||
expect(faceWireFor(undefined, 424)).toEqual({ kind: 'small' }); // ≥ 260
|
||||
expect(faceWireFor(null, 100)).toEqual({ kind: 'classic' });
|
||||
it('rejects an unknown id instead of guessing a wire shape', () => {
|
||||
expect(() => faceWireFor(null, 14)).toThrow(/absent from the current catalog/);
|
||||
expect(() => faceWireFor(undefined, 424)).toThrow(/absent from the current catalog/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -80,9 +112,193 @@ describe('FetchSysFaces.deserialize', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('SysFaceStore — persistent catalog and query seam', () => {
|
||||
const sender = {} as never;
|
||||
|
||||
it('accepts face id 0 from the authoritative catalog', async () => {
|
||||
const zero = entry('0', null, null, null, '/惊讶');
|
||||
const store = new SysFaceStore({
|
||||
storage: new MemoryCatalogStorage({
|
||||
schemaVersion: 1,
|
||||
fetchedAt: 123,
|
||||
packs: [{ packName: '经典', emojis: [zero] }],
|
||||
}),
|
||||
fetchCatalog: async () => { throw new Error('network must not be used'); },
|
||||
});
|
||||
|
||||
await store.ensureReady(sender);
|
||||
|
||||
expect(store.lookup(0)?.qDes).toBe('/惊讶');
|
||||
expect(store.classify(0)).toEqual({ kind: 'classic' });
|
||||
});
|
||||
|
||||
it('loads a persisted catalog and resolves ids, descriptions, aliases, and pack names', async () => {
|
||||
const storage = new MemoryCatalogStorage({
|
||||
schemaVersion: 1,
|
||||
fetchedAt: 123,
|
||||
packs: CATALOG,
|
||||
});
|
||||
const store = new SysFaceStore({
|
||||
storage,
|
||||
fetchCatalog: async () => { throw new Error('network must not be used'); },
|
||||
});
|
||||
|
||||
await store.ensureReady(sender);
|
||||
|
||||
expect(store.lookup(392)?.qDes).toBe('/龙年快乐');
|
||||
expect(store.search('龙年').map((face) => face.qSid)).toEqual(['392']);
|
||||
expect(store.search('SMILE').map((face) => face.qSid)).toEqual(['14']);
|
||||
expect(store.search('经典').map((face) => face.qSid)).toEqual(['14']);
|
||||
});
|
||||
|
||||
it('coalesces concurrent refreshes and persists the authoritative result once', async () => {
|
||||
const storage = new MemoryCatalogStorage();
|
||||
let fetches = 0;
|
||||
let release!: (packs: SysFacePackEntry[]) => void;
|
||||
const pending = new Promise<SysFacePackEntry[]>((resolve) => { release = resolve; });
|
||||
const store = new SysFaceStore({
|
||||
storage,
|
||||
now: () => 456,
|
||||
fetchCatalog: async () => {
|
||||
fetches += 1;
|
||||
return pending;
|
||||
},
|
||||
});
|
||||
|
||||
const first = store.refresh(sender);
|
||||
const second = store.refresh(sender);
|
||||
release(CATALOG);
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(fetches).toBe(1);
|
||||
expect(storage.saved).toEqual([{
|
||||
schemaVersion: 1,
|
||||
fetchedAt: 456,
|
||||
packs: CATALOG,
|
||||
}]);
|
||||
});
|
||||
|
||||
it('refreshes a cache miss once, then keeps an authoritative not-found result', async () => {
|
||||
const storage = new MemoryCatalogStorage({
|
||||
schemaVersion: 1,
|
||||
fetchedAt: 123,
|
||||
packs: CATALOG.slice(0, 1),
|
||||
});
|
||||
let fetches = 0;
|
||||
const store = new SysFaceStore({
|
||||
storage,
|
||||
fetchCatalog: async () => {
|
||||
fetches += 1;
|
||||
return CATALOG;
|
||||
},
|
||||
});
|
||||
|
||||
expect((await store.resolve(sender, 392))?.qSid).toBe('392');
|
||||
expect(await store.resolve(sender, 99999)).toBeNull();
|
||||
expect(await store.resolve(sender, 99999)).toBeNull();
|
||||
expect(fetches).toBe(1);
|
||||
});
|
||||
|
||||
it('prewarms from login only once per process while sharing the result across accounts', async () => {
|
||||
let fetches = 0;
|
||||
const store = new SysFaceStore({
|
||||
storage: new MemoryCatalogStorage(),
|
||||
fetchCatalog: async () => {
|
||||
fetches += 1;
|
||||
return CATALOG;
|
||||
},
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
store.prewarm({} as never),
|
||||
store.prewarm({} as never),
|
||||
store.prewarm({} as never),
|
||||
]);
|
||||
await store.prewarm({} as never);
|
||||
|
||||
expect(fetches).toBe(1);
|
||||
});
|
||||
|
||||
it('waits for an in-flight login refresh before resolving a cached face', async () => {
|
||||
const staleCatalog: SysFacePackEntry[] = [{
|
||||
packName: '旧目录',
|
||||
emojis: [entry('392', 1, 1, 52)],
|
||||
}];
|
||||
let release!: (packs: SysFacePackEntry[]) => void;
|
||||
let markFetchStarted!: () => void;
|
||||
const fetchStarted = new Promise<void>((resolve) => { markFetchStarted = resolve; });
|
||||
const pending = new Promise<SysFacePackEntry[]>((resolve) => { release = resolve; });
|
||||
const store = new SysFaceStore({
|
||||
storage: new MemoryCatalogStorage({
|
||||
schemaVersion: 1,
|
||||
fetchedAt: 123,
|
||||
packs: staleCatalog,
|
||||
}),
|
||||
fetchCatalog: async () => {
|
||||
markFetchStarted();
|
||||
return pending;
|
||||
},
|
||||
});
|
||||
|
||||
const prewarm = store.prewarm(sender);
|
||||
await fetchStarted;
|
||||
const resolved = store.resolveWire(sender, 392);
|
||||
let settled = false;
|
||||
void resolved.finally(() => { settled = true; });
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
|
||||
release(CATALOG);
|
||||
await expect(resolved).resolves.toMatchObject({ kind: 'super' });
|
||||
await prewarm;
|
||||
});
|
||||
});
|
||||
|
||||
describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () => {
|
||||
const ctx = { bridge: {} as never };
|
||||
|
||||
it('awaits an authoritative refresh when the first send misses the persisted catalog', async () => {
|
||||
sysFaceStore.load(CATALOG.slice(0, 1));
|
||||
let requests = 0;
|
||||
const responseData = protobuf_encode<OidbBase<OidbFetchSysFacesResp>>({
|
||||
body: {
|
||||
commonFace: {
|
||||
emojiList: [{
|
||||
emojiPackName: '经典',
|
||||
emojiDetail: [{ qSid: '14', qDes: '/微笑' }],
|
||||
}],
|
||||
},
|
||||
specialBigFace: {
|
||||
emojiList: [{
|
||||
emojiPackName: '超级表情',
|
||||
emojiDetail: [{
|
||||
qSid: '392', qDes: '/龙年快乐',
|
||||
aniStickerType: 3, aniStickerPackId: 2, aniStickerId: 38,
|
||||
}],
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
const liveCtx = {
|
||||
bridge: {
|
||||
sendRawPacket: async () => {
|
||||
requests += 1;
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
responseData,
|
||||
};
|
||||
},
|
||||
} as never,
|
||||
};
|
||||
|
||||
const [elem] = await buildSendElems([{ type: 'face', faceId: 392 }], liveCtx);
|
||||
|
||||
expect(requests).toBe(1);
|
||||
expect(elem.commonElem?.serviceType).toBe(37);
|
||||
});
|
||||
|
||||
it('encodes each face id by its catalog classification', async () => {
|
||||
sysFaceStore.load(CATALOG); // warm → ensureWarm no-ops, classify uses the catalog
|
||||
|
||||
@@ -101,4 +317,11 @@ describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () =>
|
||||
const [classicElem] = await buildSendElems([{ type: 'face', faceId: 14 }], ctx);
|
||||
expect(classicElem.face?.index).toBe(14);
|
||||
});
|
||||
|
||||
it('rejects an unknown id even when building without a live send context', async () => {
|
||||
sysFaceStore.load(CATALOG);
|
||||
|
||||
await expect(buildSendElems([{ type: 'face', faceId: 99999 }]))
|
||||
.rejects.toThrow(/absent from the current catalog/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { uploadImageToGroupAlbum } from '../../src/web/group-album';
|
||||
import { RequestUtil } from '../../src/web/request-util';
|
||||
|
||||
describe('group album image upload', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('rejects an MP4 before starting a remote upload', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockRejectedValue(new Error('unexpected remote upload'));
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
await expect(uploadImageToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
'base64://AAAAGGZ0eXBtcDQyAAAAAG1wNDJpc29t',
|
||||
'10000',
|
||||
)).rejects.toThrow('群相册上传仅支持 JPEG、PNG、GIF、WebP 或 BMP 图片');
|
||||
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -45,10 +45,26 @@ describe('group essence pagination', () => {
|
||||
.rejects.toThrow(/retcode 100.*permission denied/);
|
||||
});
|
||||
|
||||
it('rejects a success response without a message list', async () => {
|
||||
it.each([
|
||||
['an omitted list', { is_end: true }],
|
||||
['a null list', { is_end: true, msg_list: null }],
|
||||
])('normalizes an ended success response with %s to an empty page', async (_case, data) => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data,
|
||||
} as never);
|
||||
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789')).resolves.toEqual([{
|
||||
retcode: 0,
|
||||
data: { is_end: true, msg_list: [] },
|
||||
}]);
|
||||
expect(request).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('rejects a missing message list before the response explicitly ends', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data: { is_end: true },
|
||||
data: { is_end: false },
|
||||
} as never);
|
||||
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789'))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proton",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -409,6 +409,28 @@ export abstract class SnowLumaApiClient {
|
||||
return this.call('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId, set }, options);
|
||||
}
|
||||
|
||||
fetchSysFaces(refresh = false, options?: RequestOptions) {
|
||||
return this.call('fetch_sys_faces', { refresh }, options);
|
||||
}
|
||||
|
||||
fetchFaceEntity(faceId: number, options: RequestOptions & { refresh?: boolean } = {}) {
|
||||
return this.call('fetch_face_entity', {
|
||||
face_id: faceId,
|
||||
refresh: options.refresh ?? false,
|
||||
}, options);
|
||||
}
|
||||
|
||||
searchSysFaces(query: string, options?: RequestOptions) {
|
||||
return this.call('search_sys_faces', { query }, options);
|
||||
}
|
||||
|
||||
fetchSuperFaceId(faceId: number, options: RequestOptions & { refresh?: boolean } = {}) {
|
||||
return this.call('fetch_super_face_id', {
|
||||
face_id: faceId,
|
||||
refresh: options.refresh ?? false,
|
||||
}, options);
|
||||
}
|
||||
|
||||
markAllAsRead(options?: RequestOptions) {
|
||||
return this.call('_mark_all_as_read', {}, options);
|
||||
}
|
||||
@@ -444,12 +466,18 @@ export abstract class SnowLumaApiClient {
|
||||
return this.call('get_clientkey', {}, options);
|
||||
}
|
||||
|
||||
getGroupInfoEx(groupId: number, options?: RequestOptions) {
|
||||
return this.call('get_group_info_ex', { group_id: groupId }, options);
|
||||
getGroupInfoEx(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
|
||||
return this.call('get_group_info_ex', {
|
||||
group_id: groupId,
|
||||
no_cache: options?.noCache,
|
||||
}, options);
|
||||
}
|
||||
|
||||
getGroupDetailInfo(groupId: number, options?: RequestOptions) {
|
||||
return this.call('get_group_detail_info', { group_id: groupId }, options);
|
||||
getGroupDetailInfo(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
|
||||
return this.call('get_group_detail_info', {
|
||||
group_id: groupId,
|
||||
no_cache: options?.noCache,
|
||||
}, options);
|
||||
}
|
||||
|
||||
/** Calls any registered SnowLuma action and returns the response data. */
|
||||
|
||||
@@ -7,6 +7,8 @@ import type {
|
||||
DomainParams,
|
||||
DownloadFileParams,
|
||||
FetchCustomFaceParams,
|
||||
FetchFaceEntityParams,
|
||||
FetchSysFacesParams,
|
||||
FetchEmojiLikeParams,
|
||||
ForwardMessageParams,
|
||||
FriendPokeParams,
|
||||
@@ -70,6 +72,7 @@ import type {
|
||||
AiVoiceParams,
|
||||
DeleteGroupFolderParams,
|
||||
SendPacketParams,
|
||||
SearchSysFacesParams,
|
||||
} from './params';
|
||||
import type {
|
||||
CapabilityInfo,
|
||||
@@ -100,6 +103,10 @@ import type {
|
||||
UserOnlineStatus,
|
||||
SendGroupAiRecordResult,
|
||||
CollectionListInfo,
|
||||
SuperFaceInfo,
|
||||
SystemFaceCatalogInfo,
|
||||
SystemFaceInfo,
|
||||
SystemFaceSearchInfo,
|
||||
} from './results';
|
||||
|
||||
export type ActionData = JsonValue;
|
||||
@@ -200,6 +207,10 @@ export interface SnowLumaActionMap {
|
||||
get_recent_contact: { params: JsonObject; data: JsonArray };
|
||||
get_profile_like: { params: JsonObject; data: JsonObject };
|
||||
fetch_custom_face: { params: FetchCustomFaceParams; data: string[] };
|
||||
fetch_sys_faces: { params: FetchSysFacesParams; data: SystemFaceCatalogInfo };
|
||||
fetch_face_entity: { params: FetchFaceEntityParams; data: SystemFaceInfo | null };
|
||||
search_sys_faces: { params: SearchSysFacesParams; data: SystemFaceSearchInfo };
|
||||
fetch_super_face_id: { params: FetchFaceEntityParams; data: SuperFaceInfo };
|
||||
get_emoji_likes: { params: GetEmojiLikesParams; data: JsonObject };
|
||||
fetch_emoji_like: { params: FetchEmojiLikeParams; data: JsonObject };
|
||||
get_friends_with_category: { params: JsonObject; data: FriendCategoryResult[] };
|
||||
@@ -221,8 +232,8 @@ export interface SnowLumaActionMap {
|
||||
click_inline_keyboard_button: { params: JsonObject; data: JsonValue };
|
||||
set_group_sign: { params: JsonObject; data: EmptyData };
|
||||
send_group_sign: { params: JsonObject; data: EmptyData };
|
||||
get_group_info_ex: { params: GroupIdParams; data: JsonObject };
|
||||
get_group_detail_info: { params: GroupIdParams; data: JsonObject };
|
||||
get_group_info_ex: { params: GetGroupInfoParams; data: JsonObject };
|
||||
get_group_detail_info: { params: GetGroupInfoParams; data: JsonObject };
|
||||
trans_group_file: { params: JsonObject; data: JsonValue };
|
||||
rename_group_file: { params: JsonObject; data: JsonValue };
|
||||
get_file: { params: GetMediaParams; data: JsonValue };
|
||||
|
||||
@@ -302,6 +302,18 @@ export interface FetchCustomFaceParams extends JsonObject {
|
||||
count?: number;
|
||||
}
|
||||
|
||||
export interface FetchSysFacesParams extends JsonObject {
|
||||
refresh?: boolean;
|
||||
}
|
||||
|
||||
export interface FetchFaceEntityParams extends FetchSysFacesParams {
|
||||
face_id: number;
|
||||
}
|
||||
|
||||
export interface SearchSysFacesParams extends JsonObject {
|
||||
query: string;
|
||||
}
|
||||
|
||||
export interface GetCollectionListParams extends JsonObject {
|
||||
/** Collection category ID; 0 returns every category. */
|
||||
category?: number;
|
||||
|
||||
@@ -175,6 +175,38 @@ export interface CollectionListInfo extends JsonObject {
|
||||
collectionSearchList: CollectionSearchListInfo;
|
||||
}
|
||||
|
||||
export interface SystemFaceInfo extends JsonObject {
|
||||
q_sid: string;
|
||||
q_des: string;
|
||||
em_code: string;
|
||||
q_cid: number | null;
|
||||
ani_sticker_type: number | null;
|
||||
ani_sticker_pack_id: number | null;
|
||||
ani_sticker_id: number | null;
|
||||
url: string | null;
|
||||
emoji_name_alias: string[];
|
||||
ani_sticker_width: number | null;
|
||||
ani_sticker_height: number | null;
|
||||
is_super: boolean;
|
||||
}
|
||||
|
||||
export interface SystemFacePackInfo extends JsonObject {
|
||||
pack_name: string;
|
||||
emojis: SystemFaceInfo[];
|
||||
}
|
||||
|
||||
export interface SystemFaceCatalogInfo extends JsonObject {
|
||||
packs: SystemFacePackInfo[];
|
||||
}
|
||||
|
||||
export interface SystemFaceSearchInfo extends JsonObject {
|
||||
faces: SystemFaceInfo[];
|
||||
}
|
||||
|
||||
export interface SuperFaceInfo extends JsonObject {
|
||||
is_super: boolean;
|
||||
}
|
||||
|
||||
export interface UrlSafetyInfo {
|
||||
level: number;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,44 @@ import {
|
||||
} from '../src';
|
||||
|
||||
describe('SnowLumaHttpClient', () => {
|
||||
it('maps extended group-info refresh options to OneBot field names', async () => {
|
||||
const fetchImpl = vi.fn().mockImplementation(async () => new Response(JSON.stringify({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: null,
|
||||
})));
|
||||
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
|
||||
|
||||
await client.getGroupInfoEx(123456, { noCache: true });
|
||||
await client.getGroupDetailInfo(123456, { noCache: true });
|
||||
|
||||
expect(fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string))).toEqual([
|
||||
{ action: 'get_group_info_ex', params: { group_id: 123456, no_cache: true } },
|
||||
{ action: 'get_group_detail_info', params: { group_id: 123456, no_cache: true } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('maps system-face catalog helpers to their OneBot actions', async () => {
|
||||
const fetchImpl = vi.fn().mockImplementation(async () => new Response(JSON.stringify({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: null,
|
||||
})));
|
||||
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
|
||||
|
||||
await client.fetchSysFaces(true);
|
||||
await client.fetchFaceEntity(392, { refresh: true });
|
||||
await client.searchSysFaces('dragon');
|
||||
await client.fetchSuperFaceId(392);
|
||||
|
||||
expect(fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string))).toEqual([
|
||||
{ action: 'fetch_sys_faces', params: { refresh: true } },
|
||||
{ action: 'fetch_face_entity', params: { face_id: 392, refresh: true } },
|
||||
{ action: 'search_sys_faces', params: { query: 'dragon' } },
|
||||
{ action: 'fetch_super_face_id', params: { face_id: 392, refresh: false } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('maps group-announcement options to their OneBot field names', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({
|
||||
status: 'ok',
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = path.resolve(process.argv[2] ?? 'dist');
|
||||
const entryPoint = path.join(root, 'index.mjs');
|
||||
|
||||
if (!fs.statSync(root, { throwIfNoEntry: false })?.isDirectory()) {
|
||||
throw new Error(`release directory does not exist: ${root}`);
|
||||
}
|
||||
if (!fs.statSync(entryPoint, { throwIfNoEntry: false })?.isFile()) {
|
||||
throw new Error(`release entry point must be at the archive root: ${entryPoint}`);
|
||||
}
|
||||
|
||||
const forbidden = [];
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
const directory = pending.pop();
|
||||
if (!directory) continue;
|
||||
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const absolute = path.join(directory, entry.name);
|
||||
if (/snowluma/i.test(entry.name)) {
|
||||
forbidden.push(path.relative(root, absolute));
|
||||
}
|
||||
pending.push(absolute);
|
||||
}
|
||||
}
|
||||
|
||||
if (forbidden.length > 0) {
|
||||
throw new Error(`release contains forbidden directory names:\n${forbidden.join('\n')}`);
|
||||
}
|
||||
|
||||
console.log(`Release layout verified: ${root}`);
|
||||
Reference in new issue
Block a user