refactor(onebot): extract OneBot protocol translation into @snowluma/onebot
Phase 3 of the 4-package split (RoadMap #3). Moves the entire `packages/core/src/onebot/` subtree (43 source files + 20 test files spanning network adapters, action handlers, event converters, message parser, message store, media store, instance + manager) into the new `@snowluma/onebot` workspace package. The remaining `@snowluma/core` now hosts only the api-layer (Bridge class + 13 Api classes), the hook tooling, the WebUI server, and the runnable `index.ts`. Why --- - The OneBot adapter is the public-facing OneBot11 protocol surface; it has its own version cadence and its own consumers (third-party bots talking OneBot WS / HTTP). Splitting it lets that cadence move independently of the Api-on-ctx layer. - The two were sharing the `packages/core/` build pipeline only because they happened to live in the same directory. Nothing in the api-layer reaches into OneBot internals. - Mirrors NapCat / Lagrange.OneBot's repo split (their OneBot adapter is a separate assembly from the Core protocol library). Layout ------ Moved via `git mv` (history preserved): packages/core/src/onebot/* → @snowluma/onebot/src/<x> packages/core/tests/onebot/* (6 files) → @snowluma/onebot/tests/ packages/core/tests/{message-parser,message-store,event-pipeline, media-store,media-url-resolver,event-converter, http-server-hot-reload,http-server-content-type, api-handler-logging,message-id,group-msg-emoji-like, config,media-indexer,network-manager}.test.ts (14 files) → @snowluma/onebot/tests/ What stays in @snowluma/core ---------------------------- - `bridge/{bridge,bridge-interface,bridge-context,manager}.ts` - `bridge/apis/*` (the 13 typed Api classes) - `hook/*` (debugger/injector — tooling for the core protocol layer) - `webui/*` (admin UI server — application wiring, not the OneBot adapter itself) - `index.ts` (application entry that wires BridgeManager + OneBotManager + HookManager + WebUI together) Changes ------- - New package `packages/onebot/` (package.json with subpath exports mirroring legacy `core/src/onebot/<x>` 1:1, tsconfig.json, vitest.config.ts with `SNOWLUMA_LOG_LEVEL=debug` env so the action- dispatch logging tests see debug-level subscribers — copied verbatim from core's vitest.config.ts). - @snowluma/core grows new subpath exports for the api-layer files OneBot's type-only imports need: `./bridge`, `./bridge-interface`, `./bridge-context`, `./manager`, `./apis`. - `@snowluma/onebot` depends on `@snowluma/bridge`, `@snowluma/common`, `@snowluma/core`, `@snowluma/proto-defs`, `@snowluma/proton`, `@snowluma/websocket`. - `@snowluma/core` depends on `@snowluma/onebot` (for index.ts + webui/server.ts wiring). - 100+ import sites rewritten via sed: * OneBot → core: `'../bridge/bridge'` → `'@snowluma/core/bridge'`, `'../bridge/manager'` → `'@snowluma/core/manager'`, `'../bridge/bridge-interface'` → `'@snowluma/core/bridge-interface'`, `'@/bridge/bridge'` (vite path alias) → `'@snowluma/core/bridge'`. * Core → OneBot: `'./onebot/manager'` → `'@snowluma/onebot/manager'`, `'../onebot/config'` → `'@snowluma/onebot/config'`, etc. * Test relative paths: `'../../src/onebot/<x>'` → `'../src/<x>'` after the test file move (one level shallower). - New `packages/onebot/src/env.d.ts` declaring `__APP_VERSION__` and `__BUILD_WEBUI__` (the vite-injected globals `info.ts` reads). Workspace cycle --------------- core ↔ onebot is allowed by pnpm workspaces. The runtime direction is one-way: core → onebot (index.ts constructs OneBotManager, webui/server reads OneBot config). OneBot only reaches into core for TYPES (Bridge, BridgeInterface, BridgeManager, ClientKeyInfo, DownloadRKeyInfo); those imports use `import type` so they compile out at runtime and don't introduce a real cycle. Verification ------------ - Full workspace `pnpm -r typecheck`: all 11 projects clean. - `@snowluma/core` test suite: 302/302 pass (33 test files). - `@snowluma/onebot` test suite: 250/250 pass (20 test files; pre-existing `network-manager.test.ts` native-addon failure unchanged — same baseline as before the split). - Combined: 552/552 — identical pass count to the pre-Phase-3 baseline. - Vite build with stubbed native binary: clean, 2.84 MB bundle / 224 KB gzip (identical envelope).
This commit is contained in:
71 files changed
+286
-59
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_friend_list', async () => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_stranger_info', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (ctx.getStrangerInfo) {
|
||||
const info = await ctx.getStrangerInfo(userId);
|
||||
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
}
|
||||
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('delete_friend', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const block = asBoolean(params.block, false);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
await ctx.handleDeleteFriend(userId, block);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_group_kick', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.setGroupKick(groupId, userId, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_kick_members', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
|
||||
await ctx.setGroupKickMembers(groupId, userIds, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const duration = asNumber(params.duration) || 1800;
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.setGroupBan(groupId, userId, duration);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_whole_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.setGroupWholeBan(groupId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_option', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const addType = asNumber(params.add_type);
|
||||
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
|
||||
await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_search', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.setSearch(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_admin', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_card', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const card = asString(params.card);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_name', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.group_name);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.setName(groupId, name);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_leave', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.setGroupLeave(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_special_title', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const title = asString(params.special_title);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous_ban', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// Highway upload with cmdId 3000 + GroupAvatarExtra (Lagrange protocol).
|
||||
// `file` accepts everything bridge.setGroupAvatar's underlying
|
||||
// loadBinarySource handles: local paths, file:// URLs, http(s) URLs,
|
||||
// and base64:// data URIs — same surface as set_qq_avatar.
|
||||
h.registerAction('set_group_portrait', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const file = asString(params.file);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
try {
|
||||
await ctx.bridge.apis.profile.setGroupAvatar(groupId, file);
|
||||
return okResponse();
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_album_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
|
||||
try {
|
||||
const albumList = await ctx.getGroupAlbumList(groupId);
|
||||
return okResponse(albumList);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('upload_image_to_qun_album', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const albumName = asString(params.album_name);
|
||||
const file = asString(params.file);
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
|
||||
try {
|
||||
await ctx.uploadImageToGroupAlbum(groupId, albumId, albumName, file);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_album_media_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const attachInfo = asString(params.attach_info) || '';
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
|
||||
try {
|
||||
const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId, attachInfo);
|
||||
return okResponse(mediaList);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album media list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('do_group_album_comment', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const lloc = asString(params.lloc);
|
||||
const content = asString(params.content);
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
|
||||
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
|
||||
|
||||
try {
|
||||
const comment = await ctx.commentGroupAlbumMedia(groupId, albumId, lloc, content);
|
||||
return okResponse(comment);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to comment on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('set_group_album_media_like', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const batchId = asString(params.batch_id);
|
||||
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
|
||||
|
||||
if (!groupId || !albumId || !batchId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, true);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to set like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
// 取消点赞群相册媒体
|
||||
h.registerAction('cancel_group_album_media_like', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const batchId = asString(params.batch_id);
|
||||
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
|
||||
|
||||
if (!groupId || !albumId || !batchId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, false);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('del_group_album_media', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const lloc = asString(params.lloc);
|
||||
|
||||
if (!groupId || !albumId || !lloc) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await ctx.deleteGroupAlbumMedia(groupId, albumId, lloc);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to delete album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asBoolean, asNumber, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse } from '../types';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('upload_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
|
||||
const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile);
|
||||
return okResponse({ file_id: fileId });
|
||||
});
|
||||
|
||||
h.registerAction('upload_private_file', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
|
||||
const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile);
|
||||
return okResponse({ file_id: fileId });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_file_url', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const busId = asNumber(params.busid) || 102;
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_root_files', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
return okResponse(await ctx.getGroupFiles(groupId, '/'));
|
||||
});
|
||||
|
||||
h.registerAction('get_group_files_by_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
return okResponse(await ctx.getGroupFiles(groupId, folderId));
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.delete(groupId, fileId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('move_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const parentDirectory = asString(params.parent_directory);
|
||||
const targetDirectory = asString(params.target_directory);
|
||||
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('create_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.name);
|
||||
const parentId = asString(params.parent_id) || '/';
|
||||
if (!groupId || !name) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
|
||||
}
|
||||
await ctx.createGroupFileFolder(groupId, name, parentId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
if (!groupId || !folderId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('rename_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
const newName = asString(params.new_folder_name) || asString(params.name);
|
||||
if (!groupId || !folderId || !newName) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_private_file_url', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const fileHash = asString(params.file_hash);
|
||||
if (!userId || !fileId || !fileHash) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
|
||||
}
|
||||
return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { WebHonorType } from '@snowluma/bridge/web/group-honor';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_list', async (params) => {
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupList) {
|
||||
return okResponse(await ctx.getGroupList(noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_group_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupInfo) {
|
||||
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
}
|
||||
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_member_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberList) {
|
||||
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_group_member_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberInfo) {
|
||||
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
|
||||
return okResponse(info ?? {
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('get_group_honor_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const typeStr = asString(params.type) || 'all';
|
||||
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
|
||||
|
||||
const typeValues = Object.values(WebHonorType) as string[];
|
||||
if (!typeValues.includes(typeStr)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
|
||||
return okResponse(honorInfo);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_system_msg', async () => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_login_info', async () => {
|
||||
const login = ctx.getLoginInfo();
|
||||
return okResponse({ user_id: login.userId, nickname: login.nickname });
|
||||
});
|
||||
|
||||
h.registerAction('get_status', async () => {
|
||||
const online = ctx.isOnline();
|
||||
return okResponse({ online, good: online });
|
||||
});
|
||||
|
||||
// __APP_VERSION__ is injected by Vite from the monorepo root package.json;
|
||||
// it's undefined under vitest (no define plugin), so fall back to 'dev'.
|
||||
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
|
||||
h.registerAction('get_version_info', async () => {
|
||||
return okResponse({
|
||||
app_name: 'SnowLuma',
|
||||
app_version: `${appVersion}-node`,
|
||||
protocol_version: 'v11',
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('can_send_image', async () => {
|
||||
return okResponse({ yes: ctx.canSendImage?.() ?? false });
|
||||
});
|
||||
|
||||
h.registerAction('can_send_record', async () => {
|
||||
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('send_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
if (messageType === 'group' || params.group_id !== undefined) {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('send_private_msg', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('send_group_msg', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('get_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
|
||||
const data = ctx.getMessage(messageId);
|
||||
if (!data) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
}
|
||||
|
||||
const result: JsonObject = { ...data };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? messageId) as JsonValue;
|
||||
return okResponse(result);
|
||||
});
|
||||
|
||||
h.registerAction('delete_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||
}
|
||||
|
||||
await ctx.deleteMessage(messageId, meta);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_friend_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const approve = asBoolean(params.approve, true);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
await ctx.handleFriendRequest(flag, approve);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const subType = asString(params.sub_type, asString(params.type, 'add'));
|
||||
const approve = asBoolean(params.approve, true);
|
||||
const reason = asString(params.reason);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
await ctx.handleGroupRequest(flag, subType, approve, reason);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { summarizeParams } from '@snowluma/common/log-summary';
|
||||
|
||||
const moduleLog = createLogger('Bridge.Action');
|
||||
|
||||
import { register as registerInfo } from './actions/info';
|
||||
import { register as registerMessage } from './actions/message';
|
||||
import { register as registerFriend } from './actions/friend';
|
||||
import { register as registerGroupInfo } from './actions/group-info';
|
||||
import { register as registerGroupAdmin } from './actions/group-admin';
|
||||
import { register as registerGroupFile } from './actions/group-file';
|
||||
import { register as registerRequest } from './actions/request';
|
||||
import { register as registerExtended } from './actions/extended';
|
||||
import { register as registerGroupAlbum } from './actions/group-album';
|
||||
|
||||
import { WebHonorType } from '@snowluma/bridge/web/group-honor';
|
||||
import type { ClientKeyInfo } from '@snowluma/core/bridge';
|
||||
|
||||
export interface MessageSendResult {
|
||||
messageId: number;
|
||||
meta?: MessageMeta;
|
||||
echoEvent?: JsonObject;
|
||||
}
|
||||
|
||||
export interface GroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
data: {
|
||||
is_end: boolean;
|
||||
msg_list: any[];
|
||||
[key: string]: any;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface ApiActionContext {
|
||||
/**
|
||||
* Direct access to the BridgeInterface. Use for actions that are pure
|
||||
* 1:1 calls to a Bridge method — no rename, no default args, no
|
||||
* composition with messageStore / mediaStore. When translation IS
|
||||
* needed, route through the named adapters declared below instead.
|
||||
*/
|
||||
bridge: BridgeInterface;
|
||||
|
||||
getLoginInfo: () => { userId: number; nickname: string };
|
||||
isOnline: () => boolean;
|
||||
getMessage: (messageId: number) => JsonObject | null;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
|
||||
canSendImage: () => boolean;
|
||||
canSendRecord: () => boolean;
|
||||
// Info retrieval (async — triggers OIDB fetch)
|
||||
getFriendList: () => Promise<JsonObject[]>;
|
||||
getGroupList: (noCache?: boolean) => Promise<JsonObject[]>;
|
||||
getGroupInfo: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
|
||||
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
|
||||
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
|
||||
getStrangerInfo: (userId: number) => Promise<JsonObject | null>;
|
||||
// Group admin (adapters: rename Bridge methods to OneBot vocabulary)
|
||||
setGroupKick: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
|
||||
setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
|
||||
setGroupBan: (groupId: number, userId: number, duration: number) => Promise<void>;
|
||||
setGroupWholeBan: (groupId: number, enable: boolean) => Promise<void>;
|
||||
setGroupLeave: (groupId: number) => Promise<void>;
|
||||
// Group file (adapters: field extraction + Bridge name translation)
|
||||
uploadGroupFile: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
|
||||
uploadPrivateFile: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
|
||||
getGroupFileUrl: (groupId: number, fileId: string, busId?: number) => Promise<string>;
|
||||
getGroupFiles: (groupId: number, folderId?: string) => Promise<JsonObject>;
|
||||
createGroupFileFolder: (groupId: number, name: string, parentId?: string) => Promise<void>;
|
||||
getPrivateFileUrl: (userId: number, fileId: string, fileHash: string) => Promise<string>;
|
||||
getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
|
||||
// Requests (adapters: rename to OneBot vocabulary)
|
||||
handleFriendRequest: (flag: string, approve: boolean) => Promise<void>;
|
||||
handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
|
||||
// Pokes (adapters: flatten isGroup into bridge.sendPoke signature)
|
||||
sendFriendPoke: (userId: number, targetId?: number) => Promise<void>;
|
||||
sendGroupPoke: (groupId: number, userId: number) => Promise<void>;
|
||||
// Essence (adapter: bakes the set/unset boolean)
|
||||
setEssenceMsg: (messageId: number) => Promise<void>;
|
||||
deleteEssenceMsg: (messageId: number) => Promise<void>;
|
||||
// Profile reads with OneBot-specific default args
|
||||
getProfileLike: (userId?: number, start?: number, limit?: number) => Promise<any>;
|
||||
getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
|
||||
// Friend deletion (adapter: rename + force-boolean)
|
||||
handleDeleteFriend: (userId: number, block?: boolean) => Promise<void>;
|
||||
// Module wrappers / multi-dep compositions
|
||||
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
|
||||
getDownloadRKeys: () => Promise<JsonObject[]>;
|
||||
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
|
||||
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
|
||||
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
|
||||
// Extended NapCat-compatible
|
||||
setFriendRemark: (userId: number, remark: string) => Promise<void>;
|
||||
setGroupRemark: (groupId: number, remark: string) => Promise<void>;
|
||||
setGroupAvatar: (groupId: number, source: string) => Promise<void>;
|
||||
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
|
||||
markGroupMsgAsRead: (groupId: number, sequence: number) => Promise<void>;
|
||||
markPrivateMsgAsRead: (userId: number, sequence: number) => Promise<void>;
|
||||
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
|
||||
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
|
||||
fetchCustomFace: (count?: number) => Promise<string[]>;
|
||||
getEmojiLikes: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>;
|
||||
// Web
|
||||
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise<any>;
|
||||
getGroupEssenceAll: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
|
||||
getGroupAlbumList: (groupId: number) => Promise<any>;
|
||||
uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise<void>;
|
||||
getGroupAlbumMediaList: (groupId: number, albumId: string, attachInfo?: string) => Promise<any>;
|
||||
commentGroupAlbumMedia: (groupId: number, albumId: string, lloc: string, content: string) => Promise<any>;
|
||||
deleteGroupAlbumMedia: (groupId: number, albumId: string, lloc: string) => Promise<any>;
|
||||
likeGroupAlbumMedia: (groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean) => Promise<any>;
|
||||
sendGroupNotice: (groupId: number, content: string, options?: any) => Promise<any>;
|
||||
getGroupNotice: (groupId: number) => Promise<any[]>;
|
||||
deleteGroupNotice: (groupId: number, fid: string) => Promise<boolean>;
|
||||
getCookiesStr: (domain: string) => Promise<string>;
|
||||
getCsrfToken: () => Promise<number>;
|
||||
getCredentials: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
|
||||
forceFetchClientKey: () => Promise<ClientKeyInfo>;
|
||||
// Media lookup (populated from previously dispatched message segments)
|
||||
getImageInfo: (file: string) => Promise<JsonObject | null>;
|
||||
getRecordInfo: (file: string) => Promise<JsonObject | null>;
|
||||
}
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(context: ApiActionContext, uin?: number) {
|
||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
registerInfo(this, context);
|
||||
registerMessage(this, context);
|
||||
registerFriend(this, context);
|
||||
registerGroupInfo(this, context);
|
||||
registerGroupAdmin(this, context);
|
||||
registerGroupFile(this, context);
|
||||
registerRequest(this, context);
|
||||
registerExtended(this, context);
|
||||
registerGroupAlbum(this, context);
|
||||
}
|
||||
|
||||
registerAction(action: string, handler: ActionHandler): void {
|
||||
this.handlers.set(action, handler);
|
||||
}
|
||||
|
||||
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
|
||||
const handler = this.handlers.get(action);
|
||||
if (!handler) {
|
||||
this.log.debug('unknown action %s', action);
|
||||
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||
}
|
||||
|
||||
// Entry log goes to file always (debug); console only when level is
|
||||
// dialed down to debug. Caller-perspective summary lets the operator
|
||||
// grep "what did the bot get asked to do" without scraping wire logs.
|
||||
this.log.debug('%s params=%s', action, summarizeParams(params));
|
||||
|
||||
try {
|
||||
return await handler(params);
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
// the log file stays a useful signal of real internal faults.
|
||||
this.log.warn('%s failed: %s\n%s',
|
||||
action,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
error instanceof Error ? (error.stack ?? '') : '');
|
||||
const message = error instanceof Error ? error.message : 'internal error';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
}
|
||||
|
||||
async processRequest(rawRequest: string): Promise<string> {
|
||||
if (!rawRequest.trim()) {
|
||||
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawRequest) as unknown;
|
||||
if (!isJsonObject(parsed)) {
|
||||
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||
}
|
||||
|
||||
const action = asString(parsed.action);
|
||||
if (!action) {
|
||||
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||
}
|
||||
|
||||
const params = isJsonObject(parsed.params) ? parsed.params : {};
|
||||
const echo = parsed.echo;
|
||||
const response = await this.handle(action, params);
|
||||
if (echo !== undefined) {
|
||||
response.echo = toJsonValue(echo);
|
||||
}
|
||||
|
||||
return JSON.stringify(response);
|
||||
} catch {
|
||||
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isJsonObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function asString(value: unknown, fallback = ''): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function asNumber(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) return Math.trunc(n);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function asBoolean(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'string') {
|
||||
const text = value.trim().toLowerCase();
|
||||
if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true;
|
||||
if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function toJsonValue(value: unknown): JsonValue {
|
||||
if (value === null) return null;
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
|
||||
if (Array.isArray(value)) return value.map(toJsonValue);
|
||||
if (isJsonObject(value)) {
|
||||
const obj: JsonObject = {};
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
obj[key] = toJsonValue(item);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export function asMessage(value: unknown): import('./types').JsonValue | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (Array.isArray(parsed)) {
|
||||
return toJsonValue(parsed);
|
||||
}
|
||||
} catch {
|
||||
// Fallback to literal text if it just looks like an array but is invalid JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
return toJsonValue(value);
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
HttpClientNetwork,
|
||||
HttpServerNetwork,
|
||||
JsonObject,
|
||||
MessageFormat,
|
||||
OneBotConfig,
|
||||
OneBotNetworks,
|
||||
WsClientNetwork,
|
||||
WsRole,
|
||||
WsServerNetwork,
|
||||
} from './types';
|
||||
|
||||
const log = createLogger('OneBot.Config');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||
|
||||
export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
return {
|
||||
networks: {
|
||||
httpServers: [{
|
||||
name: 'http-default',
|
||||
host: '0.0.0.0',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
accessToken: generateAccessToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}],
|
||||
httpClients: [],
|
||||
wsServers: [{
|
||||
name: 'ws-default',
|
||||
host: '0.0.0.0',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
role: 'Universal',
|
||||
accessToken: generateAccessToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}],
|
||||
wsClients: [],
|
||||
},
|
||||
musicSignUrl: '',
|
||||
};
|
||||
}
|
||||
|
||||
function generateAccessToken(): string {
|
||||
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
|
||||
}
|
||||
|
||||
export interface LoadOneBotConfigOptions {
|
||||
/**
|
||||
* Persist the normalized config to disk when the file is missing or was
|
||||
* in legacy format. Default `false` so accidental call sites (read-only
|
||||
* GETs in particular) don't generate fresh access tokens, race on
|
||||
* concurrent writes, or surprise the operator with materialized files.
|
||||
* Pass `true` from boot / explicit POST handlers.
|
||||
*/
|
||||
persistDefaults?: boolean;
|
||||
}
|
||||
|
||||
export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig {
|
||||
ensureConfigDir();
|
||||
|
||||
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||
const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH);
|
||||
const perUinRaw = tryLoadJson(perUinPath);
|
||||
|
||||
// Detect legacy on-disk format (top-level per-type arrays). We auto-migrate
|
||||
// these entries into `networks.*` and rewrite the file on the next save.
|
||||
const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw);
|
||||
|
||||
const sources: JsonObject[] = [];
|
||||
if (globalRaw) sources.push(globalRaw);
|
||||
if (perUinRaw) sources.push(perUinRaw);
|
||||
|
||||
const config = fromJson(sources, !perUinRaw && !globalRaw);
|
||||
|
||||
if (options.persistDefaults && (!perUinRaw || legacy)) {
|
||||
saveOneBotConfig(uin, config);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
|
||||
ensureConfigDir();
|
||||
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||
saveJson(perUinPath, toJsonObject(config));
|
||||
}
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function toJsonObject(config: OneBotConfig): JsonObject {
|
||||
const nets = config.networks;
|
||||
return {
|
||||
networks: {
|
||||
httpServers: nets.httpServers.map(httpServerToJson),
|
||||
httpClients: nets.httpClients.map(httpClientToJson),
|
||||
wsServers: nets.wsServers.map(wsServerToJson),
|
||||
wsClients: nets.wsClients.map(wsClientToJson),
|
||||
},
|
||||
musicSignUrl: config.musicSignUrl ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
function applyBase(
|
||||
out: JsonObject,
|
||||
n: { name: string; enabled?: boolean; accessToken?: string; messageFormat: MessageFormat; reportSelfMessage: boolean },
|
||||
): void {
|
||||
out.name = n.name;
|
||||
if (n.enabled === false) out.enabled = false;
|
||||
if (n.accessToken) out.accessToken = n.accessToken;
|
||||
out.messageFormat = n.messageFormat;
|
||||
out.reportSelfMessage = n.reportSelfMessage;
|
||||
}
|
||||
|
||||
function httpServerToJson(n: HttpServerNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.host = n.host ?? '0.0.0.0';
|
||||
out.port = n.port;
|
||||
out.path = n.path ?? '/';
|
||||
return out;
|
||||
}
|
||||
|
||||
function httpClientToJson(n: HttpClientNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.url = n.url;
|
||||
if (typeof n.timeoutMs === 'number' && n.timeoutMs > 0) out.timeoutMs = n.timeoutMs;
|
||||
return out;
|
||||
}
|
||||
|
||||
function wsServerToJson(n: WsServerNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.host = n.host ?? '0.0.0.0';
|
||||
out.port = n.port;
|
||||
out.path = n.path ?? '/';
|
||||
out.role = n.role ?? 'Universal';
|
||||
return out;
|
||||
}
|
||||
|
||||
function wsClientToJson(n: WsClientNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.url = n.url;
|
||||
out.role = n.role ?? 'Universal';
|
||||
out.reconnectIntervalMs =
|
||||
typeof n.reconnectIntervalMs === 'number' && Number.isFinite(n.reconnectIntervalMs)
|
||||
? Math.max(1000, Math.trunc(n.reconnectIntervalMs))
|
||||
: 5000;
|
||||
return out;
|
||||
}
|
||||
|
||||
function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
|
||||
// Legacy top-level scalars are pulled DOWN into each adapter on the first
|
||||
// load: the on-disk schema has no globals anymore, every adapter is
|
||||
// self-describing. We compute the legacy fallbacks here so that adapters
|
||||
// missing `messageFormat`/`reportSelfMessage` inherit them once and the
|
||||
// file is rewritten in normalized form.
|
||||
let legacyFormat: MessageFormat | undefined;
|
||||
let legacyReport: boolean | undefined;
|
||||
let musicSignUrl = '';
|
||||
for (const src of sources) {
|
||||
const mf = parseMessageFormat(src.messageFormat);
|
||||
if (mf) legacyFormat = mf;
|
||||
if (typeof src.reportSelfMessage === 'boolean') legacyReport = src.reportSelfMessage;
|
||||
if (typeof src.musicSignUrl === 'string') musicSignUrl = src.musicSignUrl;
|
||||
}
|
||||
const inheritedFormat: MessageFormat = legacyFormat ?? 'array';
|
||||
const inheritedReport: boolean = legacyReport ?? false;
|
||||
|
||||
// Pluck per-type arrays from each source: prefer `networks.<kind>` over
|
||||
// legacy top-level arrays, but accept both. Later sources override earlier
|
||||
// ones at the network level (last write wins per `(kind, name)` pair).
|
||||
const adapterDefaults = { messageFormat: inheritedFormat, reportSelfMessage: inheritedReport };
|
||||
const httpServers = collectByName<HttpServerNetwork>(sources, 'httpServers', (raw) => parseHttpServer(raw, adapterDefaults));
|
||||
const httpClients = collectByName<HttpClientNetwork>(sources, 'httpClients', (raw) => parseHttpClient(raw, adapterDefaults), 'httpPostEndpoints');
|
||||
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
|
||||
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
|
||||
|
||||
// Seed defaults ONLY for a brand-new install (no source files at all).
|
||||
// If the operator deliberately emptied every adapter, respect that and
|
||||
// do NOT silently revive default 0.0.0.0 listeners.
|
||||
if (
|
||||
freshInstall &&
|
||||
httpServers.length === 0 &&
|
||||
httpClients.length === 0 &&
|
||||
wsServers.length === 0 &&
|
||||
wsClients.length === 0
|
||||
) {
|
||||
const defaults = makeDefaultOneBotConfig().networks;
|
||||
httpServers.push(...defaults.httpServers);
|
||||
wsServers.push(...defaults.wsServers);
|
||||
}
|
||||
|
||||
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
|
||||
return { networks, musicSignUrl };
|
||||
}
|
||||
|
||||
function collectByName<T extends { name: string }>(
|
||||
sources: JsonObject[],
|
||||
kind: keyof OneBotNetworks,
|
||||
parse: (raw: JsonObject) => T | null,
|
||||
legacyKey?: string,
|
||||
): T[] {
|
||||
const byName = new Map<string, T>();
|
||||
const order: string[] = [];
|
||||
|
||||
let counter = 0;
|
||||
const ingest = (rawArr: unknown): void => {
|
||||
if (!Array.isArray(rawArr)) return;
|
||||
for (const raw of rawArr) {
|
||||
if (!isObject(raw)) continue;
|
||||
const parsed = parse(raw);
|
||||
if (!parsed) continue;
|
||||
const name = parsed.name && parsed.name.trim() ? parsed.name.trim() : pickAutoName(kind, byName, ++counter);
|
||||
parsed.name = name;
|
||||
if (!byName.has(name)) order.push(name);
|
||||
byName.set(name, parsed);
|
||||
}
|
||||
};
|
||||
|
||||
for (const src of sources) {
|
||||
const nested = isObject(src.networks) ? (src.networks as JsonObject)[kind] : undefined;
|
||||
ingest(nested);
|
||||
if (legacyKey) ingest(src[legacyKey]);
|
||||
ingest(src[kind]);
|
||||
}
|
||||
|
||||
return order.map((n) => byName.get(n)!);
|
||||
}
|
||||
|
||||
function pickAutoName(kind: keyof OneBotNetworks, used: Map<string, unknown>, counter: number): string {
|
||||
const prefix =
|
||||
kind === 'httpServers' ? 'http' :
|
||||
kind === 'httpClients' ? 'httppost' :
|
||||
kind === 'wsServers' ? 'ws' :
|
||||
'wsclient';
|
||||
let candidate = `${prefix}-${counter}`;
|
||||
while (used.has(candidate)) {
|
||||
counter += 1;
|
||||
candidate = `${prefix}-${counter}`;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
interface AdapterDefaults {
|
||||
messageFormat: MessageFormat;
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
function parseBase(value: JsonObject, defaults: AdapterDefaults) {
|
||||
return {
|
||||
name: asString(value.name),
|
||||
enabled: typeof value.enabled === 'boolean' ? value.enabled : undefined,
|
||||
accessToken: asString(value.accessToken) || undefined,
|
||||
messageFormat: parseMessageFormat(value.messageFormat) ?? defaults.messageFormat,
|
||||
reportSelfMessage:
|
||||
typeof value.reportSelfMessage === 'boolean' ? value.reportSelfMessage : defaults.reportSelfMessage,
|
||||
};
|
||||
}
|
||||
|
||||
function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
|
||||
const port = asNumber(value.port, 0);
|
||||
if (port <= 0) return null;
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
host: asString(value.host, '0.0.0.0'),
|
||||
port,
|
||||
path: asString(value.path, '/'),
|
||||
});
|
||||
}
|
||||
|
||||
function parseHttpClient(value: JsonObject, defaults: AdapterDefaults): HttpClientNetwork | null {
|
||||
const url = asString(value.url);
|
||||
if (!url) return null;
|
||||
const timeout = asNumber(value.timeoutMs, 0);
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
url,
|
||||
timeoutMs: timeout > 0 ? timeout : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNetwork | null {
|
||||
const port = asNumber(value.port, 0);
|
||||
if (port <= 0) return null;
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
host: asString(value.host, '0.0.0.0'),
|
||||
port,
|
||||
path: asString(value.path, '/'),
|
||||
role: asRole(value.role, 'Universal'),
|
||||
});
|
||||
}
|
||||
|
||||
function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNetwork | null {
|
||||
const url = asString(value.url);
|
||||
if (!url) return null;
|
||||
const reconnectIntervalMs = asNumber(value.reconnectIntervalMs, 5000);
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
url,
|
||||
role: asRole(value.role, 'Universal'),
|
||||
reconnectIntervalMs: Math.max(1000, reconnectIntervalMs),
|
||||
});
|
||||
}
|
||||
|
||||
function hasLegacyTopLevel(raw: JsonObject): boolean {
|
||||
return (
|
||||
Array.isArray(raw.httpServers) ||
|
||||
Array.isArray(raw.httpPostEndpoints) ||
|
||||
Array.isArray(raw.wsServers) ||
|
||||
Array.isArray(raw.wsClients) ||
|
||||
typeof raw.messageFormat === 'string' ||
|
||||
typeof raw.reportSelfMessage === 'boolean'
|
||||
);
|
||||
}
|
||||
|
||||
function parseMessageFormat(value: unknown): MessageFormat | undefined {
|
||||
if (value === 'array' || value === 'string') return value;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function clean<T extends Record<string, unknown>>(obj: T): T {
|
||||
for (const key of Object.keys(obj) as (keyof T)[]) {
|
||||
if (obj[key] === undefined) delete obj[key];
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
function asRole(value: unknown, fallback: WsRole): WsRole {
|
||||
// Accept both uppercase (canonical) and lowercase (legacy on-disk) forms.
|
||||
// Lowercase values are auto-migrated to uppercase on the next save.
|
||||
const text = asString(value, fallback).toLowerCase();
|
||||
if (text === 'api') return 'Api';
|
||||
if (text === 'event') return 'Event';
|
||||
if (text === 'universal') return 'Universal';
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function asString(value: unknown, fallback = ''): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function asNumber(value: unknown, fallback = 0): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) return Math.max(0, Math.trunc(n));
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function tryLoadJson(filePath: string): JsonObject | null {
|
||||
if (!fs.existsSync(filePath)) return null;
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveJson(filePath: string, json: JsonObject): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
// Globals injected by Vite at build time (see `packages/core/vite.config.ts`).
|
||||
// `__APP_VERSION__` reads from the monorepo root `package.json::version`;
|
||||
// `__BUILD_WEBUI__` flips on when `BUILD_WEBUI=true` is set so the runner
|
||||
// stitches the SPA assets in. Both are typed as `unknown` outside vite
|
||||
// (e.g. when running tests via vitest where the plugin isn't applied) —
|
||||
// callers guard with `typeof __APP_VERSION__ !== 'undefined'`.
|
||||
declare const __BUILD_WEBUI__: boolean;
|
||||
declare const __APP_VERSION__: string;
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/bridge/events';
|
||||
import type { JsonObject } from '../types';
|
||||
import {
|
||||
convertFriendMessage,
|
||||
convertGroupMessage,
|
||||
convertTempMessage,
|
||||
} from './to-message';
|
||||
import {
|
||||
convertFriendAdd,
|
||||
convertFriendPoke,
|
||||
convertFriendRecall,
|
||||
convertGroupAdmin,
|
||||
convertGroupEssence,
|
||||
convertGroupFileUpload,
|
||||
convertGroupMemberJoin,
|
||||
convertGroupMemberLeave,
|
||||
convertGroupMsgEmojiLike,
|
||||
convertGroupMute,
|
||||
convertGroupPoke,
|
||||
convertGroupRecall,
|
||||
} from './to-notice';
|
||||
import {
|
||||
convertFriendRequest,
|
||||
convertGroupInvite,
|
||||
} from './to-request';
|
||||
import { elementsToJson } from './to-segment';
|
||||
|
||||
// ─────────────── resolver callback types ───────────────
|
||||
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
|
||||
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
|
||||
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
|
||||
/**
|
||||
* Side-channel callback invoked every time an image / record / video
|
||||
* segment is produced, so callers can keep a lookup index (e.g. for
|
||||
* `get_image` / `get_record`) without re-scanning the message store.
|
||||
*/
|
||||
export type MediaSegmentSink = (
|
||||
mediaType: 'image' | 'record' | 'video',
|
||||
element: MessageElement,
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
) => void;
|
||||
|
||||
// ─────────────── context ───────────────
|
||||
|
||||
/**
|
||||
* Everything `convertEvent` needs that isn't on the bridge event itself.
|
||||
* Built once per OneBotInstance and passed through unchanged. Resolvers
|
||||
* are nullable because tests routinely omit them; when missing, the
|
||||
* converter falls back to the bridge event's own fields (e.g. raw
|
||||
* `element.url`, raw `event.msgSeq`).
|
||||
*/
|
||||
export interface ConverterContext {
|
||||
/** Self uin parsed once into a Number for inclusion in `self_id`. */
|
||||
selfId: number;
|
||||
imageUrlResolver: ImageUrlResolver | null;
|
||||
mediaUrlResolver: MediaUrlResolver | null;
|
||||
messageIdResolver: MessageIdResolver | null;
|
||||
mediaSegmentSink: MediaSegmentSink | null;
|
||||
}
|
||||
|
||||
// ─────────────── dispatcher ───────────────
|
||||
|
||||
/**
|
||||
* Convert a bridge `QQEventVariant` to the OneBot wire-shape JSON.
|
||||
* Returns null for kinds we don't surface (so callers can skip them
|
||||
* without an explicit allow-list).
|
||||
*/
|
||||
export async function convertEvent(
|
||||
ctx: ConverterContext,
|
||||
event: QQEventVariant,
|
||||
): Promise<JsonObject | null> {
|
||||
switch (event.kind) {
|
||||
// Messages.
|
||||
case 'friend_message': return convertFriendMessage(ctx, event);
|
||||
case 'group_message': return convertGroupMessage(ctx, event);
|
||||
case 'temp_message': return convertTempMessage(ctx, event);
|
||||
|
||||
// Notices.
|
||||
case 'group_member_join': return convertGroupMemberJoin(ctx, event);
|
||||
case 'group_member_leave': return convertGroupMemberLeave(ctx, event);
|
||||
case 'group_mute': return convertGroupMute(ctx, event);
|
||||
case 'group_admin': return convertGroupAdmin(ctx, event);
|
||||
case 'friend_recall': return convertFriendRecall(ctx, event);
|
||||
case 'group_recall': return convertGroupRecall(ctx, event);
|
||||
case 'friend_poke': return convertFriendPoke(ctx, event);
|
||||
case 'group_poke': return convertGroupPoke(ctx, event);
|
||||
case 'group_essence': return convertGroupEssence(ctx, event);
|
||||
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
|
||||
case 'friend_add': return convertFriendAdd(ctx, event);
|
||||
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
|
||||
|
||||
// Requests.
|
||||
case 'friend_request': return convertFriendRequest(ctx, event);
|
||||
case 'group_invite': return convertGroupInvite(ctx, event);
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── side-channel re-export ───────────────
|
||||
|
||||
/**
|
||||
* Element-array -> OneBot segment-array helper. Used by
|
||||
* `modules/message-actions.ts` for forward-message rebuilding (where
|
||||
* we already know the elements but want the OneBot segment shape).
|
||||
* The signature stays backwards-compatible: each resolver is an
|
||||
* optional positional argument.
|
||||
*/
|
||||
export async function elementsToOneBotSegments(
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
mediaUrlResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSegmentSink?: MediaSegmentSink | null,
|
||||
) {
|
||||
return elementsToJson(
|
||||
elements, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { QQEventVariant } from '@snowluma/bridge/events';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { ConverterContext } from './index';
|
||||
import { elementsToJson } from './to-segment';
|
||||
import { applyMessageIdResolver, segmentsToRawMessage } from './utils';
|
||||
|
||||
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
type TempMessage = Extract<QQEventVariant, { kind: 'temp_message' }>;
|
||||
|
||||
export async function convertFriendMessage(ctx: ConverterContext, event: FriendMessage): Promise<JsonObject> {
|
||||
const isSelf = event.senderUin === ctx.selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
|
||||
);
|
||||
const segments = await elementsToJson(
|
||||
event.elements, false, event.senderUin,
|
||||
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: postType,
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
user_id: event.senderUin,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function convertGroupMessage(ctx: ConverterContext, event: GroupMessage): Promise<JsonObject> {
|
||||
const isSelf = event.senderUin === ctx.selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
|
||||
);
|
||||
const segments = await elementsToJson(
|
||||
event.elements, true, event.groupId,
|
||||
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: postType,
|
||||
message_type: 'group',
|
||||
sub_type: 'normal',
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
group_id: event.groupId,
|
||||
user_id: event.senderUin,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
card: event.senderCard,
|
||||
role: event.senderRole || 'member',
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
anonymous: null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function convertTempMessage(ctx: ConverterContext, event: TempMessage): Promise<JsonObject> {
|
||||
const isSelf = event.senderUin === ctx.selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
|
||||
);
|
||||
const segments = await elementsToJson(
|
||||
event.elements, false, event.senderUin,
|
||||
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: postType,
|
||||
message_type: 'private',
|
||||
sub_type: 'group',
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
user_id: event.senderUin,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import type { QQEventVariant } from '@snowluma/bridge/events';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { ConverterContext } from './index';
|
||||
import { applyMessageIdResolver, isSameActor } from './utils';
|
||||
|
||||
type GroupMemberJoin = Extract<QQEventVariant, { kind: 'group_member_join' }>;
|
||||
type GroupMemberLeave = Extract<QQEventVariant, { kind: 'group_member_leave' }>;
|
||||
type GroupMute = Extract<QQEventVariant, { kind: 'group_mute' }>;
|
||||
type GroupAdmin = Extract<QQEventVariant, { kind: 'group_admin' }>;
|
||||
type FriendRecall = Extract<QQEventVariant, { kind: 'friend_recall' }>;
|
||||
type GroupRecall = Extract<QQEventVariant, { kind: 'group_recall' }>;
|
||||
type FriendPoke = Extract<QQEventVariant, { kind: 'friend_poke' }>;
|
||||
type GroupPoke = Extract<QQEventVariant, { kind: 'group_poke' }>;
|
||||
type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
|
||||
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
|
||||
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
|
||||
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
|
||||
|
||||
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject {
|
||||
let subType: string;
|
||||
if (event.isKick) {
|
||||
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
|
||||
} else {
|
||||
subType = 'leave';
|
||||
}
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_decrease',
|
||||
sub_type: subType,
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupMute(ctx: ConverterContext, event: GroupMute): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_ban',
|
||||
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
duration: event.duration,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_admin',
|
||||
sub_type: event.set ? 'set' : 'unset',
|
||||
group_id: event.groupId,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'friend_recall',
|
||||
user_id: event.userUin,
|
||||
message_id: messageId,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_recall',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.authorUin,
|
||||
message_id: messageId,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertFriendPoke(ctx: ConverterContext, event: FriendPoke): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'notify',
|
||||
sub_type: 'poke',
|
||||
user_id: event.userUin,
|
||||
target_id: event.targetUin,
|
||||
action: event.action,
|
||||
suffix: event.suffix,
|
||||
action_img_url: event.actionImgUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'notify',
|
||||
sub_type: 'poke',
|
||||
group_id: event.groupId,
|
||||
user_id: event.userUin,
|
||||
target_id: event.targetUin,
|
||||
action: event.action,
|
||||
suffix: event.suffix,
|
||||
action_img_url: event.actionImgUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'essence',
|
||||
sub_type: event.set ? 'add' : 'delete',
|
||||
group_id: event.groupId,
|
||||
user_id: event.senderUin,
|
||||
sender_id: event.senderUin,
|
||||
operator_id: event.operatorUin,
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
random: event.random,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupFileUpload(ctx: ConverterContext, event: GroupFileUpload): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_upload',
|
||||
group_id: event.groupId,
|
||||
user_id: event.userUin,
|
||||
file: {
|
||||
id: event.fileId,
|
||||
name: event.fileName,
|
||||
size: event.fileSize,
|
||||
busid: event.busId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'friend_add',
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Group message emoji reaction notice. Matches the gocqhttp / NapCat
|
||||
* extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot
|
||||
* v11 standard has no slot for reactions and that's what every
|
||||
* downstream framework keys off.
|
||||
*/
|
||||
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
|
||||
// Reconstruct the OneBot message_id we originally minted for the
|
||||
// reacted-to message. hashMessageIdInt32 is deterministic so the ID
|
||||
// matches whatever the client received at receive-time, even when
|
||||
// the message has fallen out of our store.
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_msg_emoji_like',
|
||||
sub_type: event.isAdd ? 'add' : 'remove',
|
||||
group_id: event.groupId,
|
||||
user_id: event.operatorUin,
|
||||
operator_id: event.operatorUin,
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
likes: [{ emoji_id: event.emojiId, count: event.count }],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { QQEventVariant } from '@snowluma/bridge/events';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { ConverterContext } from './index';
|
||||
|
||||
type FriendRequest = Extract<QQEventVariant, { kind: 'friend_request' }>;
|
||||
type GroupInvite = Extract<QQEventVariant, { kind: 'group_invite' }>;
|
||||
|
||||
export function convertFriendRequest(ctx: ConverterContext, event: FriendRequest): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'request',
|
||||
request_type: 'friend',
|
||||
user_id: event.fromUin,
|
||||
comment: event.message,
|
||||
flag: event.flag,
|
||||
};
|
||||
}
|
||||
|
||||
export function convertGroupInvite(ctx: ConverterContext, event: GroupInvite): JsonObject {
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'request',
|
||||
request_type: 'group',
|
||||
sub_type: event.subType || 'invite',
|
||||
group_id: event.groupId,
|
||||
user_id: event.fromUin,
|
||||
comment: event.message,
|
||||
flag: event.flag,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
import type { JsonArray, JsonObject } from '../types';
|
||||
import type {
|
||||
ImageUrlResolver,
|
||||
MediaSegmentSink,
|
||||
MediaUrlResolver,
|
||||
MessageIdResolver,
|
||||
} from './index';
|
||||
import { resolveReplyId } from './utils';
|
||||
|
||||
export async function elementsToJson(
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
mediaUrlResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSegmentSink?: MediaSegmentSink | null,
|
||||
): Promise<JsonArray> {
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
result.push(await elementToSegment(
|
||||
element, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function elementToSegment(
|
||||
element: MessageElement,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
mediaUrlResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSegmentSink?: MediaSegmentSink | null,
|
||||
): Promise<JsonObject> {
|
||||
if (element.type === 'text') {
|
||||
return { type: 'text', data: { text: element.text ?? '' } };
|
||||
}
|
||||
|
||||
if (element.type === 'face') {
|
||||
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
|
||||
}
|
||||
|
||||
if (element.type === 'image') {
|
||||
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const data: JsonObject = {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
sub_type: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
};
|
||||
if (mediaSegmentSink) mediaSegmentSink('image', element, data, isGroup, sessionId);
|
||||
return { type: 'image', data };
|
||||
}
|
||||
|
||||
if (element.type === 'at') {
|
||||
const qq = (element.uid === 'all' || element.targetUin === 0)
|
||||
? 'all'
|
||||
: String(element.targetUin ?? 0);
|
||||
return { type: 'at', data: { qq } };
|
||||
}
|
||||
|
||||
if (element.type === 'reply') {
|
||||
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
|
||||
return { type: 'reply', data: { id: String(id) } };
|
||||
}
|
||||
|
||||
if (element.type === 'record') {
|
||||
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
const data: JsonObject = {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
};
|
||||
if (mediaSegmentSink) mediaSegmentSink('record', element, data, isGroup, sessionId);
|
||||
return { type: 'record', data };
|
||||
}
|
||||
|
||||
if (element.type === 'video') {
|
||||
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
const data: JsonObject = {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
};
|
||||
if (mediaSegmentSink) mediaSegmentSink('video', element, data, isGroup, sessionId);
|
||||
return { type: 'video', data };
|
||||
}
|
||||
|
||||
if (element.type === 'json') {
|
||||
return { type: 'json', data: { data: element.text ?? '' } };
|
||||
}
|
||||
|
||||
if (element.type === 'xml') {
|
||||
return {
|
||||
type: 'xml',
|
||||
data: {
|
||||
data: element.text ?? '',
|
||||
resid: element.subType ?? 35,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'file') {
|
||||
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
return {
|
||||
type: 'file',
|
||||
data: {
|
||||
name: element.fileName ?? '',
|
||||
size: element.fileSize ?? 0,
|
||||
id: element.fileId ?? '',
|
||||
url,
|
||||
file_hash: element.fileHash ?? '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'mface') {
|
||||
return {
|
||||
type: 'mface',
|
||||
data: {
|
||||
name: element.text ?? '',
|
||||
tab_id: element.faceId ?? 0,
|
||||
sub_type: element.subType ?? 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'poke') {
|
||||
return {
|
||||
type: 'poke',
|
||||
data: {
|
||||
type: element.subType ?? 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'forward') {
|
||||
return {
|
||||
type: 'forward',
|
||||
data: { id: element.resId ?? '' },
|
||||
};
|
||||
}
|
||||
|
||||
// Unknown / unmapped element type — emit an empty segment to keep the
|
||||
// outgoing message length consistent with the bridge event.
|
||||
return { type: element.type, data: {} };
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import type { JsonArray, JsonObject } from '../types';
|
||||
import type { MessageIdResolver } from './index';
|
||||
|
||||
export function parseSelfId(instanceUin: string): number {
|
||||
const parsed = Number.parseInt(instanceUin, 10);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Two QQEvent actors are "the same" when their uins match, or their
|
||||
* uids match when uins aren't available. Used by the group_member_join
|
||||
* sub-type calculation (self-approve vs. invite).
|
||||
*/
|
||||
export function isSameActor(
|
||||
leftUin: number,
|
||||
leftUid: string | undefined,
|
||||
rightUin: number,
|
||||
rightUid: string | undefined,
|
||||
): boolean {
|
||||
if (leftUin > 0 && rightUin > 0) return leftUin === rightUin;
|
||||
return Boolean(leftUid) && leftUid === rightUid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the optional MessageId resolver, falling back to the raw
|
||||
* sequence when no resolver is wired or it returns 0.
|
||||
*/
|
||||
export function applyMessageIdResolver(
|
||||
resolver: MessageIdResolver | null,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
): number {
|
||||
if (resolver) {
|
||||
const resolved = resolver(isGroup, sessionId, sequence, eventName);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
const seq = Math.trunc(sequence);
|
||||
return seq === 0 ? 0 : seq;
|
||||
}
|
||||
|
||||
export function resolveReplyId(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
resolver?: MessageIdResolver | null,
|
||||
): number {
|
||||
const seq = Math.trunc(sequence);
|
||||
if (seq === 0) return 0;
|
||||
|
||||
if (resolver) {
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
|
||||
return seq;
|
||||
}
|
||||
|
||||
// ─────────────── raw_message (CQ string) generation ───────────────
|
||||
|
||||
function cqEscape(text: string): string {
|
||||
return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ',');
|
||||
}
|
||||
|
||||
export function segmentsToRawMessage(segments: JsonArray): string {
|
||||
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
|
||||
}
|
||||
|
||||
function segmentToCQ(seg: JsonObject): string {
|
||||
const type = String(seg.type ?? '');
|
||||
const data = (seg.data ?? {}) as Record<string, unknown>;
|
||||
switch (type) {
|
||||
case 'text':
|
||||
return cqEscape(String(data.text ?? ''));
|
||||
case 'face':
|
||||
return `[CQ:face,id=${data.id ?? 0}]`;
|
||||
case 'image':
|
||||
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'at':
|
||||
return `[CQ:at,qq=${data.qq ?? ''}]`;
|
||||
case 'reply':
|
||||
return `[CQ:reply,id=${data.id ?? 0}]`;
|
||||
case 'record':
|
||||
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'video':
|
||||
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'json':
|
||||
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
|
||||
case 'xml':
|
||||
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
|
||||
case 'forward':
|
||||
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
|
||||
case 'mface':
|
||||
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
|
||||
case 'poke':
|
||||
return `[CQ:poke,type=${data.type ?? 0}]`;
|
||||
case 'file':
|
||||
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
default:
|
||||
return `[CQ:${type}]`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { JsonObject, JsonValue, MessageFormat } from './types';
|
||||
export interface EventReportOptions {
|
||||
/** Effective `messageFormat` for this adapter. */
|
||||
messageFormat: MessageFormat;
|
||||
/** Whether self-sent messages should be forwarded to this adapter. */
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the dispatch options from an adapter. Each adapter is fully
|
||||
* self-describing — there is no global fallback. Defaults are applied here
|
||||
* only as a safety net for partially-deserialized legacy configs.
|
||||
*/
|
||||
export function resolveReportOptions(
|
||||
network: { messageFormat?: MessageFormat; reportSelfMessage?: boolean },
|
||||
): EventReportOptions {
|
||||
return {
|
||||
messageFormat: network.messageFormat ?? 'array',
|
||||
reportSelfMessage: network.reportSelfMessage ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-built payload covering every adapter variant of a single canonical event.
|
||||
*
|
||||
* The bridge produces one OneBot-shaped event per upstream packet. Because
|
||||
* adapters only differ in (a) whether they receive `message_sent` self-events
|
||||
* and (b) whether the `message` field is the segment array or its CQ-string
|
||||
* form, we serialize the event at most twice up-front and let every adapter
|
||||
* pick the slot it needs in O(1).
|
||||
*/
|
||||
export interface DispatchPayload {
|
||||
/** True when the canonical event is a self-sent message (`post_type='message_sent'`). */
|
||||
isSelfMessage: boolean;
|
||||
/** JSON for adapters using `messageFormat: 'array'` (the canonical event). */
|
||||
arrayJson: string;
|
||||
/**
|
||||
* JSON for adapters using `messageFormat: 'string'`. For non-message events
|
||||
* this points at the same string as `arrayJson` (no transformation needed).
|
||||
*/
|
||||
stringJson: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the dispatch payload for one canonical OneBot event. Performs at most
|
||||
* two `JSON.stringify` calls (one per format variant) regardless of how many
|
||||
* adapters the payload will fan out to.
|
||||
*/
|
||||
export function buildDispatchPayload(event: JsonObject): DispatchPayload {
|
||||
const isSelfMessage = event.post_type === 'message_sent';
|
||||
const arrayJson = JSON.stringify(event);
|
||||
|
||||
let stringJson = arrayJson;
|
||||
const hasMessage = event.post_type === 'message' || event.post_type === 'message_sent';
|
||||
if (hasMessage && Array.isArray(event.message)) {
|
||||
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
|
||||
stringJson = JSON.stringify({ ...event, message: raw as JsonValue });
|
||||
}
|
||||
|
||||
return { isSelfMessage, arrayJson, stringJson };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the pre-serialized payload variant an adapter should send, or `null`
|
||||
* when the adapter chose not to receive this event. Hot-path helper: one
|
||||
* branch + one map lookup per connection, no allocation.
|
||||
*/
|
||||
export function pickDispatchJson(
|
||||
payload: DispatchPayload,
|
||||
options: EventReportOptions,
|
||||
): string | null {
|
||||
if (payload.isSelfMessage && !options.reportSelfMessage) return null;
|
||||
return options.messageFormat === 'string' ? payload.stringJson : payload.arrayJson;
|
||||
}
|
||||
|
||||
/**
|
||||
* One-shot variant of {@link buildDispatchPayload} + {@link pickDispatchJson}
|
||||
* for ad-hoc events (e.g. WS connection bootstrap meta events) that aren't
|
||||
* worth pre-building a full payload for.
|
||||
*
|
||||
* Returns `null` when the adapter shouldn't see this event. Otherwise returns
|
||||
* the original event untouched, or a shallow clone with `message` rewritten.
|
||||
*/
|
||||
export function shapeEventForAdapter(
|
||||
event: JsonObject,
|
||||
options: EventReportOptions,
|
||||
): JsonObject | null {
|
||||
if (event.post_type === 'message_sent' && !options.reportSelfMessage) return null;
|
||||
|
||||
if (options.messageFormat === 'string'
|
||||
&& (event.post_type === 'message' || event.post_type === 'message_sent')
|
||||
&& Array.isArray(event.message)
|
||||
) {
|
||||
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
|
||||
return { ...event, message: raw as JsonValue };
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { QQEventVariant } from '@snowluma/bridge/events';
|
||||
import { convertEvent } from './event-converter';
|
||||
import type { OneBotInstanceContext } from './instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
|
||||
/**
|
||||
* Subscribe every `OneBotInstanceContext`-aware handler onto the bridge
|
||||
* event bus. Returns a disposer that removes every subscription registered
|
||||
* here in one shot — useful for tests and for tearing down a session.
|
||||
*/
|
||||
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
// Every kind that maps onto an OB11 message event also seeds the
|
||||
// message-meta cache; we do that synchronously before async conversion so
|
||||
// reply / quote lookups for that message id work even if the converter
|
||||
// takes a beat to finish (e.g. while resolving image URLs).
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('group_message', async (event) => {
|
||||
cacheGroupMessageMeta(ctx, event);
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('friend_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('temp_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
|
||||
// Notice / request / non-message events: no meta caching needed, just
|
||||
// convert and dispatch.
|
||||
for (const kind of NOTICE_KINDS) {
|
||||
disposers.push(
|
||||
ctx.bridge.events.on(kind, async (event) => {
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const dispose of disposers) {
|
||||
try { dispose(); } catch { /* ignore */ }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const NOTICE_KINDS = [
|
||||
'group_member_join',
|
||||
'group_member_leave',
|
||||
'group_mute',
|
||||
'group_admin',
|
||||
'friend_recall',
|
||||
'group_recall',
|
||||
'friend_request',
|
||||
'group_invite',
|
||||
'friend_poke',
|
||||
'group_poke',
|
||||
'group_essence',
|
||||
'group_file_upload',
|
||||
'friend_add',
|
||||
'group_msg_emoji_like',
|
||||
] as const satisfies readonly QQEventVariant['kind'][];
|
||||
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
|
||||
const converted = await convertEvent(ctx.converterCtx, event);
|
||||
if (!converted) return;
|
||||
ctx.dispatchEvent(converted);
|
||||
}
|
||||
|
||||
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {
|
||||
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: event.groupId,
|
||||
sequence: event.msgSeq,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: event.msgId,
|
||||
timestamp: event.time,
|
||||
});
|
||||
}
|
||||
|
||||
function cachePrivateMessageMeta(
|
||||
ctx: OneBotInstanceContext,
|
||||
senderUin: number,
|
||||
msgSeq: number,
|
||||
timestamp: number,
|
||||
random: number,
|
||||
): void {
|
||||
const messageId = hashMessageIdInt32(msgSeq, senderUin, PRIVATE_MESSAGE_EVENT);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: senderUin,
|
||||
sequence: msgSeq,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random,
|
||||
timestamp,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import type { WebHonorType } from '@snowluma/bridge/web/group-honor';
|
||||
import type { Bridge } from '@snowluma/core/bridge';
|
||||
import type { ApiActionContext } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { MessageStore } from './message-store';
|
||||
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
|
||||
import {
|
||||
getDownloadRKeys,
|
||||
getFriendList,
|
||||
getGroupFiles,
|
||||
getGroupInfo,
|
||||
getGroupList,
|
||||
getGroupMemberInfo,
|
||||
getGroupMemberList,
|
||||
getGroupSystemMessages,
|
||||
getLoginInfo,
|
||||
getStrangerInfo,
|
||||
} from './modules/contact-actions';
|
||||
import {
|
||||
deleteMessage,
|
||||
forwardSingleMessage,
|
||||
getForwardMessage,
|
||||
getFriendMsgHistory,
|
||||
getGroupMsgHistory,
|
||||
sendGroupForwardMessage,
|
||||
sendGroupMessage,
|
||||
sendPrivateForwardMessage,
|
||||
sendPrivateMessage,
|
||||
setEssenceMessage,
|
||||
uploadForwardMessage,
|
||||
} from './modules/message-actions';
|
||||
import {
|
||||
getImageInfo as getCachedImageInfo,
|
||||
getRecordInfo as getCachedRecordInfo,
|
||||
} from './modules/media-actions';
|
||||
import { handleGroupAddRequest } from './modules/request-actions';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
|
||||
/**
|
||||
* Single shared context bag that flows through every OneBot instance-internal
|
||||
* subsystem: API builder and the per-kind event pipeline.
|
||||
*
|
||||
* Only fields that are actually read through this bag live here. The API
|
||||
* handler and network manager are owned by `OneBotInstance` directly because
|
||||
* nothing reads them via ctx, and including them here would force a
|
||||
* chicken-and-egg late-bound field dance during construction.
|
||||
*
|
||||
* `dispatchEvent` is the indirection used by the event pipeline to hand a
|
||||
* converted OneBot event back to the instance for caching + adapter fan-out;
|
||||
* it lets the pipeline stay decoupled from the network manager.
|
||||
*/
|
||||
export interface OneBotInstanceContext {
|
||||
/** Self UIN as string (matches what's on disk and on the wire). */
|
||||
uin: string;
|
||||
/** Self UIN parsed once, used in event payloads. */
|
||||
selfId: number;
|
||||
|
||||
bridge: BridgeInterface;
|
||||
|
||||
messageStore: MessageStore;
|
||||
mediaStore: MediaStore;
|
||||
|
||||
converterCtx: ConverterContext;
|
||||
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
|
||||
/** Persist meta about a message id; safe to call any number of times. */
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||
/** Hand a fully-converted OneBot event to the network manager + caches. */
|
||||
dispatchEvent(event: JsonObject): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the ApiActionContext that ApiHandler hands to each action file.
|
||||
*
|
||||
* Two flavours of entries live in here:
|
||||
* - Adapters — rename a Bridge method (setGroupKick → kickGroupMember),
|
||||
* compose with messageStore / mediaStore / ref, bake in a constant
|
||||
* (setEssenceMsg passes true; deleteEssenceMsg passes false), bridge a
|
||||
* bridge call into OneBot vocabulary (sendFriendPoke flattens the
|
||||
* isGroup boolean), or extract a field from the bridge return shape.
|
||||
* - Pass-throughs used to live here too but added zero value; OneBot
|
||||
* actions now call `ctx.bridge.<name>` directly when no translation is
|
||||
* happening (set_group_admin, set_online_status, set_avatar, …).
|
||||
*/
|
||||
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
const { bridge, messageStore, mediaStore } = ref;
|
||||
|
||||
return {
|
||||
bridge,
|
||||
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
isOnline: () => true,
|
||||
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
|
||||
// OneBot11 message actions.
|
||||
sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape),
|
||||
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
|
||||
|
||||
// OneBot11 info actions (wrap modules that also touch identity).
|
||||
getFriendList: () => getFriendList(bridge),
|
||||
getGroupList: (noCache) => getGroupList(bridge, noCache),
|
||||
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
|
||||
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
|
||||
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
|
||||
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
|
||||
|
||||
// Group admin — names translate to OneBot vocabulary.
|
||||
setGroupKick: (groupId, userId, reject) => bridge.apis.groupAdmin.kickMember(groupId, userId, reject),
|
||||
setGroupKickMembers: (groupId, userIds, reject) => bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject),
|
||||
setGroupBan: (groupId, userId, duration) => bridge.apis.groupAdmin.muteMember(groupId, userId, duration),
|
||||
setGroupWholeBan: (groupId, enable) => bridge.apis.groupAdmin.muteAll(groupId, enable),
|
||||
setGroupLeave: (groupId) => bridge.apis.groupAdmin.leave(groupId),
|
||||
|
||||
// Group file — fileId field extraction + defaults.
|
||||
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
|
||||
const result = await bridge.apis.groupFile.upload(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
|
||||
return result.fileId;
|
||||
},
|
||||
uploadPrivateFile: async (userId, file, name, uploadFile) => {
|
||||
const result = await bridge.apis.groupFile.uploadPrivate(userId, file, name ?? '', uploadFile ?? true);
|
||||
return result.fileId;
|
||||
},
|
||||
getGroupFileUrl: (groupId, fileId, busId) => bridge.apis.groupFile.getUrl(groupId, fileId, busId ?? 102),
|
||||
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
|
||||
createGroupFileFolder: (groupId, name, parentId) => bridge.apis.groupFile.createFolder(groupId, name, parentId ?? '/'),
|
||||
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash),
|
||||
|
||||
// Requests — name translation.
|
||||
handleFriendRequest: (flag, approve) => bridge.apis.friend.handleRequest(flag, approve),
|
||||
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
|
||||
|
||||
// Pokes — flatten isGroup into the bridge signature.
|
||||
sendFriendPoke: (userId, targetId) => bridge.apis.interaction.sendPoke(false, userId, targetId),
|
||||
sendGroupPoke: (groupId, userId) => bridge.apis.interaction.sendPoke(true, groupId, userId),
|
||||
|
||||
// Essence — bake the set/unset boolean.
|
||||
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
|
||||
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
|
||||
|
||||
// Profile-like / get_group_essence — OneBot-specific defaults that the
|
||||
// action handlers don't supply.
|
||||
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.apis.profile.getLike(userId, start, limit),
|
||||
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.apis.web.getEssence(groupId, pageStart, pageLimit),
|
||||
|
||||
// Message-store-backed history reads.
|
||||
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
|
||||
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
|
||||
|
||||
// Module wrappers / multi-dep compositions.
|
||||
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
|
||||
getDownloadRKeys: () => getDownloadRKeys(bridge),
|
||||
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
|
||||
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
|
||||
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
|
||||
getForwardMsg: (resId) => getForwardMessage(ref, resId),
|
||||
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
|
||||
handleDeleteFriend: (userId, block) => bridge.apis.friend.delete(userId, !!block),
|
||||
forceFetchClientKey: () => bridge.apis.web.forceFetchClientKey(),
|
||||
setFriendRemark: (userId, remark) => bridge.apis.friend.setRemark(userId, remark),
|
||||
setGroupRemark: (groupId, remark) => bridge.apis.groupAdmin.setRemark(groupId, remark),
|
||||
setGroupAvatar: (groupId, source) => bridge.apis.profile.setGroupAvatar(groupId, source),
|
||||
getGroupFileCount: (groupId) => bridge.apis.groupFile.getCount(groupId),
|
||||
|
||||
// Cross-store: looks up the meta then routes through Bridge.
|
||||
setMsgEmojiLike: async (messageId, emojiId, set) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
if (!meta) throw new Error('message not found');
|
||||
// QQ itself doesn't expose emoji reactions on private chats, so
|
||||
// there is no wire path to forward this to; fail loudly instead
|
||||
// of silently no-op'ing.
|
||||
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
|
||||
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
|
||||
},
|
||||
markGroupMsgAsRead: (groupId, sequence) => bridge.apis.message.markGroupRead(groupId, sequence),
|
||||
markPrivateMsgAsRead: (userId, sequence) => bridge.apis.message.markPrivateRead(userId, sequence),
|
||||
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus),
|
||||
setProfile: (nickname?: string, personalNote?: string) => bridge.apis.profile.setProfile(nickname, personalNote),
|
||||
|
||||
// Web-backed actions.
|
||||
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.apis.web.getHonorInfo(groupId, type),
|
||||
getGroupEssenceAll: (groupId) => bridge.apis.web.getEssenceAll(groupId),
|
||||
getGroupAlbumList: (groupId) => bridge.apis.groupAlbum.list(groupId),
|
||||
uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.apis.groupAlbum.upload(groupId, albumId, albumName, filePath),
|
||||
getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo),
|
||||
commentGroupAlbumMedia: (groupId, albumId, lloc, content) => bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content),
|
||||
deleteGroupAlbumMedia: (groupId, albumId, lloc) => bridge.apis.groupAlbum.delete(groupId, albumId, lloc),
|
||||
likeGroupAlbumMedia: (groupId, albumId, batchId, lloc, isLike) => bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, isLike),
|
||||
sendGroupNotice: (groupId, content, options) => bridge.apis.web.sendNotice(groupId, content, options),
|
||||
getGroupNotice: (groupId) => bridge.apis.web.getNotice(groupId),
|
||||
deleteGroupNotice: (groupId, fid) => bridge.apis.web.deleteNotice(groupId, fid),
|
||||
getCookiesStr: (domain) => bridge.apis.web.getCookiesStr(domain),
|
||||
getCsrfToken: () => bridge.apis.web.getCsrfToken(),
|
||||
getCredentials: (domain) => bridge.apis.web.getCredentials(domain),
|
||||
|
||||
// Extended
|
||||
fetchCustomFace: (count) => bridge.apis.profile.fetchCustomFace(count),
|
||||
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.apis.interaction.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
|
||||
|
||||
// Media lookup.
|
||||
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
|
||||
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
|
||||
};
|
||||
}
|
||||
|
||||
// Re-export Bridge type so consumers of OneBotInstanceContext that need it
|
||||
// (legacy) keep the import surface stable.
|
||||
export type { Bridge };
|
||||
|
||||
// Re-export WebHonorType so legacy spots that imported it via this module
|
||||
// keep working.
|
||||
export type { WebHonorType };
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
import type { DownloadRKeyInfo } from '@snowluma/core/bridge';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
interface CachedRKey {
|
||||
value: string;
|
||||
type: number;
|
||||
createTime: number;
|
||||
ttlSeconds: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const RKEY_REFRESH_SKEW = 60;
|
||||
const RKEY_REFRESH_COOLDOWN = 30;
|
||||
const PRIVATE_IMAGE_RKEY_TYPE = 10;
|
||||
const GROUP_IMAGE_RKEY_TYPE = 20;
|
||||
const PRIVATE_VIDEO_RKEY_TYPE = 12;
|
||||
const GROUP_VIDEO_RKEY_TYPE = 22;
|
||||
const PRIVATE_PTT_RKEY_TYPE = 14;
|
||||
const GROUP_PTT_RKEY_TYPE = 24;
|
||||
const FALLBACK_IMAGE_RKEY_TYPE = 2;
|
||||
|
||||
export class RKeyCache {
|
||||
private cache = new Map<number, CachedRKey>();
|
||||
private lastRefreshAttempt = 0;
|
||||
|
||||
warmUp(bridge: BridgeInterface, uin: string): void {
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => {
|
||||
this.updateCache(rkeys);
|
||||
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
|
||||
},
|
||||
(err) => {
|
||||
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
const url = element.imageUrl ?? '';
|
||||
if (!urlNeedsRKey(url)) return url;
|
||||
|
||||
const rkey = this.findRKey(bridge, isGroup);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||
return url + separator + encodeURIComponent(cleanRKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a URL for video/record/file media elements.
|
||||
* Appends the correct RKey type based on media kind and group/private context.
|
||||
*/
|
||||
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
const url = element.url ?? '';
|
||||
if (!url || !urlNeedsRKey(url)) return url;
|
||||
|
||||
const mediaType = element.type;
|
||||
let primaryType: number;
|
||||
if (mediaType === 'video') {
|
||||
primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
|
||||
} else if (mediaType === 'record') {
|
||||
primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
|
||||
} else {
|
||||
// For file types, try image rkeys as a fallback (file URLs typically use image rkeys)
|
||||
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
}
|
||||
|
||||
const rkey = this.findRKeyForType(bridge, primaryType);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||
return url + separator + encodeURIComponent(cleanRKey);
|
||||
}
|
||||
|
||||
private updateCache(rkeys: DownloadRKeyInfo[]): void {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
for (const rk of rkeys) {
|
||||
if (!rk.rkey || !rk.type) continue;
|
||||
const baseTime = rk.createTime || now;
|
||||
const ttl = rk.ttlSeconds || 3600;
|
||||
this.cache.set(rk.type, {
|
||||
value: rk.rkey,
|
||||
type: rk.type,
|
||||
createTime: rk.createTime,
|
||||
ttlSeconds: rk.ttlSeconds,
|
||||
expiresAt: baseTime + ttl,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
|
||||
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
return this.findRKeyForType(bridge, primaryType);
|
||||
}
|
||||
|
||||
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
const tryFind = (type: number): string | null => {
|
||||
const cached = this.cache.get(type);
|
||||
if (!cached || !cached.value) return null;
|
||||
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
|
||||
return cached.value;
|
||||
};
|
||||
|
||||
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
if (result) return result;
|
||||
|
||||
// Refresh check cooldown
|
||||
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
|
||||
this.lastRefreshAttempt = now;
|
||||
|
||||
// Schedule async refresh
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => this.updateCache(rkeys),
|
||||
() => { /* ignore */ },
|
||||
);
|
||||
|
||||
// Try again (won't be ready yet for this call, but future calls will benefit)
|
||||
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function urlNeedsRKey(url: string): boolean {
|
||||
if (!url || url.includes('rkey=')) return false;
|
||||
if (url.includes('gchat.qpic.cn')) return false;
|
||||
return url.includes('multimedia.nt.qq.com.cn') ||
|
||||
url.includes('.nt.qq.com.cn') ||
|
||||
url.includes('/download');
|
||||
}
|
||||
|
||||
function stripRKeyPrefix(rkey: string): string {
|
||||
for (const prefix of ['&rkey=', '?rkey=']) {
|
||||
if (rkey.startsWith(prefix)) return rkey.slice(prefix.length);
|
||||
}
|
||||
return rkey;
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import path from 'path';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
import { MediaStore } from './media-store';
|
||||
import { MediaUrlResolver } from './media-url-resolver';
|
||||
import { MessageStore } from './message-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import {
|
||||
OneBotNetworkManager,
|
||||
WsServerAdapter,
|
||||
WsClientAdapter,
|
||||
HttpServerAdapter,
|
||||
HttpPostAdapter,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/bridge/format';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
|
||||
private readonly bridge: BridgeInterface;
|
||||
private readonly apiHandler: ApiHandler;
|
||||
private readonly converterCtx: ConverterContext;
|
||||
private readonly messageStore: MessageStore;
|
||||
private readonly mediaStore: MediaStore;
|
||||
private readonly networkManager: OneBotNetworkManager;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
private disposeEventPipeline: (() => void) | null = null;
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
private online = true;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||
private readonly log: Logger;
|
||||
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
|
||||
|
||||
// The converter context's four callbacks delegate to small, focused
|
||||
// modules so this constructor doesn't carry the bridge-URL fetch
|
||||
// branching or the mediaStore field-mapping fanout inline.
|
||||
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
|
||||
const mediaIndexer = new MediaIndexer(this.mediaStore);
|
||||
this.converterCtx = {
|
||||
selfId: parseInt(this.uin, 10) || 0,
|
||||
imageUrlResolver: (element, isGroup) =>
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||
messageIdResolver: (isGroup, sessionId, sequence, eventName) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)),
|
||||
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
|
||||
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
};
|
||||
|
||||
// Shared instance context. Only carries fields that are actually read
|
||||
// through it — api handler and network manager stay as direct fields on
|
||||
// the instance because nothing reads them via ctx.
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: this.uin,
|
||||
selfId: parseInt(this.uin, 10) || 0,
|
||||
bridge: this.bridge,
|
||||
messageStore: this.messageStore,
|
||||
mediaStore: this.mediaStore,
|
||||
converterCtx: this.converterCtx,
|
||||
config,
|
||||
musicSignUrl: config.musicSignUrl,
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event) => this.dispatchEvent(event),
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
this.installAdaptersFromConfig(config);
|
||||
void this.networkManager.openAll().catch((err) => {
|
||||
this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
|
||||
this.startHeartbeat();
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
|
||||
// Per-kind subscription on the typed event bus. Each bridge event kind
|
||||
// gets its own focused handler in `event-pipeline`; the firehose is gone.
|
||||
this.disposeEventPipeline = registerEventPipeline(ctx);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
this.disposeEventPipeline?.();
|
||||
this.disposeEventPipeline = null;
|
||||
void this.networkManager.closeAll().catch((err) => {
|
||||
this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
this.messageStore.close();
|
||||
this.mediaStore.close();
|
||||
}
|
||||
|
||||
addPid(pid: number): void {
|
||||
this.pids.add(pid);
|
||||
}
|
||||
|
||||
removePid(pid: number): void {
|
||||
this.pids.delete(pid);
|
||||
}
|
||||
|
||||
hasPid(pid: number): boolean {
|
||||
return this.pids.has(pid);
|
||||
}
|
||||
|
||||
getPids(): number[] {
|
||||
return [...this.pids];
|
||||
}
|
||||
|
||||
get empty(): boolean {
|
||||
return this.pids.size === 0;
|
||||
}
|
||||
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// NetworkManager builds the dispatch payload once and fans out to every
|
||||
// active adapter in parallel via Promise.allSettled — per-adapter errors
|
||||
// are already isolated, so the outer promise should never reject. The
|
||||
// .catch is a belt-and-suspenders guard against future refactors.
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: this.uin,
|
||||
api: this.apiHandler,
|
||||
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
|
||||
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
|
||||
};
|
||||
}
|
||||
|
||||
private installAdaptersFromConfig(config: OneBotConfig): void {
|
||||
const ctx = this.buildNetworkContext();
|
||||
for (const net of config.networks.httpServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new HttpServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.httpClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new HttpPostAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new WsServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new WsClientAdapter(net.name, net, ctx));
|
||||
}
|
||||
}
|
||||
|
||||
private async applyConfigDiff(next: OneBotConfig): Promise<void> {
|
||||
const ctx = this.buildNetworkContext();
|
||||
const desired = new Map<string, NetworkBase>();
|
||||
const factories = new Map<string, () => void>();
|
||||
|
||||
for (const net of next.networks.httpServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpServerAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.httpClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpPostAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsServerAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsClientAdapter(net.name, net, ctx)));
|
||||
}
|
||||
|
||||
// Close adapters whose entry has been removed entirely.
|
||||
for (const adapter of this.networkManager.list()) {
|
||||
if (!desired.has(adapter.name)) {
|
||||
await this.networkManager.closeOne(adapter.name);
|
||||
}
|
||||
}
|
||||
|
||||
// Reload existing adapters in place; spin up new ones the manager hasn't
|
||||
// seen before.
|
||||
for (const [name, net] of desired) {
|
||||
const existing = this.networkManager.get(name);
|
||||
if (existing) {
|
||||
try {
|
||||
await existing.reload(net as never);
|
||||
} catch (err) {
|
||||
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else if (net.enabled !== false) {
|
||||
const factory = factories.get(name);
|
||||
if (factory) {
|
||||
factory();
|
||||
await this.networkManager.get(name)?.open();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private logReceivedMessage(event: JsonObject): void {
|
||||
const isSelf = event.post_type === 'message_sent';
|
||||
if (event.post_type !== 'message' && !isSelf) return;
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
const isGroup = event.message_type === 'group';
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
const identity = this.bridge.identity;
|
||||
|
||||
// Walk the segment array once: render via the shared formatter for
|
||||
// non-reply segments, and resolve `reply` segments through the
|
||||
// message store so the chain reference becomes legible
|
||||
// ("[回复 <user>: <body>...]" instead of "[回复:1234567890]").
|
||||
const renderedParts: string[] = [];
|
||||
const message = event.message;
|
||||
if (Array.isArray(message)) {
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const type = String((seg as JsonObject).type ?? '');
|
||||
const data = (typeof (seg as JsonObject).data === 'object' && (seg as JsonObject).data !== null && !Array.isArray((seg as JsonObject).data))
|
||||
? (seg as JsonObject).data as Record<string, unknown>
|
||||
: {};
|
||||
if (type === 'reply') {
|
||||
const replyId = toInt(data.id);
|
||||
renderedParts.push(formatReply(this.messageStore, identity, replyId));
|
||||
} else {
|
||||
renderedParts.push(formatMessageSegments([seg as JsonValue]));
|
||||
}
|
||||
}
|
||||
} else if (typeof message === 'string') {
|
||||
renderedParts.push(formatMessageSegments(message));
|
||||
}
|
||||
const content = renderedParts.join(' ').trim() || '[空消息]';
|
||||
|
||||
if (isGroup) {
|
||||
const groupId = toInt(event.group_id);
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.card as string) || (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, groupId, userId);
|
||||
this.log.success(`${selfTag}群 ${formatGroup(identity, groupId)} | ${userPart}: ${idStr} ${content}`);
|
||||
} else {
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, undefined, userId);
|
||||
this.log.success(`${selfTag}私聊 ${userPart}: ${idStr} ${content}`);
|
||||
}
|
||||
}
|
||||
|
||||
private cacheMessageEvent(event: JsonObject): void {
|
||||
if (event.post_type !== 'message' && event.post_type !== 'message_sent') return;
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
if (messageId === 0) return;
|
||||
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
|
||||
const sequence = toInt(event.message_seq);
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
|
||||
if (sessionId === 0) return;
|
||||
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
}
|
||||
|
||||
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
|
||||
if (!Number.isInteger(messageId) || messageId === 0) return;
|
||||
this.messageStore.storeMeta(messageId, meta);
|
||||
}
|
||||
|
||||
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
|
||||
const selfId = parseInt(this.uin, 10) || 0;
|
||||
const time = Math.floor(Date.now() / 1000);
|
||||
return {
|
||||
time,
|
||||
self_id: selfId,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: subType,
|
||||
status: {
|
||||
online: this.online,
|
||||
good: this.online,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// --- Heartbeat ---
|
||||
|
||||
private startHeartbeat(): void {
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
this.dispatchEvent(this.makeHeartbeatEvent());
|
||||
}, OneBotInstance.HEARTBEAT_INTERVAL);
|
||||
this.heartbeatTimer.unref?.();
|
||||
}
|
||||
|
||||
private makeHeartbeatEvent(): JsonObject {
|
||||
const selfId = parseInt(this.uin, 10) || 0;
|
||||
const time = Math.floor(Date.now() / 1000);
|
||||
return {
|
||||
time,
|
||||
self_id: selfId,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'heartbeat',
|
||||
status: { online: this.online, good: this.online },
|
||||
interval: OneBotInstance.HEARTBEAT_INTERVAL,
|
||||
};
|
||||
}
|
||||
|
||||
private stopHeartbeat(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return Math.trunc(parsed);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { OneBotInstance } from './instance';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
export class OneBotManager {
|
||||
private readonly instances = new Map<string, OneBotInstance>();
|
||||
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.setSessionStartedCallback((uin, bridge) => {
|
||||
this.onSessionStarted(uin, bridge);
|
||||
});
|
||||
|
||||
bridgeManager.setSessionClosedCallback((uin) => {
|
||||
this.onSessionClosed(uin);
|
||||
});
|
||||
}
|
||||
|
||||
getInstance(uin: string): OneBotInstance | null {
|
||||
return this.instances.get(uin) ?? null;
|
||||
}
|
||||
|
||||
getInstances(): OneBotInstance[] {
|
||||
return [...this.instances.values()];
|
||||
}
|
||||
|
||||
reloadConfig(uin: string): boolean {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
instance.reloadConfig(config);
|
||||
log.info('configuration reloaded: UIN=%s', uin);
|
||||
return true;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const instance of this.instances.values()) {
|
||||
instance.dispose();
|
||||
}
|
||||
this.instances.clear();
|
||||
}
|
||||
|
||||
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
|
||||
if (this.instances.has(uin)) return;
|
||||
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
const instance = new OneBotInstance(uin, bridge, config);
|
||||
|
||||
const activePid = bridge.activePid;
|
||||
if (activePid !== null) {
|
||||
instance.addPid(activePid);
|
||||
}
|
||||
|
||||
// Seed nickname with the UIN so the WebUI never renders blank while
|
||||
// warmup is in flight or if warmup never resolves a real nickname.
|
||||
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
|
||||
|
||||
this.instances.set(uin, instance);
|
||||
log.info('session started: UIN=%s', uin);
|
||||
|
||||
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
|
||||
warmUpBridgeState(uin, bridge).catch((err) => {
|
||||
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private onSessionClosed(uin: string): void {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return;
|
||||
|
||||
instance.dispose();
|
||||
this.instances.delete(uin);
|
||||
log.info('session closed: UIN=%s', uin);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
let selfResolved = false;
|
||||
|
||||
// Step 1: Fetch friend list + derive self profile when QQ happens to
|
||||
// include self in the response. Some accounts / versions omit self,
|
||||
// which used to leave identity.nickname empty — see step 1b for the
|
||||
// explicit fallback.
|
||||
try {
|
||||
const friends = await bridge.apis.contacts.fetchFriendList();
|
||||
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||
|
||||
for (const f of friends) {
|
||||
if (f.uin === selfUin) {
|
||||
bridge.identity.setSelfProfile({
|
||||
uin: f.uin, uid: f.uid,
|
||||
nickname: f.nickname || uin,
|
||||
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
|
||||
});
|
||||
bridge.identity.nickname = f.nickname || uin;
|
||||
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
|
||||
selfResolved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
// Step 1b: friend-list path didn't resolve self → fetch user profile
|
||||
// directly via OIDB 0xFE1_2 so multi-account WebUI shows a nickname
|
||||
// for every injected session, not just the ones where QQ echoed self
|
||||
// back in the friend list.
|
||||
if (!selfResolved && selfUin > 0) {
|
||||
try {
|
||||
const profile = await bridge.apis.contacts.fetchUserProfile(selfUin);
|
||||
bridge.identity.setSelfProfile(profile);
|
||||
bridge.identity.nickname = profile.nickname || uin;
|
||||
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
|
||||
uin, profile.uid, profile.nickname);
|
||||
} catch (e) {
|
||||
log.warn('failed to load self profile for UIN %s: %s',
|
||||
uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Fetch group list
|
||||
let groups: { groupId: number }[] = [];
|
||||
try {
|
||||
groups = await bridge.apis.contacts.fetchGroupList();
|
||||
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
|
||||
} catch (e) {
|
||||
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
// Step 3: Fetch members for each group
|
||||
let loadedGroupCount = 0;
|
||||
let loadedMemberCount = 0;
|
||||
let failedGroupCount = 0;
|
||||
for (const g of groups) {
|
||||
try {
|
||||
const members = await bridge.apis.contacts.fetchGroupMemberList(g.groupId);
|
||||
loadedGroupCount += 1;
|
||||
loadedMemberCount += members.length;
|
||||
if (VERBOSE_WARMUP) {
|
||||
log.debug('members loaded: group=%d count=%d', g.groupId, members.length);
|
||||
}
|
||||
} catch (e) {
|
||||
failedGroupCount += 1;
|
||||
log.warn('failed to load members for group %d: %s', g.groupId, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
log.info(
|
||||
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
|
||||
uin,
|
||||
loadedGroupCount,
|
||||
groups.length,
|
||||
loadedMemberCount,
|
||||
failedGroupCount,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Side-channel observer that watches every image / record / video
|
||||
// segment emitted by the event converter and writes a row into the
|
||||
// MediaStore so later `get_image` / `get_record` OneBot actions can
|
||||
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { JsonObject } from './types';
|
||||
|
||||
export type MediaType = 'image' | 'record' | 'video';
|
||||
|
||||
export class MediaIndexer {
|
||||
constructor(private readonly mediaStore: MediaStore) { }
|
||||
|
||||
remember(
|
||||
mediaType: MediaType,
|
||||
element: MessageElement,
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): void {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
|
||||
if (mediaType === 'image') {
|
||||
this.mediaStore.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileId ?? '',
|
||||
subType: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
imageUrl: element.imageUrl ?? '',
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
width: element.width,
|
||||
height: element.height,
|
||||
picFormat: element.picFormat,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (mediaType === 'record') {
|
||||
this.mediaStore.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
voiceFormat: element.voiceFormat,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// video
|
||||
this.mediaStore.rememberVideo({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
width: element.width,
|
||||
height: element.height,
|
||||
videoFormat: element.videoFormat,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// Persistent media metadata store.
|
||||
//
|
||||
// The `get_image` / `get_record` actions need to map a `data.file` (or related
|
||||
// identifier) we previously emitted in a message segment back to the URL,
|
||||
// size, name, and any OIDB media-node info needed to re-resolve a stale URL.
|
||||
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
|
||||
export interface CachedImage {
|
||||
/** Primary `data.file` value as exposed in the OneBot segment. */
|
||||
file: string;
|
||||
/** Last known resolved URL (may be empty if resolution failed). */
|
||||
url: string;
|
||||
fileSize: number;
|
||||
fileName: string;
|
||||
subType: number;
|
||||
summary: string;
|
||||
/** Conversation the media originated from. */
|
||||
isGroup: boolean;
|
||||
sessionId: number;
|
||||
/** Original imageUrl from the MessageElement, used for RKey re-appending. */
|
||||
imageUrl: string;
|
||||
/** Fingerprints used for md5/sha1 fast-upload on forward. Optional because
|
||||
* legacy CustomFace / NotOnlineImage only carry md5. */
|
||||
md5Hex?: string;
|
||||
sha1Hex?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
picFormat?: number;
|
||||
}
|
||||
|
||||
export interface CachedRecord {
|
||||
/** Primary `data.file` value as exposed in the OneBot segment. */
|
||||
file: string;
|
||||
/** Raw fileId from the MessageElement (typically the fileUuid). */
|
||||
fileId: string;
|
||||
/** Last known resolved URL (may be empty if resolution failed). */
|
||||
url: string;
|
||||
fileSize: number;
|
||||
fileName: string;
|
||||
duration: number;
|
||||
fileHash: string;
|
||||
/** OIDB media node used to re-fetch the URL via getPtt*UrlByNode. */
|
||||
mediaNode?: MessageElement['mediaNode'];
|
||||
/** Conversation the media originated from (group vs private path). */
|
||||
isGroup: boolean;
|
||||
sessionId: number;
|
||||
/** Fingerprints used for md5/sha1 fast-upload on forward. */
|
||||
md5Hex?: string;
|
||||
sha1Hex?: string;
|
||||
voiceFormat?: number;
|
||||
}
|
||||
|
||||
export interface CachedVideo {
|
||||
file: string;
|
||||
fileId: string;
|
||||
url: string;
|
||||
fileSize: number;
|
||||
fileName: string;
|
||||
duration: number;
|
||||
fileHash: string;
|
||||
mediaNode?: MessageElement['mediaNode'];
|
||||
isGroup: boolean;
|
||||
sessionId: number;
|
||||
/** Fingerprints used for md5/sha1 fast-upload on forward. */
|
||||
md5Hex?: string;
|
||||
sha1Hex?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
videoFormat?: number;
|
||||
}
|
||||
|
||||
const TYPE_IMAGE = 'image';
|
||||
const TYPE_RECORD = 'record';
|
||||
const TYPE_VIDEO = 'video';
|
||||
const DEFAULT_KEEP_ENTRIES = 4096;
|
||||
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly maxEntriesPerType: number;
|
||||
|
||||
// Prepared statements (pay the parsing cost once at startup).
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntryByKey: StatementSync;
|
||||
private readonly findEntryByPrimary: StatementSync;
|
||||
private readonly evictByType: StatementSync;
|
||||
private readonly purgeOrphanKeys: StatementSync;
|
||||
private readonly countByType: StatementSync;
|
||||
|
||||
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
|
||||
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
|
||||
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.upsertEntry = this.db.prepare(
|
||||
`INSERT INTO media_entries (type, primary_key, data, last_seen)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(type, primary_key) DO UPDATE SET
|
||||
data = excluded.data,
|
||||
last_seen = excluded.last_seen`,
|
||||
);
|
||||
this.upsertKey = this.db.prepare(
|
||||
`INSERT INTO media_keys (type, key, primary_key)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key`,
|
||||
);
|
||||
this.findEntryByKey = this.db.prepare(
|
||||
`SELECT e.data FROM media_entries e
|
||||
JOIN media_keys k ON k.type = e.type AND k.primary_key = e.primary_key
|
||||
WHERE k.type = ? AND k.key = ?
|
||||
LIMIT 1`,
|
||||
);
|
||||
this.findEntryByPrimary = this.db.prepare(
|
||||
`SELECT data FROM media_entries WHERE type = ? AND primary_key = ?`,
|
||||
);
|
||||
this.evictByType = this.db.prepare(
|
||||
// `rowid DESC` makes the tiebreaker match insertion order (newest first)
|
||||
// so reproducible inserts within the same `last_seen` second still get
|
||||
// the most recent rows retained, regardless of how the lexicographic
|
||||
// sort would have ordered the synthetic primary_key.
|
||||
`DELETE FROM media_entries WHERE type = ? AND rowid IN (
|
||||
SELECT rowid FROM media_entries
|
||||
WHERE type = ?
|
||||
ORDER BY last_seen DESC, rowid DESC
|
||||
LIMIT -1 OFFSET ?
|
||||
)`,
|
||||
);
|
||||
this.purgeOrphanKeys = this.db.prepare(
|
||||
`DELETE FROM media_keys WHERE type = ? AND primary_key NOT IN (
|
||||
SELECT primary_key FROM media_entries WHERE type = ?
|
||||
)`,
|
||||
);
|
||||
this.countByType = this.db.prepare(
|
||||
`SELECT COUNT(*) AS n FROM media_entries WHERE type = ?`,
|
||||
);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
|
||||
rememberImage(info: CachedImage): void {
|
||||
const primaryKey = pickPrimary([info.file, info.fileName]);
|
||||
if (!primaryKey) return;
|
||||
this.upsertWithAliases(TYPE_IMAGE, primaryKey, info, [info.file, info.fileName, info.url]);
|
||||
}
|
||||
|
||||
rememberRecord(info: CachedRecord): void {
|
||||
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
|
||||
if (!primaryKey) return;
|
||||
this.upsertWithAliases(TYPE_RECORD, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
}
|
||||
|
||||
rememberVideo(info: CachedVideo): void {
|
||||
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
|
||||
if (!primaryKey) return;
|
||||
this.upsertWithAliases(TYPE_VIDEO, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
}
|
||||
|
||||
findImage(key: string): CachedImage | null {
|
||||
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
|
||||
}
|
||||
|
||||
findRecord(key: string): CachedRecord | null {
|
||||
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
|
||||
}
|
||||
|
||||
findVideo(key: string): CachedVideo | null {
|
||||
return this.findByAnyKey<CachedVideo>(TYPE_VIDEO, key);
|
||||
}
|
||||
|
||||
updateImageUrl(key: string, url: string): void {
|
||||
if (!url) return;
|
||||
const cached = this.findImage(key);
|
||||
if (!cached || cached.url === url) return;
|
||||
this.rememberImage({ ...cached, url });
|
||||
}
|
||||
|
||||
updateRecordUrl(key: string, url: string): void {
|
||||
if (!url) return;
|
||||
const cached = this.findRecord(key);
|
||||
if (!cached || cached.url === url) return;
|
||||
this.rememberRecord({ ...cached, url });
|
||||
}
|
||||
|
||||
updateVideoUrl(key: string, url: string): void {
|
||||
if (!url) return;
|
||||
const cached = this.findVideo(key);
|
||||
if (!cached || cached.url === url) return;
|
||||
this.rememberVideo({ ...cached, url });
|
||||
}
|
||||
|
||||
/** Snapshot count of distinct entries per type; mostly used by tests. */
|
||||
size(): { images: number; records: number; videos: number } {
|
||||
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
|
||||
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
|
||||
const vid = this.countByType.get(TYPE_VIDEO) as { n: number } | undefined;
|
||||
return { images: img?.n ?? 0, records: rec?.n ?? 0, videos: vid?.n ?? 0 };
|
||||
}
|
||||
|
||||
// --- internals ---
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS media_entries (
|
||||
type TEXT NOT NULL,
|
||||
primary_key TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL,
|
||||
PRIMARY KEY (type, primary_key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_media_entries_lastseen
|
||||
ON media_entries(type, last_seen DESC);
|
||||
CREATE TABLE IF NOT EXISTS media_keys (
|
||||
type TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
primary_key TEXT NOT NULL,
|
||||
PRIMARY KEY (type, key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_media_keys_primary
|
||||
ON media_keys(type, primary_key);
|
||||
`);
|
||||
}
|
||||
|
||||
private upsertWithAliases<T>(
|
||||
type: string,
|
||||
primaryKey: string,
|
||||
info: T,
|
||||
aliases: (string | undefined)[],
|
||||
): void {
|
||||
const data = JSON.stringify(info);
|
||||
const lastSeen = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Run the writes in a transaction so concurrent readers always see a
|
||||
// consistent (entry, keys) pair.
|
||||
this.db.exec('BEGIN');
|
||||
try {
|
||||
this.upsertEntry.run(type, primaryKey, data, lastSeen);
|
||||
const seen = new Set<string>();
|
||||
for (const raw of aliases) {
|
||||
if (!raw) continue;
|
||||
if (seen.has(raw)) continue;
|
||||
seen.add(raw);
|
||||
this.upsertKey.run(type, raw, primaryKey);
|
||||
}
|
||||
this.db.exec('COMMIT');
|
||||
} catch (err) {
|
||||
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Eager eviction. The DELETE is a no-op when row count <= cap so
|
||||
// there is no measurable cost while we are below the limit.
|
||||
this.evictOldEntries(type);
|
||||
}
|
||||
|
||||
private findByAnyKey<T>(type: string, key: string): T | null {
|
||||
if (!key) return null;
|
||||
const row = this.findEntryByKey.get(type, key) as { data: string } | undefined;
|
||||
if (row?.data) return safeParse<T>(row.data);
|
||||
// Fall back to looking up by primary_key directly so callers that pass
|
||||
// the canonical identifier still hit (e.g. when the alias index is yet
|
||||
// to be built for that key in this session).
|
||||
const fallback = this.findEntryByPrimary.get(type, key) as { data: string } | undefined;
|
||||
return fallback?.data ? safeParse<T>(fallback.data) : null;
|
||||
}
|
||||
|
||||
private evictOldEntries(type: string): void {
|
||||
try {
|
||||
this.evictByType.run(type, type, this.maxEntriesPerType);
|
||||
this.purgeOrphanKeys.run(type, type);
|
||||
} catch {
|
||||
// Best-effort eviction; don't propagate.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pickPrimary(candidates: (string | undefined)[]): string {
|
||||
for (const c of candidates) {
|
||||
if (c && c.length > 0) return c;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function safeParse<T>(json: string): T | null {
|
||||
try {
|
||||
return JSON.parse(json) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
import type { RKeyCache } from './instance-rkey';
|
||||
|
||||
export class MediaUrlResolver {
|
||||
constructor(
|
||||
private readonly bridge: BridgeInterface,
|
||||
private readonly rkeyCache: RKeyCache,
|
||||
) { }
|
||||
|
||||
async resolve(element: MessageElement, isGroup: boolean, sessionId: number): Promise<string> {
|
||||
if (!element.url) {
|
||||
try {
|
||||
await this.populateUrl(element, isGroup, sessionId);
|
||||
} catch {
|
||||
// Best-effort: a URL fetch hiccup should never block the
|
||||
// outgoing segment. The RKey pass below still runs.
|
||||
}
|
||||
}
|
||||
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
|
||||
}
|
||||
|
||||
/** Branches by element.type + isGroup to pick the right Bridge API.
|
||||
* Mutates `element.url` in-place so the caller sees the same URL
|
||||
* the downstream rkey/media-store path will see. */
|
||||
private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise<void> {
|
||||
if (element.type === 'file' && element.fileId) {
|
||||
if (isGroup) {
|
||||
element.url = await this.bridge.apis.groupFile.getUrl(sessionId, element.fileId);
|
||||
} else if (element.fileHash) {
|
||||
element.url = await this.bridge.apis.groupFile.getPrivateUrl(sessionId, element.fileId, element.fileHash);
|
||||
} else {
|
||||
element.url = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
|
||||
if (isGroup) {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.apis.groupFile.getPttUrl(sessionId, element.mediaNode)
|
||||
: await this.bridge.apis.groupFile.getVideoUrl(sessionId, element.mediaNode);
|
||||
} else {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.apis.groupFile.getPrivatePttUrl(element.mediaNode)
|
||||
: await this.bridge.apis.groupFile.getPrivateVideoUrl(element.mediaNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
export const GROUP_MESSAGE_EVENT = 'group_message';
|
||||
export const PRIVATE_MESSAGE_EVENT = 'private_message';
|
||||
|
||||
export function hashMessageIdInt32(sequence: number, sessionId: number, eventName: string): number {
|
||||
const seq = Number.isFinite(sequence) ? Math.trunc(sequence) : 0;
|
||||
const session = Number.isFinite(sessionId) ? Math.trunc(sessionId) : 0;
|
||||
const key = `${seq}:${session}:${eventName}`;
|
||||
const digest = createHash('sha1').update(key).digest();
|
||||
|
||||
let id = digest.readInt32BE(0);
|
||||
if (id === 0) id = 1;
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { JsonValue } from './types';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
|
||||
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
|
||||
musicSignUrl?: string;
|
||||
}
|
||||
|
||||
// --- CQ Code parsing ---
|
||||
|
||||
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
|
||||
|
||||
/**
|
||||
* Best-effort base-10 integer coercion. Falls back to `fallback` (default 0)
|
||||
* when the input can't be parsed as a finite integer — `parseInt('abc')`
|
||||
* is `NaN`, which silently turns into `0`/`null` further down the wire
|
||||
* pipeline and produces undebuggable protocol-level failures.
|
||||
*/
|
||||
function intOr(value: unknown, fallback = 0): number {
|
||||
if (value === undefined || value === null) return fallback;
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
|
||||
const n = parseInt(String(value), 10);
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
function parseCQParams(raw: string): Record<string, string> {
|
||||
const params: Record<string, string> = {};
|
||||
if (!raw) return params;
|
||||
for (const pair of raw.split(',')) {
|
||||
const eq = pair.indexOf('=');
|
||||
if (eq > 0) {
|
||||
params[pair.substring(0, eq)] = pair.substring(eq + 1)
|
||||
.replace(/[/g, '[')
|
||||
.replace(/]/g, ']')
|
||||
.replace(/,/g, ',')
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
function cqUnescape(text: string): string {
|
||||
// Order matters: `&` MUST be last so that, e.g., `&#91;` keeps
|
||||
// the literal `[` instead of decoding twice into `[`.
|
||||
return text
|
||||
.replace(/[/g, '[')
|
||||
.replace(/]/g, ']')
|
||||
.replace(/,/g, ',')
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise<MessageElement[]> {
|
||||
const elements: MessageElement[] = [];
|
||||
let lastIndex = 0;
|
||||
|
||||
for (const match of message.matchAll(CQ_REGEX)) {
|
||||
// Text before this CQ code
|
||||
if (match.index! > lastIndex) {
|
||||
const text = cqUnescape(message.substring(lastIndex, match.index!));
|
||||
if (text) elements.push({ type: 'text', text });
|
||||
}
|
||||
lastIndex = match.index! + match[0].length;
|
||||
|
||||
const cqType = match[1];
|
||||
const params = parseCQParams(match[2] || '');
|
||||
const elem = await segmentToElement(cqType, params, options);
|
||||
if (elem) elements.push(elem);
|
||||
}
|
||||
|
||||
// Trailing text
|
||||
if (lastIndex < message.length) {
|
||||
const text = cqUnescape(message.substring(lastIndex));
|
||||
if (text) elements.push({ type: 'text', text });
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
// --- JSON segment parsing ---
|
||||
|
||||
interface MessageSegment {
|
||||
type: string;
|
||||
data?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function isSegmentArray(val: unknown): val is MessageSegment[] {
|
||||
return Array.isArray(val) && val.every(
|
||||
(item) => typeof item === 'object' && item !== null && 'type' in item
|
||||
);
|
||||
}
|
||||
|
||||
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
||||
const normalizedType = type.toLowerCase();
|
||||
switch (normalizedType) {
|
||||
case 'text': {
|
||||
const text = String(data.text ?? '');
|
||||
return text ? { type: 'text', text } : null;
|
||||
}
|
||||
case 'face': {
|
||||
const id = intOr(data.id, -1);
|
||||
if (id < 0) return null;
|
||||
return { type: 'face', faceId: id };
|
||||
}
|
||||
case 'at': {
|
||||
const qq = String(data.qq ?? '').trim();
|
||||
if (qq === 'all') {
|
||||
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
||||
}
|
||||
const uin = intOr(qq, 0);
|
||||
if (uin <= 0) return null;
|
||||
|
||||
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
|
||||
let uid = String(data.uid ?? '').trim();
|
||||
if (!uid && options?.resolveMentionUid) {
|
||||
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
|
||||
}
|
||||
|
||||
// Leave `text` undefined when the caller didn't supply a display
|
||||
// name. The element-builder then resolves it from the group roster
|
||||
// (so QQ renders `@昵称` instead of `@QQ号`).
|
||||
const element: MessageElement = { type: 'at', targetUin: uin };
|
||||
if (uid) element.uid = uid;
|
||||
if (name) element.text = `@${name} `;
|
||||
return element;
|
||||
}
|
||||
case 'reply': {
|
||||
const id = intOr(data.id, 0);
|
||||
if (id === 0) return null;
|
||||
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
if (typeof resolved === 'number' && resolved > 0) {
|
||||
const element: MessageElement = {
|
||||
type: 'reply',
|
||||
replySeq: resolved,
|
||||
replyMessageId: id // Keep the original messageId for logging
|
||||
};
|
||||
|
||||
// Try to get additional meta info for better reply display
|
||||
if (options?.resolveReplyMeta) {
|
||||
const meta = options.resolveReplyMeta(id);
|
||||
if (meta) {
|
||||
element.replySenderUin = meta.senderUin;
|
||||
element.replyTime = meta.time;
|
||||
element.replyRandom = meta.random;
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
// Backward-compatible path: allow direct seq reply IDs.
|
||||
return id > 0 ? { type: 'reply', replySeq: id } : null;
|
||||
}
|
||||
case 'image': {
|
||||
return {
|
||||
type: 'image',
|
||||
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
|
||||
flash: data.type === 'flash',
|
||||
subType: intOr(data.subType, 0),
|
||||
summary: data.summary ? String(data.summary) : undefined,
|
||||
};
|
||||
}
|
||||
case 'record': {
|
||||
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
|
||||
if (!source) return null;
|
||||
return {
|
||||
type: 'record',
|
||||
url: source,
|
||||
};
|
||||
}
|
||||
case 'video': {
|
||||
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
|
||||
if (!source) return null;
|
||||
return {
|
||||
type: 'video',
|
||||
url: source,
|
||||
thumbUrl: data.thumb ? String(data.thumb) : undefined,
|
||||
};
|
||||
}
|
||||
case 'json': {
|
||||
return {
|
||||
type: 'json',
|
||||
text: String(data.data ?? ''),
|
||||
};
|
||||
}
|
||||
case 'xml': {
|
||||
return {
|
||||
type: 'xml',
|
||||
text: String(data.data ?? ''),
|
||||
subType: intOr(data.id, 0),
|
||||
};
|
||||
}
|
||||
case 'poke': {
|
||||
return {
|
||||
type: 'poke',
|
||||
faceId: intOr(data.type ?? data.id, 0),
|
||||
};
|
||||
}
|
||||
case 'forward': {
|
||||
return {
|
||||
type: 'forward',
|
||||
resId: String(data.id ?? ''),
|
||||
};
|
||||
}
|
||||
case 'node': {
|
||||
// Fake forward node segment — store the raw data for later processing
|
||||
// The content field may be a segment array, a single segment, or a CQ string
|
||||
const name = String(data.nickname ?? data.name ?? '');
|
||||
return {
|
||||
type: 'node',
|
||||
targetUin: intOr(data.user_id ?? data.uin, 0),
|
||||
text: name,
|
||||
// Raw content is stored as JSON string in resId for later processing
|
||||
resId: JSON.stringify(data.content ?? ''),
|
||||
};
|
||||
}
|
||||
case 'markdown': {
|
||||
return {
|
||||
type: 'markdown',
|
||||
text: String(data.content ?? ''),
|
||||
};
|
||||
}
|
||||
case 'share': {
|
||||
// Link share — map to json card message
|
||||
const url = String(data.url ?? '');
|
||||
const title = String(data.title ?? '');
|
||||
const content = String(data.content ?? '');
|
||||
const image = String(data.image ?? '');
|
||||
const jsonData = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
view: 'news',
|
||||
prompt: title,
|
||||
meta: { news: { title, desc: content, jumpUrl: url, preview: image } },
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
}
|
||||
case 'music': {
|
||||
// Music share — uses external signing service (NapCat-compatible)
|
||||
const musicType = String(data.type ?? '');
|
||||
const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card';
|
||||
try {
|
||||
let postData: Record<string, unknown>;
|
||||
if (musicType === 'custom') {
|
||||
postData = {
|
||||
type: 'custom',
|
||||
id: undefined,
|
||||
url: String(data.url ?? ''),
|
||||
audio: String(data.audio ?? ''),
|
||||
title: String(data.title ?? ''),
|
||||
image: String(data.image ?? ''),
|
||||
singer: String(data.content ?? ''),
|
||||
};
|
||||
} else {
|
||||
postData = { type: musicType, id: String(data.id ?? '') };
|
||||
}
|
||||
const resp = await fetch(signUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(postData),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`music sign HTTP ${resp.status}`);
|
||||
const musicJson = await resp.text();
|
||||
return { type: 'json', text: musicJson };
|
||||
} catch (e) {
|
||||
log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e));
|
||||
// Fallback: build a basic card locally
|
||||
const title = String(data.title ?? 'Music');
|
||||
const jsonData = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
view: 'music',
|
||||
prompt: `[音乐]${title}`,
|
||||
meta: {
|
||||
music: {
|
||||
title,
|
||||
desc: String(data.content ?? ''),
|
||||
jumpUrl: String(data.url ?? ''),
|
||||
musicUrl: String(data.audio ?? ''),
|
||||
preview: String(data.image ?? ''),
|
||||
},
|
||||
},
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
}
|
||||
}
|
||||
case 'location': {
|
||||
// Location — map to json card
|
||||
const lat = String(data.lat ?? '');
|
||||
const lon = String(data.lon ?? '');
|
||||
const title = String(data.title ?? '位置');
|
||||
const content = String(data.content ?? `${lat},${lon}`);
|
||||
const jsonData = JSON.stringify({
|
||||
app: 'com.tencent.map',
|
||||
view: 'LocationShare',
|
||||
prompt: `[位置]${title}`,
|
||||
meta: { Location: { lat, lng: lon, title, address: content } },
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
}
|
||||
case 'contact': {
|
||||
// Contact card — map to json card
|
||||
const contactType = String(data.type ?? 'qq');
|
||||
const contactId = String(data.id ?? '');
|
||||
const jsonData = JSON.stringify({
|
||||
app: 'com.tencent.contact.lua',
|
||||
view: 'contact',
|
||||
prompt: `[推荐${contactType === 'group' ? '群' : '好友'}]`,
|
||||
meta: { contact: { type: contactType, id: contactId } },
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
}
|
||||
case 'rps': {
|
||||
// Rock-paper-scissors — map to dice-like face
|
||||
return { type: 'face', faceId: 359 };
|
||||
}
|
||||
case 'dice': {
|
||||
// Dice — map to dice face
|
||||
return { type: 'face', faceId: 358 };
|
||||
}
|
||||
case 'shake': {
|
||||
// Window shake — map to poke
|
||||
return { type: 'poke', faceId: 1 };
|
||||
}
|
||||
case 'anonymous': {
|
||||
// Anonymous flag — ignored during send, the protocol handles anonymity
|
||||
return null;
|
||||
}
|
||||
case 'file': {
|
||||
// OneBot11 file segment referencing a previously-uploaded file
|
||||
// (returned by `upload_group_file` / `upload_private_file`).
|
||||
// We deliberately do NOT support `{file: '/path'}` here because
|
||||
// the upload pipeline is async and lives behind the bridge —
|
||||
// the element-builder runs synchronously over the parsed
|
||||
// message. Callers that want upload-and-send should use the
|
||||
// dedicated `upload_*` actions which now publish the file in
|
||||
// chat atomically (`actions/group-file.ts`).
|
||||
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
|
||||
if (!fileId) {
|
||||
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
|
||||
return null;
|
||||
}
|
||||
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
|
||||
const fileSize = intOr(data.size ?? data.fileSize, 0);
|
||||
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
|
||||
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
||||
// file_hash is the c2c-file server-issued addon string — needed
|
||||
// on the wire when re-sending a previously-uploaded c2c file.
|
||||
// get_private_file_url callers already pass it through, so honour
|
||||
// the same field naming here.
|
||||
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
|
||||
const elem: MessageElement = { type: 'file', fileId };
|
||||
if (fileName) elem.fileName = fileName;
|
||||
if (fileSize > 0) elem.fileSize = fileSize;
|
||||
if (md5Hex) elem.md5Hex = md5Hex;
|
||||
if (sha1Hex) elem.sha1Hex = sha1Hex;
|
||||
if (fileHash) elem.fileHash = fileHash;
|
||||
return elem;
|
||||
}
|
||||
default:
|
||||
console.warn(`[MsgParser] unsupported segment type: ${type}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
const topLevel = { ...seg } as Record<string, unknown>;
|
||||
delete topLevel.type;
|
||||
delete topLevel.data;
|
||||
const nested = (seg.data && typeof seg.data === 'object' && !Array.isArray(seg.data))
|
||||
? seg.data
|
||||
: {};
|
||||
return { ...topLevel, ...nested };
|
||||
}
|
||||
|
||||
// --- Public API ---
|
||||
|
||||
/**
|
||||
* Parse an OneBot11 message value into internal MessageElement array.
|
||||
* Supports:
|
||||
* - string (plain text or CQ code string)
|
||||
* - array of { type, data } segments (JSON segment format)
|
||||
*
|
||||
* If autoEscape is true, the string is treated as plain text (no CQ parsing).
|
||||
*/
|
||||
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
|
||||
if (typeof message === 'string') {
|
||||
if (autoEscape) {
|
||||
return message ? [{ type: 'text', text: message }] : [];
|
||||
}
|
||||
return parseFromCQString(message, options);
|
||||
}
|
||||
|
||||
if (isSegmentArray(message)) {
|
||||
const elements: MessageElement[] = [];
|
||||
for (const seg of message) {
|
||||
const data = segmentPayload(seg);
|
||||
const elem = await segmentToElement(seg.type, data, options);
|
||||
if (elem) elements.push(elem);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
// Single segment object
|
||||
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
|
||||
const seg = message as unknown as MessageSegment;
|
||||
if (seg.type) {
|
||||
const data = segmentPayload(seg);
|
||||
const elem = await segmentToElement(seg.type, data, options);
|
||||
return elem ? [elem] : [];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: DatabaseSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
// Replace .json extension with .db if present
|
||||
const finalPath = dbPath.replace(/\.json$/, '.db');
|
||||
this.db = new DatabaseSync(finalPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
|
||||
storeEvent(
|
||||
messageId: number,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
event: JsonObject
|
||||
): void {
|
||||
if (!isValidMessageId(messageId)) return;
|
||||
const json = JSON.stringify(event);
|
||||
const timestamp = toInt(event.time);
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
|
||||
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
sequence = excluded.sequence,
|
||||
event_name = excluded.event_name,
|
||||
timestamp = excluded.timestamp,
|
||||
data = excluded.data`
|
||||
).run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json);
|
||||
}
|
||||
|
||||
storeMeta(messageId: number, meta: MessageMeta): void {
|
||||
if (!isValidMessageId(messageId)) return;
|
||||
this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
sequence = excluded.sequence,
|
||||
event_name = excluded.event_name,
|
||||
client_sequence = excluded.client_sequence,
|
||||
random = excluded.random,
|
||||
timestamp = excluded.timestamp`
|
||||
).run(
|
||||
messageId,
|
||||
meta.isGroup ? 1 : 0,
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
meta.eventName,
|
||||
meta.clientSequence,
|
||||
meta.random,
|
||||
meta.timestamp
|
||||
);
|
||||
}
|
||||
|
||||
findEvent(messageId: number): JsonObject | null {
|
||||
if (!isValidMessageId(messageId)) return null;
|
||||
const row = this.db.prepare(
|
||||
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
|
||||
).get(messageId) as { data: string } | undefined;
|
||||
|
||||
if (!row?.data) return null;
|
||||
try {
|
||||
return JSON.parse(row.data) as JsonObject;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
findMeta(messageId: number): MessageMeta | null {
|
||||
if (!isValidMessageId(messageId)) return null;
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
|
||||
).get(messageId) as {
|
||||
is_group: number;
|
||||
session_id: number;
|
||||
sequence: number;
|
||||
event_name: string;
|
||||
client_sequence: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
} | undefined;
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
return {
|
||||
isGroup: row.is_group === 1,
|
||||
targetId: row.session_id,
|
||||
sequence: row.sequence,
|
||||
eventName: row.event_name,
|
||||
clientSequence: row.client_sequence,
|
||||
random: row.random,
|
||||
timestamp: row.timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
|
||||
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// For private messages, we cannot rely on session_id matching because:
|
||||
// - When receiving: session_id is the sender's UIN
|
||||
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
|
||||
// So for private messages, we only match by message_hash and is_group flag.
|
||||
const row = isGroup
|
||||
? this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(sessionId, messageId) as { sequence: number } | undefined
|
||||
: this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(messageId) as { sequence: number } | undefined;
|
||||
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
|
||||
return null;
|
||||
}
|
||||
return row.sequence;
|
||||
}
|
||||
|
||||
listSessionEvents(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
count = 20,
|
||||
anchorSequence?: number,
|
||||
): JsonObject[] {
|
||||
if (!Number.isInteger(sessionId) || sessionId <= 0) return [];
|
||||
|
||||
const limit = normalizePositiveInt(count, 20, 200);
|
||||
const hasAnchor = Number.isInteger(anchorSequence) && (anchorSequence as number) > 0;
|
||||
const anchor = hasAnchor ? (anchorSequence as number) : 0;
|
||||
|
||||
const rows = hasAnchor
|
||||
? this.db.prepare(
|
||||
`SELECT data
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ?
|
||||
ORDER BY sequence DESC
|
||||
LIMIT ?`
|
||||
).all(isGroup ? 1 : 0, sessionId, anchor, limit)
|
||||
: this.db.prepare(
|
||||
`SELECT data
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
|
||||
ORDER BY sequence DESC
|
||||
LIMIT ?`
|
||||
).all(isGroup ? 1 : 0, sessionId, limit);
|
||||
|
||||
const result: JsonObject[] = [];
|
||||
for (const row of rows as Array<{ data: string }>) {
|
||||
if (!row?.data) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(row.data) as JsonObject;
|
||||
result.push(parsed);
|
||||
} catch {
|
||||
// Ignore malformed rows to avoid breaking history APIs.
|
||||
}
|
||||
}
|
||||
|
||||
// Keep chronological order (oldest -> newest) for API consumers.
|
||||
result.reverse();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
message_hash INTEGER PRIMARY KEY,
|
||||
is_group INTEGER NOT NULL,
|
||||
session_id INTEGER NOT NULL,
|
||||
sequence INTEGER NOT NULL,
|
||||
event_name TEXT NOT NULL,
|
||||
client_sequence INTEGER NOT NULL DEFAULT 0,
|
||||
random INTEGER NOT NULL DEFAULT 0,
|
||||
timestamp INTEGER NOT NULL DEFAULT 0,
|
||||
data TEXT
|
||||
)
|
||||
`);
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
|
||||
}
|
||||
}
|
||||
|
||||
function isValidMessageId(messageId: number): boolean {
|
||||
return Number.isInteger(messageId) && messageId !== 0;
|
||||
}
|
||||
|
||||
function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return Math.trunc(parsed);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function normalizePositiveInt(value: number, fallback: number, max: number): number {
|
||||
if (!Number.isFinite(value)) return fallback;
|
||||
const n = Math.trunc(value);
|
||||
if (n <= 0) return fallback;
|
||||
if (n > max) return max;
|
||||
return n;
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { IdentityService } from '@snowluma/bridge/identity-service';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
|
||||
const userId = parseInt(ref.uin, 10) || 0;
|
||||
const nickname = ref.bridge.identity.nickname || ref.uin;
|
||||
return { userId, nickname };
|
||||
}
|
||||
|
||||
// Keep refreshes scoped. A broad "refresh all members in all groups" call can
|
||||
// turn one OneBot request into N OIDB calls, which is risky for busy clients.
|
||||
async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise<void> {
|
||||
try {
|
||||
await bridge.apis.contacts.fetchGroupMemberList(groupId);
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
}
|
||||
|
||||
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
try {
|
||||
const friends = await bridge.apis.contacts.fetchFriendList();
|
||||
return friends.map(f => ({
|
||||
user_id: f.uin as any,
|
||||
nickname: f.nickname as any,
|
||||
remark: f.remark as any,
|
||||
}));
|
||||
} catch {
|
||||
return bridge.identity.friends.map(f => ({
|
||||
user_id: f.uin as any,
|
||||
nickname: f.nickname as any,
|
||||
remark: f.remark as any,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupList(
|
||||
bridge: BridgeInterface,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject[]> {
|
||||
try {
|
||||
if (noCache || bridge.identity.groups.length === 0) {
|
||||
await bridge.apis.contacts.fetchGroupList();
|
||||
}
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
return bridge.identity.groups.map(g => ({
|
||||
group_id: g.groupId as any,
|
||||
group_name: g.groupName as any,
|
||||
member_count: g.memberCount as any,
|
||||
max_member_count: g.memberMax as any,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getGroupInfo(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject | null> {
|
||||
if (noCache || !bridge.identity.findGroup(groupId)) {
|
||||
try {
|
||||
await bridge.apis.contacts.fetchGroupList();
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
}
|
||||
const g = bridge.identity.findGroup(groupId);
|
||||
if (!g) return null;
|
||||
return {
|
||||
group_id: g.groupId as any,
|
||||
group_name: g.groupName as any,
|
||||
member_count: g.memberCount as any,
|
||||
max_member_count: g.memberMax as any,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getGroupMemberList(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject[]> {
|
||||
if (noCache) {
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
return getCachedGroupMembers(bridge.identity, groupId);
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await bridge.apis.contacts.fetchGroupMemberList(groupId);
|
||||
return members.map(m => formatGroupMember(groupId, m));
|
||||
} catch {
|
||||
return getCachedGroupMembers(bridge.identity, groupId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupMemberInfo(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
userId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject | null> {
|
||||
if (noCache || !bridge.identity.findGroupMember(groupId, userId)) {
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
}
|
||||
const m = bridge.identity.findGroupMember(groupId, userId);
|
||||
if (!m) return null;
|
||||
return formatGroupMember(groupId, m);
|
||||
}
|
||||
|
||||
export async function getGroupFiles(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
folderId?: string,
|
||||
): Promise<JsonObject> {
|
||||
const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/');
|
||||
return {
|
||||
files: result.files.map((file) => ({
|
||||
group_id: groupId as any,
|
||||
file_id: file.fileId as any,
|
||||
file_name: file.fileName as any,
|
||||
busid: file.busId as any,
|
||||
file_size: file.fileSize as any,
|
||||
upload_time: file.uploadTime as any,
|
||||
dead_time: file.deadTime as any,
|
||||
modify_time: file.modifyTime as any,
|
||||
download_times: file.downloadTimes as any,
|
||||
uploader: file.uploader as any,
|
||||
uploader_name: file.uploaderName as any,
|
||||
} as JsonObject)) as any,
|
||||
folders: result.folders.map((folder) => ({
|
||||
group_id: groupId as any,
|
||||
folder_id: folder.folderId as any,
|
||||
folder_name: folder.folderName as any,
|
||||
create_time: folder.createTime as any,
|
||||
creator: folder.creator as any,
|
||||
create_name: folder.creatorName as any,
|
||||
total_file_count: folder.totalFileCount as any,
|
||||
} as JsonObject)) as any,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getStrangerInfo(
|
||||
bridge: BridgeInterface,
|
||||
userId: number,
|
||||
): Promise<JsonObject | null> {
|
||||
try {
|
||||
const p = await bridge.apis.contacts.fetchUserProfile(userId);
|
||||
return {
|
||||
user_id: p.uin as any,
|
||||
nickname: p.nickname as any,
|
||||
sex: p.sex as any,
|
||||
age: p.age as any,
|
||||
};
|
||||
} catch {
|
||||
const p = bridge.identity.findUserProfile(userId);
|
||||
if (!p) return null;
|
||||
return {
|
||||
user_id: p.uin as any,
|
||||
nickname: p.nickname as any,
|
||||
sex: p.sex as any,
|
||||
age: p.age as any,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
try {
|
||||
const reqs = await bridge.apis.contacts.fetchGroupRequests();
|
||||
return reqs.map(r => ({
|
||||
group_id: r.groupId,
|
||||
group_name: r.groupName,
|
||||
request_id: r.sequence,
|
||||
requester_uin: r.targetUin,
|
||||
requester_nick: r.targetName,
|
||||
message: r.comment,
|
||||
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
|
||||
} as JsonObject));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
try {
|
||||
const rkeys = await bridge.apis.contacts.fetchDownloadRKeys();
|
||||
return rkeys.map(r => ({
|
||||
rkey: r.rkey,
|
||||
type: r.type,
|
||||
ttl: r.ttlSeconds,
|
||||
create_time: r.createTime,
|
||||
} as JsonObject));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function getCachedGroupMembers(identity: IdentityService, groupId: number): JsonObject[] {
|
||||
const g = identity.findGroup(groupId);
|
||||
if (!g) return [];
|
||||
const result: JsonObject[] = [];
|
||||
for (const [, member] of g.members) {
|
||||
result.push(formatGroupMember(groupId, member));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function formatGroupMember(
|
||||
groupId: number,
|
||||
member: {
|
||||
uin: number;
|
||||
nickname: string;
|
||||
card: string;
|
||||
joinTime: number;
|
||||
lastSentTime: number;
|
||||
level: number;
|
||||
role: string;
|
||||
title: string;
|
||||
},
|
||||
): JsonObject {
|
||||
return {
|
||||
group_id: groupId as any,
|
||||
user_id: member.uin as any,
|
||||
nickname: member.nickname as any,
|
||||
card: member.card as any,
|
||||
sex: 'unknown' as any,
|
||||
age: 0 as any,
|
||||
join_time: member.joinTime as any,
|
||||
last_sent_time: member.lastSentTime as any,
|
||||
level: String(member.level) as any,
|
||||
role: member.role as any,
|
||||
title: member.title as any,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
export async function getImageInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
if (!cached) return null;
|
||||
const url = cached.url || cached.imageUrl || '';
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url,
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getRecordInfo(
|
||||
bridge: BridgeInterface,
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findRecord(file);
|
||||
if (!cached) return null;
|
||||
|
||||
// Re-resolve via OIDB if the cached URL is missing or empty.
|
||||
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
|
||||
let url = cached.url;
|
||||
if (!url && cached.mediaNode) {
|
||||
try {
|
||||
url = cached.isGroup
|
||||
? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode)
|
||||
: await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode);
|
||||
if (url) {
|
||||
mediaStore.updateRecordUrl(file, url);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url: url || '',
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,38 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
|
||||
export async function handleGroupAddRequest(
|
||||
bridge: BridgeInterface,
|
||||
flag: string,
|
||||
approve: boolean,
|
||||
reason: string,
|
||||
): Promise<void> {
|
||||
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
|
||||
const parts = flag.split(':');
|
||||
if (parts.length < 3) throw new Error('invalid group request flag');
|
||||
const requestType = parts[0];
|
||||
const groupId = parseInt(parts[1], 10);
|
||||
const targetUid = parts.slice(2).join(':');
|
||||
if (!groupId) throw new Error('invalid group_id in flag');
|
||||
if (!targetUid) throw new Error('invalid request target in flag');
|
||||
|
||||
const requests = await bridge.apis.contacts.fetchGroupRequests();
|
||||
const matching = requests.find((r) => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
if (requestType === 'add') return r.targetUid === targetUid;
|
||||
if (requestType === 'invite') return r.invitorUid === targetUid;
|
||||
return false;
|
||||
}) || requests.find(r => r.groupId === groupId);
|
||||
|
||||
if (!matching) {
|
||||
throw new Error('matching group request not found');
|
||||
}
|
||||
|
||||
await bridge.apis.groupAdmin.setAddRequest(
|
||||
groupId,
|
||||
matching.sequence,
|
||||
matching.eventType,
|
||||
approve,
|
||||
reason,
|
||||
matching.filtered,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { ApiHandler } from '../api-handler';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
|
||||
export interface NetworkAdapterContext {
|
||||
/** Self UIN as string — written into outbound headers. */
|
||||
uin: string;
|
||||
/** Shared API dispatcher used by request/response style adapters. */
|
||||
api: ApiHandler;
|
||||
/** Build a lifecycle event payload (connect/enable/disable). */
|
||||
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
|
||||
/** Build a heartbeat event payload. */
|
||||
buildHeartbeatEvent(): JsonObject;
|
||||
}
|
||||
|
||||
export enum NetworkReloadType {
|
||||
/** Configuration unchanged or only soft fields updated. */
|
||||
Normal = 0,
|
||||
/** Underlying socket/listener restarted in place. */
|
||||
Reopened = 1,
|
||||
/** Was running, now closed. */
|
||||
Closed = 2,
|
||||
/** Was idle, now opened. */
|
||||
Opened = 3,
|
||||
}
|
||||
|
||||
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
readonly name: string;
|
||||
protected config: C;
|
||||
protected readonly ctx: NetworkAdapterContext;
|
||||
protected isEnabled = false;
|
||||
|
||||
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
|
||||
this.name = name;
|
||||
// Defensive copy so reload diffs never mutate the caller's object.
|
||||
this.config = structuredClone(config);
|
||||
this.ctx = ctx;
|
||||
}
|
||||
|
||||
/** Whether the adapter is currently accepting/relaying events. */
|
||||
get isActive(): boolean { return this.isEnabled; }
|
||||
|
||||
/** Snapshot of the active config (read-only). */
|
||||
get currentConfig(): Readonly<C> { return this.config; }
|
||||
|
||||
abstract open(): void | Promise<void>;
|
||||
abstract close(): void | Promise<void>;
|
||||
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
|
||||
|
||||
/**
|
||||
* Receive one fully-shaped OneBot event for forwarding. Adapters that
|
||||
* don't push events (e.g. HTTP request-response servers) override with a
|
||||
* no-op.
|
||||
*/
|
||||
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { HttpClientNetwork, JsonObject } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const moduleLog = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.signature_ = bindingSignature(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.config.enabled === false) return;
|
||||
if (!this.config.url) return;
|
||||
this.isEnabled = true;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.isEnabled = false;
|
||||
}
|
||||
|
||||
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false && !!next.url;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.options = resolveReportOptions(next);
|
||||
const newSig = bindingSignature(next);
|
||||
const sigChanged = newSig !== this.signature_;
|
||||
this.signature_ = newSig;
|
||||
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
if (!this.isEnabled) return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
void this.postEvent(json, event).catch((err) => {
|
||||
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private async postEvent(payload: string, event: JsonObject): Promise<void> {
|
||||
if (!this.isEnabled) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'OneBot',
|
||||
'X-Self-ID': this.ctx.uin,
|
||||
};
|
||||
if (this.config.accessToken) {
|
||||
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
|
||||
}
|
||||
|
||||
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
try {
|
||||
const response = await fetch(this.config.url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: payload,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (contentType.includes('application/json')) {
|
||||
const body = await response.text();
|
||||
if (body.trim()) {
|
||||
await this.handleQuickOperation(event, body);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.isEnabled) {
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
|
||||
try {
|
||||
const operation = JSON.parse(responseBody) as Record<string, unknown>;
|
||||
if (!operation || typeof operation !== 'object') return;
|
||||
await executeQuickOperation(event, operation, this.ctx.api);
|
||||
} catch (error) {
|
||||
this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bindingSignature(net: HttpClientNetwork): string {
|
||||
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
|
||||
}
|
||||
|
||||
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
|
||||
const { createHmac } = await import('crypto');
|
||||
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'http';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
// HTTP server never receives events — `isActive` purely tracks the
|
||||
// bound listener so the network manager can skip dispatch cleanly.
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
if (this.config.enabled === false) return;
|
||||
this.startServer();
|
||||
this.isEnabled = true;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (!this.isEnabled && !this.server) return;
|
||||
this.isEnabled = false;
|
||||
this.server?.close();
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
|
||||
const sigChanged = prevSig !== bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
// HTTP server only acts on inbound requests; it doesn't push events.
|
||||
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
|
||||
|
||||
private startServer(): void {
|
||||
const server = createServer((req, res) => {
|
||||
void this.handleRequest(req, res);
|
||||
});
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
normalizePath(this.config.path ?? '/'),
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
|
||||
}
|
||||
|
||||
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
// Read `path` + `accessToken` fresh from `this.config` on every
|
||||
// request so config hot-reloads (`reload()` overwrites `this.config`
|
||||
// in place) take effect on the very next request without
|
||||
// re-binding the listener. Matches the ws-server / http-post /
|
||||
// ws-client adapters, which all read `this.config.accessToken`
|
||||
// inline at the point of use.
|
||||
const expectedPath = normalizePath(this.config.path ?? '/');
|
||||
const accessToken = this.config.accessToken ?? '';
|
||||
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
|
||||
const incomingPath = parsedUrl.pathname;
|
||||
|
||||
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
|
||||
let action = '';
|
||||
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
|
||||
action = '';
|
||||
} else if (incomingPath.startsWith(ep)) {
|
||||
action = incomingPath.substring(ep.length);
|
||||
} else {
|
||||
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isAuthorized(req, accessToken)) {
|
||||
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && !action) {
|
||||
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let params: Record<string, unknown> = {};
|
||||
let echo: unknown;
|
||||
|
||||
if (req.method === 'GET') {
|
||||
parsedUrl.searchParams.forEach((value, key) => {
|
||||
try {
|
||||
params[key] = JSON.parse(value);
|
||||
} catch {
|
||||
params[key] = value;
|
||||
}
|
||||
});
|
||||
} else if (req.method === 'POST') {
|
||||
const bodyContent = await readRequestBody(req);
|
||||
if (bodyContent.trim()) {
|
||||
const contentType = req.headers['content-type'] ?? '';
|
||||
if (contentType.includes('application/x-www-form-urlencoded')) {
|
||||
const parsed = new URLSearchParams(bodyContent);
|
||||
parsed.forEach((value, key) => {
|
||||
try {
|
||||
params[key] = JSON.parse(value);
|
||||
} catch {
|
||||
params[key] = value;
|
||||
}
|
||||
});
|
||||
if (params.action && !action) {
|
||||
action = String(params.action);
|
||||
delete params.action;
|
||||
}
|
||||
if (params.echo !== undefined) {
|
||||
echo = params.echo;
|
||||
delete params.echo;
|
||||
}
|
||||
} else if (contentType.includes('application/json') || !contentType) {
|
||||
try {
|
||||
const parsedBody = JSON.parse(bodyContent);
|
||||
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||||
if (parsedBody.action && !action) action = String(parsedBody.action);
|
||||
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
|
||||
params = parsedBody.params as Record<string, unknown>;
|
||||
} else {
|
||||
params = parsedBody as Record<string, unknown>;
|
||||
}
|
||||
echo = parsedBody.echo;
|
||||
}
|
||||
} catch {
|
||||
if (contentType.includes('application/json')) {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
return;
|
||||
}
|
||||
// 无 content-type,JSON 失败则 fallback 到 urlencoded
|
||||
const parsed = new URLSearchParams(bodyContent);
|
||||
parsed.forEach((value, key) => {
|
||||
try {
|
||||
params[key] = JSON.parse(value);
|
||||
} catch {
|
||||
params[key] = value;
|
||||
}
|
||||
});
|
||||
if (params.action && !action) {
|
||||
action = String(params.action);
|
||||
delete params.action;
|
||||
}
|
||||
if (params.echo !== undefined) {
|
||||
echo = params.echo;
|
||||
delete params.echo;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await this.ctx.api.handle(action, params as JsonObject);
|
||||
if (echo !== undefined) {
|
||||
response.echo = echo as JsonValue;
|
||||
}
|
||||
writeJson(res, 200, response);
|
||||
} catch (error) {
|
||||
const wording = error instanceof Error ? error.message : 'internal error';
|
||||
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bindingSignature(net: HttpServerNetwork): string {
|
||||
// `accessToken` deliberately omitted: it's read per-request from
|
||||
// `this.config`, so a token change doesn't need to re-bind the
|
||||
// listener. Including it here would cause a `close()` + `listen()`
|
||||
// round trip on every token edit — a needless port-rebind that, on
|
||||
// some hosts, races with the OS releasing the port and lands the
|
||||
// server in a half-broken state where the old token still
|
||||
// authenticates because the EADDRINUSE-failing new server never
|
||||
// replaced the old one. `host`/`port`/`path` still gate a restart
|
||||
// because Node's HTTP `Server.listen()` binds the socket on those.
|
||||
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
|
||||
}
|
||||
|
||||
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
req.on('data', (chunk: Buffer) => {
|
||||
total += chunk.length;
|
||||
if (total > maxBytes) {
|
||||
reject(new Error('request body too large'));
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
|
||||
res.statusCode = statusCode;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.end(JSON.stringify(data));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
export { HttpPostAdapter } from './http-post-adapter';
|
||||
export { HttpServerAdapter } from './http-server-adapter';
|
||||
export { OneBotNetworkManager } from './network-manager';
|
||||
export { executeQuickOperation } from './quick-operation';
|
||||
export { WsClientAdapter } from './ws-client-adapter';
|
||||
export { WsServerAdapter } from './ws-server-adapter';
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { buildDispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
import { IOneBotNetworkAdapter } from './adapter';
|
||||
|
||||
const log = createLogger('OneBot.Network');
|
||||
|
||||
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
|
||||
|
||||
export class OneBotNetworkManager {
|
||||
private readonly adapters = new Map<string, AnyAdapter>();
|
||||
|
||||
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
|
||||
const existing = this.adapters.get(adapter.name);
|
||||
if (existing) {
|
||||
// Replacing an adapter under the same name — close the previous one
|
||||
// before storing the new instance to keep ports/sockets clean.
|
||||
log.info('replacing adapter [%s]', adapter.name);
|
||||
void Promise.resolve(existing.close()).catch(() => { /* best-effort */ });
|
||||
}
|
||||
this.adapters.set(adapter.name, adapter as AnyAdapter);
|
||||
}
|
||||
|
||||
has(name: string): boolean { return this.adapters.has(name); }
|
||||
|
||||
get(name: string): AnyAdapter | null {
|
||||
return this.adapters.get(name) ?? null;
|
||||
}
|
||||
|
||||
list(): AnyAdapter[] { return [...this.adapters.values()]; }
|
||||
|
||||
hasActiveAdapters(): boolean {
|
||||
for (const a of this.adapters.values()) if (a.isActive) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async openAll(): Promise<void> {
|
||||
const tasks = this.list().map(async (a) => {
|
||||
try {
|
||||
await a.open();
|
||||
} catch (err) {
|
||||
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
|
||||
}
|
||||
});
|
||||
await Promise.all(tasks);
|
||||
}
|
||||
|
||||
async closeAll(): Promise<void> {
|
||||
const tasks = this.list().map(async (a) => {
|
||||
try {
|
||||
await a.close();
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
|
||||
}
|
||||
});
|
||||
await Promise.all(tasks);
|
||||
this.adapters.clear();
|
||||
}
|
||||
|
||||
async closeOne(name: string): Promise<void> {
|
||||
const adapter = this.adapters.get(name);
|
||||
if (!adapter) return;
|
||||
this.adapters.delete(name);
|
||||
try {
|
||||
await adapter.close();
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch one canonical OneBot event to every active adapter in parallel.
|
||||
* The dispatch payload is built once so each adapter pays only the cost
|
||||
* of picking the right pre-serialized variant.
|
||||
*
|
||||
* Errors thrown inside an adapter are isolated — one bad adapter never
|
||||
* blocks the others.
|
||||
*/
|
||||
async emitEvent(event: JsonObject): Promise<void> {
|
||||
if (!this.hasActiveAdapters()) return;
|
||||
const payload = buildDispatchPayload(event);
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
for (const adapter of this.adapters.values()) {
|
||||
if (!adapter.isActive) continue;
|
||||
tasks.push(
|
||||
Promise.resolve()
|
||||
.then(() => adapter.onEvent(event, payload))
|
||||
.catch((err) => {
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
}
|
||||
|
||||
function errMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { ApiHandler } from '../api-handler';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
export async function executeQuickOperation(
|
||||
event: JsonObject,
|
||||
operation: Record<string, unknown>,
|
||||
api: ApiHandler,
|
||||
): Promise<void> {
|
||||
const postType = event.post_type as string;
|
||||
|
||||
if (postType === 'message') {
|
||||
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
|
||||
const messageType = event.message_type as string;
|
||||
const autoEscape = !!operation.auto_escape;
|
||||
|
||||
if (messageType === 'group') {
|
||||
const params: JsonObject = {
|
||||
group_id: event.group_id as number,
|
||||
message: operation.reply as JsonValue,
|
||||
auto_escape: autoEscape,
|
||||
};
|
||||
if (operation.at_sender !== false && event.user_id) {
|
||||
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
|
||||
if (typeof operation.reply === 'string') {
|
||||
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as JsonValue;
|
||||
params.auto_escape = false;
|
||||
} else if (Array.isArray(operation.reply)) {
|
||||
params.message = [atSegment, ...(operation.reply as unknown[])] as JsonValue;
|
||||
}
|
||||
}
|
||||
await api.handle('send_group_msg', params);
|
||||
} else if (messageType === 'private') {
|
||||
await api.handle('send_private_msg', {
|
||||
user_id: event.user_id as number,
|
||||
message: operation.reply as JsonValue,
|
||||
auto_escape: autoEscape,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (operation.delete) {
|
||||
await api.handle('delete_msg', { message_id: event.message_id as number });
|
||||
}
|
||||
|
||||
if (operation.ban && event.message_type === 'group') {
|
||||
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
|
||||
await api.handle('set_group_ban', {
|
||||
group_id: event.group_id as number,
|
||||
user_id: event.user_id as number,
|
||||
duration: duration as JsonValue,
|
||||
});
|
||||
}
|
||||
|
||||
if (operation.kick && event.message_type === 'group') {
|
||||
await api.handle('set_group_kick', {
|
||||
group_id: event.group_id as number,
|
||||
user_id: event.user_id as number,
|
||||
reject_add_request: !!operation.reject_add_request,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (postType === 'request') {
|
||||
if (operation.approve !== undefined) {
|
||||
const requestType = event.request_type as string;
|
||||
if (requestType === 'friend') {
|
||||
await api.handle('set_friend_add_request', {
|
||||
flag: event.flag as string,
|
||||
approve: operation.approve as JsonValue,
|
||||
remark: (operation.remark ?? '') as JsonValue,
|
||||
});
|
||||
} else if (requestType === 'group') {
|
||||
await api.handle('set_group_add_request', {
|
||||
flag: event.flag as string,
|
||||
sub_type: event.sub_type as string,
|
||||
approve: operation.approve as JsonValue,
|
||||
reason: (operation.reason ?? '') as JsonValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { WebSocket } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
|
||||
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
|
||||
export function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
const auth = request.headers.authorization ?? '';
|
||||
if (auth === `Bearer ${token}`) return true;
|
||||
try {
|
||||
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
||||
if (url.searchParams.get('access_token') === token) return true;
|
||||
} catch { /* ignore malformed URLs */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Convert anything ws can hand us into a UTF-8 string. */
|
||||
export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
|
||||
if (typeof raw === 'string') return raw;
|
||||
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
|
||||
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
|
||||
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
|
||||
if (ArrayBuffer.isView(raw)) {
|
||||
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */
|
||||
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
|
||||
if (socket.readyState !== 1 /* WebSocket.OPEN */) return;
|
||||
socket.send(payload, (error?: Error | null) => {
|
||||
if (error && onError) onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
/** Best-effort close, treats already-closed sockets as a no-op. */
|
||||
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
|
||||
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
|
||||
socket.close(code, reason);
|
||||
}
|
||||
|
||||
/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */
|
||||
export function normalizePath(pathValue: string | undefined): string {
|
||||
const path = (pathValue ?? '/').trim() || '/';
|
||||
if (path === '/') return '/';
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */
|
||||
export function parseRequestPath(urlValue: string): string {
|
||||
try {
|
||||
return new URL(urlValue, 'ws://127.0.0.1').pathname;
|
||||
} catch {
|
||||
return '/';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { WebSocket } from '@snowluma/websocket';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
shapeEventForAdapter,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Client');
|
||||
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private socket: WebSocket | null = null;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.role = config.role ?? 'Universal';
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
if (this.config.enabled === false) return;
|
||||
if (!this.config.url) return;
|
||||
this.explicitlyClosed = false;
|
||||
this.isEnabled = true;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.explicitlyClosed = true;
|
||||
this.isEnabled = false;
|
||||
this.cancelReconnect();
|
||||
if (this.socket) {
|
||||
safeClose(this.socket);
|
||||
this.socket = null;
|
||||
}
|
||||
}
|
||||
|
||||
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false && !!next.url;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.options = resolveReportOptions(next);
|
||||
this.role = next.role ?? 'Universal';
|
||||
|
||||
const sigChanged = prevSig !== bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
if (!this.isEnabled || !this.socket) return;
|
||||
if (this.role !== 'Event' && this.role !== 'Universal') return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
safeSend(this.socket, json);
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
if (this.explicitlyClosed) return;
|
||||
if (!this.config.url) return;
|
||||
if (this.socket) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'User-Agent': 'OneBot/11',
|
||||
'X-Self-ID': this.ctx.uin,
|
||||
'X-Client-Role': this.role,
|
||||
};
|
||||
if (this.config.accessToken) {
|
||||
headers.Authorization = `Bearer ${this.config.accessToken}`;
|
||||
}
|
||||
|
||||
const socket = new WebSocket(this.config.url, { headers });
|
||||
this.socket = socket;
|
||||
|
||||
socket.on('open', () => {
|
||||
this.log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
});
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, raw).catch((err) => {
|
||||
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
this.socket = null;
|
||||
if (this.explicitlyClosed || !this.isEnabled) return;
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimer) return;
|
||||
if (this.explicitlyClosed) return;
|
||||
const interval = Math.max(1000, this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS);
|
||||
const timer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
if (this.explicitlyClosed || !this.isEnabled) return;
|
||||
this.connect();
|
||||
}, interval);
|
||||
timer.unref?.();
|
||||
this.reconnectTimer = timer;
|
||||
}
|
||||
|
||||
private cancelReconnect(): void {
|
||||
if (!this.reconnectTimer) return;
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
|
||||
if (this.role !== 'Api' && this.role !== 'Universal') return;
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) return;
|
||||
const response = await this.ctx.api.processRequest(text);
|
||||
safeSend(socket, response);
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket): void {
|
||||
if (this.role !== 'Event' && this.role !== 'Universal') return;
|
||||
const events = [
|
||||
this.ctx.buildLifecycleEvent('connect'),
|
||||
this.ctx.buildLifecycleEvent('enable'),
|
||||
this.ctx.buildHeartbeatEvent(),
|
||||
];
|
||||
for (const event of events) {
|
||||
const shaped = shapeEventForAdapter(event, this.options);
|
||||
if (!shaped) continue;
|
||||
safeSend(socket, JSON.stringify(shaped));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bindingSignature(net: WsClientNetwork): string {
|
||||
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
shapeEventForAdapter,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
|
||||
interface ForwardConn {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
options: EventReportOptions;
|
||||
}
|
||||
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
if (this.config.enabled === false) return;
|
||||
this.startServer();
|
||||
this.isEnabled = true;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
|
||||
// Final lifecycle broadcast before tearing down so attached event clients
|
||||
// see the disable transition.
|
||||
const lifecycle = this.ctx.buildLifecycleEvent('disable');
|
||||
for (const conn of this.connections.values()) {
|
||||
if (conn.role === 'Api') continue;
|
||||
const shaped = shapeEventForAdapter(lifecycle, conn.options);
|
||||
if (!shaped) continue;
|
||||
safeSend(conn.socket, JSON.stringify(shaped));
|
||||
}
|
||||
|
||||
this.isEnabled = false;
|
||||
for (const ws of [...this.connections.keys()]) safeClose(ws);
|
||||
this.connections.clear();
|
||||
this.wss?.close();
|
||||
this.wss = null;
|
||||
}
|
||||
|
||||
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.options = resolveReportOptions(next);
|
||||
for (const conn of this.connections.values()) conn.options = this.options;
|
||||
|
||||
const sigChanged = prevSig !== bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
if (!this.isEnabled || this.connections.size === 0) return;
|
||||
for (const conn of this.connections.values()) {
|
||||
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
|
||||
const json = pickDispatchJson(payload, conn.options);
|
||||
if (json === null) continue;
|
||||
safeSend(conn.socket, json);
|
||||
}
|
||||
}
|
||||
|
||||
private startServer(): void {
|
||||
const wss = new WebSocketServer({
|
||||
host: this.config.host ?? '0.0.0.0',
|
||||
port: this.config.port,
|
||||
path: this.config.path ?? '/',
|
||||
});
|
||||
this.wss = wss;
|
||||
|
||||
wss.on('listening', () => {
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
this.config.path ?? '/',
|
||||
);
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
}
|
||||
|
||||
private onConnection(socket: WebSocket, request: IncomingMessage): void {
|
||||
if (!isAuthorized(request, this.config.accessToken ?? '')) {
|
||||
safeClose(socket, 1008, 'invalid access token');
|
||||
return;
|
||||
}
|
||||
|
||||
const role = this.config.role ?? classifyForwardRole(request);
|
||||
const conn: ForwardConn = { socket, role, options: this.options };
|
||||
this.connections.set(socket, conn);
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
socket.on('close', () => this.connections.delete(socket));
|
||||
socket.on('error', (err: Error) => {
|
||||
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
if (role === 'Event' || role === 'Universal') {
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||
if (role !== 'Api' && role !== 'Universal') return;
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) return;
|
||||
const response = await this.ctx.api.processRequest(text);
|
||||
safeSend(socket, response);
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket): void {
|
||||
const events = [
|
||||
this.ctx.buildLifecycleEvent('connect'),
|
||||
this.ctx.buildLifecycleEvent('enable'),
|
||||
this.ctx.buildHeartbeatEvent(),
|
||||
];
|
||||
for (const event of events) {
|
||||
const shaped = shapeEventForAdapter(event, this.options);
|
||||
if (!shaped) continue;
|
||||
safeSend(socket, JSON.stringify(shaped));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function classifyForwardRole(request: IncomingMessage): WsRole {
|
||||
const path = parseRequestPath(request.url ?? '/');
|
||||
if (path.endsWith('/api')) return 'Api';
|
||||
if (path.endsWith('/event')) return 'Event';
|
||||
return 'Universal';
|
||||
}
|
||||
|
||||
function bindingSignature(net: WsServerNetwork): string {
|
||||
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Plain JSON types now live in @snowluma/common/json so @snowluma/bridge
|
||||
// (event-format / receive parsers) can talk about JSON payloads without
|
||||
// importing OneBot. Re-exported here so the legacy import shape stays
|
||||
// supported — `import { JsonValue } from '<…>/onebot/types'` keeps working.
|
||||
export type { JsonPrimitive, JsonValue, JsonObject, JsonArray } from '@snowluma/common/json';
|
||||
import type { JsonValue, JsonObject } from '@snowluma/common/json';
|
||||
|
||||
export interface ApiResponse {
|
||||
status: 'ok' | 'failed';
|
||||
retcode: number;
|
||||
data: JsonValue;
|
||||
echo?: JsonValue;
|
||||
wording?: string;
|
||||
}
|
||||
|
||||
export interface OneBotRequest {
|
||||
action: string;
|
||||
params?: JsonObject;
|
||||
echo?: JsonValue;
|
||||
}
|
||||
|
||||
export type WsRole = 'Api' | 'Event' | 'Universal';
|
||||
|
||||
export type MessageFormat = 'array' | 'string';
|
||||
|
||||
export type NetworkKind = 'httpServers' | 'httpClients' | 'wsServers' | 'wsClients';
|
||||
|
||||
/**
|
||||
* Fields shared by every network adapter. `messageFormat` and
|
||||
* `reportSelfMessage` live on the adapter itself — there is no global default
|
||||
* fallback; each adapter is fully self-describing.
|
||||
*
|
||||
* The `name` is a free-form identifier scoped to the adapter's array; it is
|
||||
* used for hot-reload bookkeeping and as a label in logs / WebUI.
|
||||
*/
|
||||
export interface NetworkBase {
|
||||
name: string;
|
||||
/** When `false`, the adapter is configured but inactive. Defaults to `true`. */
|
||||
enabled?: boolean;
|
||||
accessToken?: string;
|
||||
/** Output format for this adapter. */
|
||||
messageFormat: MessageFormat;
|
||||
/** When `true`, this adapter receives `post_type='message_sent'` self events. */
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
export interface HttpServerNetwork extends NetworkBase {
|
||||
host?: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface HttpClientNetwork extends NetworkBase {
|
||||
url: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface WsServerNetwork extends NetworkBase {
|
||||
host?: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
role?: WsRole;
|
||||
}
|
||||
|
||||
export interface WsClientNetwork extends NetworkBase {
|
||||
url: string;
|
||||
role?: WsRole;
|
||||
reconnectIntervalMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Network adapters grouped by type. Each adapter is identified by `name`
|
||||
* within its own array; hot-reload works on a per-(kind, name) basis.
|
||||
*/
|
||||
export interface OneBotNetworks {
|
||||
httpServers: HttpServerNetwork[];
|
||||
httpClients: HttpClientNetwork[];
|
||||
wsServers: WsServerNetwork[];
|
||||
wsClients: WsClientNetwork[];
|
||||
}
|
||||
|
||||
/** Per-UIN OneBot configuration. */
|
||||
export interface OneBotConfig {
|
||||
networks: OneBotNetworks;
|
||||
/** Music card signing service URL (optional). */
|
||||
musicSignUrl?: string;
|
||||
}
|
||||
|
||||
export interface MessageMeta {
|
||||
isGroup: boolean;
|
||||
targetId: number;
|
||||
sequence: number;
|
||||
eventName: string;
|
||||
clientSequence: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export const RETCODE = {
|
||||
ACTION_FAILED: 100,
|
||||
INTERNAL_ERROR: 1200,
|
||||
BAD_REQUEST: 1400,
|
||||
UNKNOWN_ACTION: 1404,
|
||||
} as const;
|
||||
|
||||
export function okResponse(data: JsonValue = null): ApiResponse {
|
||||
return {
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
export function failedResponse(retcode: number, wording: string): ApiResponse {
|
||||
return {
|
||||
status: 'failed',
|
||||
retcode,
|
||||
data: null,
|
||||
wording,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user