Compare commits

..
12 Commits
Author SHA1 Message Date
手瓜一十雪 8cf455ef0b Revert "添加自动登录 | feat(login): automatically restore last logged-in account (#1980)"
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
This reverts commit 31c45bf18e.
2026-08-07 17:42:03 +08:00
Chace efd8679e70 fix: restore PNG thumbnails for direct video sends (#2000)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-08-06 22:08:51 +08:00
叫我饼干ちゃん 31c45bf18e 添加自动登录 | feat(login): automatically restore last logged-in account (#1980)
* feat(login): automatically restore last logged-in account

* docs(shell): correct quick login argument examples
2026-08-06 20:01:40 +08:00
Leslie Lau 56a141abd2 fix: report non-latest private message recalls (#1998) 2026-08-06 17:33:57 +08:00
Zizheng Guo c4a09f01cd feat(group): add group management APIs (#1996)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-08-04 14:24:15 +08:00
Chace 5ee1150277 fix: 修复合并转发视频过期及移动端延迟显示问题 (#1983)
* fix: 修复合并转发视频过期问题

* fix: 修复移动端合并转发内容延迟显示问题

* fix: 同步 ffmpegAddon 视频封面处理产物
2026-08-03 15:23:26 +08:00
Airline233 33546b936e feat(qzone): add QQ space message deletion functionality (#1978)
- Add deleteQzoneMsg API method to NTQQWebApi for deleting Qzone posts by tid
- Implement buildQzoneDeleteBody to construct form-encoded request payload
- Implement parseQzoneDeleteResponse to validate deletion API response
- Add QzoneDeleteResponse and QzoneDeleteParams type definitions
- Create DeleteQzoneMsg OneBot action handler with payload validation
- Register delete_qzone_msg action in router and action handlers
- Add example payload and response for DeleteQzoneMsg action
- Add comprehensive unit tests for delete body construction and response parsing
- Fix indentation inconsistency in createAlbumCommentRequest call
2026-07-22 21:45:42 +08:00
Airline233 288cc7c54f feat(qzone): add QQ space message publishing and image upload (#1965)
- Add QzonePublishResponse interface and parsing logic for publish API responses
- Add buildQzonePublishBody function to construct publish request parameters
- Add buildQzoneUploadImageBody function to construct image upload request parameters
- Add parseQzoneUploadImageResponseText function to parse upload API responses
- Add toQzoneRichval function to format image data for publish requests
- Add publishQzoneMsg method to NTQQWebApi for publishing space messages with optional images
- Add uploadImageToQzone method to NTQQWebApi for uploading images to QQ space
- Add getQzoneAuth private method to retrieve authentication tokens (skey, pskey, g_tk)
- Add SendQzoneMsg action handler to expose QQ space publishing via OneBot API
- Add comprehensive unit tests for all Qzone data construction and parsing functions
- Update action router to register SendQzoneMsg action
- Update action examples to demonstrate Qzone publishing usage
2026-07-20 20:30:17 +08:00
mitsukina 216d0c7c6b Update release note prompt and AI model
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Clarifies the release note prompt to require strict output format without wrapping the result in a code block. Also updates the release publish workflow to use `google/gemma-4-26b-a4b-it:free` instead of the previous OpenAI model endpoint setting.
2026-07-19 21:06:50 +08:00
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
66 changed files with 468 additions and 2967 deletions

No files matched your search

+6 -8
View File
@@ -5,14 +5,12 @@
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
+7 -9
View File
@@ -44,14 +44,12 @@ NapCat.Shell.Windows.OneKey.zip (无头)
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
@@ -78,7 +76,7 @@ NapCat.Shell.Windows.OneKey.zip (无头)
- "Windows 一键包"部分的文本必须完全一致,不要修改任何措辞
- "警告"部分必须包含所有 QQ 版本下载链接,保持原有格式
- "如果WinX64缺少运行库或者xxx.dll?"这一行必须保持原样
- QQ 版本号、下载链接、"官方 CDN"标注和"MacOS 暂不支持"保持不变
- QQ 版本号和下载链接保持不变(40990 版本)
- 只有"## 更新"部分下面的内容需要根据实际 commit 生成
## 重要约束
+2 -2
View File
@@ -9,8 +9,8 @@ on:
type: string
env:
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.AppImage'
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.AppImage'
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_x86_64.AppImage'
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_arm64.AppImage'
jobs:
get-version:
+10 -34
View File
@@ -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
+4 -33
View File
@@ -297,9 +297,6 @@ export class NTQQGroupApi {
const updateCache = async () => {
try {
const members = await this.getGroupMemberAll(groupCode, true);
if (!members?.result?.infos) {
throw new Error(`errCode: ${members?.errCode}, errMsg: ${members?.errMsg}`);
}
this.groupMemberCache.set(groupCode, members.result.infos);
} catch (e) {
this.context.logger.logError(`刷新群成员缓存失败, 群号: ${groupCode}, 错误: ${e}`);
@@ -329,57 +326,31 @@ export class NTQQGroupApi {
// 获取群成员缓存
let members = this.groupMemberCache.get(groupCodeStr);
const cached = !!members;
if (!members) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
}
// 刚入的群可能拉不到成员列表,这时 members 为空,不能直接抛错,否则整条群消息都上报不出去
const getMember = () => {
if (!members) {
return undefined;
}
if (isNumeric(memberUinOrUidStr)) {
return Array.from(members.values()).find(member => member.uin === memberUinOrUidStr);
return Array.from(members!.values()).find(member => member.uin === memberUinOrUidStr);
} else {
return members.get(memberUinOrUidStr);
return members!.get(memberUinOrUidStr);
}
};
let member = getMember();
// 缓存里没有该成员(比如新入群),刷新一次;上面刚刷新过就不再重复拉取
if (!member && cached) {
// 如果缓存中不存在该成员,尝试刷新缓存
if (!member) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
member = getMember();
}
return member;
}
// 从已缓存的群成员里按 QQ 号找 uid,供 uin 转 uid 兜底
getUidFromMemberCache (uin: string) {
for (const members of this.groupMemberCache.values()) {
for (const [uid, member] of members) {
if (member.uin === uin) {
return uid;
}
}
}
return undefined;
}
async getGroupRecommendContactArkJson (groupCode: string) {
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);
}
-1
View File
@@ -198,7 +198,6 @@ export class NTQQUserApi {
.add(() => this.context.session.getUixConvertService().getUid([uin]).then((data) => data.uidInfo.get(uin)))
.add(() => this.context.session.getProfileService().getUidByUin('FriendsServiceImpl', [uin]).get(uin))
.add(() => this.context.session.getGroupService().getUidByUins([uin]).then((data) => data.uids.get(uin)))
.add(() => this.core.apis.GroupApi.getUidFromMemberCache(uin))
.add(() => this.getUserDetailInfoByUin(uin).then((data) => data.detail.uid));
const uid = await fallback.run().catch(() => '');
+33 -229
View File
@@ -8,14 +8,11 @@ import {
WebHonorType, NapCatCore,
} from '@/napcat-core/index';
import { createReadStream, existsSync, statSync } from 'node:fs';
import { open, unlink, writeFile, type FileHandle } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
import { basename, join } from 'node:path';
import { qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl, QunAlbumBatch, nextQunAlbumBatchId } from '../data/webapi';
import { createReadStream, readFileSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { basename } from 'node:path';
import { qunAlbumControl } from '../data/webapi';
import { createAlbumCommentRequest, createAlbumFeedPublish, createAlbumMediaFeed } from '../data/album';
import { FFmpegService } from '../helper/ffmpeg/ffmpeg';
import { defaultVideoThumbB64 } from '../helper/ffmpeg/video';
import {
buildQzoneDeleteBody,
buildQzonePublishBody,
@@ -38,34 +35,6 @@ export interface SetNoticeRetSuccess {
srv_code: number;
}
// 群相册分片上传的并发数
const QUN_ALBUM_SLICE_CONCURRENCY = 8;
// 服务端没给分片大小时的下限,以及防止异常值的上限
const QUN_ALBUM_SLICE_MIN = 16384;
const QUN_ALBUM_SLICE_MAX = 4 * 1024 * 1024;
// 流式计算文件摘要,避免为了算 MD5/SHA1 把整个文件读进内存(视频可能有几十上百 MB)
function hashFile (path: string, algorithm: 'md5' | 'sha1'): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash(algorithm);
createReadStream(path)
.on('data', chunk => hash.update(chunk))
.on('end', () => resolve(hash.digest('hex')))
.on('error', reject);
});
}
// 按需读取单个分片:并发上传时的内存占用只有「并发数 × 分片大小」
async function readSlice (handle: FileHandle, offset: number, length: number): Promise<Buffer> {
const buffer = Buffer.alloc(length);
const { bytesRead } = await handle.read(buffer, 0, length, offset);
// 读不满说明文件在上传过程中被改短了,继续传只会传上去一段补零的数据
if (bytesRead !== length) {
throw new Error(`读取分片失败: offset=${offset} 预期 ${length} 字节,实际 ${bytesRead} 字节`);
}
return buffer;
}
export class NTQQWebApi {
context: InstanceContext;
core: NapCatCore;
@@ -413,11 +382,9 @@ export class NTQQWebApi {
return response.data.album;
}
async createQunAlbumSession (
gc: string, sAlbumID: string, sAlbumName: string, path: string,
skey: string, pskey: string, img_md5: string, uin: string, batch?: QunAlbumBatch
) {
const img_size = statSync(path).size;
async createQunAlbumSession (gc: string, sAlbumID: string, sAlbumName: string, path: string, skey: string, pskey: string, img_md5: string, uin: string) {
const img = readFileSync(path);
const img_size = img.length;
const img_name = basename(path);
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
@@ -430,76 +397,42 @@ export class NTQQWebApi {
img_name,
sAlbumName,
sAlbumID,
// 同批多图共用 batchId,并按「第几张 / 共几张」上报,相册里才会合并成同一条
batchId: batch?.batchId,
batchIndex: batch?.index,
photo_num: batch?.count,
batch_num: batch?.count,
});
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${img_md5}?g_tk=${GTK}`;
const post = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(api, 'POST', body, {
const post = await RequestUtil.HttpGetJson<{ data: { session: string; }, ret: number, msg: string; }>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/json',
});
return post;
}
// 服务端会在会话响应里给出建议的分片大小;取不到或异常时退回 16384。
private resolveQunAlbumSliceSize (raw: unknown) {
const value = Number(raw);
if (!Number.isFinite(value) || value < QUN_ALBUM_SLICE_MIN) return QUN_ALBUM_SLICE_MIN;
return Math.min(value, QUN_ALBUM_SLICE_MAX);
}
async uploadQunAlbumSlice (
path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number,
options: { appid?: string, cmd?: string; } = {}
) {
const appid = options.appid ?? 'qun';
const cmd = options.cmd ?? 'FileUpload';
async uploadQunAlbumSlice (path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number) {
const img_size = statSync(path).size;
let seq = 0;
let offset = 0;
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
// 只记分片位置,不预先读内容;再并发上传(串行上传在几 MB 的图上要几十秒)
const slices: { seq: number, offset: number, end: number; }[] = [];
let seq = 0;
let offset = 0;
while (offset < img_size) {
const end = Math.min(offset + slice_size, img_size);
slices.push({ seq, offset, end });
offset = end;
seq++;
}
const stream = createReadStream(path, { highWaterMark: slice_size });
// 视频分片响应里会带 sVid,封面二段上传要靠它把封面挂到视频上
let sVid: string | undefined;
const handle = await open(path, 'r');
const uploadSlice = async (slice: { seq: number, offset: number, end: number; }) => {
const chunk = await readSlice(handle, slice.offset, slice.end - slice.offset);
for await (const chunk of stream) {
const end = Math.min(offset + chunk.length, img_size);
const form = new FormData();
form.append('uin', uin);
form.append('appid', appid);
form.append('appid', 'qun');
form.append('session', session);
form.append('offset', slice.offset.toString());
form.append('offset', offset.toString());
form.append('data', new Blob([chunk], { type: 'application/octet-stream' }), 'blob');
form.append('checksum', '');
form.append('check_type', '0');
form.append('retry', '0');
form.append('seq', slice.seq.toString());
form.append('end', slice.end.toString());
form.append('cmd', cmd);
form.append('seq', seq.toString());
form.append('end', end.toString());
form.append('cmd', 'FileUpload');
form.append('slice_size', slice_size.toString());
form.append('biz_req.iUploadType', '0');
// 分片路径必须与 cmd 一致:视频走 /sliceUpload/FileUploadVideo,
// 否则服务端按图片处理,分片会「成功」但响应里没有 sVid
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/${cmd}?seq=${slice.seq}&retry=0&offset=${slice.offset}&end=${slice.end}&total=${img_size}&type=form&g_tk=${GTK}`;
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${GTK}`;
const response = await fetch(api, {
method: 'POST',
headers: {
@@ -512,153 +445,24 @@ export class NTQQWebApi {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json() as { ret: number, msg: string, data?: { biz?: { sVid?: string; }; }; };
if (post.ret !== 0) {
throw new Error(`分片 ${slice.seq} 上传失败: ${post.msg}`);
const post = await response.json() as { ret: number, msg: string; }; if (post.ret !== 0) {
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
}
if (!sVid && typeof post.data?.biz?.sVid === 'string' && post.data.biz.sVid) {
sVid = post.data.biz.sVid;
}
};
try {
// 最后一片要等前面的全部传完再发:服务端收到最后一片就认为文件传完了,
// 并发时它可能比前面的分片先到
const lastSlice = slices.pop();
let next = 0;
let failure: { error: unknown; } | undefined;
// 固定数量的 worker 各自领下一片,慢的分片不会拖住整批
const worker = async () => {
while (!failure) {
const slice = slices[next++];
if (!slice) break;
try {
await uploadSlice(slice);
} catch (error) {
if (!failure) failure = { error };
}
}
};
await Promise.all(Array.from({ length: Math.min(QUN_ALBUM_SLICE_CONCURRENCY, slices.length) }, worker));
if (failure) throw failure.error;
if (lastSlice) await uploadSlice(lastSlice);
} finally {
await handle.close();
offset += chunk.length;
seq++;
}
return { success: true, message: '上传完成', sVid };
}
// 多张图片一次上传:共用同一个 batchId,相册里显示为同一条
async uploadImagesToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, paths: string[]) {
if (!paths.length) throw new Error('上传列表为空');
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 batchId = nextQunAlbumBatchId();
const count = paths.length.toString();
for (const [index, path] of paths.entries()) {
const img_md5 = await hashFile(path, 'md5');
const post = await this.createQunAlbumSession(
gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin,
{ batchId, count, index: index.toString() }
);
if (!post.data?.session) throw new Error(`创建群相册会话失败: ${post.msg || post.ret}`);
await this.uploadQunAlbumSlice(path, post.data.session, skey, pskey, uin, this.resolveQunAlbumSliceSize(post.data.slice_size));
}
return { success: true, message: '上传完成' };
}
async uploadImageToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
await this.uploadImagesToQunAlbum(gc, sAlbumID, sAlbumName, [path]);
}
/**
* 上传视频到群相册。
*
* 分三步:
* 1. 建视频会话:appid=video_qun / cmd=FileUploadVideo / SHA1 校验,此时不带相册
* 2. 分片上传视频,从分片响应里拿 sVid
* 3. 按图片上传封面并用 vid 关联视频,相册和批次号在这一步带上,视频随封面进相册
*/
async uploadVideoToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
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 img_md5 = createHash('md5').update(readFileSync(path)).digest('hex');
const uin = this.core.selfInfo.uin || '10001';
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const video_sha1 = await hashFile(path, 'sha1');
// 时长:ffmpeg 不可用时上报 0
let playTime = 0;
try {
playTime = Math.max(0, Math.round(await FFmpegService.getDuration(path)));
} catch (e) {
this.context.logger.logWarn('获取视频时长失败,iPlayTime 上报 0', e);
}
// 1) 视频主体(不带相册,只传成素材)
const videoSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${video_sha1}?g_tk=${GTK}`, 'POST', qunAlbumVideoControl({
uin,
group_id: gc,
pskey,
video_sha1,
video_size: statSync(path).size,
play_time: playTime,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!videoSession.data?.session) throw new Error(`创建群相册视频会话失败: ${videoSession.msg || videoSession.ret}`);
const uploaded = await this.uploadQunAlbumSlice(path, videoSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(videoSession.data.slice_size), { appid: 'video_qun', cmd: 'FileUploadVideo' });
if (!uploaded.sVid) throw new Error('视频上传完成但未取得 sVid,无法挂进相册');
// 2) 封面:抽首帧,失败(含 ffmpeg 不可用)回落内置默认封面
// 用 .png:Native Addon 路径产出的就是 png(日志里可见 Detected format: png),
// 而命令行路径会按扩展名编码,两条路都能得到真正的 PNG
const coverPath = join(this.core.NapCatTempPath, `${randomUUID()}.png`);
try {
try {
await FFmpegService.extractThumbnail(path, coverPath);
} catch (e) {
this.context.logger.logWarn('提取视频封面失败,使用默认封面', e);
await writeFile(coverPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
// 3) 封面二段上传:这一步才带相册和批次号,视频靠它进相册
const cover_md5 = await hashFile(coverPath, 'md5');
const coverSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${cover_md5}?g_tk=${GTK}`, 'POST', qunAlbumVideoCoverControl({
uin,
group_id: gc,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size: statSync(coverPath).size,
vid: uploaded.sVid,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!coverSession.data?.session) throw new Error(`创建群相册视频封面会话失败: ${coverSession.msg || coverSession.ret}`);
await this.uploadQunAlbumSlice(coverPath, coverSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(coverSession.data.slice_size));
} finally {
if (existsSync(coverPath)) {
await unlink(coverPath);
}
}
const session = (await this.createQunAlbumSession(gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin)).data.session;
if (!session) throw new Error('创建群相册会话失败');
await this.uploadQunAlbumSlice(path, session, skey, pskey, uin, 16384);
}
async getAlbumMediaListByNTQQ (gc: string, albumId: string, attach_info: string = '') {
@@ -686,10 +490,10 @@ export class NTQQWebApi {
const client_key = Date.now() * 1000;
return await this.context.session.getAlbumService().doQunComment(
random_seq, {
map_info: [],
map_bytes_info: [],
map_user_account: [],
},
map_info: [],
map_bytes_info: [],
map_user_account: [],
},
qunId,
2,
createAlbumMediaFeed(uin, albumId, lloc),
+55 -265
View File
@@ -18,64 +18,20 @@ export interface BizReq {
iBatchID: number;
iBitmap: number;
iDistinctUse: number;
iNeedFeeds?: number;
iNeedFeeds: number;
iPicHight: number;
iPicWidth: number;
iUploadTime: number;
iUploadType: number;
iUpPicType: number;
iWaterType: number;
mapExt?: MapExt;
mutliPicInfo?: MutliPicInfo;
mapExt: MapExt;
sAlbumID: string;
sAlbumName: string;
sPicDesc: string;
sPicPath: string;
sPicTitle: string;
stExtendInfo?: StExtendInfo;
// 视频主体上传专用
extend_info?: VideoExtendInfo;
iFlag?: number;
iIsFormatF20?: number;
iIsNew?: number;
iIsOriginalVideo?: number;
iPlayTime?: number;
sCoverUrl?: string;
sDesc?: string;
sTitle?: string;
// 视频封面二段上传专用
stExternalMapExt?: StExternalMapExt;
sExif_CameraMaker?: string;
sExif_CameraModel?: string;
sExif_Latitude?: string;
sExif_LatitudeRef?: string;
sExif_Longitude?: string;
sExif_LongitudeRef?: string;
sExif_Time?: string;
}
// 多图同批上传时描述「本批共几张 / 当前第几张」,相册里据此合并成同一条
export interface MutliPicInfo {
iBatUploadNum: string;
iCurUpload: string;
iSuccNum: number;
iFailNum: number;
}
// 视频主体上传用(视频不走 stExtendInfo.mapParams,而是这段扩展信息)
export interface VideoExtendInfo {
video_type: string;
domainid: string;
photo_num: string;
video_num: string;
batch_num: string;
qun_id: string;
}
// 视频封面二段上传用:声明这是客户端上传的封面,且与图片混合在同一条动态里
export interface StExternalMapExt {
is_client_upload_cover: string;
is_pic_video_mix_feeds: string;
stExtendInfo: StExtendInfo;
}
export interface MapExt {
@@ -91,8 +47,6 @@ export interface MapParams {
batch_num: string;
photo_num: string;
video_num: string;
// 视频封面二段上传时用它把封面挂到已上传的视频上
vid?: string;
}
export interface Env {
@@ -106,96 +60,6 @@ export interface Token {
type: number;
}
// 一次上传的批次信息:同批的多张图必须共用 batchId,相册里才会显示成同一条。
export interface QunAlbumBatch {
batchId: number,
count: string,
index: string
}
let lastQunAlbumBatchId = 0;
// 批次号取秒级时间戳。同一秒里发起的两次上传要错开,不然会被相册并成同一条
export function nextQunAlbumBatchId () {
lastQunAlbumBatchId = Math.max(Math.floor(Date.now() / 1000), lastQunAlbumBatchId + 1);
return lastQunAlbumBatchId;
}
// control_req 的外层(鉴权、来源、会话),图片、视频、封面都一样
function buildQunAlbumControlReq (
{ uin, pskey, appid, checksum, check_type, file_len, refer = 'qzone', cmd }: {
uin: string,
pskey: string,
appid: string,
checksum: string,
check_type: number,
file_len: number,
refer?: string,
cmd?: string
},
biz_req: BizReq
): ControlReq {
const req: ControlReq = {
uin,
token: { type: 4, data: pskey, appid: 5 },
appid,
checksum,
check_type,
file_len,
env: { refer, deviceInfo: 'h5' },
model: 0,
biz_req,
session: '',
asy_upload: 0,
};
if (cmd) req.cmd = cmd;
return req;
}
// biz_req 里三种上传都要带的基础字段
function buildQunAlbumBizBase (
{ iUploadType, sAlbumName = '', sAlbumID = '', iBatchID = 0, sPicTitle = '' }: {
iUploadType: number,
sAlbumName?: string,
sAlbumID?: string,
iBatchID?: number,
sPicTitle?: string
}
): BizReq {
return {
sPicTitle,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType,
iUpPicType: 0,
iBatchID,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iUploadTime: Math.floor(Date.now() / 1000),
};
}
// 进相册的那一步(图片、视频封面)要带的群与批次信息
function buildQunAlbumFeedFields (group_id: string, mapParams: MapParams, batchIndex: string) {
return {
iNeedFeeds: 1,
mapExt: { appid: 'qun', userid: group_id },
stExtendInfo: { mapParams },
mutliPicInfo: {
iBatUploadNum: mapParams.batch_num,
iCurUpload: batchIndex,
iSuccNum: 0,
iFailNum: 0,
},
};
}
export function qunAlbumControl ({
uin,
group_id,
@@ -208,8 +72,6 @@ export function qunAlbumControl ({
photo_num = '1',
video_num = '0',
batch_num = '1',
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
}: {
uin: string,
group_id: string,
@@ -221,21 +83,64 @@ export function qunAlbumControl ({
sAlbumID: string,
photo_num?: string,
video_num?: string,
batch_num?: string,
batchId?: number,
batchIndex?: string
batch_num?: string
}
): {
control_req: ControlReq[]
} {
const timestamp = Math.floor(Date.now() / 1000);
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: pic_md5, check_type: 0, file_len: img_size, cmd: 'FileUpload' },
control_req: [
{
...buildQunAlbumBizBase({ iUploadType: 0, sAlbumName, sAlbumID, iBatchID: batchId, sPicTitle: img_name }),
...buildQunAlbumFeedFields(group_id, { photo_num, video_num, batch_num }, batchIndex),
}
)],
uin,
token: {
type: 4,
data: pskey,
appid: 5,
},
appid: 'qun',
checksum: pic_md5,
check_type: 0,
file_len: img_size,
env: {
refer: 'qzone',
deviceInfo: 'h5',
},
model: 0,
biz_req: {
sPicTitle: img_name,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType: 0,
iUpPicType: 0,
iBatchID: timestamp,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iNeedFeeds: 1,
iUploadTime: timestamp,
mapExt: {
appid: 'qun',
userid: group_id,
},
stExtendInfo: {
mapParams: {
photo_num,
video_num,
batch_num,
},
},
},
session: '',
asy_upload: 0,
cmd: 'FileUpload',
}],
};
}
@@ -269,118 +174,3 @@ export function createStreamUpload (
},
};
}
/**
* 视频主体上传的控制体。
*
* 视频这一步不进相册(相册留空,iBatchID 为 0),只是先把视频传成素材;
* 分片响应里拿到 sVid 后,再由封面上传(qunAlbumVideoCoverControl)把视频挂进相册。
*/
export function qunAlbumVideoControl ({
uin,
group_id,
pskey,
video_sha1,
video_size,
play_time = 0,
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
video_sha1: string,
video_size: number,
play_time?: number,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'video_qun', checksum: video_sha1, check_type: 1, file_len: video_size, cmd: 'FileUploadVideo' },
{
...buildQunAlbumBizBase({ iUploadType: 3 }),
sTitle: '',
sDesc: '',
sCoverUrl: '',
iFlag: 0,
iPlayTime: play_time,
iIsNew: 111,
iIsOriginalVideo: 0,
iIsFormatF20: 0,
extend_info: {
video_type: '3',
domainid: '5',
photo_num,
video_num,
batch_num,
qun_id: group_id,
},
}
)],
};
}
/**
* 视频封面上传的控制体。
*
* 按图片上传,但 iUploadType 为 2,并用 mapParams.vid 指向已上传的视频。
* 相册和批次号只在这一步出现,视频是靠封面进的相册。
*/
export function qunAlbumVideoCoverControl ({
uin,
group_id,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size,
vid,
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
sAlbumName: string,
sAlbumID: string,
cover_md5: string,
cover_size: number,
vid: string,
batchId?: number,
batchIndex?: string,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: cover_md5, check_type: 0, file_len: cover_size, refer: 'huodong' },
{
...buildQunAlbumBizBase({ iUploadType: 2, sAlbumName, sAlbumID, iBatchID: batchId }),
...buildQunAlbumFeedFields(group_id, { vid, photo_num, video_num, batch_num }, batchIndex),
// 标明封面由客户端上传,且允许和图片出现在同一条动态里
stExternalMapExt: {
is_client_upload_cover: '1',
is_pic_video_mix_feeds: '1',
},
sExif_CameraMaker: '',
sExif_CameraModel: '',
sExif_Time: '',
sExif_LatitudeRef: '',
sExif_Latitude: '',
sExif_LongitudeRef: '',
sExif_Longitude: '',
}
)],
};
}
+1 -37
View File
@@ -606,41 +606,5 @@
"3.2.30-50969": {
"appid": 537376344,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"3.2.30-50969-arm64": {
"appid": 537376345,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"9.9.33-52230": {
"appid": 537379411,
"qua": "V1_WIN_NQ_9.9.33_52230_GW_B"
},
"3.2.32-52194": {
"appid": 537379447,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"3.2.32-52194-arm64": {
"appid": 537379448,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"9.9.35-52804": {
"appid": 537382717,
"qua": "V1_WIN_NQ_9.9.35_52804_GW_B"
},
"9.9.35-52892": {
"appid": 537382819,
"qua": "V1_WIN_NQ_9.9.35_52892_GW_B"
},
"9.9.36-53489": {
"appid": 537391475,
"qua": "V1_WIN_NQ_9.9.36_53489_GW_B"
},
"3.2.33-52892": {
"appid": 537382855,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"3.2.33-52892-arm64": {
"appid": 537382856,
"qua": "V1_LNX_NQ_3.2.33_52892_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": [
+1 -33
View File
@@ -278,37 +278,5 @@
"3.2.30-50969-arm64": {
"send": "43A4804",
"recv": "1608CC8"
},
"9.9.33-52230-x64": {
"send": "BF2B5F",
"recv": "23BB4DD"
},
"3.2.32-52194-x64": {
"send": "6C45D20",
"recv": "393DE00"
},
"3.2.32-52194-arm64": {
"send": "493FAD8",
"recv": "17EA1DC"
},
"9.9.35-52804-x64": {
"send": "C3614F",
"recv": "246F481"
},
"9.9.35-52892-x64": {
"send": "C361DF",
"recv": "246F3A1"
},
"9.9.36-53489-x64": {
"send": "C3ED0F",
"recv": "24A6235"
},
"3.2.33-52892-x64": {
"send": "6DDB4C0",
"recv": "39DA860"
},
"3.2.33-52892-arm64": {
"send": "4A5D658",
"recv": "1813A34"
}
}
}
+1 -33
View File
@@ -786,37 +786,5 @@
"3.2.30-50969-arm64": {
"send": "75BD1D0",
"recv": "75C0B80"
},
"9.9.33-52230-x64": {
"send": "367FE18",
"recv": "36835CC"
},
"3.2.32-52194-x64": {
"send": "C7DBF80",
"recv": "C7DFA20"
},
"3.2.32-52194-arm64": {
"send": "80F36D0",
"recv": "80F7080"
},
"9.9.35-52804-x64": {
"send": "37C3298",
"recv": "37C6A4C"
},
"9.9.35-52892-x64": {
"send": "37C30D8",
"recv": "37C688C"
},
"9.9.36-53489-x64": {
"send": "38253B0",
"recv": "3828BF0"
},
"3.2.33-52892-x64": {
"send": "CB06D60",
"recv": "CB0A800"
},
"3.2.33-52892-arm64": {
"send": "832ECA0",
"recv": "8332650"
}
}
}
+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,58 +0,0 @@
export interface OfflineRecoveryOptions {
// 当前账号是否在线
isOnline: () => boolean;
// 刚下线:同步 WebUI 状态
onOffline: (tips: string) => void;
// 静默离线期间账号自己恢复了,不需要重启
onRecovered: () => void;
// 重启 Worker;返回 false 或抛错表示失败,之后可以再次触发
restart: (tips: string) => Promise<boolean>;
// 被踢下线后多久重启。常规状态轮询为 3 秒,留出一个轮询周期,确保浏览器先清除旧二维码
kickedDelayMs?: number;
// 静默离线后多久重启。网络短暂断开时 QQ 也可能报离线,先给它自己重连的机会,
// 不然一次网络抖动就会把整个 Worker 重启掉
selfOfflineDelayMs?: number;
}
/**
* 下线恢复:被踢下线(KickedOffLine)和静默离线(SelfOffline)共用。
* 返回的函数在每次收到下线事件时调用,allowSelfRecovery 为 true 表示静默离线。
*/
export function createOfflineRecovery ({
isOnline,
onOffline,
onRecovered,
restart,
kickedDelayMs = 3_500,
selfOfflineDelayMs = 60_000,
}: OfflineRecoveryOptions) {
let restartRequested = false;
let selfRecoveryTimer: ReturnType<typeof setTimeout> | undefined;
return (tips: string, allowSelfRecovery: boolean) => {
onOffline(tips);
if (restartRequested) {
// 被踢时离线状态可能先到:还在等静默离线自行恢复的话,不用再等了
if (allowSelfRecovery || !selfRecoveryTimer) return;
clearTimeout(selfRecoveryTimer);
}
restartRequested = true;
// 不在 RefreshQRcode 请求里直接重启 Worker,否则请求在返回前就被中断,
// 浏览器只能得到 ERR_EMPTY_RESPONSE;延后调度也让前端先看到「二维码已清空、正在恢复」
const timer = setTimeout(() => {
selfRecoveryTimer = undefined;
if (allowSelfRecovery && isOnline()) {
restartRequested = false;
onRecovered();
return;
}
restart(tips).then((ok) => {
if (!ok) restartRequested = false;
}, () => {
restartRequested = false;
});
}, allowSelfRecovery ? selfOfflineDelayMs : kickedDelayMs);
selfRecoveryTimer = allowSelfRecovery ? timer : undefined;
};
}
+2 -3
View File
@@ -79,11 +79,10 @@ export class QQBasicInfoWrapper {
getAppidV2 (): { appid: string; qua: string; } {
// 通过已有表 性能好
const appidTable = AppidTable as unknown as QQAppidTableType;
const appidTbale = AppidTable as unknown as QQAppidTableType;
const fullVersion = this.getFullQQVersion();
if (fullVersion) {
// 同一 Linux 版本的 x64 和 arm64 使用不同的 AppID,优先匹配架构。
const data = appidTable[`${fullVersion}-${process.arch}`] ?? appidTable[fullVersion];
const data = appidTbale[fullVersion];
if (data) {
return data;
}
+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),
+7 -30
View File
@@ -59,30 +59,12 @@ export enum NapCatCoreWorkingEnv {
Framework = 2,
}
function dlopenWrapper (wrapperPath: string): WrapperNodeApi {
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
try {
process.dlopen(nativemodule, wrapperPath);
} catch (error) {
// QQNT.dll 依赖媒体基础(mfplat.dll 等),Windows Server 默认不装这个组件。
// 缺了它系统只会报 The specified module could not be found,看不出缺的是什么
const mfplatPath = path.join(process.env['SystemRoot'] || 'C:\\Windows', 'System32', 'mfplat.dll');
if (os.platform() === 'win32' && !fs.existsSync(mfplatPath)) {
throw new Error(
'加载 wrapper.node 失败:系统缺少「媒体基础」组件(找不到 mfplat.dll),Windows Server 默认不安装它。' +
'请在服务器管理器的「添加角色和功能」里勾选「媒体基础」,' +
'或在管理员 PowerShell 中执行 Install-WindowsFeature Server-Media-Foundation,重启后再启动。' +
`原始错误:${(error as Error).message}`
);
}
throw error;
}
return nativemodule.exports;
}
export function loadQQWrapper (execPath: string | undefined, QQVersion: string): WrapperNodeApi {
if (process.env['NAPCAT_WRAPPER_PATH']) {
return dlopenWrapper(process.env['NAPCAT_WRAPPER_PATH']);
const wrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperPath);
return nativemodule.exports;
}
if (!execPath) {
throw new Error('无法加载Wrapper,execPath未定义');
@@ -103,9 +85,10 @@ export function loadQQWrapper (execPath: string | undefined, QQVersion: string):
if (!fs.existsSync(wrapperNodePath)) {
wrapperNodePath = path.join(path.dirname(execPath), `./resources/app/versions/${QQVersion}/wrapper.node`);
}
const exports = dlopenWrapper(wrapperNodePath);
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperNodePath);
process.env['NAPCAT_WRAPPER_PATH'] = wrapperNodePath;
return exports;
return nativemodule.exports;
}
export function getMajorPath (execPath: string, QQVersion: string): string {
// major.node
@@ -278,14 +261,8 @@ export class NapCatCore {
};
profileListener.onSelfStatusChanged = (Info: SelfStatusInfo) => {
if (Info.status === 20) {
// 静默离线:服务端判定会话失效,但不会下发 KickedOffLine 通知。
// 仅在 在线 -> 离线 的跳变上广播一次,供上层复用下线恢复链路。
const wasOnline = this.selfInfo.online === true;
this.selfInfo.online = false;
this.context.logger.log('账号状态变更为离线');
if (wasOnline) {
this.event.emit('SelfOffline', '[SelfOffline] 账号状态变更为离线(未收到 KickedOffLine 通知)');
}
} else {
this.selfInfo.online = true;
}
@@ -3,7 +3,5 @@ import { TypedEventEmitter } from './typeEvent';
export interface AppEvents {
'event:emoji_like': { groupId: string; senderUin: string; emojiId: string, msgSeq: string, isAdd: boolean, count: number; };
KickedOffLine: string;
// 静默离线:服务端会话已失效,但没有下发 KickedOffLine 通知
SelfOffline: string;
}
export const appEvent = new TypedEventEmitter<AppEvents>();
-2
View File
@@ -78,7 +78,6 @@ export interface WebApiGroupNoticeFeed {
remind_ts: number
tip_window_type: number
confirm_required: number
inst_no_pinned?: number // 仅 inst 条目有:0 = 置顶中,1 = 未置顶
};
read_num: number;
is_read: number;
@@ -93,7 +92,6 @@ export interface WebApiGroupNoticeRet {
read_only: number
role: number
feeds: WebApiGroupNoticeFeed[]
inst?: WebApiGroupNoticeFeed[] // 「发给新成员」类公告,不在 feeds 里
group: {
group_id: number
class_ext: number
+4 -66
View File
@@ -9,7 +9,6 @@ import { logSubscription, LogWrapper } from 'napcat-core/helper/log';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
import { InstanceContext, loadQQWrapper, NapCatCore, NapCatCoreWorkingEnv, NodeIKernelLoginListener, NodeIKernelLoginService, NodeIQQNTWrapperSession, SelfInfo, WrapperNodeApi } from '@/napcat-core';
import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
import { createOfflineRecovery } from '@/napcat-core/helper/offline-recovery';
import { statusHelperSubscription } from '@/napcat-core/helper/status';
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
@@ -106,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());
});
@@ -126,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);
};
@@ -156,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] 二维码已被扫描,等待确认...');
};
@@ -209,44 +194,12 @@ export async function NCoreInitFramework (
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
// 监听下线并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
// KickedOffLine:账号被踢下线;SelfOffline:静默离线(服务端会话语义失效但无通知)。
// 两者复用同一条恢复链路:同步 WebUI -> 重启 Worker -> 快速登录。
const handleOffline = createOfflineRecovery({
isOnline: () => loaderObject.core.selfInfo.online === true,
onOffline: (tips) => {
WebUiDataRuntime.setQQLoginStatus(false);
// 下线后的二维码已失效,绝不能继续交给页面展示或扫码。
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
},
onRecovered: () => {
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('ready');
},
restart: async (tips) => {
try {
const restartResult = await WebUiDataRuntime.requestRestartProcess();
logger.logWarn('[NapCat] [Framework] 账号已离线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (restartResult.result) return true;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
} catch (error) {
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
}
return false;
},
// 监听下线通知并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
loaderObject.core.event.on('KickedOffLine', () => {
WebUiDataRuntime.setQQLoginStatus(false);
});
loaderObject.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
loaderObject.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
}
function registerWebUiLoginCallbacks (
@@ -256,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();
});
// 快速登录
Binary file not shown.
Binary file not shown.
@@ -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,66 +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 } from 'node:fs';
import { unlink } from 'node:fs/promises';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
album_name: Type.String({ description: '相册名称' }),
files: Type.Array(Type.String(), { description: '图片路径、URL或Base64 数组,一次上传多张' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Any({ description: '上传结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class UploadImagesToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.UploadImagesToQunAlbum;
override actionSummary = '上传多张图片到群相册';
override actionDescription = '一次上传多张图片,这些图片在群相册里显示为同一条上传';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
album_name: '相册1',
files: ['/path/to/1.jpg', '/path/to/2.jpg'],
};
override returnExample = {
result: null,
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
if (!payload.files.length) throw new Error('files 不能为空');
const localPaths: string[] = [];
const tempPaths: string[] = [];
try {
for (const file of payload.files) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, file);
localPaths.push(downloadResult.path);
if (!downloadResult.isLocal && downloadResult.path) {
tempPaths.push(downloadResult.path);
}
}
return await this.core.apis.WebApi.uploadImagesToQunAlbum(
payload.group_id,
payload.album_id,
payload.album_name,
localPaths
);
} finally {
for (const path of tempPaths) {
if (existsSync(path)) {
await unlink(path);
}
}
}
}
}
@@ -1,55 +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 } from 'node:fs';
import { unlink } from 'node:fs/promises';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
album_name: Type.String({ description: '相册名称' }),
file: Type.String({ description: '视频路径、URL或Base64' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Any({ description: '上传结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class UploadVideoToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.UploadVideoToQunAlbum;
override actionSummary = '上传视频到群相册';
override actionDescription = '上传视频到群相册,封面自动抽取首帧(失败时使用内置默认封面)';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
album_name: '相册1',
file: '/path/to/video.mp4',
};
override returnExample = {
result: null,
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
try {
return await this.core.apis.WebApi.uploadVideoToQunAlbum(
payload.group_id,
payload.album_id,
payload.album_name,
downloadResult.path
);
} finally {
if (!downloadResult.isLocal && downloadResult.path && existsSync(downloadResult.path)) {
await unlink(downloadResult.path);
}
}
}
}
@@ -55,7 +55,7 @@ export default class GetFriendMsgHistory extends OneBotAction<PayloadType, Retur
}));
// 烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url)))
).filter((msg): msg is OB11Message => msg !== undefined);
return { messages: ob11MsgList };
}
@@ -26,7 +26,7 @@ export class SetQQProfile extends OneBotAction<SetQQProfilePayload, any> {
return await this.core.apis.UserApi.modifySelfProfile({
nick: payload.nickname,
longNick: (payload?.personal_note ?? OldProfile?.longNick) || '',
sex: parseInt(payload.sex != null && payload.sex !== '' ? payload.sex.toString() : OldProfile?.sex!.toString()),
sex: parseInt(payload?.sex ? payload?.sex.toString() : OldProfile?.sex!.toString()),
birthday: {
birthday_year: OldProfile?.birthday_year!.toString(),
birthday_month: OldProfile?.birthday_month!.toString(),
@@ -48,7 +48,7 @@ export default class DelEssenceMsg extends OneBotAction<PayloadType, ReturnType>
const data = this.core.apis.GroupApi.essenceLRU.getValue(+payload.message_id);
if (!data) throw new Error('消息不存在');
const { msg_seq, msg_random, group_id } = JSON.parse(data) as { msg_seq: string, msg_random: string, group_id: string; };
return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_random, msg_seq);
return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_seq, msg_random);
}
return await this.core.apis.GroupApi.removeGroupEssence(
msg.Peer.peerUid,
@@ -21,8 +21,6 @@ const ReturnSchema = Type.Array(Type.Object({
}, { description: '公告内容' }),
settings: Type.Optional(Type.Any({ description: '设置项' })),
read_num: Type.Optional(Type.Number({ description: '阅读数' })),
send_to_new_member: Type.Optional(Type.Boolean({ description: '是否为「发给新成员」公告' })),
pinned: Type.Optional(Type.Boolean({ description: '是否置顶(仅「发给新成员」公告可读到)' })),
}), { description: '群公告列表' });
type ReturnType = Static<typeof ReturnSchema>;
@@ -46,44 +44,30 @@ export class GetGroupNotice extends OneBotAction<PayloadType, ReturnType> {
throw new Error('获取公告失败');
}
const retNotices: ReturnType = [];
const seen = new Set<string>();
// 「发给新成员」类公告只出现在 inst 里,追加在 feeds 之后,保持原有条目的顺序不变
for (const [list, sendToNewMember] of [[ret.feeds, false], [ret.inst, true]] as const) {
for (const retApiNotice of Array.isArray(list) ? list : []) {
if (!retApiNotice || seen.has(retApiNotice.fid)) {
continue;
}
seen.add(retApiNotice.fid);
retNotices.push(this.toNotice(retApiNotice, sendToNewMember));
for (const key in ret.feeds) {
if (!ret.feeds[key]) {
continue;
}
const retApiNotice: WebApiGroupNoticeFeed = ret.feeds[key];
const image = retApiNotice.msg.pics?.map((pic) => {
return { id: pic.id, height: pic.h, width: pic.w };
}) || [];
const retNotice: ReturnType[number] = {
notice_id: retApiNotice.fid,
sender_id: retApiNotice.u,
publish_time: retApiNotice.pubt,
message: {
text: retApiNotice.msg.text,
image,
images: image,
},
settings: retApiNotice.settings,
read_num: retApiNotice.read_num,
};
retNotices.push(retNotice);
}
return retNotices;
}
private toNotice (retApiNotice: WebApiGroupNoticeFeed, sendToNewMember: boolean): ReturnType[number] {
const image = retApiNotice.msg.pics?.map((pic) => {
return { id: pic.id, height: pic.h, width: pic.w };
}) || [];
const retNotice: ReturnType[number] = {
notice_id: retApiNotice.fid,
sender_id: retApiNotice.u,
publish_time: retApiNotice.pubt,
message: {
text: retApiNotice.msg.text,
image,
images: image,
},
settings: retApiNotice.settings,
read_num: retApiNotice.read_num,
send_to_new_member: sendToNewMember,
};
// 置顶状态只在 inst 条目的 settings.inst_no_pinned 里:0 = 置顶中,1 = 未置顶
const instNoPinned = retApiNotice.settings?.inst_no_pinned;
if (typeof instNoPinned === 'number') {
retNotice.pinned = instNoPinned === 0;
}
return retNotice;
}
}
-6
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';
@@ -134,8 +133,6 @@ import { CancelGroupTodo } from './packet/CancelGroupTodo';
import { SetGroupTodo } from './packet/SetGroupTodo';
import { GetQunAlbumList } from './extends/GetQunAlbumList';
import { UploadImageToQunAlbum } from './extends/UploadImageToQunAlbum';
import { UploadImagesToQunAlbum } from './extends/UploadImagesToQunAlbum';
import { UploadVideoToQunAlbum } from './extends/UploadVideoToQunAlbum';
import { DoGroupAlbumComment } from './extends/DoGroupAlbumComment';
import { GetGroupAlbumMediaList } from './extends/GetGroupAlbumMediaList';
import { SetGroupAlbumMediaLike, CancelGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
@@ -184,8 +181,6 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetGroupAlbumMediaList(obContext, core),
new GetQunAlbumList(obContext, core),
new UploadImageToQunAlbum(obContext, core),
new UploadImagesToQunAlbum(obContext, core),
new UploadVideoToQunAlbum(obContext, core),
new SetGroupTodo(obContext, core),
new CompleteGroupTodo(obContext, core),
new CancelGroupTodo(obContext, core),
@@ -201,7 +196,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),
-3
View File
@@ -28,8 +28,6 @@ export const ActionName = {
DoGroupAlbumComment: 'do_group_album_comment',
GetGroupAlbumMediaList: 'get_group_album_media_list',
UploadImageToQunAlbum: 'upload_image_to_qun_album',
UploadImagesToQunAlbum: 'upload_images_to_qun_album',
UploadVideoToQunAlbum: 'upload_video_to_qun_album',
GetQunAlbumList: 'get_qun_album_list',
SetGroupTodo: 'set_group_todo',
CompleteGroupTodo: 'complete_group_todo',
@@ -168,7 +166,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',
+7 -45
View File
@@ -385,30 +385,6 @@ export class OneBotMsgApi {
this.core.context.logger.logError('所有查找方法均失败,获取不到旧客户端的引用消息', element.replayMsgSeq);
}
// 私聊引用:replayMsgSeq 常为 0(客户端未填序号),seq 查询链与协议兜底都会落空,
// 而引用元素里的 replyMsgClientSeq / replyMsgTime 此时依然准确,用它反查被引用消息。
if (element.replyMsgClientSeq) {
try {
const replyMsgTime = element.replyMsgTime ?? records?.msgTime;
if (replyMsgTime) {
const byClientSeq = await this.core.apis.MsgApi.getMsgByClientSeqAndTime(
peer,
element.replyMsgClientSeq,
replyMsgTime
);
const replyMsg = byClientSeq.msgList?.find(msg => msg.msgId);
if (replyMsg) {
return createReplyData(replyMsg.msgId);
}
this.core.context.logger.logWarn(
`按 clientSeq 查询未命中,序号: ${element.replayMsgSeq}, clientSeq: ${element.replyMsgClientSeq}`
);
}
} catch (error) {
this.core.context.logger.logError('按 clientSeq 查询引用消息出错', error);
}
}
// 协议兜底:尝试通过协议直接获取消息
if (this.core.apis.PacketApi.packetStatus) {
try {
@@ -884,23 +860,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,
@@ -1165,8 +1130,8 @@ export class OneBotMsgApi {
resMsg.sub_type = 'normal';
resMsg.group_id = parseInt(msg.peerUin);
resMsg.group_name = msg.peerName;
// getGroupMember 找不到成员时内部已经刷新过一次缓存,这里不用再查第二遍
const member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
let member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
if (!member) member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
if (member) {
resMsg.sender.role = OB11Construct.groupMemberRole(member.role);
resMsg.sender.nickname = member.nick;
@@ -1189,12 +1154,9 @@ export class OneBotMsgApi {
resMsg.sub_type = 'group';
const ret = await this.core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, msg.senderUid);
if (ret.result === 0) {
// 临时会话的 peerUin 是对方 QQ 号,成员要去来源群里找;uid 一般不空,优先用 uid 查
const groupCode = ret.tmpChatInfo!.groupCode;
const member = groupCode
? await this.core.apis.GroupApi.getGroupMember(groupCode, msg.senderUid || msg.senderUin)
: undefined;
resMsg.group_id = parseInt(groupCode);
// 避免uin:'' uid非空,uid一般不空
const member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, await this.core.apis.UserApi.getUinByUidV2(msg.senderUid));
resMsg.group_id = parseInt(ret.tmpChatInfo!.groupCode);
resMsg.sender.nickname = member?.nick ?? member?.cardName ?? '临时会话';
resMsg.temp_source = 0;
} else {
-3
View File
@@ -135,9 +135,6 @@ export class OB11Construct {
creator: +folder.createUin,
creator_name: folder.creatorName,
total_file_count: folder.totalFileCount,
modify_time: folder.modifyTime,
modifier: +folder.modifyUin,
modifier_name: folder.modifyName,
};
}
}
@@ -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";
}
/**
-3
View File
@@ -105,7 +105,4 @@ export interface OB11GroupFileFolder {
creator: number; // 创建者ID
creator_name: string; // 创建者名称
total_file_count: number; // 文件总数
modify_time: number; // 最后修改时间
modifier: number; // 最后修改者ID
modifier_name: string; // 最后修改者名称
}
-1
View File
@@ -14,7 +14,6 @@
"napcat-vite": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.1",
"tsx": "^4.7.1",
"vite": "^6.0.0"
}
+13 -92
View File
@@ -37,7 +37,6 @@ import { OidbSvcTrpcTcpBase, OidbSvcTrpcTcp0XCDE_2RespBody } from '@/napcat-core
import { loadNapcatConfig } from '@/napcat-core/helper/config';
import { logSubscription, LogWrapper } from '@/napcat-core/helper/log';
import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
import { createOfflineRecovery } from '@/napcat-core/helper/offline-recovery';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
import { statusHelperSubscription } from '@/napcat-core/helper/status';
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
@@ -127,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;
@@ -143,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,
@@ -158,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');
@@ -205,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();
}
};
@@ -232,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) {
@@ -253,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,39 +792,11 @@ export class NapCatShell {
// }
// }
// 监听下线并同步到 WebUI
// KickedOffLine:账号被踢下线;SelfOffline:静默离线(服务端会话语义失效但无通知)。
// 两者复用同一条恢复链路:同步 WebUI -> 重启 Worker -> 快速登录。
const handleOffline = createOfflineRecovery({
isOnline: () => this.core.selfInfo.online === true,
onOffline: (tips) => {
WebUiDataRuntime.setQQLoginStatus(false);
// 下线后的二维码已失效,绝不能继续交给页面展示或扫码。
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
},
onRecovered: () => {
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('ready');
},
restart: async (tips) => {
try {
const restartResult = await WebUiDataRuntime.requestRestartProcess();
this.context.logger.logWarn('[Core] [Login] 账号已离线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (restartResult.result) return true;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
} catch (error) {
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
}
return false;
},
// 监听下线通知并同步到 WebUI
this.core.event.on('KickedOffLine', (tips: string) => {
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginError(tips);
});
this.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
this.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
// 使用 NapCatAdapterManager 统一管理协议适配器
const adapterManager = new NapCatAdapterManager(this.core, this.context, this.context.pathWrapper);
await adapterManager.initAdapters()
@@ -881,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,53 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { MessageUnique } from '../napcat-common/src/message-unique';
import DelEssenceMsg from '../napcat-onebot/action/group/DelEssenceMsg';
function createAction (essenceLRUValue: string | undefined) {
const removeGroupEssenceBySeq = vi.fn().mockResolvedValue({ result: 0 });
const action = new DelEssenceMsg(
undefined as never,
{
apis: {
GroupApi: {
essenceLRU: { getValue: vi.fn().mockReturnValue(essenceLRUValue) },
removeGroupEssenceBySeq,
},
},
} as never
);
return { action, removeGroupEssenceBySeq };
}
describe('delete_essence_msg argument order', () => {
afterEach(() => {
vi.restoreAllMocks();
});
test('passes msg_random before msg_seq for explicitly supplied parameters', async () => {
const { action, removeGroupEssenceBySeq } = createAction(undefined);
await action._handle({ group_id: '33', msg_seq: '11', msg_random: '22' });
// GroupApi.removeGroupEssenceBySeq(groupCode, msgRandom, msgSeq)
expect(removeGroupEssenceBySeq).toHaveBeenCalledWith('33', '22', '11');
});
test('passes msg_random before msg_seq for the essence LRU fallback', async () => {
// get_essence_msg_list stores this payload under a synthetic message_id when the
// original message can no longer be resolved from the local message cache.
const { action, removeGroupEssenceBySeq } = createAction(JSON.stringify({
msg_seq: '11',
msg_random: '22',
group_id: '33',
}));
vi.spyOn(MessageUnique, 'getMsgIdAndPeerByShortId').mockReturnValue(undefined);
await action._handle({ message_id: 12345 });
// GroupApi.removeGroupEssenceBySeq(groupCode, msgRandom, msgSeq)
expect(removeGroupEssenceBySeq).toHaveBeenCalledWith('33', '22', '11');
});
});
@@ -1,89 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { afterEach, describe, expect, test, vi } from 'vitest';
import type { NetworkAdapterConfig } from '../napcat-onebot/config/config';
import GetFriendMsgHistory from '../napcat-onebot/action/go-cqhttp/GetFriendMsgHistory';
// `GetFriendMsgHistory` imports `napcat-core/types` via the bare package subpath,
// which Node exports resolution cannot map in this workspace (`./*` pattern cannot
// target an extensionless directory). Remap it onto the aliased source tree.
vi.mock('napcat-core/types', async () => await vi.importActual('@/napcat-core/types/index'));
vi.mock('napcat-common/src/message-unique', async () => await vi.importActual('@/napcat-common/src/message-unique'));
const SAMPLE_MSG = {
msgId: '100',
msgSeq: '1',
chatType: 1,
peerUid: 'friend-uid',
peerUin: '42',
senderUin: '42',
msgTime: '1700000000',
msgRandom: '1',
elements: [],
} as never;
const TEST_ADAPTER = 'test';
const TEST_CONFIG = { messagePostFormat: 'array' } as NetworkAdapterConfig;
function createHistoryAction () {
const parseMessage = vi.fn().mockResolvedValue({ message: [], raw_message: '' });
const core = {
selfInfo: { uid: 'self-uid', uin: '1' },
apis: {
UserApi: { getUidByUinV2: vi.fn().mockResolvedValue('friend-uid') },
FriendApi: { isBuddy: vi.fn().mockResolvedValue(true) },
MsgApi: {
getAioFirstViewLatestMsgs: vi.fn().mockResolvedValue({ msgList: [SAMPLE_MSG] }),
},
},
};
const obContext = {
apis: { MsgApi: { parseMessage } },
};
const action = new GetFriendMsgHistory(obContext as never, core as never);
return { action, parseMessage };
}
describe('get_friend_msg_history quick_reply forwarding', () => {
afterEach(() => {
vi.restoreAllMocks();
});
test('forwards quick_reply: true to parseMessage', async () => {
const { action, parseMessage } = createHistoryAction();
await action._handle(
{ user_id: '42', count: 20, reverse_order: false, disable_get_url: false, parse_mult_msg: true, quick_reply: true, reverseOrder: false },
TEST_ADAPTER,
TEST_CONFIG
);
expect(parseMessage).toHaveBeenCalledWith(
SAMPLE_MSG,
'array',
true,
false,
true
);
});
test('forwards quick_reply: false (default) to parseMessage', async () => {
const { action, parseMessage } = createHistoryAction();
await action._handle(
{ user_id: '42', count: 20, reverse_order: false, disable_get_url: false, parse_mult_msg: true, quick_reply: false, reverseOrder: false },
TEST_ADAPTER,
TEST_CONFIG
);
expect(parseMessage).toHaveBeenCalledWith(
SAMPLE_MSG,
'array',
true,
false,
false
);
});
});
@@ -1,71 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, test, vi } from 'vitest';
import { GetGroupNotice } from '../napcat-onebot/action/group/GetGroupNotice';
function feed (fid: string, settings?: Record<string, number>) {
return {
u: 10001,
fid,
pubt: 1750000000,
msg: { text: `notice ${fid}`, text_face: '', title: '' },
type: 1,
fn: 0,
cn: 0,
vn: 0,
settings,
read_num: 3,
is_read: 0,
is_all_confirm: 0,
};
}
function createAction (ret: unknown) {
return new GetGroupNotice(
undefined as never,
{ apis: { WebApi: { getGroupNotice: vi.fn().mockResolvedValue(ret) } } } as never
);
}
describe('_get_group_notice', () => {
test('returns "send to new member" notices from inst after feeds', async () => {
const action = createAction({
ec: 0,
feeds: [feed('feed-1'), feed('feed-2')],
inst: [feed('inst-1', { inst_no_pinned: 0 })],
});
const notices = await action._handle({ group_id: '123' });
expect(notices.map(n => n.notice_id)).toEqual(['feed-1', 'feed-2', 'inst-1']);
expect(notices.map(n => n.send_to_new_member)).toEqual([false, false, true]);
expect(notices[2]?.message.text).toBe('notice inst-1');
});
test('maps inst_no_pinned to pinned only when the field is present', async () => {
const action = createAction({
ec: 0,
feeds: [feed('feed-1', { tip_window_type: 1 })],
inst: [feed('pinned', { inst_no_pinned: 0 }), feed('unpinned', { inst_no_pinned: 1 })],
});
const notices = await action._handle({ group_id: '123' });
expect(notices.find(n => n.notice_id === 'feed-1')?.pinned).toBeUndefined();
expect(notices.find(n => n.notice_id === 'pinned')?.pinned).toBe(true);
expect(notices.find(n => n.notice_id === 'unpinned')?.pinned).toBe(false);
});
test('keeps working when inst is missing and skips duplicated notices', async () => {
const withoutInst = await createAction({ ec: 0, feeds: [feed('feed-1')] })._handle({ group_id: '123' });
expect(withoutInst.map(n => n.notice_id)).toEqual(['feed-1']);
const duplicated = await createAction({
ec: 0,
feeds: [feed('same')],
inst: [feed('same', { inst_no_pinned: 0 })],
})._handle({ group_id: '123' });
expect(duplicated.map(n => n.notice_id)).toEqual(['same']);
});
});
@@ -1,282 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { NTQQWebApi } from '@/napcat-core/apis/webapi';
import { nextQunAlbumBatchId, qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl } from '@/napcat-core/data/webapi';
const GROUP_ID = '2161015335';
const ALBUM_ID = 'V624Oe3c1Dk7pX4et6lh4703uM49iGAR';
const ALBUM_NAME = '水哥';
const UIN = '2965296625';
// control_req 在严格模式(noUncheckedIndexedAccess)下是可选元素,这里统一收敛掉
const firstReq = (body: { control_req: unknown[] }) => {
const req = body.control_req[0];
if (!req) throw new Error('control_req 为空');
return req as NonNullable<ReturnType<typeof qunAlbumControl>['control_req'][0]>;
};
const imageReq = (overrides: Record<string, unknown> = {}) => firstReq(qunAlbumControl({
uin: UIN,
group_id: GROUP_ID,
pskey: 'PSKEY',
pic_md5: 'MD5A',
img_size: 12345,
img_name: 'a.jpg',
sAlbumName: ALBUM_NAME,
sAlbumID: ALBUM_ID,
...overrides,
}));
describe('群相册图片组包', () => {
it('单图:字段与改动前一致,批次号为秒级时间戳', () => {
const req = imageReq();
expect(req.appid).toBe('qun');
expect(req.cmd).toBe('FileUpload');
expect(req.check_type).toBe(0);
expect(req.checksum).toBe('MD5A');
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
expect(req.biz_req?.sPicTitle).toBe('a.jpg');
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
expect(req.biz_req?.iUploadType).toBe(0);
expect(req.biz_req?.iNeedFeeds).toBe(1);
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: '1', video_num: '0', batch_num: '1' });
// 每张图各自成批时,批次号仍是 10 位秒级时间戳
expect(String(req.biz_req?.iBatchID)).toHaveLength(10);
});
it('同一秒内的两次上传批次号不同,不会被相册并成一条', () => {
const first = imageReq().biz_req?.iBatchID;
const second = imageReq().biz_req?.iBatchID;
expect(second).toBeGreaterThan(first ?? Infinity);
expect(nextQunAlbumBatchId()).toBeGreaterThan(second ?? Infinity);
});
it('多图同批:共用批次号,张数与序号按批上报', () => {
const batchId = 1791038000;
const total = '3';
const reqs = [0, 1, 2].map(i => imageReq({
pic_md5: `MD5${i}`,
batchId,
batchIndex: String(i),
photo_num: total,
batch_num: total,
}));
expect(new Set(reqs.map(r => r.biz_req?.iBatchID)).size).toBe(1);
expect(reqs[0]?.biz_req?.iBatchID).toBe(batchId);
reqs.forEach((req, i) => {
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: total, video_num: '0', batch_num: total });
expect(req.biz_req?.mutliPicInfo).toEqual({
iBatUploadNum: total,
iCurUpload: String(i),
iSuccNum: 0,
iFailNum: 0,
});
expect(req.checksum).toBe(`MD5${i}`);
});
});
});
describe('群相册视频组包', () => {
it('视频主体:video_qun / FileUploadVideo / SHA1,且不带相册与批次号', () => {
const req = firstReq(qunAlbumVideoControl({
uin: UIN,
group_id: GROUP_ID,
pskey: 'PSKEY',
video_sha1: 'SHA1A',
video_size: 1048576,
play_time: 37,
}));
expect(req.appid).toBe('video_qun');
expect(req.cmd).toBe('FileUploadVideo');
expect(req.check_type).toBe(1);
expect(req.checksum).toBe('SHA1A');
expect(req.file_len).toBe(1048576);
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
expect(req.biz_req?.iUploadType).toBe(3);
expect(req.biz_req?.iPlayTime).toBe(37);
expect(req.biz_req?.iIsNew).toBe(111);
// 视频主体不参与批次:iBatchID 固定 0,相册留空,也没有 mutliPicInfo
expect(req.biz_req?.iBatchID).toBe(0);
expect(req.biz_req?.sAlbumID).toBe('');
expect(req.biz_req?.sAlbumName).toBe('');
expect(req.biz_req?.mutliPicInfo).toBeUndefined();
expect(req.biz_req?.stExtendInfo).toBeUndefined();
expect(req.biz_req?.mapExt).toBeUndefined();
expect(req.biz_req?.extend_info).toEqual({
video_type: '3',
domainid: '5',
photo_num: '0',
video_num: '1',
batch_num: '1',
qun_id: GROUP_ID,
});
});
it('封面二段:走图片口径带相册与批次号,并用 vid 绑定视频', () => {
const batchId = 1791038000;
const req = firstReq(qunAlbumVideoCoverControl({
uin: UIN,
group_id: GROUP_ID,
pskey: 'PSKEY',
sAlbumName: ALBUM_NAME,
sAlbumID: ALBUM_ID,
cover_md5: 'COVERMD5',
cover_size: 20000,
vid: 'SV123',
batchId,
}));
expect(req.appid).toBe('qun');
expect(req.cmd).toBeUndefined();
expect(req.check_type).toBe(0);
expect(req.checksum).toBe('COVERMD5');
// 封面这一步才带相册和批次号——视频靠它进相册
expect(req.env).toEqual({ refer: 'huodong', deviceInfo: 'h5' });
expect(req.biz_req?.iUploadType).toBe(2);
expect(req.biz_req?.iBatchID).toBe(batchId);
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
expect(req.biz_req?.iNeedFeeds).toBe(1);
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({
vid: 'SV123',
photo_num: '0',
video_num: '1',
batch_num: '1',
});
expect(req.biz_req?.stExternalMapExt).toEqual({
is_client_upload_cover: '1',
is_pic_video_mix_feeds: '1',
});
expect(req.biz_req?.mutliPicInfo).toEqual({
iBatUploadNum: '1',
iCurUpload: '0',
iSuccNum: 0,
iFailNum: 0,
});
expect(req.biz_req?.mapExt).toEqual({ appid: 'qun', userid: GROUP_ID });
});
});
describe('群相册分片上传', () => {
let tempDir: string;
let sliceFile: string;
const createApi = () => new NTQQWebApi(
{ logger: { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn(), logDebug: vi.fn() } } as never,
{ NapCatTempPath: tempDir } as never
);
beforeEach(async () => {
tempDir = await mkdtemp(path.join(tmpdir(), 'napcat-album-slice-'));
sliceFile = path.join(tempDir, 'payload.bin');
// 40000 字节 / 16384 分片 = 3 片
await writeFile(sliceFile, Buffer.alloc(40000, 7));
});
afterEach(async () => {
vi.unstubAllGlobals();
await rm(tempDir, { recursive: true, force: true });
});
it('按分片大小切片,把 appid/cmd 透传到每个分片请求,并回收 sVid', async () => {
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({
ret: 0,
msg: '',
data: { biz: { sVid: 'SV123' } },
}), { status: 200 }));
vi.stubGlobal('fetch', fetchMock);
const result = await createApi().uploadQunAlbumSlice(
sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384,
{ appid: 'video_qun', cmd: 'FileUploadVideo' }
);
expect(fetchMock).toHaveBeenCalledTimes(3);
expect(result).toMatchObject({ success: true, sVid: 'SV123' });
// 分片是并发发出的,调用顺序不确定,按 seq 建索引再断言
const forms = new Map(fetchMock.mock.calls.map((call) => {
const form = call[1]?.body as unknown as FormData;
return [form.get('seq'), form] as const;
}));
const first = forms.get('0');
expect(first).toBeDefined();
expect(first?.get('appid')).toBe('video_qun');
expect(first?.get('cmd')).toBe('FileUploadVideo');
expect(first?.get('session')).toBe('SESSION');
expect(first?.get('offset')).toBe('0');
expect(first?.get('end')).toBe('16384');
expect(first?.get('slice_size')).toBe('16384');
const urls = fetchMock.mock.calls.map(call => String(call[0]));
expect(urls.some(url => url.includes('seq=0&retry=0&offset=0&end=16384&total=40000'))).toBe(true);
expect(urls.some(url => url.includes('seq=2&retry=0&offset=32768&end=40000&total=40000'))).toBe(true);
// 路径必须跟随 cmd:视频走 /sliceUpload/FileUploadVideo,否则服务端不返回 sVid
expect(urls.every(url => url.includes('/webapp/json/sliceUpload/FileUploadVideo?'))).toBe(true);
});
it('不传 appid/cmd 时退回图片口径(路径也是 FileUpload)', async () => {
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 }));
vi.stubGlobal('fetch', fetchMock);
const result = await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
const form = fetchMock.mock.calls[0]?.[1]?.body as unknown as FormData;
expect(form.get('appid')).toBe('qun');
expect(form.get('cmd')).toBe('FileUpload');
expect(String(fetchMock.mock.calls[0]?.[0])).toContain('/webapp/json/sliceUpload/FileUpload?');
expect(result.sVid).toBeUndefined();
});
it('最后一片等其它分片全部传完才发', async () => {
// 100000 字节 / 16384 = 7 片(seq 0~6)
await writeFile(sliceFile, Buffer.alloc(100000, 7));
let finished = 0;
let finishedWhenLastSent = -1;
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
const seq = Number((init.body as unknown as FormData).get('seq'));
if (seq === 6) {
finishedWhenLastSent = finished;
} else {
// 前面的分片故意慢一点、倒序完成
await new Promise(resolve => setTimeout(resolve, (6 - seq) * 5));
finished++;
}
return new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 });
});
vi.stubGlobal('fetch', fetchMock);
await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
expect(fetchMock).toHaveBeenCalledTimes(7);
expect(finishedWhenLastSent).toBe(6);
});
it('前面的分片失败时不再发最后一片', async () => {
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
const seq = (init.body as unknown as FormData).get('seq');
return new Response(JSON.stringify(seq === '1' ? { ret: -1, msg: 'boom' } : { ret: 0, msg: '' }), { status: 200 });
});
vi.stubGlobal('fetch', fetchMock);
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
.rejects.toThrow('分片 1 上传失败: boom');
const seqs = fetchMock.mock.calls.map(call => (call[1]?.body as unknown as FormData).get('seq'));
expect(seqs).not.toContain('2');
});
it('分片失败时抛出带序号与原因的错误', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ ret: -1, msg: 'boom' }), { status: 200 })));
// 分片是并发上传的,Promise.all 抛出的是最先失败的那一片,序号不确定
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
.rejects.toThrow(/分片 \d+ 上传失败: boom/);
});
});
-29
View File
@@ -1,29 +0,0 @@
import { describe, expect, test } from 'vitest';
import { OB11Construct } from '../napcat-onebot/helper/data';
describe('group file folder construction', () => {
test('exposes the last modification time and modifier of a folder', () => {
const folder = OB11Construct.folder('123', {
folderId: '/folder-1',
parentFolderId: '/',
folderName: '资料',
createTime: 1700000000,
modifyTime: 1750000000,
createUin: '10001',
creatorName: 'creator',
totalFileCount: 2,
modifyUin: '10002',
modifyName: 'uploader',
usedSpace: '0',
});
expect(folder).toMatchObject({
group_id: 123,
folder_id: '/folder-1',
creator: 10001,
modify_time: 1750000000,
modifier: 10002,
modifier_name: 'uploader',
});
});
});
@@ -1,140 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, test, vi } from 'vitest';
import { ChatType, type GroupMember, type RawMessage } from 'napcat-core';
import { NTQQGroupApi } from '../napcat-core/apis/group';
import { NTQQUserApi } from '../napcat-core/apis/user';
import { OneBotMsgApi } from '../napcat-onebot/api/msg';
vi.mock('../napcat-webui-backend/index', () => ({
pendingTokenToSend: undefined,
}));
vi.mock('../napcat-webui-backend/src/helper/Data', () => ({
WebUiDataRuntime: {},
}));
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/http-server-sse', () => ({
OB11HttpSSEServerAdapter: class {},
}));
vi.mock('@/napcat-onebot/network/plugin-manger', () => ({
OB11PluginMangerAdapter: class {},
}));
// msg.ts 按目录导入 proto,vitest 解析不了;这里用不到,给个空模块
vi.mock('napcat-core/packet/transformer/proto', () => ({}));
function member (uid: string, uin: string, nick: string) {
return { uid, uin, nick, cardName: '', role: 2 } as unknown as GroupMember;
}
function memberList (...members: GroupMember[]) {
return {
errCode: 0,
errMsg: '',
result: { ids: [], infos: new Map(members.map(m => [m.uid, m])), finish: true, hasRobot: false },
};
}
function createGroupApi (getAllMemberList: ReturnType<typeof vi.fn>) {
const context = {
session: { getGroupService: () => ({ getAllMemberList }) },
logger: { logError: vi.fn() },
};
return new NTQQGroupApi(context as never, {} as never);
}
describe('group member lookup', () => {
test('returns undefined instead of throwing when the member list of a new group cannot be fetched', async () => {
const getAllMemberList = vi.fn()
.mockRejectedValueOnce(new Error('timeout'))
.mockResolvedValueOnce({ errCode: 1, errMsg: 'not ready', result: undefined });
const groupApi = createGroupApi(getAllMemberList);
await expect(groupApi.getGroupMember('1053882091', '2060875951')).resolves.toBeUndefined();
await expect(groupApi.getGroupMember('1053882091', 'u_member')).resolves.toBeUndefined();
// 拉不到的结果不能写进缓存,否则之后一直拿到空成员表
expect(groupApi.groupMemberCache.has('1053882091')).toBe(false);
// 每次调用只拉一次,不会为同一条消息重复强制刷新
expect(getAllMemberList).toHaveBeenCalledTimes(2);
});
test('refreshes a cached group once when a new member is not in the cache yet', async () => {
const oldMember = member('u_old', '10001', 'old');
const newMember = member('u_new', '10002', 'new');
const getAllMemberList = vi.fn().mockResolvedValue(memberList(oldMember, newMember));
const groupApi = createGroupApi(getAllMemberList);
groupApi.groupMemberCache.set('123', new Map([[oldMember.uid, oldMember]]));
await expect(groupApi.getGroupMember('123', '10002')).resolves.toBe(newMember);
await expect(groupApi.getGroupMember('123', 'u_new')).resolves.toBe(newMember);
expect(getAllMemberList).toHaveBeenCalledTimes(1);
});
test('uin to uid falls back to the cached group members before the network lookup', async () => {
const groupApi = createGroupApi(vi.fn());
groupApi.groupMemberCache.set('123', new Map([['u_new', member('u_new', '3680714873', 'new')]]));
const callNoListenerEvent = vi.fn();
const context = {
session: {
getUixConvertService: () => ({ getUid: vi.fn().mockResolvedValue({ uidInfo: new Map() }) }),
getProfileService: () => ({ getUidByUin: vi.fn().mockReturnValue(new Map()) }),
getGroupService: () => ({ getUidByUins: vi.fn().mockResolvedValue({ uids: new Map() }) }),
},
};
const userApi = new NTQQUserApi(context as never, {
apis: { GroupApi: groupApi },
eventWrapper: { callNoListenerEvent },
} as never);
await expect(userApi.getUidByUinV2('3680714873')).resolves.toBe('u_new');
expect(callNoListenerEvent).not.toHaveBeenCalled();
});
test('temp messages look up the sender in the source group instead of using the sender QQ as group', async () => {
const getGroupMember = vi.fn().mockResolvedValue(member('u_temp', '3680714873', 'temp sender'));
const msgApi = new OneBotMsgApi(undefined as never, {
apis: {
MsgApi: { getTempChatInfo: vi.fn().mockResolvedValue({ result: 0, tmpChatInfo: { groupCode: '603036233' } }) },
GroupApi: { getGroupMember },
},
} as never);
const resMsg = { sender: {} } as Record<string, unknown> & { sender: Record<string, unknown>; };
const msg = {
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
senderUid: 'u_temp',
senderUin: '3680714873',
peerUid: 'u_temp',
peerUin: '3680714873',
} as RawMessage;
await (msgApi as unknown as { handleTempGroupMessage (r: unknown, m: RawMessage): Promise<void>; })
.handleTempGroupMessage(resMsg, msg);
expect(getGroupMember).toHaveBeenCalledWith('603036233', 'u_temp');
expect(resMsg).toMatchObject({ sub_type: 'group', group_id: 603036233, sender: { nickname: 'temp sender' } });
});
});
+1 -3
View File
@@ -1,5 +1,4 @@
import { describe, expect, test } from 'vitest';
import type { GeneralCallResultStatus } from '../napcat-core/services/common';
import {
applyGroupManagementSettings,
createGroupDetailInfoV2Param,
@@ -11,8 +10,7 @@ describe('NTQQ group operations', () => {
test('reports the exact native setting that failed', () => {
expect(() => assertGroupManagementResults('设置群成员功能权限', [{
setting: 'allow_member_create_group',
// 枚举里只有 OK/ERROR,这里刻意用一个任意的原生错误码
result: { result: 1006 as GeneralCallResultStatus, errMsg: '未知错误' },
result: { result: 1006, errMsg: '未知错误' },
}])).toThrow(/allow_member_create_group.*1006.*未知错误/);
expect(() => assertGroupManagementResults('设置群成员功能权限', []))
.not.toThrow();
@@ -1,46 +0,0 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import { loadQQWrapper } from '../napcat-core/index';
describe('loadQQWrapper', () => {
const originalWrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
beforeEach(() => {
process.env['NAPCAT_WRAPPER_PATH'] = 'E:\\NapCat\\wrapper.node';
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw new Error('The specified module could not be found.\r\n\\\\?\\E:\\NapCat\\wrapper.node');
});
});
afterEach(() => {
vi.restoreAllMocks();
if (originalWrapperPath === undefined) {
delete process.env['NAPCAT_WRAPPER_PATH'];
} else {
process.env['NAPCAT_WRAPPER_PATH'] = originalWrapperPath;
}
});
test('explains the missing Media Foundation feature on Windows Server', () => {
vi.spyOn(os, 'platform').mockReturnValue('win32');
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(() => loadQQWrapper(undefined, '9.9.33-52230'))
.toThrow(/媒体基础.*Install-WindowsFeature Server-Media-Foundation.*The specified module could not be found/s);
});
test('keeps the original error when Media Foundation is installed', () => {
vi.spyOn(os, 'platform').mockReturnValue('win32');
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(() => loadQQWrapper(undefined, '9.9.33-52230')).toThrow(/^The specified module could not be found/);
});
test('keeps the original error on other platforms', () => {
vi.spyOn(os, 'platform').mockReturnValue('linux');
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(() => loadQQWrapper(undefined, '3.2.32-52194')).toThrow(/^The specified module could not be found/);
});
});
@@ -1,98 +0,0 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { createOfflineRecovery } from '../napcat-core/helper/offline-recovery';
function setup (restartResult: boolean | Error = true) {
const state = { online: false };
const onOffline = vi.fn();
const onRecovered = vi.fn();
const restart = vi.fn(async () => {
if (restartResult instanceof Error) throw restartResult;
return restartResult;
});
const handleOffline = createOfflineRecovery({
isOnline: () => state.online,
onOffline,
onRecovered,
restart,
});
return { state, onOffline, onRecovered, restart, handleOffline };
}
describe('offline recovery', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
test('kicked offline restarts after a short delay', async () => {
const { restart, onOffline, handleOffline } = setup();
handleOffline('kicked', false);
expect(onOffline).toHaveBeenCalledWith('kicked');
await vi.advanceTimersByTimeAsync(3_000);
expect(restart).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(500);
expect(restart).toHaveBeenCalledTimes(1);
expect(restart).toHaveBeenCalledWith('kicked');
});
test('silent offline waits for the account to reconnect before restarting', async () => {
const { restart, handleOffline } = setup();
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(60_000);
expect(restart).toHaveBeenCalledTimes(1);
});
test('silent offline that recovers on its own does not restart', async () => {
const { state, restart, onRecovered, handleOffline } = setup();
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(10_000);
state.online = true;
await vi.advanceTimersByTimeAsync(60_000);
expect(restart).not.toHaveBeenCalled();
expect(onRecovered).toHaveBeenCalledTimes(1);
});
test('a kick during the silent-offline wait restarts without waiting the full minute', async () => {
const { restart, handleOffline } = setup();
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(1_000);
handleOffline('kicked', false);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).toHaveBeenCalledTimes(1);
expect(restart).toHaveBeenCalledWith('kicked');
await vi.advanceTimersByTimeAsync(120_000);
expect(restart).toHaveBeenCalledTimes(1);
});
test('repeated offline events schedule only one restart', async () => {
const { restart, onOffline, handleOffline } = setup();
handleOffline('kicked', false);
handleOffline('kicked again', false);
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(120_000);
expect(restart).toHaveBeenCalledTimes(1);
expect(onOffline).toHaveBeenCalledTimes(3);
});
test.each([false, new Error('boom')])('a failed restart (%s) can be retried by the next offline event', async (result) => {
const { restart, handleOffline } = setup(result);
handleOffline('kicked', false);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).toHaveBeenCalledTimes(1);
handleOffline('kicked', false);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).toHaveBeenCalledTimes(2);
});
});
@@ -1,123 +0,0 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { NapCatCore } from '../napcat-core/index';
import type { SelfStatusInfo, SelfInfo } from '../napcat-core/types';
interface FakeProfileListener {
onSelfStatusChanged: (info: SelfStatusInfo) => void;
}
interface FakeMessageListener {
onKickedOffLine: (info: { tipsTitle: string; tipsDesc: string; }) => void;
}
function status (value: number): SelfStatusInfo {
return {
uid: 'self-uid',
status: value,
extStatus: 0,
termType: 0,
netType: 0,
iconType: 0,
customStatus: undefined,
setTime: '0',
};
}
function createCore (online: boolean | undefined) {
let profileListener: FakeProfileListener | undefined;
let messageListener: FakeMessageListener | undefined;
const session = {
getMsgService: () => ({
addKernelMsgListener: vi.fn((listener: FakeMessageListener) => {
messageListener = listener;
}),
}),
getProfileService: () => ({
addKernelProfileListener: vi.fn((listener: FakeProfileListener) => {
profileListener = listener;
}),
}),
};
const logger = {
log: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
logDebug: vi.fn(),
};
const emit = vi.fn();
// NapCatCore's constructor loads the native wrapper, which is unavailable in tests.
// Only the listener wiring is under test, so the instance is built field-by-field.
const core = Object.create(NapCatCore.prototype) as NapCatCore;
Object.assign(core, {
context: { logger, session },
selfInfo: { uid: 'self-uid', uin: '1', online } as SelfInfo,
event: { emit },
});
return {
core,
emit,
profileListener: () => profileListener,
messageListener: () => messageListener,
};
}
describe('silent offline (SelfOffline) event', () => {
afterEach(() => {
vi.restoreAllMocks();
});
test('emits SelfOffline when the account transitions online -> offline', async () => {
const { core, emit, profileListener } = createCore(true);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).toHaveBeenCalledTimes(1);
expect(emit).toHaveBeenCalledWith('SelfOffline', expect.stringContaining('账号状态变更为离线'));
expect(core.selfInfo.online).toBe(false);
});
test('does not emit again while the account stays offline', async () => {
const { core, emit, profileListener } = createCore(true);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
profileListener()!.onSelfStatusChanged(status(20));
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).toHaveBeenCalledTimes(1);
});
test('emits again after the account recovered and went offline once more', async () => {
const { core, emit, profileListener } = createCore(true);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
profileListener()!.onSelfStatusChanged(status(10));
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).toHaveBeenCalledTimes(2);
expect(core.selfInfo.online).toBe(false);
});
test('does not emit during startup when the account was never online', async () => {
const { core, emit, profileListener } = createCore(undefined);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).not.toHaveBeenCalled();
expect(core.selfInfo.online).toBe(false);
});
test('keeps emitting KickedOffLine as before', async () => {
const { core, emit, messageListener } = createCore(true);
await core.initNapCatCoreListeners();
messageListener()!.onKickedOffLine({ tipsTitle: '下线通知', tipsDesc: '当前账号已在其它设备登录' });
expect(emit).toHaveBeenCalledTimes(1);
expect(emit).toHaveBeenCalledWith('KickedOffLine', expect.stringContaining('当前账号已在其它设备登录'));
expect(core.selfInfo.online).toBe(false);
});
});
+1 -3
View File
@@ -5,11 +5,9 @@
"type": "module",
"scripts": {
"test": "vitest",
"test:ui": "vitest --ui",
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
"test:ui": "vitest --ui"
},
"devDependencies": {
"@types/node": "^22.0.1",
"vitest": "^4.0.9"
},
"dependencies": {
-72
View File
@@ -1,72 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
vi.mock('@/napcat-core/index', () => ({ getMajorPath: vi.fn() }));
describe('QQ AppID lookup', () => {
let info: QQBasicInfoWrapper;
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
beforeEach(() => {
Object.defineProperty(process, 'arch', { ...archDescriptor, value: 'x64' });
info = Object.create(QQBasicInfoWrapper.prototype);
info.context = { logger: { log: vi.fn() } } as unknown as QQBasicInfoWrapper['context'];
vi.spyOn(info, 'getFullQQVersion');
vi.spyOn(info, 'getAppidV2ByMajor').mockReturnValue('537999999');
});
afterEach(() => {
Object.defineProperty(process, 'arch', archDescriptor);
vi.restoreAllMocks();
});
it.each([
['3.2.30-50969', 'x64', 537376344],
['3.2.30-50969', 'arm64', 537376345],
['3.2.32-52194', 'x64', 537379447],
['3.2.32-52194', 'arm64', 537379448],
['3.2.33-52892', 'x64', 537382855],
['3.2.33-52892', 'arm64', 537382856],
] as const)('uses the scanned AppID for Linux %s %s', (version, arch, appid) => {
Object.defineProperty(process, 'arch', { ...archDescriptor, value: arch });
vi.mocked(info.getFullQQVersion).mockReturnValue(version);
expect(info.getAppidV2()).toEqual({
appid,
qua: `V1_LNX_NQ_${version.replace('-', '_')}_GW_B`,
});
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
});
it.each([
['9.9.33-52230', 537379411],
['9.9.35-52892', 537382819],
] as const)('finds Windows %s by its actual package version', (version, appid) => {
vi.mocked(info.getFullQQVersion).mockReturnValue(version);
expect(info.getAppidV2()).toEqual({
appid,
qua: `V1_WIN_NQ_${version.replace('-', '_')}_GW_B`,
});
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
});
it('preserves version-only entries when an architecture override is absent', () => {
Object.defineProperty(process, 'arch', { ...archDescriptor, value: 'arm64' });
vi.mocked(info.getFullQQVersion).mockReturnValue('3.2.29-49738');
expect(info.getAppidV2()).toEqual({
appid: 537355867,
qua: 'V1_LNX_NQ_3.2.29_49738_GW_B',
});
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
});
it('still scans major.node for an unknown version', () => {
vi.mocked(info.getFullQQVersion).mockReturnValue('3.2.99-99999');
vi.spyOn(info, 'getQUAFallback').mockReturnValue('fallback-qua');
expect(info.getAppidV2()).toEqual({ appid: '537999999', qua: 'fallback-qua' });
expect(info.getAppidV2ByMajor).toHaveBeenCalledWith('3.2.99-99999');
});
});
@@ -1,66 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { SetQQProfile } from '../napcat-onebot/action/go-cqhttp/SetQQProfile';
const OLD_PROFILE = {
sex: 1,
longNick: 'old note',
birthday_year: 2000,
birthday_month: 1,
birthday_day: 1,
};
function createAction () {
const modifySelfProfile = vi.fn().mockResolvedValue({});
const action = new SetQQProfile(undefined as never, {
selfInfo: { uid: 'u1' },
apis: {
UserApi: {
getUserDetailInfo: vi.fn().mockResolvedValue(OLD_PROFILE),
modifySelfProfile,
},
},
} as never);
return { action, modifySelfProfile };
}
describe('set_qq_profile sex handling', () => {
afterEach(() => {
vi.restoreAllMocks();
});
// NTSex.GENDER_UNKOWN === 0, and the payload schema documents "0: 未知".
test('forwards sex: 0 instead of falling back to the current profile', async () => {
const { action, modifySelfProfile } = createAction();
await action._handle({ nickname: 'newnick', sex: 0 });
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ nick: 'newnick', sex: 0 }));
});
test('forwards sex: 2', async () => {
const { action, modifySelfProfile } = createAction();
await action._handle({ nickname: 'newnick', sex: 2 });
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ sex: 2 }));
});
test('falls back to the current profile when sex is omitted', async () => {
const { action, modifySelfProfile } = createAction();
await action._handle({ nickname: 'newnick' });
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ sex: OLD_PROFILE.sex }));
});
test('falls back to the current profile when sex is an empty string', async () => {
const { action, modifySelfProfile } = createAction();
await action._handle({ nickname: 'newnick', sex: '' });
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ sex: OLD_PROFILE.sex }));
});
});
@@ -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;
@@ -2,10 +2,6 @@ import { Card, CardProps } from '@heroui/card';
import clsx from 'clsx';
import React from 'react';
// Firefox 里 backdrop-filter 和 3D transform 作用在同一个元素上时,卡片内容会画不出来
// (#2083,macOS 上的 Firefox 157 复现),所以 Firefox 下不做倾斜,只保留光晕。
const tiltEnabled = !/firefox/i.test(navigator.userAgent);
export interface HoverEffectCardProps extends CardProps {
children: React.ReactNode
maxXRotation?: number
@@ -40,22 +36,20 @@ const HoverEffectCard: React.FC<HoverEffectCardProps> = (props) => {
'relative overflow-hidden bg-opacity-50 backdrop-blur-lg',
className
)}
style={tiltEnabled
? {
willChange: 'transform',
transform:
'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)',
...style,
}
: style}
style={{
willChange: 'transform',
transform:
'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)',
...style,
}}
onMouseEnter={() => {
if (tiltEnabled && cardRef.current) {
if (cardRef.current) {
cardRef.current.style.transition = 'transform 0.3s ease-out';
}
}}
onMouseLeave={() => {
setIsShowLight(false);
if (tiltEnabled && cardRef.current) {
if (cardRef.current) {
cardRef.current.style.transition = 'transform 0.5s';
cardRef.current.style.transform =
'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)';
@@ -84,10 +78,6 @@ const HoverEffectCard: React.FC<HoverEffectCardProps> = (props) => {
top,
});
if (!tiltEnabled) {
return;
}
cardRef.current.style.transition = 'transform 0.1s';
const rangeX = 400 / 2;
@@ -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>
@@ -3,7 +3,7 @@ import { CardBody, CardHeader } from '@heroui/card';
import { Image } from '@heroui/image';
import { Input } from '@heroui/input';
import { useLocalStorage } from '@uidotdev/usehooks';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useState } from 'react';
import { toast } from 'react-hot-toast';
import { IoKeyOutline, IoArrowBack } from 'react-icons/io5';
import { useNavigate } from 'react-router-dom';
@@ -20,10 +20,6 @@ import WebUIManager from '@/controllers/webui_manager';
import PureLayout from '@/layouts/pure';
import { motion } from 'motion/react';
// Passkey 检查的最长等待时间。部分手机浏览器在本机没有对应 Passkey 时,
// navigator.credentials.get 会一直不返回,不能让它无限期占住登录流程。
const PASSKEY_TIMEOUT_MS = 30_000;
export default function WebLoginPage () {
const urlSearchParams = new URLSearchParams(window.location.search);
const token = urlSearchParams.get('token');
@@ -31,7 +27,6 @@ export default function WebLoginPage () {
const [tokenValue, setTokenValue] = useState<string>(token || '');
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isPasskeyLoading, setIsPasskeyLoading] = useState<boolean>(true); // 初始为true,表示正在检查passkey
const passkeyAbortRef = useRef<AbortController | null>(null);
const [, setLocalToken] = useLocalStorage<string>(key.token, '');
// 2FA相关状态
@@ -62,9 +57,6 @@ export default function WebLoginPage () {
// toast.error('当前浏览器/环境不支持 Passkey 登录。');
return;
}
const controller = new AbortController();
passkeyAbortRef.current = controller;
const timer = setTimeout(() => controller.abort(), PASSKEY_TIMEOUT_MS);
try {
// 检查是否有passkey
const options = await WebUIManager.generatePasskeyAuthenticationOptions();
@@ -79,9 +71,7 @@ export default function WebLoginPage () {
transports: cred.transports,
})),
userVerification: options.userVerification,
timeout: PASSKEY_TIMEOUT_MS,
},
signal: controller.signal,
}) as PublicKeyCredential;
if (!credential) {
@@ -105,10 +95,6 @@ export default function WebLoginPage () {
// 验证认证
const data = await WebUIManager.verifyPasskeyAuthentication(response);
// 用户已改用 Token 登录,不再用 Passkey 的结果覆盖
if (controller.signal.aborted) {
return false;
}
if (data && data.Credential) {
setLocalToken(data.Credential);
navigate('/qq_login', { replace: true });
@@ -117,11 +103,6 @@ export default function WebLoginPage () {
} catch (error) {
// passkey登录失败,继续显示token登录界面
console.log('Passkey login failed or not available:', error);
} finally {
clearTimeout(timer);
if (passkeyAbortRef.current === controller) {
passkeyAbortRef.current = null;
}
}
return false; // 登录失败
};
@@ -132,8 +113,6 @@ export default function WebLoginPage () {
toast.error('请输入token');
return;
}
// 改用 Token 登录时放弃仍在等待的 Passkey 验证
passkeyAbortRef.current?.abort();
setIsLoading(true);
try {
const data = await WebUIManager.loginWithToken(tokenValue);
@@ -190,7 +169,7 @@ export default function WebLoginPage () {
// 处理全局键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter' && !isLoading) {
if (e.key === 'Enter' && !isLoading && !isPasskeyLoading) {
if (require2FA) {
onSubmit2FA();
} else {
@@ -206,7 +185,7 @@ export default function WebLoginPage () {
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [tokenValue, totpCode, isLoading, require2FA]); // 依赖项包含用于登录的状态
}, [tokenValue, totpCode, isLoading, isPasskeyLoading, require2FA]); // 依赖项包含用于登录的状态
useEffect(() => {
// 如果URL中有token,直接登录
@@ -221,9 +200,6 @@ export default function WebLoginPage () {
tryPasskeyLogin().finally(() => {
setIsPasskeyLoading(false);
});
return () => {
passkeyAbortRef.current?.abort();
};
}, []);
return (
@@ -257,166 +233,164 @@ export default function WebLoginPage () {
<CardBody className='flex gap-5 py-5 px-5 md:px-10'>
{isPasskeyLoading && (
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
🔐 正在检查Passkey,也可以直接输入Token登录
🔐 正在检查Passkey...
</div>
)}
{/* 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}
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';
-6
View File
@@ -332,9 +332,6 @@ importers:
specifier: workspace:*
version: link:../napcat-vite
devDependencies:
'@types/node':
specifier: ^22.0.1
version: 22.19.1
tsx:
specifier: ^4.7.1
version: 4.21.0
@@ -397,9 +394,6 @@ importers:
specifier: workspace:*
version: link:../napcat-rpc
devDependencies:
'@types/node':
specifier: ^22.0.1
version: 22.19.1
vitest:
specifier: ^4.0.9
version: 4.0.9(@types/debug@4.1.12)(@types/node@22.19.1)(@vitest/ui@4.0.9)(jiti@1.21.7)(tsx@4.21.0)(yaml@2.8.2)