Compare commits

..
3 Commits
Author SHA1 Message Date
mitsukina 62b50e2548 Update QQNT release download URLs
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Refresh the downstream release workflow to use the newer QQNT 3.2.30-50969 AppImage URLs for both x86_64 and arm64 builds.
2026-07-19 20:59:24 +08:00
mitsukina e0844a0bce Update QQNT installer URL in release workflow
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Switches the release publish workflow to download a newer QQNT x64 installer (9.9.32.50969) from the updated qqdl.gtimg.cn source instead of the previous dldir1v6.qq.com link.
2026-07-19 20:57:43 +08:00
mitsukina 8447a46f8b Add mappings for QQ 50969 builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add appid/QUA entries and native/packet send-recv offsets for the new 9.9.32-50969 Windows build and 3.2.30-50969 Linux x64/arm64 builds. Also normalize the existing 3.2.30-50828 x64 native recv offset format by removing the leading zero.
2026-07-19 20:49:54 +08:00
62 changed files with 432 additions and 2896 deletions

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@
- **控制数量**:最终保持 5-15 条更新要点
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
## 输出模板 - 必须严格遵守以下格式
```
# {VERSION}
+11 -35
View File
@@ -12,7 +12,7 @@ permissions: write-all
env:
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
RELEASE_NAME: "NapCat"
jobs:
@@ -35,11 +35,6 @@ jobs:
uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
@@ -48,6 +43,7 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run ${{ matrix.target.build_cmd }}
@@ -65,11 +61,6 @@ jobs:
assemble-windows-node:
needs: build
runs-on: ubuntu-latest
env:
# QQ 9.9.31.49738; SHA256 matches the microsoft/winget-pkgs installer manifest.
QQ_URL: https://github.com/Rodert/qq-versions/releases/download/qq-packages-20260528-3e8913a2/QQ_9.9.31_260528_x64_01.exe
QQ_SHA256: 0beb5cb4ff776cba822caa0abadbd53f5892f12628a86dabea1b372c82c086bc
NODE_VERSION: '22.11.0'
steps:
- uses: actions/checkout@v5
with:
@@ -85,18 +76,12 @@ jobs:
sudo apt update
sudo apt install -y aria2 unzip zip p7zip-full curl jq
- name: Generate download cache key
id: download-cache-key
run: |
DOWNLOAD_HASH=$(printf '%s\n' "$QQ_URL" "$QQ_SHA256" "$NODE_VERSION" | sha256sum | cut -d ' ' -f 1)
echo "key=napcat-downloads-v2-$DOWNLOAD_HASH" >> "$GITHUB_OUTPUT"
- name: Cache QQ and Node.js downloads
id: cache-downloads
uses: actions/cache@v4
with:
path: /tmp/napcat-downloads
key: ${{ steps.download-cache-key.outputs.key }}
key: napcat-downloads-qq9.9.27.45627-node22.11.0
- name: Download QQ and Node.js
if: steps.cache-downloads.outputs.cache-hit != 'true'
@@ -105,20 +90,15 @@ jobs:
mkdir -p /tmp/napcat-downloads
cd /tmp/napcat-downloads
NT_URL="https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/a33ab721/QQ9.9.32.50969_x64.exe"
echo "Downloading QQ installer..."
# Retry download errors, including HTTP 404 responses.
curl --fail --location --retry 5 --retry-all-errors --retry-delay 5 \
--connect-timeout 30 --max-time 600 --user-agent "Mozilla/5.0" \
--output "QQ_x64.exe" "$QQ_URL"
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
NODE_URL="https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-win-x64.zip"
echo "Downloading Node.js $NODE_VERSION..."
NODE_VER="22.11.0"
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
echo "Downloading Node.js $NODE_VER..."
aria2c -x1 -s1 -k1M -o "node-win-x64.zip" "$NODE_URL"
- name: Verify QQ installer
run: |
echo "$QQ_SHA256 /tmp/napcat-downloads/QQ_x64.exe" | sha256sum --check --strict -
- name: Assemble NapCat.Shell.Windows.Node.zip
run: |
set -euo pipefail
@@ -175,7 +155,8 @@ jobs:
# -----------------------------
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
# -----------------------------
cp -a "$NODE_EXTRACT/node-v$NODE_VERSION-win-x64/node.exe" "$OUT_DIR/" || true
NODE_VER="22.11.0"
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
- name: Upload Artifact
uses: actions/upload-artifact@v6
@@ -433,16 +414,11 @@ jobs:
NapCat.Shell.Windows.OneKey.zip
draft: false
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Update apifox
env:
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
run: |
npm i -g pnpm
pnpm i --ignore-scripts
pnpm run build:openapi
+1 -64
View File
@@ -12,17 +12,11 @@ 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,
createGroupManagementRequests,
} from '../data';
import { createGroupDetailInfoV2Param, createGroupExtFilter, createGroupExtInfo } from '../data';
import { NTEventWrapper } from '../helper/event';
export class NTQQGroupApi {
@@ -174,54 +168,6 @@ 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;
@@ -351,15 +297,6 @@ 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);
}
-83
View File
@@ -13,17 +13,6 @@ 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;
@@ -551,78 +540,6 @@ 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 -139
View File
@@ -1,142 +1,4 @@
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;
}
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter } from '../types';
export function createGroupDetailInfoV2Param (group_code: string): GroupDetailInfoV2Param {
return {
-199
View File
@@ -1,199 +0,0 @@
/**
* 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 };
}
-4
View File
@@ -606,9 +606,5 @@
"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
View File
@@ -2593,171 +2593,6 @@
"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": [
-4
View File
@@ -278,9 +278,5 @@
"3.2.30-50969-arm64": {
"send": "43A4804",
"recv": "1608CC8"
},
"9.9.32-55230-x64": {
"send": "367FE18",
"recv": "36835CC"
}
}
@@ -21,13 +21,13 @@ export interface VideoInfo {
/** Video duration in seconds */
duration: number;
/** Generated thumbnail image format */
/** Container format name (e.g., "mp4", "mkv", "avi") */
format: string;
/** Video codec name (e.g., "h264", "hevc", "vp9") */
videoCodec: string;
/** First frame thumbnail as JPEG image buffer */
/** First frame thumbnail as BMP image buffer */
image: Buffer;
}
@@ -6,7 +6,6 @@ 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) {
@@ -95,15 +94,6 @@ 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);
}
/**
* 转换音频文件
*/
+3 -3
View File
@@ -187,14 +187,14 @@ export class LogWrapper implements ILogWrapper {
_log (level: LogLevel, ...args: any[]) {
if (this.consoleLogEnabled || this.fileLogEnabled) {
// eslint-disable-next-line no-control-regex
const message = this.formatMsg(args).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|\x1B\[[0-?]*[ -/]*[@-~]|\x1B/g, '');
const message = this.formatMsg(args);
if (this.consoleLogEnabled && this.fileLogEnabled) {
this.logger.log(level, message);
} else if (this.consoleLogEnabled) {
this.logger.log(level, message);
} else if (this.fileLogEnabled) {
this.logger.log(level, message);
// eslint-disable-next-line no-control-regex
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
}
logSubscription.notify(JSON.stringify({ level, message }));
}
+1 -11
View File
@@ -107,20 +107,10 @@ export class RkeyManager {
for (const url of availableUrls) {
try {
let temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
if (typeof temp === 'object' && temp !== null && 'retcode' in temp) {
if ('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),
@@ -19,7 +19,6 @@ 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;
@@ -106,7 +105,15 @@ export class PacketOperationContext {
.filter(Boolean)
);
const res = await Promise.allSettled(reqList);
assertUploadResults(res, this.context.logger);
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}`);
}
});
}
}
async UploadImage (img: PacketMsgPicElement) {
@@ -233,10 +240,9 @@ export class PacketOperationContext {
}
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
// await this.SendPreprocess(msg, groupUin);
// 遍历上传资源(跳过已有原始数据的项)
await Promise.all(msg.filter(item => item.actionMsg).map(async (item) => {
await this.SendPreprocess(item.actionMsg!, groupUin);
}));
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return 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);
@@ -364,23 +370,6 @@ 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;
})
);
@@ -1,26 +0,0 @@
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,11 +21,8 @@ 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;
@@ -113,37 +110,22 @@ export class PacketHighwayContext {
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
}
const cleanupThumbPaths: string[] = [];
// 如果缺少视频缩略图,自动生成一个
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);
}
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) {
@@ -152,21 +134,23 @@ export class PacketHighwayContext {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
} finally {
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}`);
}
}
}));
// 清理临时生成的缩略图文件
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}`);
}
});
}
}
}
/**
* 使用当前 FFmpeg 适配器生成符合 QQ 大小限制的视频缩略图
* 确保视频缩略图存在,如果不存在则自动生成
* @returns 生成的临时缩略图路径,用于后续清理
*/
private async ensureVideoThumb (video: PacketMsgVideoElement): Promise<string> {
@@ -177,10 +161,9 @@ 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_${randomUUID()}.jpg`);
const thumbPath = path.join(videoDir, `${videoBasename}_thumb.png`);
this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
video.thumbPath = thumbPath;
try {
// 尝试使用 FFmpeg 提取视频缩略图
@@ -191,36 +174,26 @@ 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) {
@@ -323,17 +296,13 @@ 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 md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: videoIndex.fileUuid,
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -355,15 +324,16 @@ 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 md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
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');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -379,7 +349,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;
}
@@ -391,17 +361,13 @@ 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 md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: videoIndex.fileUuid,
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -423,15 +389,16 @@ 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 md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
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');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -447,7 +414,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,8 +4,6 @@ import {
MessageElement,
Peer,
RawMessage,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -17,7 +15,7 @@ import {
SendReplyElement,
SendTextElement,
SendVideoElement,
} from '@/napcat-core/types/element';
} from '@/napcat-core/index';
import {
IPacketMsgElement,
PacketMsgAtElement,
@@ -160,8 +158,7 @@ export class PacketMsgConverter {
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
const converters = [PacketMsgTextElement.parseElement,
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement,
PacketMsgVideoElement.parseElement, PacketMsgPicElement.parseElement];
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
return msg.map((element) => {
for (const converter of converters) {
const result = converter(element);
+6 -56
View File
@@ -20,11 +20,7 @@ import {
FaceType,
MessageElement,
NTMsgAtType,
NTVideoType,
PicType,
Peer,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -36,7 +32,8 @@ import {
SendMultiForwardMsgElement,
SendTextElement,
SendVideoElement,
} from '@/napcat-core/types/element';
Peer,
} from '@/napcat-core/index';
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
@@ -390,10 +387,8 @@ 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) &&
elem.commonElem.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
const msgInfoBody = extra.msgInfoBody[0];
const index = msgInfoBody?.index;
return [{
@@ -411,7 +406,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
summary: '[图片]',
thumbPath: new Map(),
},
elementType: ElementType.PIC,
elementType: ElementType.UNKNOWN,
elementId: '',
}, elem];
}
@@ -451,13 +446,8 @@ 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;
@@ -466,18 +456,12 @@ 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;
@@ -496,45 +480,11 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
commonElem: {
serviceType: 48,
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
businessType: this.businessType,
businessType: 21,
},
}];
}
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: video.fileName || 'video.mp4',
fileName: 'nya.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: video.fileFormat,
videoFormat: 0,
voiceFormat: 0,
},
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
height: 0,
width: 0,
time: 0,
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: `${video.thumbMd5 || 'video-thumb'}.jpg`,
fileName: 'nya.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: video.fileName || 'video.mp4',
fileName: 'nya.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: video.fileFormat,
videoFormat: 0,
voiceFormat: 0,
},
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
height: 0,
width: 0,
time: 0,
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: `${video.thumbMd5 || 'video-thumb'}.jpg`,
fileName: 'nya.jpg',
type: {
type: 1,
picFormat: 0,
-2
View File
@@ -118,8 +118,6 @@ export interface VideoElement {
thumbSize?: number; // byte
fileFormat?: NTVideoType; // 2表示mp4 参考下面条目
fileSize?: string; // byte
fileWidth?: number;
fileHeight?: number;
thumbWidth?: number;
thumbHeight?: number;
busiType?: 0; //
-14
View File
@@ -74,20 +74,6 @@ 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[];
}
+2 -54
View File
@@ -105,13 +105,6 @@ export async function NCoreInitFramework (
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
const oneBotContext = WebUiDataRuntime.getOneBotContext();
if (oneBotContext?.core?.selfInfo) {
oneBotContext.core.selfInfo.online = true;
WebUiDataRuntime.setQQLoginPhase('ready');
} else {
WebUiDataRuntime.setQQLoginPhase('initializing');
}
await new Promise<void>(resolve => {
registerInitCallback(() => resolve());
});
@@ -125,8 +118,6 @@ export async function NCoreInitFramework (
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('waiting_qrcode');
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
};
@@ -155,14 +146,9 @@ export async function NCoreInitFramework (
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
WebUiDataRuntime.setQQNewLoginList(list);
}).catch(e => logger.logError('[NapCat] [Framework] 获取登录列表失败:', e));
if (!loginContext.isLogined) {
const requested = loginService.getQRCodePicture();
logger.logWarn('[NapCat] [Framework] 登录服务连接完成,正在获取二维码', { requested, msfStatus: loginService.getMsfStatus() });
}
};
loginListener.onQRCodeSessionUserScaned = () => {
WebUiDataRuntime.setQQLoginPhase('qrcode_scanned');
logger.log('[NapCat] [Framework] 二维码已被扫描,等待确认...');
};
@@ -208,34 +194,11 @@ export async function NCoreInitFramework (
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
// 监听下线通知并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
let restartRequested = false;
loaderObject.core.event.on('KickedOffLine', (tips: string) => {
loaderObject.core.event.on('KickedOffLine', () => {
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
if (restartRequested) return;
restartRequested = true;
setTimeout(() => {
WebUiDataRuntime.requestRestartProcess().then((restartResult) => {
logger.logWarn('[NapCat] [Framework] 账号被踢下线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (!restartResult.result) {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
}
}).catch((error) => {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
});
}, 3_500);
});
}
@@ -246,22 +209,7 @@ function registerWebUiLoginCallbacks (
) {
// 刷新二维码
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
loginContext.isLogined = false;
const msfStatus = loginService.getMsfStatus();
if (msfStatus === 2) {
WebUiDataRuntime.setQQLoginPhase('reconnecting');
const connected = loginService.connect();
logger.logWarn('[NapCat] [Framework] 登录服务离线,正在重连以获取二维码', { connected, msfStatus });
if (!connected) {
throw new Error('QQ 登录服务无法重新连接');
}
return;
}
const requested = loginService.getQRCodePicture();
logger.logWarn('[NapCat] [Framework] 请求刷新二维码', { requested, msfStatus });
if (!requested) {
throw new Error('QQ 未接受二维码刷新请求');
}
loginService.getQRCodePicture();
});
// 快速登录
@@ -42,12 +42,4 @@ 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,21 +1,4 @@
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,
@@ -1,26 +0,0 @@
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);
}
}
@@ -1,51 +0,0 @@
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 };
}
}
@@ -1,73 +0,0 @@
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(() => { });
}
}
}
}
}
@@ -1,13 +0,0 @@
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 || '未知错误'}`
);
}
@@ -1,41 +0,0 @@
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;
}
}
@@ -1,43 +0,0 @@
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;
}
}
@@ -1,35 +0,0 @@
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;
}
}
-12
View File
@@ -75,7 +75,6 @@ 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';
@@ -161,11 +160,6 @@ 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 = [
@@ -197,7 +191,6 @@ 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),
@@ -223,11 +216,6 @@ 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),
+1 -6
View File
@@ -245,12 +245,7 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
});
}
} else {
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(
OB11Data,
msgPeer,
[],
{ usePacketVideoMetadata: true }
);
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
sendElements = sendElementsCreateReturn.sendElements;
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
}
-8
View File
@@ -43,9 +43,6 @@ 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',
@@ -166,7 +163,6 @@ 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',
@@ -218,8 +214,4 @@ export const ActionName = {
CancelOnlineFile: 'cancel_online_file',
GetGroupSignedList: 'get_group_signed_list',
// QQ 空间扩展
SendQzoneMsg: 'send_qzone_msg',
DeleteQzoneMsg: 'delete_qzone_msg',
} as const;
+5 -36
View File
@@ -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, NTVideoType, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
import { ElementType, NapCatCore, 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,21 +12,6 @@ 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;
@@ -129,16 +114,9 @@ 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 usePacketVideoMetadata = context.usePacketVideoMetadata === true;
const thumbExtension = usePacketVideoMetadata ? 'jpg' : 'png';
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.${thumbExtension}`);
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
try {
if (usePacketVideoMetadata) {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
} else {
videoInfo = await FFmpegService.getVideoInfo(filePath, '');
await FFmpegService.extractLegacyVideoThumbnail(filePath, thumbPath);
}
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
if (!fs.existsSync(thumbPath)) {
this.core.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
throw new Error('获取视频缩略图失败');
@@ -157,18 +135,9 @@ 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: '',
@@ -177,7 +146,7 @@ export class OneBotFileApi {
filePath: path,
videoMd5: md5,
thumbMd5,
...videoMetadata,
fileTime: videoInfo.time,
thumbPath: new Map([[0, thumbPath]]),
thumbSize,
thumbWidth: videoInfo.width,
+4 -23
View File
@@ -74,7 +74,6 @@ type Ob11ToRawConverters = {
export type SendMessageContext = {
deleteAfterSentFiles: string[],
peer: Peer;
usePacketVideoMetadata?: boolean;
};
export type RecvMessageContext = {
@@ -860,23 +859,12 @@ export class OneBotMsgApi {
// 获取签名服务地址
let signUrl = this.obContext.configLoader.configData.musicSignUrl;
if (!signUrl) {
signUrl = 'http://106.55.0.102:10087/'; // 首选,yibai音卡签名,已更换稳定签名服务器
signUrl = 'https://ss.xingzhige.com/music_card/card';// 感谢思思!已获思思许可 其余地方使用请自行询问
}
// 请求签名服务
try {
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
);
}
const musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
return this.ob11ToRawConverters.json({
data: { data: musicJson },
type: OB11MessageDataType.json,
@@ -1231,10 +1219,7 @@ export class OneBotMsgApi {
async createSendElements (
messageData: OB11MessageData[],
peer: Peer,
ignoreTypes: OB11MessageDataType[] = [],
options: {
usePacketVideoMetadata?: boolean;
} = {}
ignoreTypes: OB11MessageDataType[] = []
) {
const deleteAfterSentFiles: string[] = [];
const callResultList: Array<Promise<SendMessageElement | undefined>> = [];
@@ -1251,11 +1236,7 @@ export class OneBotMsgApi {
}
const callResult = converter(
sendMsg,
{
peer,
deleteAfterSentFiles,
usePacketVideoMetadata: options.usePacketVideoMetadata,
}
{ peer, deleteAfterSentFiles }
)?.catch(undefined);
callResultList.push(callResult);
}
+23 -107
View File
@@ -65,10 +65,6 @@ 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;
@@ -80,8 +76,6 @@ 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;
@@ -390,34 +384,36 @@ 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: '',
};
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}`);
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);
}
} catch (e) {
this.context.logger.logError('查询撤回消息失败', e);
}
};
msgListener.onKickedOffLine = async (kick) => {
@@ -666,86 +662,6 @@ 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";
}
/**
+9 -84
View File
@@ -126,7 +126,7 @@ async function handleLogin (
quickLoginUin: string | undefined,
historyLoginList: LoginListItem[]
): Promise<SelfInfo> {
const context = { isLogined: false, loginFlowInitialized: false };
const context = { isLogined: false };
let inner_resolve: (value: SelfInfo) => void;
const selfInfo: Promise<SelfInfo> = new Promise((resolve) => {
inner_resolve = resolve;
@@ -142,14 +142,6 @@ async function handleLogin (
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
context.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
const oneBotContext = WebUiDataRuntime.getOneBotContext();
if (oneBotContext?.core?.selfInfo) {
oneBotContext.core.selfInfo.online = true;
WebUiDataRuntime.setQQLoginPhase('ready');
} else {
WebUiDataRuntime.setQQLoginPhase('initializing');
}
inner_resolve({
uid: loginResult.uid,
uin: loginResult.uin,
@@ -157,35 +149,14 @@ async function handleLogin (
online: true,
});
};
loginListener.onLoginDisConnected = () => {
context.isLogined = false;
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginPhase('offline');
logger.logWarn('[Core] [Login] 登录服务已断开,将允许重新获取二维码');
};
loginListener.onLogoutSucceed = () => {
context.isLogined = false;
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginPhase('offline');
};
loginListener.onLoginConnected = () => {
waitForNetworkConnection(loginService, logger).then(async () => {
if (!context.loginFlowInitialized) {
context.loginFlowInitialized = true;
await handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList);
return;
}
if (!context.isLogined) {
WebUiDataRuntime.setQQLoginPhase('generating_qrcode');
const requested = loginService.getQRCodePicture();
logger.logWarn('[Core] [Login] 登录服务重连完成,正在获取二维码', { requested, msfStatus: loginService.getMsfStatus() });
}
}).catch(e => logger.logError(e));
waitForNetworkConnection(loginService, logger).then(() => {
handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList).then().catch(e => logger.logError(e));
loginListener.onLoginConnected = () => { };
});
};
loginListener.onQRCodeGetPicture = ({ pngBase64QrcodeData, qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('waiting_qrcode');
const realBase64 = pngBase64QrcodeData.replace(/^data:image\/\w+;base64,/, '');
const buffer = Buffer.from(realBase64, 'base64');
@@ -204,20 +175,14 @@ async function handleLogin (
});
};
loginListener.onQRCodeSessionUserScaned = () => {
WebUiDataRuntime.setQQLoginPhase('qrcode_scanned');
logger.log('[Core] [Login] 二维码已被扫描,等待确认...');
};
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
if (!context.isLogined) {
logger.logError('[Core] [Login] Login Error,ErrType: ', errType, ' ErrCode:', errCode);
if (errType === 1 && errCode === 3) {
// 仅二维码过期时自动请求下一张二维码。账号被踢下线等其他错误
// 需要由用户触发刷新,避免每两秒重复创建原生登录会话。
// 二维码过期刷新
WebUiDataRuntime.setQQLoginError('二维码已过期,请刷新');
loginService.getQRCodePicture();
}
loginService.getQRCodePicture();
}
};
@@ -231,7 +196,7 @@ async function handleLogin (
loginService.connect();
return await selfInfo;
}
async function handleLoginInner (context: { isLogined: boolean; loginFlowInitialized: boolean; }, logger: LogWrapper, loginService: NodeIKernelLoginService, quickLoginUin: string | undefined, historyLoginList: LoginListItem[]) {
async function handleLoginInner (context: { isLogined: boolean; }, logger: LogWrapper, loginService: NodeIKernelLoginService, quickLoginUin: string | undefined, historyLoginList: LoginListItem[]) {
const resolveQuickPasswordMd5 = (): string | undefined => {
const quickPasswordMd5 = process.env['NAPCAT_QUICK_PASSWORD_MD5']?.trim();
if (quickPasswordMd5) {
@@ -252,19 +217,7 @@ async function handleLoginInner (context: { isLogined: boolean; loginFlowInitial
// 注册刷新二维码回调
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
context.isLogined = false;
const msfStatus = loginService.getMsfStatus();
if (msfStatus === 2) {
// KickedOffLine 会在后台负责重启 Worker。这里不能重启:该回调由
// RefreshQRcode HTTP 请求触发,重启会中断正在等待响应的请求。
WebUiDataRuntime.setQQLoginPhase('reconnecting');
throw new Error('QQ_LOGIN_SERVICE_RESTARTING');
}
const requested = loginService.getQRCodePicture();
logger.logWarn('[Core] [Login] 请求刷新二维码', { requested, msfStatus });
if (!requested) {
throw new Error('QQ 未接受二维码刷新请求');
}
loginService.getQRCodePicture();
});
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
@@ -840,34 +793,9 @@ export class NapCatShell {
// }
// 监听下线通知并同步到 WebUI
let restartRequested = false;
this.core.event.on('KickedOffLine', (tips: string) => {
WebUiDataRuntime.setQQLoginStatus(false);
// 被踢后的二维码已失效,绝不能继续交给页面展示或扫码。
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
if (restartRequested) return;
restartRequested = true;
// 不从 RefreshQRcode 请求中重启 Worker;否则请求会在返回前被中断,
// 浏览器只能得到 ERR_EMPTY_RESPONSE。KickedOffLine 是独立事件,
// 在此异步调度可让前端先观察到“二维码已清空、正在恢复”的状态。
setTimeout(() => {
WebUiDataRuntime.requestRestartProcess().then((restartResult) => {
this.context.logger.logWarn('[Core] [Login] 账号被踢下线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (!restartResult.result) {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
}
}).catch((error) => {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
});
// 常规状态轮询为 3 秒;留出一个轮询周期,确保浏览器先清除旧二维码。
}, 3_500);
});
// 使用 NapCatAdapterManager 统一管理协议适配器
const adapterManager = new NapCatAdapterManager(this.core, this.context, this.context.pathWrapper);
@@ -877,9 +805,6 @@ export class NapCatShell {
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
}
}
-8
View File
@@ -247,14 +247,6 @@ 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;
+1 -2
View File
@@ -34,7 +34,6 @@ export interface IWorkerProcess {
export interface ProcessOptions {
env: NodeJS.ProcessEnv;
stdio: 'pipe' | 'ignore' | 'inherit' | Array<'pipe' | 'ignore' | 'inherit' | 'ipc'>;
execArgv?: string[];
}
/**
@@ -169,7 +168,7 @@ export async function createProcessManager (): Promise<{
manager: IProcessManager;
isElectron: boolean;
}> {
const isElectron = process.env['NAPCAT_FORCE_NODE_PROCESS'] !== '1' && typeof process.versions['electron'] !== 'undefined';
const isElectron = typeof process.versions['electron'] !== 'undefined';
if (isElectron) {
// @ts-ignore - electron 运行时存在但类型声明可能缺失
@@ -1,124 +0,0 @@
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([]);
});
});
-120
View File
@@ -1,120 +0,0 @@
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');
});
});
-309
View File
@@ -1,309 +0,0 @@
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,
}));
});
});
-170
View File
@@ -1,170 +0,0 @@
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();
});
});
-131
View File
@@ -1,131 +0,0 @@
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);
});
});
@@ -94,19 +94,13 @@ export const QQCheckLoginStatusHandler: RequestHandler = async (_, res) => {
const selfInfo = oneBotContext?.core?.selfInfo;
const isOnline = selfInfo?.online;
const qqLoginStatus = WebUiDataRuntime.getQQLoginStatus();
const loginPhase = WebUiDataRuntime.getQQLoginPhase();
// 必须同时满足:已登录且在线(online 必须明确为 true)
// 登录状态以 QQ 登录成功和 Core 明确在线为准。loginPhase 用于展示进度,
// 不能作为跳转的额外门槛,否则 phase 事件延迟时会卡在扫码页。
const isLogin = qqLoginStatus && isOnline === true;
// 检测掉线状态:已登录但不在线
const isOffline = qqLoginStatus && isOnline === false;
const data = {
isLogin,
isOffline,
loginPhase,
qrLoginAccepted: qqLoginStatus && (loginPhase === 'qrcode_scanned' || loginPhase === 'initializing'),
coreReady: qqLoginStatus && isOnline === true,
qrcodeurl: WebUiDataRuntime.getQQLoginQrcodeURL(),
loginError: WebUiDataRuntime.getQQLoginError(),
};
@@ -180,25 +174,14 @@ export const setAutoLoginAccountHandler: RequestHandler = async (req, res) => {
// 刷新QQ登录二维码
export const QQRefreshQRcodeHandler: RequestHandler = async (_, res) => {
// 与 CheckLoginStatus 保持一致:运行时登录标记可能在账号下线后
// 尚未同步,但 core.selfInfo.online 已能反映实际在线状态。
const oneBotContext = WebUiDataRuntime.getOneBotContext();
const isOnline = oneBotContext?.core?.selfInfo?.online === true;
if (WebUiDataRuntime.getQQLoginStatus() && isOnline) {
// 判断是否已经登录
if (WebUiDataRuntime.getQQLoginStatus()) {
// 已经登录
return sendError(res, 'QQ Is Logined');
}
// 被踢下线后,后台会从 KickedOffLine 事件异步重启 Worker。不要在这个
// HTTP 请求里再次触发刷新/重启,否则 Worker 退出会打断该响应。
if (WebUiDataRuntime.getQQLoginPhase() === 'reconnecting') {
return sendSuccess(res, { qrcodeurl: '', restarting: true });
}
try {
const qrcodeurl = await WebUiDataRuntime.refreshQRCode();
return sendSuccess(res, { qrcodeurl });
} catch (error) {
return sendError(res, `QRCode Refresh Error: ${(error as Error).message}`);
}
// 刷新二维码
await WebUiDataRuntime.refreshQRCode();
return sendSuccess(res, null);
};
// 密码登录
@@ -1,13 +1,12 @@
import store from 'napcat-common/src/store';
import { napCatVersion } from 'napcat-common/src/version';
import { NapCatCoreWorkingEnv, type LoginRuntimeType, type QQLoginPhase } from '../types';
import { NapCatCoreWorkingEnv, type LoginRuntimeType } from '../types';
const LoginRuntime: LoginRuntimeType = {
workingEnv: NapCatCoreWorkingEnv.Unknown,
LoginCurrentTime: Date.now(),
LoginCurrentRate: 0,
QQLoginStatus: false, // 已实现 但太傻了 得去那边注册个回调刷新
QQLoginPhase: 'waiting_qrcode',
QQQRCodeURL: '',
QQLoginUin: '',
QQLoginInfo: {
@@ -102,14 +101,6 @@ export const WebUiDataRuntime = {
LoginRuntime.QQLoginStatus = status;
},
setQQLoginPhase (phase: QQLoginPhase): void {
LoginRuntime.QQLoginPhase = phase;
},
getQQLoginPhase (): QQLoginPhase {
return LoginRuntime.QQLoginPhase;
},
setQQLoginQrcodeURL (url: LoginRuntimeType['QQQRCodeURL']): void {
LoginRuntime.QQQRCodeURL = url;
},
@@ -247,23 +238,7 @@ export const WebUiDataRuntime = {
},
refreshQRCode: async function () {
const previousQRCodeUrl = LoginRuntime.QQQRCodeURL;
LoginRuntime.QQLoginError = '';
LoginRuntime.QQLoginPhase = 'generating_qrcode';
await LoginRuntime.onRefreshQRCode();
const refreshTimeout = 10_000;
const deadline = Date.now() + refreshTimeout;
while (Date.now() < deadline) {
const qrcodeUrl = LoginRuntime.QQQRCodeURL;
if (qrcodeUrl && qrcodeUrl !== previousQRCodeUrl) {
LoginRuntime.QQLoginPhase = 'waiting_qrcode';
return qrcodeUrl;
}
await new Promise(resolve => setTimeout(resolve, 50));
}
LoginRuntime.QQLoginPhase = previousQRCodeUrl ? 'waiting_qrcode' : 'offline';
throw new Error('二维码刷新超时:QQ 登录服务未返回新的二维码');
},
};
@@ -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(/=+$/, '');
@@ -39,22 +39,11 @@ export enum NapCatCoreWorkingEnv {
Shell = 1,
Framework = 2,
}
export type QQLoginPhase =
| 'waiting_qrcode'
| 'generating_qrcode'
| 'qrcode_scanned'
| 'initializing'
| 'ready'
| 'offline'
| 'reconnecting';
export interface LoginRuntimeType {
workingEnv: NapCatCoreWorkingEnv;
LoginCurrentTime: number;
LoginCurrentRate: number;
QQLoginStatus: boolean;
QQLoginPhase: QQLoginPhase;
QQQRCodeURL: string;
QQLoginUin: string;
QQLoginInfo: SelfInfo;
@@ -7,33 +7,12 @@ interface QrCodeLoginProps {
qrcode: string;
loginError?: string;
onRefresh?: () => void;
isRefreshing?: boolean;
loginPhase?: string;
isRecoveringLoginService?: boolean;
}
const QrCodeLogin: React.FC<QrCodeLoginProps> = ({ qrcode, loginError, onRefresh, isRefreshing = false, loginPhase, isRecoveringLoginService = false }) => {
const transitionMessage = loginPhase === 'qrcode_scanned'
? '二维码已扫描,等待手机确认…'
: loginPhase === 'initializing'
? 'QQ 登录成功,正在启动 NapCat…'
: loginPhase === 'reconnecting' || isRecoveringLoginService
? '正在重新连接 QQ 登录服务…'
: undefined;
const QrCodeLogin: React.FC<QrCodeLoginProps> = ({ qrcode, loginError, onRefresh }) => {
return (
<div className='flex flex-col items-center'>
{(isRefreshing || transitionMessage) && (
<div className='fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm'>
<div className='flex flex-col items-center gap-4 rounded-xl bg-content1 px-10 py-8 shadow-xl'>
<Spinner color='primary' size='lg' />
<div className='text-lg font-medium'>{transitionMessage || '正在刷新二维码…'}</div>
<div className='text-sm text-default-500'>
{transitionMessage ? '请不要关闭此页面,最长可能需要 3 分钟' : '正在等待新的二维码,最长 10 秒'}
</div>
</div>
</div>
)}
{loginError && !qrcode && !isRecoveringLoginService
{loginError
? (
<div className='flex flex-col items-center py-4'>
<div className='w-full flex justify-center mb-6'>
@@ -55,8 +34,6 @@ const QrCodeLogin: React.FC<QrCodeLoginProps> = ({ qrcode, loginError, onRefresh
size='lg'
startContent={<IoRefresh />}
onPress={onRefresh}
isLoading={isRefreshing}
isDisabled={isRefreshing}
>
重新获取二维码
</Button>
@@ -65,18 +42,13 @@ const QrCodeLogin: React.FC<QrCodeLoginProps> = ({ qrcode, loginError, onRefresh
)
: (
<>
{loginError && (
<div className='mb-4 w-full max-w-[360px] rounded-lg bg-warning-50 px-4 py-3 text-center text-sm text-warning-700 dark:bg-warning-50/20 dark:text-warning-300'>
{loginError}
</div>
)}
<div className='bg-white p-2 rounded-md w-fit mx-auto relative overflow-hidden'>
{!qrcode && (
<div className='absolute left-0 top-0 right-0 bottom-0 bg-white dark:bg-zinc-900 bg-opacity-90 backdrop-blur-sm flex items-center justify-center z-10'>
<Spinner color='primary' />
</div>
)}
<QRCodeSVG key={qrcode} size={180} value={qrcode || ' '} />
<QRCodeSVG size={180} value={qrcode || ' '} />
</div>
<div className='mt-5 text-center text-default-500 text-sm'>请使用QQ或者TIM扫描上方二维码</div>
{onRefresh && qrcode && (
@@ -87,8 +59,6 @@ const QrCodeLogin: React.FC<QrCodeLoginProps> = ({ qrcode, loginError, onRefresh
size='sm'
startContent={<IoRefresh />}
onPress={onRefresh}
isLoading={isRefreshing}
isDisabled={isRefreshing}
>
刷新二维码
</Button>
@@ -32,23 +32,14 @@ export default class QQManager {
public static async checkQQLoginStatusWithQrcode () {
const data = await serverRequest.post<
ServerResponse<{
qrcodeurl: string;
isLogin: boolean;
isOffline?: boolean;
loginError?: string;
loginPhase?: 'waiting_qrcode' | 'generating_qrcode' | 'qrcode_scanned' | 'initializing' | 'ready' | 'offline' | 'reconnecting';
qrLoginAccepted?: boolean;
coreReady?: boolean;
}>
ServerResponse<{ qrcodeurl: string; isLogin: boolean; isOffline?: boolean; loginError?: string; }>
>('/QQLogin/CheckLoginStatus');
return data.data.data;
}
public static async refreshQRCode () {
const data = await serverRequest.post<ServerResponse<{ qrcodeurl: string; restarting?: boolean; }>>('/QQLogin/RefreshQRcode');
return data.data.data;
await serverRequest.post<ServerResponse<null>>('/QQLogin/RefreshQRcode');
}
public static async getQQLoginQrcode () {
@@ -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,101 +457,99 @@ 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>
{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>
)
: (
<>
<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>
<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'>
<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}
</div>
{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 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>
<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
@@ -563,4 +561,4 @@ const WebUIConfigCard = () => {
);
};
export default WebUIConfigCard;
export default WebUIConfigCard;
@@ -53,11 +53,6 @@ export default function QQLoginPage () {
const [uinValue, setUinValue] = useState<string>('');
const [isLoading, setIsLoading] = useState<boolean>(false);
const [qrcode, setQrcode] = useState<string>('');
const [loginPhase, setLoginPhase] = useState<string>('waiting_qrcode');
const [isRecoveringLoginService, setIsRecoveringLoginService] = useState(false);
const qrcodeRef = useRef<string>('');
const qrcodeRequestVersionRef = useRef(0);
const isRefreshingQRCodeRef = useRef(false);
const [loginError, setLoginError] = useState<string>('');
const lastErrorRef = useRef<string>('');
const [qqList, setQQList] = useState<(QQItem | LoginListItem)[]>([]);
@@ -204,14 +199,9 @@ export default function QQLoginPage () {
};
const onUpdateQrCode = async () => {
const requestVersion = qrcodeRequestVersionRef.current;
if (firstLoad.current) setIsLoading(true);
try {
const data = await QQManager.checkQQLoginStatusWithQrcode();
setLoginPhase(data.loginPhase || (data.isLogin ? 'ready' : 'waiting_qrcode'));
if (data.loginPhase === 'reconnecting') {
setIsRecoveringLoginService(true);
}
if (firstLoad.current) {
setIsLoading(false);
@@ -221,26 +211,17 @@ export default function QQLoginPage () {
toast.success('QQ登录成功');
navigate('/', { replace: true });
} else {
// 刷新二维码是一个需要等待结果的操作。忽略在它开始前发出的
// 轮询响应,避免旧 URL 在刷新完成后覆盖刚拿到的新二维码。
if (requestVersion === qrcodeRequestVersionRef.current && !isRefreshingQRCodeRef.current) {
qrcodeRef.current = data.qrcodeurl;
setQrcode(data.qrcodeurl);
if (data.qrcodeurl) {
setIsRecoveringLoginService(false);
}
}
setQrcode(data.qrcodeurl);
if (data.loginError && data.loginError !== lastErrorRef.current) {
lastErrorRef.current = data.loginError;
setLoginError(data.loginError);
const friendlyMsg = parseLoginError(data.loginError);
// 被踢下线时页面会自动进入登录服务恢复流程。它不是可由用户
// 处理的登录表单错误,也不应弹出对话框遮住恢复状态。
const isRecovering = data.loginPhase === 'reconnecting' || isRecoveringLoginService;
// 仅在扫码登录 Tab 下才弹窗,或者错误不是"二维码已过期"
// 如果是 "二维码已过期",且不在 qrcode tab,则不弹窗
const isQrCodeExpired = friendlyMsg.includes('二维码') && (friendlyMsg.includes('过期') || friendlyMsg.includes('失效'));
if (!isRecovering && (!isQrCodeExpired || activeTab === 'qrcode')) {
if (!isQrCodeExpired || activeTab === 'qrcode') {
dialog.alert({
title: '登录失败',
content: friendlyMsg,
@@ -254,11 +235,8 @@ export default function QQLoginPage () {
}
} catch (error) {
const msg = (error as Error).message;
// Worker 重启时,旧连接被关闭是预期现象。恢复状态持续轮询即可,
// 不要把 ERR_EMPTY_RESPONSE 作为用户可操作的错误反复弹出。
if (!isRecoveringLoginService) {
toast.error(`获取二维码失败: ${msg}`);
}
toast.error(`获取二维码失败: ${msg}`);
}
};
@@ -293,74 +271,29 @@ export default function QQLoginPage () {
};
const onRefreshQRCode = async () => {
if (isRecoveringLoginService || loginPhase === 'reconnecting') {
toast('QQ 登录服务正在恢复,请等待新的二维码…', { icon: '⏳' });
return;
}
if (isRefreshingQRCodeRef.current) {
return;
}
qrcodeRequestVersionRef.current += 1;
isRefreshingQRCodeRef.current = true;
setIsRefreshingQRCode(true);
try {
lastErrorRef.current = '';
setLoginError('');
const { qrcodeurl, restarting } = await QQManager.refreshQRCode();
if (restarting) {
setIsRecoveringLoginService(true);
setLoginPhase('reconnecting');
return;
}
if (!qrcodeurl || qrcodeurl === qrcodeRef.current) {
throw new Error('未获取到新的二维码');
}
qrcodeRef.current = qrcodeurl;
setQrcode(qrcodeurl);
toast.success('二维码已刷新');
await QQManager.refreshQRCode();
toast.success('已发送刷新请求');
} catch (error) {
const msg = (error as Error).message;
if (msg.includes('QQ_LOGIN_SERVICE_RESTARTING')) {
setIsRecoveringLoginService(true);
setLoginPhase('reconnecting');
toast('QQ 登录服务正在重启,正在生成新的二维码…', { icon: '⏳' });
} else if (msg.includes('二维码刷新超时')) {
toast.error('未能取得新的二维码,请稍后重试');
} else {
toast.error(`刷新二维码失败: ${msg}`);
}
} finally {
qrcodeRequestVersionRef.current += 1;
isRefreshingQRCodeRef.current = false;
setIsRefreshingQRCode(false);
toast.error(`刷新二维码失败: ${msg}`);
}
};
const [showGUIDManager, setShowGUIDManager] = useState(false);
const [isRefreshingQRCode, setIsRefreshingQRCode] = useState(false);
useEffect(() => {
const isLoginTransitioning = loginPhase === 'qrcode_scanned' || loginPhase === 'initializing' || loginPhase === 'reconnecting' || isRecoveringLoginService;
const pollInterval = isRefreshingQRCode || isLoginTransitioning ? 500 : 3000;
const timer = setInterval(() => {
onUpdateQrCode();
}, pollInterval);
}, 3000);
onUpdateQrCode();
onUpdateQQList();
return () => clearInterval(timer);
}, [isRefreshingQRCode, loginPhase, isRecoveringLoginService]);
useEffect(() => {
if (!isRecoveringLoginService) return;
const timer = setTimeout(() => {
setIsRecoveringLoginService(false);
setLoginPhase('offline');
setLoginError('QQ 登录服务恢复超时,请稍后重试');
}, 180_000);
return () => clearTimeout(timer);
}, [isRecoveringLoginService]);
}, []);
return (
<>
@@ -436,9 +369,6 @@ export default function QQLoginPage () {
loginError={parseLoginError(loginError)}
qrcode={qrcode}
onRefresh={onRefreshQRCode}
isRefreshing={isRefreshingQRCode}
loginPhase={loginPhase}
isRecoveringLoginService={isRecoveringLoginService}
/>
</Tab>
</Tabs>
@@ -238,161 +238,159 @@ 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();
{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',
],
}}
>
<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',
],
}}
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'
isDisabled={isLoading}
label='验证码'
placeholder='请输入6位验证码'
radius='lg'
size='lg'
variant='shadow'
onPress={onSubmit2FA}
>
验证
</Button>
</>
)
: (
<>
<form
onSubmit={(e) => {
e.preventDefault();
onSubmitToken();
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',
],
}}
>
{/* 隐藏的用户名字段,帮助浏览器识别登录表单 */}
<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'
isDisabled={isLoading || isPasskeyLoading}
label='Token'
placeholder='请输入token'
radius='lg'
size='lg'
variant='shadow'
onPress={onSubmitToken}
>
{!isLoading && (
<Image
alt='logo'
classNames={{
wrapper: '-ml-8',
}}
height='2em'
src={logo}
/>
)}
登录
</Button>
</>
)}
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,11 +44,8 @@ export default defineConfig(({ mode }) => {
// if (id.includes('@heroui/')) {
// return 'heroui';
// }
// 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-dom')) {
return 'react-dom';
}
if (id.includes('react-router-dom')) {
return 'react-router-dom';