This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

File diff suppressed because it is too large. Load diff
+111 -83
View File
@@ -2,90 +2,118 @@ import { defineAction, f } from '../action-kit';
import { okResponse } from '../types';
export const actions = [
defineAction({
name: 'get_friend_list',
summary: '获取好友列表',
readOnly: true,
returns: '好友列表数组,每项含 QQ 号、昵称与备注。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
defineAction({
name: 'get_friend_list',
summary: '获取好友列表',
readOnly: true,
returns: '好友列表数组,每项含 QQ 号、昵称与备注。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
},
required: ['user_id', 'nickname', 'remark'],
},
},
params: {},
run: async (_p, ctx) => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
},
}),
params: {},
run: async (_p, ctx) => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
defineAction({
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
returns: '用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
uid: { type: 'string', description: '账号唯一标识(仅查到资料时返回)' },
qid: { type: 'string', description: '自定义账号标识(仅查到资料时返回)' },
nickname: { type: 'string', description: '昵称' },
remark: { type: 'string', description: '好友备注;非好友或未设置时为空字符串' },
sex: { type: 'string', description: '性别(male/female/unknown)' },
age: { type: 'integer', description: '年龄' },
long_nick: { type: 'string', description: '个性签名' },
qq_level: { type: 'integer', description: 'QQ 等级(仅查到资料时返回)' },
qqLevel: { type: 'integer', description: 'QQ 等级,同 qq_level' },
reg_time: { type: 'integer', description: '注册时间戳(秒),不可用时省略' },
is_vip: { type: 'boolean', description: '超级会员状态,兼容 NapCat;不可用时省略' },
is_years_vip: { type: 'boolean', description: '年费会员状态,不可用时省略' },
vip_level: { type: 'integer', description: '会员等级,不可用时省略' },
level: { type: 'integer', description: 'QQ 等级,同 qq_level(仅查到资料时返回)' },
status: { type: 'integer', description: '在线状态码' },
extStatus: { type: 'integer', description: '扩展状态码' },
ext_status: { type: 'integer', description: '扩展状态码(同 extStatus)' },
batteryStatus: { type: 'integer', description: '电量状态' },
customStatus: { type: 'object', description: '自定义状态', nullable: true },
customStatusDescInfo: { type: 'string', description: '自定义状态说明' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
qidian_enterprise_name: { type: 'string', description: '企点企业名称;非企点账号或未获取到时为空字符串' },
},
required: ['user_id', 'nickname', 'remark', 'sex', 'age', 'long_nick'],
},
params: { user_id: f.userId().describe('QQ 号') },
run: async (p, ctx) => {
const userId = p.user_id;
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(info ?? {
user_id: userId, nickname: '', remark: '', sex: 'unknown', age: 0, long_nick: '',
});
}
return okResponse({
user_id: userId, nickname: '', remark: '', sex: 'unknown', age: 0, long_nick: '',
});
},
}),
return okResponse([]);
},
}),
defineAction({
name: 'delete_friend',
summary: '删除好友',
params: { user_id: f.userId().describe('QQ 号'), block: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
return okResponse();
},
}),
defineAction({
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
returns:
'用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
uid: { type: 'string', description: '账号唯一标识(仅查到资料时返回)' },
qid: { type: 'string', description: '自定义账号标识(仅查到资料时返回)' },
nickname: { type: 'string', description: '昵称' },
remark: { type: 'string', description: '好友备注;非好友或未设置时为空字符串' },
sex: { type: 'string', description: '性别(male/female/unknown)' },
age: { type: 'integer', description: '年龄' },
long_nick: { type: 'string', description: '个性签名' },
qq_level: { type: 'integer', description: 'QQ 等级(仅查到资料时返回)' },
qqLevel: { type: 'integer', description: 'QQ 等级,同 qq_level' },
reg_time: { type: 'integer', description: '注册时间戳(秒),不可用时省略' },
is_vip: { type: 'boolean', description: '超级会员状态,兼容 NapCat;不可用时省略' },
is_years_vip: { type: 'boolean', description: '年费会员状态,不可用时省略' },
vip_level: { type: 'integer', description: '会员等级,不可用时省略' },
level: { type: 'integer', description: 'QQ 等级,同 qq_level(仅查到资料时返回)' },
status: { type: 'integer', description: '在线状态码' },
extStatus: { type: 'integer', description: '扩展状态码' },
ext_status: { type: 'integer', description: '扩展状态码(同 extStatus)' },
batteryStatus: { type: 'integer', description: '电量状态' },
customStatus: { type: 'object', description: '自定义状态', nullable: true },
customStatusDescInfo: { type: 'string', description: '自定义状态说明' },
qidian_master_flag: {
type: 'integer',
description: '企点主号标志,0 或 1;普通账号为 0',
},
qidian_crew_flag: {
type: 'integer',
description: '企点员工标志,0 或 1;普通账号为 0',
},
qidian_crew_flag_2: {
type: 'integer',
description: '企点保留标志,0 或 1;普通账号为 0',
},
qidian_enterprise_name: {
type: 'string',
description: '企点企业名称;非企点账号或未获取到时为空字符串',
},
},
required: ['user_id', 'nickname', 'remark', 'sex', 'age', 'long_nick'],
},
params: { user_id: f.userId().describe('QQ 号') },
run: async (p, ctx) => {
const userId = p.user_id;
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(
info ?? {
user_id: userId,
nickname: '',
remark: '',
sex: 'unknown',
age: 0,
long_nick: '',
},
);
}
return okResponse({
user_id: userId,
nickname: '',
remark: '',
sex: 'unknown',
age: 0,
long_nick: '',
});
},
}),
defineAction({
name: 'delete_friend',
summary: '删除好友',
params: { user_id: f.userId().describe('QQ 号'), block: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
return okResponse();
},
}),
];
+322 -265
View File
@@ -2,284 +2,341 @@ import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { okResponse } from '../types';
export const actions = [
groupUserAction({
name: 'set_group_kick',
summary: '踢出群成员',
params: { reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMember(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
},
}),
groupAction({
name: 'set_group_kick_members',
summary: '批量踢出群成员',
params: { user_id: f.array(f.memberId()).nonEmpty(), reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_ban',
summary: '禁言群成员(duration=0 解除)',
params: { duration: f.duration().default(1800) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
return okResponse();
},
}),
groupAction({
name: 'set_group_whole_ban',
summary: '全员禁言开关',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteAll(p.group_id, p.enable);
return okResponse();
},
}),
groupAction({
name: 'set_group_add_option',
summary: '设置加群选项',
params: {
add_type: f.int({ min: 0 }).default(0),
group_question: f.string().optional(),
group_answer: f.string().optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAddOption(
p.group_id, p.add_type, p.group_question, p.group_answer,
);
return okResponse();
},
}),
groupAction({
name: 'set_group_search',
summary: '设置群被搜索方式(群指纹 / 群号搜索开关)',
params: {
no_finger_open: f.int({ min: 0 }).optional(),
no_code_finger_open: f.int({ min: 0 }).optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id, p.no_finger_open, p.no_code_finger_open);
return okResponse();
},
}),
groupAction({
name: 'set_group_member_invite_policy',
summary: '设置群成员邀请策略',
params: {
policy: f.enum(
'disabled',
'require_approval',
'no_approval',
'no_approval_under_100',
),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setMemberInvitePolicy(p.group_id, p.policy);
return okResponse();
},
}),
groupAction({
name: 'set_group_new_member_history_visibility',
summary: '设置新成员是否可查看历史消息',
params: { visible: f.bool() },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setNewMemberHistoryVisibility(p.group_id, p.visible);
return okResponse();
},
}),
groupAction({
name: 'set_group_member_permissions',
summary: '设置群成员权限(仅群主可改)',
params: {
allow_member_upload_album: f.bool().optional(),
allow_member_temporary_session: f.bool().optional(),
allow_member_create_group: f.bool().optional(),
},
rules: (r) => [r.atLeastOneOf(
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
)],
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setMemberPermissions(p.group_id, {
allowMemberUploadAlbum: p.allow_member_upload_album,
allowMemberTemporarySession: p.allow_member_temporary_session,
allowMemberCreateGroup: p.allow_member_create_group,
});
return okResponse();
},
}),
groupAction({
name: 'get_group_admin_settings',
summary: '获取群管理设置的当前值',
readOnly: true,
returns: '与对应设置接口字段对齐的当前群管理设置。',
returnsSchema: {
type: 'object',
properties: {
add_type: { type: 'integer', description: '加群选项(同 set_group_add_option.add_type)' },
group_question: { type: 'string', description: '加群问题(同 set_group_add_option.group_question)' },
group_answer: { type: 'string', description: '加群答案(同 set_group_add_option.group_answer)' },
robot_member_switch: { type: 'integer', description: '机器人加群开关(同 set_group_robot_add_option)' },
robot_member_examine: { type: 'integer', description: '机器人加群审核(同 set_group_robot_add_option)' },
member_invite_policy: {
type: 'string',
enum: ['disabled', 'require_approval', 'no_approval', 'no_approval_under_100'],
description: '成员邀请策略(同 set_group_member_invite_policy.policy)',
groupUserAction({
name: 'set_group_kick',
summary: '踢出群成员',
params: { reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMember(
p.group_id,
p.user_id,
p.reject_add_request,
);
return okResponse();
},
allow_member_upload_album: { type: 'boolean', description: '是否允许成员上传相册' },
allow_member_temporary_session: { type: 'boolean', description: '是否允许成员发起临时会话' },
allow_member_create_group: { type: 'boolean', description: '是否允许成员创建群聊' },
new_member_history_visible: { type: 'boolean', description: '新成员是否可查看历史消息' },
no_finger_open: { type: 'integer', description: '是否关闭群指纹/关键词搜索(0 开 1 关)' },
no_code_finger_open: { type: 'integer', description: '是否关闭群号搜索(0 开 1 关)' },
},
required: [
'add_type',
'group_question',
'group_answer',
'robot_member_switch',
'robot_member_examine',
'member_invite_policy',
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
'new_member_history_visible',
'no_finger_open',
'no_code_finger_open',
],
},
run: async (p, ctx) => {
return okResponse(await ctx.bridge.apis.groupAdmin.getAdminSettings(p.group_id));
},
}),
}),
defineAction({
name: 'get_group_tags',
summary: '读取某个群分类下的资料标签',
readOnly: true,
returns: '该分类下的资料标签列表。',
returnsSchema: {
type: 'object',
properties: {
tags: {
type: 'array',
description: '资料标签',
items: {
groupAction({
name: 'set_group_kick_members',
summary: '批量踢出群成员',
params: {
user_id: f.array(f.memberId()).nonEmpty(),
reject_add_request: f.bool().default(false),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMembers(
p.group_id,
p.user_id,
p.reject_add_request,
);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_ban',
summary: '禁言群成员(duration=0 解除)',
params: { duration: f.duration().default(1800) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
return okResponse();
},
}),
groupAction({
name: 'set_group_whole_ban',
summary: '全员禁言开关',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteAll(p.group_id, p.enable);
return okResponse();
},
}),
groupAction({
name: 'set_group_add_option',
summary: '设置加群选项',
params: {
add_type: f.int({ min: 0 }).default(0),
group_question: f.string().optional(),
group_answer: f.string().optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAddOption(
p.group_id,
p.add_type,
p.group_question,
p.group_answer,
);
return okResponse();
},
}),
groupAction({
name: 'set_group_search',
summary: '设置群被搜索方式(群指纹 / 群号搜索开关)',
params: {
no_finger_open: f.int({ min: 0 }).optional(),
no_code_finger_open: f.int({ min: 0 }).optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSearch(
p.group_id,
p.no_finger_open,
p.no_code_finger_open,
);
return okResponse();
},
}),
groupAction({
name: 'set_group_member_invite_policy',
summary: '设置群成员邀请策略',
params: {
policy: f.enum('disabled', 'require_approval', 'no_approval', 'no_approval_under_100'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setMemberInvitePolicy(p.group_id, p.policy);
return okResponse();
},
}),
groupAction({
name: 'set_group_new_member_history_visibility',
summary: '设置新成员是否可查看历史消息',
params: { visible: f.bool() },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setNewMemberHistoryVisibility(p.group_id, p.visible);
return okResponse();
},
}),
groupAction({
name: 'set_group_member_permissions',
summary: '设置群成员权限(仅群主可改)',
params: {
allow_member_upload_album: f.bool().optional(),
allow_member_temporary_session: f.bool().optional(),
allow_member_create_group: f.bool().optional(),
},
rules: (r) => [
r.atLeastOneOf(
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
),
],
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setMemberPermissions(p.group_id, {
allowMemberUploadAlbum: p.allow_member_upload_album,
allowMemberTemporarySession: p.allow_member_temporary_session,
allowMemberCreateGroup: p.allow_member_create_group,
});
return okResponse();
},
}),
groupAction({
name: 'get_group_admin_settings',
summary: '获取群管理设置的当前值',
readOnly: true,
returns: '与对应设置接口字段对齐的当前群管理设置。',
returnsSchema: {
type: 'object',
properties: {
id: { type: 'integer', description: '标签编号' },
name: { type: 'string', description: '标签名' },
type: { type: 'integer', description: '标签类型' },
add_type: {
type: 'integer',
description: '加群选项(同 set_group_add_option.add_type)',
},
group_question: {
type: 'string',
description: '加群问题(同 set_group_add_option.group_question)',
},
group_answer: {
type: 'string',
description: '加群答案(同 set_group_add_option.group_answer)',
},
robot_member_switch: {
type: 'integer',
description: '机器人加群开关(同 set_group_robot_add_option)',
},
robot_member_examine: {
type: 'integer',
description: '机器人加群审核(同 set_group_robot_add_option)',
},
member_invite_policy: {
type: 'string',
enum: ['disabled', 'require_approval', 'no_approval', 'no_approval_under_100'],
description: '成员邀请策略(同 set_group_member_invite_policy.policy)',
},
allow_member_upload_album: { type: 'boolean', description: '是否允许成员上传相册' },
allow_member_temporary_session: {
type: 'boolean',
description: '是否允许成员发起临时会话',
},
allow_member_create_group: { type: 'boolean', description: '是否允许成员创建群聊' },
new_member_history_visible: {
type: 'boolean',
description: '新成员是否可查看历史消息',
},
no_finger_open: {
type: 'integer',
description: '是否关闭群指纹/关键词搜索(0 开 1 关)',
},
no_code_finger_open: {
type: 'integer',
description: '是否关闭群号搜索(0 开 1 关)',
},
},
required: ['id', 'name', 'type'],
},
required: [
'add_type',
'group_question',
'group_answer',
'robot_member_switch',
'robot_member_examine',
'member_invite_policy',
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
'new_member_history_visible',
'no_finger_open',
'no_code_finger_open',
],
},
},
required: ['tags'],
},
params: { group_class: f.int({ min: 0, max: 0xFFFFFFFF }) },
run: async (p, ctx) => okResponse(await ctx.bridge.apis.groupAdmin.listCategoryTags(p.group_class)),
}),
run: async (p, ctx) => {
return okResponse(await ctx.bridge.apis.groupAdmin.getAdminSettings(p.group_id));
},
}),
defineAction({
name: 'add_group_tag',
summary: '向某个群分类添加资料标签',
params: {
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.addCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
defineAction({
name: 'get_group_tags',
summary: '读取某个群分类下的资料标签',
readOnly: true,
returns: '该分类下的资料标签列表。',
returnsSchema: {
type: 'object',
properties: {
tags: {
type: 'array',
description: '资料标签',
items: {
type: 'object',
properties: {
id: { type: 'integer', description: '标签编号' },
name: { type: 'string', description: '标签名' },
type: { type: 'integer', description: '标签类型' },
},
required: ['id', 'name', 'type'],
},
},
},
required: ['tags'],
},
params: { group_class: f.int({ min: 0, max: 0xffffffff }) },
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.groupAdmin.listCategoryTags(p.group_class)),
}),
defineAction({
name: 'delete_group_tag',
summary: '从某个群分类移除资料标签',
params: {
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.removeCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
defineAction({
name: 'add_group_tag',
summary: '向某个群分类添加资料标签',
params: {
group_class: f.int({ min: 0, max: 0xffffffff }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.addCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_admin',
summary: '设置/取消管理员',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAdmin(p.group_id, p.user_id, p.enable);
return okResponse();
},
}),
defineAction({
name: 'delete_group_tag',
summary: '从某个群分类移除资料标签',
params: {
group_class: f.int({ min: 0, max: 0xffffffff }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.removeCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_card',
summary: '设置群名片(空字符串清除)',
params: { card: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setCard(p.group_id, p.user_id, p.card);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_admin',
summary: '设置/取消管理员',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAdmin(p.group_id, p.user_id, p.enable);
return okResponse();
},
}),
groupAction({
name: 'set_group_name',
summary: '设置群名',
params: { group_name: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setName(p.group_id, p.group_name);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_card',
summary: '设置群名片(空字符串清除)',
params: { card: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setCard(p.group_id, p.user_id, p.card);
return okResponse();
},
}),
groupAction({
name: 'set_group_leave',
summary: '退群',
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.leave(p.group_id);
return okResponse();
},
}),
groupAction({
name: 'set_group_name',
summary: '设置群名',
params: { group_name: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setName(p.group_id, p.group_name);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_special_title',
summary: '设置群头衔',
params: { special_title: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSpecialTitle(p.group_id, p.user_id, p.special_title);
return okResponse();
},
}),
groupAction({
name: 'set_group_leave',
summary: '退群',
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.leave(p.group_id);
return okResponse();
},
}),
// No-op stubs (accept and ignore any params, as before).
defineAction({ name: 'set_group_anonymous', summary: '匿名开关(未实现,返回 ok)', params: {}, run: () => okResponse() }),
defineAction({ name: 'set_group_anonymous_ban', summary: '匿名禁言(未实现,返回 ok)', params: {}, run: () => okResponse() }),
groupUserAction({
name: 'set_group_special_title',
summary: '设置群头衔',
params: { special_title: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSpecialTitle(
p.group_id,
p.user_id,
p.special_title,
);
return okResponse();
},
}),
groupAction({
name: 'set_group_portrait',
summary: '设置群头像',
params: { file: f.image() },
run: async (p, ctx) => {
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
},
}),
// No-op stubs (accept and ignore any params, as before).
defineAction({
name: 'set_group_anonymous',
summary: '匿名开关(未实现,返回 ok)',
params: {},
run: () => okResponse(),
}),
defineAction({
name: 'set_group_anonymous_ban',
summary: '匿名禁言(未实现,返回 ok)',
params: {},
run: () => okResponse(),
}),
groupAction({
name: 'set_group_portrait',
summary: '设置群头像',
params: { file: f.image() },
run: async (p, ctx) => {
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
},
}),
];
+266 -230
View File
@@ -3,256 +3,292 @@ import type { JsonValue } from '../types';
import { okResponse } from '../types';
const albumCoverUrlSchema = {
type: ['object', 'null'],
properties: {
url: { type: 'string', description: '封面地址' },
width: { type: 'integer', description: '封面宽度' },
height: { type: 'integer', description: '封面高度' },
},
required: ['url', 'width', 'height'],
type: ['object', 'null'],
properties: {
url: { type: 'string', description: '封面地址' },
width: { type: 'integer', description: '封面宽度' },
height: { type: 'integer', description: '封面高度' },
},
required: ['url', 'width', 'height'],
};
const albumCoverSchema = {
type: ['object', 'null'],
description: '相册封面;没有封面时为 null',
properties: {
type: { type: 'integer', description: '封面媒体类型' },
image: {
type: ['object', 'null'],
description: '封面图片信息',
properties: {
name: { type: 'string', description: '图片名称' },
sloc: { type: 'string', description: '图片短定位标识' },
lloc: { type: 'string', description: '图片长定位标识' },
photoUrls: {
type: 'array',
description: '不同规格的封面地址',
items: {
type: 'object',
type: ['object', 'null'],
description: '相册封面;没有封面时为 null',
properties: {
type: { type: 'integer', description: '封面媒体类型' },
image: {
type: ['object', 'null'],
description: '封面图片信息',
properties: {
spec: { type: 'integer', description: '图片规格' },
url: albumCoverUrlSchema,
name: { type: 'string', description: '图片名称' },
sloc: { type: 'string', description: '图片短定位标识' },
lloc: { type: 'string', description: '图片长定位标识' },
photoUrls: {
type: 'array',
description: '不同规格的封面地址',
items: {
type: 'object',
properties: {
spec: { type: 'integer', description: '图片规格' },
url: albumCoverUrlSchema,
},
required: ['spec', 'url'],
},
},
defaultUrl: albumCoverUrlSchema,
isGif: { type: 'boolean', description: '是否为动图' },
hasRaw: { type: 'boolean', description: '是否有原图' },
},
required: ['spec', 'url'],
},
required: ['name', 'sloc', 'lloc', 'photoUrls', 'defaultUrl', 'isGif', 'hasRaw'],
},
defaultUrl: albumCoverUrlSchema,
isGif: { type: 'boolean', description: '是否为动图' },
hasRaw: { type: 'boolean', description: '是否有原图' },
},
required: ['name', 'sloc', 'lloc', 'photoUrls', 'defaultUrl', 'isGif', 'hasRaw'],
},
},
required: ['type', 'image'],
required: ['type', 'image'],
};
export const actions = [
groupAction({
name: 'get_group_album_list',
readOnly: true,
returns: '群相册列表数组,每项为一个相册的基本信息。',
returnsSchema: {
type: 'array',
description: '群相册列表',
items: {
type: 'object',
properties: {
id: { type: 'string', description: '相册 id' },
name: { type: 'string', description: '相册名称' },
picNum: { type: 'integer', description: '相册内照片数量' },
createTime: { type: 'integer', description: '相册创建时间(unix 秒)' },
last_upload_time: { type: 'integer', description: '最后上传时间(unix 秒)' },
cover: albumCoverSchema,
createuin: { type: 'string', description: '相册创建者 QQ 号' },
createnickname: { type: 'string', description: '相册创建者昵称(原始 Unicode)' },
groupAction({
name: 'get_group_album_list',
readOnly: true,
returns: '群相册列表数组,每项为一个相册的基本信息。',
returnsSchema: {
type: 'array',
description: '群相册列表',
items: {
type: 'object',
properties: {
id: { type: 'string', description: '相册 id' },
name: { type: 'string', description: '相册名称' },
picNum: { type: 'integer', description: '相册内照片数量' },
createTime: { type: 'integer', description: '相册创建时间(unix 秒)' },
last_upload_time: { type: 'integer', description: '最后上传时间(unix 秒)' },
cover: albumCoverSchema,
createuin: { type: 'string', description: '相册创建者 QQ 号' },
createnickname: {
type: 'string',
description: '相册创建者昵称(原始 Unicode)',
},
},
required: [
'id',
'name',
'picNum',
'createTime',
'last_upload_time',
'cover',
'createuin',
'createnickname',
],
},
},
required: [
'id',
'name',
'picNum',
'createTime',
'last_upload_time',
'cover',
'createuin',
'createnickname',
],
},
},
run: async (p, ctx) => {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse(albumList);
},
}),
run: async (p, ctx) => {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse(albumList);
},
}),
// get_qun_album_list — NapCat-compatible view of QQ NT's AlbumService.
groupAction({
name: 'get_qun_album_list',
readOnly: true,
returns: 'NapCat 风格的相册列表封套:{album_list, attach_info, has_more}。',
returnsSchema: {
type: 'object',
properties: {
album_list: {
type: 'array',
description: '相册列表',
items: {
// get_qun_album_list — NapCat-compatible view of QQ NT's AlbumService.
groupAction({
name: 'get_qun_album_list',
readOnly: true,
returns: 'NapCat 风格的相册列表封套:{album_list, attach_info, has_more}。',
returnsSchema: {
type: 'object',
properties: {
album_id: { type: 'string', description: '相册 id' },
name: { type: 'string', description: '相册名称' },
create_time: { type: 'string', description: '相册创建时间(unix 秒)' },
last_upload_time: { type: 'string', description: '最后上传时间(unix 秒)' },
upload_number: { type: 'string', description: '相册内媒体数量' },
cover: albumCoverSchema,
creator: {
type: 'object',
description: '相册创建者信息',
properties: {
uin: { type: 'string', description: '创建者 QQ 号' },
uid: { type: 'string', description: '创建者 UID' },
nick: { type: 'string', description: '创建者原始 Unicode 昵称' },
album_list: {
type: 'array',
description: '相册列表',
items: {
type: 'object',
properties: {
album_id: { type: 'string', description: '相册 id' },
name: { type: 'string', description: '相册名称' },
create_time: { type: 'string', description: '相册创建时间(unix 秒)' },
last_upload_time: {
type: 'string',
description: '最后上传时间(unix 秒)',
},
upload_number: { type: 'string', description: '相册内媒体数量' },
cover: albumCoverSchema,
creator: {
type: 'object',
description: '相册创建者信息',
properties: {
uin: { type: 'string', description: '创建者 QQ 号' },
uid: { type: 'string', description: '创建者 UID' },
nick: {
type: 'string',
description: '创建者原始 Unicode 昵称',
},
},
},
},
required: [
'album_id',
'name',
'create_time',
'last_upload_time',
'upload_number',
'cover',
],
},
},
},
attach_info: { type: 'string', description: '下一页分页游标' },
has_more: { type: 'boolean', description: '是否还有更多' },
},
required: [
'album_id',
'name',
'create_time',
'last_upload_time',
'upload_number',
'cover',
],
},
required: ['album_list', 'attach_info', 'has_more'],
},
attach_info: { type: 'string', description: '下一页分页游标' },
has_more: { type: 'boolean', description: '是否还有更多' },
},
required: ['album_list', 'attach_info', 'has_more'],
},
params: {
attach_info: f.string().default(''),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupAlbum.listQun(p.group_id, p.attach_info);
return okResponse({
album_list: result.albumList,
attach_info: result.attachInfo,
has_more: result.hasMore,
} as unknown as JsonValue);
},
}),
groupAction({
name: 'upload_image_to_qun_album',
params: {
album_id: f.string({ allowEmpty: false }),
album_name: f.string({ allowEmpty: false }),
file: f.image(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(null);
},
}),
groupAction({
name: 'upload_video_to_qun_album',
summary: '上传视频到群相册',
returns: '{ id: string }',
returnsSchema: {
type: 'object',
properties: {
id: { type: 'string', description: '视频 id' },
},
required: ['id'],
},
params: {
album_id: f.string({ allowEmpty: false }).describe('相册 id'),
album_name: f.string({ allowEmpty: false }).describe('相册名称'),
file: f.video().describe('视频文件'),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupAlbum.uploadVideo(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(result);
},
}),
groupAction({
name: 'get_group_album_media_list',
readOnly: true,
returns: '相册图片/视频列表及下一页分页游标;视频项包含 id、url、cover、尺寸、时长和多规格地址。',
returnsSchema: {
type: 'object',
properties: {
mediaList: {
type: 'array',
description: '相册媒体项列表(各项字段不固定)',
items: { type: 'object' },
params: {
attach_info: f.string().default(''),
},
nextAttachInfo: { type: 'string', description: '下一页分页游标(空串表示无更多)' },
},
required: ['mediaList', 'nextAttachInfo'],
},
params: {
album_id: f.string({ allowEmpty: false }),
attach_info: f.string().default(''),
},
run: async (p, ctx) => {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info);
return okResponse(mediaList as unknown as JsonValue);
},
}),
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupAlbum.listQun(p.group_id, p.attach_info);
return okResponse({
album_list: result.albumList,
attach_info: result.attachInfo,
has_more: result.hasMore,
} as unknown as JsonValue);
},
}),
groupAction({
name: 'do_group_album_comment',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }),
content: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content);
return okResponse(comment as unknown as JsonValue);
},
}),
groupAction({
name: 'upload_image_to_qun_album',
params: {
album_id: f.string({ allowEmpty: false }),
album_name: f.string({ allowEmpty: false }),
file: f.image(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(null);
},
}),
groupAction({
name: 'set_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true);
return okResponse(res);
},
}),
groupAction({
name: 'upload_video_to_qun_album',
summary: '上传视频到群相册',
returns: '{ id: string }',
returnsSchema: {
type: 'object',
properties: {
id: { type: 'string', description: '视频 id' },
},
required: ['id'],
},
params: {
album_id: f.string({ allowEmpty: false }).describe('相册 id'),
album_name: f.string({ allowEmpty: false }).describe('相册名称'),
file: f.video().describe('视频文件'),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupAlbum.uploadVideo(
p.group_id,
p.album_id,
p.album_name,
p.file,
);
return okResponse(result);
},
}),
// 取消点赞群相册媒体
groupAction({
name: 'cancel_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false);
return okResponse(res);
},
}),
groupAction({
name: 'get_group_album_media_list',
readOnly: true,
returns:
'相册图片/视频列表及下一页分页游标;视频项包含 id、url、cover、尺寸、时长和多规格地址。',
returnsSchema: {
type: 'object',
properties: {
mediaList: {
type: 'array',
description: '相册媒体项列表(各项字段不固定)',
items: { type: 'object' },
},
nextAttachInfo: { type: 'string', description: '下一页分页游标(空串表示无更多)' },
},
required: ['mediaList', 'nextAttachInfo'],
},
params: {
album_id: f.string({ allowEmpty: false }),
attach_info: f.string().default(''),
},
run: async (p, ctx) => {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(
p.group_id,
p.album_id,
p.attach_info,
);
return okResponse(mediaList as unknown as JsonValue);
},
}),
groupAction({
name: 'del_group_album_media',
summary: '删除群相册图片或视频',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }).describe('图片长定位标识,或视频 id'),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
return okResponse(res);
},
}),
groupAction({
name: 'do_group_album_comment',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }),
content: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
const comment = await ctx.bridge.apis.groupAlbum.comment(
p.group_id,
p.album_id,
p.lloc,
p.content,
);
return okResponse(comment as unknown as JsonValue);
},
}),
groupAction({
name: 'set_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.like(
p.group_id,
p.album_id,
p.batch_id,
p.lloc || undefined,
true,
);
return okResponse(res);
},
}),
// 取消点赞群相册媒体
groupAction({
name: 'cancel_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.like(
p.group_id,
p.album_id,
p.batch_id,
p.lloc || undefined,
false,
);
return okResponse(res);
},
}),
groupAction({
name: 'del_group_album_media',
summary: '删除群相册图片或视频',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }).describe('图片长定位标识,或视频 id'),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
return okResponse(res);
},
}),
];
+350 -292
View File
@@ -8,314 +8,372 @@ import { RETCODE, failedResponse, okResponse } from '../types';
// semantics that a strict `f.int({min:0}).default(102)` regressed (a *present*
// non-numeric busid was rejected with `expected an integer`). See issue #147.
function busidOr102(raw: unknown): number {
const n = typeof raw === 'number' && Number.isFinite(raw)
? Math.trunc(raw)
: typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))
? Math.trunc(Number(raw))
: NaN;
return Number.isInteger(n) && n >= 0 ? n : 102;
const n =
typeof raw === 'number' && Number.isFinite(raw)
? Math.trunc(raw)
: typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))
? Math.trunc(Number(raw))
: NaN;
return Number.isInteger(n) && n >= 0 ? n : 102;
}
export const actions = [
groupAction({
name: 'upload_group_file',
summary: '上传群文件',
returns: '{ file_id: string }',
// `folder` / `folder_id` are two aliases for one target dir; the first
// non-empty wins, else '/'. Both default '' so the `||` chain matches the
// legacy `asString(folder) || asString(folder_id) || '/'`.
params: {
file: f.file(),
name: f.string().default(''),
folder: f.string().default(''),
folder_id: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const folderId = p.folder || p.folder_id || '/';
const result = await ctx.bridge.apis.groupFile.upload(p.group_id, p.file, p.name, folderId, p.upload_file);
return okResponse({ file_id: result.fileId });
},
}),
groupAction({
name: 'upload_group_file',
summary: '上传群文件',
returns: '{ file_id: string }',
// `folder` / `folder_id` are two aliases for one target dir; the first
// non-empty wins, else '/'. Both default '' so the `||` chain matches the
// legacy `asString(folder) || asString(folder_id) || '/'`.
params: {
file: f.file(),
name: f.string().default(''),
folder: f.string().default(''),
folder_id: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const folderId = p.folder || p.folder_id || '/';
const result = await ctx.bridge.apis.groupFile.upload(
p.group_id,
p.file,
p.name,
folderId,
p.upload_file,
);
return okResponse({ file_id: result.fileId });
},
}),
defineAction({
name: 'upload_private_file',
summary: '上传私聊文件',
returns: '{ file_id: string }',
params: {
user_id: f.userId(),
file: f.file(),
name: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupFile.uploadPrivate(
p.user_id,
p.file,
p.name,
p.upload_file,
false,
);
if (p.upload_file) {
if (!result.fileId) throw new Error('private file upload returned no file_id');
const uploaded = ctx.bridge.recallUploadedFile(result.fileId);
if (!uploaded || uploaded.scope !== 'private' || uploaded.userId !== p.user_id) {
throw new Error(`private file upload metadata missing for file_id ${result.fileId}`);
}
await ctx.sendPrivateMessage(p.user_id, [{
type: 'file',
data: {
file_id: result.fileId,
name: uploaded.fileName,
file_size: uploaded.fileSize,
md5: Buffer.from(uploaded.fileMd5).toString('hex'),
file_hash: result.fileHash ?? uploaded.fileHash ?? '',
},
}], false);
}
return okResponse({ file_id: result.fileId });
},
}),
defineAction({
name: 'upload_private_file',
summary: '上传私聊文件',
returns: '{ file_id: string }',
params: {
user_id: f.userId(),
file: f.file(),
name: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupFile.uploadPrivate(
p.user_id,
p.file,
p.name,
p.upload_file,
false,
);
groupAction({
name: 'get_group_file_url',
summary: '获取群文件下载链接',
readOnly: true,
returns: '群文件下载链接。',
returnsSchema: {
type: 'object',
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
// busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it,
// so a present null/empty/non-numeric value must not 400 the request (#147).
params: { file_id: f.fileId(), busid: f.raw() },
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, busidOr102(p.busid)) });
},
}),
if (p.upload_file) {
if (!result.fileId) {
throw new Error('private file upload returned no file_id');
}
groupAction({
name: 'get_group_root_files',
summary: '获取群根目录文件列表',
readOnly: true,
returns: '群文件系统信息(文件与文件夹列表)。',
returnsSchema: {
type: 'object',
properties: {
files: {
type: 'array',
description: '文件列表',
items: {
const uploaded = ctx.bridge.recallUploadedFile(result.fileId);
if (!uploaded || uploaded.scope !== 'private' || uploaded.userId !== p.user_id) {
throw new Error(
`private file upload metadata missing for file_id ${result.fileId}`,
);
}
await ctx.sendPrivateMessage(
p.user_id,
[
{
type: 'file',
data: {
file_id: result.fileId,
name: uploaded.fileName,
file_size: uploaded.fileSize,
md5: Buffer.from(uploaded.fileMd5).toString('hex'),
file_hash: result.fileHash ?? uploaded.fileHash ?? '',
},
},
],
false,
);
}
return okResponse({ file_id: result.fileId });
},
}),
groupAction({
name: 'get_group_file_url',
summary: '获取群文件下载链接',
readOnly: true,
returns: '群文件下载链接。',
returnsSchema: {
type: 'object',
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
// busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it,
// so a present null/empty/non-numeric value must not 400 the request (#147).
params: { file_id: f.fileId(), busid: f.raw() },
run: async (p, ctx) => {
return okResponse({
url: await ctx.bridge.apis.groupFile.getUrl(
p.group_id,
p.file_id,
busidOr102(p.busid),
),
});
},
}),
groupAction({
name: 'get_group_root_files',
summary: '获取群根目录文件列表',
readOnly: true,
returns: '群文件系统信息(文件与文件夹列表)。',
returnsSchema: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
file_id: { type: 'string', description: '文件 ID' },
file_name: { type: 'string', description: '文件名' },
busid: { type: 'integer', description: '业务 ID' },
file_size: { type: 'integer', description: '文件大小(字节)' },
upload_time: { type: 'integer', description: '上传时间戳' },
dead_time: { type: 'integer', description: '过期时间戳' },
modify_time: { type: 'integer', description: '修改时间戳' },
download_times: { type: 'integer', description: '下载次数' },
uploader: { type: 'integer', description: '上传者 QQ 号' },
uploader_name: { type: 'string', description: '上传者昵称' },
files: {
type: 'array',
description: '文件列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
file_id: { type: 'string', description: '文件 ID' },
file_name: { type: 'string', description: '文件名' },
busid: { type: 'integer', description: '业务 ID' },
file_size: { type: 'integer', description: '文件大小(字节)' },
upload_time: { type: 'integer', description: '上传时间戳' },
dead_time: { type: 'integer', description: '过期时间戳' },
modify_time: { type: 'integer', description: '修改时间戳' },
download_times: { type: 'integer', description: '下载次数' },
uploader: { type: 'integer', description: '上传者 QQ 号' },
uploader_name: { type: 'string', description: '上传者昵称' },
},
},
},
folders: {
type: 'array',
description: '文件夹列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
folder_id: { type: 'string', description: '文件夹 ID' },
folder_name: { type: 'string', description: '文件夹名' },
create_time: { type: 'integer', description: '创建时间戳' },
creator: { type: 'integer', description: '创建者 QQ 号' },
create_name: { type: 'string', description: '创建者昵称' },
total_file_count: { type: 'integer', description: '文件夹内文件总数' },
last_upload_time: { type: 'integer', description: '最后上传时间戳' },
last_uploader: { type: 'integer', description: '最后上传者 QQ 号' },
last_uploader_name: { type: 'string', description: '最后上传者昵称' },
},
},
},
},
},
required: ['files', 'folders'],
},
folders: {
type: 'array',
description: '文件夹列表',
items: {
run: async (p, ctx) => {
return okResponse(await ctx.getGroupFiles(p.group_id, '/'));
},
}),
groupAction({
name: 'get_group_files_by_folder',
summary: '获取群子目录文件列表',
readOnly: true,
returns: '群文件系统信息(文件与文件夹列表)。',
returnsSchema: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
folder_id: { type: 'string', description: '文件夹 ID' },
folder_name: { type: 'string', description: '文件夹名' },
create_time: { type: 'integer', description: '创建时间戳' },
creator: { type: 'integer', description: '创建者 QQ 号' },
create_name: { type: 'string', description: '创建者昵称' },
total_file_count: { type: 'integer', description: '文件夹内文件总数' },
last_upload_time: { type: 'integer', description: '最后上传时间戳' },
last_uploader: { type: 'integer', description: '最后上传者 QQ 号' },
last_uploader_name: { type: 'string', description: '最后上传者昵称' },
files: {
type: 'array',
description: '文件列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
file_id: { type: 'string', description: '文件 ID' },
file_name: { type: 'string', description: '文件名' },
busid: { type: 'integer', description: '业务 ID' },
file_size: { type: 'integer', description: '文件大小(字节)' },
upload_time: { type: 'integer', description: '上传时间戳' },
dead_time: { type: 'integer', description: '过期时间戳' },
modify_time: { type: 'integer', description: '修改时间戳' },
download_times: { type: 'integer', description: '下载次数' },
uploader: { type: 'integer', description: '上传者 QQ 号' },
uploader_name: { type: 'string', description: '上传者昵称' },
},
},
},
folders: {
type: 'array',
description: '文件夹列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
folder_id: { type: 'string', description: '文件夹 ID' },
folder_name: { type: 'string', description: '文件夹名' },
create_time: { type: 'integer', description: '创建时间戳' },
creator: { type: 'integer', description: '创建者 QQ 号' },
create_name: { type: 'string', description: '创建者昵称' },
total_file_count: { type: 'integer', description: '文件夹内文件总数' },
last_upload_time: { type: 'integer', description: '最后上传时间戳' },
last_uploader: { type: 'integer', description: '最后上传者 QQ 号' },
last_uploader_name: { type: 'string', description: '最后上传者昵称' },
},
},
},
},
},
required: ['files', 'folders'],
},
},
required: ['files', 'folders'],
},
run: async (p, ctx) => {
return okResponse(await ctx.getGroupFiles(p.group_id, '/'));
},
}),
// folder_id / folder are aliases; first non-empty wins, else '/'.
params: { folder_id: f.string().default(''), folder: f.string().default('') },
run: async (p, ctx) => {
const folderId = p.folder_id || p.folder || '/';
return okResponse(await ctx.getGroupFiles(p.group_id, folderId));
},
}),
groupAction({
name: 'get_group_files_by_folder',
summary: '获取群子目录文件列表',
readOnly: true,
returns: '群文件系统信息(文件与文件夹列表)。',
returnsSchema: {
type: 'object',
properties: {
files: {
type: 'array',
description: '文件列表',
items: {
groupAction({
name: 'delete_group_file',
summary: '删除群文件',
params: { file_id: f.fileId() },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id);
return okResponse();
},
}),
groupAction({
name: 'move_group_file',
summary: '移动群文件',
params: {
file_id: f.fileId(),
parent_directory: f.string({ allowEmpty: false }),
target_directory: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.move(
p.group_id,
p.file_id,
p.parent_directory,
p.target_directory,
);
return okResponse();
},
}),
// rename_group_file — 0x6D6_4。NapCat 入参:file_id + current_parent_directory
// (文件当前所在目录)+ new_name。SnowLuma 的 file_id 即原始 fileId,无需 UUID 解码。
groupAction({
name: 'rename_group_file',
summary: '重命名群文件',
params: {
file_id: f.fileId(),
current_parent_directory: f.string().default('/'),
new_name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.rename(
p.group_id,
p.file_id,
p.current_parent_directory || '/',
p.new_name,
);
// {ok:true} 刻意对齐 NapCat RenameGroupFile 的返回体,偏离 SnowLuma 同类
// 文件写操作(move/delete 返回空 data)——为 NapCat 客户端 drop-in 兼容。
return okResponse({ ok: true });
},
}),
groupAction({
name: 'create_group_file_folder',
summary: '创建群文件夹',
// NapCat-aligned data so callers can read back the new folderId (#195):
// { result, groupItem: { folderInfo: { folderId, folderName, … } } }.
returns:
'{ result: { retCode, retMsg }, groupItem: { folderInfo: { folderId, folderName, folderPath, createTime, modifyTime, createUin, modifyUin } } }',
params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') },
run: async (p, ctx) => {
const folderInfo = await ctx.bridge.apis.groupFile.createFolder(
p.group_id,
p.name,
p.parent_id || '/',
);
return okResponse({
result: { retCode: 0, retMsg: 'success' },
groupItem: { folderInfo },
});
},
}),
groupAction({
name: 'delete_group_file_folder',
summary: '删除群文件夹',
params: { folder_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id);
return okResponse();
},
}),
groupAction({
name: 'rename_group_file_folder',
summary: '重命名群文件夹',
// new_folder_name / name are aliases; first non-empty wins and must be
// non-empty (legacy `asString(new_folder_name) || asString(name)` + `!newName`).
params: {
folder_id: f.string({ allowEmpty: false }),
new_folder_name: f.string().default(''),
name: f.string().default(''),
},
run: async (p, ctx) => {
const newName = p.new_folder_name || p.name;
if (!newName) {
return failedResponse(
RETCODE.BAD_REQUEST,
'group_id, folder_id and new_folder_name are required',
);
}
await ctx.bridge.apis.groupFile.renameFolder(p.group_id, p.folder_id, newName);
return okResponse();
},
}),
defineAction({
name: 'get_private_file_url',
summary: '获取私聊文件下载链接',
readOnly: true,
returns: '私聊文件下载链接。',
returnsSchema: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
file_id: { type: 'string', description: '文件 ID' },
file_name: { type: 'string', description: '文件名' },
busid: { type: 'integer', description: '业务 ID' },
file_size: { type: 'integer', description: '文件大小(字节)' },
upload_time: { type: 'integer', description: '上传时间戳' },
dead_time: { type: 'integer', description: '过期时间戳' },
modify_time: { type: 'integer', description: '修改时间戳' },
download_times: { type: 'integer', description: '下载次数' },
uploader: { type: 'integer', description: '上传者 QQ 号' },
uploader_name: { type: 'string', description: '上传者昵称' },
},
},
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
folders: {
type: 'array',
description: '文件夹列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
folder_id: { type: 'string', description: '文件夹 ID' },
folder_name: { type: 'string', description: '文件夹名' },
create_time: { type: 'integer', description: '创建时间戳' },
creator: { type: 'integer', description: '创建者 QQ 号' },
create_name: { type: 'string', description: '创建者昵称' },
total_file_count: { type: 'integer', description: '文件夹内文件总数' },
last_upload_time: { type: 'integer', description: '最后上传时间戳' },
last_uploader: { type: 'integer', description: '最后上传者 QQ 号' },
last_uploader_name: { type: 'string', description: '最后上传者昵称' },
},
},
// NapCat's `get_private_file_url` requires only file_id — it re-derives the
// file hash by decoding its composite file_id and reading file10MMd5 off the
// original message. SnowLuma's file_id is the bare fileUUID, so it relies on
// the file_hash that it already emits alongside file_id in the received file
// segment (event-converter/to-segment.ts). To stay drop-in for NapCat-style
// clients that only persist file_id, both user_id and file_hash are now
// optional; file_hash falls through empty when absent. See issue #147.
params: {
user_id: f.userId().optional(),
file_id: f.fileId(),
file_hash: f.string().default(''),
},
},
required: ['files', 'folders'],
},
// folder_id / folder are aliases; first non-empty wins, else '/'.
params: { folder_id: f.string().default(''), folder: f.string().default('') },
run: async (p, ctx) => {
const folderId = p.folder_id || p.folder || '/';
return okResponse(await ctx.getGroupFiles(p.group_id, folderId));
},
}),
groupAction({
name: 'delete_group_file',
summary: '删除群文件',
params: { file_id: f.fileId() },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id);
return okResponse();
},
}),
groupAction({
name: 'move_group_file',
summary: '移动群文件',
params: {
file_id: f.fileId(),
parent_directory: f.string({ allowEmpty: false }),
target_directory: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.move(p.group_id, p.file_id, p.parent_directory, p.target_directory);
return okResponse();
},
}),
// rename_group_file — 0x6D6_4。NapCat 入参:file_id + current_parent_directory
// (文件当前所在目录)+ new_name。SnowLuma 的 file_id 即原始 fileId,无需 UUID 解码。
groupAction({
name: 'rename_group_file',
summary: '重命名群文件',
params: {
file_id: f.fileId(),
current_parent_directory: f.string().default('/'),
new_name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.rename(p.group_id, p.file_id, p.current_parent_directory || '/', p.new_name);
// {ok:true} 刻意对齐 NapCat RenameGroupFile 的返回体,偏离 SnowLuma 同类
// 文件写操作(move/delete 返回空 data)——为 NapCat 客户端 drop-in 兼容。
return okResponse({ ok: true });
},
}),
groupAction({
name: 'create_group_file_folder',
summary: '创建群文件夹',
// NapCat-aligned data so callers can read back the new folderId (#195):
// { result, groupItem: { folderInfo: { folderId, folderName, … } } }.
returns: '{ result: { retCode, retMsg }, groupItem: { folderInfo: { folderId, folderName, folderPath, createTime, modifyTime, createUin, modifyUin } } }',
params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') },
run: async (p, ctx) => {
const folderInfo = await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/');
return okResponse({
result: { retCode: 0, retMsg: 'success' },
groupItem: { folderInfo },
});
},
}),
groupAction({
name: 'delete_group_file_folder',
summary: '删除群文件夹',
params: { folder_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id);
return okResponse();
},
}),
groupAction({
name: 'rename_group_file_folder',
summary: '重命名群文件夹',
// new_folder_name / name are aliases; first non-empty wins and must be
// non-empty (legacy `asString(new_folder_name) || asString(name)` + `!newName`).
params: { folder_id: f.string({ allowEmpty: false }), new_folder_name: f.string().default(''), name: f.string().default('') },
run: async (p, ctx) => {
const newName = p.new_folder_name || p.name;
if (!newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.bridge.apis.groupFile.renameFolder(p.group_id, p.folder_id, newName);
return okResponse();
},
}),
defineAction({
name: 'get_private_file_url',
summary: '获取私聊文件下载链接',
readOnly: true,
returns: '私聊文件下载链接。',
returnsSchema: {
type: 'object',
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
// NapCat's `get_private_file_url` requires only file_id — it re-derives the
// file hash by decoding its composite file_id and reading file10MMd5 off the
// original message. SnowLuma's file_id is the bare fileUUID, so it relies on
// the file_hash that it already emits alongside file_id in the received file
// segment (event-converter/to-segment.ts). To stay drop-in for NapCat-style
// clients that only persist file_id, both user_id and file_hash are now
// optional; file_hash falls through empty when absent. See issue #147.
params: {
user_id: f.userId().optional(),
file_id: f.fileId(),
file_hash: f.string().default(''),
},
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id ?? 0, p.file_id, p.file_hash) });
},
}),
run: async (p, ctx) => {
return okResponse({
url: await ctx.bridge.apis.groupFile.getPrivateUrl(
p.user_id ?? 0,
p.file_id,
p.file_hash,
),
});
},
}),
];
+372 -249
View File
@@ -3,264 +3,387 @@ import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
export const groupInfoReturnsSchema = {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名' },
group_remark: { type: 'string', description: '当前账号设置的群备注' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: { type: 'integer', description: '群等级' },
group_memo: { type: 'string', description: '群简介 / 公告预览' },
group_description: { type: 'string', description: '群简介(公告不算;未加入的群为空)' },
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
},
required: [
'group_id', 'group_name', 'group_remark', 'member_count',
'max_member_count', 'group_all_shut',
],
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名' },
group_remark: { type: 'string', description: '当前账号设置的群备注' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: { type: 'integer', description: '群等级' },
group_memo: { type: 'string', description: '群简介 / 公告预览' },
group_description: { type: 'string', description: '群简介(公告不算;未加入的群为空)' },
group_all_shut: {
type: 'integer',
enum: [-1, 0],
description: '是否开启全员禁言(-1 开启,0 关闭)',
},
},
required: [
'group_id',
'group_name',
'group_remark',
'member_count',
'max_member_count',
'group_all_shut',
],
};
export const actions = [
defineAction({
name: 'get_group_list',
summary: '获取群列表',
readOnly: true,
returns: '群信息对象数组。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名' },
group_remark: { type: 'string', description: '当前账号设置的群备注' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: { type: 'integer', description: '群等级(列表批量场景恒 0,详见 get_group_info)' },
group_memo: { type: 'string', description: '群简介 / 公告预览' },
group_description: { type: 'string', description: '群简介(公告不算;未加入的群为空)' },
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
defineAction({
name: 'get_group_list',
summary: '获取群列表',
readOnly: true,
returns: '群信息对象数组。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名' },
group_remark: { type: 'string', description: '当前账号设置的群备注' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: {
type: 'integer',
description: '群等级(列表批量场景恒 0,详见 get_group_info)',
},
group_memo: { type: 'string', description: '群简介 / 公告预览' },
group_description: {
type: 'string',
description: '群简介(公告不算;未加入的群为空)',
},
group_all_shut: {
type: 'integer',
enum: [-1, 0],
description: '是否开启全员禁言(-1 开启,0 关闭)',
},
},
required: [
'group_id',
'group_name',
'group_remark',
'member_count',
'max_member_count',
'group_all_shut',
],
},
},
required: [
'group_id', 'group_name', 'group_remark', 'member_count',
'max_member_count', 'group_all_shut',
],
},
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const noCache = p.no_cache;
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
return okResponse([]);
},
}),
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const noCache = p.no_cache;
groupAction({
name: 'get_group_info',
summary: '获取群信息',
readOnly: true,
returns: '群信息对象。',
returnsSchema: groupInfoReturnsSchema,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
const fallback = {
group_id: groupId,
group_name: '',
group_remark: '',
member_count: 0,
max_member_count: 0,
group_create_time: 0,
group_level: 0,
group_memo: '',
group_description: '',
group_all_shut: 0,
};
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? fallback);
}
return okResponse(fallback);
},
}),
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
groupAction({
name: 'get_group_member_list',
summary: '获取群成员列表',
readOnly: true,
returns: '群成员信息对象数组。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
card: { type: 'string', description: '群名片' },
is_robot: { type: 'boolean', description: '是否为机器人' },
sex: { type: 'string', enum: ['male', 'female', 'unknown'], description: '性别' },
age: { type: 'integer', description: '年龄' },
join_time: { type: 'integer', description: '入群时间戳(秒)' },
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
return okResponse([]);
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
},
}),
}),
groupUserAction({
name: 'get_group_member_info',
summary: '获取群成员信息',
readOnly: true,
returns: '群成员信息对象。',
returnsSchema: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
card: { type: 'string', description: '群名片' },
is_robot: { type: 'boolean', description: '是否为机器人' },
sex: { type: 'string', enum: ['male', 'female', 'unknown'], description: '性别' },
age: { type: 'integer', description: '年龄' },
join_time: { type: 'integer', description: '入群时间戳(秒)' },
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const userId = p.user_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(info ?? {
group_id: groupId, user_id: userId, nickname: '', card: '',
is_robot: false,
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
shut_up_timestamp: 0,
level: '0', role: 'member', title: '',
qidian_master_flag: 0, qidian_crew_flag: 0, qidian_crew_flag_2: 0,
});
}
return okResponse({
group_id: groupId, user_id: userId, nickname: '', card: '',
is_robot: false,
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
shut_up_timestamp: 0,
level: '0', role: 'member', title: '',
});
},
}),
groupAction({
name: 'get_group_info',
summary: '获取群信息',
readOnly: true,
returns: '群信息对象。',
returnsSchema: groupInfoReturnsSchema,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
const fallback = {
group_id: groupId,
group_name: '',
group_remark: '',
member_count: 0,
max_member_count: 0,
group_create_time: 0,
group_level: 0,
group_memo: '',
group_description: '',
group_all_shut: 0,
};
groupAction({
name: 'get_group_honor_info',
summary: '获取群荣誉信息',
readOnly: true,
params: { type: f.string().optional() },
run: async (p, ctx) => {
const groupId = p.group_id;
const typeStr = p.type || 'all';
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? fallback);
}
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
}
try {
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
}
},
}),
defineAction({
name: 'get_group_system_msg',
summary: '获取群系统消息',
readOnly: true,
returns: '群系统消息数组,可按群号或未处理状态过滤。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名称' },
request_id: { type: 'integer', description: '请求序列号' },
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
invitor_uin: { type: 'integer', description: '邀请人 QQ 号,无邀请时为 0' },
invitor_nick: { type: 'string', description: '邀请人昵称' },
message: { type: 'string', description: '验证留言' },
checked: { type: 'boolean', description: '是否已处理' },
flag: { type: 'string', description: '处理请求使用的规范 flag' },
return okResponse(fallback);
},
required: [
'group_id', 'group_name', 'request_id', 'requester_uin',
'requester_nick', 'invitor_uin', 'invitor_nick',
'message', 'checked', 'flag',
],
},
},
params: {
group_id: f.groupId().optional(),
only_pending: f.bool().default(false),
count: f.int({ min: 1, max: 100 }).default(50).describe('每个收件箱最多读取的记录数'),
},
run: async (p, ctx) => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg({
groupId: p.group_id,
onlyPending: p.only_pending,
count: p.count,
}));
}
return okResponse([]);
},
}),
}),
groupAction({
name: 'get_group_member_list',
summary: '获取群成员列表',
readOnly: true,
returns: '群成员信息对象数组。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
card: { type: 'string', description: '群名片' },
is_robot: { type: 'boolean', description: '是否为机器人' },
sex: {
type: 'string',
enum: ['male', 'female', 'unknown'],
description: '性别',
},
age: { type: 'integer', description: '年龄' },
join_time: { type: 'integer', description: '入群时间戳(秒)' },
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: {
type: 'integer',
description: '禁言结束时间戳(秒,未禁言时为 0)',
},
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: {
type: 'integer',
description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略',
},
role: {
type: 'string',
enum: ['owner', 'admin', 'member'],
description: '角色',
},
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: {
type: 'boolean',
description: '是否不良记录(QQ NT 不提供,恒 false)',
},
title_expire_time: {
type: 'integer',
description: '头衔过期时间戳(QQ NT 不提供,恒 0)',
},
card_changeable: {
type: 'boolean',
description: '是否可改名片(占位,恒 true)',
},
qidian_master_flag: {
type: 'integer',
description: '企点主号标志,0 或 1;普通账号为 0',
},
qidian_crew_flag: {
type: 'integer',
description: '企点员工标志,0 或 1;普通账号为 0',
},
qidian_crew_flag_2: {
type: 'integer',
description: '企点保留标志,0 或 1;普通账号为 0',
},
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
},
}),
groupUserAction({
name: 'get_group_member_info',
summary: '获取群成员信息',
readOnly: true,
returns: '群成员信息对象。',
returnsSchema: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
card: { type: 'string', description: '群名片' },
is_robot: { type: 'boolean', description: '是否为机器人' },
sex: { type: 'string', enum: ['male', 'female', 'unknown'], description: '性别' },
age: { type: 'integer', description: '年龄' },
join_time: { type: 'integer', description: '入群时间戳(秒)' },
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: {
type: 'integer',
description: '禁言结束时间戳(秒,未禁言时为 0)',
},
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: {
type: 'integer',
description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略',
},
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: {
type: 'boolean',
description: '是否不良记录(QQ NT 不提供,恒 false)',
},
title_expire_time: {
type: 'integer',
description: '头衔过期时间戳(QQ NT 不提供,恒 0)',
},
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
qidian_master_flag: {
type: 'integer',
description: '企点主号标志,0 或 1;普通账号为 0',
},
qidian_crew_flag: {
type: 'integer',
description: '企点员工标志,0 或 1;普通账号为 0',
},
qidian_crew_flag_2: {
type: 'integer',
description: '企点保留标志,0 或 1;普通账号为 0',
},
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const userId = p.user_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(
info ?? {
group_id: groupId,
user_id: userId,
nickname: '',
card: '',
is_robot: false,
sex: 'unknown',
age: 0,
join_time: 0,
last_sent_time: 0,
shut_up_timestamp: 0,
level: '0',
role: 'member',
title: '',
qidian_master_flag: 0,
qidian_crew_flag: 0,
qidian_crew_flag_2: 0,
},
);
}
return okResponse({
group_id: groupId,
user_id: userId,
nickname: '',
card: '',
is_robot: false,
sex: 'unknown',
age: 0,
join_time: 0,
last_sent_time: 0,
shut_up_timestamp: 0,
level: '0',
role: 'member',
title: '',
});
},
}),
groupAction({
name: 'get_group_honor_info',
summary: '获取群荣誉信息',
readOnly: true,
params: { type: f.string().optional() },
run: async (p, ctx) => {
const groupId = p.group_id;
const typeStr = p.type || 'all';
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
return failedResponse(
RETCODE.BAD_REQUEST,
`invalid type, must be one of ${typeValues.join(', ')}`,
);
}
try {
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(
groupId,
typeStr as WebHonorType,
);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(
RETCODE.ACTION_FAILED,
`failed to get group honor info: ${(e as Error).message}`,
);
}
},
}),
defineAction({
name: 'get_group_system_msg',
summary: '获取群系统消息',
readOnly: true,
returns: '群系统消息数组,可按群号或未处理状态过滤。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名称' },
request_id: { type: 'integer', description: '请求序列号' },
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
invitor_uin: { type: 'integer', description: '邀请人 QQ 号,无邀请时为 0' },
invitor_nick: { type: 'string', description: '邀请人昵称' },
message: { type: 'string', description: '验证留言' },
checked: { type: 'boolean', description: '是否已处理' },
flag: { type: 'string', description: '处理请求使用的规范 flag' },
},
required: [
'group_id',
'group_name',
'request_id',
'requester_uin',
'requester_nick',
'invitor_uin',
'invitor_nick',
'message',
'checked',
'flag',
],
},
},
params: {
group_id: f.groupId().optional(),
only_pending: f.bool().default(false),
count: f.int({ min: 1, max: 100 }).default(50).describe('每个收件箱最多读取的记录数'),
},
run: async (p, ctx) => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(
await ctx.handleGetGroupSystemMsg({
groupId: p.group_id,
onlyPending: p.only_pending,
count: p.count,
}),
);
}
return okResponse([]);
},
}),
];
+218 -180
View File
@@ -23,46 +23,46 @@ import { actions as streamDownloadActions } from './stream-download';
import { actions as systemFaceActions } from './system-face';
export interface ActionGroup {
/** Domain category (= source file), surfaced to the MCP / UI for grouping. */
readonly category: string;
readonly actions: readonly RegisteredActionSpec[];
/** Domain category (= source file), surfaced to the MCP / UI for grouping. */
readonly category: string;
readonly actions: readonly RegisteredActionSpec[];
}
export interface RawActionReservation {
/** Executable wire name reserved for a handler that cannot be an ActionSpec. */
readonly name: string;
/** Diagnostic owner. Usually identical to name; explicit for conflict logs. */
readonly canonical: string;
/** Executable wire name reserved for a handler that cannot be an ActionSpec. */
readonly name: string;
/** Diagnostic owner. Usually identical to name; explicit for conflict logs. */
readonly canonical: string;
}
export type CompiledActionKind = RegisteredActionSpec['kind'] | 'raw';
export type ActionNameRole = 'canonical' | 'alias' | 'raw';
export interface CompiledAction {
readonly canonical: string;
readonly names: readonly string[];
readonly kind: RegisteredActionSpec['kind'];
readonly category: string;
readonly doc: ActionDoc;
readonly spec: RegisteredActionSpec;
readonly canonical: string;
readonly names: readonly string[];
readonly kind: RegisteredActionSpec['kind'];
readonly category: string;
readonly doc: ActionDoc;
readonly spec: RegisteredActionSpec;
}
interface ActionNameClaimBase {
readonly name: string;
readonly canonical: string;
readonly kind: CompiledActionKind;
readonly role: ActionNameRole;
readonly name: string;
readonly canonical: string;
readonly kind: CompiledActionKind;
readonly role: ActionNameRole;
}
export interface CompiledDeclarativeName extends ActionNameClaimBase {
readonly kind: RegisteredActionSpec['kind'];
readonly role: 'canonical' | 'alias';
readonly action: CompiledAction;
readonly kind: RegisteredActionSpec['kind'];
readonly role: 'canonical' | 'alias';
readonly action: CompiledAction;
}
export interface CompiledRawName extends ActionNameClaimBase {
readonly kind: 'raw';
readonly role: 'raw';
readonly kind: 'raw';
readonly role: 'raw';
}
export type CompiledActionName = CompiledDeclarativeName | CompiledRawName;
@@ -70,204 +70,242 @@ export type CompiledActionName = CompiledDeclarativeName | CompiledRawName;
export type RawActionFactory = (api: ApiHandler) => ActionHandler;
export interface BoundAction {
readonly handler: ActionHandler;
readonly canonical: string;
readonly kind: CompiledActionKind;
readonly handler: ActionHandler;
readonly canonical: string;
readonly kind: CompiledActionKind;
}
export interface CompiledActionRegistry {
/** Canonical declarative actions in authored group/action order. */
readonly actions: readonly CompiledAction[];
/** Every executable name, including aliases and reserved raw handlers. */
readonly executableNames: readonly CompiledActionName[];
/** Category order/counts used by the docs and UI. */
readonly categories: readonly { category: string; count: number }[];
readonly rawActions: readonly CompiledRawName[];
resolve(name: string): CompiledActionName | undefined;
/** Produce the sealed executable table. Extra or missing raw factories fail. */
bind(
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
): ReadonlyMap<string, BoundAction>;
/** Canonical declarative actions in authored group/action order. */
readonly actions: readonly CompiledAction[];
/** Every executable name, including aliases and reserved raw handlers. */
readonly executableNames: readonly CompiledActionName[];
/** Category order/counts used by the docs and UI. */
readonly categories: readonly { category: string; count: number }[];
readonly rawActions: readonly CompiledRawName[];
resolve(name: string): CompiledActionName | undefined;
/** Produce the sealed executable table. Extra or missing raw factories fail. */
bind(
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
): ReadonlyMap<string, BoundAction>;
}
function validateSpecProjection(spec: RegisteredActionSpec, doc: ActionDoc): void {
const canonical = spec.names[0];
if (!canonical || canonical.trim() === '') {
throw new Error(`Action registry invalid ${spec.kind} action: canonical name must not be empty`);
}
for (const name of spec.names) {
if (name.trim() === '') {
throw new Error(`Action registry invalid ${spec.kind} action canonical "${canonical}": executable name must not be empty`);
}
}
const canonical = spec.names[0];
const aliases = spec.names.slice(1);
if (doc.name !== canonical || doc.aliases.length !== aliases.length || doc.aliases.some((name, i) => name !== aliases[i])) {
throw new Error(
`Action registry invalid ${spec.kind} action canonical "${canonical}": describe() names do not match executable names`,
);
}
const documentedKind = doc.stream === true ? 'stream' : 'normal';
if (documentedKind !== spec.kind) {
throw new Error(
`Action registry invalid ${spec.kind} action canonical "${canonical}": describe() reports kind ${documentedKind}`,
);
}
if (!canonical || canonical.trim() === '') {
throw new Error(
`Action registry invalid ${spec.kind} action: canonical name must not be empty`,
);
}
for (const name of spec.names) {
if (name.trim() === '') {
throw new Error(
`Action registry invalid ${spec.kind} action canonical "${canonical}": executable name must not be empty`,
);
}
}
const aliases = spec.names.slice(1);
if (
doc.name !== canonical ||
doc.aliases.length !== aliases.length ||
doc.aliases.some((name, i) => name !== aliases[i])
) {
throw new Error(
`Action registry invalid ${spec.kind} action canonical "${canonical}": describe() names do not match executable names`,
);
}
const documentedKind = doc.stream === true ? 'stream' : 'normal';
if (documentedKind !== spec.kind) {
throw new Error(
`Action registry invalid ${spec.kind} action canonical "${canonical}": describe() reports kind ${documentedKind}`,
);
}
}
function conflictMessage(name: string, first: CompiledActionName, second: CompiledActionName): string {
return [
`Action registry conflict for executable name "${name}"`,
`canonical "${first.canonical}" (name "${first.name}", kind ${first.kind}, role ${first.role})`,
`canonical "${second.canonical}" (name "${second.name}", kind ${second.kind}, role ${second.role})`,
].join(': ');
function conflictMessage(
name: string,
first: CompiledActionName,
second: CompiledActionName,
): string {
return [
`Action registry conflict for executable name "${name}"`,
`canonical "${first.canonical}" (name "${first.name}", kind ${first.kind}, role ${first.role})`,
`canonical "${second.canonical}" (name "${second.name}", kind ${second.kind}, role ${second.role})`,
].join(': ');
}
/** Compile and validate a complete executable namespace. Exported so the
* conflict matrix can be tested without constructing an ApiHandler. */
export function compileActionRegistry(
groups: readonly ActionGroup[],
rawReservations: readonly RawActionReservation[] = [],
groups: readonly ActionGroup[],
rawReservations: readonly RawActionReservation[] = [],
): CompiledActionRegistry {
const actions: CompiledAction[] = [];
const executableNames: CompiledActionName[] = [];
const rawActions: CompiledRawName[] = [];
const byName = new Map<string, CompiledActionName>();
const actions: CompiledAction[] = [];
const executableNames: CompiledActionName[] = [];
const rawActions: CompiledRawName[] = [];
const byName = new Map<string, CompiledActionName>();
const claim = (next: CompiledActionName): void => {
const previous = byName.get(next.name);
if (previous) throw new Error(conflictMessage(next.name, previous, next));
byName.set(next.name, next);
executableNames.push(next);
};
const claim = (next: CompiledActionName): void => {
const previous = byName.get(next.name);
for (const group of groups) {
for (const spec of group.actions) {
const described = spec.describe();
validateSpecProjection(spec, described);
const canonical = spec.names[0]!;
const action: CompiledAction = Object.freeze({
canonical,
names: Object.freeze([...spec.names]),
kind: spec.kind,
category: group.category,
doc: Object.freeze({ ...described, category: group.category }),
spec,
});
actions.push(action);
action.names.forEach((name, index) => claim(Object.freeze({
name,
canonical,
kind: action.kind,
role: index === 0 ? 'canonical' : 'alias',
action,
})));
if (previous) {
throw new Error(conflictMessage(next.name, previous, next));
}
byName.set(next.name, next);
executableNames.push(next);
};
for (const group of groups) {
for (const spec of group.actions) {
const described = spec.describe();
validateSpecProjection(spec, described);
const canonical = spec.names[0]!;
const action: CompiledAction = Object.freeze({
canonical,
names: Object.freeze([...spec.names]),
kind: spec.kind,
category: group.category,
doc: Object.freeze({ ...described, category: group.category }),
spec,
});
actions.push(action);
action.names.forEach((name, index) =>
claim(
Object.freeze({
name,
canonical,
kind: action.kind,
role: index === 0 ? 'canonical' : 'alias',
action,
}),
),
);
}
}
}
for (const reservation of rawReservations) {
if (reservation.name.trim() === '' || reservation.canonical.trim() === '') {
throw new Error('Action registry invalid raw action: canonical and executable name must not be empty');
for (const reservation of rawReservations) {
if (reservation.name.trim() === '' || reservation.canonical.trim() === '') {
throw new Error(
'Action registry invalid raw action: canonical and executable name must not be empty',
);
}
const raw: CompiledRawName = Object.freeze({
name: reservation.name,
canonical: reservation.canonical,
kind: 'raw',
role: 'raw',
});
claim(raw);
rawActions.push(raw);
}
const raw: CompiledRawName = Object.freeze({
name: reservation.name,
canonical: reservation.canonical,
kind: 'raw',
role: 'raw',
const categories = groups.map(({ category, actions: groupActions }) =>
Object.freeze({
category,
count: groupActions.length,
}),
);
return Object.freeze({
actions: Object.freeze(actions),
executableNames: Object.freeze(executableNames),
categories: Object.freeze(categories),
rawActions: Object.freeze(rawActions),
resolve: (name: string) => byName.get(name),
bind: (
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
) => bindActionRegistry(executableNames, ctx, api, rawFactories),
});
claim(raw);
rawActions.push(raw);
}
const categories = groups.map(({ category, actions: groupActions }) => Object.freeze({
category,
count: groupActions.length,
}));
return Object.freeze({
actions: Object.freeze(actions),
executableNames: Object.freeze(executableNames),
categories: Object.freeze(categories),
rawActions: Object.freeze(rawActions),
resolve: (name: string) => byName.get(name),
bind: (
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
) => bindActionRegistry(executableNames, ctx, api, rawFactories),
});
}
function bindActionRegistry(
executableNames: readonly CompiledActionName[],
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
executableNames: readonly CompiledActionName[],
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
): ReadonlyMap<string, BoundAction> {
const factoryNames = new Set(Object.keys(rawFactories));
const handlers = new Map<string, BoundAction>();
const factoryNames = new Set(Object.keys(rawFactories));
const handlers = new Map<string, BoundAction>();
for (const claim of executableNames) {
if (claim.kind === 'raw') {
const factory = rawFactories[claim.canonical];
if (!factory) {
throw new Error(
`Action registry raw factory missing: canonical "${claim.canonical}" `
+ `(name "${claim.name}", kind raw)`,
for (const claim of executableNames) {
if (claim.kind === 'raw') {
const factory = rawFactories[claim.canonical];
if (!factory) {
throw new Error(
`Action registry raw factory missing: canonical "${claim.canonical}" ` +
`(name "${claim.name}", kind raw)`,
);
}
factoryNames.delete(claim.canonical);
handlers.set(
claim.name,
Object.freeze({
handler: factory(api),
canonical: claim.canonical,
kind: 'raw',
}),
);
continue;
}
const handler = claim.action.spec.toHandler(ctx);
handlers.set(
claim.name,
Object.freeze({
handler,
canonical: claim.canonical,
kind: claim.kind,
}),
);
}
factoryNames.delete(claim.canonical);
handlers.set(claim.name, Object.freeze({
handler: factory(api),
canonical: claim.canonical,
kind: 'raw',
}));
continue;
}
const handler = claim.action.spec.toHandler(ctx);
handlers.set(claim.name, Object.freeze({
handler,
canonical: claim.canonical,
kind: claim.kind,
}));
}
if (factoryNames.size > 0) {
const extra = [...factoryNames][0]!;
throw new Error(
`Action registry unexpected raw factory: canonical "${extra}" ` +
`(name "${extra}", kind raw)`,
);
}
if (factoryNames.size > 0) {
const extra = [...factoryNames][0]!;
throw new Error(
`Action registry unexpected raw factory: canonical "${extra}" `
+ `(name "${extra}", kind raw)`,
);
}
return handlers;
return handlers;
}
/** Every declarative action, grouped by domain category. Authored input. */
export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '信息', actions: infoActions },
{ category: '消息', actions: messageActions },
{ category: '好友', actions: friendActions },
{ category: '群信息', actions: groupInfoActions },
{ category: '群管理', actions: groupAdminActions },
{ category: '群文件', actions: groupFileActions },
{ category: '请求', actions: requestActions },
{ category: '扩展', actions: extendedActions },
{ category: '群相册', actions: groupAlbumActions },
{ category: '空间', actions: qzoneActions },
{ category: '系统表情', actions: systemFaceActions },
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
{ category: '信息', actions: infoActions },
{ category: '消息', actions: messageActions },
{ category: '好友', actions: friendActions },
{ category: '群信息', actions: groupInfoActions },
{ category: '群管理', actions: groupAdminActions },
{ category: '群文件', actions: groupFileActions },
{ category: '请求', actions: requestActions },
{ category: '扩展', actions: extendedActions },
{ category: '群相册', actions: groupAlbumActions },
{ category: '空间', actions: qzoneActions },
{ category: '系统表情', actions: systemFaceActions },
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
];
/** Hidden OneBot v11 quick-operation handler; `_async` is the NoneBot 1 alias. */
export const HANDLE_QUICK_OPERATION_ACTION = '.handle_quick_operation';
export const HANDLE_QUICK_OPERATION_ASYNC_ACTION = '.handle_quick_operation_async';
export const RAW_ACTION_RESERVATIONS: readonly RawActionReservation[] = [
{ name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
{ name: HANDLE_QUICK_OPERATION_ASYNC_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
{ name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
{ name: HANDLE_QUICK_OPERATION_ASYNC_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
];
/** Complete, validated runtime/docs registry. Compilation happens on import. */
+98 -87
View File
@@ -5,95 +5,106 @@ import { okResponse } from '../types';
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
export const actions = [
defineAction({
name: 'get_login_info',
readOnly: true,
returns: '当前登录账号的 QQ 号与昵称。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '登录 QQ 号' },
nickname: { type: 'string', description: '登录昵称' },
},
required: ['user_id', 'nickname'],
},
params: {},
run: (_p, ctx) => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
},
}),
defineAction({
name: 'get_login_info',
readOnly: true,
returns: '当前登录账号的 QQ 号与昵称。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '登录 QQ 号' },
nickname: { type: 'string', description: '登录昵称' },
},
required: ['user_id', 'nickname'],
},
params: {},
run: (_p, ctx) => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
},
}),
defineAction({
name: 'get_status',
readOnly: true,
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。',
returnsSchema: {
type: 'object',
properties: {
online: { type: 'boolean', description: '是否在线' },
good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' },
time: { type: 'integer', description: '当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时' },
},
required: ['online', 'good', 'time'],
},
params: {},
run: (_p, ctx) => {
const online = ctx.isOnline();
return okResponse({ online, good: online && ctx.bridge.receiveHealthy, time: Math.floor(ctx.getUptimeMs() / 1000) });
},
}),
defineAction({
name: 'get_status',
readOnly: true,
returns:
'运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。',
returnsSchema: {
type: 'object',
properties: {
online: { type: 'boolean', description: '是否在线' },
good: {
type: 'boolean',
description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false',
},
time: {
type: 'integer',
description: '当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时',
},
},
required: ['online', 'good', 'time'],
},
params: {},
run: (_p, ctx) => {
const online = ctx.isOnline();
return okResponse({
online,
good: online && ctx.bridge.receiveHealthy,
time: Math.floor(ctx.getUptimeMs() / 1000),
});
},
}),
defineAction({
name: 'get_version_info',
readOnly: true,
returns: '实现与协议版本信息。',
returnsSchema: {
type: 'object',
properties: {
app_name: { type: 'string', description: '实现名称(SnowLuma)' },
app_version: { type: 'string', description: '实现版本' },
protocol_version: { type: 'string', description: 'OneBot 协议版本' },
},
required: ['app_name', 'app_version', 'protocol_version'],
},
params: {},
run: () => {
return okResponse({
app_name: 'SnowLuma',
app_version: `${appVersion}-node`,
protocol_version: 'v11',
});
},
}),
defineAction({
name: 'get_version_info',
readOnly: true,
returns: '实现与协议版本信息。',
returnsSchema: {
type: 'object',
properties: {
app_name: { type: 'string', description: '实现名称(SnowLuma)' },
app_version: { type: 'string', description: '实现版本' },
protocol_version: { type: 'string', description: 'OneBot 协议版本' },
},
required: ['app_name', 'app_version', 'protocol_version'],
},
params: {},
run: () => {
return okResponse({
app_name: 'SnowLuma',
app_version: `${appVersion}-node`,
protocol_version: 'v11',
});
},
}),
defineAction({
name: 'can_send_image',
readOnly: true,
returns: '能力查询结果。',
returnsSchema: {
type: 'object',
properties: { yes: { type: 'boolean', description: '是否支持发送图片' } },
required: ['yes'],
},
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
},
}),
defineAction({
name: 'can_send_image',
readOnly: true,
returns: '能力查询结果。',
returnsSchema: {
type: 'object',
properties: { yes: { type: 'boolean', description: '是否支持发送图片' } },
required: ['yes'],
},
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
},
}),
defineAction({
name: 'can_send_record',
readOnly: true,
returns: '能力查询结果。',
returnsSchema: {
type: 'object',
properties: { yes: { type: 'boolean', description: '是否支持发送语音' } },
required: ['yes'],
},
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
},
}),
defineAction({
name: 'can_send_record',
readOnly: true,
returns: '能力查询结果。',
returnsSchema: {
type: 'object',
properties: { yes: { type: 'boolean', description: '是否支持发送语音' } },
required: ['yes'],
},
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
},
}),
];
+213 -141
View File
@@ -7,13 +7,16 @@ import { RETCODE, failedResponse, okResponse } from '../types';
/** send_msg only (#426). Some clients send `group_id: ""` on private chats.
* Treat that exact empty string as absent. Do not change `f.groupId()`. */
function sendMsgOptionalGroupId(): Field<number | undefined> {
const inner = f.groupId().optional();
return Object.assign(Object.create(inner) as Field<number | undefined>, {
coerce(raw: Parameters<Field<number | undefined>['coerce']>[0], field: string) {
if (raw === '') return { ok: true as const, value: undefined };
return inner.coerce(raw, field);
},
});
const inner = f.groupId().optional();
return Object.assign(Object.create(inner) as Field<number | undefined>, {
coerce(raw: Parameters<Field<number | undefined>['coerce']>[0], field: string) {
if (raw === '') {
return { ok: true as const, value: undefined };
}
return inner.coerce(raw, field);
},
});
}
const log = createLogger('OneBot');
@@ -26,147 +29,216 @@ const log = createLogger('OneBot');
* `findEvent` returns a fresh parse, so mutating the array is safe.
*/
async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise<void> {
const segments = event.message;
if (!Array.isArray(segments)) return;
for (const seg of segments) {
if (!seg || typeof seg !== 'object') continue;
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
if (segment.type !== 'image') continue;
const data = segment.data;
if (!data || typeof data !== 'object') continue;
const file = typeof data.file === 'string' ? data.file
: typeof data.file_id === 'string' ? data.file_id
: '';
if (!file) continue;
try {
const info = await ctx.getImageInfo(file);
if (info && typeof info.url === 'string' && info.url) data.url = info.url;
} catch {
// Keep the stored URL when the refresh fails.
const segments = event.message;
if (!Array.isArray(segments)) {
return;
}
for (const seg of segments) {
if (!seg || typeof seg !== 'object') {
continue;
}
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
if (segment.type !== 'image') {
continue;
}
const data = segment.data;
if (!data || typeof data !== 'object') {
continue;
}
const file =
typeof data.file === 'string'
? data.file
: typeof data.file_id === 'string'
? data.file_id
: '';
if (!file) {
continue;
}
try {
const info = await ctx.getImageInfo(file);
if (info && typeof info.url === 'string' && info.url) {
data.url = info.url;
}
} catch {
// Keep the stored URL when the refresh fails.
}
}
}
}
export const actions = [
defineAction({
name: 'send_custom_face',
summary: '发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式',
returns: '{ message_id: number }',
params: {
emoji_id: f.string().describe('当前账号收藏表情的完整 ID 或 32 位 MD5'),
group_id: f.groupId().optional().describe('目标群号;与 user_id 二选一'),
user_id: f.userId().optional().describe('目标 QQ 号;与 group_id 二选一'),
reply_to: f.messageId().optional().describe('可选回复消息 ID'),
},
run: async (p, ctx) => {
if ((p.group_id === undefined) === (p.user_id === undefined)) {
return failedResponse(RETCODE.BAD_REQUEST, 'exactly one of group_id and user_id is required');
}
if (!p.emoji_id.trim()) return failedResponse(RETCODE.BAD_REQUEST, 'emoji_id is required');
const face = await ctx.bridge.apis.profile.resolveCustomFace(p.emoji_id);
const message: JsonObject[] = [];
if (p.reply_to !== undefined) message.push({ type: 'reply', data: { id: String(p.reply_to) } });
message.push({ type: 'image', data: { file: face.url, sub_type: 1, summary: '[动画表情]' } });
const result = p.group_id !== undefined
? await ctx.sendGroupMessage(p.group_id, message, false)
: await ctx.sendPrivateMessage(p.user_id!, message, false);
return okResponse({ message_id: result.messageId });
},
}),
defineAction({
name: 'send_custom_face',
summary: '发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式',
returns: '{ message_id: number }',
params: {
emoji_id: f.string().describe('当前账号收藏表情的完整 ID 或 32 位 MD5'),
group_id: f.groupId().optional().describe('目标群号;与 user_id 二选一'),
user_id: f.userId().optional().describe('目标 QQ 号;与 group_id 二选一'),
reply_to: f.messageId().optional().describe('可选回复消息 ID'),
},
run: async (p, ctx) => {
if ((p.group_id === undefined) === (p.user_id === undefined)) {
return failedResponse(
RETCODE.BAD_REQUEST,
'exactly one of group_id and user_id is required',
);
}
// send_msg routes on message_type / group_id presence, so the *required*
// id is conditional — that branch stays in run(). The fields themselves
// (message required; group_id/user_id valid uints when present) are
// validated by the spec; message_type is left lenient for parity.
defineAction({
name: 'send_msg',
summary: '发送消息(按 message_type/群号 自动路由群聊或私聊)',
returns: '{ message_id: number }',
params: {
message: f.message(),
message_type: f.string().optional(),
group_id: sendMsgOptionalGroupId(),
user_id: f.userId().optional(),
auto_escape: f.bool().default(false),
},
run: async (p, ctx) => {
// Group temp-session reply: message_type=private with BOTH a user_id and
// a group_id (the source group). Detect it first so a group_id here
// doesn't get misrouted to a group message.
const isTempReply = p.message_type === 'private' && p.user_id !== undefined && p.group_id !== undefined;
if (!isTempReply && (p.message_type === 'group' || p.group_id !== undefined)) {
if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
}
if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, isTempReply ? p.group_id : undefined);
return okResponse({ message_id: result.messageId });
},
}),
if (!p.emoji_id.trim()) {
return failedResponse(RETCODE.BAD_REQUEST, 'emoji_id is required');
}
defineAction({
name: 'send_private_msg',
summary: '发送私聊消息',
returns: '{ message_id: number }',
params: {
user_id: f.userId(),
message: f.message(),
// Optional source group: reply into that group's temp session (临时会话)
// instead of a friend chat. int({min:0}) rather than groupId (which
// rejects 0): a client that fills every field with group_id:0 must keep
// working as a plain private send, so 0/absent means "no temp session".
group_id: f.int({ min: 0 }).optional(),
auto_escape: f.bool().default(false),
},
run: async (p, ctx) => {
const tempGroupId = p.group_id && p.group_id > 0 ? p.group_id : undefined;
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, tempGroupId);
return okResponse({ message_id: result.messageId });
},
}),
const face = await ctx.bridge.apis.profile.resolveCustomFace(p.emoji_id);
const message: JsonObject[] = [];
groupAction({
name: 'send_group_msg',
summary: '发送群消息',
returns: '{ message_id: number }',
params: { message: f.message(), auto_escape: f.bool().default(false) },
run: async (p, ctx) => {
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
},
}),
if (p.reply_to !== undefined) {
message.push({ type: 'reply', data: { id: String(p.reply_to) } });
}
defineAction({
name: 'get_msg',
summary: '获取消息',
readOnly: true,
returns: '消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const data = ctx.getMessage(p.message_id);
if (!data) {
log.warn('[get_msg] miss message_id=%d', p.message_id);
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 ?? p.message_id) as JsonValue;
await refreshStoredImageUrls(result, ctx);
return okResponse(result);
},
}),
message.push({
type: 'image',
data: { file: face.url, sub_type: 1, summary: '[动画表情]' },
});
const result =
p.group_id !== undefined
? await ctx.sendGroupMessage(p.group_id, message, false)
: await ctx.sendPrivateMessage(p.user_id!, message, false);
return okResponse({ message_id: result.messageId });
},
}),
defineAction({
name: 'delete_msg',
summary: '撤回消息',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
await ctx.deleteMessage(p.message_id, meta);
return okResponse();
},
}),
// send_msg routes on message_type / group_id presence, so the *required*
// id is conditional — that branch stays in run(). The fields themselves
// (message required; group_id/user_id valid uints when present) are
// validated by the spec; message_type is left lenient for parity.
defineAction({
name: 'send_msg',
summary: '发送消息(按 message_type/群号 自动路由群聊或私聊)',
returns: '{ message_id: number }',
params: {
message: f.message(),
message_type: f.string().optional(),
group_id: sendMsgOptionalGroupId(),
user_id: f.userId().optional(),
auto_escape: f.bool().default(false),
},
run: async (p, ctx) => {
// Group temp-session reply: message_type=private with BOTH a user_id and
// a group_id (the source group). Detect it first so a group_id here
// doesn't get misrouted to a group message.
const isTempReply =
p.message_type === 'private' && p.user_id !== undefined && p.group_id !== undefined;
if (!isTempReply && (p.message_type === 'group' || p.group_id !== undefined)) {
if (p.group_id === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
}
if (p.user_id === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
const result = await ctx.sendPrivateMessage(
p.user_id,
p.message,
p.auto_escape,
isTempReply ? p.group_id : undefined,
);
return okResponse({ message_id: result.messageId });
},
}),
defineAction({
name: 'send_private_msg',
summary: '发送私聊消息',
returns: '{ message_id: number }',
params: {
user_id: f.userId(),
message: f.message(),
// Optional source group: reply into that group's temp session (临时会话)
// instead of a friend chat. int({min:0}) rather than groupId (which
// rejects 0): a client that fills every field with group_id:0 must keep
// working as a plain private send, so 0/absent means "no temp session".
group_id: f.int({ min: 0 }).optional(),
auto_escape: f.bool().default(false),
},
run: async (p, ctx) => {
const tempGroupId = p.group_id && p.group_id > 0 ? p.group_id : undefined;
const result = await ctx.sendPrivateMessage(
p.user_id,
p.message,
p.auto_escape,
tempGroupId,
);
return okResponse({ message_id: result.messageId });
},
}),
groupAction({
name: 'send_group_msg',
summary: '发送群消息',
returns: '{ message_id: number }',
params: { message: f.message(), auto_escape: f.bool().default(false) },
run: async (p, ctx) => {
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
},
}),
defineAction({
name: 'get_msg',
summary: '获取消息',
readOnly: true,
returns:
'消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const data = ctx.getMessage(p.message_id);
if (!data) {
log.warn('[get_msg] miss message_id=%d', p.message_id);
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 ?? p.message_id) as JsonValue;
await refreshStoredImageUrls(result, ctx);
return okResponse(result);
},
}),
defineAction({
name: 'delete_msg',
summary: '撤回消息',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
if (!meta) {
return failedResponse(
RETCODE.ACTION_FAILED,
'message not found or not retractable',
);
}
await ctx.deleteMessage(p.message_id, meta);
return okResponse();
},
}),
];
+300 -219
View File
@@ -4,246 +4,327 @@ import type { JsonValue } from '../types';
import { okResponse } from '../types';
async function uploadQzoneImages(
ctx: ApiActionContext,
images: string[],
select: (upload: { richval: string; url: string }) => string,
ctx: ApiActionContext,
images: string[],
select: (upload: { richval: string; url: string }) => string,
): Promise<string> {
const parts: string[] = [];
for (let i = 0; i < images.length; i++) {
try {
const upload = await ctx.bridge.apis.qzone.uploadImageFromSource(images[i]);
parts.push(select(upload));
} catch (error) {
const message = error instanceof Error ? error.message : 'unknown error';
throw new Error(`第 ${i + 1} 张图片上传失败: ${message}`);
const parts: string[] = [];
for (let i = 0; i < images.length; i++) {
try {
const upload = await ctx.bridge.apis.qzone.uploadImageFromSource(images[i]);
parts.push(select(upload));
} catch (error) {
const message = error instanceof Error ? error.message : 'unknown error';
throw new Error(`第 ${i + 1} 张图片上传失败: ${message}`);
}
}
}
return parts.join('\t');
return parts.join('\t');
}
const QZONE_UGC_RIGHTS = new Set<number>([1, 4, 16, 64, 128]);
export const actions = [
// get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。
// 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。
// 复用 qzone.qq.com 的 cookie/g_tk 基建(与群相册同源),纯 web,无 trpc。
defineAction({
name: 'get_qzone_msg_list',
readOnly: true,
returns: '说说列表对象,含说说总数与本页说说数组。',
returnsSchema: {
type: 'object',
properties: {
total: { type: 'integer', description: '账号说说总数(非本页数量)' },
msglist: {
type: 'array',
description: '本页说说数组',
items: {
// get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。
// 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。
// 复用 qzone.qq.com 的 cookie/g_tk 基建(与群相册同源),纯 web,无 trpc。
defineAction({
name: 'get_qzone_msg_list',
readOnly: true,
returns: '说说列表对象,含说说总数与本页说说数组。',
returnsSchema: {
type: 'object',
properties: {
tid: { type: 'string', description: '说说 id(delete/comment/like 的句柄)' },
content: { type: 'string', description: '说说正文' },
time: { type: 'integer', description: '发表时间(unix 秒)' },
comment_num: { type: 'integer', description: '评论数' },
is_private: { type: 'boolean', description: '是否仅自己可见' },
images: { type: 'array', items: { type: 'string' }, description: '图片 URL 列表(每图取最大可用变体)' },
total: { type: 'integer', description: '账号说说总数(非本页数量)' },
msglist: {
type: 'array',
description: '本页说说数组',
items: {
type: 'object',
properties: {
tid: {
type: 'string',
description: '说说 id(delete/comment/like 的句柄)',
},
content: { type: 'string', description: '说说正文' },
time: { type: 'integer', description: '发表时间(unix 秒)' },
comment_num: { type: 'integer', description: '评论数' },
is_private: { type: 'boolean', description: '是否仅自己可见' },
images: {
type: 'array',
items: { type: 'string' },
description: '图片 URL 列表(每图取最大可用变体)',
},
},
required: ['tid', 'content', 'time', 'comment_num', 'is_private', 'images'],
},
},
},
required: ['tid', 'content', 'time', 'comment_num', 'is_private', 'images'],
},
required: ['total', 'msglist'],
},
},
required: ['total', 'msglist'],
},
summary: '获取 QQ 空间说说列表(默认机器人自己的空间)',
params: {
target_uin: f.userId().describe('目标 QQ 号,省略则取机器人自己').optional(),
pos: f.int({ min: 0 }).describe('起始偏移').default(0),
num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num);
return okResponse(res as unknown as JsonValue);
},
}),
summary: '获取 QQ 空间说说列表(默认机器人自己的空间)',
params: {
target_uin: f.userId().describe('目标 QQ 号,省略则取机器人自己').optional(),
pos: f.int({ min: 0 }).describe('起始偏移').default(0),
num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num);
return okResponse(res as unknown as JsonValue);
},
}),
// get_qzone_feeds — 获取好友动态(feed)。只读,始终以机器人自己身份拉取。
// 每条 feed 含结构化字段 + 预渲染 html 原样透传(深度解析交由调用方)。
defineAction({
name: 'get_qzone_feeds',
readOnly: true,
returns: '好友动态对象,含本页 feed 数组与是否有更多页。',
returnsSchema: {
type: 'object',
properties: {
feeds: {
type: 'array',
description: '本页好友动态数组',
items: {
// get_qzone_feeds — 获取好友动态(feed)。只读,始终以机器人自己身份拉取。
// 每条 feed 含结构化字段 + 预渲染 html 原样透传(深度解析交由调用方)。
defineAction({
name: 'get_qzone_feeds',
readOnly: true,
returns: '好友动态对象,含本页 feed 数组与是否有更多页。',
returnsSchema: {
type: 'object',
properties: {
uin: { type: 'integer', description: '动态作者 QQ 号' },
nickname: { type: 'string', description: '作者昵称' },
time: { type: 'integer', description: '发表时间(unix 秒)' },
appid: { type: 'integer', description: 'Qzone 应用 id(311=说说,4=相册,…)' },
key: { type: 'string', description: 'feed 句柄(Qzone 用于定位该条动态)' },
html: { type: 'string', description: '预渲染 HTML 原样透传' },
feeds: {
type: 'array',
description: '本页好友动态数组',
items: {
type: 'object',
properties: {
uin: { type: 'integer', description: '动态作者 QQ 号' },
nickname: { type: 'string', description: '作者昵称' },
time: { type: 'integer', description: '发表时间(unix 秒)' },
appid: {
type: 'integer',
description: 'Qzone 应用 id(311=说说,4=相册,…)',
},
key: {
type: 'string',
description: 'feed 句柄(Qzone 用于定位该条动态)',
},
html: { type: 'string', description: '预渲染 HTML 原样透传' },
},
required: ['uin', 'nickname', 'time', 'appid', 'key', 'html'],
},
},
has_more: { type: 'boolean', description: '服务端是否报告本页之后还有更多页' },
},
required: ['uin', 'nickname', 'time', 'appid', 'key', 'html'],
},
required: ['feeds', 'has_more'],
},
has_more: { type: 'boolean', description: '服务端是否报告本页之后还有更多页' },
},
required: ['feeds', 'has_more'],
},
summary: '获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)',
params: {
page_num: f.int({ min: 1 }).describe('页码(1 起;仅首页可靠)').default(1),
count: f.int({ min: 1, max: 50 }).describe('本页数量').default(10),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count);
return okResponse(res as unknown as JsonValue);
},
}),
summary: '获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)',
params: {
page_num: f.int({ min: 1 }).describe('页码(1 起;仅首页可靠)').default(1),
count: f.int({ min: 1, max: 50 }).describe('本页数量').default(10),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count);
return okResponse(res as unknown as JsonValue);
},
}),
// send_qzone_msg — 发表说说(纯文字或带图)。写操作,发到机器人自己的空间。
// 传入 images 数组,自动上传并发布。
// 返回新说说的 tid(供后续 delete/comment/like 使用)。
// 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。
defineAction({
name: 'send_qzone_msg',
summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)',
params: {
content: f.string({ allowEmpty: false }).describe('说说正文'),
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
ugc_right: f.int({ min: 1 }).describe('查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见').default(1),
target_uins: f.array(f.uint()).describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单').optional(),
},
rules: (r) => [
r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) => QZONE_UGC_RIGHTS.has(p.ugc_right)),
r.rule('target_uins is required when ugc_right is 16 or 128', (p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length),
],
run: async (p, ctx) => {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval);
const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval, p.ugc_right, p.target_uins?.join('|'));
return okResponse(res as unknown as JsonValue);
}
const res = await ctx.bridge.apis.qzone.publish(p.content, undefined, undefined, p.ugc_right, p.target_uins?.join('|'));
return okResponse(res as unknown as JsonValue);
},
}),
// send_qzone_msg — 发表说说(纯文字或带图)。写操作,发到机器人自己的空间。
// 传入 images 数组,自动上传并发布。
// 返回新说说的 tid(供后续 delete/comment/like 使用)。
// 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。
defineAction({
name: 'send_qzone_msg',
summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)',
params: {
content: f.string({ allowEmpty: false }).describe('说说正文'),
images: f
.array(f.string({ allowEmpty: false }))
.describe('图片数组(可选),支持 file:// http:// base64://;自动上传')
.optional(),
ugc_right: f
.int({ min: 1 })
.describe(
'查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见',
)
.default(1),
target_uins: f
.array(f.uint())
.describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单')
.optional(),
},
rules: (r) => [
r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) =>
QZONE_UGC_RIGHTS.has(p.ugc_right),
),
r.rule(
'target_uins is required when ugc_right is 16 or 128',
(p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length,
),
],
run: async (p, ctx) => {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval);
const res = await ctx.bridge.apis.qzone.publish(
p.content,
1,
richval,
p.ugc_right,
p.target_uins?.join('|'),
);
return okResponse(res as unknown as JsonValue);
}
// delete_qzone_msg — 删除机器人自己空间的一条说说(按 tid)。写操作。
defineAction({
name: 'delete_qzone_msg',
summary: '删除一条说说(QQ 空间,按 tid)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.delete(p.tid);
return okResponse(null);
},
}),
const res = await ctx.bridge.apis.qzone.publish(
p.content,
undefined,
undefined,
p.ugc_right,
p.target_uins?.join('|'),
);
return okResponse(res as unknown as JsonValue);
},
}),
// set_qzone_msg_right — 修改机器人自己空间一条已发说说的查看权限(按 tid)。
// 写操作;ugc_right/target_uins 语义与 send_qzone_msg 一致。
defineAction({
name: 'set_qzone_msg_right',
returns: '更新后的权限对象。',
returnsSchema: {
type: 'object',
properties: {
ugc_right: { type: 'integer', description: '更新后的查看权限' },
},
required: ['ugc_right'],
},
summary: '修改一条已发说说的查看权限(QQ 空间,按 tid)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'),
ugc_right: f.int({ min: 1 }).describe('查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见'),
target_uins: f.array(f.uint()).describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单').optional(),
},
rules: (r) => [
r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) => QZONE_UGC_RIGHTS.has(p.ugc_right)),
r.rule('target_uins is required when ugc_right is 16 or 128', (p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length),
],
run: async (p, ctx) => {
const res = await ctx.bridge.apis.qzone.updateRight(p.tid, p.ugc_right, p.target_uins?.join('|'));
return okResponse(res as unknown as JsonValue);
},
}),
// delete_qzone_msg — 删除机器人自己空间的一条说说(按 tid)。写操作。
defineAction({
name: 'delete_qzone_msg',
summary: '删除一条说说(QQ 空间,按 tid)',
params: {
tid: f
.string({ allowEmpty: false })
.describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.delete(p.tid);
return okResponse(null);
},
}),
// like_qzone — 给一条说说点赞。target_uin 省略=机器人自己空间;点赞好友说说传其 uin。
// abstime=该说说的发表时间(unix 秒,来自 get_qzone_feeds/get_qzone_msg_list),
// 传真实值更可靠;不传按 0。写操作;高频点赞会被 Qzone 风控,调用方需限流。
defineAction({
name: 'like_qzone',
summary: '给一条说说点赞(QQ 空间)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, true, p.abstime);
return okResponse(null);
},
}),
// set_qzone_msg_right — 修改机器人自己空间一条已发说说的查看权限(按 tid)。
// 写操作;ugc_right/target_uins 语义与 send_qzone_msg 一致。
defineAction({
name: 'set_qzone_msg_right',
returns: '更新后的权限对象。',
returnsSchema: {
type: 'object',
properties: {
ugc_right: { type: 'integer', description: '更新后的查看权限' },
},
required: ['ugc_right'],
},
summary: '修改一条已发说说的查看权限(QQ 空间,按 tid)',
params: {
tid: f
.string({ allowEmpty: false })
.describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'),
ugc_right: f
.int({ min: 1 })
.describe(
'查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见',
),
target_uins: f
.array(f.uint())
.describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单')
.optional(),
},
rules: (r) => [
r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) =>
QZONE_UGC_RIGHTS.has(p.ugc_right),
),
r.rule(
'target_uins is required when ugc_right is 16 or 128',
(p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length,
),
],
run: async (p, ctx) => {
const res = await ctx.bridge.apis.qzone.updateRight(
p.tid,
p.ugc_right,
p.target_uins?.join('|'),
);
return okResponse(res as unknown as JsonValue);
},
}),
// unlike_qzone — 取消对一条说说的点赞。参数同 like_qzone。写操作。
// 注意:取消赞端点(internal_unlike_app)暂未经真机核实,待抓包确认。
defineAction({
name: 'unlike_qzone',
summary: '取消对一条说说的点赞(QQ 空间;取消赞端点待真机核实)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, false, p.abstime);
return okResponse(null);
},
}),
// like_qzone — 给一条说说点赞。target_uin 省略=机器人自己空间;点赞好友说说传其 uin。
// abstime=该说说的发表时间(unix 秒,来自 get_qzone_feeds/get_qzone_msg_list),
// 传真实值更可靠;不传按 0。写操作;高频点赞会被 Qzone 风控,调用方需限流。
defineAction({
name: 'like_qzone',
summary: '给一条说说点赞(QQ 空间)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f
.int({ min: 0 })
.describe('说说发表时间(unix 秒),传真实值更可靠')
.default(0)
.role('timestamp'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, true, p.abstime);
return okResponse(null);
},
}),
// comment_qzone — 评论一条说说。target_uin=说说所属 QQ 号(省略=机器人自己空间)。
// 传入 images 数组,自动上传获取直链(多图用 tab 拼接)。
// 写操作;高频评论会被 Qzone 风控,调用方需限流。
defineAction({
name: 'comment_qzone',
summary: '评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
content: f.string({ allowEmpty: false }).describe('评论内容'),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
},
run: async (p, ctx) => {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url);
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval);
return okResponse(res as unknown as JsonValue);
}
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin);
return okResponse(res as unknown as JsonValue);
},
}),
// unlike_qzone — 取消对一条说说的点赞。参数同 like_qzone。写操作。
// 注意:取消赞端点(internal_unlike_app)暂未经真机核实,待抓包确认。
defineAction({
name: 'unlike_qzone',
summary: '取消对一条说说的点赞(QQ 空间;取消赞端点待真机核实)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f
.int({ min: 0 })
.describe('说说发表时间(unix 秒),传真实值更可靠')
.default(0)
.role('timestamp'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, false, p.abstime);
return okResponse(null);
},
}),
// set_qzone_ban — 拉黑/解除拉黑某人(修改机器人自身 QQ 空间黑名单)。写操作。
// enable=true 拉黑,enable=false 解除拉黑。
defineAction({
name: 'set_qzone_ban',
summary: '拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单;enable=true 拉黑,false 解除)',
params: {
user_id: f.userId().describe('目标 QQ 号'),
enable: f.bool().describe('true 拉黑,false 解除拉黑').default(true),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.setBlack(p.user_id, p.enable);
return okResponse(null);
},
}),
// comment_qzone — 评论一条说说。target_uin=说说所属 QQ 号(省略=机器人自己空间)。
// 传入 images 数组,自动上传获取直链(多图用 tab 拼接)。
// 写操作;高频评论会被 Qzone 风控,调用方需限流。
defineAction({
name: 'comment_qzone',
summary: '评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
content: f.string({ allowEmpty: false }).describe('评论内容'),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
images: f
.array(f.string({ allowEmpty: false }))
.describe('图片数组(可选),支持 file:// http:// base64://;自动上传')
.optional(),
},
run: async (p, ctx) => {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url);
const res = await ctx.bridge.apis.qzone.comment(
p.tid,
p.content,
p.target_uin,
1,
richval,
);
return okResponse(res as unknown as JsonValue);
}
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin);
return okResponse(res as unknown as JsonValue);
},
}),
// set_qzone_ban — 拉黑/解除拉黑某人(修改机器人自身 QQ 空间黑名单)。写操作。
// enable=true 拉黑,enable=false 解除拉黑。
defineAction({
name: 'set_qzone_ban',
summary: '拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单;enable=true 拉黑,false 解除)',
params: {
user_id: f.userId().describe('目标 QQ 号'),
enable: f.bool().describe('true 拉黑,false 解除拉黑').default(true),
},
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.setBlack(p.user_id, p.enable);
return okResponse(null);
},
}),
];
+31 -30
View File
@@ -2,35 +2,36 @@ import { defineAction, f } from '../action-kit';
import { okResponse } from '../types';
export const actions = [
defineAction({
name: 'set_friend_add_request',
summary: '处理好友添加请求',
params: {
flag: f.string({ allowEmpty: false }),
approve: f.bool().default(true),
},
run: async (p, ctx) => {
await ctx.bridge.apis.friend.handleRequest(p.flag, p.approve);
return okResponse();
},
}),
defineAction({
name: 'set_friend_add_request',
summary: '处理好友添加请求',
params: {
flag: f.string({ allowEmpty: false }),
approve: f.bool().default(true),
},
run: async (p, ctx) => {
await ctx.bridge.apis.friend.handleRequest(p.flag, p.approve);
return okResponse();
},
}),
defineAction({
name: 'set_group_add_request',
summary: '处理加群请求',
params: {
// Opaque handle from the original request event; callers must echo it.
flag: f.string({ allowEmpty: false }),
// sub_type → type → 'add'. Empty string is kept, not treated as missing.
sub_type: f.string().optional(),
type: f.string().optional(),
approve: f.bool().default(true),
reason: f.string().default(''),
},
run: async (p, ctx) => {
const subType = p.sub_type !== undefined ? p.sub_type : (p.type !== undefined ? p.type : 'add');
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
return okResponse();
},
}),
defineAction({
name: 'set_group_add_request',
summary: '处理加群请求',
params: {
// Opaque handle from the original request event; callers must echo it.
flag: f.string({ allowEmpty: false }),
// sub_type → type → 'add'. Empty string is kept, not treated as missing.
sub_type: f.string().optional(),
type: f.string().optional(),
approve: f.bool().default(true),
reason: f.string().default(''),
},
run: async (p, ctx) => {
const subType =
p.sub_type !== undefined ? p.sub_type : p.type !== undefined ? p.type : 'add';
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
return okResponse();
},
}),
];
+482 -273
View File
@@ -26,102 +26,170 @@ import { defineStreamAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types';
import { type StreamSink, StreamStatus } from '../streaming';
import {
STREAM_ROOT,
ensureStreamDirectory,
registerActiveStreamItem,
} from '../stream-storage';
import { STREAM_ROOT, ensureStreamDirectory, registerActiveStreamItem } from '../stream-storage';
const DEFAULT_CHUNK_BYTES = 64 * 1024;
const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size
const MAX_DOWNLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB total
const FETCH_CONNECT_TIMEOUT_MS = 30_000; // TTFB only — cleared once headers arrive (not the whole transfer)
const IDLE_TIMEOUT_MS = 60_000; // abort if no chunk arrives for this long (anti-stall)
const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size
const MAX_DOWNLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB total
const FETCH_CONNECT_TIMEOUT_MS = 30_000; // TTFB only — cleared once headers arrive (not the whole transfer)
const IDLE_TIMEOUT_MS = 60_000; // abort if no chunk arrives for this long (anti-stall)
const MAX_REDIRECTS = 5;
const DOWNLOAD_USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
class DownloadError extends Error {}
// ─────────────────────────── source resolution ───────────────────────────
function isWithinStreamRoot(p: string): boolean {
// Resolve the root through any symlinks too (e.g. macOS /tmp → /private/tmp),
// so a realpath'd target compares against a realpath'd root — otherwise a
// legitimate file reads as "outside" purely from the tmpdir symlink.
let root = path.resolve(STREAM_ROOT);
try { root = fs.realpathSync(STREAM_ROOT); } catch { /* root may not exist yet */ }
const rel = path.relative(root, path.resolve(p));
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
// Resolve the root through any symlinks too (e.g. macOS /tmp → /private/tmp),
// so a realpath'd target compares against a realpath'd root — otherwise a
// legitimate file reads as "outside" purely from the tmpdir symlink.
let root = path.resolve(STREAM_ROOT);
try {
root = fs.realpathSync(STREAM_ROOT);
} catch {
/* root may not exist yet */
}
const rel = path.relative(root, path.resolve(p));
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
}
function isPrivateV4(o: number[]): boolean {
return (
o[0] === 0 || o[0] === 127 || o[0] === 10 ||
(o[0] === 192 && o[1] === 168) ||
(o[0] === 172 && o[1] >= 16 && o[1] <= 31) ||
(o[0] === 169 && o[1] === 254) || // link-local
(o[0] === 100 && o[1] >= 64 && o[1] <= 127) // CGNAT
);
return (
o[0] === 0 ||
o[0] === 127 ||
o[0] === 10 ||
(o[0] === 192 && o[1] === 168) ||
(o[0] === 172 && o[1] >= 16 && o[1] <= 31) ||
(o[0] === 169 && o[1] === 254) || // link-local
(o[0] === 100 && o[1] >= 64 && o[1] <= 127) // CGNAT
);
}
/** Parse an IPv6 string (any form, incl. `::` compression and embedded IPv4)
* to its 16 bytes. `new URL().hostname` normalises v4-mapped addresses to hex
* (`::ffff:7f00:1`), so string matching is unreliable — we work on bytes. */
function ipv6ToBytes(input: string): Uint8Array | null {
let s = input.replace(/^\[|\]$/g, '');
if (net.isIP(s) !== 6) return null;
const v4m = /:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s); // embedded IPv4 tail
if (v4m) {
const o = v4m[1].split('.').map(Number);
if (o.some((n) => n > 255)) return null;
s = s.slice(0, v4m.index) + ':' + `${((o[0] << 8) | o[1]).toString(16)}:${((o[2] << 8) | o[3]).toString(16)}`;
}
const halves = s.split('::');
if (halves.length > 2) return null;
const head = halves[0] ? halves[0].split(':') : [];
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
let groups: string[];
if (halves.length === 2) {
const missing = 8 - head.length - tail.length;
if (missing < 0) return null;
groups = [...head, ...new Array(missing).fill('0'), ...tail];
} else {
groups = head;
}
if (groups.length !== 8) return null;
const bytes = new Uint8Array(16);
for (let i = 0; i < 8; i++) {
const g = parseInt(groups[i] || '0', 16);
if (Number.isNaN(g) || g < 0 || g > 0xffff) return null;
bytes[i * 2] = g >> 8;
bytes[i * 2 + 1] = g & 0xff;
}
return bytes;
let s = input.replace(/^\[|\]$/g, '');
if (net.isIP(s) !== 6) {
return null;
}
const v4m = /:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s); // embedded IPv4 tail
if (v4m) {
const o = v4m[1].split('.').map(Number);
if (o.some((n) => n > 255)) {
return null;
}
s =
s.slice(0, v4m.index) +
':' +
`${((o[0] << 8) | o[1]).toString(16)}:${((o[2] << 8) | o[3]).toString(16)}`;
}
const halves = s.split('::');
if (halves.length > 2) {
return null;
}
const head = halves[0] ? halves[0].split(':') : [];
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
let groups: string[];
if (halves.length === 2) {
const missing = 8 - head.length - tail.length;
if (missing < 0) {
return null;
}
groups = [...head, ...new Array(missing).fill('0'), ...tail];
} else {
groups = head;
}
if (groups.length !== 8) {
return null;
}
const bytes = new Uint8Array(16);
for (let i = 0; i < 8; i++) {
const g = parseInt(groups[i] || '0', 16);
if (Number.isNaN(g) || g < 0 || g > 0xffff) {
return null;
}
bytes[i * 2] = g >> 8;
bytes[i * 2 + 1] = g & 0xff;
}
return bytes;
}
function isPrivateIp(ip: string): boolean {
const host = ip.replace(/^\[|\]$/g, '');
const fam = net.isIP(host);
if (fam === 4) return isPrivateV4(host.split('.').map(Number));
if (fam === 6) {
const b = ipv6ToBytes(host);
if (!b) return true; // unparseable IPv6 → treat as unsafe
if (b.every((x) => x === 0)) return true; // ::
if (b.slice(0, 15).every((x) => x === 0) && b[15] === 1) return true; // ::1
if ((b[0] & 0xfe) === 0xfc) return true; // fc00::/7 unique-local
if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) return true; // fe80::/10 link-local
// v4-mapped ::ffff:a.b.c.d / v4-compatible ::a.b.c.d
if (b.slice(0, 10).every((x) => x === 0) && ((b[10] === 0xff && b[11] === 0xff) || (b[10] === 0 && b[11] === 0))) {
return isPrivateV4([b[12], b[13], b[14], b[15]]);
const host = ip.replace(/^\[|\]$/g, '');
const fam = net.isIP(host);
if (fam === 4) {
return isPrivateV4(host.split('.').map(Number));
}
// NAT64 64:ff9b::/96
if (b[0] === 0x00 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b && b.slice(4, 12).every((x) => x === 0)) {
return isPrivateV4([b[12], b[13], b[14], b[15]]);
if (fam === 6) {
const b = ipv6ToBytes(host);
if (!b) {
return true;
} // unparseable IPv6 → treat as unsafe
if (b.every((x) => x === 0)) {
return true;
} // ::
if (b.slice(0, 15).every((x) => x === 0) && b[15] === 1) {
return true;
} // ::1
if ((b[0] & 0xfe) === 0xfc) {
return true;
} // fc00::/7 unique-local
if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) {
return true;
} // fe80::/10 link-local
// v4-mapped ::ffff:a.b.c.d / v4-compatible ::a.b.c.d
if (
b.slice(0, 10).every((x) => x === 0) &&
((b[10] === 0xff && b[11] === 0xff) || (b[10] === 0 && b[11] === 0))
) {
return isPrivateV4([b[12], b[13], b[14], b[15]]);
}
// NAT64 64:ff9b::/96
if (
b[0] === 0x00 &&
b[1] === 0x64 &&
b[2] === 0xff &&
b[3] === 0x9b &&
b.slice(4, 12).every((x) => x === 0)
) {
return isPrivateV4([b[12], b[13], b[14], b[15]]);
}
return false;
}
return false;
}
return false;
}
/** Parse + SSRF-guard a URL: http(s) only, and neither the literal host nor any
@@ -129,36 +197,60 @@ function isPrivateIp(ip: string): boolean {
* against DNS rebinding, but blocks the obvious metadata-endpoint / internal
* service reach. */
async function assertSafeUrl(raw: string): Promise<URL> {
let u: URL;
try { u = new URL(raw); } catch { throw new DownloadError('invalid URL'); }
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new DownloadError('only http(s) URLs are allowed');
const host = u.hostname.replace(/^\[|\]$/g, '');
if (net.isIP(host)) {
if (isPrivateIp(host)) throw new DownloadError('refusing to fetch a private/loopback address');
let u: URL;
try {
u = new URL(raw);
} catch {
throw new DownloadError('invalid URL');
}
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
throw new DownloadError('only http(s) URLs are allowed');
}
const host = u.hostname.replace(/^\[|\]$/g, '');
if (net.isIP(host)) {
if (isPrivateIp(host)) {
throw new DownloadError('refusing to fetch a private/loopback address');
}
return u;
}
let addrs: Array<{ address: string }>;
try {
addrs = await dns.lookup(host, { all: true });
} catch {
throw new DownloadError(`cannot resolve host: ${host}`);
}
for (const a of addrs) {
if (isPrivateIp(a.address)) {
throw new DownloadError('refusing to fetch a host that resolves to a private address');
}
}
return u;
}
let addrs: Array<{ address: string }>;
try { addrs = await dns.lookup(host, { all: true }); } catch { throw new DownloadError(`cannot resolve host: ${host}`); }
for (const a of addrs) {
if (isPrivateIp(a.address)) throw new DownloadError('refusing to fetch a host that resolves to a private address');
}
return u;
}
interface DownloadSource {
name: string;
size: number; // 0 when unknown
iterable: AsyncIterable<Uint8Array>;
/** Local stream-storage path that must be protected from cleanup while read. */
managedPath?: string;
/** Force the underlying source closed (idle-timeout watchdog / abort). */
abort?: () => void;
name: string;
size: number; // 0 when unknown
iterable: AsyncIterable<Uint8Array>;
/** Local stream-storage path that must be protected from cleanup while read. */
managedPath?: string;
/** Force the underlying source closed (idle-timeout watchdog / abort). */
abort?: () => void;
}
const asStr = (v: JsonValue | undefined): string => (typeof v === 'string' ? v : '');
const asNum = (v: JsonValue | undefined): number => {
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : 0;
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : 0;
};
/** Follow redirects MANUALLY, SSRF-guarding every hop. Default fetch follows
@@ -170,231 +262,348 @@ const asNum = (v: JsonValue | undefined): number => {
* body. (DNS rebinding between our check and undici's own connect remains a
* known residual — it needs connect-time peer-IP validation to fully close.) */
async function fetchGuarded(rawUrl: string): Promise<{ resp: Response; abort: () => void }> {
let current = rawUrl;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
const u = await assertSafeUrl(current);
const ac = new AbortController();
const t = setTimeout(() => ac.abort(), FETCH_CONNECT_TIMEOUT_MS);
let resp: Response;
try {
resp = await fetch(u, { headers: { 'User-Agent': DOWNLOAD_USER_AGENT }, redirect: 'manual', signal: ac.signal });
} finally {
clearTimeout(t);
let current = rawUrl;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
const u = await assertSafeUrl(current);
const ac = new AbortController();
const t = setTimeout(() => ac.abort(), FETCH_CONNECT_TIMEOUT_MS);
let resp: Response;
try {
resp = await fetch(u, {
headers: { 'User-Agent': DOWNLOAD_USER_AGENT },
redirect: 'manual',
signal: ac.signal,
});
} finally {
clearTimeout(t);
}
if (resp.status >= 300 && resp.status < 400) {
const loc = resp.headers.get('location');
await resp.body?.cancel().catch(() => {
/* ignore */
});
if (!loc) {
throw new DownloadError(
`download failed: ${resp.status} redirect without Location`,
);
}
current = new URL(loc, u).toString();
continue;
}
return { resp, abort: () => ac.abort() };
}
if (resp.status >= 300 && resp.status < 400) {
const loc = resp.headers.get('location');
await resp.body?.cancel().catch(() => { /* ignore */ });
if (!loc) throw new DownloadError(`download failed: ${resp.status} redirect without Location`);
current = new URL(loc, u).toString();
continue;
}
return { resp, abort: () => ac.abort() };
}
throw new DownloadError('download failed: too many redirects');
throw new DownloadError('download failed: too many redirects');
}
async function openUrl(rawUrl: string, name: string, knownSize: number): Promise<DownloadSource> {
const { resp, abort } = await fetchGuarded(rawUrl);
if (!resp.ok) {
await resp.body?.cancel().catch(() => { /* ignore */ });
throw new DownloadError(`download failed: HTTP ${resp.status}`);
}
const declared = Number(resp.headers.get('content-length') ?? '');
const size = (Number.isFinite(declared) && declared > 0 ? declared : 0) || knownSize;
if (!resp.body) throw new DownloadError('download failed: empty response body');
return { name: name || urlBasename(rawUrl), size, iterable: resp.body as unknown as AsyncIterable<Uint8Array>, abort };
const { resp, abort } = await fetchGuarded(rawUrl);
if (!resp.ok) {
await resp.body?.cancel().catch(() => {
/* ignore */
});
throw new DownloadError(`download failed: HTTP ${resp.status}`);
}
const declared = Number(resp.headers.get('content-length') ?? '');
const size = (Number.isFinite(declared) && declared > 0 ? declared : 0) || knownSize;
if (!resp.body) {
throw new DownloadError('download failed: empty response body');
}
return {
name: name || urlBasename(rawUrl),
size,
iterable: resp.body as unknown as AsyncIterable<Uint8Array>,
abort,
};
}
function urlBasename(u: string): string {
try {
const name = path.basename(new URL(u).pathname);
return name && name !== '/' ? decodeURIComponent(name) : 'download.bin';
} catch { return 'download.bin'; }
try {
const name = path.basename(new URL(u).pathname);
return name && name !== '/' ? decodeURIComponent(name) : 'download.bin';
} catch {
return 'download.bin';
}
}
async function resolveDownload(
target: string,
ctx: ApiActionContext,
prefer: 'auto' | 'image' | 'record',
chunkSize: number,
target: string,
ctx: ApiActionContext,
prefer: 'auto' | 'image' | 'record',
chunkSize: number,
): Promise<DownloadSource> {
// 1. local file — but ONLY a real existing file, fenced inside the stream
// temp root. `resolveLocalFilePath` returns the input verbatim for any
// non-URL string (including cached-media ids), so we must NOT treat a
// non-existent "path" as local — that would shadow the cached-media branch
// below (the whole point of the *_image/_record_stream actions).
const local = resolveLocalFilePath(target);
if (local) {
let st: fs.Stats | null = null;
try { st = fs.statSync(local); } catch { st = null; }
if (st?.isFile()) {
ensureStreamDirectory(STREAM_ROOT);
// Fence against the *real* path so a symlink inside the root can't point
// out (lexical resolve alone would follow it).
let real = local;
try { real = fs.realpathSync(local); } catch { /* keep lexical */ }
if (!isWithinStreamRoot(real)) throw new DownloadError('local downloads are restricted to the stream temp directory');
const rs = fs.createReadStream(real, { highWaterMark: chunkSize });
return {
name: path.basename(real),
size: st.size,
iterable: rs,
managedPath: real,
abort: () => rs.destroy(),
};
// 1. local file — but ONLY a real existing file, fenced inside the stream
// temp root. `resolveLocalFilePath` returns the input verbatim for any
// non-URL string (including cached-media ids), so we must NOT treat a
// non-existent "path" as local — that would shadow the cached-media branch
// below (the whole point of the *_image/_record_stream actions).
const local = resolveLocalFilePath(target);
if (local) {
let st: fs.Stats | null = null;
try {
st = fs.statSync(local);
} catch {
st = null;
}
if (st?.isFile()) {
ensureStreamDirectory(STREAM_ROOT);
// Fence against the *real* path so a symlink inside the root can't point
// out (lexical resolve alone would follow it).
let real = local;
try {
real = fs.realpathSync(local);
} catch {
/* keep lexical */
}
if (!isWithinStreamRoot(real)) {
throw new DownloadError(
'local downloads are restricted to the stream temp directory',
);
}
const rs = fs.createReadStream(real, { highWaterMark: chunkSize });
return {
name: path.basename(real),
size: st.size,
iterable: rs,
managedPath: real,
abort: () => rs.destroy(),
};
}
}
}
// 2. explicit http(s) URL.
if (/^https?:\/\//i.test(target)) return openUrl(target, '', 0);
// 2. explicit http(s) URL.
if (/^https?:\/\//i.test(target)) {
return openUrl(target, '', 0);
}
// 3. cached image / voice id → QQ CDN URL.
let info: JsonObject | null = null;
if (prefer !== 'record') info = await ctx.getImageInfo(target);
if (!info && prefer !== 'image') info = await ctx.getRecordInfo(target);
if (info) {
const url = asStr(info.url) || asStr(info.file);
if (/^https?:\/\//i.test(url)) return openUrl(url, asStr(info.file_name), asNum(info.file_size));
}
// 3. cached image / voice id → QQ CDN URL.
let info: JsonObject | null = null;
throw new DownloadError('file not found (expected a stream-dir path, an http(s) URL, or a cached image/voice id)');
if (prefer !== 'record') {
info = await ctx.getImageInfo(target);
}
if (!info && prefer !== 'image') {
info = await ctx.getRecordInfo(target);
}
if (info) {
const url = asStr(info.url) || asStr(info.file);
if (/^https?:\/\//i.test(url)) {
return openUrl(url, asStr(info.file_name), asNum(info.file_size));
}
}
throw new DownloadError(
'file not found (expected a stream-dir path, an http(s) URL, or a cached image/voice id)',
);
}
// ─────────────────────────── push engine ───────────────────────────
async function streamChunks(
sink: StreamSink,
iterable: AsyncIterable<Uint8Array>,
totalSize: number,
dataType: string,
abort?: () => void,
sink: StreamSink,
iterable: AsyncIterable<Uint8Array>,
totalSize: number,
dataType: string,
abort?: () => void,
): Promise<{ totalChunks: number; totalBytes: number }> {
let index = 0;
let bytesRead = 0;
// Anti-stall: if no chunk arrives for IDLE_TIMEOUT_MS, force the source closed
// so a server that sends headers then hangs can't pin a socket forever (the
// sink's own liveness check only fires when we actually send a frame).
let idle: NodeJS.Timeout | null = null;
const armIdle = (): void => {
if (idle) clearTimeout(idle);
idle = setTimeout(() => { abort?.(); }, IDLE_TIMEOUT_MS);
if (idle.unref) idle.unref();
};
armIdle();
try {
for await (const part of iterable) {
armIdle();
const buf = Buffer.isBuffer(part) ? part : Buffer.from(part);
bytesRead += buf.length;
if (bytesRead > MAX_DOWNLOAD_BYTES) throw new DownloadError(`download exceeds size limit (${MAX_DOWNLOAD_BYTES} bytes)`);
const b64 = buf.toString('base64');
await sink.send({
type: StreamStatus.Stream,
data_type: dataType,
index,
data: b64,
size: buf.length,
progress: totalSize > 0 ? Math.min(100, Math.round((bytesRead / totalSize) * 100)) : 0,
base64_size: b64.length,
});
index++;
let index = 0;
let bytesRead = 0;
// Anti-stall: if no chunk arrives for IDLE_TIMEOUT_MS, force the source closed
// so a server that sends headers then hangs can't pin a socket forever (the
// sink's own liveness check only fires when we actually send a frame).
let idle: NodeJS.Timeout | null = null;
const armIdle = (): void => {
if (idle) {
clearTimeout(idle);
}
idle = setTimeout(() => {
abort?.();
}, IDLE_TIMEOUT_MS);
if (idle.unref) {
idle.unref();
}
};
armIdle();
try {
for await (const part of iterable) {
armIdle();
const buf = Buffer.isBuffer(part) ? part : Buffer.from(part);
bytesRead += buf.length;
if (bytesRead > MAX_DOWNLOAD_BYTES) {
throw new DownloadError(
`download exceeds size limit (${MAX_DOWNLOAD_BYTES} bytes)`,
);
}
const b64 = buf.toString('base64');
await sink.send({
type: StreamStatus.Stream,
data_type: dataType,
index,
data: b64,
size: buf.length,
progress:
totalSize > 0 ? Math.min(100, Math.round((bytesRead / totalSize) * 100)) : 0,
base64_size: b64.length,
});
index++;
}
} finally {
if (idle) {
clearTimeout(idle);
}
}
} finally {
if (idle) clearTimeout(idle);
}
return { totalChunks: index, totalBytes: bytesRead };
return { totalChunks: index, totalBytes: bytesRead };
}
async function runDownload(
target: string,
chunkSizeReq: number | undefined,
ctx: ApiActionContext,
sink: StreamSink,
prefer: 'auto' | 'image' | 'record',
target: string,
chunkSizeReq: number | undefined,
ctx: ApiActionContext,
sink: StreamSink,
prefer: 'auto' | 'image' | 'record',
): Promise<ApiResponse> {
if (!target) throw new DownloadError('file is required');
let chunkSize = chunkSizeReq && chunkSizeReq > 0 ? chunkSizeReq : DEFAULT_CHUNK_BYTES;
if (chunkSize > MAX_CHUNK_REQUEST_BYTES) chunkSize = MAX_CHUNK_REQUEST_BYTES;
if (!target) {
throw new DownloadError('file is required');
}
const src = await resolveDownload(target, ctx, prefer, chunkSize);
const releaseStorageActivity = src.managedPath
? registerActiveStreamItem([src.managedPath])
: undefined;
try {
await sink.send({
type: StreamStatus.Stream,
data_type: 'file_info',
file_name: src.name,
file_size: src.size,
chunk_size: chunkSize,
});
const { totalChunks, totalBytes } = await streamChunks(
sink,
src.iterable,
src.size,
'file_chunk',
src.abort,
);
return okResponse({
type: StreamStatus.Response,
data_type: 'file_complete',
file_name: src.name,
total_chunks: totalChunks,
total_bytes: totalBytes,
message: 'Download completed',
});
} finally {
releaseStorageActivity?.();
}
let chunkSize = chunkSizeReq && chunkSizeReq > 0 ? chunkSizeReq : DEFAULT_CHUNK_BYTES;
if (chunkSize > MAX_CHUNK_REQUEST_BYTES) {
chunkSize = MAX_CHUNK_REQUEST_BYTES;
}
const src = await resolveDownload(target, ctx, prefer, chunkSize);
const releaseStorageActivity = src.managedPath
? registerActiveStreamItem([src.managedPath])
: undefined;
try {
await sink.send({
type: StreamStatus.Stream,
data_type: 'file_info',
file_name: src.name,
file_size: src.size,
chunk_size: chunkSize,
});
const { totalChunks, totalBytes } = await streamChunks(
sink,
src.iterable,
src.size,
'file_chunk',
src.abort,
);
return okResponse({
type: StreamStatus.Response,
data_type: 'file_complete',
file_name: src.name,
total_chunks: totalChunks,
total_bytes: totalBytes,
message: 'Download completed',
});
} finally {
releaseStorageActivity?.();
}
}
// ─────────────────────────── action definitions ───────────────────────────
const downloadParams = {
file: f.string().optional().describe('文件路径(限 stream 临时目录)/ http(s) URL').role('file'),
file_id: f.string().optional().describe('文件 ID(缓存的图片/语音 id)').role('file_id'),
chunk_size: f.int({ min: 1 }).optional().describe('分块大小(字节,默认 64KB)'),
file: f.string().optional().describe('文件路径(限 stream 临时目录)/ http(s) URL').role('file'),
file_id: f.string().optional().describe('文件 ID(缓存的图片/语音 id)').role('file_id'),
chunk_size: f.int({ min: 1 }).optional().describe('分块大小(字节,默认 64KB)'),
};
const downloadFileStream = defineStreamAction({
name: 'download_file_stream',
summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'),
name: 'download_file_stream',
summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'),
});
const downloadFileImageStream = defineStreamAction({
name: 'download_file_image_stream',
summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'),
name: 'download_file_image_stream',
summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'),
});
const downloadFileRecordStream = defineStreamAction({
name: 'download_file_record_stream',
summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'),
name: 'download_file_record_stream',
summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, sink) =>
runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'),
});
const testDownloadStream = defineStreamAction({
name: 'test_download_stream',
summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)',
returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)',
params: { error: f.bool().default(false).describe('是否触发测试错误') },
run: async (p, _ctx, sink) => {
for (let i = 0; i < 10; i++) {
await sink.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: 'data_chunk' });
}
if (p.error) throw new DownloadError('This is a test error');
return okResponse({ type: StreamStatus.Response, data_type: 'data_complete', data: 'Stream transmission complete' });
},
name: 'test_download_stream',
summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)',
returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)',
params: { error: f.bool().default(false).describe('是否触发测试错误') },
run: async (p, _ctx, sink) => {
for (let i = 0; i < 10; i++) {
await sink.send({
type: StreamStatus.Stream,
data: `Index-> ${i + 1}`,
data_type: 'data_chunk',
});
}
if (p.error) {
throw new DownloadError('This is a test error');
}
return okResponse({
type: StreamStatus.Response,
data_type: 'data_complete',
data: 'Stream transmission complete',
});
},
});
export const actions = [downloadFileStream, downloadFileImageStream, downloadFileRecordStream, testDownloadStream];
export const actions = [
downloadFileStream,
downloadFileImageStream,
downloadFileRecordStream,
testDownloadStream,
];
// Exposed for tests.
export const __test = { resolveDownload, isWithinStreamRoot, isPrivateIp, assertSafeUrl, streamChunks, runDownload };
export const __test = {
resolveDownload,
isWithinStreamRoot,
isPrivateIp,
assertSafeUrl,
streamChunks,
runDownload,
};
+404 -277
View File
@@ -26,28 +26,28 @@ import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse } from '../types';
import { StreamStatus } from '../streaming';
import {
STREAM_DOWNLOAD_DIR,
STREAM_ROOT,
STREAM_UPLOAD_DIR,
clearInactiveStreamStorage,
ensureStreamDirectory,
registerActiveStreamItem,
STREAM_DOWNLOAD_DIR,
STREAM_ROOT,
STREAM_UPLOAD_DIR,
clearInactiveStreamStorage,
ensureStreamDirectory,
registerActiveStreamItem,
} from '../stream-storage';
const log = createLogger('OneBot.Stream');
export { STREAM_DOWNLOAD_DIR, STREAM_ROOT, STREAM_UPLOAD_DIR };
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; // idle stream reaped after 10 min
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; // idle stream reaped after 10 min
const DEFAULT_RETENTION_MS = 5 * 60 * 1000; // reassembled file auto-deleted after 5 min
// Resource caps (DoS guards — the whole point of the disk-streaming design is
// blown if a single request can still OOM, and an unbounded server can be
// flooded with streams/chunks/bytes).
const MAX_CONCURRENT_STREAMS = 64;
const MAX_CHUNKS = 200_000; // also bounds the completion scan
const MAX_CHUNK_BYTES = 32 * 1024 * 1024; // one decoded chunk
const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB cumulative per stream
const MAX_CHUNKS = 200_000; // also bounds the completion scan
const MAX_CHUNK_BYTES = 32 * 1024 * 1024; // one decoded chunk
const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB cumulative per stream
// stream_id / account key allowlist: filename-safe, no separators, no dots
// (so no `.`/`..` traversal token can ever reach a path segment).
@@ -56,51 +56,60 @@ const SAFE_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
class StreamError extends Error {}
function validateStreamId(id: string): void {
if (!SAFE_ID_RE.test(id)) throw new StreamError('invalid stream_id (allowed: 1-128 chars of A-Z a-z 0-9 _ -)');
if (!SAFE_ID_RE.test(id)) {
throw new StreamError('invalid stream_id (allowed: 1-128 chars of A-Z a-z 0-9 _ -)');
}
}
/** Account namespace for the in-memory map + on-disk dirs. Empty (tests / no
* login) → flat, un-namespaced. Sanitised so it can't widen the path either. */
function accountKey(ctx?: ApiActionContext): string {
let raw = '';
try { raw = String(ctx?.getLoginInfo?.().userId ?? ''); } catch { raw = ''; }
return raw.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64);
let raw = '';
try {
raw = String(ctx?.getLoginInfo?.().userId ?? '');
} catch {
raw = '';
}
return raw.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64);
}
/** Belt-and-braces: assert a derived path stays inside the upload dir even if
* the allowlist above is ever weakened. */
function assertWithin(root: string, target: string): void {
const rel = path.relative(root, target);
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
throw new StreamError('resolved stream path escapes the upload directory');
}
const rel = path.relative(root, target);
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
throw new StreamError('resolved stream path escapes the upload directory');
}
}
// ─────────────────────────── upload state ───────────────────────────
interface UploadState {
/** Client-facing stream_id (echoed in frames). */
id: string;
/** Internal map key — `<account>:<id>` or just `<id>` when un-namespaced. */
key: string;
filename: string;
totalChunks: number;
/** Indices CLAIMED (sync, before the write await) — drives dedup + byte
* accounting so two concurrent calls for one index can't double-count. */
claimed: Set<number>;
/** Indices actually FLUSHED to disk (added after the write resolves) — drives
* completion + the reported count, so completion can't fire while a chunk
* file is still being written (which would read a truncated part). Neither
* set is pre-allocated to total_chunks (that would defeat the no-OOM goal). */
written: Set<number>;
bytesWritten: number;
fileSize?: number;
expectedSha256?: string;
tempDir: string;
finalPath: string;
fileRetention: number;
timeoutId: NodeJS.Timeout;
releaseStorageActivity: () => void;
/** Client-facing stream_id (echoed in frames). */
id: string;
/** Internal map key — `<account>:<id>` or just `<id>` when un-namespaced. */
key: string;
filename: string;
totalChunks: number;
/** Indices CLAIMED (sync, before the write await) — drives dedup + byte
* accounting so two concurrent calls for one index can't double-count. */
claimed: Set<number>;
/** Indices actually FLUSHED to disk (added after the write resolves) — drives
* completion + the reported count, so completion can't fire while a chunk
* file is still being written (which would read a truncated part). Neither
* set is pre-allocated to total_chunks (that would defeat the no-OOM goal). */
written: Set<number>;
bytesWritten: number;
fileSize?: number;
expectedSha256?: string;
tempDir: string;
finalPath: string;
fileRetention: number;
timeoutId: NodeJS.Timeout;
releaseStorageActivity: () => void;
}
/** Process-wide. Key is account-namespaced so two accounts (same process) can't
@@ -108,303 +117,421 @@ interface UploadState {
const uploads = new Map<string, UploadState>();
function reapTimer(key: string): NodeJS.Timeout {
const t = setTimeout(() => { cleanupUpload(key, true); }, UPLOAD_TIMEOUT_MS);
if (typeof t.unref === 'function') t.unref(); // don't pin the event loop on a stalled upload
return t;
const t = setTimeout(() => {
cleanupUpload(key, true);
}, UPLOAD_TIMEOUT_MS);
if (typeof t.unref === 'function') {
t.unref();
} // don't pin the event loop on a stalled upload
return t;
}
function cleanupUpload(key: string, deleteFinal: boolean): void {
const state = uploads.get(key);
if (!state) return;
clearTimeout(state.timeoutId);
try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch (error) {
log.warn('failed to delete stream upload chunks %s: %s', state.tempDir, errorMessage(error));
}
if (deleteFinal) {
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete stream upload file %s: %s', state.finalPath, errorMessage(error));
const state = uploads.get(key);
if (!state) {
return;
}
}
uploads.delete(key);
state.releaseStorageActivity();
clearTimeout(state.timeoutId);
try {
fs.rmSync(state.tempDir, { recursive: true, force: true });
} catch (error) {
log.warn(
'failed to delete stream upload chunks %s: %s',
state.tempDir,
errorMessage(error),
);
}
if (deleteFinal) {
try {
fs.rmSync(state.finalPath, { force: true });
} catch (error) {
log.warn(
'failed to delete stream upload file %s: %s',
state.finalPath,
errorMessage(error),
);
}
}
uploads.delete(key);
state.releaseStorageActivity();
}
function safeFilename(name: string | undefined, id: string): string {
const base = (name ?? '')
.replace(/[/\\]/g, '_') // no directory separators
.replace(/\.\.+/g, '_') // no `..` traversal tokens
.replace(/^\.+/, '') // no leading dots
.trim();
return base || `upload_${id}`;
const base = (name ?? '')
.replace(/[/\\]/g, '_') // no directory separators
.replace(/\.\.+/g, '_') // no `..` traversal tokens
.replace(/^\.+/, '') // no leading dots
.trim();
return base || `upload_${id}`;
}
function createUpload(p: UploadParams, account: string): UploadState {
if (!p.total_chunks || p.total_chunks <= 0) throw new StreamError('total_chunks required for new stream');
if (p.total_chunks > MAX_CHUNKS) throw new StreamError(`total_chunks exceeds limit (${MAX_CHUNKS})`);
if (p.file_size !== undefined && p.file_size > MAX_UPLOAD_BYTES) throw new StreamError(`file_size exceeds limit (${MAX_UPLOAD_BYTES} bytes)`);
if (uploads.size >= MAX_CONCURRENT_STREAMS) throw new StreamError(`too many concurrent upload streams (${MAX_CONCURRENT_STREAMS})`);
if (!p.total_chunks || p.total_chunks <= 0) {
throw new StreamError('total_chunks required for new stream');
}
const filename = safeFilename(p.filename, p.stream_id);
const dirRoot = account ? path.join(STREAM_UPLOAD_DIR, account) : STREAM_UPLOAD_DIR;
const tempDir = path.join(dirRoot, p.stream_id);
const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`);
assertWithin(STREAM_UPLOAD_DIR, tempDir);
assertWithin(STREAM_UPLOAD_DIR, finalPath);
ensureStreamDirectory(tempDir);
if (p.total_chunks > MAX_CHUNKS) {
throw new StreamError(`total_chunks exceeds limit (${MAX_CHUNKS})`);
}
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]);
const state: UploadState = {
id: p.stream_id,
key,
filename,
totalChunks: p.total_chunks,
claimed: new Set(),
written: new Set(),
bytesWritten: 0,
fileSize: p.file_size,
expectedSha256: p.expected_sha256,
tempDir,
finalPath,
fileRetention: p.file_retention,
timeoutId: reapTimer(key),
releaseStorageActivity,
};
uploads.set(key, state);
return state;
if (p.file_size !== undefined && p.file_size > MAX_UPLOAD_BYTES) {
throw new StreamError(`file_size exceeds limit (${MAX_UPLOAD_BYTES} bytes)`);
}
if (uploads.size >= MAX_CONCURRENT_STREAMS) {
throw new StreamError(`too many concurrent upload streams (${MAX_CONCURRENT_STREAMS})`);
}
const filename = safeFilename(p.filename, p.stream_id);
const dirRoot = account ? path.join(STREAM_UPLOAD_DIR, account) : STREAM_UPLOAD_DIR;
const tempDir = path.join(dirRoot, p.stream_id);
const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`);
assertWithin(STREAM_UPLOAD_DIR, tempDir);
assertWithin(STREAM_UPLOAD_DIR, finalPath);
ensureStreamDirectory(tempDir);
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]);
const state: UploadState = {
id: p.stream_id,
key,
filename,
totalChunks: p.total_chunks,
claimed: new Set(),
written: new Set(),
bytesWritten: 0,
fileSize: p.file_size,
expectedSha256: p.expected_sha256,
tempDir,
finalPath,
fileRetention: p.file_retention,
timeoutId: reapTimer(key),
releaseStorageActivity,
};
uploads.set(key, state);
return state;
}
function statusFrame(state: UploadState, status: string): ApiResponse {
return okResponse({
type: StreamStatus.Stream,
stream_id: state.id,
status,
received_chunks: state.written.size,
total_chunks: state.totalChunks,
});
return okResponse({
type: StreamStatus.Stream,
stream_id: state.id,
status,
received_chunks: state.written.size,
total_chunks: state.totalChunks,
});
}
function writeChunkToStream(stream: fs.WriteStream, buf: Buffer): Promise<void> {
return new Promise((resolve, reject) => {
stream.write(buf, (err) => (err ? reject(err) : resolve()));
});
return new Promise((resolve, reject) => {
stream.write(buf, (err) => (err ? reject(err) : resolve()));
});
}
async function completeUpload(state: UploadState): Promise<ApiResponse> {
if (state.written.size !== state.totalChunks) {
const missing: number[] = [];
for (let i = 0; i < state.totalChunks && missing.length < 16; i++) {
if (!state.written.has(i)) missing.push(i);
if (state.written.size !== state.totalChunks) {
const missing: number[] = [];
for (let i = 0; i < state.totalChunks && missing.length < 16; i++) {
if (!state.written.has(i)) {
missing.push(i);
}
}
const more = state.totalChunks - state.written.size > missing.length ? '…' : '';
throw new StreamError(
`incomplete stream: missing ${state.totalChunks - state.written.size} chunk(s) [${missing.join(',')}${more}]`,
);
}
const more = state.totalChunks - state.written.size > missing.length ? '…' : '';
throw new StreamError(`incomplete stream: missing ${state.totalChunks - state.written.size} chunk(s) [${missing.join(',')}${more}]`);
}
// Stream each chunk file into the final file in order, hashing as we go — one
// chunk in memory at a time, never the whole payload.
const hash = createHash('sha256');
const out = fs.createWriteStream(state.finalPath);
try {
for (let i = 0; i < state.totalChunks; i++) {
const buf = await fs.promises.readFile(path.join(state.tempDir, `${i}.chunk`));
hash.update(buf);
await writeChunkToStream(out, buf);
// Stream each chunk file into the final file in order, hashing as we go — one
// chunk in memory at a time, never the whole payload.
const hash = createHash('sha256');
const out = fs.createWriteStream(state.finalPath);
try {
for (let i = 0; i < state.totalChunks; i++) {
const buf = await fs.promises.readFile(path.join(state.tempDir, `${i}.chunk`));
hash.update(buf);
await writeChunkToStream(out, buf);
}
await new Promise<void>((resolve, reject) =>
out.end((err?: Error | null) => (err ? reject(err) : resolve())),
);
} catch (err) {
out.destroy();
try {
fs.rmSync(state.finalPath, { force: true });
} catch (error) {
log.warn(
'failed to delete incomplete stream file %s: %s',
state.finalPath,
errorMessage(error),
);
}
throw err;
}
await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve())));
} catch (err) {
out.destroy();
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete incomplete stream file %s: %s', state.finalPath, errorMessage(error));
const sha256 = hash.digest('hex');
if (state.expectedSha256 && sha256 !== state.expectedSha256) {
try {
fs.rmSync(state.finalPath, { force: true });
} catch (error) {
log.warn(
'failed to delete invalid stream file %s: %s',
state.finalPath,
errorMessage(error),
);
}
throw new StreamError(`sha256 mismatch (expected ${state.expectedSha256}, got ${sha256})`);
}
throw err;
}
const sha256 = hash.digest('hex');
if (state.expectedSha256 && sha256 !== state.expectedSha256) {
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete invalid stream file %s: %s', state.finalPath, errorMessage(error));
const finalPath = state.finalPath;
const fileSize = fs.statSync(finalPath).size;
const received = state.written.size;
const total = state.totalChunks;
const retention = state.fileRetention;
// Drop chunk parts + in-memory state but KEEP the reassembled file.
cleanupUpload(state.key, false);
if (retention > 0) {
const t = setTimeout(() => {
fs.rm(finalPath, { force: true }, (err) => {
if (err) {
log.warn(
'failed to delete retained stream file %s: %s',
finalPath,
err.message,
);
}
});
}, retention);
if (typeof t.unref === 'function') {
t.unref();
}
}
throw new StreamError(`sha256 mismatch (expected ${state.expectedSha256}, got ${sha256})`);
}
const finalPath = state.finalPath;
const fileSize = fs.statSync(finalPath).size;
const received = state.written.size;
const total = state.totalChunks;
const retention = state.fileRetention;
// Drop chunk parts + in-memory state but KEEP the reassembled file.
cleanupUpload(state.key, false);
if (retention > 0) {
const t = setTimeout(() => {
fs.rm(finalPath, { force: true }, (err) => {
if (err) log.warn('failed to delete retained stream file %s: %s', finalPath, err.message);
});
}, retention);
if (typeof t.unref === 'function') t.unref();
}
return okResponse({
type: StreamStatus.Response,
stream_id: state.id,
status: 'file_complete',
received_chunks: received,
total_chunks: total,
file_path: finalPath,
file_name: state.filename,
file_size: fileSize,
sha256,
});
return okResponse({
type: StreamStatus.Response,
stream_id: state.id,
status: 'file_complete',
received_chunks: received,
total_chunks: total,
file_path: finalPath,
file_name: state.filename,
file_size: fileSize,
sha256,
});
}
async function handleUpload(p: UploadParams, account = ''): Promise<ApiResponse> {
validateStreamId(p.stream_id);
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
validateStreamId(p.stream_id);
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
if (p.reset) {
cleanupUpload(key, true);
// NapCat surfaces reset as an error frame; mirror it for client parity.
throw new StreamError('Stream reset completed');
}
if (p.verify_only) {
const state = uploads.get(key);
if (!state) throw new StreamError('stream not found');
return statusFrame(state, 'file_created');
}
const state = uploads.get(key) ?? createUpload(p, account);
// Metadata may arrive on the creating call or any later one (e.g. the client
// only knows the whole-file sha256 when it sends `is_complete`).
if (p.expected_sha256 !== undefined) state.expectedSha256 = p.expected_sha256;
if (p.file_size !== undefined) state.fileSize = p.file_size;
if (p.chunk_data !== undefined && p.chunk_index !== undefined) {
const index = p.chunk_index;
if (index < 0 || index >= state.totalChunks) throw new StreamError(`invalid chunk index: ${index}`);
if (state.claimed.has(index)) return statusFrame(state, 'chunk_received'); // duplicate / in-flight — idempotent
const buf = Buffer.from(p.chunk_data, 'base64');
if (buf.length > MAX_CHUNK_BYTES) throw new StreamError(`chunk exceeds size limit (${MAX_CHUNK_BYTES} bytes)`);
if (state.bytesWritten + buf.length > MAX_UPLOAD_BYTES) throw new StreamError(`stream exceeds total size limit (${MAX_UPLOAD_BYTES} bytes)`);
// Claim the index synchronously (before the write await) so two concurrent
// calls for the same index can't both pass the dedup check or double-count
// bytes. `written` is only set AFTER the bytes hit disk, so completion can
// never fire while this chunk file is still being written.
state.claimed.add(index);
state.bytesWritten += buf.length;
try {
await fs.promises.writeFile(path.join(state.tempDir, `${index}.chunk`), buf);
} catch (err) {
state.claimed.delete(index);
state.bytesWritten -= buf.length;
throw err;
if (p.reset) {
cleanupUpload(key, true);
// NapCat surfaces reset as an error frame; mirror it for client parity.
throw new StreamError('Stream reset completed');
}
state.written.add(index);
clearTimeout(state.timeoutId);
state.timeoutId = reapTimer(state.key);
return statusFrame(state, 'chunk_received');
}
if (p.is_complete || state.written.size === state.totalChunks) {
return completeUpload(state);
}
if (p.verify_only) {
const state = uploads.get(key);
return statusFrame(state, 'file_created');
if (!state) {
throw new StreamError('stream not found');
}
return statusFrame(state, 'file_created');
}
const state = uploads.get(key) ?? createUpload(p, account);
// Metadata may arrive on the creating call or any later one (e.g. the client
// only knows the whole-file sha256 when it sends `is_complete`).
if (p.expected_sha256 !== undefined) {
state.expectedSha256 = p.expected_sha256;
}
if (p.file_size !== undefined) {
state.fileSize = p.file_size;
}
if (p.chunk_data !== undefined && p.chunk_index !== undefined) {
const index = p.chunk_index;
if (index < 0 || index >= state.totalChunks) {
throw new StreamError(`invalid chunk index: ${index}`);
}
if (state.claimed.has(index)) {
return statusFrame(state, 'chunk_received');
} // duplicate / in-flight — idempotent
const buf = Buffer.from(p.chunk_data, 'base64');
if (buf.length > MAX_CHUNK_BYTES) {
throw new StreamError(`chunk exceeds size limit (${MAX_CHUNK_BYTES} bytes)`);
}
if (state.bytesWritten + buf.length > MAX_UPLOAD_BYTES) {
throw new StreamError(`stream exceeds total size limit (${MAX_UPLOAD_BYTES} bytes)`);
}
// Claim the index synchronously (before the write await) so two concurrent
// calls for the same index can't both pass the dedup check or double-count
// bytes. `written` is only set AFTER the bytes hit disk, so completion can
// never fire while this chunk file is still being written.
state.claimed.add(index);
state.bytesWritten += buf.length;
try {
await fs.promises.writeFile(path.join(state.tempDir, `${index}.chunk`), buf);
} catch (err) {
state.claimed.delete(index);
state.bytesWritten -= buf.length;
throw err;
}
state.written.add(index);
clearTimeout(state.timeoutId);
state.timeoutId = reapTimer(state.key);
return statusFrame(state, 'chunk_received');
}
if (p.is_complete || state.written.size === state.totalChunks) {
return completeUpload(state);
}
return statusFrame(state, 'file_created');
}
// ─────────────────────────── action definitions ───────────────────────────
const uploadParams = {
stream_id: f.string({ allowEmpty: false }).describe('流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])'),
chunk_data: f.string().optional().describe('分块数据(Base64)'),
chunk_index: f.int({ min: 0 }).optional().describe('分块索引(从 0 开始)'),
total_chunks: f.int({ min: 1 }).optional().describe('总分块数(新流必填)'),
file_size: f.int({ min: 0 }).optional().describe('文件总大小(字节)'),
expected_sha256: f.string().optional().describe('期望的整文件 SHA256(校验)'),
is_complete: f.bool().optional().describe('是否为最后一个分块/触发合并'),
filename: f.string().optional().describe('文件名'),
reset: f.bool().optional().describe('重置并丢弃该流'),
verify_only: f.bool().optional().describe('仅查询当前流状态'),
file_retention: f.int({ min: 0 }).default(DEFAULT_RETENTION_MS).describe('合并文件保留毫秒(0=不回收)'),
stream_id: f
.string({ allowEmpty: false })
.describe('流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])'),
chunk_data: f.string().optional().describe('分块数据(Base64)'),
chunk_index: f.int({ min: 0 }).optional().describe('分块索引(从 0 开始)'),
total_chunks: f.int({ min: 1 }).optional().describe('总分块数(新流必填)'),
file_size: f.int({ min: 0 }).optional().describe('文件总大小(字节)'),
expected_sha256: f.string().optional().describe('期望的整文件 SHA256(校验)'),
is_complete: f.bool().optional().describe('是否为最后一个分块/触发合并'),
filename: f.string().optional().describe('文件名'),
reset: f.bool().optional().describe('重置并丢弃该流'),
verify_only: f.bool().optional().describe('仅查询当前流状态'),
file_retention: f
.int({ min: 0 })
.default(DEFAULT_RETENTION_MS)
.describe('合并文件保留毫秒(0=不回收)'),
};
type UploadParams = {
stream_id: string;
chunk_data: string | undefined;
chunk_index: number | undefined;
total_chunks: number | undefined;
file_size: number | undefined;
expected_sha256: string | undefined;
is_complete: boolean | undefined;
filename: string | undefined;
reset: boolean | undefined;
verify_only: boolean | undefined;
file_retention: number;
stream_id: string;
chunk_data: string | undefined;
chunk_index: number | undefined;
total_chunks: number | undefined;
file_size: number | undefined;
expected_sha256: string | undefined;
is_complete: boolean | undefined;
filename: string | undefined;
reset: boolean | undefined;
verify_only: boolean | undefined;
file_retention: number;
};
const uploadFileStream = defineStreamAction({
name: 'upload_file_stream',
summary: '以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)',
returns: '流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)',
params: uploadParams,
run: (p, ctx) => handleUpload(p, accountKey(ctx)),
name: 'upload_file_stream',
summary: '以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)',
returns:
'流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)',
params: uploadParams,
run: (p, ctx) => handleUpload(p, accountKey(ctx)),
});
function cleanDir(dir: string): number {
let removed = 0;
let entries: string[];
try {
entries = fs.readdirSync(dir);
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return 0;
throw error;
}
for (const name of entries) {
try { fs.rmSync(path.join(dir, name), { recursive: true, force: true }); removed++; } catch (err) {
log.warn('failed to remove stream temp %s: %s', path.join(dir, name), err instanceof Error ? err.message : String(err));
let removed = 0;
let entries: string[];
try {
entries = fs.readdirSync(dir);
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
return 0;
}
throw error;
}
}
return removed;
for (const name of entries) {
try {
fs.rmSync(path.join(dir, name), { recursive: true, force: true });
removed++;
} catch (err) {
log.warn(
'failed to remove stream temp %s: %s',
path.join(dir, name),
err instanceof Error ? err.message : String(err),
);
}
}
return removed;
}
const cleanStreamTempFile = defineAction({
name: 'clean_stream_temp_file',
summary: '清理流式传输临时文件(仅清理 stream 上传/下载目录)',
returns: '{ message, removed }',
params: {},
run: () => {
const result = clearInactiveStreamStorage();
for (const failure of result.failures) {
log.warn('failed to remove stream temp %s: %s', failure.item, failure.message);
}
if (result.failures.length > 0) {
throw new StreamError(`failed to remove ${result.failures.length} stream temp item(s)`);
}
return okResponse({
message: 'success',
removed: result.deletedFiles,
freed_bytes: result.freedBytes,
skipped_active: result.skippedActiveItems,
});
},
name: 'clean_stream_temp_file',
summary: '清理流式传输临时文件(仅清理 stream 上传/下载目录)',
returns: '{ message, removed }',
params: {},
run: () => {
const result = clearInactiveStreamStorage();
for (const failure of result.failures) {
log.warn('failed to remove stream temp %s: %s', failure.item, failure.message);
}
if (result.failures.length > 0) {
throw new StreamError(`failed to remove ${result.failures.length} stream temp item(s)`);
}
return okResponse({
message: 'success',
removed: result.deletedFiles,
freed_bytes: result.freedBytes,
skipped_active: result.skippedActiveItems,
});
},
});
export const actions = [uploadFileStream, cleanStreamTempFile];
// Exposed for tests.
export const __test = {
uploads,
handleUpload,
cleanupUpload,
cleanDir,
validateStreamId,
STREAM_UPLOAD_DIR,
MAX_CONCURRENT_STREAMS,
MAX_CHUNKS,
uploads,
handleUpload,
cleanupUpload,
cleanDir,
validateStreamId,
STREAM_UPLOAD_DIR,
MAX_CONCURRENT_STREAMS,
MAX_CHUNKS,
};
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
return error instanceof Error ? error.message : String(error);
}
+127 -113
View File
@@ -4,20 +4,20 @@ import { defineAction, f } from '../action-kit';
import { okResponse, type JsonObject } from '../types';
function faceEntry(face: SysFaceEntry): JsonObject {
return {
q_sid: face.qSid,
q_des: face.qDes,
em_code: face.emCode,
q_cid: face.qCid,
ani_sticker_type: face.aniStickerType,
ani_sticker_pack_id: face.aniStickerPackId,
ani_sticker_id: face.aniStickerId,
url: face.url,
emoji_name_alias: face.emojiNameAlias,
ani_sticker_width: face.aniStickerWidth,
ani_sticker_height: face.aniStickerHeight,
is_super: isSuperFaceEntry(face),
};
return {
q_sid: face.qSid,
q_des: face.qDes,
em_code: face.emCode,
q_cid: face.qCid,
ani_sticker_type: face.aniStickerType,
ani_sticker_pack_id: face.aniStickerPackId,
ani_sticker_id: face.aniStickerId,
url: face.url,
emoji_name_alias: face.emojiNameAlias,
ani_sticker_width: face.aniStickerWidth,
ani_sticker_height: face.aniStickerHeight,
is_super: isSuperFaceEntry(face),
};
}
const refreshField = () => f.bool().default(false).describe('是否强制从 QQ 刷新目录');
@@ -25,113 +25,127 @@ const faceIdField = () => f.faceId().describe('QQ 系统表情编号');
const nullableInteger = { type: ['integer', 'null'] };
const nullableString = { type: ['string', 'null'] };
const faceSchema = {
type: 'object',
properties: {
q_sid: { type: 'string', description: 'QQ 表情目录标识(部分 emoji 为 Unicode 表情字符串)' },
q_des: { type: 'string', description: '表情描述' },
em_code: { type: 'string' },
q_cid: nullableInteger,
ani_sticker_type: nullableInteger,
ani_sticker_pack_id: nullableInteger,
ani_sticker_id: nullableInteger,
url: nullableString,
emoji_name_alias: { type: 'array', items: { type: 'string' } },
ani_sticker_width: nullableInteger,
ani_sticker_height: nullableInteger,
is_super: { type: 'boolean', description: '是否使用超级表情格式' },
},
required: [
'q_sid', 'q_des', 'em_code', 'q_cid', 'ani_sticker_type',
'ani_sticker_pack_id', 'ani_sticker_id', 'url', 'emoji_name_alias',
'ani_sticker_width', 'ani_sticker_height', 'is_super',
],
type: 'object',
properties: {
q_sid: {
type: 'string',
description: 'QQ 表情目录标识(部分 emoji 为 Unicode 表情字符串)',
},
q_des: { type: 'string', description: '表情描述' },
em_code: { type: 'string' },
q_cid: nullableInteger,
ani_sticker_type: nullableInteger,
ani_sticker_pack_id: nullableInteger,
ani_sticker_id: nullableInteger,
url: nullableString,
emoji_name_alias: { type: 'array', items: { type: 'string' } },
ani_sticker_width: nullableInteger,
ani_sticker_height: nullableInteger,
is_super: { type: 'boolean', description: '是否使用超级表情格式' },
},
required: [
'q_sid',
'q_des',
'em_code',
'q_cid',
'ani_sticker_type',
'ani_sticker_pack_id',
'ani_sticker_id',
'url',
'emoji_name_alias',
'ani_sticker_width',
'ani_sticker_height',
'is_super',
],
};
export const actions = [
defineAction({
name: 'fetch_sys_faces',
summary: '获取 QQ 系统表情目录',
readOnly: true,
returns: '按分组返回完整的 QQ 系统表情映射。',
returnsSchema: {
type: 'object',
properties: {
packs: {
type: 'array',
items: {
defineAction({
name: 'fetch_sys_faces',
summary: '获取 QQ 系统表情目录',
readOnly: true,
returns: '按分组返回完整的 QQ 系统表情映射。',
returnsSchema: {
type: 'object',
properties: {
pack_name: { type: 'string' },
emojis: { type: 'array', items: faceSchema },
packs: {
type: 'array',
items: {
type: 'object',
properties: {
pack_name: { type: 'string' },
emojis: { type: 'array', items: faceSchema },
},
required: ['pack_name', 'emojis'],
},
},
},
required: ['pack_name', 'emojis'],
},
required: ['packs'],
},
params: { refresh: refreshField() },
run: async (params, ctx) => {
const packs = await ctx.bridge.apis.systemFace.fetchCatalog(params.refresh);
return okResponse({
packs: packs.map((pack) => ({
pack_name: pack.packName,
emojis: pack.emojis.map(faceEntry),
})),
});
},
},
required: ['packs'],
},
params: { refresh: refreshField() },
run: async (params, ctx) => {
const packs = await ctx.bridge.apis.systemFace.fetchCatalog(params.refresh);
return okResponse({
packs: packs.map((pack) => ({
pack_name: pack.packName,
emojis: pack.emojis.map(faceEntry),
})),
});
},
}),
defineAction({
name: 'fetch_face_entity',
summary: '按编号查询 QQ 系统表情',
readOnly: true,
returns: '表情详情;编号不存在时返回 null。',
returnsSchema: { anyOf: [faceSchema, { type: 'null' }] },
params: {
face_id: faceIdField(),
refresh: refreshField(),
},
run: async (params, ctx) => {
const face = await ctx.bridge.apis.systemFace.fetchFace(params.face_id, params.refresh);
return okResponse(face ? faceEntry(face) : null);
},
}),
defineAction({
name: 'search_sys_faces',
summary: '搜索 QQ 系统表情',
readOnly: true,
returns: '匹配编号、名称、别名或分组名的表情列表。',
returnsSchema: {
type: 'object',
properties: { faces: { type: 'array', items: faceSchema } },
required: ['faces'],
},
params: {
query: f.string({ allowEmpty: false }).describe('编号、名称、别名或分组名'),
},
run: async (params, ctx) => okResponse({
faces: (await ctx.bridge.apis.systemFace.search(params.query)).map(faceEntry),
}),
}),
defineAction({
name: 'fetch_super_face_id',
summary: '判断 QQ 系统表情是否使用超级表情格式',
readOnly: true,
returns: '是否使用超级表情格式。',
returnsSchema: {
type: 'object',
properties: { is_super: { type: 'boolean' } },
required: ['is_super'],
},
params: {
face_id: faceIdField(),
refresh: refreshField(),
},
run: async (params, ctx) => okResponse({
is_super: await ctx.bridge.apis.systemFace.isSuper(params.face_id, params.refresh),
defineAction({
name: 'fetch_face_entity',
summary: '按编号查询 QQ 系统表情',
readOnly: true,
returns: '表情详情;编号不存在时返回 null。',
returnsSchema: { anyOf: [faceSchema, { type: 'null' }] },
params: {
face_id: faceIdField(),
refresh: refreshField(),
},
run: async (params, ctx) => {
const face = await ctx.bridge.apis.systemFace.fetchFace(params.face_id, params.refresh);
return okResponse(face ? faceEntry(face) : null);
},
}),
defineAction({
name: 'search_sys_faces',
summary: '搜索 QQ 系统表情',
readOnly: true,
returns: '匹配编号、名称、别名或分组名的表情列表。',
returnsSchema: {
type: 'object',
properties: { faces: { type: 'array', items: faceSchema } },
required: ['faces'],
},
params: {
query: f.string({ allowEmpty: false }).describe('编号、名称、别名或分组名'),
},
run: async (params, ctx) =>
okResponse({
faces: (await ctx.bridge.apis.systemFace.search(params.query)).map(faceEntry),
}),
}),
defineAction({
name: 'fetch_super_face_id',
summary: '判断 QQ 系统表情是否使用超级表情格式',
readOnly: true,
returns: '是否使用超级表情格式。',
returnsSchema: {
type: 'object',
properties: { is_super: { type: 'boolean' } },
required: ['is_super'],
},
params: {
face_id: faceIdField(),
refresh: refreshField(),
},
run: async (params, ctx) =>
okResponse({
is_super: await ctx.bridge.apis.systemFace.isSuper(params.face_id, params.refresh),
}),
}),
}),
];