Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c03b162f5 | ||
|
|
4079214dc5 | ||
|
|
109d0c1dff | ||
|
|
96de2314b0 | ||
|
|
eecb02140f | ||
|
|
3ac54c181b | ||
|
|
0c4c371eee | ||
|
|
af07479351 | ||
|
|
c59a47a5a7 | ||
|
|
49ea8d5624 | ||
|
|
fe7a1f053a | ||
|
|
0fcd0e80e0 | ||
|
|
624ecf5b9a | ||
|
|
63a349d119 | ||
|
|
56549cd0f2 | ||
|
|
ead24423b5 | ||
|
|
f0e045df35 | ||
|
|
33ee94ab0f | ||
|
|
cbec362ed1 | ||
|
|
766ca6e071 | ||
|
|
7c2514be6c | ||
|
|
738e272d2c | ||
|
|
f7edbfd8d9 | ||
|
|
74dc33fee6 | ||
|
|
c95dd3d030 | ||
|
|
68e6a9bff9 | ||
|
|
5c18a62530 | ||
|
|
a82a5d5203 |
No files matched your search
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(tasklist)",
|
||||
"Bash(sort -rk5)",
|
||||
"Bash(powershell \"Get-Process | Sort-Object CPU -Descending | Select-Object -First 15 Name,CPU,Id,WorkingSet | Format-Table -AutoSize\")",
|
||||
"Bash(powershell *)",
|
||||
"Bash(where ssh *)",
|
||||
"Bash(where plink *)",
|
||||
"Bash(where sshpass *)",
|
||||
"Bash(echo \"exit=$?\")",
|
||||
"Bash(python -c \"import paramiko; print\\('paramiko OK'\\)\")",
|
||||
"Bash(pnpm --filter napcat-common run typecheck)",
|
||||
"Bash(pnpm --filter napcat-core run typecheck)",
|
||||
"Bash(pnpm --filter napcat-onebot run typecheck)",
|
||||
"Bash(git *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
- **控制数量**:最终保持 5-15 条更新要点
|
||||
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
|
||||
|
||||
## 输出模板 - 必须严格遵守以下格式
|
||||
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
|
||||
|
||||
```
|
||||
# {VERSION}
|
||||
|
||||
@@ -9,8 +9,8 @@ on:
|
||||
type: string
|
||||
|
||||
env:
|
||||
QQ_URL_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage'
|
||||
QQ_URL_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage'
|
||||
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_x86_64.AppImage'
|
||||
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_arm64.AppImage'
|
||||
|
||||
jobs:
|
||||
get-version:
|
||||
|
||||
@@ -12,7 +12,7 @@ permissions: write-all
|
||||
|
||||
env:
|
||||
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
|
||||
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
|
||||
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
|
||||
RELEASE_NAME: "NapCat"
|
||||
|
||||
jobs:
|
||||
@@ -90,7 +90,7 @@ jobs:
|
||||
mkdir -p /tmp/napcat-downloads
|
||||
cd /tmp/napcat-downloads
|
||||
|
||||
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
|
||||
NT_URL="https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/a33ab721/QQ9.9.32.50969_x64.exe"
|
||||
echo "Downloading QQ installer..."
|
||||
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
|
||||
|
||||
|
||||
@@ -21,3 +21,4 @@ tests/run/
|
||||
guild1.db-wal
|
||||
guild1.db-shm
|
||||
packages/napcat-develop/config/.env
|
||||
.claude
|
||||
@@ -12,11 +12,17 @@ import {
|
||||
ShutUpGroupMember,
|
||||
Peer,
|
||||
ChatType,
|
||||
GroupManagementSettings,
|
||||
} from '@/napcat-core/index';
|
||||
import { isNumeric, solveAsyncProblem } from 'napcat-common/src/helper';
|
||||
import { LimitedHashTable } from 'napcat-common/src/message-unique';
|
||||
import { CancelableTask, TaskExecutor } from 'napcat-common/src/cancel-task';
|
||||
import { createGroupDetailInfoV2Param, createGroupExtFilter, createGroupExtInfo } from '../data';
|
||||
import {
|
||||
createGroupDetailInfoV2Param,
|
||||
createGroupExtFilter,
|
||||
createGroupExtInfo,
|
||||
createGroupManagementRequests,
|
||||
} from '../data';
|
||||
import { NTEventWrapper } from '../helper/event';
|
||||
|
||||
export class NTQQGroupApi {
|
||||
@@ -168,6 +174,54 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getGroupService().modifyGroupDetailInfoV2(param, 0);
|
||||
}
|
||||
|
||||
async setGroupMemberInvitePolicy (
|
||||
groupCode: string,
|
||||
policy: NonNullable<GroupManagementSettings['memberInvite']>
|
||||
) {
|
||||
return this.modifyGroupManagementSettings(groupCode, { memberInvite: policy });
|
||||
}
|
||||
|
||||
async setGroupMemberPermissions (
|
||||
groupCode: string,
|
||||
permissions: Pick<
|
||||
GroupManagementSettings,
|
||||
'allowMemberUploadAlbum' | 'allowMemberTemporarySession' | 'allowMemberCreateGroup'
|
||||
>
|
||||
) {
|
||||
return this.modifyGroupManagementSettings(groupCode, permissions);
|
||||
}
|
||||
|
||||
async setGroupNewMemberHistoryVisibility (groupCode: string, visible: boolean) {
|
||||
return this.modifyGroupManagementSettings(groupCode, { newMembersSeeRecentHistory: visible });
|
||||
}
|
||||
|
||||
private async modifyGroupManagementSettings (groupCode: string, settings: GroupManagementSettings) {
|
||||
const results: Array<{ setting: string, result: GeneralCallResult; }> = [];
|
||||
const changesKnownFlags = settings.memberInvite !== undefined ||
|
||||
settings.allowMemberUploadAlbum !== undefined ||
|
||||
settings.allowMemberTemporarySession !== undefined ||
|
||||
settings.allowMemberCreateGroup !== undefined ||
|
||||
settings.newMembersSeeRecentHistory !== undefined;
|
||||
const currentDetail = changesKnownFlags ? await this.fetchGroupDetail(groupCode) : undefined;
|
||||
|
||||
for (const request of createGroupManagementRequests(
|
||||
groupCode,
|
||||
settings,
|
||||
currentDetail?.privilegeFlag,
|
||||
currentDetail?.groupFlagExt4
|
||||
)) {
|
||||
results.push({
|
||||
setting: request.setting,
|
||||
result: await this.context.session.getGroupService().modifyGroupDetailInfoV2(
|
||||
request.param,
|
||||
request.operationType
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
async setGroupSearch (groupCode: string, option: {
|
||||
noCodeFingerOpenFlag?: number;
|
||||
noFingerOpenFlag?: number;
|
||||
@@ -297,6 +351,15 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getGroupService().getGroupRecommendContactArkJson(groupCode);
|
||||
}
|
||||
|
||||
async getJoinGroupLink (groupCode: string, needShortUrl = true, srcId = 73, additionalParam = '') {
|
||||
return this.context.session.getGroupService().getJoinGroupLink({
|
||||
groupCode,
|
||||
srcId,
|
||||
needShortUrl,
|
||||
additionalParam,
|
||||
});
|
||||
}
|
||||
|
||||
async creatGroupFileFolder (groupCode: string, folderName: string) {
|
||||
return this.context.session.getRichMediaService().createGroupFolder(groupCode, folderName);
|
||||
}
|
||||
@@ -430,6 +493,24 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getRichMediaService().batchGetGroupFileCount(groupCodes);
|
||||
}
|
||||
|
||||
// getGroupFileList also carries the group's used/total space in its call
|
||||
// result's `groupSpaceResult`; a single-item fetch is enough to read it.
|
||||
async getGroupFileSpace (groupCode: string) {
|
||||
const [result] = await this.core.eventWrapper.callNormalEventV2(
|
||||
'NodeIKernelRichMediaService/getGroupFileList',
|
||||
'NodeIKernelMsgListener/onGroupFileInfoUpdate',
|
||||
[
|
||||
groupCode,
|
||||
{ sortType: 1, fileCount: 1, startIndex: 0, sortOrder: 1, showOnlinedocFolder: 0 },
|
||||
],
|
||||
() => true,
|
||||
() => true,
|
||||
1,
|
||||
5000
|
||||
);
|
||||
return result?.groupSpaceResult;
|
||||
}
|
||||
|
||||
async getArkJsonGroupShare (groupCode: string) {
|
||||
const ret = await this.core.eventWrapper.callNoListenerEvent(
|
||||
'NodeIKernelGroupService/getGroupRecommendContactArkJson',
|
||||
|
||||
@@ -36,7 +36,7 @@ export class NTQQPacketApi {
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.logError(err);
|
||||
this.errStack.push(err);
|
||||
this.pushError(err);
|
||||
return false;
|
||||
})) && this.pkt?.available;
|
||||
}
|
||||
@@ -46,7 +46,15 @@ export class NTQQPacketApi {
|
||||
}
|
||||
|
||||
get clientLogStack () {
|
||||
return this.pkt?.clientLogStack + '\n' + this.errStack.join('\n');
|
||||
return [this.pkt?.clientLogStack, ...this.errStack].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
private pushError (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
this.errStack.push(error.stack || error.message);
|
||||
return;
|
||||
}
|
||||
this.errStack.push(String(error));
|
||||
}
|
||||
|
||||
async InitSendPacket (qqVer: string) {
|
||||
@@ -67,10 +75,17 @@ export class NTQQPacketApi {
|
||||
}
|
||||
this.pkt = new PacketClientSession(this.core);
|
||||
await this.pkt.init(process.pid, table.recv, table.send);
|
||||
if (!this.pkt.available) {
|
||||
const err = '[Core] [Packet] NativePacketClient 初始化失败,PacketBackend 发包能力不可用!';
|
||||
this.logger.logError(err);
|
||||
this.errStack.push(err);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this.pkt.operation.FetchRkey(3000);
|
||||
} catch (error) {
|
||||
this.logger.logError('测试Packet状态异常', error);
|
||||
this.pushError(error);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -13,6 +13,17 @@ import { createHash } from 'node:crypto';
|
||||
import { basename } from 'node:path';
|
||||
import { qunAlbumControl } from '../data/webapi';
|
||||
import { createAlbumCommentRequest, createAlbumFeedPublish, createAlbumMediaFeed } from '../data/album';
|
||||
import {
|
||||
buildQzoneDeleteBody,
|
||||
buildQzonePublishBody,
|
||||
buildQzoneUploadImageBody,
|
||||
parseQzoneDeleteResponse,
|
||||
parseQzonePublishResponse,
|
||||
parseQzoneUploadImageResponseText,
|
||||
toQzoneRichval,
|
||||
QzoneDeleteResponse,
|
||||
QzonePublishResponse,
|
||||
} from '../data/qzone';
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec: number;
|
||||
em: string;
|
||||
@@ -540,6 +551,78 @@ export class NTQQWebApi {
|
||||
);
|
||||
}
|
||||
|
||||
private async getQzoneAuth () {
|
||||
const skey = await this.core.apis.UserApi.getSKey() || '';
|
||||
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
const g_tk = this.getBknFromSKey(skey);
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
return { skey, pskey, uin, g_tk, cookie };
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片到 QQ 空间相册, 返回可用于发说说的 richval 字符串
|
||||
* @param base64 图片Base64编码内容(不带data:前缀)
|
||||
*/
|
||||
async uploadImageToQzone (base64: string): Promise<string> {
|
||||
const { skey, pskey, uin, g_tk, cookie } = await this.getQzoneAuth();
|
||||
const body = buildQzoneUploadImageBody({ uin, skey, pskey, g_tk, base64 });
|
||||
const api = `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
|
||||
const resultText = await RequestUtil.HttpGetText(api, 'POST', body, {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
const parsed = parseQzoneUploadImageResponseText(resultText);
|
||||
if (parsed.code !== undefined && parsed.code !== 0) {
|
||||
throw new Error(parsed.msg || `QQ空间图片上传失败, code=${parsed.code}`);
|
||||
}
|
||||
if (!parsed.data) {
|
||||
throw new Error('QQ空间图片上传失败, 响应缺少data字段');
|
||||
}
|
||||
return toQzoneRichval(parsed.data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发表QQ空间说说
|
||||
* @param content 说说正文
|
||||
* @param richvals 每张图片对应的richval数组, 为空表示纯文字说说
|
||||
* @param ugcRight 查看权限 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见
|
||||
* @param targetUins 权限作用QQ号数组, ugcRight为16/128时使用
|
||||
*/
|
||||
async publishQzoneMsg (content: string, richvals: string[], ugcRight: number, targetUins?: number[]) {
|
||||
const { uin, g_tk, cookie } = await this.getQzoneAuth();
|
||||
const richval = richvals.length > 0 ? richvals.join('\t') : undefined;
|
||||
const allowUins = targetUins && targetUins.length > 0 ? targetUins.join('|') : undefined;
|
||||
const body = buildQzonePublishBody({
|
||||
hostuin: uin,
|
||||
content,
|
||||
richval,
|
||||
ugcRight,
|
||||
allowUins,
|
||||
});
|
||||
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${g_tk}`;
|
||||
const result = await RequestUtil.HttpGetJson<QzonePublishResponse>(api, 'POST', body, {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
}, true, false);
|
||||
return parseQzonePublishResponse(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除QQ空间说说
|
||||
* @param tid 说说Tid, 来自 publishQzoneMsg 的返回值
|
||||
*/
|
||||
async deleteQzoneMsg (tid: string) {
|
||||
const { uin, g_tk, cookie } = await this.getQzoneAuth();
|
||||
const body = buildQzoneDeleteBody({ hostuin: uin, tid });
|
||||
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6?g_tk=${g_tk}`;
|
||||
const result = await RequestUtil.HttpGetJson<QzoneDeleteResponse>(api, 'POST', body, {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
}, true, false);
|
||||
return parseQzoneDeleteResponse(result);
|
||||
}
|
||||
|
||||
async getDaySignedList (groupCode: string) {
|
||||
const pSkey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const selfUin = this.core.selfInfo.uin;
|
||||
|
||||
@@ -1,4 +1,142 @@
|
||||
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter } from '../types';
|
||||
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter, GroupManagementSettings } from '../types';
|
||||
|
||||
const MEMBER_INVITE_PRIVILEGE_MASK = 0x06100000;
|
||||
const MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK = 0x1;
|
||||
const MEMBER_CREATE_GROUP_FLAG = 0x8000;
|
||||
const MEMBER_TEMPORARY_SESSION_FLAG = 0x10000;
|
||||
const NEW_MEMBER_RECENT_HISTORY_FLAG = 0x4;
|
||||
|
||||
function mergeMaskedFlag (currentFlag: number, requestedFlag: number, maskValue: number): number {
|
||||
const mask = BigInt(maskValue);
|
||||
return Number((BigInt(currentFlag) & ~mask) | (BigInt(requestedFlag) & mask));
|
||||
}
|
||||
|
||||
export function applyGroupManagementSettings (
|
||||
param: GroupDetailInfoV2Param,
|
||||
settings: GroupManagementSettings
|
||||
): boolean {
|
||||
let changed = false;
|
||||
|
||||
if (settings.memberInvite !== undefined) {
|
||||
const privilegeByPolicy = {
|
||||
disabled: 0x04000000,
|
||||
require_approval: 0,
|
||||
no_approval: 0x00100000,
|
||||
no_approval_under_100: 0x02000000,
|
||||
} satisfies Record<NonNullable<GroupManagementSettings['memberInvite']>, number>;
|
||||
|
||||
param.filter.allowMemberInvite = 1;
|
||||
param.modifyInfo.allowMemberInvite = settings.memberInvite === 'disabled' ? 0 : 1;
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_INVITE_PRIVILEGE_MASK;
|
||||
param.modifyInfo.appPrivilegeFlag |= privilegeByPolicy[settings.memberInvite];
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.allowMemberUploadAlbum !== undefined) {
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
|
||||
if (!settings.allowMemberUploadAlbum) param.modifyInfo.appPrivilegeFlag |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.allowMemberTemporarySession !== undefined) {
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_TEMPORARY_SESSION_FLAG;
|
||||
if (!settings.allowMemberTemporarySession) param.modifyInfo.appPrivilegeFlag |= MEMBER_TEMPORARY_SESSION_FLAG;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.allowMemberCreateGroup !== undefined) {
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_CREATE_GROUP_FLAG;
|
||||
if (!settings.allowMemberCreateGroup) param.modifyInfo.appPrivilegeFlag |= MEMBER_CREATE_GROUP_FLAG;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.newMembersSeeRecentHistory !== undefined) {
|
||||
param.filter.groupFlagExt4 = 1;
|
||||
param.filter.groupFlagExt4Mask = 1;
|
||||
param.modifyInfo.groupFlagExt4Mask |= NEW_MEMBER_RECENT_HISTORY_FLAG;
|
||||
if (settings.newMembersSeeRecentHistory) param.modifyInfo.groupFlagExt4 |= NEW_MEMBER_RECENT_HISTORY_FLAG;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
export function createGroupManagementRequests (
|
||||
groupCode: string,
|
||||
settings: GroupManagementSettings,
|
||||
initialAppPrivilegeFlag = 0,
|
||||
initialGroupFlagExt4 = 0
|
||||
) {
|
||||
const requests: Array<{ setting: string, param: GroupDetailInfoV2Param, operationType: number; }> = [];
|
||||
const requestSettings: Array<{
|
||||
setting: string,
|
||||
value: GroupManagementSettings,
|
||||
operationType: number;
|
||||
}> = [
|
||||
{ setting: 'member_invite', value: { memberInvite: settings.memberInvite }, operationType: 0 },
|
||||
{
|
||||
setting: 'new_members_see_recent_history',
|
||||
value: { newMembersSeeRecentHistory: settings.newMembersSeeRecentHistory },
|
||||
operationType: 0,
|
||||
},
|
||||
{
|
||||
setting: 'allow_member_upload_album',
|
||||
value: { allowMemberUploadAlbum: settings.allowMemberUploadAlbum },
|
||||
operationType: 8,
|
||||
},
|
||||
{
|
||||
setting: 'allow_member_temporary_session',
|
||||
value: { allowMemberTemporarySession: settings.allowMemberTemporarySession },
|
||||
operationType: 8,
|
||||
},
|
||||
{
|
||||
setting: 'allow_member_create_group',
|
||||
value: { allowMemberCreateGroup: settings.allowMemberCreateGroup },
|
||||
operationType: 8,
|
||||
},
|
||||
];
|
||||
|
||||
let currentAppPrivilegeFlag = initialAppPrivilegeFlag;
|
||||
let currentGroupFlagExt4 = initialGroupFlagExt4;
|
||||
for (const requestSetting of requestSettings) {
|
||||
const param = createGroupDetailInfoV2Param(groupCode);
|
||||
if (applyGroupManagementSettings(param, requestSetting.value)) {
|
||||
if (param.filter.appPrivilegeFlag) {
|
||||
const nextAppPrivilegeFlag = mergeMaskedFlag(
|
||||
currentAppPrivilegeFlag,
|
||||
param.modifyInfo.appPrivilegeFlag,
|
||||
param.modifyInfo.appPrivilegeMask
|
||||
);
|
||||
if (requestSetting.operationType === 8 && nextAppPrivilegeFlag === currentAppPrivilegeFlag) continue;
|
||||
currentAppPrivilegeFlag = nextAppPrivilegeFlag;
|
||||
// Linux NTQQ's wrapper builds this field from the current complete privilege value.
|
||||
// Supplying only the targeted bit makes zero-valued clears get acknowledged but ignored.
|
||||
param.modifyInfo.appPrivilegeFlag = currentAppPrivilegeFlag;
|
||||
}
|
||||
if (param.filter.groupFlagExt4) {
|
||||
const nextGroupFlagExt4 = mergeMaskedFlag(
|
||||
currentGroupFlagExt4,
|
||||
param.modifyInfo.groupFlagExt4,
|
||||
param.modifyInfo.groupFlagExt4Mask
|
||||
);
|
||||
if (nextGroupFlagExt4 === currentGroupFlagExt4) continue;
|
||||
currentGroupFlagExt4 = nextGroupFlagExt4;
|
||||
param.modifyInfo.groupFlagExt4 = currentGroupFlagExt4;
|
||||
}
|
||||
requests.push({ setting: requestSetting.setting, param, operationType: requestSetting.operationType });
|
||||
}
|
||||
}
|
||||
|
||||
return requests;
|
||||
}
|
||||
|
||||
export function createGroupDetailInfoV2Param (group_code: string): GroupDetailInfoV2Param {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* QQ空间(Qzone)发说说/上传图片相关的纯数据构造与解析函数
|
||||
* 不发起任何网络请求,方便单独测试
|
||||
*/
|
||||
|
||||
export interface QzoneUploadImageParams {
|
||||
uin: string;
|
||||
skey: string;
|
||||
pskey: string;
|
||||
g_tk: string;
|
||||
base64: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造上传图片到 QQ 空间的表单请求体 (application/x-www-form-urlencoded)
|
||||
* 对齐 https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image
|
||||
*/
|
||||
export function buildQzoneUploadImageBody (params: QzoneUploadImageParams): string {
|
||||
const { uin, skey, pskey, g_tk, base64 } = params;
|
||||
const backUrls = `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
|
||||
const query = new URLSearchParams({
|
||||
filename: 'filename',
|
||||
uin,
|
||||
skey,
|
||||
zzpaneluin: uin,
|
||||
p_uin: uin,
|
||||
p_skey: pskey,
|
||||
uploadtype: '1',
|
||||
albumtype: '7',
|
||||
exttype: '0',
|
||||
refer: 'shuoshuo',
|
||||
output_type: 'jsonhtml',
|
||||
charset: 'utf-8',
|
||||
output_charset: 'utf-8',
|
||||
upload_hd: '1',
|
||||
hd_width: '2048',
|
||||
hd_height: '10000',
|
||||
hd_quality: '96',
|
||||
backUrls,
|
||||
base64: '1',
|
||||
jsonhtml_callback: 'callback',
|
||||
picfile: base64,
|
||||
qzreferrer: `https://user.qzone.qq.com/${uin}/main`,
|
||||
});
|
||||
return query.toString();
|
||||
}
|
||||
|
||||
export interface QzoneUploadImageData {
|
||||
albumid: string;
|
||||
lloc: string;
|
||||
type: string;
|
||||
height: string;
|
||||
width: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface QzoneUploadImageRawResponse {
|
||||
code?: number;
|
||||
msg?: string;
|
||||
data?: QzoneUploadImageData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析上传图片接口返回的 `frameElement.callback({...});</script>` 包裹响应
|
||||
*/
|
||||
export function parseQzoneUploadImageResponseText (raw: string): QzoneUploadImageRawResponse {
|
||||
const startTag = 'frameElement.callback';
|
||||
const endTag = '</script>';
|
||||
const startIdx = raw.indexOf(startTag);
|
||||
const endIdx = raw.indexOf(endTag);
|
||||
if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {
|
||||
throw new Error('QQ空间图片上传响应格式异常');
|
||||
}
|
||||
const segment = raw.slice(startIdx + startTag.length, endIdx);
|
||||
const jsonStart = segment.indexOf('(');
|
||||
const jsonEnd = segment.lastIndexOf(')');
|
||||
if (jsonStart === -1 || jsonEnd === -1 || jsonEnd <= jsonStart) {
|
||||
throw new Error('QQ空间图片上传响应解析失败');
|
||||
}
|
||||
const jsonText = segment.slice(jsonStart + 1, jsonEnd);
|
||||
try {
|
||||
return JSON.parse(jsonText) as QzoneUploadImageRawResponse;
|
||||
} catch {
|
||||
throw new Error('QQ空间图片上传响应JSON解析失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 依据上传图片返回数据拼接 richval 字段
|
||||
* 格式: ,albumid,lloc,sloc,type,height,width,,height,width (sloc 与 lloc 一致)
|
||||
*/
|
||||
export function toQzoneRichval (data: QzoneUploadImageData): string {
|
||||
const { albumid, lloc, type, height, width } = data;
|
||||
return `,${albumid},${lloc},${lloc},${type},${height},${width},,${height},${width}`;
|
||||
}
|
||||
|
||||
export interface QzonePublishParams {
|
||||
hostuin: string;
|
||||
content: string;
|
||||
/** 多张图片使用 \t 拼接后的 richval,无图时不传 */
|
||||
richval?: string;
|
||||
ugcRight: number;
|
||||
/** ugc_right 为 16/128 时必填,多个QQ号使用 | 拼接 */
|
||||
allowUins?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造发表说说的表单请求体 (application/x-www-form-urlencoded)
|
||||
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6
|
||||
*/
|
||||
export function buildQzonePublishBody (params: QzonePublishParams): string {
|
||||
const { hostuin, content, richval, ugcRight, allowUins } = params;
|
||||
const fields: Record<string, string> = {
|
||||
syn_tweet_verson: '1',
|
||||
paramstr: '1',
|
||||
con: content,
|
||||
feedversion: '1',
|
||||
ver: '1',
|
||||
ugc_right: String(ugcRight),
|
||||
to_sign: '0',
|
||||
hostuin,
|
||||
code_version: '1',
|
||||
format: 'json',
|
||||
qzreferrer: `https://user.qzone.qq.com/${hostuin}/main`,
|
||||
};
|
||||
if (richval) {
|
||||
fields['richtype'] = '1';
|
||||
fields['richval'] = richval;
|
||||
}
|
||||
if (allowUins) {
|
||||
fields['allow_uins'] = allowUins;
|
||||
fields['who'] = '1';
|
||||
}
|
||||
return new URLSearchParams(fields).toString();
|
||||
}
|
||||
|
||||
export interface QzonePublishResponse {
|
||||
subcode?: number;
|
||||
code?: number;
|
||||
tid?: string;
|
||||
t1_tid?: string;
|
||||
message?: string;
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析发表说说接口返回的 JSON, 提取 tid
|
||||
*/
|
||||
export function parseQzonePublishResponse (json: QzonePublishResponse): { tid: string; } {
|
||||
const subcode = json.subcode ?? json.code;
|
||||
if (subcode !== undefined && subcode !== 0) {
|
||||
throw new Error(json.message || json.msg || `QQ空间发说说失败, subcode=${subcode}`);
|
||||
}
|
||||
const tid = json.t1_tid || json.tid;
|
||||
if (!tid) {
|
||||
throw new Error('QQ空间发说说失败, 未返回tid');
|
||||
}
|
||||
return { tid };
|
||||
}
|
||||
|
||||
export interface QzoneDeleteParams {
|
||||
hostuin: string;
|
||||
tid: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造删除说说的表单请求体 (application/x-www-form-urlencoded)
|
||||
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6
|
||||
*/
|
||||
export function buildQzoneDeleteBody (params: QzoneDeleteParams): string {
|
||||
const { hostuin, tid } = params;
|
||||
const fields: Record<string, string> = {
|
||||
hostuin,
|
||||
tid,
|
||||
t1_source: '1',
|
||||
code_version: '1',
|
||||
format: 'json',
|
||||
qzreferrer: `https://user.qzone.qq.com/${hostuin}`,
|
||||
};
|
||||
return new URLSearchParams(fields).toString();
|
||||
}
|
||||
|
||||
export interface QzoneDeleteResponse {
|
||||
subcode?: number;
|
||||
code?: number;
|
||||
message?: string;
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析删除说说接口返回的 JSON
|
||||
*/
|
||||
export function parseQzoneDeleteResponse (json: QzoneDeleteResponse): { success: true; } {
|
||||
const subcode = json.subcode ?? json.code;
|
||||
if (subcode !== undefined && subcode !== 0) {
|
||||
throw new Error(json.message || json.msg || `QQ空间删说说失败, subcode=${subcode}`);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
+20
@@ -590,5 +590,25 @@
|
||||
"3.2.29-49738": {
|
||||
"appid": 537355867,
|
||||
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
|
||||
},
|
||||
"9.9.32-50828": {
|
||||
"appid": 537358739,
|
||||
"qua": "V1_WIN_NQ_9.9.32_50828_GW_B"
|
||||
},
|
||||
"3.2.30-50828": {
|
||||
"appid": 537358775,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
|
||||
},
|
||||
"9.9.32-50969": {
|
||||
"appid": 537376308,
|
||||
"qua": "V1_WIN_NQ_9.9.32_50969_GW_B"
|
||||
},
|
||||
"3.2.30-50969": {
|
||||
"appid": 537376344,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
|
||||
},
|
||||
"9.9.32-55230": {
|
||||
"appid": 537379411,
|
||||
"qua": "V1_WIN_NQ_9.9.32_55230_GW_B"
|
||||
}
|
||||
}
|
||||
+165
@@ -2593,6 +2593,171 @@
|
||||
"AniStickerType": 1,
|
||||
"AniStickerPackId": "1",
|
||||
"AniStickerId": "59"
|
||||
},
|
||||
{
|
||||
"QSid": "450",
|
||||
"QDes": "/撇嘴",
|
||||
"EMCode": "10450"
|
||||
},
|
||||
{
|
||||
"QSid": "451",
|
||||
"QDes": "/色",
|
||||
"EMCode": "10451"
|
||||
},
|
||||
{
|
||||
"QSid": "452",
|
||||
"QDes": "/微笑",
|
||||
"EMCode": "10452"
|
||||
},
|
||||
{
|
||||
"QSid": "453",
|
||||
"QDes": "/发呆",
|
||||
"EMCode": "10453"
|
||||
},
|
||||
{
|
||||
"QSid": "454",
|
||||
"QDes": "/得意",
|
||||
"EMCode": "10454"
|
||||
},
|
||||
{
|
||||
"QSid": "455",
|
||||
"QDes": "/害羞",
|
||||
"EMCode": "10455"
|
||||
},
|
||||
{
|
||||
"QSid": "456",
|
||||
"QDes": "/闭嘴",
|
||||
"EMCode": "10456"
|
||||
},
|
||||
{
|
||||
"QSid": "457",
|
||||
"QDes": "/睡",
|
||||
"EMCode": "10457"
|
||||
},
|
||||
{
|
||||
"QSid": "458",
|
||||
"QDes": "/我吗",
|
||||
"EMCode": "10458"
|
||||
},
|
||||
{
|
||||
"QSid": "459",
|
||||
"QDes": "/优雅",
|
||||
"EMCode": "10459"
|
||||
},
|
||||
{
|
||||
"QSid": "460",
|
||||
"QDes": "/硬撑",
|
||||
"EMCode": "10460"
|
||||
},
|
||||
{
|
||||
"QSid": "461",
|
||||
"QDes": "/宕机",
|
||||
"EMCode": "10461"
|
||||
},
|
||||
{
|
||||
"QSid": "462",
|
||||
"QDes": "/无语",
|
||||
"EMCode": "10462"
|
||||
},
|
||||
{
|
||||
"QSid": "463",
|
||||
"QDes": "/新年快乐",
|
||||
"EMCode": "10463"
|
||||
},
|
||||
{
|
||||
"QSid": "464",
|
||||
"QDes": "/马上到",
|
||||
"EMCode": "10464"
|
||||
},
|
||||
{
|
||||
"QSid": "465",
|
||||
"QDes": "/拆红包",
|
||||
"EMCode": "10465"
|
||||
},
|
||||
{
|
||||
"QSid": "466",
|
||||
"QDes": "/羞羞哒",
|
||||
"EMCode": "10466"
|
||||
},
|
||||
{
|
||||
"QSid": "467",
|
||||
"QDes": "/摇花手",
|
||||
"EMCode": "10467"
|
||||
},
|
||||
{
|
||||
"QSid": "468",
|
||||
"QDes": "/失眠",
|
||||
"EMCode": "10468"
|
||||
},
|
||||
{
|
||||
"QSid": "469",
|
||||
"QDes": "/坚毅",
|
||||
"EMCode": "10469"
|
||||
},
|
||||
{
|
||||
"QSid": "470",
|
||||
"QDes": "/马到成功",
|
||||
"EMCode": "10470"
|
||||
},
|
||||
{
|
||||
"QSid": "472",
|
||||
"QDes": "/心动",
|
||||
"EMCode": "10472"
|
||||
},
|
||||
{
|
||||
"QSid": "474",
|
||||
"QDes": "/给你一拳",
|
||||
"EMCode": "10474"
|
||||
},
|
||||
{
|
||||
"QSid": "475",
|
||||
"QDes": "/干饭",
|
||||
"EMCode": "10475"
|
||||
},
|
||||
{
|
||||
"QSid": "476",
|
||||
"QDes": "/不是吧",
|
||||
"EMCode": "10476"
|
||||
},
|
||||
{
|
||||
"QSid": "477",
|
||||
"QDes": "/你懂的",
|
||||
"EMCode": "10477"
|
||||
},
|
||||
{
|
||||
"QSid": "478",
|
||||
"QDes": "/对的对的",
|
||||
"EMCode": "10478"
|
||||
},
|
||||
{
|
||||
"QSid": "479",
|
||||
"QDes": "/不对不对",
|
||||
"EMCode": "10479"
|
||||
},
|
||||
{
|
||||
"QSid": "480",
|
||||
"QDes": "/散味儿",
|
||||
"EMCode": "10480"
|
||||
},
|
||||
{
|
||||
"QSid": "481",
|
||||
"QDes": "/学习",
|
||||
"EMCode": "10481"
|
||||
},
|
||||
{
|
||||
"QSid": "482",
|
||||
"QDes": "/热化了",
|
||||
"EMCode": "10482"
|
||||
},
|
||||
{
|
||||
"QSid": "483",
|
||||
"QDes": "/略",
|
||||
"EMCode": "10483"
|
||||
},
|
||||
{
|
||||
"QSid": "484",
|
||||
"QDes": "/比爱心",
|
||||
"EMCode": "10484"
|
||||
}
|
||||
],
|
||||
"emoji": [
|
||||
|
||||
+28
@@ -254,5 +254,33 @@
|
||||
"3.2.29-49738-arm64": {
|
||||
"send": "426AA04",
|
||||
"recv": "1596254"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "0B245CC",
|
||||
"recv": "2073D65"
|
||||
},
|
||||
"3.2.30-50828-x64": {
|
||||
"send": "6340530",
|
||||
"recv": "346DA50"
|
||||
},
|
||||
"3.2.30-50828-arm64": {
|
||||
"send": "4327764",
|
||||
"recv": "15e3184"
|
||||
},
|
||||
"9.9.32-50969-x64": {
|
||||
"send": "0B2E2AC",
|
||||
"recv": "209C709"
|
||||
},
|
||||
"3.2.30-50969-x64": {
|
||||
"send": "63F47B0",
|
||||
"recv": "34B9E30"
|
||||
},
|
||||
"3.2.30-50969-arm64": {
|
||||
"send": "43A4804",
|
||||
"recv": "1608CC8"
|
||||
},
|
||||
"9.9.32-55230-x64": {
|
||||
"send": "367FE18",
|
||||
"recv": "36835CC"
|
||||
}
|
||||
}
|
||||
+24
@@ -762,5 +762,29 @@
|
||||
"3.2.29-49738-arm64": {
|
||||
"send": "7342800",
|
||||
"recv": "73461B0"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "3155200",
|
||||
"recv": "3158788"
|
||||
},
|
||||
"9.9.32-50828-arm64": {
|
||||
"send": "4327764",
|
||||
"recv": "15E3184"
|
||||
},
|
||||
"3.2.30-50828-x64": {
|
||||
"send": "B5D0FC0",
|
||||
"recv": "B5D4A60"
|
||||
},
|
||||
"9.9.32-50969-x64": {
|
||||
"send": "31994E0",
|
||||
"recv": "319CA68"
|
||||
},
|
||||
"3.2.30-50969-x64": {
|
||||
"send": "B7394C0",
|
||||
"recv": "B73CF60"
|
||||
},
|
||||
"3.2.30-50969-arm64": {
|
||||
"send": "75BD1D0",
|
||||
"recv": "75C0B80"
|
||||
}
|
||||
}
|
||||
@@ -21,13 +21,13 @@ export interface VideoInfo {
|
||||
/** Video duration in seconds */
|
||||
duration: number;
|
||||
|
||||
/** Container format name (e.g., "mp4", "mkv", "avi") */
|
||||
/** Generated thumbnail image format */
|
||||
format: string;
|
||||
|
||||
/** Video codec name (e.g., "h264", "hevc", "vp9") */
|
||||
videoCodec: string;
|
||||
|
||||
/** First frame thumbnail as BMP image buffer */
|
||||
/** First frame thumbnail as JPEG image buffer */
|
||||
image: Buffer;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { platform } from 'node:os';
|
||||
import { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory';
|
||||
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
|
||||
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
|
||||
|
||||
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
|
||||
if (process.platform === 'win32' && binaryPath) {
|
||||
@@ -94,6 +95,15 @@ export class FFmpegService {
|
||||
await adapter.extractThumbnail(videoPath, thumbnailPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接发送到 QQ kernel 的旧视频元素使用 PNG 缩略图。
|
||||
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
|
||||
*/
|
||||
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
|
||||
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
|
||||
await adapter.extractThumbnail(videoPath, thumbnailPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换音频文件
|
||||
*/
|
||||
|
||||
@@ -187,14 +187,14 @@ export class LogWrapper implements ILogWrapper {
|
||||
|
||||
_log (level: LogLevel, ...args: any[]) {
|
||||
if (this.consoleLogEnabled || this.fileLogEnabled) {
|
||||
const message = this.formatMsg(args);
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const message = this.formatMsg(args).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|\x1B\[[0-?]*[ -/]*[@-~]|\x1B/g, '');
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
this.logger.log(level, message);
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
|
||||
@@ -107,10 +107,20 @@ export class RkeyManager {
|
||||
for (const url of availableUrls) {
|
||||
try {
|
||||
let temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
|
||||
if ('retcode' in temp) {
|
||||
if (typeof temp === 'object' && temp !== null && 'retcode' in temp) {
|
||||
// 支持Onebot Ret风格
|
||||
temp = (temp as unknown as OneBotApiRet).data;
|
||||
}
|
||||
if (
|
||||
typeof temp?.group_rkey !== 'string' ||
|
||||
typeof temp?.private_rkey !== 'string' ||
|
||||
typeof temp?.expired_time !== 'number' ||
|
||||
temp.group_rkey.length <= 6 ||
|
||||
temp.private_rkey.length <= 6 ||
|
||||
temp.expired_time <= 0
|
||||
) {
|
||||
throw new Error('Rkey 服务返回格式无效:group_rkey/private_rkey/expired_time 缺失或不合法');
|
||||
}
|
||||
this.rkeyData = {
|
||||
group_rkey: temp.group_rkey.slice(6),
|
||||
private_rkey: temp.private_rkey.slice(6),
|
||||
|
||||
@@ -39,12 +39,17 @@ export class NativePacketClient {
|
||||
|
||||
async init (_pid: number, recv: string, send: string): Promise<void> {
|
||||
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
|
||||
if (isNewQQ) {
|
||||
const success = this.napi2nativeLoader.initHook(send, recv);
|
||||
if (success) {
|
||||
this.available = true;
|
||||
}
|
||||
if (!isNewQQ) {
|
||||
this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化');
|
||||
return;
|
||||
}
|
||||
const success = this.napi2nativeLoader.initHook(send, recv);
|
||||
if (success) {
|
||||
this.available = true;
|
||||
this.logStack.pushLogInfo(`[PacketClient] NativePacketClient Hook 初始化成功 platform=${process.platform}.${process.arch}`);
|
||||
return;
|
||||
}
|
||||
this.logStack.pushLogError(`[PacketClient] NativePacketClient Hook 初始化失败 platform=${process.platform}.${process.arch} send=${send} recv=${recv}`);
|
||||
}
|
||||
|
||||
async sendPacket (
|
||||
|
||||
@@ -19,6 +19,7 @@ import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
|
||||
import { gunzipSync } from 'zlib';
|
||||
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
|
||||
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
|
||||
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
|
||||
|
||||
export class PacketOperationContext {
|
||||
private readonly context: PacketContext;
|
||||
@@ -105,15 +106,7 @@ export class PacketOperationContext {
|
||||
.filter(Boolean)
|
||||
);
|
||||
const res = await Promise.allSettled(reqList);
|
||||
const failedCount = res.filter((r) => r.status === 'rejected').length;
|
||||
if (failedCount > 0) {
|
||||
this.context.logger.warn(`上传资源${res.length}个,失败${failedCount}个`);
|
||||
res.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
assertUploadResults(res, this.context.logger);
|
||||
}
|
||||
|
||||
async UploadImage (img: PacketMsgPicElement) {
|
||||
@@ -240,9 +233,10 @@ export class PacketOperationContext {
|
||||
}
|
||||
|
||||
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
|
||||
// await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源(跳过已有原始数据的项)
|
||||
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
|
||||
await Promise.all(msg.filter(item => item.actionMsg).map(async (item) => {
|
||||
await this.SendPreprocess(item.actionMsg!, groupUin);
|
||||
}));
|
||||
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
@@ -370,6 +364,23 @@ export class PacketOperationContext {
|
||||
}
|
||||
return element;
|
||||
}
|
||||
if (element.videoElement && rawElem?.commonElem?.pbElem) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(rawElem.commonElem.pbElem);
|
||||
const index = extra?.msgInfoBody[0]?.index;
|
||||
if (!index) return element;
|
||||
if (msg?.responseHead.grp !== undefined) {
|
||||
element.videoElement = {
|
||||
...element.videoElement,
|
||||
filePath: await this.GetGroupVideoUrl(msg.responseHead.grp.groupUin ?? 0, index),
|
||||
};
|
||||
} else {
|
||||
element.videoElement = {
|
||||
...element.videoElement,
|
||||
filePath: await this.GetVideoUrl(this.context.napcore.basicInfo.uid, index),
|
||||
};
|
||||
}
|
||||
return element;
|
||||
}
|
||||
return element;
|
||||
})
|
||||
);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface UploadResultLogger {
|
||||
warn (message: string): unknown;
|
||||
error (message: string): unknown;
|
||||
}
|
||||
|
||||
export function assertUploadResults (
|
||||
results: PromiseSettledResult<unknown>[],
|
||||
logger: UploadResultLogger
|
||||
): void {
|
||||
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
|
||||
if (failures.length === 0) return;
|
||||
|
||||
logger.warn(`上传资源${results.length}个,失败${failures.length}个`);
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
const reason = result.reason instanceof Error
|
||||
? result.reason.stack ?? result.reason.message
|
||||
: String(result.reason);
|
||||
logger.error(`上传第${index + 1}个资源失败:${reason}`);
|
||||
}
|
||||
});
|
||||
throw new AggregateError(
|
||||
failures.map(result => result.reason),
|
||||
`上传转发消息资源失败:${failures.length}/${results.length}`
|
||||
);
|
||||
}
|
||||
@@ -21,8 +21,11 @@ import { PacketClientContext } from '@/napcat-core/packet/context/clientContext'
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
import { calculateFileMD5 } from 'napcat-common/src/file';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { imageSizeFallBack } from 'napcat-image-size/src/index';
|
||||
|
||||
export const BlockSize = 1024 * 1024;
|
||||
const VIDEO_THUMBNAIL_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
interface HighwayServerAddr {
|
||||
ip: string;
|
||||
@@ -110,22 +113,37 @@ export class PacketHighwayContext {
|
||||
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
|
||||
}
|
||||
|
||||
// 如果缺少视频缩略图,自动生成一个
|
||||
let tempThumbPath: string | null = null;
|
||||
let thumbExists = false;
|
||||
if (video.thumbPath) {
|
||||
try {
|
||||
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
|
||||
thumbExists = true;
|
||||
} catch {
|
||||
thumbExists = false;
|
||||
}
|
||||
}
|
||||
if (!video.thumbPath || !thumbExists) {
|
||||
tempThumbPath = await this.ensureVideoThumb(video);
|
||||
}
|
||||
|
||||
const cleanupThumbPaths: string[] = [];
|
||||
try {
|
||||
let thumbExists = false;
|
||||
if (video.thumbPath) {
|
||||
try {
|
||||
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
|
||||
thumbExists = true;
|
||||
} catch {
|
||||
thumbExists = false;
|
||||
}
|
||||
}
|
||||
|
||||
let shouldGenerateThumb = !video.thumbPath || !thumbExists;
|
||||
if (!shouldGenerateThumb) {
|
||||
try {
|
||||
await this.updateVideoThumbInfo(video);
|
||||
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
|
||||
this.logger.warn(`[Highway] Video thumbnail is too large: ${video.thumbSize} bytes, regenerating`);
|
||||
shouldGenerateThumb = true;
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`[Highway] Failed to inspect video thumbnail, regenerating. Reason: ${e instanceof Error ? e.message : e}`);
|
||||
shouldGenerateThumb = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldGenerateThumb) {
|
||||
cleanupThumbPaths.push(await this.ensureVideoThumb(video));
|
||||
}
|
||||
video.businessType = peer.chatType === ChatType.KCHATTYPEGROUP ? 21 : 11;
|
||||
|
||||
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
|
||||
await this.uploadGroupVideo(+peer.peerUid, video);
|
||||
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
|
||||
@@ -134,23 +152,21 @@ export class PacketHighwayContext {
|
||||
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
|
||||
}
|
||||
} finally {
|
||||
// 清理临时生成的缩略图文件
|
||||
if (tempThumbPath) {
|
||||
const thumbToClean = tempThumbPath;
|
||||
fs.promises.unlink(thumbToClean)
|
||||
.then(() => this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`))
|
||||
.catch((e) => {
|
||||
// 文件不存在时忽略错误
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
await Promise.allSettled(cleanupThumbPaths.map(async (thumbToClean) => {
|
||||
try {
|
||||
await fs.promises.unlink(thumbToClean);
|
||||
this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保视频缩略图存在,如果不存在则自动生成
|
||||
* 使用当前 FFmpeg 适配器生成符合 QQ 大小限制的视频缩略图
|
||||
* @returns 生成的临时缩略图路径,用于后续清理
|
||||
*/
|
||||
private async ensureVideoThumb (video: PacketMsgVideoElement): Promise<string> {
|
||||
@@ -161,9 +177,10 @@ export class PacketHighwayContext {
|
||||
// 生成缩略图路径
|
||||
const videoDir = path.dirname(video.filePath);
|
||||
const videoBasename = path.basename(video.filePath, path.extname(video.filePath));
|
||||
const thumbPath = path.join(videoDir, `${videoBasename}_thumb.png`);
|
||||
const thumbPath = path.join(videoDir, `${videoBasename}_thumb_${randomUUID()}.jpg`);
|
||||
|
||||
this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
|
||||
video.thumbPath = thumbPath;
|
||||
|
||||
try {
|
||||
// 尝试使用 FFmpeg 提取视频缩略图
|
||||
@@ -174,26 +191,36 @@ export class PacketHighwayContext {
|
||||
} catch {
|
||||
throw new Error('FFmpeg failed to generate thumbnail');
|
||||
}
|
||||
await this.updateVideoThumbInfo(video);
|
||||
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
|
||||
throw new Error(`generated thumbnail is too large: ${video.thumbSize} bytes`);
|
||||
}
|
||||
} catch (e) {
|
||||
// FFmpeg 失败时(包括未初始化的情况)使用默认缩略图
|
||||
this.logger.warn(`[Highway] Failed to extract thumbnail, using default. Reason: ${e instanceof Error ? e.message : e}`);
|
||||
await fs.promises.writeFile(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
|
||||
await this.updateVideoThumbInfo(video);
|
||||
}
|
||||
|
||||
// 更新视频元素的缩略图信息
|
||||
video.thumbPath = thumbPath;
|
||||
const thumbStat = await fs.promises.stat(thumbPath);
|
||||
video.thumbSize = thumbStat.size;
|
||||
video.thumbMd5 = await calculateFileMD5(thumbPath);
|
||||
// 默认缩略图尺寸(与 defaultVideoThumbB64 匹配的尺寸)
|
||||
if (!video.thumbWidth) video.thumbWidth = 240;
|
||||
if (!video.thumbHeight) video.thumbHeight = 383;
|
||||
|
||||
this.logger.debug(`[Highway] Video thumb info set: path=${thumbPath}, size=${video.thumbSize}, md5=${video.thumbMd5}`);
|
||||
|
||||
return thumbPath;
|
||||
}
|
||||
|
||||
private async updateVideoThumbInfo (video: PacketMsgVideoElement): Promise<void> {
|
||||
if (!video.thumbPath) {
|
||||
throw new Error('video.thumbPath is empty, cannot inspect thumbnail');
|
||||
}
|
||||
const [thumbStat, thumbMd5, dimensions] = await Promise.all([
|
||||
fs.promises.stat(video.thumbPath),
|
||||
calculateFileMD5(video.thumbPath),
|
||||
imageSizeFallBack(video.thumbPath),
|
||||
]);
|
||||
video.thumbSize = thumbStat.size;
|
||||
video.thumbMd5 = thumbMd5;
|
||||
video.thumbWidth = dimensions.width;
|
||||
video.thumbHeight = dimensions.height;
|
||||
this.logger.debug(`[Highway] Video thumbnail ready: ${dimensions.width}x${dimensions.height}, ${thumbStat.size} bytes`);
|
||||
}
|
||||
|
||||
async uploadPtt (peer: Peer, ptt: PacketMsgPttElement): Promise<void> {
|
||||
await this.checkAvailable();
|
||||
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
|
||||
@@ -296,13 +323,17 @@ export class PacketHighwayContext {
|
||||
const req = trans.UploadGroupVideo.build(groupUin, video);
|
||||
const resp = await this.client.sendOidbPacket(req, true);
|
||||
const preRespData = trans.UploadGroupVideo.parse(resp);
|
||||
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
|
||||
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
|
||||
if (!videoIndex || !thumbIndex) {
|
||||
throw new Error('[Highway] uploadGroupVideo response is missing video or thumbnail MsgInfo');
|
||||
}
|
||||
const ukey = preRespData.upload.uKey;
|
||||
if (ukey && ukey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
uKey: ukey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
|
||||
@@ -324,16 +355,15 @@ export class PacketHighwayContext {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
|
||||
}
|
||||
const subFile = preRespData.upload.subFileInfos[0];
|
||||
if (subFile!.uKey && subFile!.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
|
||||
if (subFile?.uKey && subFile.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
|
||||
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
uKey: subFile!.uKey,
|
||||
fileUuid: thumbIndex.fileUuid,
|
||||
uKey: subFile.uKey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
|
||||
},
|
||||
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
|
||||
blockSize: BlockSize,
|
||||
@@ -349,7 +379,7 @@ export class PacketHighwayContext {
|
||||
extend
|
||||
);
|
||||
} else {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
|
||||
}
|
||||
video.msgInfo = preRespData.upload.msgInfo;
|
||||
}
|
||||
@@ -361,13 +391,17 @@ export class PacketHighwayContext {
|
||||
const req = trans.UploadPrivateVideo.build(peerUid, video);
|
||||
const resp = await this.client.sendOidbPacket(req, true);
|
||||
const preRespData = trans.UploadPrivateVideo.parse(resp);
|
||||
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
|
||||
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
|
||||
if (!videoIndex || !thumbIndex) {
|
||||
throw new Error('[Highway] uploadC2CVideo response is missing video or thumbnail MsgInfo');
|
||||
}
|
||||
const ukey = preRespData.upload.uKey;
|
||||
if (ukey && ukey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
uKey: ukey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
|
||||
@@ -389,16 +423,15 @@ export class PacketHighwayContext {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
|
||||
}
|
||||
const subFile = preRespData.upload.subFileInfos[0];
|
||||
if (subFile!.uKey && subFile!.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
|
||||
if (subFile?.uKey && subFile.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
|
||||
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
uKey: subFile!.uKey,
|
||||
fileUuid: thumbIndex.fileUuid,
|
||||
uKey: subFile.uKey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
|
||||
},
|
||||
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
|
||||
blockSize: BlockSize,
|
||||
@@ -414,7 +447,7 @@ export class PacketHighwayContext {
|
||||
extend
|
||||
);
|
||||
} else {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
|
||||
}
|
||||
video.msgInfo = preRespData.upload.msgInfo;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
MessageElement,
|
||||
Peer,
|
||||
RawMessage,
|
||||
} from '@/napcat-core/types/msg';
|
||||
import {
|
||||
SendArkElement,
|
||||
SendFaceElement,
|
||||
SendFileElement,
|
||||
@@ -15,7 +17,7 @@ import {
|
||||
SendReplyElement,
|
||||
SendTextElement,
|
||||
SendVideoElement,
|
||||
} from '@/napcat-core/index';
|
||||
} from '@/napcat-core/types/element';
|
||||
import {
|
||||
IPacketMsgElement,
|
||||
PacketMsgAtElement,
|
||||
@@ -158,7 +160,8 @@ export class PacketMsgConverter {
|
||||
|
||||
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
|
||||
const converters = [PacketMsgTextElement.parseElement,
|
||||
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
|
||||
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement,
|
||||
PacketMsgVideoElement.parseElement, PacketMsgPicElement.parseElement];
|
||||
return msg.map((element) => {
|
||||
for (const converter of converters) {
|
||||
const result = converter(element);
|
||||
|
||||
@@ -20,7 +20,11 @@ import {
|
||||
FaceType,
|
||||
MessageElement,
|
||||
NTMsgAtType,
|
||||
NTVideoType,
|
||||
PicType,
|
||||
Peer,
|
||||
} from '@/napcat-core/types/msg';
|
||||
import {
|
||||
SendArkElement,
|
||||
SendFaceElement,
|
||||
SendFileElement,
|
||||
@@ -32,8 +36,7 @@ import {
|
||||
SendMultiForwardMsgElement,
|
||||
SendTextElement,
|
||||
SendVideoElement,
|
||||
Peer,
|
||||
} from '@/napcat-core/index';
|
||||
} from '@/napcat-core/types/element';
|
||||
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
|
||||
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
|
||||
|
||||
@@ -387,8 +390,10 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
}
|
||||
|
||||
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
|
||||
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
|
||||
if (elem?.commonElem?.serviceType === 48 &&
|
||||
[10, 20].includes(elem.commonElem.businessType ?? 0) &&
|
||||
elem.commonElem.pbElem) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
|
||||
const msgInfoBody = extra.msgInfoBody[0];
|
||||
const index = msgInfoBody?.index;
|
||||
return [{
|
||||
@@ -406,7 +411,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
summary: '[图片]',
|
||||
thumbPath: new Map(),
|
||||
},
|
||||
elementType: ElementType.UNKNOWN,
|
||||
elementType: ElementType.PIC,
|
||||
elementId: '',
|
||||
}, elem];
|
||||
}
|
||||
@@ -446,8 +451,13 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
}
|
||||
|
||||
export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
fileName: string;
|
||||
fileSize?: string;
|
||||
filePath?: string;
|
||||
fileTime: number;
|
||||
fileFormat: NTVideoType;
|
||||
fileWidth?: number;
|
||||
fileHeight?: number;
|
||||
thumbSize?: number;
|
||||
thumbPath?: string;
|
||||
fileMd5?: string;
|
||||
@@ -456,12 +466,18 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
thumbSha1?: string;
|
||||
thumbWidth?: number;
|
||||
thumbHeight?: number;
|
||||
businessType: 11 | 21 = 21;
|
||||
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
|
||||
|
||||
constructor (element: SendVideoElement) {
|
||||
super(element);
|
||||
this.fileName = element.videoElement.fileName;
|
||||
this.fileSize = element.videoElement.fileSize;
|
||||
this.filePath = element.videoElement.filePath;
|
||||
this.fileTime = Math.max(0, Math.round(element.videoElement.fileTime ?? 0));
|
||||
this.fileFormat = element.videoElement.fileFormat ?? NTVideoType.VIDEO_FORMAT_MP4;
|
||||
this.fileWidth = element.videoElement.fileWidth;
|
||||
this.fileHeight = element.videoElement.fileHeight;
|
||||
this.thumbSize = element.videoElement.thumbSize;
|
||||
this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
|
||||
this.fileMd5 = element.videoElement.videoMd5;
|
||||
@@ -480,11 +496,45 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
|
||||
businessType: 21,
|
||||
businessType: this.businessType,
|
||||
},
|
||||
}];
|
||||
}
|
||||
|
||||
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
|
||||
if (elem?.commonElem?.serviceType !== 48 ||
|
||||
![11, 21].includes(elem.commonElem.businessType ?? 0) ||
|
||||
!elem.commonElem.pbElem) {
|
||||
return undefined;
|
||||
}
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
|
||||
const videoIndex = extra.msgInfoBody[0]?.index;
|
||||
const thumbIndex = extra.msgInfoBody[1]?.index;
|
||||
if (!videoIndex) return undefined;
|
||||
return [{
|
||||
videoElement: {
|
||||
filePath: '',
|
||||
fileName: videoIndex.info.fileName || videoIndex.info.fileHash,
|
||||
videoMd5: videoIndex.info.fileHash,
|
||||
thumbMd5: thumbIndex?.info.fileHash,
|
||||
fileTime: videoIndex.info.time,
|
||||
fileFormat: (videoIndex.info.type.videoFormat || NTVideoType.VIDEO_FORMAT_MP4) as NTVideoType,
|
||||
fileSize: String(videoIndex.info.fileSize),
|
||||
fileWidth: videoIndex.info.width,
|
||||
fileHeight: videoIndex.info.height,
|
||||
thumbWidth: thumbIndex?.info.width,
|
||||
thumbHeight: thumbIndex?.info.height,
|
||||
thumbSize: thumbIndex?.info.fileSize,
|
||||
thumbPath: new Map(),
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
busiType: 0,
|
||||
subBusiType: 0,
|
||||
},
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: '',
|
||||
}, elem];
|
||||
};
|
||||
|
||||
override toPreview (): string {
|
||||
return '[视频]';
|
||||
}
|
||||
|
||||
@@ -33,16 +33,16 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
|
||||
fileSize: +video.fileSize,
|
||||
fileHash: video.fileMd5,
|
||||
fileSha1: video.fileSha1,
|
||||
fileName: 'nya.mp4',
|
||||
fileName: video.fileName || 'video.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
picFormat: 0,
|
||||
videoFormat: 0,
|
||||
videoFormat: video.fileFormat,
|
||||
voiceFormat: 0,
|
||||
},
|
||||
height: 0,
|
||||
width: 0,
|
||||
time: 0,
|
||||
height: video.fileHeight ?? 0,
|
||||
width: video.fileWidth ?? 0,
|
||||
time: video.fileTime,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
@@ -51,7 +51,7 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
|
||||
fileSize: +video.thumbSize,
|
||||
fileHash: video.thumbMd5,
|
||||
fileSha1: video.thumbSha1,
|
||||
fileName: 'nya.jpg',
|
||||
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
|
||||
@@ -34,16 +34,16 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
|
||||
fileSize: +video.fileSize,
|
||||
fileHash: video.fileMd5,
|
||||
fileSha1: video.fileSha1,
|
||||
fileName: 'nya.mp4',
|
||||
fileName: video.fileName || 'video.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
picFormat: 0,
|
||||
videoFormat: 0,
|
||||
videoFormat: video.fileFormat,
|
||||
voiceFormat: 0,
|
||||
},
|
||||
height: 0,
|
||||
width: 0,
|
||||
time: 0,
|
||||
height: video.fileHeight ?? 0,
|
||||
width: video.fileWidth ?? 0,
|
||||
time: video.fileTime,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
@@ -52,7 +52,7 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
|
||||
fileSize: +video.thumbSize,
|
||||
fileHash: video.thumbMd5,
|
||||
fileSha1: video.thumbSha1,
|
||||
fileName: 'nya.jpg',
|
||||
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
|
||||
@@ -118,6 +118,8 @@ export interface VideoElement {
|
||||
thumbSize?: number; // byte
|
||||
fileFormat?: NTVideoType; // 2表示mp4 参考下面条目
|
||||
fileSize?: string; // byte
|
||||
fileWidth?: number;
|
||||
fileHeight?: number;
|
||||
thumbWidth?: number;
|
||||
thumbHeight?: number;
|
||||
busiType?: 0; //
|
||||
|
||||
@@ -74,6 +74,20 @@ export interface EXTInfo {
|
||||
groupSquareSwitch: number;
|
||||
}
|
||||
|
||||
export type GroupMemberInvitePolicy =
|
||||
| 'disabled'
|
||||
| 'require_approval'
|
||||
| 'no_approval'
|
||||
| 'no_approval_under_100';
|
||||
|
||||
export interface GroupManagementSettings {
|
||||
memberInvite?: GroupMemberInvitePolicy;
|
||||
allowMemberUploadAlbum?: boolean;
|
||||
allowMemberTemporarySession?: boolean;
|
||||
allowMemberCreateGroup?: boolean;
|
||||
newMembersSeeRecentHistory?: boolean;
|
||||
}
|
||||
|
||||
export interface GroupGuildIDS {
|
||||
guildIds: any[];
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -42,4 +42,12 @@ export const ExtendsActionsExamples = {
|
||||
payload: { group_id: '123456', user_id: '123456789', special_title: '头衔' },
|
||||
response: null,
|
||||
},
|
||||
SendQzoneMsg: {
|
||||
payload: { content: '今天天气不错', images: [], ugc_right: 1, target_uins: [] },
|
||||
response: { tid: '1234567890abcdef1234567890' },
|
||||
},
|
||||
DeleteQzoneMsg: {
|
||||
payload: { tid: '1234567890abcdef1234567890' },
|
||||
response: null,
|
||||
},
|
||||
};
|
||||
@@ -1,4 +1,21 @@
|
||||
export const GroupActionsExamples = {
|
||||
SetGroupMemberInvitePolicy: {
|
||||
payload: { group_id: '123456', policy: 'require_approval' },
|
||||
response: null,
|
||||
},
|
||||
SetGroupMemberPermissions: {
|
||||
payload: {
|
||||
group_id: '123456',
|
||||
allow_member_upload_album: true,
|
||||
allow_member_temporary_session: true,
|
||||
allow_member_create_group: true,
|
||||
},
|
||||
response: null,
|
||||
},
|
||||
SetGroupNewMemberHistoryVisibility: {
|
||||
payload: { group_id: '123456', visible: true },
|
||||
response: null,
|
||||
},
|
||||
DelEssenceMsg: {
|
||||
payload: { message_id: 123456 },
|
||||
response: null,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
tid: Type.String({ description: '说说 tid (来自 get_qzone_msg_list / send_qzone_msg)' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
export class DeleteQzoneMsg extends OneBotAction<PayloadType, void> {
|
||||
override actionName = ActionName.DeleteQzoneMsg;
|
||||
override actionSummary = '删除QQ空间说说';
|
||||
override actionDescription = '删除QQ空间(Qzone)的一条说说, 按 tid 删除';
|
||||
override actionTags = ['扩展接口'];
|
||||
override payloadExample = ExtendsActionsExamples.DeleteQzoneMsg.payload;
|
||||
override returnExample = ExtendsActionsExamples.DeleteQzoneMsg.response;
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = Type.Null();
|
||||
|
||||
async _handle (payload: PayloadType): Promise<void> {
|
||||
await this.core.apis.WebApi.deleteQzoneMsg(payload.tid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.Union([Type.Number(), Type.String()], { description: '群号' }),
|
||||
need_short_url: Type.Optional(Type.Union([Type.Boolean(), Type.String()], { default: true, description: '是否返回短链 (qm.qq.com/q/xxx),false 返回完整 universal-share 链接' })),
|
||||
src_id: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 73, description: '分享来源 ID' })),
|
||||
additional_param: Type.Optional(Type.String({ default: '', description: '附加参数' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Object({
|
||||
url: Type.String({ description: '群分享链接' }),
|
||||
}, { description: '群分享链接' });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class GetGroupShareLink extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.GetGroupShareLink;
|
||||
override actionSummary = '获取群分享链接';
|
||||
override actionDescription = '通过 NTQQ 原生 getJoinGroupLink 获取群的 H5 分享/加群链接 (qm.qq.com/q/xxx 或 qun.qq.com/universal-share/share?...)';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
need_short_url: true,
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
url: 'https://qm.qq.com/q/xxxxxxxxxx',
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const needShortUrl = payload.need_short_url === undefined ? true : payload.need_short_url.toString() === 'true';
|
||||
const srcId = payload.src_id === undefined ? 73 : Number(payload.src_id);
|
||||
const ret = await this.core.apis.GroupApi.getJoinGroupLink(
|
||||
payload.group_id.toString(),
|
||||
needShortUrl,
|
||||
srcId,
|
||||
payload.additional_param ?? ''
|
||||
);
|
||||
if (!ret?.url) {
|
||||
throw new Error(`获取群分享链接失败: ${ret?.errMsg || JSON.stringify(ret)}`);
|
||||
}
|
||||
return { url: ret.url };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { uriToLocalFile } from 'napcat-common/src/file';
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { unlink } from 'node:fs/promises';
|
||||
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
|
||||
|
||||
const ValidUgcRights = [1, 4, 16, 64, 128] as const;
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
content: Type.String({ description: '说说正文' }),
|
||||
images: Type.Optional(Type.Array(Type.String(), { description: '图片数组, 支持 file:// http(s):// base64:// , 自动上传' })),
|
||||
ugc_right: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '查看权限: 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见' })),
|
||||
target_uins: Type.Optional(Type.Array(Type.Union([Type.Number(), Type.String()]), { description: 'ugc_right为16/128时, 权限作用的QQ号数组' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Object({
|
||||
tid: Type.String({ description: '说说Tid' }),
|
||||
}, { description: '发说说结果' });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class SendQzoneMsg extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SendQzoneMsg;
|
||||
override actionSummary = '发表QQ空间说说';
|
||||
override actionDescription = '在QQ空间(Qzone)发表说说, 支持纯文字或带(多)图, 可设置查看权限';
|
||||
override actionTags = ['扩展接口'];
|
||||
override payloadExample = ExtendsActionsExamples.SendQzoneMsg.payload;
|
||||
override returnExample = ExtendsActionsExamples.SendQzoneMsg.response;
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const ugcRight = payload.ugc_right !== undefined ? +payload.ugc_right : 1;
|
||||
if (!ValidUgcRights.includes(ugcRight as typeof ValidUgcRights[number])) {
|
||||
throw new Error(`ugc_right 参数不合法, 允许的值为: ${ValidUgcRights.join(', ')}`);
|
||||
}
|
||||
const targetUins = payload.target_uins?.map((uin) => +uin).filter((uin) => !Number.isNaN(uin));
|
||||
if ((ugcRight === 16 || ugcRight === 128) && (!targetUins || targetUins.length === 0)) {
|
||||
throw new Error('ugc_right 为 16 或 128 时, target_uins 不能为空');
|
||||
}
|
||||
|
||||
const richvals: string[] = [];
|
||||
const cleanupPaths: string[] = [];
|
||||
try {
|
||||
for (const image of payload.images ?? []) {
|
||||
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, image);
|
||||
if (!downloadResult.success) {
|
||||
throw new Error(`图片${image}处理失败, ${downloadResult.errMsg}`);
|
||||
}
|
||||
if (!downloadResult.isLocal) {
|
||||
cleanupPaths.push(downloadResult.path);
|
||||
}
|
||||
const base64 = readFileSync(downloadResult.path).toString('base64');
|
||||
const richval = await this.core.apis.WebApi.uploadImageToQzone(base64);
|
||||
richvals.push(richval);
|
||||
}
|
||||
|
||||
const result = await this.core.apis.WebApi.publishQzoneMsg(payload.content, richvals, ugcRight, targetUins);
|
||||
return result;
|
||||
} finally {
|
||||
for (const p of cleanupPaths) {
|
||||
if (existsSync(p)) {
|
||||
await unlink(p).catch(() => { });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,15 +29,22 @@ export class GetGroupFileSystemInfo extends OneBotAction<PayloadType, ReturnType
|
||||
override returnExample = GoCQHTTPActionsExamples.GetGroupFileSystemInfo.response;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const groupFileCount = (await this.core.apis.GroupApi.getGroupFileCount([payload.group_id.toString()])).groupFileCounts[0];
|
||||
if (!groupFileCount) {
|
||||
const groupCode = payload.group_id.toString();
|
||||
const [countResult, space] = await Promise.all([
|
||||
this.core.apis.GroupApi.getGroupFileCount([groupCode]),
|
||||
this.core.apis.GroupApi.getGroupFileSpace(groupCode),
|
||||
]);
|
||||
const groupFileCount = countResult.groupFileCounts[0];
|
||||
if (groupFileCount === undefined) {
|
||||
throw new Error('Group not found');
|
||||
}
|
||||
return {
|
||||
file_count: groupFileCount,
|
||||
limit_count: 10000,
|
||||
used_space: 0,
|
||||
total_space: 10 * 1024 * 1024 * 1024,
|
||||
// Real values from the kernel's groupSpaceResult; fall back to the old
|
||||
// placeholders if the field is unexpectedly absent.
|
||||
used_space: space?.usedSpace ?? 0,
|
||||
total_space: space?.totalSpace ?? 10 * 1024 * 1024 * 1024,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { GeneralCallResult } from 'napcat-core';
|
||||
|
||||
export function assertGroupManagementResults (
|
||||
operation: string,
|
||||
results: Array<{ setting: string, result: GeneralCallResult; }>
|
||||
): void {
|
||||
const failure = results.find(item => item.result.result !== 0);
|
||||
if (!failure) return;
|
||||
throw new Error(
|
||||
`${operation}失败 Setting: ${failure.setting} ErrCode: ${failure.result.result} ` +
|
||||
`ErrMsg: ${failure.result.errMsg || '未知错误'}`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
import { assertGroupManagementResults } from './GroupOperationHelpers';
|
||||
|
||||
const MemberInvitePolicySchema = Type.Union([
|
||||
Type.Literal('disabled'),
|
||||
Type.Literal('require_approval'),
|
||||
Type.Literal('no_approval'),
|
||||
Type.Literal('no_approval_under_100'),
|
||||
], {
|
||||
description: '成员邀请策略:禁止、需要管理员审核、无需审核、群成员少于100人时无需审核',
|
||||
});
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
policy: MemberInvitePolicySchema,
|
||||
});
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null({ description: '操作结果' });
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export default class SetGroupMemberInvitePolicy extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SetGroupMemberInvitePolicy;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '设置群成员邀请策略';
|
||||
override actionDescription = '设置是否允许群成员邀请好友进群,以及邀请是否需要管理员审核';
|
||||
override actionTags = ['群组接口'];
|
||||
override payloadExample = GroupActionsExamples.SetGroupMemberInvitePolicy.payload;
|
||||
override returnExample = GroupActionsExamples.SetGroupMemberInvitePolicy.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const results = await this.core.apis.GroupApi.setGroupMemberInvitePolicy(payload.group_id, payload.policy);
|
||||
assertGroupManagementResults('设置群成员邀请策略', results);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
import { assertGroupManagementResults } from './GroupOperationHelpers';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
allow_member_upload_album: Type.Optional(Type.Boolean({ description: '允许成员上传群相册' })),
|
||||
allow_member_temporary_session: Type.Optional(Type.Boolean({ description: '允许成员发起临时会话' })),
|
||||
allow_member_create_group: Type.Optional(Type.Boolean({ description: '允许成员发起新的群聊' })),
|
||||
});
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null({ description: '操作结果' });
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export default class SetGroupMemberPermissions extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SetGroupMemberPermissions;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '设置群成员功能权限';
|
||||
override actionDescription = '设置群成员上传相册、发起临时会话和发起新群聊的权限;未传入的项目保持不变';
|
||||
override actionTags = ['群组接口'];
|
||||
override payloadExample = GroupActionsExamples.SetGroupMemberPermissions.payload;
|
||||
override returnExample = GroupActionsExamples.SetGroupMemberPermissions.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const permissions = {
|
||||
allowMemberUploadAlbum: payload.allow_member_upload_album,
|
||||
allowMemberTemporarySession: payload.allow_member_temporary_session,
|
||||
allowMemberCreateGroup: payload.allow_member_create_group,
|
||||
};
|
||||
if (Object.values(permissions).every(value => value === undefined)) {
|
||||
throw new Error('至少需要提供一个群成员功能权限');
|
||||
}
|
||||
|
||||
const results = await this.core.apis.GroupApi.setGroupMemberPermissions(payload.group_id, permissions);
|
||||
assertGroupManagementResults('设置群成员功能权限', results);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
import { assertGroupManagementResults } from './GroupOperationHelpers';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
visible: Type.Boolean({ description: '新成员默认可见最近聊天记录' }),
|
||||
});
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null({ description: '操作结果' });
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export default class SetGroupNewMemberHistoryVisibility extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SetGroupNewMemberHistoryVisibility;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '设置新成员历史消息可见性';
|
||||
override actionDescription = '设置新入群成员默认是否可以查看最近聊天记录';
|
||||
override actionTags = ['群组接口'];
|
||||
override payloadExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.payload;
|
||||
override returnExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const results = await this.core.apis.GroupApi.setGroupNewMemberHistoryVisibility(
|
||||
payload.group_id,
|
||||
payload.visible
|
||||
);
|
||||
assertGroupManagementResults('设置新成员历史消息可见性', results);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,7 @@ import { SetInputStatus } from './extends/SetInputStatus';
|
||||
import { GetCSRF } from './system/GetCSRF';
|
||||
import { DelGroupNotice } from './group/DelGroupNotice';
|
||||
import { GetGroupInfoEx } from './extends/GetGroupInfoEx';
|
||||
import { GetGroupShareLink } from './extends/GetGroupShareLink';
|
||||
import { DeleteGroupFile } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFile';
|
||||
import { CreateGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/CreateGroupFileFolder';
|
||||
import { DeleteGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFileFolder';
|
||||
@@ -160,6 +161,11 @@ import { RefuseOnlineFile } from './file/online/RefuseOnlineFile';
|
||||
import { GetFilesetId } from './file/flash/GetFilesetIdByCode';
|
||||
import { FetchPttText } from '@/napcat-onebot/action/msg/FetchPttText';
|
||||
import { GetGroupSignedList } from './extends/GetGroupSignedList';
|
||||
import { SendQzoneMsg } from './extends/SendQzoneMsg';
|
||||
import { DeleteQzoneMsg } from './extends/DeleteQzoneMsg';
|
||||
import SetGroupMemberInvitePolicy from './group/SetGroupMemberInvitePolicy';
|
||||
import SetGroupMemberPermissions from './group/SetGroupMemberPermissions';
|
||||
import SetGroupNewMemberHistoryVisibility from './group/SetGroupNewMemberHistoryVisibility';
|
||||
|
||||
export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCore) {
|
||||
const actionHandlers = [
|
||||
@@ -191,6 +197,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetRkeyServer(obContext, core),
|
||||
new SetGroupRemark(obContext, core),
|
||||
new GetGroupInfoEx(obContext, core),
|
||||
new GetGroupShareLink(obContext, core),
|
||||
new FetchEmojiLike(obContext, core),
|
||||
new GetEmojiLikes(obContext, core),
|
||||
new FetchPttText(obContext, core),
|
||||
@@ -216,6 +223,11 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new RenameGroupFile(obContext, core),
|
||||
new TransGroupFile(obContext, core),
|
||||
new GetGroupSignedList(obContext, core),
|
||||
new SendQzoneMsg(obContext, core),
|
||||
new DeleteQzoneMsg(obContext, core),
|
||||
new SetGroupMemberInvitePolicy(obContext, core),
|
||||
new SetGroupMemberPermissions(obContext, core),
|
||||
new SetGroupNewMemberHistoryVisibility(obContext, core),
|
||||
// onebot11
|
||||
new SendLike(obContext, core),
|
||||
new GetMsg(obContext, core),
|
||||
|
||||
@@ -84,6 +84,13 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
|
||||
}
|
||||
const isBuddy = await core.apis.FriendApi.isBuddy(Uid);
|
||||
if (!isBuddy) {
|
||||
if (payload.group_id) {
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
|
||||
peerUid: Uid,
|
||||
guildId: payload.group_id.toString(),
|
||||
};
|
||||
}
|
||||
const ret = await core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, Uid);
|
||||
if (ret.tmpChatInfo?.groupCode) {
|
||||
return {
|
||||
@@ -92,13 +99,6 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
|
||||
guildId: '',
|
||||
};
|
||||
}
|
||||
if (payload.group_id) {
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
|
||||
peerUid: Uid,
|
||||
guildId: payload.group_id.toString(),
|
||||
};
|
||||
}
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPEC2C,
|
||||
peerUid: Uid,
|
||||
@@ -245,7 +245,12 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
|
||||
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(
|
||||
OB11Data,
|
||||
msgPeer,
|
||||
[],
|
||||
{ usePacketVideoMetadata: true }
|
||||
);
|
||||
sendElements = sendElementsCreateReturn.sendElements;
|
||||
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import { Type } from '@sinclair/typebox';
|
||||
|
||||
export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT> {
|
||||
protected override async check (payload: PT): Promise<BaseCheckResult> {
|
||||
const schemaResult = await super.check(payload);
|
||||
if (!schemaResult.valid) return schemaResult;
|
||||
if (!this.core.apis.PacketApi.packetStatus) {
|
||||
return {
|
||||
valid: false,
|
||||
@@ -11,7 +13,22 @@ export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT
|
||||
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
|
||||
};
|
||||
}
|
||||
return await super.check(payload);
|
||||
return { valid: true };
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class PacketSendAvailableDepends<PT, RT> extends OneBotAction<PT, RT> {
|
||||
protected override async check (payload: PT): Promise<BaseCheckResult> {
|
||||
const schemaResult = await super.check(payload);
|
||||
if (!schemaResult.valid) return schemaResult;
|
||||
if (!this.core.apis.PacketApi.available) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'packetBackend发包能力不可用,请参照文档 https://napneko.github.io/config/advanced 和启动日志检查packetBackend状态或进行配置!' +
|
||||
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
|
||||
};
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
import { PacketSendAvailableDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { PacketActionsExamples } from '../example/PacketActionsExamples';
|
||||
@@ -11,7 +11,7 @@ export const SendPokePayloadSchema = Type.Object({
|
||||
});
|
||||
|
||||
export type SendPokePayload = Static<typeof SendPokePayloadSchema>;
|
||||
export class SendPokeBase extends GetPacketStatusDepends<SendPokePayload, void> {
|
||||
export class SendPokeBase extends PacketSendAvailableDepends<SendPokePayload, void> {
|
||||
override payloadSchema = SendPokePayloadSchema;
|
||||
override returnSchema = Type.Null();
|
||||
override actionSummary = '发送戳一戳';
|
||||
|
||||
@@ -43,6 +43,9 @@ export const ActionName = {
|
||||
GetRkeyEx: 'get_rkey',
|
||||
GetRkeyServer: 'get_rkey_server',
|
||||
SetGroupRemark: 'set_group_remark',
|
||||
SetGroupMemberInvitePolicy: 'set_group_member_invite_policy',
|
||||
SetGroupMemberPermissions: 'set_group_member_permissions',
|
||||
SetGroupNewMemberHistoryVisibility: 'set_group_new_member_history_visibility',
|
||||
NapCat_GetPrivateFileUrl: 'get_private_file_url',
|
||||
ClickInlineKeyboardButton: 'click_inline_keyboard_button',
|
||||
GetUnidirectionalFriendList: 'get_unidirectional_friend_list',
|
||||
@@ -163,6 +166,7 @@ export const ActionName = {
|
||||
GetEmojiLikes: 'get_emoji_likes',
|
||||
SetInputStatus: 'set_input_status',
|
||||
GetGroupInfoEx: 'get_group_info_ex',
|
||||
GetGroupShareLink: 'get_group_share_link',
|
||||
GetGroupDetailInfo: 'get_group_detail_info',
|
||||
GetGroupIgnoreAddRequest: 'get_group_ignore_add_request',
|
||||
DelGroupNotice: '_del_group_notice',
|
||||
@@ -214,4 +218,8 @@ export const ActionName = {
|
||||
CancelOnlineFile: 'cancel_online_file',
|
||||
|
||||
GetGroupSignedList: 'get_group_signed_list',
|
||||
|
||||
// QQ 空间扩展
|
||||
SendQzoneMsg: 'send_qzone_msg',
|
||||
DeleteQzoneMsg: 'delete_qzone_msg',
|
||||
} as const;
|
||||
@@ -2,7 +2,7 @@ import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
|
||||
import { encodeSilk } from '@/napcat-core/helper/audio';
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { calculateFileMD5 } from 'napcat-common/src/file';
|
||||
import { ElementType, NapCatCore, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
|
||||
import { ElementType, NapCatCore, NTVideoType, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
|
||||
import { getFileTypeForSendType } from 'napcat-core/helper/msg';
|
||||
import { imageSizeFallBack } from 'napcat-image-size';
|
||||
import { SendMessageContext } from './msg';
|
||||
@@ -12,6 +12,21 @@ import fsPromises from 'fs/promises';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
|
||||
const videoFormatByExtension: Partial<Record<string, NTVideoType>> = {
|
||||
afs: NTVideoType.VIDEO_FORMAT_AFS,
|
||||
avi: NTVideoType.VIDEO_FORMAT_AVI,
|
||||
mkv: NTVideoType.VIDEO_FORMAT_MKV,
|
||||
mod: NTVideoType.VIDEO_FORMAT_MOD,
|
||||
mov: NTVideoType.VIDEO_FORMAT_MOV,
|
||||
mp4: NTVideoType.VIDEO_FORMAT_MP4,
|
||||
mts: NTVideoType.VIDEO_FORMAT_MTS,
|
||||
rm: NTVideoType.VIDEO_FORMAT_RM,
|
||||
rmvb: NTVideoType.VIDEO_FORMAT_RMVB,
|
||||
ts: NTVideoType.VIDEO_FORMAT_TS,
|
||||
wmv: NTVideoType.VIDEO_FORMAT_WMV,
|
||||
};
|
||||
|
||||
export class OneBotFileApi {
|
||||
obContext: NapCatOneBot11Adapter;
|
||||
core: NapCatCore;
|
||||
@@ -114,9 +129,16 @@ export class OneBotFileApi {
|
||||
}
|
||||
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
|
||||
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
|
||||
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
|
||||
const usePacketVideoMetadata = context.usePacketVideoMetadata === true;
|
||||
const thumbExtension = usePacketVideoMetadata ? 'jpg' : 'png';
|
||||
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.${thumbExtension}`);
|
||||
try {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
|
||||
if (usePacketVideoMetadata) {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
|
||||
} else {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, '');
|
||||
await FFmpegService.extractLegacyVideoThumbnail(filePath, thumbPath);
|
||||
}
|
||||
if (!fs.existsSync(thumbPath)) {
|
||||
this.core.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
|
||||
throw new Error('获取视频缩略图失败');
|
||||
@@ -135,9 +157,18 @@ export class OneBotFileApi {
|
||||
context.deleteAfterSentFiles.push(thumbPath);
|
||||
const thumbSize = (await fsPromises.stat(thumbPath)).size;
|
||||
const thumbMd5 = await calculateFileMD5(thumbPath);
|
||||
context.deleteAfterSentFiles.push(thumbPath);
|
||||
|
||||
const uploadName = (fileName || _fileName).toLocaleLowerCase().endsWith(`.${fileExt.toLocaleLowerCase()}`) ? (fileName || _fileName) : `${fileName || _fileName}.${fileExt}`;
|
||||
const videoMetadata = usePacketVideoMetadata
|
||||
? {
|
||||
fileTime: Math.max(0, Math.round(videoInfo.time)),
|
||||
fileFormat: videoFormatByExtension[fileExt.toLowerCase()] ?? NTVideoType.VIDEO_FORMAT_MP4,
|
||||
fileWidth: videoInfo.width,
|
||||
fileHeight: videoInfo.height,
|
||||
}
|
||||
: {
|
||||
fileTime: videoInfo.time,
|
||||
};
|
||||
return {
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: '',
|
||||
@@ -146,7 +177,7 @@ export class OneBotFileApi {
|
||||
filePath: path,
|
||||
videoMd5: md5,
|
||||
thumbMd5,
|
||||
fileTime: videoInfo.time,
|
||||
...videoMetadata,
|
||||
thumbPath: new Map([[0, thumbPath]]),
|
||||
thumbSize,
|
||||
thumbWidth: videoInfo.width,
|
||||
|
||||
@@ -74,6 +74,7 @@ type Ob11ToRawConverters = {
|
||||
export type SendMessageContext = {
|
||||
deleteAfterSentFiles: string[],
|
||||
peer: Peer;
|
||||
usePacketVideoMetadata?: boolean;
|
||||
};
|
||||
|
||||
export type RecvMessageContext = {
|
||||
@@ -278,7 +279,7 @@ export class OneBotMsgApi {
|
||||
};
|
||||
},
|
||||
|
||||
replyElement: async (element, msg, _, quick_reply) => {
|
||||
replyElement: async (element, msg, _, { quick_reply }) => {
|
||||
const peer = {
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
@@ -310,9 +311,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, msgTime, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
if (quick_reply) {
|
||||
@@ -327,9 +328,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, 1, true, true
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
@@ -341,9 +342,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
@@ -859,12 +860,23 @@ export class OneBotMsgApi {
|
||||
// 获取签名服务地址
|
||||
let signUrl = this.obContext.configLoader.configData.musicSignUrl;
|
||||
if (!signUrl) {
|
||||
signUrl = 'https://ss.xingzhige.com/music_card/card';// 感谢思思!已获思思许可 其余地方使用请自行询问
|
||||
signUrl = 'http://106.55.0.102:10087/'; // 首选,yibai音卡签名,已更换稳定签名服务器
|
||||
}
|
||||
|
||||
// 请求签名服务
|
||||
try {
|
||||
const musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
|
||||
let musicJson: string;
|
||||
try {
|
||||
musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
|
||||
} catch {
|
||||
// 首选失败,降级到备选
|
||||
this.core.context.logger.logError('[音乐卡片签名] 首选地址失败,尝试备选地址...');
|
||||
musicJson = await RequestUtil.HttpGetJson<string>(
|
||||
'https://ss.xingzhige.com/music_card/card', // 思思的音卡签名
|
||||
'POST',
|
||||
postData
|
||||
);
|
||||
}
|
||||
return this.ob11ToRawConverters.json({
|
||||
data: { data: musicJson },
|
||||
type: OB11MessageDataType.json,
|
||||
@@ -1219,7 +1231,10 @@ export class OneBotMsgApi {
|
||||
async createSendElements (
|
||||
messageData: OB11MessageData[],
|
||||
peer: Peer,
|
||||
ignoreTypes: OB11MessageDataType[] = []
|
||||
ignoreTypes: OB11MessageDataType[] = [],
|
||||
options: {
|
||||
usePacketVideoMetadata?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
const deleteAfterSentFiles: string[] = [];
|
||||
const callResultList: Array<Promise<SendMessageElement | undefined>> = [];
|
||||
@@ -1236,7 +1251,11 @@ export class OneBotMsgApi {
|
||||
}
|
||||
const callResult = converter(
|
||||
sendMsg,
|
||||
{ peer, deleteAfterSentFiles }
|
||||
{
|
||||
peer,
|
||||
deleteAfterSentFiles,
|
||||
usePacketVideoMetadata: options.usePacketVideoMetadata,
|
||||
}
|
||||
)?.catch(undefined);
|
||||
callResultList.push(callResult);
|
||||
}
|
||||
|
||||
@@ -73,7 +73,12 @@ export function encodeCQCode (data: OB11MessageData) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const text = value?.toString();
|
||||
let text: string | undefined;
|
||||
if (typeof value === 'object' && value?.toString === Object.prototype.toString) {
|
||||
text = JSON.stringify(value);
|
||||
} else {
|
||||
text = value?.toString();
|
||||
}
|
||||
if (text) {
|
||||
result += `,${name}=${CQCodeEscape(text)}`;
|
||||
}
|
||||
|
||||
+107
-23
@@ -65,6 +65,10 @@ interface ApiListType {
|
||||
QuickActionApi: OneBotQuickActionApi;
|
||||
FileApi: OneBotFileApi;
|
||||
}
|
||||
|
||||
const RECALL_EVENT_DEDUP_MAX_SIZE = 1_000;
|
||||
const RECALL_UPDATE_CLOCK_SKEW_SECONDS = 30;
|
||||
|
||||
// OneBot实现类
|
||||
export class NapCatOneBot11Adapter {
|
||||
readonly core: NapCatCore;
|
||||
@@ -76,6 +80,8 @@ export class NapCatOneBot11Adapter {
|
||||
actions: ActionMap;
|
||||
private readonly bootTime = Date.now() / 1000;
|
||||
recallEventCache = new Map<string, NodeJS.Timeout>();
|
||||
private readonly reportedRecallEventCache = new Map<string, true>();
|
||||
private readonly processingRecallEvents = new Map<string, Promise<void>>();
|
||||
constructor (core: NapCatCore, context: InstanceContext, pathWrapper: NapCatPathWrapper) {
|
||||
this.core = core;
|
||||
this.context = context;
|
||||
@@ -384,36 +390,34 @@ export class NapCatOneBot11Adapter {
|
||||
this.context.logger.logError('处理发送消息失败', error);
|
||||
}
|
||||
};
|
||||
|
||||
msgListener.onMsgInfoListUpdate = async (msgList: RawMessage[]) => {
|
||||
for (const msg of msgList) {
|
||||
const element = this.getRecallElement(msg);
|
||||
if (element && this.isCurrentRecallUpdate(msg)) {
|
||||
// The gray-tip update is authoritative; the recall callback's sequence query can return a newer message.
|
||||
await this.handleRecallMessage(msg, element);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
msgListener.onMsgRecall = async (chatType: ChatType, uid: string, msgSeq: string) => {
|
||||
const peer: Peer = {
|
||||
chatType,
|
||||
peerUid: uid,
|
||||
guildId: '',
|
||||
};
|
||||
let msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList.find(e => e.msgType === NTMsgType.KMSGTYPEGRAYTIPS);
|
||||
const element = msg?.elements.find(e => !!e.grayTipElement?.revokeElement);
|
||||
if (msg && element?.grayTipElement?.revokeElement.isSelfOperate) {
|
||||
const isSelfDevice = this.recallEventCache.has(msg.msgId);
|
||||
if (isSelfDevice) {
|
||||
await this.core.eventWrapper.registerListen('NodeIKernelMsgListener/onMsgRecall',
|
||||
(chatType: ChatType, uid: string, msgSeq: string) => {
|
||||
return chatType === msg?.chatType && uid === msg?.peerUid && msgSeq === msg?.msgSeq;
|
||||
}
|
||||
).catch(() => {
|
||||
msg = undefined;
|
||||
this.context.logger.logDebug('自操作消息撤回事件');
|
||||
});
|
||||
}
|
||||
}
|
||||
if (msg && element) {
|
||||
const recallEvent = await this.emitRecallMsg(msg, element);
|
||||
try {
|
||||
if (recallEvent) {
|
||||
await this.networkManager.emitEvent(recallEvent);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('处理消息撤回失败', e);
|
||||
try {
|
||||
const msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList
|
||||
.find(message => this.getRecallElement(message));
|
||||
const element = msg && this.getRecallElement(msg);
|
||||
if (msg && element) {
|
||||
await this.handleRecallMessage(msg, element);
|
||||
} else {
|
||||
this.context.logger.logDebug(`撤回回调暂未查询到灰条消息,等待消息更新: ${chatType}/${uid}/${msgSeq}`);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('查询撤回消息失败', e);
|
||||
}
|
||||
};
|
||||
msgListener.onKickedOffLine = async (kick) => {
|
||||
@@ -662,6 +666,86 @@ export class NapCatOneBot11Adapter {
|
||||
}
|
||||
}
|
||||
|
||||
private getRecallElement (message: RawMessage): MessageElement | undefined {
|
||||
if (message.msgType !== NTMsgType.KMSGTYPEGRAYTIPS) {
|
||||
return undefined;
|
||||
}
|
||||
return message.elements.find(element => !!element.grayTipElement?.revokeElement);
|
||||
}
|
||||
|
||||
private isCurrentRecallUpdate (message: RawMessage): boolean {
|
||||
const recallTime = Number(message.recallTime);
|
||||
if (!Number.isFinite(recallTime) || recallTime <= 0) {
|
||||
return false;
|
||||
}
|
||||
const recallTimeInSeconds = recallTime > 10_000_000_000 ? recallTime / 1000 : recallTime;
|
||||
return recallTimeInSeconds >= this.bootTime - RECALL_UPDATE_CLOCK_SKEW_SECONDS;
|
||||
}
|
||||
|
||||
private getRecallEventKey (message: RawMessage): string {
|
||||
return `${message.chatType}/${message.peerUid}/${message.msgId}`;
|
||||
}
|
||||
|
||||
private hasReportedRecallEvent (key: string): boolean {
|
||||
return this.reportedRecallEventCache.has(key);
|
||||
}
|
||||
|
||||
private markRecallEventReported (key: string): void {
|
||||
this.reportedRecallEventCache.delete(key);
|
||||
this.reportedRecallEventCache.set(key, true);
|
||||
while (this.reportedRecallEventCache.size > RECALL_EVENT_DEDUP_MAX_SIZE) {
|
||||
const oldestKey = this.reportedRecallEventCache.keys().next().value;
|
||||
if (oldestKey === undefined) break;
|
||||
this.reportedRecallEventCache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleRecallMessage (message: RawMessage, element: MessageElement): Promise<void> {
|
||||
const revokeElement = element.grayTipElement?.revokeElement;
|
||||
if (!revokeElement) return;
|
||||
|
||||
if (revokeElement.isSelfOperate) {
|
||||
const selfRecallTimeout = this.recallEventCache.get(message.msgId);
|
||||
if (selfRecallTimeout) {
|
||||
clearTimeout(selfRecallTimeout);
|
||||
this.recallEventCache.delete(message.msgId);
|
||||
this.context.logger.logDebug('自操作消息撤回事件');
|
||||
}
|
||||
}
|
||||
|
||||
const key = this.getRecallEventKey(message);
|
||||
while (!this.hasReportedRecallEvent(key)) {
|
||||
const processing = this.processingRecallEvents.get(key);
|
||||
if (processing) {
|
||||
// A duplicate callback becomes the retry path if the in-flight report fails.
|
||||
await processing;
|
||||
continue;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
const recallEvent = await this.emitRecallMsg(message, element);
|
||||
if (recallEvent) {
|
||||
await this.networkManager.emitEvent(recallEvent);
|
||||
this.markRecallEventReported(key);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('处理消息撤回失败', e);
|
||||
}
|
||||
})();
|
||||
|
||||
this.processingRecallEvents.set(key, task);
|
||||
try {
|
||||
await task;
|
||||
} finally {
|
||||
if (this.processingRecallEvents.get(key) === task) {
|
||||
this.processingRecallEvents.delete(key);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async emitRecallMsg (message: RawMessage, element: MessageElement) {
|
||||
const peer: Peer = { chatType: message.chatType, peerUid: message.peerUid, guildId: '' };
|
||||
const oriMessageId = MessageUnique.getShortIdByMsgId(message.msgId) ?? MessageUnique.createUniqueMsgId(peer, message.msgId);
|
||||
|
||||
@@ -249,7 +249,7 @@ export class PluginLoader {
|
||||
if (hit) {
|
||||
return `sensitive keyword "${hit}"`;
|
||||
}
|
||||
return "not in official plugin whitelist";
|
||||
return 'not in official plugin whitelist';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -247,6 +247,14 @@ async function startWorker (passQuickLogin: boolean = true, secretKey?: string,
|
||||
...(preferredPort ? { NAPCAT_WEBUI_PREFERRED_PORT: String(preferredPort) } : {}),
|
||||
},
|
||||
stdio: isElectron ? 'pipe' : ['inherit', 'pipe', 'pipe', 'ipc'],
|
||||
// --no-sandbox 是 Chromium 开关,仅当子进程完整引导 Electron(未设 ELECTRON_RUN_AS_NODE)时
|
||||
// 才会被解析;纯 Node / Electron node 模式子进程会因 bad option 以退出码 9 拒绝启动
|
||||
// (ELECTRON_RUN_AS_NODE 变量存在即触发 node 模式,与取值无关)
|
||||
...(!isElectron &&
|
||||
process.versions['electron'] &&
|
||||
process.env['ELECTRON_RUN_AS_NODE'] === undefined
|
||||
? { execArgv: ['--no-sandbox'] }
|
||||
: {}),
|
||||
});
|
||||
|
||||
currentWorker = child;
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface IWorkerProcess {
|
||||
export interface ProcessOptions {
|
||||
env: NodeJS.ProcessEnv;
|
||||
stdio: 'pipe' | 'ignore' | 'inherit' | Array<'pipe' | 'ignore' | 'inherit' | 'ipc'>;
|
||||
execArgv?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -168,7 +169,7 @@ export async function createProcessManager (): Promise<{
|
||||
manager: IProcessManager;
|
||||
isElectron: boolean;
|
||||
}> {
|
||||
const isElectron = typeof process.versions['electron'] !== 'undefined';
|
||||
const isElectron = process.env['NAPCAT_FORCE_NODE_PROCESS'] !== '1' && typeof process.versions['electron'] !== 'undefined';
|
||||
|
||||
if (isElectron) {
|
||||
// @ts-ignore - electron 运行时存在但类型声明可能缺失
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import {
|
||||
applyGroupManagementSettings,
|
||||
createGroupDetailInfoV2Param,
|
||||
createGroupManagementRequests,
|
||||
} from '../napcat-core/data/group';
|
||||
import { assertGroupManagementResults } from '../napcat-onebot/action/group/GroupOperationHelpers';
|
||||
|
||||
describe('NTQQ group operations', () => {
|
||||
test('reports the exact native setting that failed', () => {
|
||||
expect(() => assertGroupManagementResults('设置群成员功能权限', [{
|
||||
setting: 'allow_member_create_group',
|
||||
result: { result: 1006, errMsg: '未知错误' },
|
||||
}])).toThrow(/allow_member_create_group.*1006.*未知错误/);
|
||||
expect(() => assertGroupManagementResults('设置群成员功能权限', []))
|
||||
.not.toThrow();
|
||||
});
|
||||
|
||||
test('builds the NTQQ permission masks without changing unrelated flags', async () => {
|
||||
const request = createGroupDetailInfoV2Param('123456');
|
||||
expect(applyGroupManagementSettings(request, {
|
||||
memberInvite: 'no_approval',
|
||||
allowMemberUploadAlbum: false,
|
||||
allowMemberTemporarySession: true,
|
||||
allowMemberCreateGroup: false,
|
||||
newMembersSeeRecentHistory: true,
|
||||
})).toBe(true);
|
||||
expect(request.groupCode).toBe('123456');
|
||||
expect(request.filter).toMatchObject({
|
||||
allowMemberInvite: 1,
|
||||
appPrivilegeFlag: 1,
|
||||
appPrivilegeMask: 1,
|
||||
groupFlagExt4: 1,
|
||||
groupFlagExt4Mask: 1,
|
||||
});
|
||||
expect(request.modifyInfo).toMatchObject({
|
||||
allowMemberInvite: 1,
|
||||
appPrivilegeFlag: 0x00108001,
|
||||
appPrivilegeMask: 0x06118001,
|
||||
groupFlagExt3: 0,
|
||||
groupFlagExt3Mask: 0,
|
||||
groupFlagExt4: 0x4,
|
||||
groupFlagExt4Mask: 0x4,
|
||||
});
|
||||
});
|
||||
|
||||
test('maps every member invite policy to the native app privilege value', async () => {
|
||||
const expected = {
|
||||
disabled: 0x04000000,
|
||||
require_approval: 0,
|
||||
no_approval: 0x00100000,
|
||||
no_approval_under_100: 0x02000000,
|
||||
} as const;
|
||||
|
||||
for (const [memberInvite, privilegeFlag] of Object.entries(expected)) {
|
||||
const request = createGroupDetailInfoV2Param('123456');
|
||||
applyGroupManagementSettings(request, { memberInvite: memberInvite as keyof typeof expected });
|
||||
expect(request.modifyInfo.allowMemberInvite).toBe(memberInvite === 'disabled' ? 0 : 1);
|
||||
expect(request.modifyInfo.appPrivilegeFlag).toBe(privilegeFlag);
|
||||
expect(request.modifyInfo.appPrivilegeMask).toBe(0x06100000);
|
||||
}
|
||||
});
|
||||
|
||||
test('uses NTQQ privilege operation type 8 for album, temporary-session, and create-group flags', () => {
|
||||
const requests = createGroupManagementRequests('123456', {
|
||||
memberInvite: 'require_approval',
|
||||
allowMemberUploadAlbum: true,
|
||||
allowMemberTemporarySession: true,
|
||||
allowMemberCreateGroup: true,
|
||||
}, 0x18001);
|
||||
|
||||
expect(requests.map(request => request.operationType)).toEqual([0, 8, 8, 8]);
|
||||
expect(requests.map(request => request.setting)).toEqual([
|
||||
'member_invite',
|
||||
'allow_member_upload_album',
|
||||
'allow_member_temporary_session',
|
||||
'allow_member_create_group',
|
||||
]);
|
||||
expect(requests.slice(1).map(request => request.param.modifyInfo.appPrivilegeMask))
|
||||
.toEqual([0x1, 0x10000, 0x8000]);
|
||||
expect(requests[1]?.param.modifyInfo).toMatchObject({
|
||||
appPrivilegeFlag: 0x18000,
|
||||
appPrivilegeMask: 0x1,
|
||||
groupFlagExt3: 0,
|
||||
groupFlagExt3Mask: 0,
|
||||
});
|
||||
expect(requests[2]?.param.modifyInfo).toMatchObject({
|
||||
appPrivilegeFlag: 0x8000,
|
||||
appPrivilegeMask: 0x10000,
|
||||
groupFlagExt3: 0,
|
||||
groupFlagExt3Mask: 0,
|
||||
});
|
||||
expect(requests[3]?.param.modifyInfo).toMatchObject({
|
||||
appPrivilegeFlag: 0,
|
||||
appPrivilegeMask: 0x8000,
|
||||
groupFlagExt3: 0,
|
||||
groupFlagExt3Mask: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test('preserves the complete privilege value when clearing Linux NTQQ permission bits', () => {
|
||||
const requests = createGroupManagementRequests('123456', {
|
||||
allowMemberUploadAlbum: false,
|
||||
allowMemberTemporarySession: false,
|
||||
allowMemberCreateGroup: false,
|
||||
}, 0);
|
||||
|
||||
expect(requests.map(request => request.param.modifyInfo.appPrivilegeFlag))
|
||||
.toEqual([0x1, 0x10001, 0x18001]);
|
||||
expect(requests.map(request => request.param.modifyInfo.appPrivilegeMask))
|
||||
.toEqual([0x1, 0x10000, 0x8000]);
|
||||
});
|
||||
|
||||
test('skips privilege requests whose effective value is already current', () => {
|
||||
const requests = createGroupManagementRequests('123456', {
|
||||
allowMemberUploadAlbum: true,
|
||||
allowMemberTemporarySession: true,
|
||||
allowMemberCreateGroup: true,
|
||||
newMembersSeeRecentHistory: true,
|
||||
}, 0x00100000, 0x4);
|
||||
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import {
|
||||
buildQzoneDeleteBody,
|
||||
buildQzonePublishBody,
|
||||
buildQzoneUploadImageBody,
|
||||
parseQzoneDeleteResponse,
|
||||
parseQzonePublishResponse,
|
||||
parseQzoneUploadImageResponseText,
|
||||
toQzoneRichval,
|
||||
} from '@/napcat-core/data/qzone';
|
||||
|
||||
describe('Qzone data helpers', () => {
|
||||
test('buildQzoneUploadImageBody encodes required fields', () => {
|
||||
const body = buildQzoneUploadImageBody({
|
||||
uin: '123456',
|
||||
skey: 'sk',
|
||||
pskey: 'pk',
|
||||
g_tk: '999',
|
||||
base64: 'AAAA',
|
||||
});
|
||||
const params = new URLSearchParams(body);
|
||||
expect(params.get('uin')).toBe('123456');
|
||||
expect(params.get('skey')).toBe('sk');
|
||||
expect(params.get('p_skey')).toBe('pk');
|
||||
expect(params.get('picfile')).toBe('AAAA');
|
||||
expect(params.get('uploadtype')).toBe('1');
|
||||
expect(params.get('albumtype')).toBe('7');
|
||||
expect(params.get('base64')).toBe('1');
|
||||
expect(params.get('qzreferrer')).toContain('123456');
|
||||
});
|
||||
|
||||
test('parseQzoneUploadImageResponseText parses valid callback wrapper', () => {
|
||||
const raw = 'frameElement.callback({"code":0,"data":{"albumid":"a1","lloc":"l1","type":"22","height":"100","width":"200"}});</script>';
|
||||
const parsed = parseQzoneUploadImageResponseText(raw);
|
||||
expect(parsed.code).toBe(0);
|
||||
expect(parsed.data?.albumid).toBe('a1');
|
||||
expect(parsed.data?.lloc).toBe('l1');
|
||||
});
|
||||
|
||||
test('parseQzoneUploadImageResponseText throws on malformed response', () => {
|
||||
expect(() => parseQzoneUploadImageResponseText('not a valid response')).toThrow();
|
||||
});
|
||||
|
||||
test('toQzoneRichval builds expected format', () => {
|
||||
const richval = toQzoneRichval({ albumid: 'a1', lloc: 'l1', type: '22', height: '100', width: '200' });
|
||||
expect(richval).toBe(',a1,l1,l1,22,100,200,,100,200');
|
||||
});
|
||||
|
||||
test('buildQzonePublishBody without images omits richval/richtype', () => {
|
||||
const body = buildQzonePublishBody({
|
||||
hostuin: '123456',
|
||||
content: 'hello world',
|
||||
ugcRight: 1,
|
||||
});
|
||||
const params = new URLSearchParams(body);
|
||||
expect(params.get('con')).toBe('hello world');
|
||||
expect(params.get('ugc_right')).toBe('1');
|
||||
expect(params.has('richval')).toBe(false);
|
||||
expect(params.has('richtype')).toBe(false);
|
||||
expect(params.has('allow_uins')).toBe(false);
|
||||
});
|
||||
|
||||
test('buildQzonePublishBody with images and allow_uins sets richtype and who', () => {
|
||||
const body = buildQzonePublishBody({
|
||||
hostuin: '123456',
|
||||
content: 'with pic',
|
||||
richval: ',a1,l1,l1,22,100,200,,100,200\t,a2,l2,l2,22,100,200,,100,200',
|
||||
ugcRight: 16,
|
||||
allowUins: '10001|10002',
|
||||
});
|
||||
const params = new URLSearchParams(body);
|
||||
expect(params.get('richtype')).toBe('1');
|
||||
expect(params.get('richval')).toContain('\t');
|
||||
expect(params.get('ugc_right')).toBe('16');
|
||||
expect(params.get('allow_uins')).toBe('10001|10002');
|
||||
expect(params.get('who')).toBe('1');
|
||||
});
|
||||
|
||||
test('parseQzonePublishResponse extracts tid on success', () => {
|
||||
const result = parseQzonePublishResponse({ subcode: 0, tid: 'tid123' });
|
||||
expect(result.tid).toBe('tid123');
|
||||
});
|
||||
|
||||
test('parseQzonePublishResponse prefers t1_tid over tid', () => {
|
||||
const result = parseQzonePublishResponse({ subcode: 0, tid: 'tid123', t1_tid: 't1tid456' });
|
||||
expect(result.tid).toBe('t1tid456');
|
||||
});
|
||||
|
||||
test('parseQzonePublishResponse throws when subcode indicates failure', () => {
|
||||
expect(() => parseQzonePublishResponse({ subcode: -200, message: '权限不足' })).toThrow('权限不足');
|
||||
});
|
||||
|
||||
test('parseQzonePublishResponse throws when tid missing', () => {
|
||||
expect(() => parseQzonePublishResponse({ subcode: 0 })).toThrow();
|
||||
});
|
||||
|
||||
test('buildQzoneDeleteBody encodes required fields', () => {
|
||||
const body = buildQzoneDeleteBody({ hostuin: '123456', tid: 'tid123' });
|
||||
const params = new URLSearchParams(body);
|
||||
expect(params.get('hostuin')).toBe('123456');
|
||||
expect(params.get('tid')).toBe('tid123');
|
||||
expect(params.get('t1_source')).toBe('1');
|
||||
expect(params.get('code_version')).toBe('1');
|
||||
expect(params.get('format')).toBe('json');
|
||||
expect(params.get('qzreferrer')).toContain('123456');
|
||||
});
|
||||
|
||||
test('parseQzoneDeleteResponse succeeds when subcode is 0', () => {
|
||||
const result = parseQzoneDeleteResponse({ subcode: 0 });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
test('parseQzoneDeleteResponse throws when subcode indicates failure', () => {
|
||||
expect(() => parseQzoneDeleteResponse({ subcode: -200, message: '权限不足' })).toThrow('权限不足');
|
||||
});
|
||||
|
||||
test('parseQzoneDeleteResponse throws with default message when subcode indicates failure without message', () => {
|
||||
expect(() => parseQzoneDeleteResponse({ subcode: -200 })).toThrow('subcode=-200');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,309 @@
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import { ChatType, NTMsgType, type RawMessage } from 'napcat-core';
|
||||
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
|
||||
|
||||
vi.mock('../napcat-webui-backend/index', () => ({
|
||||
pendingTokenToSend: undefined,
|
||||
}));
|
||||
|
||||
vi.mock('../napcat-webui-backend/src/helper/Data', () => ({
|
||||
WebUiDataRuntime: {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/config', () => ({
|
||||
OB11ConfigLoader: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network', () => ({
|
||||
OB11HttpClientAdapter: class {},
|
||||
OB11WebSocketClientAdapter: class {},
|
||||
OB11NetworkManager: class {},
|
||||
OB11NetworkReloadType: {},
|
||||
OB11HttpServerAdapter: class {},
|
||||
OB11WebSocketServerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/api', () => ({
|
||||
OneBotFriendApi: class {},
|
||||
OneBotGroupApi: class {},
|
||||
OneBotMsgApi: class {},
|
||||
OneBotQuickActionApi: class {},
|
||||
OneBotUserApi: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/action', () => ({
|
||||
createActionMap: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/adapter', () => ({
|
||||
IOB11NetworkAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/http-server-sse', () => ({
|
||||
OB11HttpSSEServerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/plugin-manger', () => ({
|
||||
OB11PluginMangerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/api/file', () => ({
|
||||
OneBotFileApi: class {},
|
||||
}));
|
||||
|
||||
interface TestMsgListener {
|
||||
onMsgRecall (chatType: ChatType, uid: string, msgSeq: string): Promise<void> | void;
|
||||
onMsgInfoListUpdate (messages: RawMessage[]): Promise<void> | void;
|
||||
}
|
||||
|
||||
const friendUid = 'u_friend';
|
||||
const friendUin = '123456';
|
||||
const recalledMsgId = 'recalled-message-id';
|
||||
const recalledMsgSeq = '100';
|
||||
const botUin = '999999';
|
||||
|
||||
function createMessage (overrides: Partial<RawMessage>): RawMessage {
|
||||
return {
|
||||
msgId: 'message-id',
|
||||
msgRandom: '1',
|
||||
msgSeq: '101',
|
||||
cntSeq: '101',
|
||||
chatType: ChatType.KCHATTYPEC2C,
|
||||
msgType: NTMsgType.KMSGTYPEUNKNOWN,
|
||||
subMsgType: 0,
|
||||
sendStatus: 2,
|
||||
senderUid: friendUid,
|
||||
senderUin: friendUin,
|
||||
peerUid: friendUid,
|
||||
peerUin: friendUin,
|
||||
peerName: 'friend',
|
||||
sendNickName: 'friend',
|
||||
sendRemarkName: 'friend',
|
||||
msgTime: '1',
|
||||
recallTime: '0',
|
||||
elements: [],
|
||||
records: [],
|
||||
sourceType: 0,
|
||||
isOnlineMsg: true,
|
||||
...overrides,
|
||||
} as RawMessage;
|
||||
}
|
||||
|
||||
function createRecallGrayTip (): RawMessage {
|
||||
return createMessage({
|
||||
msgId: recalledMsgId,
|
||||
msgSeq: recalledMsgSeq,
|
||||
msgType: NTMsgType.KMSGTYPEGRAYTIPS,
|
||||
recallTime: Math.floor(Date.now() / 1000).toString(),
|
||||
elements: [{
|
||||
elementType: 8,
|
||||
elementId: 'recall-element',
|
||||
grayTipElement: {
|
||||
revokeElement: {
|
||||
operatorRole: '0',
|
||||
operatorUid: friendUid,
|
||||
operatorNick: 'friend',
|
||||
operatorRemark: '',
|
||||
isSelfOperate: false,
|
||||
wording: '',
|
||||
},
|
||||
},
|
||||
} as unknown as RawMessage['elements'][number]],
|
||||
});
|
||||
}
|
||||
|
||||
function createHarness (queryResult: RawMessage[], operatorUin = '654321') {
|
||||
let listener: TestMsgListener | undefined;
|
||||
const emitEvent = vi.fn(async (_event: unknown): Promise<void> => undefined);
|
||||
const queryMsgsWithFilterExWithSeq = vi.fn(async () => ({ msgList: queryResult }));
|
||||
const registerListen = vi.fn();
|
||||
const logger = {
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logMessage: vi.fn(),
|
||||
};
|
||||
const context = {
|
||||
logger,
|
||||
session: {
|
||||
getMsgService: () => ({
|
||||
addKernelMsgListener: (registeredListener: TestMsgListener) => {
|
||||
listener = registeredListener;
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
const core = {
|
||||
selfInfo: { uin: botUin },
|
||||
apis: {
|
||||
MsgApi: { queryMsgsWithFilterExWithSeq },
|
||||
UserApi: { getUinByUidV2: vi.fn(async () => operatorUin) },
|
||||
},
|
||||
eventWrapper: { registerListen },
|
||||
};
|
||||
const adapter = Object.create(NapCatOneBot11Adapter.prototype) as NapCatOneBot11Adapter;
|
||||
|
||||
Object.assign(adapter, {
|
||||
core,
|
||||
context,
|
||||
networkManager: { emitEvent },
|
||||
bootTime: Date.now() / 1000,
|
||||
recallEventCache: new Map(),
|
||||
reportedRecallEventCache: new Map(),
|
||||
processingRecallEvents: new Map(),
|
||||
});
|
||||
|
||||
(adapter as unknown as { initMsgListener (): void }).initMsgListener();
|
||||
|
||||
if (!listener) {
|
||||
throw new Error('message listener was not registered');
|
||||
}
|
||||
|
||||
return { adapter, listener, emitEvent, logger, queryMsgsWithFilterExWithSeq, registerListen };
|
||||
}
|
||||
|
||||
describe('friend recall reporting', () => {
|
||||
test('reports a recalled non-latest private message from its gray-tip update', async () => {
|
||||
const botReply = createMessage({
|
||||
msgId: 'bot-reply-id',
|
||||
msgSeq: '101',
|
||||
senderUid: 'u_bot',
|
||||
senderUin: botUin,
|
||||
});
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent } = createHarness([botReply]);
|
||||
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
expect(emitEvent).toHaveBeenCalledWith(expect.objectContaining({
|
||||
notice_type: 'friend_recall',
|
||||
user_id: Number(friendUin),
|
||||
}));
|
||||
});
|
||||
|
||||
test('deduplicates the same recall from the gray-tip update and recall callback', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent } = createHarness([grayTip]);
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('deduplicates concurrent update and callback processing', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent } = createHarness([grayTip]);
|
||||
let finishEmit: (() => void) | undefined;
|
||||
emitEvent.mockImplementationOnce(() => new Promise<void>((resolve) => {
|
||||
finishEmit = resolve;
|
||||
}));
|
||||
|
||||
const updateTask = listener.onMsgInfoListUpdate([grayTip]);
|
||||
await vi.waitFor(() => expect(emitEvent).toHaveBeenCalledTimes(1));
|
||||
const callbackTask = listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
|
||||
finishEmit?.();
|
||||
await Promise.all([updateTask, callbackTask]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('uses a concurrent duplicate callback to retry a failed report', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent, logger } = createHarness([grayTip]);
|
||||
let failFirstEmit: (() => void) | undefined;
|
||||
emitEvent
|
||||
.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
|
||||
failFirstEmit = () => reject(new Error('network unavailable'));
|
||||
}))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
|
||||
const updateTask = listener.onMsgInfoListUpdate([grayTip]);
|
||||
await vi.waitFor(() => expect(emitEvent).toHaveBeenCalledTimes(1));
|
||||
const callbackTask = listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
|
||||
failFirstEmit?.();
|
||||
await Promise.all([updateTask, callbackTask]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(2);
|
||||
expect(logger.logError).toHaveBeenCalledWith('处理消息撤回失败', expect.any(Error));
|
||||
});
|
||||
|
||||
test('reports one self recall without waiting for a duplicate callback', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const revokeElement = grayTip.elements[0]?.grayTipElement?.revokeElement;
|
||||
if (!revokeElement) throw new Error('missing revoke element');
|
||||
revokeElement.isSelfOperate = true;
|
||||
|
||||
const { adapter, listener, emitEvent, registerListen } = createHarness([grayTip]);
|
||||
const originTimeout = setTimeout(() => undefined, 60_000);
|
||||
adapter.recallEventCache.set(recalledMsgId, originTimeout);
|
||||
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
expect(adapter.recallEventCache.has(recalledMsgId)).toBe(false);
|
||||
expect(registerListen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('retries reporting when the first network emission fails', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent, logger } = createHarness([grayTip]);
|
||||
emitEvent
|
||||
.mockRejectedValueOnce(new Error('network unavailable'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(2);
|
||||
expect(logger.logError).toHaveBeenCalledWith('处理消息撤回失败', expect.any(Error));
|
||||
});
|
||||
|
||||
test('ignores historical recall rows replayed during startup sync', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
grayTip.recallTime = Math.floor(Date.now() / 1000 - 120).toString();
|
||||
const { listener, emitEvent } = createHarness([]);
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('ignores ordinary message updates', async () => {
|
||||
const ordinaryMessage = createMessage({ recallTime: Math.floor(Date.now() / 1000).toString() });
|
||||
const { listener, emitEvent } = createHarness([]);
|
||||
|
||||
await listener.onMsgInfoListUpdate([ordinaryMessage]);
|
||||
|
||||
expect(emitEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('group recall reporting', () => {
|
||||
test('preserves group, sender and operator fields', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const groupUin = '112233';
|
||||
const senderUin = '223344';
|
||||
grayTip.chatType = ChatType.KCHATTYPEGROUP;
|
||||
grayTip.peerUid = groupUin;
|
||||
grayTip.peerUin = groupUin;
|
||||
grayTip.senderUin = senderUin;
|
||||
|
||||
const { listener, emitEvent } = createHarness([], '334455');
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
expect(emitEvent).toHaveBeenCalledWith(expect.objectContaining({
|
||||
notice_type: 'group_recall',
|
||||
group_id: Number(groupUin),
|
||||
user_id: Number(senderUin),
|
||||
operator_id: 334455,
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import { ElementType, NTVideoType } from '@/napcat-core/types/msg';
|
||||
import { SendVideoElement } from '@/napcat-core/types/element';
|
||||
import {
|
||||
PacketMsgPicElement,
|
||||
PacketMsgVideoElement,
|
||||
} from '@/napcat-core/packet/message/element';
|
||||
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
|
||||
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
|
||||
import { Elem, MsgInfo } from '@/napcat-core/packet/transformer/proto';
|
||||
import { NTV2RichMediaReq } from '@/napcat-core/packet/transformer/proto/oidb/common/Ntv2.RichMediaReq';
|
||||
import UploadGroupVideo from '@/napcat-core/packet/transformer/highway/UploadGroupVideo';
|
||||
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
function createVideoMsgInfo (): NapProtoEncodeStructType<typeof MsgInfo> {
|
||||
return {
|
||||
msgInfoBody: [
|
||||
{
|
||||
index: {
|
||||
info: {
|
||||
fileSize: 1024,
|
||||
fileHash: '00112233445566778899aabbccddeeff',
|
||||
fileSha1: '00112233445566778899aabbccddeeff00112233',
|
||||
fileName: 'clip.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
videoFormat: NTVideoType.VIDEO_FORMAT_MP4,
|
||||
},
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
time: 12,
|
||||
},
|
||||
fileUuid: 'video-uuid',
|
||||
},
|
||||
},
|
||||
{
|
||||
index: {
|
||||
info: {
|
||||
fileSize: 2048,
|
||||
fileHash: 'ffeeddccbbaa99887766554433221100',
|
||||
fileSha1: 'ffeeddccbbaa99887766554433221100ffeeddcc',
|
||||
fileName: 'thumb.jpg',
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
},
|
||||
width: 640,
|
||||
height: 360,
|
||||
},
|
||||
fileUuid: 'thumb-uuid',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function createSendVideoElement (): SendVideoElement {
|
||||
return {
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: '',
|
||||
videoElement: {
|
||||
filePath: 'clip.mp4',
|
||||
fileName: 'clip.mp4',
|
||||
videoMd5: '00112233445566778899aabbccddeeff',
|
||||
thumbMd5: 'ffeeddccbbaa99887766554433221100',
|
||||
fileTime: 12,
|
||||
fileFormat: NTVideoType.VIDEO_FORMAT_MP4,
|
||||
fileSize: '1024',
|
||||
fileWidth: 1920,
|
||||
fileHeight: 1080,
|
||||
thumbWidth: 640,
|
||||
thumbHeight: 360,
|
||||
thumbSize: 2048,
|
||||
thumbPath: new Map([[0, 'thumb.jpg']]),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function decodeElem (
|
||||
elem: NapProtoEncodeStructType<typeof Elem>
|
||||
): NapProtoDecodeStructType<typeof Elem> {
|
||||
const codec = new NapProtoMsg(Elem);
|
||||
return codec.decode(codec.encode(elem));
|
||||
}
|
||||
|
||||
function createCommonVideoElem (businessType: 11 | 21): NapProtoDecodeStructType<typeof Elem> {
|
||||
return decodeElem({
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
businessType,
|
||||
pbElem: new NapProtoMsg(MsgInfo).encode(createVideoMsgInfo()),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('packet video forwarding', () => {
|
||||
it('emits only the common rich-media element so mobile rendering is not blocked', () => {
|
||||
const video = new PacketMsgVideoElement(createSendVideoElement());
|
||||
video.msgInfo = createVideoMsgInfo();
|
||||
video.businessType = 11;
|
||||
|
||||
const elems = video.buildElement();
|
||||
|
||||
expect(elems).toHaveLength(1);
|
||||
expect(elems[0]?.videoFile).toBeUndefined();
|
||||
expect(elems[0]?.commonElem?.serviceType).toBe(48);
|
||||
expect(elems[0]?.commonElem?.businessType).toBe(11);
|
||||
expect(video.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('parses common business type 11/21 as video instead of image', () => {
|
||||
for (const businessType of [11, 21] as const) {
|
||||
const commonElem = createCommonVideoElem(businessType);
|
||||
expect(PacketMsgPicElement.parseElement(commonElem)).toBeUndefined();
|
||||
|
||||
const parsed = new PacketMsgConverter().packetMsgToRaw([commonElem]);
|
||||
|
||||
expect(parsed).toHaveLength(1);
|
||||
expect(parsed[0]?.[0].elementType).toBe(ElementType.VIDEO);
|
||||
expect(parsed[0]?.[0].picElement).toBeUndefined();
|
||||
expect(parsed[0]?.[0].videoElement).toMatchObject({
|
||||
fileName: 'clip.mp4',
|
||||
fileTime: 12,
|
||||
fileWidth: 1920,
|
||||
fileHeight: 1080,
|
||||
thumbWidth: 640,
|
||||
thumbHeight: 360,
|
||||
fileUuid: 'video-uuid',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('preserves video metadata in the rich-media upload request', () => {
|
||||
const video = new PacketMsgVideoElement(createSendVideoElement());
|
||||
video.fileSha1 = '00112233445566778899aabbccddeeff00112233';
|
||||
video.thumbSha1 = 'ffeeddccbbaa99887766554433221100ffeeddcc';
|
||||
|
||||
const packet = UploadGroupVideo.build(123456, video);
|
||||
const envelope = OidbBase.parse(packet.data);
|
||||
const request = new NapProtoMsg(NTV2RichMediaReq).decode(envelope.body);
|
||||
const videoInfo = request.upload?.uploadInfo[0]?.fileInfo;
|
||||
const thumbInfo = request.upload?.uploadInfo[1]?.fileInfo;
|
||||
|
||||
expect(videoInfo).toMatchObject({
|
||||
fileName: 'clip.mp4',
|
||||
fileSize: 1024,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
time: 12,
|
||||
});
|
||||
expect(videoInfo?.type.videoFormat).toBe(NTVideoType.VIDEO_FORMAT_MP4);
|
||||
expect(thumbInfo?.fileName).toBe('ffeeddccbbaa99887766554433221100.jpg');
|
||||
});
|
||||
|
||||
it('propagates resource upload failures instead of silently continuing', () => {
|
||||
const uploadError = new Error('thumb upload failed');
|
||||
const logger = {
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
};
|
||||
|
||||
expect(() => assertUploadResults([
|
||||
{ status: 'fulfilled', value: undefined },
|
||||
{ status: 'rejected', reason: uploadError },
|
||||
], logger)).toThrow('上传转发消息资源失败');
|
||||
expect(logger.warn).toHaveBeenCalledWith('上传资源2个,失败1个');
|
||||
expect(logger.error).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { OneBotFileApi } from '@/napcat-onebot/api/file';
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { NTVideoType } from '@/napcat-core/types/msg';
|
||||
|
||||
const MP4_HEADER = Buffer.from([
|
||||
0x00, 0x00, 0x00, 0x18,
|
||||
0x66, 0x74, 0x79, 0x70,
|
||||
0x69, 0x73, 0x6f, 0x6d,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x69, 0x73, 0x6f, 0x6d,
|
||||
]);
|
||||
const PNG_HEADER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
const JPEG_HEADER = Buffer.from([0xff, 0xd8, 0xff, 0xe0]);
|
||||
|
||||
describe('OneBot video send modes', () => {
|
||||
let tempDir: string;
|
||||
let sourceVideoPath: string;
|
||||
let uploadedVideoPath: string;
|
||||
let fileApi: OneBotFileApi;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(path.join(tmpdir(), 'napcat-video-send-mode-'));
|
||||
sourceVideoPath = path.join(tempDir, 'clip.mp4');
|
||||
uploadedVideoPath = path.join(tempDir, 'cache', 'Ori', 'clip.mp4');
|
||||
await mkdir(path.dirname(uploadedVideoPath), { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(sourceVideoPath, MP4_HEADER),
|
||||
writeFile(uploadedVideoPath, MP4_HEADER),
|
||||
]);
|
||||
|
||||
const core = {
|
||||
NapCatTempPath: tempDir,
|
||||
context: {
|
||||
logger: {
|
||||
logError: vi.fn(),
|
||||
},
|
||||
},
|
||||
apis: {
|
||||
FileApi: {
|
||||
uploadFile: vi.fn().mockResolvedValue({
|
||||
fileName: 'clip.mp4',
|
||||
path: uploadedVideoPath,
|
||||
fileSize: MP4_HEADER.length,
|
||||
md5: '00112233445566778899aabbccddeeff',
|
||||
}),
|
||||
copyFile: vi.fn(),
|
||||
},
|
||||
},
|
||||
} as unknown as ConstructorParameters<typeof OneBotFileApi>[1];
|
||||
|
||||
fileApi = new OneBotFileApi(
|
||||
{} as ConstructorParameters<typeof OneBotFileApi>[0],
|
||||
core
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('uses a PNG thumbnail and legacy minimal metadata for direct kernel sends', async () => {
|
||||
const getVideoInfo = vi.spyOn(FFmpegService, 'getVideoInfo').mockResolvedValue({
|
||||
width: 480,
|
||||
height: 852,
|
||||
time: 3.6,
|
||||
format: 'jpg',
|
||||
size: MP4_HEADER.length,
|
||||
filePath: sourceVideoPath,
|
||||
});
|
||||
const extractLegacyThumbnail = vi
|
||||
.spyOn(FFmpegService, 'extractLegacyVideoThumbnail')
|
||||
.mockImplementation(async (_videoPath, thumbnailPath) => {
|
||||
await writeFile(thumbnailPath, PNG_HEADER);
|
||||
});
|
||||
|
||||
const context = {
|
||||
deleteAfterSentFiles: [],
|
||||
peer: {},
|
||||
} as unknown as Parameters<OneBotFileApi['createValidSendVideoElement']>[0];
|
||||
const element = await fileApi.createValidSendVideoElement(context, sourceVideoPath);
|
||||
const thumbnailPath = element.videoElement.thumbPath?.get(0) as string;
|
||||
|
||||
expect(getVideoInfo).toHaveBeenCalledWith(sourceVideoPath, '');
|
||||
expect(extractLegacyThumbnail).toHaveBeenCalledWith(sourceVideoPath, thumbnailPath);
|
||||
expect(path.extname(thumbnailPath)).toBe('.png');
|
||||
expect((await readFile(thumbnailPath)).subarray(0, PNG_HEADER.length)).toEqual(PNG_HEADER);
|
||||
expect(element.videoElement.fileTime).toBe(3.6);
|
||||
expect('fileFormat' in element.videoElement).toBe(false);
|
||||
expect('fileWidth' in element.videoElement).toBe(false);
|
||||
expect('fileHeight' in element.videoElement).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps JPEG thumbnails and complete metadata for packet forward uploads', async () => {
|
||||
const getVideoInfo = vi
|
||||
.spyOn(FFmpegService, 'getVideoInfo')
|
||||
.mockImplementation(async (videoPath, thumbnailPath) => {
|
||||
await writeFile(thumbnailPath, JPEG_HEADER);
|
||||
return {
|
||||
width: 480,
|
||||
height: 852,
|
||||
time: 3.6,
|
||||
format: 'jpg',
|
||||
size: MP4_HEADER.length,
|
||||
filePath: videoPath,
|
||||
};
|
||||
});
|
||||
const extractLegacyThumbnail = vi.spyOn(FFmpegService, 'extractLegacyVideoThumbnail');
|
||||
|
||||
const context = {
|
||||
deleteAfterSentFiles: [],
|
||||
peer: {},
|
||||
usePacketVideoMetadata: true,
|
||||
} as unknown as Parameters<OneBotFileApi['createValidSendVideoElement']>[0];
|
||||
const element = await fileApi.createValidSendVideoElement(context, sourceVideoPath);
|
||||
const thumbnailPath = element.videoElement.thumbPath?.get(0) as string;
|
||||
|
||||
expect(getVideoInfo).toHaveBeenCalledWith(sourceVideoPath, thumbnailPath);
|
||||
expect(extractLegacyThumbnail).not.toHaveBeenCalled();
|
||||
expect(path.extname(thumbnailPath)).toBe('.jpg');
|
||||
expect((await readFile(thumbnailPath)).subarray(0, JPEG_HEADER.length)).toEqual(JPEG_HEADER);
|
||||
expect(element.videoElement.fileTime).toBe(4);
|
||||
expect(element.videoElement.fileFormat).toBe(NTVideoType.VIDEO_FORMAT_MP4);
|
||||
expect(element.videoElement.fileWidth).toBe(480);
|
||||
expect(element.videoElement.fileHeight).toBe(852);
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,7 @@ export class TotpHelper {
|
||||
* @param length 密钥长度(字节),默认16字节
|
||||
* @returns Base32编码的密钥
|
||||
*/
|
||||
static generateSecret(length: number = 16): string {
|
||||
static generateSecret (length: number = 16): string {
|
||||
const buffer = crypto.randomBytes(length);
|
||||
return this.toBase32(buffer);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export class TotpHelper {
|
||||
* @param window 允许的时间窗口(前后各多少个时间步长),默认1
|
||||
* @returns 是否验证通过
|
||||
*/
|
||||
static verifyTotp(
|
||||
static verifyTotp (
|
||||
secret: string,
|
||||
code: string,
|
||||
timeStep: number = 30,
|
||||
@@ -47,7 +47,7 @@ export class TotpHelper {
|
||||
* @param counter 计数器
|
||||
* @returns 6位数字验证码
|
||||
*/
|
||||
private static generateHotp(secret: string, counter: number): string {
|
||||
private static generateHotp (secret: string, counter: number): string {
|
||||
// 将 Base32 密钥转换为字节
|
||||
const key = this.base32ToBytes(secret);
|
||||
|
||||
@@ -93,7 +93,7 @@ export class TotpHelper {
|
||||
* @param issuer 发行方名称
|
||||
* @returns otpauth:// URL
|
||||
*/
|
||||
static generateQrCodeUrl(
|
||||
static generateQrCodeUrl (
|
||||
secret: string,
|
||||
account: string,
|
||||
issuer: string
|
||||
@@ -108,7 +108,7 @@ export class TotpHelper {
|
||||
* @param buffer 字节数组
|
||||
* @returns Base32编码字符串
|
||||
*/
|
||||
private static toBase32(buffer: Buffer): string {
|
||||
private static toBase32 (buffer: Buffer): string {
|
||||
const base32Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
let output = '';
|
||||
|
||||
@@ -138,7 +138,7 @@ export class TotpHelper {
|
||||
* @param base32 Base32编码字符串
|
||||
* @returns 字节数组
|
||||
*/
|
||||
private static base32ToBytes(base32: string): Buffer {
|
||||
private static base32ToBytes (base32: string): Buffer {
|
||||
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
const base32Clean = base32.toUpperCase().replace(/=+$/, '');
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
|
||||
import key from '@/const/key';
|
||||
|
||||
//把修改密码移动到WebUI栏目中
|
||||
//import ChangePasswordCard from './change_password';
|
||||
// 把修改密码移动到WebUI栏目中
|
||||
// import ChangePasswordCard from './change_password';
|
||||
import LoginConfigCard from './login';
|
||||
import OneBotConfigCard from './onebot';
|
||||
import ServerConfigCard from './server';
|
||||
@@ -102,7 +102,7 @@ export default function ConfigPage () {
|
||||
<LoginConfigCard />
|
||||
</ConfigPageItem>
|
||||
</Tab>
|
||||
//把修改密码移动到WebUI栏目中
|
||||
{/* 把修改密码移动到WebUI栏目中 */}
|
||||
{
|
||||
/*
|
||||
<Tab title='修改密码' key='token'>
|
||||
|
||||
@@ -457,99 +457,101 @@ const WebUIConfigCard = () => {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{twoFAStatus.enable2FA ? (
|
||||
<div className='bg-green-50 border border-green-200 rounded-lg p-4'>
|
||||
<div className='text-sm text-green-700 mb-3'>✅ 双因素认证已启用</div>
|
||||
<div className='mb-3'>
|
||||
<div className='text-sm text-default-600 mb-2'>输入验证码以禁用</div>
|
||||
<input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
value={disableTotpCode}
|
||||
onChange={(e) => setDisableTotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
placeholder='000000'
|
||||
className='w-32 px-3 py-2 border border-default-300 rounded-lg text-center text-lg tracking-widest'
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
color='danger'
|
||||
variant='flat'
|
||||
onPress={disableTwoFA}
|
||||
isLoading={isDisabling2FA}
|
||||
disabled={!disableTotpCode || disableTotpCode.length !== 6}
|
||||
className='w-fit'
|
||||
>
|
||||
禁用双因素认证
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className='text-sm text-default-400 mb-2'>
|
||||
启用双因素认证后,登录时需要额外输入Authenticator应用生成的验证码
|
||||
</div>
|
||||
<div className='bg-default-50 border border-default-200 rounded-lg p-4'>
|
||||
{twoFAStatus.enable2FA
|
||||
? (
|
||||
<div className='bg-green-50 border border-green-200 rounded-lg p-4'>
|
||||
<div className='text-sm text-green-700 mb-3'>✅ 双因素认证已启用</div>
|
||||
<div className='mb-3'>
|
||||
<div className='text-sm text-default-600 mb-2'>输入验证码以禁用</div>
|
||||
<input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
value={disableTotpCode}
|
||||
onChange={(e) => setDisableTotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
placeholder='000000'
|
||||
className='w-32 px-3 py-2 border border-default-300 rounded-lg text-center text-lg tracking-widest'
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
color='secondary'
|
||||
color='danger'
|
||||
variant='flat'
|
||||
onPress={generateTwoFASecret}
|
||||
isLoading={isGeneratingSecret}
|
||||
className='w-fit mb-4'
|
||||
onPress={disableTwoFA}
|
||||
isLoading={isDisabling2FA}
|
||||
disabled={!disableTotpCode || disableTotpCode.length !== 6}
|
||||
className='w-fit'
|
||||
>
|
||||
<IoQrCode className='mr-2' />
|
||||
生成密钥
|
||||
禁用双因素认证
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<div className='text-sm text-default-400 mb-2'>
|
||||
启用双因素认证后,登录时需要额外输入Authenticator应用生成的验证码
|
||||
</div>
|
||||
<div className='bg-default-50 border border-default-200 rounded-lg p-4'>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='flat'
|
||||
onPress={generateTwoFASecret}
|
||||
isLoading={isGeneratingSecret}
|
||||
className='w-fit mb-4'
|
||||
>
|
||||
<IoQrCode className='mr-2' />
|
||||
生成密钥
|
||||
</Button>
|
||||
|
||||
{twoFASecret && (
|
||||
<>
|
||||
<div className='mb-4'>
|
||||
<div className='text-sm text-default-600 mb-2'>请使用 Authenticator 应用扫描下方二维码</div>
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='bg-white border border-default-300 rounded-lg p-3'>
|
||||
<QRCodeSVG
|
||||
value={twoFAQrCodeUrl}
|
||||
size={128}
|
||||
level='M'
|
||||
includeMargin={false}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className='text-xs text-default-500 mb-1'>密钥(手动输入用)</div>
|
||||
<div className='font-mono text-sm bg-default-100 px-3 py-2 rounded break-all max-w-[200px]'>
|
||||
{twoFASecret}
|
||||
{twoFASecret && (
|
||||
<>
|
||||
<div className='mb-4'>
|
||||
<div className='text-sm text-default-600 mb-2'>请使用 Authenticator 应用扫描下方二维码</div>
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='bg-white border border-default-300 rounded-lg p-3'>
|
||||
<QRCodeSVG
|
||||
value={twoFAQrCodeUrl}
|
||||
size={128}
|
||||
level='M'
|
||||
includeMargin={false}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className='text-xs text-default-500 mb-1'>密钥(手动输入用)</div>
|
||||
<div className='font-mono text-sm bg-default-100 px-3 py-2 rounded break-all max-w-[200px]'>
|
||||
{twoFASecret}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='mb-4'>
|
||||
<div className='text-sm text-default-600 mb-2'>输入Authenticator验证码</div>
|
||||
<input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
value={twoFATotpCode}
|
||||
onChange={(e) => setTwoFATotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
placeholder='000000'
|
||||
className='w-32 px-3 py-2 border border-default-300 rounded-lg text-center text-lg tracking-widest'
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
color='primary'
|
||||
variant='flat'
|
||||
onPress={enableTwoFA}
|
||||
isLoading={isEnabling2FA}
|
||||
disabled={!twoFATotpCode || twoFATotpCode.length !== 6}
|
||||
className='w-fit'
|
||||
>
|
||||
启用双因素认证
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className='mb-4'>
|
||||
<div className='text-sm text-default-600 mb-2'>输入Authenticator验证码</div>
|
||||
<input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
value={twoFATotpCode}
|
||||
onChange={(e) => setTwoFATotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
placeholder='000000'
|
||||
className='w-32 px-3 py-2 border border-default-300 rounded-lg text-center text-lg tracking-widest'
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
color='primary'
|
||||
variant='flat'
|
||||
onPress={enableTwoFA}
|
||||
isLoading={isEnabling2FA}
|
||||
disabled={!twoFATotpCode || twoFATotpCode.length !== 6}
|
||||
className='w-fit'
|
||||
>
|
||||
启用双因素认证
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SaveButtons
|
||||
@@ -561,4 +563,4 @@ const WebUIConfigCard = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default WebUIConfigCard;
|
||||
export default WebUIConfigCard;
|
||||
@@ -238,159 +238,161 @@ export default function WebLoginPage () {
|
||||
)}
|
||||
|
||||
{/* 2FA验证步骤 */}
|
||||
{require2FA ? (
|
||||
<>
|
||||
<Button
|
||||
isIconOnly
|
||||
variant='light'
|
||||
className='self-start -ml-2'
|
||||
onPress={goBackToToken}
|
||||
>
|
||||
<IoArrowBack size={20} />
|
||||
</Button>
|
||||
<div className='text-center text-default-600 dark:text-default-400'>
|
||||
请输入Authenticator中的验证码
|
||||
</div>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit2FA();
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
classNames={{
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
'bg-transparent',
|
||||
'text-black/90 dark:text-white/90',
|
||||
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
|
||||
],
|
||||
innerWrapper: 'bg-transparent',
|
||||
inputWrapper: [
|
||||
'shadow-xl',
|
||||
'bg-default-100/70',
|
||||
'dark:bg-default/60',
|
||||
'backdrop-blur-xl',
|
||||
'backdrop-saturate-200',
|
||||
'hover:bg-default-0/70',
|
||||
'dark:hover:bg-default/70',
|
||||
'group-data-[focus=true]:bg-default-100/50',
|
||||
'dark:group-data-[focus=true]:bg-default/60',
|
||||
'!cursor-text',
|
||||
],
|
||||
{require2FA
|
||||
? (
|
||||
<>
|
||||
<Button
|
||||
isIconOnly
|
||||
variant='light'
|
||||
className='self-start -ml-2'
|
||||
onPress={goBackToToken}
|
||||
>
|
||||
<IoArrowBack size={20} />
|
||||
</Button>
|
||||
<div className='text-center text-default-600 dark:text-default-400'>
|
||||
请输入Authenticator中的验证码
|
||||
</div>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit2FA();
|
||||
}}
|
||||
isDisabled={isLoading}
|
||||
label='验证码'
|
||||
placeholder='请输入6位验证码'
|
||||
radius='lg'
|
||||
size='lg'
|
||||
startContent={
|
||||
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
|
||||
}
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
/>
|
||||
</form>
|
||||
<Button
|
||||
className='mx-10 mt-10 text-lg py-7'
|
||||
color='primary'
|
||||
isLoading={isLoading}
|
||||
radius='full'
|
||||
size='lg'
|
||||
variant='shadow'
|
||||
onPress={onSubmit2FA}
|
||||
>
|
||||
验证
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmitToken();
|
||||
}}
|
||||
>
|
||||
{/* 隐藏的用户名字段,帮助浏览器识别登录表单 */}
|
||||
<input
|
||||
type='text'
|
||||
name='username'
|
||||
value='napcat-webui'
|
||||
autoComplete='username'
|
||||
className='absolute -left-[9999px] opacity-0 pointer-events-none'
|
||||
readOnly
|
||||
tabIndex={-1}
|
||||
aria-label='Username'
|
||||
/>
|
||||
<Input
|
||||
isClearable
|
||||
type='password'
|
||||
name='password'
|
||||
autoComplete='current-password'
|
||||
classNames={{
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
'bg-transparent',
|
||||
'text-black/90 dark:text-white/90',
|
||||
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
|
||||
],
|
||||
innerWrapper: 'bg-transparent',
|
||||
inputWrapper: [
|
||||
'shadow-xl',
|
||||
'bg-default-100/70',
|
||||
'dark:bg-default/60',
|
||||
'backdrop-blur-xl',
|
||||
'backdrop-saturate-200',
|
||||
'hover:bg-default-0/70',
|
||||
'dark:hover:bg-default/70',
|
||||
'group-data-[focus=true]:bg-default-100/50',
|
||||
'dark:group-data-[focus=true]:bg-default/60',
|
||||
'!cursor-text',
|
||||
],
|
||||
}}
|
||||
isDisabled={isLoading || isPasskeyLoading}
|
||||
label='Token'
|
||||
placeholder='请输入token'
|
||||
radius='lg'
|
||||
size='lg'
|
||||
startContent={
|
||||
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
|
||||
}
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
onClear={() => setTokenValue('')}
|
||||
/>
|
||||
</form>
|
||||
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
|
||||
💡 提示:请从 NapCat 启动日志中查看登录密钥
|
||||
</div>
|
||||
<Button
|
||||
className='mx-10 mt-10 text-lg py-7'
|
||||
color='primary'
|
||||
isLoading={isLoading}
|
||||
radius='full'
|
||||
size='lg'
|
||||
variant='shadow'
|
||||
onPress={onSubmitToken}
|
||||
>
|
||||
{!isLoading && (
|
||||
<Image
|
||||
alt='logo'
|
||||
>
|
||||
<Input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
classNames={{
|
||||
wrapper: '-ml-8',
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
'bg-transparent',
|
||||
'text-black/90 dark:text-white/90',
|
||||
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
|
||||
],
|
||||
innerWrapper: 'bg-transparent',
|
||||
inputWrapper: [
|
||||
'shadow-xl',
|
||||
'bg-default-100/70',
|
||||
'dark:bg-default/60',
|
||||
'backdrop-blur-xl',
|
||||
'backdrop-saturate-200',
|
||||
'hover:bg-default-0/70',
|
||||
'dark:hover:bg-default/70',
|
||||
'group-data-[focus=true]:bg-default-100/50',
|
||||
'dark:group-data-[focus=true]:bg-default/60',
|
||||
'!cursor-text',
|
||||
],
|
||||
}}
|
||||
height='2em'
|
||||
src={logo}
|
||||
isDisabled={isLoading}
|
||||
label='验证码'
|
||||
placeholder='请输入6位验证码'
|
||||
radius='lg'
|
||||
size='lg'
|
||||
startContent={
|
||||
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
|
||||
}
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
/>
|
||||
)}
|
||||
登录
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
<Button
|
||||
className='mx-10 mt-10 text-lg py-7'
|
||||
color='primary'
|
||||
isLoading={isLoading}
|
||||
radius='full'
|
||||
size='lg'
|
||||
variant='shadow'
|
||||
onPress={onSubmit2FA}
|
||||
>
|
||||
验证
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmitToken();
|
||||
}}
|
||||
>
|
||||
{/* 隐藏的用户名字段,帮助浏览器识别登录表单 */}
|
||||
<input
|
||||
type='text'
|
||||
name='username'
|
||||
value='napcat-webui'
|
||||
autoComplete='username'
|
||||
className='absolute -left-[9999px] opacity-0 pointer-events-none'
|
||||
readOnly
|
||||
tabIndex={-1}
|
||||
aria-label='Username'
|
||||
/>
|
||||
<Input
|
||||
isClearable
|
||||
type='password'
|
||||
name='password'
|
||||
autoComplete='current-password'
|
||||
classNames={{
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
'bg-transparent',
|
||||
'text-black/90 dark:text-white/90',
|
||||
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
|
||||
],
|
||||
innerWrapper: 'bg-transparent',
|
||||
inputWrapper: [
|
||||
'shadow-xl',
|
||||
'bg-default-100/70',
|
||||
'dark:bg-default/60',
|
||||
'backdrop-blur-xl',
|
||||
'backdrop-saturate-200',
|
||||
'hover:bg-default-0/70',
|
||||
'dark:hover:bg-default/70',
|
||||
'group-data-[focus=true]:bg-default-100/50',
|
||||
'dark:group-data-[focus=true]:bg-default/60',
|
||||
'!cursor-text',
|
||||
],
|
||||
}}
|
||||
isDisabled={isLoading || isPasskeyLoading}
|
||||
label='Token'
|
||||
placeholder='请输入token'
|
||||
radius='lg'
|
||||
size='lg'
|
||||
startContent={
|
||||
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
|
||||
}
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
onClear={() => setTokenValue('')}
|
||||
/>
|
||||
</form>
|
||||
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
|
||||
💡 提示:请从 NapCat 启动日志中查看登录密钥
|
||||
</div>
|
||||
<Button
|
||||
className='mx-10 mt-10 text-lg py-7'
|
||||
color='primary'
|
||||
isLoading={isLoading}
|
||||
radius='full'
|
||||
size='lg'
|
||||
variant='shadow'
|
||||
onPress={onSubmitToken}
|
||||
>
|
||||
{!isLoading && (
|
||||
<Image
|
||||
alt='logo'
|
||||
classNames={{
|
||||
wrapper: '-ml-8',
|
||||
}}
|
||||
height='2em'
|
||||
src={logo}
|
||||
/>
|
||||
)}
|
||||
登录
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardBody>
|
||||
</HoverEffectCard>
|
||||
</motion.div>
|
||||
|
||||
@@ -44,8 +44,11 @@ export default defineConfig(({ mode }) => {
|
||||
// if (id.includes('@heroui/')) {
|
||||
// return 'heroui';
|
||||
// }
|
||||
if (id.includes('react-dom')) {
|
||||
return 'react-dom';
|
||||
// React 19: react / react-dom / scheduler 必须合并到同一 vendor chunk,
|
||||
// 否则 react 的 forwardRef 等 API 会被错导向 react-dom 块而变成 undefined,
|
||||
// 导致 codemirror-core 等 chunk 初始化即崩溃(Cannot read properties of undefined (reading 'forwardRef'))。
|
||||
if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id)) {
|
||||
return 'react-vendor';
|
||||
}
|
||||
if (id.includes('react-router-dom')) {
|
||||
return 'react-router-dom';
|
||||
|
||||
Reference in new issue
Block a user