Migrate project to pnpm monorepo
Restructure the repository into a pnpm workspace under packages/ (core, webui, runtime). Move source files for core and webui into packages/*, add package manifests for @snowluma/core and @snowluma/runtime, and remove the old launcher package.json. Update root package.json to be a monorepo controller (scripts delegate to pnpm filters, set packageManager and Node engine). Configure build outputs to emit into the repo-root dist/ (vite config changes) so the existing release pipeline continues to work. Add .npmrc with mirrors, expand .gitignore for monorepo layout, add tsconfig base and package-level tsconfigs, and add vitest config for the core package. Adjust injector native search paths and update tests import paths to the new package layout. Small CI/workflow comment added to clarify build behavior and README updated with monorepo structure and common commands.
This commit is contained in:
1 parent
6bba36bba6
commit
39f1672b29
122 files changed
+279
-85
No files matched your search
@@ -0,0 +1,601 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
// --- Likes & Pokes ---
|
||||
|
||||
h.registerAction('send_like', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const times = asNumber(params.times) || 1;
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.sendLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendLike(userId, times);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('friend_poke', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const targetId = asNumber(params.target_id) || undefined;
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendFriendPoke(userId, targetId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('group_poke', 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');
|
||||
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendGroupPoke(groupId, userId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('send_poke', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (groupId) {
|
||||
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendGroupPoke(groupId, userId);
|
||||
} else {
|
||||
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendFriendPoke(userId);
|
||||
}
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- Essence ---
|
||||
|
||||
h.registerAction('set_essence_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
if (!ctx.setEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setEssenceMsg(messageId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('delete_essence_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
if (!ctx.deleteEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.deleteEssenceMsg(messageId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_essence_msg_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
// Essence list fetch requires web ticket/cookie flow not wired yet.
|
||||
// Keep API-compatible output shape for callers.
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
// --- Reactions ---
|
||||
|
||||
h.registerAction('set_group_reaction', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const messageId = asNumber(params.message_id);
|
||||
const code = asString(params.code);
|
||||
const isSet = asBoolean(params.is_set, true);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0 || !code) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and code are required');
|
||||
}
|
||||
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message');
|
||||
}
|
||||
|
||||
if (groupId && groupId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
|
||||
}
|
||||
|
||||
if (!ctx.setGroupReaction) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- History ---
|
||||
|
||||
h.registerAction('get_group_msg_history', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const messageId = asNumber(params.message_id) || 0;
|
||||
const count = asNumber(params.count) || 20;
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!ctx.getGroupMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const messages = await ctx.getGroupMsgHistory(groupId, messageId, count);
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
h.registerAction('get_friend_msg_history', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const messageId = asNumber(params.message_id) || 0;
|
||||
const count = asNumber(params.count) || 20;
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.getFriendMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const messages = await ctx.getFriendMsgHistory(userId, messageId, count);
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
h.registerAction('mark_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- RKey ---
|
||||
|
||||
h.registerAction('get_rkey', async () => {
|
||||
if (ctx.getDownloadRKeys) {
|
||||
return okResponse(await ctx.getDownloadRKeys());
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
});
|
||||
|
||||
// --- OCR stubs ---
|
||||
|
||||
h.registerAction('ocr_image', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('.ocr_image', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
// --- Group notice stubs ---
|
||||
|
||||
h.registerAction('_send_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('_get_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('_del_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
// --- Forward messages ---
|
||||
|
||||
h.registerAction('upload_forward_msg', async (params) => {
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
const data: Record<string, unknown> = {
|
||||
res_id: result.forwardId,
|
||||
forward_id: result.forwardId,
|
||||
message_id: 0,
|
||||
};
|
||||
if (groupId > 0) data.group_id = groupId;
|
||||
return okResponse(data as any);
|
||||
});
|
||||
|
||||
h.registerAction('upload_foward_msg', async (params) => {
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('send_forward_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
|
||||
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
}
|
||||
|
||||
if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) {
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
}
|
||||
|
||||
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
h.registerAction('send_group_forward_msg', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendGroupForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
h.registerAction('send_private_forward_msg', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendPrivateForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
h.registerAction('get_forward_msg', async (params) => {
|
||||
let id = asString(params.id);
|
||||
if (!id) {
|
||||
const rawMessageId = params.message_id;
|
||||
const numericMessageId = asNumber(rawMessageId);
|
||||
if (numericMessageId > 0) {
|
||||
const event = ctx.getMessage(numericMessageId);
|
||||
const segments = Array.isArray(event?.message) ? event.message : [];
|
||||
for (const seg of segments) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const so = seg as Record<string, unknown>;
|
||||
if (String(so.type ?? '') !== 'forward') continue;
|
||||
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data))
|
||||
? so.data as Record<string, unknown>
|
||||
: null;
|
||||
const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id);
|
||||
if (candidate) {
|
||||
id = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
id = asString(rawMessageId);
|
||||
}
|
||||
}
|
||||
|
||||
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
|
||||
if (!ctx.getForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const messages = await ctx.getForwardMsg(id);
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
// --- Media ---
|
||||
|
||||
h.registerAction('get_image', async (params) => {
|
||||
const file = asString(params.file);
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
const imageInfo = findMediaInStore('image', file, ctx);
|
||||
if (imageInfo) {
|
||||
return okResponse(imageInfo as unknown as import('../types').JsonValue);
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache');
|
||||
});
|
||||
|
||||
h.registerAction('get_record', async (params) => {
|
||||
const file = asString(params.file);
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
const recordInfo = findMediaInStore('record', file, ctx);
|
||||
if (recordInfo) {
|
||||
return okResponse(recordInfo as unknown as import('../types').JsonValue);
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
|
||||
});
|
||||
|
||||
// --- Credentials ---
|
||||
|
||||
h.registerAction('get_cookies', async () => {
|
||||
return okResponse({ cookies: '' });
|
||||
});
|
||||
|
||||
h.registerAction('get_csrf_token', async () => {
|
||||
return okResponse({ token: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('get_credentials', async () => {
|
||||
return okResponse({ cookies: '', csrf_token: 0 });
|
||||
});
|
||||
|
||||
// --- Utility ---
|
||||
|
||||
h.registerAction('set_restart', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not supported');
|
||||
});
|
||||
|
||||
h.registerAction('clean_cache', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('.handle_quick_operation', async (params) => {
|
||||
const context = params.context as import('../types').JsonObject | undefined;
|
||||
const operation = params.operation as Record<string, unknown> | undefined;
|
||||
if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
|
||||
const { executeQuickOperation } = await import('../http-post-transport');
|
||||
await executeQuickOperation(context, operation, h);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- NapCat-compatible extended APIs ---
|
||||
|
||||
h.registerAction('set_friend_remark', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const remark = asString(params.remark) ?? '';
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.setFriendRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setFriendRemark(userId, remark);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_msg_emoji_like', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const emojiId = asString(params.emoji_id);
|
||||
const set = asBoolean(params.set, true);
|
||||
if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
|
||||
}
|
||||
if (!ctx.setMsgEmojiLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setMsgEmojiLike(messageId, emojiId, set);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_private_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_group_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('_mark_all_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_group_file_system_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (ctx.getGroupFileCount) {
|
||||
const info = await ctx.getGroupFileCount(groupId);
|
||||
return okResponse({
|
||||
file_count: info.fileCount,
|
||||
limit_count: info.maxCount,
|
||||
used_space: 0,
|
||||
total_space: 10737418240,
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
file_count: 0,
|
||||
limit_count: 10000,
|
||||
used_space: 0,
|
||||
total_space: 10737418240,
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('check_url_safely', async () => {
|
||||
return okResponse({ level: 1 });
|
||||
});
|
||||
|
||||
h.registerAction('download_file', async (params) => {
|
||||
const url = asString(params.url);
|
||||
const base64 = asString(params.base64);
|
||||
const name = asString(params.name);
|
||||
if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required');
|
||||
|
||||
const fs = await import('fs');
|
||||
const pathMod = await import('path');
|
||||
const cryptoMod = await import('crypto');
|
||||
const tempDir = pathMod.join('data', 'downloads');
|
||||
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
let filePath: string;
|
||||
if (base64) {
|
||||
const buf = Buffer.from(base64, 'base64');
|
||||
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||
filePath = pathMod.join(tempDir, fileName);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
} else {
|
||||
const response = await fetch(url!, {
|
||||
headers: parseDownloadHeaders(params.headers),
|
||||
});
|
||||
if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`);
|
||||
const buf = Buffer.from(await response.arrayBuffer());
|
||||
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||
filePath = pathMod.join(tempDir, fileName);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
}
|
||||
return okResponse({ file: pathMod.resolve(filePath) });
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_profile', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_online_status', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_ignored_notifies', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_group_shut_list', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('forward_friend_single_msg', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('forward_group_single_msg', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_recent_contact', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_profile_like', async () => {
|
||||
return okResponse({});
|
||||
});
|
||||
|
||||
h.registerAction('get_friends_with_category', async () => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
// --- Additional NapCat-compatible stubs ---
|
||||
|
||||
h.registerAction('get_online_clients', async () => {
|
||||
return okResponse({ clients: [] });
|
||||
});
|
||||
|
||||
h.registerAction('_get_model_show', async () => {
|
||||
return okResponse({ variants: [] });
|
||||
});
|
||||
|
||||
h.registerAction('_set_model_show', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('.get_word_slices', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_at_all_remain', async () => {
|
||||
return okResponse({ can_at_all: false, remain_at_all_count_for_group: 0, remain_at_all_count_for_uin: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('get_unidirectional_friend_list', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('set_self_longnick', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_collection_list', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('create_collection', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_avatar', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_input_status', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('translate_en2zh', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_clientkey', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_mini_app_ark', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('click_inline_keyboard_button', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_group_sign', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('send_group_sign', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_info_ex', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (ctx.getGroupInfo) {
|
||||
return okResponse(await ctx.getGroupInfo(groupId));
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_detail_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (ctx.getGroupInfo) {
|
||||
return okResponse(await ctx.getGroupInfo(groupId));
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
});
|
||||
|
||||
h.registerAction('trans_group_file', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('rename_group_file', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_file', async (params) => {
|
||||
const fileId = asString(params.file_id) || asString(params.file);
|
||||
if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required');
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('.send_packet', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search through cached message segments to find a media element (image/record)
|
||||
* that matches the given file identifier.
|
||||
*/
|
||||
function findMediaInStore(
|
||||
mediaType: 'image' | 'record',
|
||||
file: string,
|
||||
ctx: ApiActionContext,
|
||||
): Record<string, unknown> | null {
|
||||
// The file param can match a file id, a URL, or a filename stored in segments.
|
||||
// We don't have a reverse index, so this is best-effort from stored events.
|
||||
// Most callers will pass the `file` field from a received message segment.
|
||||
// Just return the info if we can look it up from any recent cached message.
|
||||
// This is a known limitation — full implementation would require a media cache.
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse download_file headers parameter into a Record.
|
||||
*/
|
||||
function parseDownloadHeaders(headers: unknown): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
if (!headers) return result;
|
||||
const headerList: string[] = [];
|
||||
if (typeof headers === 'string') {
|
||||
headerList.push(...headers.split(/\r?\n/).filter(Boolean));
|
||||
} else if (Array.isArray(headers)) {
|
||||
for (const h of headers) {
|
||||
if (typeof h === 'string') headerList.push(h);
|
||||
}
|
||||
}
|
||||
for (const line of headerList) {
|
||||
const idx = line.indexOf('=');
|
||||
if (idx > 0) {
|
||||
result[line.substring(0, idx).trim()] = line.substring(idx + 1).trim();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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');
|
||||
if (!ctx.handleDeleteFriend) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.handleDeleteFriend(userId, block);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
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');
|
||||
if (!ctx.setGroupKick) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupKick(groupId, userId, 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');
|
||||
if (!ctx.setGroupBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
if (!ctx.setGroupWholeBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupWholeBan(groupId, enable);
|
||||
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');
|
||||
if (!ctx.setGroupAdmin) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupAdmin(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');
|
||||
if (!ctx.setGroupCard) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupCard(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');
|
||||
if (!ctx.setGroupName) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupName(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');
|
||||
if (!ctx.setGroupLeave) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
if (!ctx.setGroupSpecialTitle) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupSpecialTitle(groupId, userId, title);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous_ban', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_portrait', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
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');
|
||||
if (!ctx.uploadGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
if (!ctx.uploadPrivateFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
}
|
||||
if (!ctx.getGroupFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
}
|
||||
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
}
|
||||
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
}
|
||||
if (!ctx.deleteGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.deleteGroupFile(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');
|
||||
}
|
||||
if (!ctx.moveGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.moveGroupFile(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');
|
||||
}
|
||||
if (!ctx.createGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
}
|
||||
if (!ctx.deleteGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.deleteGroupFileFolder(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');
|
||||
}
|
||||
if (!ctx.renameGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.renameGroupFileFolder(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');
|
||||
}
|
||||
if (!ctx.getPrivateFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
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_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);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
return okResponse({
|
||||
group_id: groupId, current_talkative: null, talkative_list: [],
|
||||
performer_list: [], legend_list: [], strong_newbie_list: [], emotion_list: [],
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('get_group_system_msg', async () => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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 });
|
||||
});
|
||||
|
||||
h.registerAction('get_version_info', async () => {
|
||||
return okResponse({
|
||||
app_name: 'SnowLuma',
|
||||
app_version: '0.1.0-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,112 @@
|
||||
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');
|
||||
}
|
||||
if (!ctx.sendGroupMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
|
||||
}
|
||||
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');
|
||||
}
|
||||
if (!ctx.sendPrivateMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
|
||||
}
|
||||
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');
|
||||
}
|
||||
if (!ctx.sendPrivateMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
if (!ctx.sendGroupMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
if (!ctx.deleteMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'delete_msg is not implemented');
|
||||
}
|
||||
|
||||
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,25 @@
|
||||
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');
|
||||
if (!ctx.handleFriendRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
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');
|
||||
if (!ctx.handleGroupRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.handleGroupRequest(flag, subType, approve, reason);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
|
||||
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';
|
||||
|
||||
export interface MessageSendResult {
|
||||
messageId: number;
|
||||
meta?: MessageMeta;
|
||||
echoEvent?: JsonObject;
|
||||
}
|
||||
|
||||
export interface ApiActionContext {
|
||||
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
|
||||
setGroupKick?: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
|
||||
setGroupBan?: (groupId: number, userId: number, duration: number) => Promise<void>;
|
||||
setGroupWholeBan?: (groupId: number, enable: boolean) => Promise<void>;
|
||||
setGroupAdmin?: (groupId: number, userId: number, enable: boolean) => Promise<void>;
|
||||
setGroupCard?: (groupId: number, userId: number, card: string) => Promise<void>;
|
||||
setGroupName?: (groupId: number, name: string) => Promise<void>;
|
||||
setGroupLeave?: (groupId: number) => Promise<void>;
|
||||
setGroupSpecialTitle?: (groupId: number, userId: number, title: string) => Promise<void>;
|
||||
// Group file
|
||||
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>;
|
||||
deleteGroupFile?: (groupId: number, fileId: string) => Promise<void>;
|
||||
moveGroupFile?: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise<void>;
|
||||
createGroupFileFolder?: (groupId: number, name: string, parentId?: string) => Promise<void>;
|
||||
deleteGroupFileFolder?: (groupId: number, folderId: string) => Promise<void>;
|
||||
renameGroupFileFolder?: (groupId: number, folderId: string, newName: string) => Promise<void>;
|
||||
getPrivateFileUrl?: (userId: number, fileId: string, fileHash: string) => Promise<string>;
|
||||
// Requests
|
||||
handleFriendRequest?: (flag: string, approve: boolean) => Promise<void>;
|
||||
handleGroupRequest?: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
|
||||
// Extended
|
||||
sendLike?: (userId: number, times: number) => Promise<void>;
|
||||
sendFriendPoke?: (userId: number, targetId?: number) => Promise<void>;
|
||||
sendGroupPoke?: (groupId: number, userId: number) => Promise<void>;
|
||||
setEssenceMsg?: (messageId: number) => Promise<void>;
|
||||
deleteEssenceMsg?: (messageId: number) => Promise<void>;
|
||||
// New context methods
|
||||
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
|
||||
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
|
||||
getGroupMsgHistory?: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||
getFriendMsgHistory?: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||
handleGetGroupSystemMsg?: () => Promise<JsonObject[]>;
|
||||
getDownloadRKeys?: () => Promise<JsonObject[]>;
|
||||
// Forward message
|
||||
sendGroupForwardMsg?: (groupId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendPrivateForwardMsg?: (userId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendForwardMsg?: (messages: JsonValue) => Promise<{ forwardId: string }>;
|
||||
getForwardMsg?: (resId: string) => Promise<JsonObject[]>;
|
||||
// Extended NapCat-compatible
|
||||
setFriendRemark?: (userId: number, remark: string) => Promise<void>;
|
||||
getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
|
||||
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
|
||||
constructor(context: ApiActionContext) {
|
||||
registerInfo(this, context);
|
||||
registerMessage(this, context);
|
||||
registerFriend(this, context);
|
||||
registerGroupInfo(this, context);
|
||||
registerGroupAdmin(this, context);
|
||||
registerGroupFile(this, context);
|
||||
registerRequest(this, context);
|
||||
registerExtended(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) {
|
||||
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||
}
|
||||
|
||||
try {
|
||||
return await handler(params);
|
||||
} catch (error) {
|
||||
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,315 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type {
|
||||
HttpPostEndpoint,
|
||||
HttpServerEndpoint,
|
||||
JsonObject,
|
||||
OneBotConfig,
|
||||
WsClientEndpoint,
|
||||
WsRole,
|
||||
WsServerEndpoint,
|
||||
} from './types';
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
|
||||
export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
return {
|
||||
httpServers: [{ host: '0.0.0.0', port: 3000, path: '/' }],
|
||||
httpPostEndpoints: [],
|
||||
wsServers: [{ host: '0.0.0.0', port: 3001 }],
|
||||
wsClients: [],
|
||||
musicSignUrl: '',
|
||||
};
|
||||
}
|
||||
|
||||
export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||
ensureConfigDir();
|
||||
|
||||
const merged = deepClone(toJsonObject(makeDefaultOneBotConfig()));
|
||||
const globalConfig = tryLoadJson(DEFAULT_CONFIG_PATH);
|
||||
if (globalConfig) {
|
||||
deepMerge(merged, globalConfig);
|
||||
}
|
||||
|
||||
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||
const perUinConfig = tryLoadJson(perUinPath);
|
||||
if (perUinConfig) {
|
||||
deepMerge(merged, perUinConfig);
|
||||
}
|
||||
|
||||
const config = fromJson(merged);
|
||||
let shouldSave = !perUinConfig;
|
||||
|
||||
// Auto-generate per-endpoint accessToken if not set.
|
||||
for (const s of config.httpServers) {
|
||||
if (!s.accessToken) {
|
||||
s.accessToken = generateRandomKey();
|
||||
shouldSave = true;
|
||||
}
|
||||
}
|
||||
for (const s of config.wsServers) {
|
||||
if (!s.accessToken) {
|
||||
s.accessToken = generateRandomKey();
|
||||
shouldSave = true;
|
||||
}
|
||||
}
|
||||
for (const c of config.wsClients) {
|
||||
if (!c.accessToken) {
|
||||
c.accessToken = generateRandomKey();
|
||||
shouldSave = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Persist normalized endpoints and generated keys.
|
||||
merged.httpServers = config.httpServers.map((s) => {
|
||||
const out: JsonObject = {
|
||||
host: s.host,
|
||||
port: s.port,
|
||||
path: s.path ?? '/',
|
||||
accessToken: s.accessToken ?? '',
|
||||
};
|
||||
if (s.name) out.name = s.name;
|
||||
return out;
|
||||
});
|
||||
merged.httpPostEndpoints = config.httpPostEndpoints.map((e) => {
|
||||
const out: JsonObject = { url: e.url };
|
||||
if (e.name) out.name = e.name;
|
||||
if (e.accessToken) out.accessToken = e.accessToken;
|
||||
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
|
||||
return out;
|
||||
});
|
||||
merged.wsServers = config.wsServers.map((s) => {
|
||||
const out: JsonObject = {
|
||||
host: s.host,
|
||||
port: s.port,
|
||||
path: s.path ?? '/',
|
||||
role: s.role ?? 'universal',
|
||||
accessToken: s.accessToken ?? '',
|
||||
};
|
||||
if (s.name) out.name = s.name;
|
||||
return out;
|
||||
});
|
||||
merged.wsClients = config.wsClients.map((c) => {
|
||||
const out: JsonObject = {
|
||||
url: c.url,
|
||||
role: c.role ?? 'universal',
|
||||
accessToken: c.accessToken ?? '',
|
||||
};
|
||||
if (c.name) out.name = c.name;
|
||||
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
|
||||
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
|
||||
}
|
||||
return out;
|
||||
});
|
||||
merged.musicSignUrl = config.musicSignUrl ?? '';
|
||||
|
||||
if (shouldSave) {
|
||||
saveJson(perUinPath, merged);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
|
||||
ensureConfigDir();
|
||||
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||
const jsonObj = toJsonObject(config);
|
||||
saveJson(perUinPath, jsonObj);
|
||||
}
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function toJsonObject(config: OneBotConfig): JsonObject {
|
||||
return {
|
||||
httpServers: config.httpServers.map((s) => {
|
||||
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', accessToken: s.accessToken ?? '' };
|
||||
if (s.name) out.name = s.name;
|
||||
return out;
|
||||
}),
|
||||
httpPostEndpoints: config.httpPostEndpoints.map((e) => {
|
||||
const out: JsonObject = { url: e.url };
|
||||
if (e.name) out.name = e.name;
|
||||
if (e.accessToken) out.accessToken = e.accessToken;
|
||||
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
|
||||
return out;
|
||||
}),
|
||||
wsServers: config.wsServers.map((s) => {
|
||||
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', role: s.role ?? 'universal', accessToken: s.accessToken ?? '' };
|
||||
if (s.name) out.name = s.name;
|
||||
return out;
|
||||
}),
|
||||
wsClients: config.wsClients.map((c) => {
|
||||
const out: JsonObject = {
|
||||
url: c.url,
|
||||
role: c.role ?? 'universal',
|
||||
accessToken: c.accessToken ?? '',
|
||||
};
|
||||
if (c.name) out.name = c.name;
|
||||
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
|
||||
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
|
||||
}
|
||||
return out;
|
||||
}),
|
||||
musicSignUrl: config.musicSignUrl ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
function fromJson(json: JsonObject): OneBotConfig {
|
||||
const httpServers = toHttpServers(json.httpServers);
|
||||
const httpPostEndpoints = toHttpPostEndpoints(json.httpPostEndpoints);
|
||||
const wsServers = toWsServers(json.wsServers);
|
||||
const wsClients = toWsClients(json.wsClients);
|
||||
|
||||
return {
|
||||
httpServers: httpServers.length > 0 ? httpServers : [{ host: '0.0.0.0', port: 3000, path: '/' }],
|
||||
httpPostEndpoints,
|
||||
wsServers: wsServers.length > 0 ? wsServers : [{ host: '0.0.0.0', port: 3001 }],
|
||||
wsClients,
|
||||
musicSignUrl: typeof json.musicSignUrl === 'string' ? json.musicSignUrl : '',
|
||||
};
|
||||
}
|
||||
|
||||
function toHttpServers(value: unknown): HttpServerEndpoint[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const result: HttpServerEndpoint[] = [];
|
||||
|
||||
for (const item of value) {
|
||||
if (!isObject(item)) continue;
|
||||
const host = asString(item.host, '0.0.0.0');
|
||||
const port = asNumber(item.port, 3000);
|
||||
const pathValue = asString(item.path, '/');
|
||||
const endpoint: HttpServerEndpoint = { host, port, path: pathValue };
|
||||
const name = asString(item.name);
|
||||
if (name) endpoint.name = name;
|
||||
const token = asString(item.accessToken);
|
||||
if (token) endpoint.accessToken = token;
|
||||
result.push(endpoint);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function toHttpPostEndpoints(value: unknown): HttpPostEndpoint[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const result: HttpPostEndpoint[] = [];
|
||||
|
||||
for (const item of value) {
|
||||
if (!isObject(item)) continue;
|
||||
const url = asString(item.url);
|
||||
if (!url) continue;
|
||||
const endpoint: HttpPostEndpoint = { url };
|
||||
const name = asString(item.name);
|
||||
if (name) endpoint.name = name;
|
||||
const token = asString(item.accessToken);
|
||||
if (token) endpoint.accessToken = token;
|
||||
const timeout = asNumber(item.timeoutMs, 0);
|
||||
if (timeout > 0) endpoint.timeoutMs = timeout;
|
||||
result.push(endpoint);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function toWsServers(value: unknown): WsServerEndpoint[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const result: WsServerEndpoint[] = [];
|
||||
|
||||
for (const item of value) {
|
||||
if (!isObject(item)) continue;
|
||||
const host = asString(item.host, '0.0.0.0');
|
||||
const port = asNumber(item.port, 3001);
|
||||
const pathValue = asString(item.path, '/');
|
||||
const role = asRole(item.role, 'universal');
|
||||
const endpoint: WsServerEndpoint = { host, port, path: pathValue, role };
|
||||
const name = asString(item.name);
|
||||
if (name) endpoint.name = name;
|
||||
const token = asString(item.accessToken);
|
||||
if (token) endpoint.accessToken = token;
|
||||
result.push(endpoint);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function toWsClients(value: unknown): WsClientEndpoint[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const result: WsClientEndpoint[] = [];
|
||||
|
||||
for (const item of value) {
|
||||
if (!isObject(item)) continue;
|
||||
const url = asString(item.url);
|
||||
if (!url) continue;
|
||||
const role = asRole(item.role, 'universal');
|
||||
const reconnectIntervalMs = asNumber(item.reconnectIntervalMs, 5000);
|
||||
const endpoint: WsClientEndpoint = { url, role, reconnectIntervalMs };
|
||||
const name = asString(item.name);
|
||||
if (name) endpoint.name = name;
|
||||
const token = asString(item.accessToken);
|
||||
if (token) endpoint.accessToken = token;
|
||||
result.push(endpoint);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function asRole(value: unknown, fallback: WsRole): WsRole {
|
||||
const text = asString(value, fallback);
|
||||
return text === 'api' || text === 'event' || text === 'universal' ? text : 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 generateRandomKey(byteLength = 18): string {
|
||||
return randomBytes(byteLength).toString('hex');
|
||||
}
|
||||
|
||||
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 {
|
||||
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 deepClone(obj: JsonObject): JsonObject {
|
||||
return JSON.parse(JSON.stringify(obj)) as JsonObject;
|
||||
}
|
||||
|
||||
function deepMerge(base: JsonObject, override: JsonObject): void {
|
||||
for (const [key, value] of Object.entries(override)) {
|
||||
if (isObject(base[key]) && isObject(value)) {
|
||||
deepMerge(base[key] as JsonObject, value);
|
||||
} else {
|
||||
base[key] = value as never;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
import type { MessageElement, QQEventVariant } from '../bridge/events';
|
||||
import type { JsonArray, JsonObject } from './types';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from './message-id';
|
||||
|
||||
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;
|
||||
|
||||
export class EventConverter {
|
||||
private imageUrlResolver_: ImageUrlResolver | null = null;
|
||||
private mediaUrlResolver_: MediaUrlResolver | null = null;
|
||||
private messageIdResolver_: MessageIdResolver | null = null;
|
||||
|
||||
setImageUrlResolver(resolver: ImageUrlResolver): void {
|
||||
this.imageUrlResolver_ = resolver;
|
||||
}
|
||||
|
||||
setMediaUrlResolver(resolver: MediaUrlResolver): void {
|
||||
this.mediaUrlResolver_ = resolver;
|
||||
}
|
||||
|
||||
setMessageIdResolver(resolver: MessageIdResolver): void {
|
||||
this.messageIdResolver_ = resolver;
|
||||
}
|
||||
|
||||
async convert(instanceUin: string, event: QQEventVariant): Promise<JsonObject | null> {
|
||||
const selfId = parseSelfId(instanceUin);
|
||||
|
||||
switch (event.kind) {
|
||||
case 'friend_message':
|
||||
{
|
||||
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'message',
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_message':
|
||||
{
|
||||
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'message',
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
case 'temp_message':
|
||||
{
|
||||
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'message',
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_member_join':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
sub_type: event.operatorUin === event.userUin ? 'approve' : 'invite',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
|
||||
case 'group_member_leave':
|
||||
{
|
||||
let subType: string;
|
||||
if (event.isKick) {
|
||||
subType = event.userUin === parseSelfId(instanceUin) ? 'kick_me' : 'kick';
|
||||
} else {
|
||||
subType = 'leave';
|
||||
}
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_decrease',
|
||||
sub_type: subType,
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_mute':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: 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,
|
||||
};
|
||||
|
||||
case 'group_admin':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_admin',
|
||||
sub_type: event.set ? 'set' : 'unset',
|
||||
group_id: event.groupId,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
|
||||
case 'friend_recall':
|
||||
{
|
||||
const messageId = this.resolveMessageId(false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'friend_recall',
|
||||
user_id: event.userUin,
|
||||
message_id: messageId,
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_recall':
|
||||
{
|
||||
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_recall',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.authorUin,
|
||||
message_id: messageId,
|
||||
};
|
||||
}
|
||||
|
||||
case 'friend_request':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'request',
|
||||
request_type: 'friend',
|
||||
user_id: event.fromUin,
|
||||
comment: event.message,
|
||||
flag: event.flag,
|
||||
};
|
||||
|
||||
case 'group_invite':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: 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,
|
||||
};
|
||||
|
||||
case 'friend_poke':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: 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,
|
||||
};
|
||||
|
||||
case 'group_poke':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: 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,
|
||||
};
|
||||
|
||||
case 'group_essence':
|
||||
{
|
||||
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: 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,
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_file_upload':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: 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,
|
||||
},
|
||||
};
|
||||
|
||||
case 'friend_add':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'friend_add',
|
||||
user_id: event.userUin,
|
||||
};
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveMessageId(isGroup: boolean, sessionId: number, sequence: number, eventName: string): number {
|
||||
if (this.messageIdResolver_) {
|
||||
const resolved = this.messageIdResolver_(isGroup, sessionId, sequence, eventName);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
const seq = Math.trunc(sequence);
|
||||
return seq === 0 ? 0 : seq;
|
||||
}
|
||||
}
|
||||
|
||||
function parseSelfId(instanceUin: string): number {
|
||||
const parsed = Number.parseInt(instanceUin, 10);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
async function elementsToJson(
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
): Promise<JsonArray> {
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function elementsToOneBotSegments(
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
): Promise<JsonArray> {
|
||||
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver);
|
||||
}
|
||||
|
||||
async function elementToSegment(
|
||||
element: MessageElement,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | 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 = resolver ? resolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
return {
|
||||
type: 'image',
|
||||
data: {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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 = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
return {
|
||||
type: 'record',
|
||||
data: {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'video') {
|
||||
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
return {
|
||||
type: 'video',
|
||||
data: {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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 = mediaResolver ? await mediaResolver(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 (!isGroup && element.type === 'at') {
|
||||
return { type: 'text', data: { text: element.text ?? '' } };
|
||||
}
|
||||
|
||||
return { type: element.type, data: {} };
|
||||
}
|
||||
|
||||
// --- CQ code raw_message generation (from already-resolved JSON segments) ---
|
||||
|
||||
function cqEscape(text: string): string {
|
||||
return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ',');
|
||||
}
|
||||
|
||||
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}]`;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { JsonObject, OneBotConfig, HttpPostEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export interface HttpPostTransportContext {
|
||||
uin: string;
|
||||
api: import('./api-handler').ApiHandler;
|
||||
}
|
||||
|
||||
const log = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostTransport {
|
||||
private readonly context: HttpPostTransportContext;
|
||||
private endpoints: HttpPostEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
const count = this.endpoints.length;
|
||||
if (count > 0) {
|
||||
log.info('configured %d HTTP POST endpoint(s)', count);
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
log.info('reloaded %d HTTP POST endpoint(s)', this.endpoints.length);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
publishEvent(event: JsonObject): void {
|
||||
const endpoints = this.endpoints;
|
||||
if (!endpoints || endpoints.length === 0) return;
|
||||
|
||||
const payload = JSON.stringify(event);
|
||||
for (const endpoint of endpoints) {
|
||||
void this.postEvent(endpoint, payload, event);
|
||||
}
|
||||
}
|
||||
|
||||
private async postEvent(endpoint: HttpPostEndpoint, payload: string, event: JsonObject): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'OneBot',
|
||||
'X-Self-ID': this.context.uin,
|
||||
};
|
||||
|
||||
if (endpoint.accessToken) {
|
||||
headers['X-Signature'] = await computeHmacSha1(endpoint.accessToken, payload);
|
||||
}
|
||||
|
||||
const timeoutMs = endpoint.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
|
||||
try {
|
||||
const response = await fetch(endpoint.url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: payload,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
|
||||
// OneBot v11: if the response has a JSON body, it's a quick operation
|
||||
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 {
|
||||
log.warn('POST %s returned %d', endpoint.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!this.stopped) {
|
||||
log.warn('POST %s failed: %s', endpoint.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.context.api);
|
||||
} catch (error) {
|
||||
log.warn('quick operation failed: %s', error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
|
||||
const { createHmac } = await import('crypto');
|
||||
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a quick operation based on the event type and the response body.
|
||||
* This implements the .handle_quick_operation hidden API behavior.
|
||||
* See: https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
|
||||
*/
|
||||
export async function executeQuickOperation(
|
||||
event: JsonObject,
|
||||
operation: Record<string, unknown>,
|
||||
api: import('./api-handler').ApiHandler,
|
||||
): Promise<void> {
|
||||
const postType = event.post_type as string;
|
||||
|
||||
if (postType === 'message') {
|
||||
// Quick reply
|
||||
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 import('./types').JsonValue,
|
||||
auto_escape: autoEscape,
|
||||
};
|
||||
// at_sender defaults to true for group messages
|
||||
if (operation.at_sender !== false && event.user_id) {
|
||||
// Prepend an @ segment
|
||||
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 import('./types').JsonValue;
|
||||
params.auto_escape = false;
|
||||
} else if (Array.isArray(operation.reply)) {
|
||||
params.message = [atSegment, ...(operation.reply as unknown[])] as import('./types').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 import('./types').JsonValue,
|
||||
auto_escape: autoEscape,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Quick delete
|
||||
if (operation.delete) {
|
||||
await api.handle('delete_msg', { message_id: event.message_id as number });
|
||||
}
|
||||
|
||||
// Quick ban (group only)
|
||||
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 import('./types').JsonValue,
|
||||
});
|
||||
}
|
||||
|
||||
// Quick kick (group only)
|
||||
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 as unknown as import('./types').JsonValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 import('./types').JsonValue,
|
||||
remark: (operation.remark ?? '') as import('./types').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 import('./types').JsonValue,
|
||||
reason: (operation.reason ?? '') as import('./types').JsonValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { HttpServerEndpoint, OneBotConfig } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export interface HttpTransportContext {
|
||||
api: ApiHandler;
|
||||
}
|
||||
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpTransport {
|
||||
private readonly context: HttpTransportContext;
|
||||
private readonly servers = new Map<string, Server>();
|
||||
private endpoints: HttpServerEndpoint[] = [];
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
||||
this.endpoints = [...config.httpServers];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextEndpoints = [...config.httpServers];
|
||||
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
|
||||
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextEndpoints) {
|
||||
if (!this.servers.has(httpServerKey(endpoint))) {
|
||||
this.startEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.endpoints = nextEndpoints;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
for (const server of this.servers.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
private startEndpoint(endpoint: HttpServerEndpoint): void {
|
||||
const expectedPath = normalizePath(endpoint.path ?? '/');
|
||||
const endpointToken = endpoint.accessToken ?? '';
|
||||
const server = createServer((req, res) => {
|
||||
void this.handleRequest(expectedPath, endpointToken, req, res);
|
||||
});
|
||||
|
||||
server.on('listening', () => {
|
||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
|
||||
});
|
||||
|
||||
server.on('error', (error) => {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
server.listen(endpoint.port, endpoint.host);
|
||||
this.servers.set(httpServerKey(endpoint), server);
|
||||
}
|
||||
|
||||
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
|
||||
const incomingPath = parsedUrl.pathname;
|
||||
|
||||
// Determine the expected prefix (e.g., "/" or "/api/")
|
||||
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
|
||||
let action = '';
|
||||
|
||||
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
|
||||
action = ''; // No action in URL (legacy body mode)
|
||||
} else if (incomingPath.startsWith(ep)) {
|
||||
action = incomingPath.substring(ep.length); // Extract action from URL
|
||||
} 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()) {
|
||||
try {
|
||||
const parsedBody = JSON.parse(bodyContent);
|
||||
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||||
// Legacy format: { action: "...", params: {...} } vs standard raw params
|
||||
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 {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
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;
|
||||
}
|
||||
|
||||
// Handle the API call
|
||||
const response = await this.context.api.handle(action, params as import('./types').JsonObject);
|
||||
|
||||
if (echo !== undefined) {
|
||||
response.echo = echo as import('./types').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 parseRequestPath(urlValue: string): string {
|
||||
try {
|
||||
return new URL(urlValue, 'http://127.0.0.1').pathname;
|
||||
} catch {
|
||||
return '/';
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePath(pathValue: string): string {
|
||||
const path = pathValue.trim() || '/';
|
||||
if (path === '/') return '/';
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
function httpServerKey(endpoint: HttpServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizePath(endpoint.path ?? '/')}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
// 1. Header auth
|
||||
const rawAuth = request.headers.authorization;
|
||||
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
|
||||
if (auth === `Bearer ${token}`) return true;
|
||||
|
||||
// 2. Query string auth
|
||||
try {
|
||||
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
||||
if (url.searchParams.get('access_token') === token) {
|
||||
return true;
|
||||
}
|
||||
} catch {}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
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,614 @@
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { ForwardNodePayload } from '../bridge/events';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import type { ApiActionContext, MessageSendResult } from './api-handler';
|
||||
import { elementsToOneBotSegments } from './event-converter';
|
||||
import { MessageStore } from './message-store';
|
||||
import { parseMessage } from './message-parser';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
|
||||
export interface InstanceRef {
|
||||
uin: string;
|
||||
qqInfo: QQInfo;
|
||||
bridge: Bridge;
|
||||
messageStore: MessageStore;
|
||||
musicSignUrl?: string;
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||
}
|
||||
|
||||
export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||
const { bridge, qqInfo, messageStore } = ref;
|
||||
|
||||
return {
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
isOnline: () => true,
|
||||
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => false,
|
||||
sendPrivateMessage: (userId, message, autoEscape) => handleSendPrivate(ref, userId, message, autoEscape),
|
||||
sendGroupMessage: (groupId, message, autoEscape) => handleSendGroup(ref, groupId, message, autoEscape),
|
||||
deleteMessage: (messageId, meta) => handleDeleteMessage(bridge, meta),
|
||||
// Info retrieval (async, triggers OIDB fetch)
|
||||
getFriendList: () => handleGetFriendList(bridge, qqInfo),
|
||||
getGroupList: (noCache) => handleGetGroupList(bridge, qqInfo, noCache),
|
||||
getGroupInfo: (groupId, noCache) => handleGetGroupInfo(bridge, qqInfo, groupId, noCache),
|
||||
getGroupMemberList: (groupId, noCache) => handleGetGroupMemberList(bridge, qqInfo, groupId, noCache),
|
||||
getGroupMemberInfo: (groupId, userId, noCache) => handleGetGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
|
||||
getStrangerInfo: (userId) => handleGetStrangerInfo(bridge, qqInfo, userId),
|
||||
// Group admin
|
||||
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
|
||||
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
|
||||
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
|
||||
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
|
||||
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
|
||||
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
|
||||
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
|
||||
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
|
||||
// Group file
|
||||
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
|
||||
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
|
||||
return result.fileId;
|
||||
},
|
||||
uploadPrivateFile: async (userId, file, name, uploadFile) => {
|
||||
const result = await bridge.uploadPrivateFile(userId, file, name ?? '', uploadFile ?? true);
|
||||
return result.fileId;
|
||||
},
|
||||
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
|
||||
getGroupFiles: (groupId, folderId) => handleGetGroupFiles(bridge, groupId, folderId),
|
||||
deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId),
|
||||
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory),
|
||||
createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'),
|
||||
deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId),
|
||||
renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName),
|
||||
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
|
||||
// Requests
|
||||
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
|
||||
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
|
||||
// Extended
|
||||
sendLike: (userId, times) => bridge.sendLike(userId, times),
|
||||
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
|
||||
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
|
||||
setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true),
|
||||
deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false),
|
||||
// New extended
|
||||
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
|
||||
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
|
||||
getGroupMsgHistory: (groupId, messageId, count) => handleGetGroupMsgHistory(messageStore, groupId, messageId, count),
|
||||
getFriendMsgHistory: (userId, messageId, count) => handleGetFriendMsgHistory(messageStore, userId, messageId, count),
|
||||
handleGetGroupSystemMsg: async () => {
|
||||
try {
|
||||
const reqs = await bridge.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 []; }
|
||||
},
|
||||
getDownloadRKeys: async () => {
|
||||
try {
|
||||
const rkeys = await bridge.fetchDownloadRKeys();
|
||||
return rkeys.map(r => ({
|
||||
rkey: r.rkey, type: r.type, ttl: r.ttlSeconds, create_time: r.createTime,
|
||||
} as JsonObject));
|
||||
} catch { return []; }
|
||||
},
|
||||
sendGroupForwardMsg: async (groupId, messages) => {
|
||||
return handleSendGroupForward(ref, groupId, messages);
|
||||
},
|
||||
sendPrivateForwardMsg: async (userId, messages) => {
|
||||
return handleSendPrivateForward(ref, userId, messages);
|
||||
},
|
||||
sendForwardMsg: async (messages) => {
|
||||
return handleUploadForward(ref, messages);
|
||||
},
|
||||
getForwardMsg: async (resId) => {
|
||||
return handleGetForward(ref, resId);
|
||||
},
|
||||
// Extended NapCat-compatible
|
||||
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
|
||||
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
|
||||
setMsgEmojiLike: async (messageId, emojiId, set) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
|
||||
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// --- Login info ---
|
||||
|
||||
function getLoginInfo(ref: InstanceRef): { userId: number; nickname: string } {
|
||||
const userId = parseInt(ref.uin, 10) || 0;
|
||||
const nickname = ref.qqInfo.nickname || ref.uin;
|
||||
return { userId, nickname };
|
||||
}
|
||||
|
||||
async function refreshAllGroupMembersCache(bridge: Bridge, qqInfo: QQInfo): Promise<void> {
|
||||
let groups = qqInfo.groups;
|
||||
try {
|
||||
groups = await bridge.fetchGroupList();
|
||||
} catch { /* use cached groups */ }
|
||||
|
||||
for (const g of groups) {
|
||||
try {
|
||||
await bridge.fetchGroupMemberList(g.groupId);
|
||||
} catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHistoryCount(count?: number): number {
|
||||
if (!Number.isFinite(count)) return 20;
|
||||
const n = Math.trunc(count as number);
|
||||
if (n <= 0) return 20;
|
||||
if (n > 200) return 200;
|
||||
return n;
|
||||
}
|
||||
|
||||
function sanitizeMessageEventForApi(event: JsonObject): JsonObject {
|
||||
const result: JsonObject = { ...event };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? 0) as JsonValue;
|
||||
return result;
|
||||
}
|
||||
|
||||
// --- Info retrieval ---
|
||||
|
||||
async function handleGetFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
|
||||
try {
|
||||
const friends = await bridge.fetchFriendList();
|
||||
return friends.map(f => ({
|
||||
user_id: f.uin as any,
|
||||
nickname: f.nickname as any,
|
||||
remark: f.remark as any,
|
||||
}));
|
||||
} catch {
|
||||
return qqInfo.friends.map(f => ({
|
||||
user_id: f.uin as any,
|
||||
nickname: f.nickname as any,
|
||||
remark: f.remark as any,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGetGroupList(bridge: Bridge, qqInfo: QQInfo, noCache?: boolean): Promise<JsonObject[]> {
|
||||
try {
|
||||
if (noCache) {
|
||||
await refreshAllGroupMembersCache(bridge, qqInfo);
|
||||
} else if (qqInfo.groups.length === 0) {
|
||||
await bridge.fetchGroupList();
|
||||
}
|
||||
} catch { /* use cached */ }
|
||||
return qqInfo.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,
|
||||
}));
|
||||
}
|
||||
|
||||
async function handleGetGroupInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject | null> {
|
||||
if (noCache) {
|
||||
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
|
||||
} else if (!qqInfo.findGroup(groupId)) {
|
||||
try { await bridge.fetchGroupList(); } catch { /* use cached */ }
|
||||
}
|
||||
const g = qqInfo.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,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleGetGroupMemberList(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject[]> {
|
||||
if (noCache) {
|
||||
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
|
||||
|
||||
const g = qqInfo.findGroup(groupId);
|
||||
if (!g) return [];
|
||||
const result: JsonObject[] = [];
|
||||
for (const [, m] of g.members) {
|
||||
result.push({
|
||||
group_id: groupId as any, user_id: m.uin as any,
|
||||
nickname: m.nickname as any, card: m.card as any,
|
||||
sex: 'unknown' as any, age: 0 as any,
|
||||
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
|
||||
level: String(m.level) as any, role: m.role as any, title: m.title as any,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await bridge.fetchGroupMemberList(groupId);
|
||||
return members.map(m => ({
|
||||
group_id: groupId as any,
|
||||
user_id: m.uin as any,
|
||||
nickname: m.nickname as any,
|
||||
card: m.card as any,
|
||||
sex: 'unknown' as any,
|
||||
age: 0 as any,
|
||||
join_time: m.joinTime as any,
|
||||
last_sent_time: m.lastSentTime as any,
|
||||
level: String(m.level) as any,
|
||||
role: m.role as any,
|
||||
title: m.title as any,
|
||||
}));
|
||||
} catch {
|
||||
const g = qqInfo.findGroup(groupId);
|
||||
if (!g) return [];
|
||||
const result: JsonObject[] = [];
|
||||
for (const [, m] of g.members) {
|
||||
result.push({
|
||||
group_id: groupId as any, user_id: m.uin as any,
|
||||
nickname: m.nickname as any, card: m.card as any,
|
||||
sex: 'unknown' as any, age: 0 as any,
|
||||
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
|
||||
level: String(m.level) as any, role: m.role as any, title: m.title as any,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGetGroupMemberInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, userId: number, noCache?: boolean): Promise<JsonObject | null> {
|
||||
if (noCache) {
|
||||
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
|
||||
} else if (!qqInfo.findGroupMember(groupId, userId)) {
|
||||
try { await bridge.fetchGroupMemberList(groupId); } catch { /* use cached */ }
|
||||
}
|
||||
const m = qqInfo.findGroupMember(groupId, userId);
|
||||
if (!m) return null;
|
||||
return {
|
||||
group_id: groupId as any, user_id: m.uin as any,
|
||||
nickname: m.nickname as any, card: m.card as any,
|
||||
sex: 'unknown' as any, age: 0 as any,
|
||||
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
|
||||
level: String(m.level) as any, role: m.role as any, title: m.title as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleGetGroupFiles(bridge: Bridge, groupId: number, folderId?: string): Promise<JsonObject> {
|
||||
const result = await bridge.fetchGroupFiles(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,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleGetStrangerInfo(bridge: Bridge, qqInfo: QQInfo, userId: number): Promise<JsonObject | null> {
|
||||
try {
|
||||
const p = await bridge.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 = qqInfo.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 };
|
||||
}
|
||||
}
|
||||
|
||||
// --- Message history ---
|
||||
|
||||
async function handleGetGroupMsgHistory(
|
||||
messageStore: MessageStore,
|
||||
groupId: number,
|
||||
messageId?: number,
|
||||
count?: number,
|
||||
): Promise<JsonObject[]> {
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) return [];
|
||||
const limit = normalizeHistoryCount(count);
|
||||
|
||||
let anchorSequence: number | undefined;
|
||||
if (Number.isInteger(messageId) && messageId !== 0) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return [];
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(true, groupId, limit, anchorSequence);
|
||||
return events
|
||||
.filter((event) => {
|
||||
if (event.message_type !== 'group') return false;
|
||||
const gid = Number(event.group_id ?? 0);
|
||||
return Number.isFinite(gid) && Math.trunc(gid) === groupId;
|
||||
})
|
||||
.map(sanitizeMessageEventForApi);
|
||||
}
|
||||
|
||||
async function handleGetFriendMsgHistory(
|
||||
messageStore: MessageStore,
|
||||
userId: number,
|
||||
messageId?: number,
|
||||
count?: number,
|
||||
): Promise<JsonObject[]> {
|
||||
if (!Number.isInteger(userId) || userId <= 0) return [];
|
||||
const limit = normalizeHistoryCount(count);
|
||||
|
||||
let anchorSequence: number | undefined;
|
||||
if (Number.isInteger(messageId) && messageId !== 0) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return [];
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(false, userId, limit, anchorSequence);
|
||||
return events
|
||||
.filter((event) => {
|
||||
if (event.message_type !== 'private') return false;
|
||||
const uid = Number(event.user_id ?? 0);
|
||||
return Number.isFinite(uid) && Math.trunc(uid) === userId;
|
||||
})
|
||||
.map(sanitizeMessageEventForApi);
|
||||
}
|
||||
|
||||
// --- Delete message ---
|
||||
|
||||
async function handleDeleteMessage(bridge: Bridge, meta: MessageMeta): Promise<void> {
|
||||
if (meta.isGroup) {
|
||||
await bridge.recallGroupMessage(meta.targetId, meta.sequence);
|
||||
} else {
|
||||
await bridge.recallPrivateMessage(
|
||||
meta.targetId, meta.clientSequence, meta.sequence, meta.random, meta.timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Group request ---
|
||||
|
||||
async function handleGroupAddRequest(bridge: Bridge, 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 groupId = parseInt(parts[1], 10);
|
||||
if (!groupId) throw new Error('invalid group_id in flag');
|
||||
// We need sequence and eventType -- fetch from group requests
|
||||
const requests = await bridge.fetchGroupRequests();
|
||||
const matching = requests.find(r => r.groupId === groupId);
|
||||
if (matching) {
|
||||
await bridge.setGroupAddRequest(groupId, matching.sequence, matching.eventType, approve, reason, matching.filtered);
|
||||
} else {
|
||||
throw new Error('matching group request not found');
|
||||
}
|
||||
}
|
||||
|
||||
// --- Essence ---
|
||||
|
||||
async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, messageId: number, enable: boolean): Promise<void> {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
|
||||
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
|
||||
}
|
||||
|
||||
// --- Send message ---
|
||||
|
||||
async function handleSendPrivate(
|
||||
ref: InstanceRef,
|
||||
userId: number,
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) =>
|
||||
ref.messageStore.resolveReplySequence(false, userId, replyMessageId),
|
||||
musicSignUrl: ref.musicSignUrl,
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
// Cache the sent message meta
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: userId,
|
||||
sequence: receipt.sequence,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: receipt.clientSequence,
|
||||
random: receipt.random,
|
||||
timestamp: receipt.timestamp,
|
||||
});
|
||||
|
||||
return { messageId };
|
||||
}
|
||||
|
||||
async function handleSendGroup(
|
||||
ref: InstanceRef,
|
||||
groupId: number,
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) =>
|
||||
ref.messageStore.resolveReplySequence(true, groupId, replyMessageId),
|
||||
musicSignUrl: ref.musicSignUrl,
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||
|
||||
// Cache the sent message meta
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: groupId,
|
||||
sequence: receipt.sequence,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: receipt.clientSequence,
|
||||
random: receipt.random,
|
||||
timestamp: receipt.timestamp,
|
||||
});
|
||||
|
||||
return { messageId };
|
||||
}
|
||||
|
||||
async function handleSendGroupForward(
|
||||
ref: InstanceRef,
|
||||
groupId: number,
|
||||
messages: JsonValue,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
|
||||
const receipt = await ref.bridge.sendGroupMessage(groupId, [{ type: 'forward', resId: forwardId }]);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: groupId,
|
||||
sequence: receipt.sequence,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: receipt.clientSequence,
|
||||
random: receipt.random,
|
||||
timestamp: receipt.timestamp,
|
||||
});
|
||||
|
||||
return { messageId, forwardId };
|
||||
}
|
||||
|
||||
async function handleSendPrivateForward(
|
||||
ref: InstanceRef,
|
||||
userId: number,
|
||||
messages: JsonValue,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, [{ type: 'forward', resId: forwardId }]);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: userId,
|
||||
sequence: receipt.sequence,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: receipt.clientSequence,
|
||||
random: receipt.random,
|
||||
timestamp: receipt.timestamp,
|
||||
});
|
||||
|
||||
return { messageId, forwardId };
|
||||
}
|
||||
|
||||
async function handleUploadForward(
|
||||
ref: InstanceRef,
|
||||
messages: JsonValue,
|
||||
): Promise<{ forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||
return { forwardId };
|
||||
}
|
||||
|
||||
async function handleGetForward(
|
||||
ref: InstanceRef,
|
||||
resId: string,
|
||||
): Promise<JsonObject[]> {
|
||||
const nodes = await ref.bridge.fetchForwardNodes(resId);
|
||||
const results: JsonObject[] = [];
|
||||
for (const node of nodes) {
|
||||
results.push({
|
||||
type: 'node' as any,
|
||||
data: {
|
||||
user_id: node.userUin as any,
|
||||
nickname: node.nickname as any,
|
||||
uin: String(node.userUin) as any,
|
||||
name: node.nickname as any,
|
||||
content: await elementsToOneBotSegments(node.elements, false, node.userUin) as any,
|
||||
} as any,
|
||||
} as JsonObject);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
async function parseForwardNodes(ref: InstanceRef, messages: JsonValue): Promise<ForwardNodePayload[]> {
|
||||
if (!Array.isArray(messages)) {
|
||||
throw new Error('forward messages must be an array');
|
||||
}
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
for (const item of messages) {
|
||||
const segment = asJsonObject(item);
|
||||
if (!segment) continue;
|
||||
|
||||
let nodeData: JsonObject | null = null;
|
||||
if (String(segment.type ?? '') === 'node') {
|
||||
nodeData = asJsonObject(segment.data);
|
||||
} else if (segment.content !== undefined || segment.message !== undefined) {
|
||||
nodeData = segment;
|
||||
}
|
||||
if (!nodeData) continue;
|
||||
|
||||
const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id);
|
||||
if (messageId > 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
if (!event) throw new Error(`forward node message_id not found: ${messageId}`);
|
||||
|
||||
const eventSender = asJsonObject(event.sender) ?? {};
|
||||
const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? '');
|
||||
const userUin = toPositiveInt(event.user_id);
|
||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||
const elements = await parseMessage(content, false);
|
||||
if (userUin > 0 && elements.length > 0) {
|
||||
nodes.push({ userUin, nickname: nickname || String(userUin), elements });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const userUin = toPositiveInt(nodeData.user_id ?? nodeData.uin);
|
||||
if (userUin <= 0) throw new Error('forward node user_id/uin is required');
|
||||
|
||||
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
const elements = await parseMessage(content, false);
|
||||
if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`);
|
||||
|
||||
nodes.push({ userUin, nickname, elements });
|
||||
}
|
||||
|
||||
if (nodes.length === 0) {
|
||||
throw new Error('forward node list is empty');
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
function asJsonObject(value: JsonValue | undefined): JsonObject | null {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
|
||||
return value as JsonObject;
|
||||
}
|
||||
|
||||
function toPositiveInt(value: JsonValue | undefined): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return Math.max(0, Math.trunc(parsed));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { Bridge, DownloadRKeyInfo } from '../bridge/bridge';
|
||||
import { createLogger } from '../utils/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: Bridge, uin: string): void {
|
||||
bridge.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: Bridge, 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: Bridge, 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: Bridge, isGroup: boolean): string | null {
|
||||
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
return this.findRKeyForType(bridge, primaryType);
|
||||
}
|
||||
|
||||
private findRKeyForType(bridge: Bridge, 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.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,276 @@
|
||||
import path from 'path';
|
||||
import type { QQEventVariant } from '../bridge/events';
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import { EventConverter } from './event-converter';
|
||||
import { MessageStore } from './message-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext } from './instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
|
||||
import { HttpTransport } from './http-transport';
|
||||
import { HttpPostTransport } from './http-post-transport';
|
||||
import { WsTransport } from './ws-transport';
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
|
||||
readonly qqInfo: QQInfo;
|
||||
private readonly bridge: Bridge;
|
||||
private readonly apiHandler: ApiHandler;
|
||||
private readonly eventConverter: EventConverter;
|
||||
private readonly messageStore: MessageStore;
|
||||
private readonly httpTransport: HttpTransport;
|
||||
private readonly httpPostTransport: HttpPostTransport;
|
||||
private readonly wsTransport: WsTransport;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
private online = true;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||
|
||||
constructor(uin: string, qqInfo: QQInfo, bridge: Bridge, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.qqInfo = qqInfo;
|
||||
this.bridge = bridge;
|
||||
|
||||
this.eventConverter = new EventConverter();
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.eventConverter.setImageUrlResolver((element, isGroup) =>
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup));
|
||||
this.eventConverter.setMediaUrlResolver(async (element, isGroup, sessionId) => {
|
||||
// Fetch URL from bridge if not already present
|
||||
if (!element.url) {
|
||||
try {
|
||||
if (element.type === 'file' && element.fileId) {
|
||||
element.url = isGroup
|
||||
? await this.bridge.fetchGroupFileUrl(sessionId, element.fileId)
|
||||
: element.fileHash
|
||||
? await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash)
|
||||
: '';
|
||||
} else if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
|
||||
if (isGroup) {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode)
|
||||
: await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode);
|
||||
} else {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode)
|
||||
: await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode);
|
||||
}
|
||||
}
|
||||
} catch { /* best-effort */ }
|
||||
}
|
||||
// Then apply RKey if needed
|
||||
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
|
||||
});
|
||||
this.eventConverter.setMessageIdResolver((isGroup, sessionId, sequence, eventName) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)));
|
||||
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
|
||||
|
||||
const context = buildApiContext({
|
||||
uin: this.uin,
|
||||
qqInfo: this.qqInfo,
|
||||
bridge: this.bridge,
|
||||
messageStore: this.messageStore,
|
||||
musicSignUrl: config.musicSignUrl,
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
});
|
||||
this.apiHandler = new ApiHandler(context);
|
||||
|
||||
this.httpTransport = new HttpTransport(config, {
|
||||
api: this.apiHandler,
|
||||
});
|
||||
|
||||
this.httpPostTransport = new HttpPostTransport(config, {
|
||||
uin: this.uin,
|
||||
api: this.apiHandler,
|
||||
});
|
||||
|
||||
this.wsTransport = new WsTransport(config, {
|
||||
uin: this.uin,
|
||||
api: this.apiHandler,
|
||||
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
|
||||
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
|
||||
});
|
||||
|
||||
this.httpTransport.start();
|
||||
this.httpPostTransport.start();
|
||||
this.wsTransport.start();
|
||||
this.startHeartbeat();
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.httpTransport.reloadConfig(config);
|
||||
this.httpPostTransport.reloadConfig(config);
|
||||
this.wsTransport.reloadConfig(config);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
this.httpTransport.stop();
|
||||
this.httpPostTransport.stop();
|
||||
this.wsTransport.stop();
|
||||
this.messageStore.close();
|
||||
}
|
||||
|
||||
onBridgeEvent(event: QQEventVariant): void {
|
||||
this.cacheMessageMetaFromBridgeEvent(event);
|
||||
|
||||
void this.dispatchBridgeEventAsync(event);
|
||||
}
|
||||
|
||||
private async dispatchBridgeEventAsync(event: QQEventVariant): Promise<void> {
|
||||
const converted = await this.eventConverter.convert(this.uin, event);
|
||||
if (!converted) return;
|
||||
|
||||
this.dispatchEvent(converted);
|
||||
}
|
||||
|
||||
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.wsTransport.publishEvent(event);
|
||||
this.httpPostTransport.publishEvent(event);
|
||||
}
|
||||
|
||||
private cacheMessageEvent(event: JsonObject): void {
|
||||
if (event.post_type !== 'message') 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 cacheMessageMetaFromBridgeEvent(event: QQEventVariant): void {
|
||||
if (event.kind === 'group_message') {
|
||||
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
|
||||
this.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: event.groupId,
|
||||
sequence: event.msgSeq,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: event.msgId,
|
||||
timestamp: event.time,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.kind === 'friend_message') {
|
||||
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
|
||||
this.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: event.senderUin,
|
||||
sequence: event.msgSeq,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: event.msgId,
|
||||
timestamp: event.time,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.kind === 'temp_message') {
|
||||
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
|
||||
this.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: event.senderUin,
|
||||
sequence: event.msgSeq,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: event.time,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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,149 @@
|
||||
import type { QQEventVariant } from '../bridge/events';
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { OneBotInstance } from './instance';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
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, qqInfo, bridge) => {
|
||||
this.onSessionStarted(uin, qqInfo, bridge);
|
||||
});
|
||||
|
||||
bridgeManager.setSessionClosedCallback((uin) => {
|
||||
this.onSessionClosed(uin);
|
||||
});
|
||||
|
||||
bridgeManager.setEventCallback((uin, event) => {
|
||||
this.onBridgeEvent(uin, event);
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
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, qqInfo: QQInfo, bridge: Bridge): void {
|
||||
if (this.instances.has(uin)) return;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const instance = new OneBotInstance(uin, qqInfo, bridge, config);
|
||||
|
||||
const activePid = bridge.activePid;
|
||||
if (activePid !== null) {
|
||||
instance.addPid(activePid);
|
||||
}
|
||||
|
||||
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, qqInfo, 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);
|
||||
}
|
||||
|
||||
private onBridgeEvent(uin: string, event: QQEventVariant): void {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return;
|
||||
|
||||
instance.onBridgeEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {
|
||||
// Step 1: Fetch friend list + derive self profile
|
||||
try {
|
||||
const friends = await bridge.fetchFriendList();
|
||||
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
for (const f of friends) {
|
||||
if (f.uin === selfUin) {
|
||||
qqInfo.setSelfProfile({
|
||||
uin: f.uin, uid: f.uid,
|
||||
nickname: f.nickname || uin,
|
||||
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
|
||||
});
|
||||
qqInfo.nickname = f.nickname || uin;
|
||||
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.warn('failed to load friends 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.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.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,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,326 @@
|
||||
// OneBot11 message segment parser.
|
||||
// Converts OneBot message format (string with CQ codes or JSON segment arrays)
|
||||
// into internal MessageElement arrays for sending.
|
||||
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { JsonValue, JsonObject } from './types';
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
musicSignUrl?: string;
|
||||
}
|
||||
|
||||
// --- CQ Code parsing ---
|
||||
|
||||
const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g;
|
||||
|
||||
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 {
|
||||
return text
|
||||
.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>;
|
||||
}
|
||||
|
||||
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> {
|
||||
switch (type) {
|
||||
case 'text': {
|
||||
const text = String(data.text ?? '');
|
||||
return text ? { type: 'text', text } : null;
|
||||
}
|
||||
case 'face': {
|
||||
const id = parseInt(String(data.id ?? '0'), 10);
|
||||
return { type: 'face', faceId: id };
|
||||
}
|
||||
case 'at': {
|
||||
const qq = String(data.qq ?? '');
|
||||
if (qq === 'all') {
|
||||
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
||||
}
|
||||
const uin = parseInt(qq, 10);
|
||||
return uin > 0 ? { type: 'at', targetUin: uin, text: `@${uin} ` } : null;
|
||||
}
|
||||
case 'reply': {
|
||||
const id = parseInt(String(data.id ?? '0'), 10);
|
||||
if (!Number.isInteger(id) || id === 0) return null;
|
||||
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
if (typeof resolved === 'number' && resolved > 0) {
|
||||
return { type: 'reply', replySeq: resolved };
|
||||
}
|
||||
}
|
||||
|
||||
// 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 ?? ''),
|
||||
flash: data.type === 'flash',
|
||||
subType: parseInt(String(data.subType ?? '0'), 10),
|
||||
summary: data.summary ? String(data.summary) : undefined,
|
||||
};
|
||||
}
|
||||
case 'record': {
|
||||
return {
|
||||
type: 'record',
|
||||
url: String(data.file ?? data.url ?? ''),
|
||||
};
|
||||
}
|
||||
case 'video': {
|
||||
return {
|
||||
type: 'video',
|
||||
url: String(data.file ?? data.url ?? ''),
|
||||
};
|
||||
}
|
||||
case 'json': {
|
||||
return {
|
||||
type: 'json',
|
||||
text: String(data.data ?? ''),
|
||||
};
|
||||
}
|
||||
case 'xml': {
|
||||
return {
|
||||
type: 'xml',
|
||||
text: String(data.data ?? ''),
|
||||
subType: parseInt(String(data.id ?? '0'), 10),
|
||||
};
|
||||
}
|
||||
case 'poke': {
|
||||
return {
|
||||
type: 'poke',
|
||||
faceId: parseInt(String(data.type ?? data.id ?? '0'), 10),
|
||||
};
|
||||
}
|
||||
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 uin = String(data.user_id ?? data.uin ?? '0');
|
||||
const name = String(data.nickname ?? data.name ?? '');
|
||||
return {
|
||||
type: 'node',
|
||||
targetUin: parseInt(uin, 10) || 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) {
|
||||
console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`);
|
||||
// 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;
|
||||
}
|
||||
default:
|
||||
console.warn(`[MsgParser] unsupported segment type: ${type}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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 = (seg.data ?? {}) as Record<string, unknown>;
|
||||
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 = (seg.data ?? {}) as Record<string, unknown>;
|
||||
const elem = await segmentToElement(seg.type, data, options);
|
||||
return elem ? [elem] : [];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// SQLite-backed message store using node:sqlite (DatabaseSync).
|
||||
// Refactored to use a single unified `messages` table for all message types.
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
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;
|
||||
const row = this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(isGroup ? 1 : 0, sessionId, 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,96 @@
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
export type JsonArray = JsonValue[];
|
||||
|
||||
export interface ApiResponse {
|
||||
status: 'ok' | 'failed';
|
||||
retcode: number;
|
||||
data: JsonValue;
|
||||
echo?: JsonValue;
|
||||
wording?: string;
|
||||
}
|
||||
|
||||
export interface OneBotRequest {
|
||||
action: string;
|
||||
params?: JsonObject;
|
||||
echo?: JsonValue;
|
||||
}
|
||||
|
||||
export interface WsServerEndpoint {
|
||||
name?: string;
|
||||
host: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
role?: WsRole;
|
||||
accessToken?: string;
|
||||
}
|
||||
|
||||
export interface HttpServerEndpoint {
|
||||
name?: string;
|
||||
host: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
accessToken?: string;
|
||||
}
|
||||
|
||||
export interface WsClientEndpoint {
|
||||
name?: string;
|
||||
url: string;
|
||||
role?: WsRole;
|
||||
reconnectIntervalMs?: number;
|
||||
accessToken?: string;
|
||||
}
|
||||
|
||||
export interface HttpPostEndpoint {
|
||||
name?: string;
|
||||
url: string;
|
||||
accessToken?: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface OneBotConfig {
|
||||
httpServers: HttpServerEndpoint[];
|
||||
httpPostEndpoints: HttpPostEndpoint[];
|
||||
wsServers: WsServerEndpoint[];
|
||||
wsClients: WsClientEndpoint[];
|
||||
musicSignUrl?: string;
|
||||
}
|
||||
|
||||
export type WsRole = 'api' | 'event' | 'universal';
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { JsonObject, OneBotConfig, WsClientEndpoint, WsRole, WsServerEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
interface ForwardConnection {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
}
|
||||
|
||||
interface ReverseConnection {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
endpointUrl: string;
|
||||
reconnectIntervalMs: number;
|
||||
key: string;
|
||||
}
|
||||
|
||||
export interface WsTransportContext {
|
||||
uin: string;
|
||||
api: ApiHandler;
|
||||
buildLifecycleEvent: (subType: 'connect' | 'enable' | 'disable') => JsonObject;
|
||||
buildHeartbeatEvent: () => JsonObject;
|
||||
}
|
||||
|
||||
const log = createLogger('OneBot.WS');
|
||||
|
||||
export class WsTransport {
|
||||
private readonly context: WsTransportContext;
|
||||
|
||||
private readonly servers = new Map<string, WebSocketServer>();
|
||||
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||
private readonly reverseConnections = new Set<ReverseConnection>();
|
||||
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
||||
private serverEndpoints: WsServerEndpoint[] = [];
|
||||
private clientEndpoints: WsClientEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||
this.serverEndpoints = [...config.wsServers];
|
||||
this.clientEndpoints = [...config.wsClients];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
this.startServers();
|
||||
this.startReverseClients();
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextServers = [...config.wsServers];
|
||||
const nextClients = [...config.wsClients];
|
||||
const nextServerKeys = new Set(nextServers.map(wsServerKey));
|
||||
const nextClientKeys = new Set(nextClients.map(wsClientKey));
|
||||
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextServerKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped forward server %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextServers) {
|
||||
if (!this.servers.has(wsServerKey(endpoint))) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
for (const conn of [...this.reverseConnections]) {
|
||||
if (!nextClientKeys.has(conn.key)) {
|
||||
safeClose(conn.socket);
|
||||
this.reverseConnections.delete(conn);
|
||||
log.info('stopped reverse client %s', conn.endpointUrl);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextClients) {
|
||||
const key = wsClientKey(endpoint);
|
||||
if (![...this.reverseConnections].some(conn => conn.key === key)) {
|
||||
this.startClientEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.serverEndpoints = nextServers;
|
||||
this.clientEndpoints = nextClients;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
||||
|
||||
for (const timer of this.reconnectTimers) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.reconnectTimers.clear();
|
||||
|
||||
for (const [socket] of this.forwardConnections) {
|
||||
safeClose(socket);
|
||||
}
|
||||
this.forwardConnections.clear();
|
||||
|
||||
for (const conn of this.reverseConnections) {
|
||||
safeClose(conn.socket);
|
||||
}
|
||||
this.reverseConnections.clear();
|
||||
|
||||
for (const server of this.servers.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
publishEvent(event: JsonObject): void {
|
||||
const payload = JSON.stringify(event);
|
||||
|
||||
for (const { socket, role } of this.forwardConnections.values()) {
|
||||
if (role === 'event' || role === 'universal') {
|
||||
safeSend(socket, payload);
|
||||
}
|
||||
}
|
||||
|
||||
for (const { socket, role } of this.reverseConnections.values()) {
|
||||
if (role === 'event' || role === 'universal') {
|
||||
safeSend(socket, payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private startServers(): void {
|
||||
for (const endpoint of this.serverEndpoints) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private startServerEndpoint(endpoint: WsServerEndpoint): void {
|
||||
const wss = new WebSocketServer({
|
||||
host: endpoint.host,
|
||||
port: endpoint.port,
|
||||
path: endpoint.path ?? '/',
|
||||
});
|
||||
|
||||
wss.on('listening', () => {
|
||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, endpoint.path ?? '/');
|
||||
});
|
||||
|
||||
wss.on('connection', (socket, request) => {
|
||||
if (!isAuthorized(request, endpoint.accessToken ?? '')) {
|
||||
safeClose(socket, 1008, 'invalid access token');
|
||||
return;
|
||||
}
|
||||
|
||||
const role = endpoint.role ?? classifyForwardRole(request);
|
||||
const conn: ForwardConnection = { socket, role };
|
||||
this.forwardConnections.set(socket, conn);
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
this.forwardConnections.delete(socket);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.sendBootstrapMetaEvents(socket, role);
|
||||
});
|
||||
|
||||
wss.on('error', (error) => {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.servers.set(wsServerKey(endpoint), wss);
|
||||
}
|
||||
|
||||
private startReverseClients(): void {
|
||||
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
|
||||
}
|
||||
|
||||
private startClientEndpoint(endpoint: WsClientEndpoint): void {
|
||||
const role = endpoint.role ?? 'universal';
|
||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||
this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name);
|
||||
}
|
||||
|
||||
private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string): void {
|
||||
if (this.stopped) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'User-Agent': 'OneBot',
|
||||
'X-Self-ID': this.context.uin,
|
||||
'X-Client-Role': role,
|
||||
};
|
||||
|
||||
if (accessToken) {
|
||||
headers.Authorization = `Bearer ${accessToken}`;
|
||||
}
|
||||
|
||||
const socket = new WebSocket(endpointUrl, { headers });
|
||||
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken) };
|
||||
this.reverseConnections.add(conn);
|
||||
|
||||
socket.on('open', () => {
|
||||
const label = name ? `[${name}] ` : '';
|
||||
log.info('%sreverse connected %s', label, endpointUrl);
|
||||
this.sendBootstrapMetaEvents(socket, role);
|
||||
});
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
this.reverseConnections.delete(conn);
|
||||
if (this.stopped) return;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this.reconnectTimers.delete(timer);
|
||||
this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name);
|
||||
}, reconnectIntervalMs);
|
||||
timer.unref?.();
|
||||
this.reconnectTimers.add(timer);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
log.warn('reverse error %s: %s', endpointUrl, error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: WebSocket.RawData): Promise<void> {
|
||||
if (role !== 'api' && role !== 'universal') return;
|
||||
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) return;
|
||||
|
||||
const response = await this.context.api.processRequest(text);
|
||||
safeSend(socket, response);
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket, role: WsRole): void {
|
||||
if (role !== 'event' && role !== 'universal') return;
|
||||
|
||||
const connectEvent = this.context.buildLifecycleEvent('connect');
|
||||
const enableEvent = this.context.buildLifecycleEvent('enable');
|
||||
const heartbeatEvent = this.context.buildHeartbeatEvent();
|
||||
|
||||
safeSend(socket, JSON.stringify(connectEvent));
|
||||
safeSend(socket, JSON.stringify(enableEvent));
|
||||
safeSend(socket, JSON.stringify(heartbeatEvent));
|
||||
}
|
||||
}
|
||||
|
||||
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 parseRequestPath(urlValue: string): string {
|
||||
try {
|
||||
return new URL(urlValue, 'ws://127.0.0.1').pathname;
|
||||
} catch {
|
||||
return '/';
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeWsPath(pathValue: string | undefined): string {
|
||||
const path = (pathValue ?? '/').trim() || '/';
|
||||
if (path === '/') return '/';
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
function wsServerKey(endpoint: WsServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizeWsPath(endpoint.path)}#${endpoint.role ?? 'auto'}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
function wsClientPartsKey(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string): string {
|
||||
return `${endpointUrl}#${role}#${reconnectIntervalMs}#${accessToken}`;
|
||||
}
|
||||
|
||||
function wsClientKey(endpoint: WsClientEndpoint): string {
|
||||
const role = endpoint.role ?? 'universal';
|
||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||
return wsClientPartsKey(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '');
|
||||
}
|
||||
|
||||
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
// 1. Header auth
|
||||
const rawAuth = request.headers.authorization;
|
||||
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
|
||||
if (auth === `Bearer ${token}`) return true;
|
||||
|
||||
// 2. Query string auth
|
||||
try {
|
||||
const url = new URL(request.url ?? '/', 'ws://127.0.0.1');
|
||||
if (url.searchParams.get('access_token') === token) {
|
||||
return true;
|
||||
}
|
||||
} catch {}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function rawDataToString(raw: WebSocket.RawData): string {
|
||||
if (typeof raw === 'string') return raw;
|
||||
if (raw instanceof Buffer) 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 '';
|
||||
}
|
||||
|
||||
function safeSend(socket: WebSocket, payload: string): void {
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
socket.send(payload, (error) => {
|
||||
if (error) {
|
||||
log.warn('send error: %s', error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
|
||||
if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
|
||||
socket.close(code, reason);
|
||||
}
|
||||
Reference in new issue
Block a user