Compare commits

..
26 Commits
Author SHA1 Message Date
手瓜一十雪 859eb530c5 fix(ci): avoid resolving dev dependencies in release artifacts
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-21 16:36:48 +08:00
手瓜一十雪 89e8efc57e fix: #2100 2026-10-21 16:16:27 +08:00
Ekko 450fb0429a Remove ghproxy.imciel.com from proxy URLs (#2108)
Removed deprecated proxy URL from the list.

Signed-off-by: Ekko <beijiu572@gmail.com>
2026-10-19 12:15:20 +08:00
cherry-xw 810052c605 fix(onebot): preserve profile regions in user and member responses (#2107) 2026-10-15 15:31:19 +08:00
手瓜一十雪 3f66b36901 fix(album): restore comments and support batch targets
Initialize comment like data required by QQNT and allow comments on upload batches while preserving single-image targets. Add action and native argument conversion regression tests.

Fixes #1979. Closes #2028.
2026-10-12 12:46:50 +08:00
手瓜一十雪 bbd0d2aca3 fix(message): 修复合并转发中动画表情吞掉后续消息段 (#2097)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-12 12:26:58 +08:00
H3CoF6 7471e3ecd6 feat: 支持 macOS 设备 GUID 管理与修正 Linux global 路径 (#2099)
* feat(webui): 支持 macOS 设备 GUID 管理与修正 Linux global 路径

    Linux 的 global 目录直接位于数据根目录下(不再经过 nt_qq), 与 macOS 对齐;
    新增 getGlobalDataPath 统一推导, 修正 Registry20/machine-info 在 Linux 下指向错误目录。

    macOS 设备 GUID 实现(逆向自 wrapper.node, 对齐 qq_guid_tool):
    - guid = MD5(machine_id[8] || sn)
    - machineid-info 使用 QQ 私有 TEA 容器(16 轮, 大端), 密钥为 IOPlatformUUID 前 16 字节
    - machine_id 优先读 machineid-info, 失败回退主网卡 MAC + 0000
    - sn 优先 /dev/disk0 序列号, 回退 IOPlatformSerialNumber
    - 新增 GetMacGUIDInfo / GetMacHardwareInfo / SetMacMachineId /
      GetMacInfoBackups / CreateMacInfoBackup / RestoreMacInfoBackup / ResetMacDeviceID
    - 前端 GUID 面板支持 macOS: 显示硬件信息, 编辑 machine_id 并实时预览 GUID, 备份/恢复/删除

* fix(webui): 加固 GUID 管理并补充 Linux global 路径迁移

按评审意见处理:

- Linux 迁移: 仅当 <dataPath>/global 不存在且 <dataPath>/nt_qq/global 存在时
  搬运旧目录, 新目录已存在则保持原样; 逻辑抽到 global-migrate.ts 便于测试
- macOS 主网卡 MAC: 优先 en0, 再回退父级 IOEthernetController 上的
  IOMACAddress, 整条链路判空容错
- 恢复接口防目录穿越: 备份名必须命中白名单且匹配 .bak.<时间戳> 格式,
  写入前校验内容合法性 (Registry20 / machine-info / TEA 容器)
- SN 留空语义统一为"沿用当前生效值", 前后端预览与落库一致
- 前端保存按钮 dirty 判定纳入 SN
- 备份命名加毫秒时间戳与随机后缀, COPYFILE_EXCL 落盘, 杜绝同秒覆盖
- 硬件查询改为异步 execFile 并加进程内缓存, 不再阻塞事件循环

测试: 新增 Linux 迁移 5 例与备份命名/穿越/内容校验用例,
全量 27 文件 256 例通过; tsc --noEmit 与 eslint 通过。
2026-10-11 12:22:47 +08:00
手瓜一十雪 6797143b04 chore(ci): remove one-off compatibility validation 2026-10-10 12:50:35 +08:00
手瓜一十雪 ff37736a4a docs(release): remove obsolete release note templates 2026-10-10 12:27:51 +08:00
手瓜一十雪 26ad589367 fix(release): generate notes from verified tag history 2026-10-10 12:27:51 +08:00
手瓜一十雪 ff9a829e29 fix(shell): preserve Windows launcher paths and elevation arguments
macOS QQ runtime / runtime (arm64, macos-15) (push) Canceled after 0s
macOS QQ runtime / runtime (x64, macos-15-intel) (push) Canceled after 0s
Windows launcher / launchers (push) Canceled after 0s
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
macOS native compatibility / native (arm64, macos-15) (push) Canceled after 0s
macOS native compatibility / native (x64, macos-15-intel) (push) Canceled after 0s
2026-10-10 11:17:31 +08:00
手瓜一十雪 f8786c65de test(macos): read XML entitlements and cache verified QQ image 2026-10-10 10:41:55 +08:00
手瓜一十雪 038dd558da test(macos): exercise signed QQ with native modules without login 2026-10-10 10:29:52 +08:00
手瓜一十雪 abda6a96de fix(native): complete cross-platform media and packet integration
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
macOS native compatibility / native (arm64, macos-15) (push) Canceled after 0s
macOS native compatibility / native (x64, macos-15-intel) (push) Canceled after 0s
2026-10-10 09:53:28 +08:00
H3CoF6 4e2c48624a fix(onebot): 修复 create_flash_task 触发的 QQ 内核崩溃,并新增时效字段 (#2098) 2026-10-10 05:37:09 +08:00
手瓜一十雪 1c0f7cce4f fix(macos): support verified QQ builds on arm64 and x64 2026-10-10 01:05:09 +08:00
手瓜一十雪 b31e1c0f0c fix(packet): extend QQ build coverage from 40768 to 53644
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-09 22:15:24 +08:00
手瓜一十雪 83c1d1d596 fix(packet): support QQ 53644 and missing recent builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-09 20:19:36 +08:00
Shxiao 05feca9a2c fix(onebot): get_group_files_by_folder 不再丢弃子文件夹 (#2095)
该接口的 returnSchema 声明了 folders(文件夹列表),actionDescription
也写着「获取指定群文件夹下的文件及子文件夹列表」,但 _handle 把 folders
硬编码成空数组。

它调用的 MsgApi.getGroupFileList 与 get_group_root_files 相同,返回项
既可能带 fileInfo 也可能带 folderInfo;兄弟实现 GetGroupRootFiles 把
两类都映射了出来。后果是进入某个子目录后无法继续往下遍历,调用方永远
只能拿到空的 folders。

改为按兄弟接口的方式映射 folderInfo。
2026-10-07 22:05:51 +08:00
Shxiao f750d95545 fix(onebot): 恢复 set_group_leave 的 is_dismiss 解散群聊支持 (#2094)
payloadSchema 声明了 is_dismiss(是否解散),该字段也会出现在 build:openapi
生成的接口文档中,但 _handle 始终只调用 quitGroup:群主传 is_dismiss=true
期望解散群聊时,实际只把账号退出群聊——群没解散,账号却已经不在群里。

同一问题曾在 #1694(deae7fd4)修复过。该 PR 随后被 #1701(e6f646837,
2026-03-13)整包回滚,54 个文件全部撤销;触发原因记录在 #1700(v4.17.48
无法正常发送 JSON 卡片消息),回滚后 v4.17.49 确认修复。回滚一并删掉了
destroyGroup 与 is_dismiss 分支,本次只恢复这一条分支。

本补丁不触碰任何 schema、描述与示例字段。
2026-10-07 22:05:16 +08:00
手瓜一十雪 ec6aadaeea fix(shell): support QQ 9.9.36 Windows file query aliases
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-07 00:07:42 +08:00
手瓜一十雪 463d3ea5b1 fix(test): use typed spawn options for Windows batch regression
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-06 18:08:08 +08:00
手瓜一十雪 0d6ce7f509 fix(ci): sync typescript dependency in workspace lockfile 2026-10-06 18:07:06 +08:00
手瓜一十雪 4f1401da78 fix(types): preserve complete nested types during post-processing
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Use the TypeScript parser instead of a regex that truncates nested generics and function types. Validate generated syntax and add a regression test. Include workspace aliases and PTY ambient declarations. The full type package build still reports six errors in third-party node-pty source; this commit does not claim to resolve that remaining issue.
2026-10-06 17:51:21 +08:00
手瓜一十雪 9109b8cfe2 fix: repair Windows release dependencies and loader paths
Bundle required crypto and SSL DLLs and gate releases on a Windows native-load smoke test. Resolve loader paths independently of the working directory and encode file URLs correctly. Include the quick-login launcher built from Windows-Boot 0ff70ce10e34ac26411f9e6bcedaedfacc1e74f0. Validated builds, five path regressions, and live Shell and Windows Node startup to QR login.
2026-10-06 17:51:21 +08:00
手瓜一十雪 297133a1b1 fix(shell): update Windows hook for native file information queries
Include the x64 Release hook built from NapCat-Windows-Boot commit 789e6cce00be40d02659e1aca992f8cd928b790a. SHA256: 7C48E7D10D77E2C3936E5D190AEB0DDEE353D55FD06DE81C714F2740112B94B1.

Related to #2091. The replacement passes 10 independent Win32 checks; the reported QQ crash remains to be verified in the reporter's environment.
2026-10-06 16:54:12 +08:00
87 changed files with 3751 additions and 775 deletions

No files matched your search

-35
View File
@@ -1,35 +0,0 @@
# {VERSION}
[使用文档](https://napneko.github.io/)
## 警告
**注意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 暂不支持**
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
## 更新
### 🐛 修复
1. 修复 WebUI 主题配置在有未保存更改时卸载组件导致字体重置的问题 (ae42eed6)
### ✨ 新增
1. 文件上传相关接口(UploadGroupFile/UploadPrivateFile)新增 `upload_file` 参数支持 (91e0839e)
2. 消息发送逻辑支持 PTT(语音)元素过滤,确保语音消息正确独立发送 (47983e29)
### 🔧 优化
1. 优化合并转发消息(GetForwardMsg)的获取与解析逻辑,提高兼容性 (334c4233)
2. 改进消息发送方法中发送者 UIN 的处理逻辑 (71bb4f68)
3. 增强 WebUI 系统信息界面中对构建产物的处理与展示 (cb061890)
---
**完整更新日志**: [v4.10.6...v4.10.7](https://github.com/NapNeko/NapCatQQ/compare/v4.10.6...v4.10.7)
-113
View File
@@ -1,113 +0,0 @@
# NapCat Release Note Generator
你是 NapCat 项目的发布说明生成器。请根据提供的 commit 列表生成标准格式的发布说明。
## 核心规则
1. **版本号**:第一行必须是 `# {VERSION}`,使用用户提供的版本号,如果版本号是小写 v 开头(如 v4.10.2),必须转换为大写 V(如 V4.10.2)
2. **语言**:全部使用简体中文
3. **格式**:严格按照下方模板输出,不要添加额外的 markdown 格式
## Commit 分析规则
将 commit 分类为以下类型:
- 🐛 **修复**:bug fix、修复、fix 相关
- ✨ **新增**:新功能、feat、add 相关
- 🔧 **优化**:优化、重构、refactor、improve、perf 相关
- 📦 **依赖**:deps、依赖更新(通常可以忽略或合并)
- 🔨 **构建**:ci、build、workflow 相关(通常可以忽略)
## 合并和筛选
- **合并相似项**:同一功能的多个 commit 合并为一条
- **忽略琐碎项**:合并冲突、格式化、typo 等可忽略
- **控制数量**:最终保持 5-15 条更新要点
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
```
# {VERSION}
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
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 暂不支持**
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
## 更新
### 🐛 修复
1. 修复 xxx 问题 (a1b2c3d)
2. 修复 yyy 崩溃 (b2c3d4e)
### ✨ 新增
1. 新增 xxx 功能 (c3d4e5f)
2. 支持 yyy 特性 (d4e5f6g)
### 🔧 优化
1. 优化 xxx 性能 (e5f6g7h)
2. 重构 yyy 模块 (f6g7h8i)
---
**完整更新日志**: [{PREV_VERSION}...{VERSION}](https://github.com/NapNeko/NapCatQQ/compare/{PREV_VERSION}...{VERSION})
```
**格式要求 - 务必严格遵守:**
- "Windows 一键包"部分的文本必须完全一致,不要修改任何措辞
- "警告"部分必须包含所有 QQ 版本下载链接,保持原有格式
- "如果WinX64缺少运行库或者xxx.dll?"这一行必须保持原样
- QQ 版本号、下载链接、"官方 CDN"标注和"MacOS 暂不支持"保持不变
- 只有"## 更新"部分下面的内容需要根据实际 commit 生成
## 重要约束
1. 如果某个分类没有内容,则完全省略该分类
2. 不要编造不存在的更新
3. 保持简洁,每条更新控制在一行内
4. 使用用户友好的语言,避免过于技术化的描述
5. 重大变更(Breaking Changes)需要在注意事项中加粗提示
## 文件变化分析
用户会提供文件变化统计和具体代码diff,帮助你理解变更内容:
### 目录含义
- `packages/napcat-core/` → 核心功能、消息处理、QQ接口
- `packages/napcat-onebot/` → OneBot 协议实现、API、事件
- `packages/napcat-webui-backend/` → WebUI 后端接口
- `packages/napcat-webui-frontend/` → WebUI 前端界面
- `packages/napcat-shell/` → Shell 启动器
### 代码diff阅读指南
- `+` 开头的行是新增代码
- `-` 开头的行是删除代码
- 关注函数名、类名的变化来理解功能变更
- 关注 `fix`、`bug`、`error` 等关键词识别修复项
- 关注 `add`、`new`、`feature` 等关键词识别新功能
- 忽略纯重构(代码移动但功能不变)和格式化变更
### 截断说明
- 如果看到 `[... 已截断 ...]`,表示内容过长被截断
- 根据已有信息推断完整变更意图即可
@@ -0,0 +1,77 @@
import { execFileSync } from 'node:child_process';
import { writeFileSync } from 'node:fs';
function parseVersion (tag) {
const match = /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/.exec(tag);
if (!match) return null;
const prerelease = match[4]?.split('.') ?? [];
if (prerelease.some(identifier => !identifier || /^0\d+$/.test(identifier))) return null;
return { tag, numbers: match.slice(1, 4).map(BigInt), prerelease };
}
function compareVersions (left, right) {
for (let index = 0; index < 3; index++) {
if (left.numbers[index] !== right.numbers[index]) {
return left.numbers[index] > right.numbers[index] ? 1 : -1;
}
}
if (!left.prerelease.length || !right.prerelease.length) {
return Number(!left.prerelease.length) - Number(!right.prerelease.length);
}
for (let index = 0; index < Math.min(left.prerelease.length, right.prerelease.length); index++) {
const leftIdentifier = left.prerelease[index];
const rightIdentifier = right.prerelease[index];
if (leftIdentifier === rightIdentifier) continue;
const leftNumeric = /^\d+$/.test(leftIdentifier);
const rightNumeric = /^\d+$/.test(rightIdentifier);
if (leftNumeric && rightNumeric) return BigInt(leftIdentifier) > BigInt(rightIdentifier) ? 1 : -1;
if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
return leftIdentifier > rightIdentifier ? 1 : -1;
}
return left.prerelease.length - right.prerelease.length;
}
function git (...args) {
return execFileSync('git', args, { encoding: 'utf8' }).trim();
}
const [tag, repository, outputFile] = process.argv.slice(2);
const currentVersion = parseVersion(tag);
if (process.argv.length !== 5 || !currentVersion || !repository || !outputFile) {
throw new Error('Usage: node generate-release-notes.mjs <vX.Y.Z[-prerelease]> <owner/repo> <output.md>');
}
if (git('rev-parse', '--is-shallow-repository') === 'true') {
throw new Error('Release notes require complete Git history and tags (fetch-depth: 0)');
}
const currentRef = `refs/tags/${currentVersion.tag}`;
const previousVersion = git('tag', '--merged', currentRef)
.split('\n')
.map(parseVersion)
.filter(version => version && compareVersions(version, currentVersion) < 0)
.sort((left, right) => compareVersions(right, left))[0];
if (!previousVersion) throw new Error(`No preceding version tag is reachable from ${currentVersion.tag}`);
const commits = git('log', '--reverse', '--format=%H%x09%s', `refs/tags/${previousVersion.tag}..${currentRef}`);
const repositoryUrl = `https://github.com/${repository}`;
const changes = commits.split('\n').filter(Boolean).map(commit => {
const separator = commit.indexOf('\t');
const hash = commit.slice(0, separator);
const subject = commit.slice(separator + 1).replace(/[\\`*_[\]<>]/g, '\\$&');
return `- ${subject} ([${hash.slice(0, 8)}](${repositoryUrl}/commit/${hash}))`;
});
const notes = [
`# NapCat ${currentVersion.tag}`,
'',
'[使用文档](https://napneko.github.io/) · [Shell 安装与兼容说明](https://napneko.github.io/guide/boot/Shell)',
'',
'## 更新',
'',
...changes,
...(changes.length ? [] : ['此标签范围内没有新增提交。']),
'',
`[完整变更](${repositoryUrl}/compare/${previousVersion.tag}...${currentVersion.tag})`,
'',
].join('\n');
writeFileSync(outputFile, notes, 'utf8');
console.log(`Generated release notes: ${previousVersion.tag}...${currentVersion.tag}`);
+2 -1
View File
@@ -103,7 +103,8 @@ function postBuild (target: BuildTarget): void {
// Install production dependencies
console.log('→ Installing production dependencies');
execSync('npm install --omit=dev', {
// --omit=dev still resolves dev peer dependencies; remove build tooling first.
execSync('npm pkg delete devDependencies && npm install --omit=dev', {
cwd: destDir,
stdio: 'inherit',
shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/bash',
@@ -0,0 +1,3 @@
cmake_minimum_required(VERSION 3.20)
project(NapCatWindowsLoaderTest LANGUAGES CXX)
add_executable(windows-loader-test probe.cpp)
+96
View File
@@ -0,0 +1,96 @@
#include <windows.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
using QueryByName = BOOL(WINAPI *)(PCWSTR, FILE_INFO_BY_NAME_CLASS, PVOID, ULONG);
int wmain(int argumentCount, wchar_t **arguments)
{
if (argumentCount != 3)
return 2;
const wchar_t *providers[] = {L"kernel32.dll", L"kernelbase.dll", L"api-ms-win-core-file-l2-1-4.dll"};
HMODULE providerModules[3]{};
QueryByName nativeQueries[3]{};
unsigned char nativeCode[3][12]{};
unsigned char nativeInfo[3][4][1024]{};
BOOL nativeResults[3][4]{};
DWORD nativeErrors[3][4]{};
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
providerModules[providerIndex] = LoadLibraryW(providers[providerIndex]);
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
if (!query)
return 3;
nativeQueries[providerIndex] = query;
std::memcpy(nativeCode[providerIndex], reinterpret_cast<void *>(query), sizeof(nativeCode[providerIndex]));
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
SetLastError(ERROR_SUCCESS);
nativeResults[providerIndex][infoClass] = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), nativeInfo[providerIndex][infoClass], sizeof(nativeInfo[providerIndex][infoClass]));
nativeErrors[providerIndex][infoClass] = GetLastError();
}
}
FILE_STAT_BASIC_INFORMATION expected{};
if (!nativeQueries[0](arguments[2], FileStatBasicByNameInfo, &expected, sizeof(expected)))
return 4;
if (_wputenv_s(L"NAPCAT_LOAD_PATH", arguments[2]) || _wputenv_s(L"NAPCAT_PATCH_PACKAGE", arguments[2]))
return 5;
if (!LoadLibraryW(arguments[1]))
{
std::printf("LoadLibrary failed: %lu\n", GetLastError());
return 6;
}
const std::wstring missingRoot = L"C:\\napcat-loader-test-" + std::to_wstring(GetCurrentProcessId());
const std::wstring loaderPath = missingRoot + L"\\loadNapCat.js";
const std::wstring packagePath = missingRoot + L"\\resources\\app\\package.json";
const std::wstring unrelatedPath = missingRoot + L"\\unrelated.txt";
const wchar_t *redirectedPaths[] = {loaderPath.c_str(), packagePath.c_str()};
int failures = 0;
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
bool preserved = std::memcmp(nativeCode[providerIndex], reinterpret_cast<void *>(nativeQueries[providerIndex]), sizeof(nativeCode[providerIndex])) == 0;
std::wprintf(L"%ls native code preserved: %ls\n", providers[providerIndex], preserved ? L"PASS" : L"FAIL");
failures += !preserved;
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
unsigned char actual[1024]{};
SetLastError(ERROR_SUCCESS);
BOOL result = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), actual, sizeof(actual));
DWORD error = GetLastError();
bool passed = result == nativeResults[providerIndex][infoClass] &&
(result ? std::memcmp(actual, nativeInfo[providerIndex][infoClass], sizeof(actual)) == 0 : error == nativeErrors[providerIndex][infoClass]);
std::wprintf(L"%ls information class %d native parity: %ls\n", providers[providerIndex], infoClass, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
for (const auto *redirectedPath : redirectedPaths)
{
FILE_STAT_BASIC_INFORMATION actual{};
BOOL result = query(redirectedPath, FileStatBasicByNameInfo, &actual, sizeof(actual));
bool passed = result && actual.EndOfFile.QuadPart == expected.EndOfFile.QuadPart &&
actual.FileId.QuadPart == expected.FileId.QuadPart && actual.FileAttributes == expected.FileAttributes;
std::wprintf(L"%ls redirect %ls: %ls\n", providers[providerIndex], redirectedPath, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION missing{};
SetLastError(ERROR_SUCCESS);
BOOL nativeResult = nativeQueries[providerIndex](unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
DWORD nativeError = GetLastError();
SetLastError(ERROR_SUCCESS);
BOOL result = query(unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
bool passed = !result && result == nativeResult && GetLastError() == nativeError;
std::wprintf(L"%ls unrelated missing file: %ls\n", providers[providerIndex], passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION direct{};
BOOL result = GetFileInformationByName(loaderPath.c_str(), FileStatBasicByNameInfo, &direct, sizeof(direct));
bool passed = result && direct.FileId.QuadPart == expected.FileId.QuadPart && direct.EndOfFile.QuadPart == expected.EndOfFile.QuadPart;
std::printf("static import redirection: %s\n", passed ? "PASS" : "FAIL");
failures += !passed;
return failures ? 1 : 0;
}
+22
View File
@@ -9,6 +9,26 @@ on:
permissions: write-all
jobs:
windows-loader-test:
name: Windows Loader Test
needs: build
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell
path: shell-dist
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/shell-dist/NapCatWinBootHook.dll" "$pwd/shell-dist/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
typecheck-and-test:
name: Type Check & Test
runs-on: ubuntu-latest
@@ -82,6 +102,8 @@ jobs:
pnpm --filter napcat-plugin-builtin run build || exit 1
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
cd ${{ matrix.target.dist_dir }}
# --omit=dev still resolves dev peer dependencies; remove build tooling first.
npm pkg delete devDependencies
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
+5 -3
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.36/beta/9ee04bef/linuxqq_3.2.34-53644_x86_64.AppImage'
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.36/beta/9ee04bef/linuxqq_3.2.34-53644_arm64.AppImage'
jobs:
get-version:
@@ -86,17 +86,19 @@ jobs:
git push
shell-docker:
needs: get-version
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
-d '{"ref":"main"}'
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\"}}"
framework-docker:
runs-on: ubuntu-latest
+49 -213
View File
@@ -11,8 +11,6 @@ on:
permissions: write-all
env:
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
RELEASE_NAME: "NapCat"
jobs:
@@ -47,6 +45,7 @@ jobs:
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ inputs.version }}
run: |
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
@@ -54,6 +53,8 @@ jobs:
pnpm --filter napcat-plugin-builtin run build || exit 1
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
cd ${{ matrix.target.dist_dir }}
# --omit=dev still resolves dev peer dependencies; remove build tooling first.
npm pkg delete devDependencies
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
@@ -153,9 +154,14 @@ jobs:
# -----------------------------
# 5) 拷贝 QQ 文件到 NapCat.Shell.Windows.Node
# -----------------------------
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "crypto.dll" "ssl.dll" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
for name in "${QQ_TARGETS[@]}"; do
find "$QQ_EXTRACT" -iname "$name" -exec cp -a {} "$OUT_DIR" \; || true
source_file=$(find "$QQ_EXTRACT" -type f -iname "$name" -print -quit)
if [ -z "$source_file" ]; then
echo "Missing required QQ file: $name" >&2
exit 1
fi
cp -a "$source_file" "$OUT_DIR/"
done
# -----------------------------
@@ -183,8 +189,39 @@ jobs:
name: NapCat.Shell.Windows.Node
path: NapCat.Shell.Windows.Node
validate-windows-node:
needs: assemble-windows-node
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell.Windows.Node
path: windows-node
- name: Verify bundled Node and QQ native dependencies
shell: pwsh
working-directory: windows-node
run: |
& .\node.exe --check .\index.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& .\node.exe -e "const wrapper = require('./wrapper.node'); if (!wrapper.NodeQQNTWrapperUtil) throw new Error('Missing NodeQQNTWrapperUtil'); console.log('wrapper.node native-load PASS'); process.exit(0);"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/windows-node/napcat/NapCatWinBootHook.dll" "$pwd/windows-node/napcat/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
release-napcat:
needs: [build, assemble-windows-node]
needs: [build, assemble-windows-node, validate-windows-node]
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -209,216 +246,15 @@ jobs:
[ -d NapCat.Shell.Windows.Node ] && (cd NapCat.Shell.Windows.Node && zip -qr ../../NapCat.Shell.Windows.Node.zip .)
cd ..
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Generate release note
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
GITHUB_OWNER: "NapNeko"
GITHUB_REPO: "NapCatQQ"
run: |
set -euo pipefail
# 当前 tag
CURRENT_TAG="${{ inputs.version }}"
echo "Current tag: $CURRENT_TAG"
# 从 GitHub API 获取 tag 列表
TAGS_JSON=$(curl -s "https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/tags?per_page=100")
TAGS=( $(echo "$TAGS_JSON" | jq -r '.[].name' | sort -V) )
# 找到上一个 tag
PREV_TAG=""
for i in "${!TAGS[@]}"; do
if [ "${TAGS[$i]}" = "$CURRENT_TAG" ]; then
if [ $i -gt 0 ]; then
PREV_TAG="${TAGS[$((i-1))]}"
fi
break
fi
done
if [ -z "$PREV_TAG" ]; then
echo "Could not find previous tag for $CURRENT_TAG, using first commit"
PREV_TAG=$(git rev-list --max-parents=0 HEAD | head -1)
fi
echo "Previous tag: $PREV_TAG"
# 强制拉取上一个 tag 和当前 tag
git fetch origin "refs/tags/$PREV_TAG:refs/tags/$PREV_TAG" --force || true
git fetch origin "refs/tags/$CURRENT_TAG:refs/tags/$CURRENT_TAG" --force || true
# 获取 commit,使用更清晰的格式
COMMITS=$(git log --pretty=format:'- %s (%h)' "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || git log --pretty=format:'- %s (%h)' -20)
echo "Commit list from $PREV_TAG to $CURRENT_TAG:"
echo "$COMMITS"
# 获取文件变化统计
echo "Getting file change statistics..."
FILE_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || echo "")
# 获取总体统计(最后一行)
SUMMARY_LINE=$(echo "$FILE_STATS" | tail -1)
echo "Summary: $SUMMARY_LINE"
# 获取每个文件的变化(去掉最后一行汇总)
# 截断过长的输出(最多50个文件,每行最多80字符)
FILE_CHANGES=$(echo "$FILE_STATS" | head -n -1 | head -50 | cut -c1-80)
# 如果文件变化太多,进一步精简:只保留主要目录的变化
FILE_COUNT=$(echo "$FILE_STATS" | head -n -1 | wc -l)
if [ "$FILE_COUNT" -gt 50 ]; then
echo "Too many files ($FILE_COUNT), grouping by directory..."
# 按目录分组统计
DIR_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | head -n -1 | \
sed 's/|.*//g' | \
awk -F'/' '{if(NF>1) print $1"/"$2; else print $1}' | \
sort | uniq -c | sort -rn | head -20)
FILE_CHANGES="[按目录分组统计 - 共 $FILE_COUNT 个文件变更]
$DIR_STATS"
fi
echo "File changes:"
echo "$FILE_CHANGES"
# 获取具体代码变化(关键文件的diff)
echo "Getting code diff for key files..."
# 定义关键目录(优先展示这些目录的变化)
KEY_DIRS="packages/napcat-core packages/napcat-onebot packages/napcat-webui-backend"
# 获取变更的关键文件列表(排除测试、配置等)
KEY_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "^packages/napcat-(core|onebot|webui-backend|shell)/" || true | \
grep -E "\.(ts|js)$" || true | \
grep -v -E "(test|spec|\.d\.ts|config)" || true | \
head -15) || true
CODE_DIFF=""
DIFF_CHAR_LIMIT=6000
CURRENT_CHARS=0
if [ -n "$KEY_FILES" ]; then
for file in $KEY_FILES; do
if [ "$CURRENT_CHARS" -ge "$DIFF_CHAR_LIMIT" ]; then
CODE_DIFF="$CODE_DIFF
[... 更多文件变化已截断 ...]"
break
fi
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -50) || true
FILE_DIFF_LEN=${#FILE_DIFF}
if [ "$FILE_DIFF_LEN" -gt 1500 ]; then
FILE_DIFF=$(echo "$FILE_DIFF" | head -c 1500)
FILE_DIFF="$FILE_DIFF
[... 文件 $file 变化已截断 ...]"
fi
if [ -n "$FILE_DIFF" ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
\`\`\`"
CURRENT_CHARS=$((CURRENT_CHARS + FILE_DIFF_LEN))
fi
done
fi
# 如果没有关键文件变化,获取前5个变更文件的diff
if [ -z "$CODE_DIFF" ]; then
echo "No key files changed, getting top changed files..."
TOP_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "\.(ts|js|yml|md)$" | head -5) || true
if [ -n "$TOP_FILES" ]; then
for file in $TOP_FILES; do
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -30) || true
if [ -n "$FILE_DIFF" ] && [ ${#FILE_DIFF} -lt 1000 ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
\`\`\`"
fi
done
fi
fi
# 如果仍然没有代码变化,添加说明
if [ -z "$CODE_DIFF" ]; then
CODE_DIFF="[本次更新主要涉及配置文件和文档变更,无核心代码变化]"
fi
echo "Code diff preview:"
echo "$CODE_DIFF" | head -50
# 读取 prompt
PROMPT_FILE=".github/prompt/release_note_prompt.txt"
SYSTEM_PROMPT=$(<"$PROMPT_FILE")
# 构建用户内容,传递更多上下文(包含文件变化和代码diff)
USER_CONTENT="当前版本: $CURRENT_TAG
上一版本: $PREV_TAG
## 提交列表
$COMMITS
## 文件变化统计
$SUMMARY_LINE
## 变更文件列表
$FILE_CHANGES
## 关键代码变化
$CODE_DIFF"
# 构建请求 JSON,增加 max_tokens 以获取更完整的输出
BODY=$(jq -n \
--arg system "$SYSTEM_PROMPT" \
--arg user "$USER_CONTENT" \
--arg model "$OPENAI_MODEL" \
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:5000}')
echo "=== request body ==="
echo "$BODY" | jq .
if RESPONSE=$(curl -s -X POST "$OPENAI_API_URL" \
-H "Authorization: Bearer $OPENAI_KEY" \
-H "Content-Type: application/json" \
-d "$BODY"); then
echo "=== raw response ==="
echo "$RESPONSE"
echo "=== parsed response ==="
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
echo "$RESPONSE" | jq .
else
echo "jq failed to parse response"
fi
# 提取生成内容
RELEASE_BODY=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // .choices[0].text // ""' 2>/dev/null || echo "")
if [ -z "$RELEASE_BODY" ]; then
echo "LLM failed to generate release note, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
else
# 后处理:确保版本号正确,并添加比较链接
echo -e "$RELEASE_BODY" > CHANGELOG.md
sed -i "s/{VERSION}/$CURRENT_TAG/g" CHANGELOG.md
sed -i "s/{PREV_VERSION}/$PREV_TAG/g" CHANGELOG.md
fi
else
echo "Curl failed, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
fi
echo "=== generated release note ==="
cat CHANGELOG.md
CURRENT_TAG: ${{ inputs.version }}
run: node .github/scripts/generate-release-notes.mjs "$CURRENT_TAG" "$GITHUB_REPOSITORY" CHANGELOG.md
- name: Create Release and Upload Artifacts
uses: softprops/action-gh-release@v2
+5
View File
@@ -74,6 +74,7 @@ interface FileUUIDData {
msgId?: string;
elementId?: string;
fileUUID?: string;
busId?: number;
}
class FileUUIDManager {
@@ -105,6 +106,10 @@ export class FileNapCatOneBotUUIDWrap {
return this.manager.encode({ peer, modelId, fileId, fileUUID }, endString, customUUID);
}
public encodeGroupFile (peer: Peer, file: { fileModelId: string; fileId: string; busId: number; }): string {
return this.manager.encode({ peer, modelId: file.fileModelId, fileId: file.fileId, fileUUID: file.fileId, busId: file.busId });
}
public decodeModelId (uuid: string): FileUUIDData | undefined {
return this.manager.decode(uuid);
}
-1
View File
@@ -40,7 +40,6 @@ export const GITHUB_FILE_MIRRORS = [
'https://gh-proxy.com/',
'https://ghfile.geekertao.top/',
'https://j.1lin.dpdns.org/',
'https://ghproxy.imciel.com/',
'https://github-proxy.teach-english.tech/',
'https://gh.927223.xyz/',
'https://github.ednovas.xyz/',
+16 -4
View File
@@ -1,6 +1,7 @@
import { GeneralCallResult, InstanceContext, NapCatCore } from '@/napcat-core';
import {
createFlashTransferResult,
DEFAULT_FLASH_VALIDITY_SECONDS,
FileListResponse,
FlashFileSetInfo,
SendStatus,
@@ -22,8 +23,9 @@ export class NTQQFlashApi {
* @param fileListToUpload 上传文件绝对路径的列表,可以是文件夹!!
* @param thumbnailPath
* @param filesetName
* @param validitySeconds 文件集有效期(秒),默认 1209600(14 天),可选 90 天 / 180 天,必须传否则新版内核段错误
*/
async createFlashTransferUploadTask (fileListToUpload: string[], thumbnailPath: string, filesetName: string): Promise<GeneralCallResult & {
async createFlashTransferUploadTask (fileListToUpload: string[], thumbnailPath: string, filesetName: string, validitySeconds: number = DEFAULT_FLASH_VALIDITY_SECONDS): Promise<GeneralCallResult & {
createFlashTransferResult: createFlashTransferResult;
seq: number;
}> {
@@ -33,14 +35,17 @@ export class NTQQFlashApi {
const selfInfo = this.core.selfInfo;
const fileUploadArg = {
screen: 1, // 1
scene: 1, // 1
name: filesetName,
uploaders: [{
uin: selfInfo.uin,
nickname: selfInfo.nick,
uid: selfInfo.uid,
sendEntrance: '',
nickname: selfInfo.nick,
}],
permission: {
code: 0,
},
coverPath: thumbnailPath,
paths: fileListToUpload,
excludePaths: [],
@@ -56,8 +61,15 @@ export class NTQQFlashApi {
uploadSceneType: UploadSceneType.KUPLOADSCENEAIOFILESELECTOR, // 不知道怎么枚举 先硬编码吧 (PC QQ 10)
detectPrivacyInfoResult: {
exists: false,
allDetectResults: new Map(),
allDetectResults: {},
},
announcement: {
announcementSegments: [],
modifyTime: '',
avatarUrl: '',
},
albumFilePathList: [],
validitySeconds,
};
const uploadResult = await flashService.createFlashTransferUploadTask(timestamp, fileUploadArg);
+7 -2
View File
@@ -24,6 +24,7 @@ import {
createGroupManagementRequests,
} from '../data';
import { NTEventWrapper } from '../helper/event';
import { deleteGroupFiles } from '../helper/group-file';
export class NTQQGroupApi {
context: InstanceContext;
@@ -384,8 +385,8 @@ export class NTQQGroupApi {
return this.context.session.getRichMediaService().createGroupFolder(groupCode, folderName);
}
async delGroupFile (groupCode: string, files: Array<string>) {
return this.context.session.getRichMediaService().deleteGroupFile(groupCode, [102], files);
async delGroupFile (groupCode: string, files: Array<string>, busIds?: Array<number>) {
return deleteGroupFiles(this.context.session.getRichMediaService(), groupCode, files, busIds);
}
async delGroupFileFolder (groupCode: string, folderId: string) {
@@ -562,6 +563,10 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().quitGroup(groupCode);
}
async destroyGroup (groupCode: string) {
return this.context.session.getGroupService().destroyGroup(groupCode);
}
async kickMember (groupCode: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') {
return this.context.session.getGroupService().kickMember(groupCode, kickUids, refuseForever, kickReason);
}
+4 -3
View File
@@ -678,8 +678,9 @@ export class NTQQWebApi {
async doAlbumMediaPlainCommentByNTQQ (
qunId: string,
albumId: string,
lloc: string,
content: string) {
lloc: string | undefined,
content: string,
batchId: string = '') {
const random_seq = Math.floor(Math.random() * 9000) + 1000;
const uin = this.core.selfInfo.uin || '10001';
// 16位number数字
@@ -692,7 +693,7 @@ export class NTQQWebApi {
},
qunId,
2,
createAlbumMediaFeed(uin, albumId, lloc),
createAlbumMediaFeed(uin, albumId, lloc, batchId),
createAlbumCommentRequest(uin, content, client_key)
);
}
+21 -8
View File
@@ -65,14 +65,20 @@ export interface AlbumMediaFeed {
* 创建相册媒体请求参数
* @param uin 用户QQ号
* @param albumId 相册ID
* @param lloc
* @param lloc 图片ID;不传或为空时评论整个上传批次
* @param batchId 上传批次ID;lloc 为空时必填
* @returns 媒体请求参数对象
*/
export function createAlbumMediaFeed (
uin: string,
albumId: string,
lloc: string
lloc?: string,
batchId: string = ''
): AlbumMediaFeed {
if (!lloc && !batchId) {
throw new Error('lloc 或 batch_id 至少需要提供一个');
}
return {
cell_common: {
time: '',
@@ -84,12 +90,8 @@ export function createAlbumMediaFeed (
},
cell_media: {
album_id: albumId,
batch_id: '',
media_items: [{
image: {
lloc,
},
}],
batch_id: batchId,
media_items: lloc ? [{ image: { lloc } }] : [],
},
};
}
@@ -114,6 +116,11 @@ export interface AlbumCommentReplyContent {
user: {
uin: string;
};
like: {
id: string;
count: number;
status: number;
};
}
export enum RichMsgType {
KRICHMSGTYPEPLAINTEXT,
@@ -148,6 +155,12 @@ export function createAlbumCommentRequest (
user: {
uin,
},
// QQNT 会将 like 转换为对象,即使新评论没有点赞也不能省略。
like: {
id: '',
count: 0,
status: 0,
},
};
}
+12 -2
View File
@@ -214,15 +214,19 @@ export enum UploadSceneType {
KUPLOADSCENEAIOFILESELECTOR,
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV,
}
/** 闪传文件集默认有效期(秒):14 天 */
export const DEFAULT_FLASH_VALIDITY_SECONDS = 1209600;
export interface StartFlashTaskRequests {
screen: number; // 1 PC-QQ
scene: number; // 1 PC-QQ
name?: string;
uploaders: UploaderInfo[];
permission?: {};
permission?: { code: number; };
coverPath?: string;
paths: string[]; // 文件的绝对路径,可以是文件夹
excludePaths?: string[];
expireLeftTime?: number, // 0
validitySeconds: number, // 文件集有效期(秒):14 天 1209600 / 90 天 7776000 / 180 天 15552000,必须传,否则新版内核段错误
isNeedDelDeviceInfo: boolean,
isNeedDelLocation: boolean,
coverOriginalInfos?: {
@@ -234,6 +238,12 @@ export interface StartFlashTaskRequests {
exists: boolean,
allDetectResults: {};
};
announcement: {
announcementSegments: unknown[],
modifyTime: string,
avatarUrl: string;
};
albumFilePathList: unknown[];
}
export enum BusiScene {
KBUSISCENEINVALID,
+149 -13
View File
@@ -395,12 +395,16 @@
"appid": 537319840,
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
},
"3.2.20-40768-arm64": {
"appid": 537319841,
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
},
"9.9.22-40768": {
"appid": 537319804,
"qua": "V1_WIN_NQ_9.9.22_40768_GW_B"
},
"6.9.82-40768": {
"appid": 537319829,
"appid": 537319828,
"qua": "V1_MAC_NQ_6.9.82_40768_GW_B"
},
"3.2.20-40824": {
@@ -416,23 +420,27 @@
"qua": "V1_MAC_NQ_6.9.82_40824_GW_B"
},
"6.9.82-40990": {
"appid": 537319880,
"appid": 537319879,
"qua": "V1_MAC_NQ_6.9.82_40990_GW_B"
},
"9.9.22-40990": {
"appid": 537319855,
"qua": "V1_WIN_NQ_9.9.22.40990_GW_B"
"qua": "V1_WIN_NQ_9.9.22_40990_GW_B"
},
"3.2.20-40990": {
"appid": 537319891,
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
},
"3.2.20-40990-arm64": {
"appid": 537319892,
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
},
"9.9.23-41679": {
"appid": 537320110,
"qua": "V1_WIN_NQ_9.9.23_41679_GW_B"
},
"6.9.83-41679": {
"appid": 537320135,
"appid": 537320134,
"qua": "V1_MAC_NQ_6.9.83_41679_GW_B"
},
"9.9.23-41785": {
@@ -440,7 +448,7 @@
"qua": "V1_WIN_NQ_9.9.23_41785_GW_B"
},
"6.9.83-41785": {
"appid": 537320135,
"appid": 537320134,
"qua": "V1_MAC_NQ_6.9.83_41785_GW_B"
},
"9.9.23-41857": {
@@ -451,20 +459,28 @@
"appid": 537320197,
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
},
"3.2.21-41857-arm64": {
"appid": 537320198,
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
},
"6.9.83-41857": {
"appid": 537320186,
"appid": 537320185,
"qua": "V1_MAC_NQ_6.9.83_41857_GW_B"
},
"3.2.21-42086": {
"appid": 537320248,
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
},
"3.2.21-42086-arm64": {
"appid": 537320249,
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
},
"9.9.23-42086": {
"appid": 537320212,
"qua": "V1_WIN_NQ_9.9.23_42086_GW_B"
},
"6.9.85-42086": {
"appid": 537320237,
"appid": 537320236,
"qua": "V1_MAC_NQ_6.9.85_42086_GW_B"
},
"9.9.23-42430": {
@@ -473,30 +489,34 @@
},
"9.9.25-42744": {
"appid": 537328470,
"qua": "V1_WIN_NQ_9.9.23_42744_GW_B"
"qua": "V1_WIN_NQ_9.9.25_42744_GW_B"
},
"6.9.86-42744": {
"appid": 537328495,
"qua": "V1_MAC_NQ_6.9.85_42744_GW_B"
"appid": 537328494,
"qua": "V1_MAC_NQ_6.9.86_42744_GW_B"
},
"9.9.25-42905": {
"appid": 537328521,
"qua": "V1_WIN_NQ_9.9.25_42905_GW_B"
},
"6.9.86-42905": {
"appid": 537328546,
"appid": 537328545,
"qua": "V1_MAC_NQ_6.9.86_42905_GW_B"
},
"3.2.22-42941": {
"appid": 537328659,
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
},
"3.2.22-42941-arm64": {
"appid": 537328660,
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
},
"9.9.25-42941": {
"appid": 537328623,
"qua": "V1_WIN_NQ_9.9.25_42941_GW_B"
},
"6.9.86-42941": {
"appid": 537328648,
"appid": 537328647,
"qua": "V1_MAC_NQ_6.9.86_42941_GW_B"
},
"9.9.26-44175": {
@@ -511,6 +531,14 @@
"appid": 537336639,
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
},
"3.2.23-44343-arm64": {
"appid": 537336640,
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
},
"6.9.87-44343": {
"appid": 537336627,
"qua": "V1_MAC_NQ_6.9.87_44343_GW_B"
},
"9.9.26-44498": {
"appid": 537337416,
"qua": "V1_WIN_NQ_9.9.26_44498_GW_B"
@@ -524,13 +552,21 @@
"qua": "V1_WIN_NQ_9.9.27_45627_GW_B"
},
"6.9.88-44725": {
"appid": 537337594,
"appid": 537337593,
"qua": "V1_MAC_NQ_6.9.88_44725_GW_B"
},
"3.2.25-45758": {
"appid": 537340249,
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
},
"3.2.25-45758-arm64": {
"appid": 537340250,
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
},
"6.9.89-45758": {
"appid": 537340237,
"qua": "V1_MAC_NQ_6.9.89_45758_GW_B"
},
"9.9.27-45758": {
"appid": 537340213,
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
@@ -539,6 +575,10 @@
"appid": 537345891,
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
},
"3.2.26-46494-arm64": {
"appid": 537345892,
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
},
"9.9.28-46494": {
"appid": 537345855,
"qua": "V1_WIN_NQ_9.9.28_46494_GW_B"
@@ -548,13 +588,25 @@
"qua": "V1_MAC_NQ_6.9.90_46494_GW_B"
},
"3.2.26-46928": {
"appid": 537345993,
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
},
"3.2.26-46928-arm64": {
"appid": 537345994,
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
},
"6.9.91-46928": {
"appid": 537345981,
"qua": "V1_MAC_NQ_6.9.91_46928_GW_B"
},
"9.9.28-46928": {
"appid": 537345957,
"qua": "V1_WIN_NQ_9.9.28_46928_GW_B"
},
"3.2.27-47256": {
"appid": 537346857,
"qua": "V1_LNX_NQ_3.2.27_47256_GW_B"
},
"3.2.27-47354": {
"appid": 537346908,
"qua": "V1_LNX_NQ_3.2.27_47354_GW_B"
@@ -575,6 +627,14 @@
"appid": 537352510,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
},
"3.2.28-48517-arm64": {
"appid": 537352511,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
},
"6.9.95-48517": {
"appid": 537352498,
"qua": "V1_MAC_NQ_6.9.95_48517_GW_B"
},
"9.9.30-48762": {
"appid": 537352525,
"qua": "V1_WIN_NQ_9.9.30_48762_GW_B"
@@ -588,9 +648,17 @@
"qua": "V1_WIN_NQ_9.9.31_49738_GW_B"
},
"3.2.29-49738": {
"appid": 537355866,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
},
"3.2.29-49738-arm64": {
"appid": 537355867,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
},
"6.9.96-49738": {
"appid": 537355854,
"qua": "V1_MAC_NQ_6.9.96_49738_GW_B"
},
"9.9.32-50828": {
"appid": 537358739,
"qua": "V1_WIN_NQ_9.9.32_50828_GW_B"
@@ -599,6 +667,10 @@
"appid": 537358775,
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
},
"3.2.30-50828-arm64": {
"appid": 537358776,
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
},
"9.9.32-50969": {
"appid": 537376308,
"qua": "V1_WIN_NQ_9.9.32_50969_GW_B"
@@ -611,6 +683,46 @@
"appid": 537376345,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"3.2.31-51102": {
"appid": 537376497,
"qua": "V1_LNX_NQ_3.2.31_51102_GW_B"
},
"3.2.31-51102-arm64": {
"appid": 537376498,
"qua": "V1_LNX_NQ_3.2.31_51102_GW_B"
},
"6.9.98-51102": {
"appid": 537376485,
"qua": "V1_MAC_NQ_6.9.98_51102_GW_B"
},
"9.9.32-51246": {
"appid": 537376512,
"qua": "V1_WIN_NQ_9.9.32_51246_GW_B"
},
"3.2.32-51728": {
"appid": 537376803,
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
},
"3.2.32-51728-arm64": {
"appid": 537376804,
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
},
"3.2.32-51802": {
"appid": 537376854,
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
},
"3.2.32-51802-arm64": {
"appid": 537376855,
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
},
"6.9.99-51802": {
"appid": 537376842,
"qua": "V1_MAC_NQ_6.9.99_51802_GW_B"
},
"9.9.33-51802": {
"appid": 537376818,
"qua": "V1_WIN_NQ_9.9.33_51802_GW_B"
},
"9.9.33-52230": {
"appid": 537379411,
"qua": "V1_WIN_NQ_9.9.33_52230_GW_B"
@@ -623,6 +735,10 @@
"appid": 537379448,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"7.0.0-52194": {
"appid": 537379435,
"qua": "V1_MAC_NQ_7.0.0_52194_GW_B"
},
"9.9.35-52804": {
"appid": 537382717,
"qua": "V1_WIN_NQ_9.9.35_52804_GW_B"
@@ -642,5 +758,25 @@
"3.2.33-52892-arm64": {
"appid": 537382856,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"7.0.1-52892": {
"appid": 537382843,
"qua": "V1_MAC_NQ_7.0.1_52892_GW_B"
},
"3.2.34-53644": {
"appid": 537391664,
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
},
"3.2.34-53644-arm64": {
"appid": 537391665,
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
},
"7.0.2-53644": {
"appid": 537391652,
"qua": "V1_MAC_NQ_7.0.2_53644_GW_B"
},
"9.9.36-53644": {
"appid": 537391628,
"qua": "V1_WIN_NQ_9.9.36_53644_GW_B"
}
}
+177 -5
View File
@@ -64,7 +64,7 @@
"recv": "1D19FF9"
},
"6.9.83-41857-arm64": {
"send": "0815774",
"send": "23B41F0",
"recv": "0958B3C"
},
"3.2.21-41857-x64": {
@@ -85,7 +85,7 @@
},
"6.9.85-42086-arm64": {
"send": "23B0330",
"recv": "0957648"
"recv": "9556B8"
},
"3.2.21-42086-arm64": {
"send": "3D6D98C",
@@ -103,7 +103,7 @@
"send": "0A0D104",
"recv": "1D3E7F9"
},
"6.9.85-42744-arm64": {
"6.9.86-42744-arm64": {
"send": "23DFEF0",
"recv": "095FD80"
},
@@ -147,6 +147,10 @@
"send": "59A27B0",
"recv": "2FFBE90"
},
"6.9.87-44343-arm64": {
"send": "2311B68",
"recv": "9673A4"
},
"9.9.26-44498-x64": {
"send": "0A1051C",
"recv": "1D3BC0D"
@@ -161,7 +165,7 @@
},
"6.9.88-44725-x64": {
"send": "2756EF6",
"recv": "0A36152"
"recv": "A36152"
},
"6.9.88-44725-arm64": {
"send": "2313C68",
@@ -175,6 +179,10 @@
"send": "3EB6554",
"recv": "149AF0C"
},
"6.9.89-45758-arm64": {
"send": "2425228",
"recv": "9B6770"
},
"9.9.27-45758-x64": {
"send": "0A6A6BC",
"recv": "1E87EC1"
@@ -191,6 +199,10 @@
"send": "3EDC654",
"recv": "14A3124"
},
"6.9.90-46494-arm64": {
"send": "2438B4C",
"recv": "9BBE00"
},
"3.2.26-46928-x64": {
"send": "5D30910",
"recv": "31814B0"
@@ -199,10 +211,18 @@
"send": "3EDC654",
"recv": "14A3124"
},
"6.9.91-46928-arm64": {
"send": "2438B4C",
"recv": "9BBE00"
},
"9.9.28-46928-x64": {
"send": "0A6D66C",
"recv": "1E9890D"
},
"3.2.27-47256-x64": {
"send": "5D389C0",
"recv": "318D090"
},
"3.2.27-47354-x64": {
"send": "5D38930",
"recv": "318D090"
@@ -221,7 +241,7 @@
},
"6.9.93-47354-x64": {
"send": "28ADE46",
"recv": "0A8FD5A"
"recv": "A8FD5A"
},
"9.9.30-48517-x64": {
"send": "0A9B1BC",
@@ -235,6 +255,10 @@
"send": "3F9C7E4",
"recv": "14E1AA8"
},
"6.9.95-48517-arm64": {
"send": "25120A8",
"recv": "9DB00C"
},
"9.9.30-48762-x64": {
"send": "0A9B1BC",
"recv": "1F0324D"
@@ -255,6 +279,10 @@
"send": "426AA04",
"recv": "1596254"
},
"6.9.96-49738-arm64": {
"send": "2785BB8",
"recv": "A29880"
},
"9.9.32-50828-x64": {
"send": "0B245CC",
"recv": "2073D65"
@@ -279,6 +307,46 @@
"send": "43A4804",
"recv": "1608CC8"
},
"3.2.31-51102-x64": {
"send": "63F4910",
"recv": "34B9F90"
},
"3.2.31-51102-arm64": {
"send": "43A48E4",
"recv": "1608D98"
},
"6.9.98-51102-arm64": {
"send": "2849378",
"recv": "A66CFC"
},
"9.9.32-51246-x64": {
"send": "B2E37C",
"recv": "209C7D9"
},
"3.2.32-51728-arm64": {
"send": "48CA8F8",
"recv": "17D5A78"
},
"3.2.32-51728-x64": {
"send": "6B9ADD0",
"recv": "38F5F30"
},
"3.2.32-51802-x64": {
"send": "6B9B790",
"recv": "38F68F0"
},
"3.2.32-51802-arm64": {
"send": "48CB078",
"recv": "17D620C"
},
"6.9.99-51802-arm64": {
"send": "2B0B384",
"recv": "B4526C"
},
"9.9.33-51802-x64": {
"send": "BDE15F",
"recv": "237BC91"
},
"9.9.33-52230-x64": {
"send": "BF2B5F",
"recv": "23BB4DD"
@@ -291,6 +359,10 @@
"send": "493FAD8",
"recv": "17EA1DC"
},
"7.0.0-52194-arm64": {
"send": "2B3FBA4",
"recv": "B4E85C"
},
"9.9.35-52804-x64": {
"send": "C3614F",
"recv": "246F481"
@@ -310,5 +382,105 @@
"3.2.33-52892-arm64": {
"send": "4A5D658",
"recv": "1813A34"
},
"7.0.1-52892-arm64": {
"send": "2B3FBCC",
"recv": "B64170"
},
"3.2.34-53644-x64": {
"send": "6E5AB20",
"recv": "3A12CD0"
},
"3.2.34-53644-arm64": {
"send": "4AABA5C",
"recv": "182C534"
},
"7.0.2-53644-arm64": {
"send": "2B82DEC",
"recv": "B71088"
},
"9.9.36-53644-x64": {
"send": "C3EE2F",
"recv": "24A6355"
},
"6.9.82-40768-x64": {
"send": "6587B8",
"recv": "C45C6E"
},
"6.9.82-40990-x64": {
"send": "6587B8",
"recv": "C45C6E"
},
"6.9.83-41679-x64": {
"send": "271A206",
"recv": "A1E04A"
},
"6.9.83-41785-x64": {
"send": "2744756",
"recv": "A1DE4A"
},
"6.9.83-41857-x64": {
"send": "2745186",
"recv": "A1E96E"
},
"6.9.85-42086-x64": {
"send": "27462F6",
"recv": "A1FC0A"
},
"6.9.86-42744-x64": {
"send": "27770E6",
"recv": "A2725A"
},
"6.9.86-42905-x64": {
"send": "2786206",
"recv": "A2D6A6"
},
"6.9.86-42941-x64": {
"send": "2786366",
"recv": "A2D2E2"
},
"6.9.87-44343-x64": {
"send": "2750306",
"recv": "A2F432"
},
"6.9.89-45758-x64": {
"send": "288CBB6",
"recv": "A87816"
},
"6.9.90-46494-x64": {
"send": "28A2F96",
"recv": "A8D2FE"
},
"6.9.91-46928-x64": {
"send": "28A2F96",
"recv": "A8D2FE"
},
"6.9.95-48517-x64": {
"send": "28DC616",
"recv": "AAED2A"
},
"6.9.96-49738-x64": {
"send": "2B8C936",
"recv": "AFF03E"
},
"6.9.98-51102-x64": {
"send": "2C6CD06",
"recv": "B42922"
},
"6.9.99-51802-x64": {
"send": "2F6C1AB",
"recv": "C16A4A"
},
"7.0.0-52194-x64": {
"send": "2FAC58B",
"recv": "C20DB2"
},
"7.0.1-52892-x64": {
"send": "304CC8B",
"recv": "C3A54E"
},
"7.0.2-53644-x64": {
"send": "309B1BB",
"recv": "C47262"
}
}
+185 -9
View File
@@ -528,8 +528,8 @@
"recv": "7D4D4A8"
},
"6.9.82-40768-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"9.9.22-40824-x64": {
"send": "31C1838",
@@ -540,8 +540,8 @@
"recv": "7D4D4A8"
},
"6.9.82-40824-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"3.2.20-40990-x64": {
"send": "B69CFE0",
@@ -556,8 +556,8 @@
"recv": "31C4FDC"
},
"6.9.82-40990-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"9.9.23-41679-x64": {
"send": "2C94520",
@@ -603,6 +603,10 @@
"send": "6B13038",
"recv": "6B169C8"
},
"6.9.85-42086-arm64": {
"send": "3D6D028",
"recv": "3D6F938"
},
"9.9.23-42430-x64": {
"send": "2C9A4A0",
"recv": "2C9DA20"
@@ -655,6 +659,10 @@
"send": "6926F60",
"recv": "692A910"
},
"6.9.87-44343-arm64": {
"send": "3D74F50",
"recv": "3D77860"
},
"9.9.26-44498-x64": {
"send": "2CDAE40",
"recv": "2CDE3C0"
@@ -687,6 +695,10 @@
"send": "6D6F9A0",
"recv": "6D73350"
},
"6.9.89-45758-arm64": {
"send": "3F9BD68",
"recv": "3F9E678"
},
"3.2.26-46494-x64": {
"send": "AB341C0",
"recv": "AB37C60"
@@ -699,6 +711,10 @@
"send": "6DBBBB0",
"recv": "6DBF560"
},
"6.9.90-46494-arm64": {
"send": "3FC2CD0",
"recv": "3FC55E0"
},
"3.2.26-46928-arm64": {
"send": "6DBBBB0",
"recv": "6DBF560"
@@ -707,10 +723,18 @@
"send": "AB341C0",
"recv": "AB37C60"
},
"6.9.91-46928-arm64": {
"send": "3FC2CD0",
"recv": "3FC55E0"
},
"9.9.28-46928-x64": {
"send": "2E77C20",
"recv": "2E7B1A0"
},
"3.2.27-47256-x64": {
"send": "AB6A7E0",
"recv": "AB6E280"
},
"3.2.27-47354-x64": {
"send": "AB6A6C0",
"recv": "AB6E160"
@@ -743,6 +767,10 @@
"send": "6F48B70",
"recv": "6F4C520"
},
"6.9.95-48517-arm64": {
"send": "40A0438",
"recv": "40A2D48"
},
"9.9.30-48762-x64": {
"send": "2F3B960",
"recv": "2F3EEE0"
@@ -763,13 +791,17 @@
"send": "7342800",
"recv": "73461B0"
},
"6.9.96-49738-arm64": {
"send": "428B660",
"recv": "428DF70"
},
"9.9.32-50828-x64": {
"send": "3155200",
"recv": "3158788"
},
"9.9.32-50828-arm64": {
"send": "4327764",
"recv": "15E3184"
"3.2.30-50828-arm64": {
"send": "74C3070",
"recv": "74C6A20"
},
"3.2.30-50828-x64": {
"send": "B5D0FC0",
@@ -787,6 +819,46 @@
"send": "75BD1D0",
"recv": "75C0B80"
},
"3.2.31-51102-x64": {
"send": "B739780",
"recv": "B73D220"
},
"3.2.31-51102-arm64": {
"send": "75BD390",
"recv": "75C0D40"
},
"6.9.98-51102-arm64": {
"send": "4419468",
"recv": "441BD78"
},
"9.9.32-51246-x64": {
"send": "3199680",
"recv": "319CC08"
},
"3.2.32-51728-arm64": {
"send": "8009330",
"recv": "800CCE0"
},
"3.2.32-51728-x64": {
"send": "C6860E0",
"recv": "C689B80"
},
"3.2.32-51802-x64": {
"send": "C687460",
"recv": "C68AF00"
},
"3.2.32-51802-arm64": {
"send": "800A230",
"recv": "800DBE0"
},
"6.9.99-51802-arm64": {
"send": "499CF40",
"recv": "499FA40"
},
"9.9.33-51802-x64": {
"send": "360A0D8",
"recv": "360D88C"
},
"9.9.33-52230-x64": {
"send": "367FE18",
"recv": "36835CC"
@@ -799,6 +871,10 @@
"send": "80F36D0",
"recv": "80F7080"
},
"7.0.0-52194-arm64": {
"send": "4A05FB0",
"recv": "4A08AB0"
},
"9.9.35-52804-x64": {
"send": "37C3298",
"recv": "37C6A4C"
@@ -818,5 +894,105 @@
"3.2.33-52892-arm64": {
"send": "832ECA0",
"recv": "8332650"
},
"7.0.1-52892-arm64": {
"send": "4B1E4B8",
"recv": "4B20FB8"
},
"3.2.34-53644-x64": {
"send": "CBF25A0",
"recv": "CBF60E0"
},
"3.2.34-53644-arm64": {
"send": "83D1BD0",
"recv": "83D5610"
},
"7.0.2-53644-arm64": {
"send": "4BA3870",
"recv": "4BA6388"
},
"9.9.36-53644-x64": {
"send": "38255F0",
"recv": "3828E30"
},
"6.9.82-40768-x64": {
"send": "489A168",
"recv": "489CD18"
},
"6.9.82-40990-x64": {
"send": "489A168",
"recv": "489CD18"
},
"6.9.83-41679-x64": {
"send": "450C8E0",
"recv": "450F490"
},
"6.9.83-41785-x64": {
"send": "450C540",
"recv": "450F0F0"
},
"6.9.83-41857-x64": {
"send": "450D998",
"recv": "4510548"
},
"6.9.85-42086-x64": {
"send": "450E430",
"recv": "4510FE0"
},
"6.9.86-42744-x64": {
"send": "4570018",
"recv": "4572BC8"
},
"6.9.86-42905-x64": {
"send": "457E7C0",
"recv": "4581370"
},
"6.9.86-42941-x64": {
"send": "457EA78",
"recv": "4581628"
},
"6.9.87-44343-x64": {
"send": "45126C0",
"recv": "4515270"
},
"6.9.89-45758-x64": {
"send": "478B860",
"recv": "478E410"
},
"6.9.90-46494-x64": {
"send": "47B8018",
"recv": "47BABC8"
},
"6.9.91-46928-x64": {
"send": "47B8018",
"recv": "47BABC8"
},
"6.9.95-48517-x64": {
"send": "48A92C0",
"recv": "48ABE70"
},
"6.9.96-49738-x64": {
"send": "4ACD9D8",
"recv": "4AD0588"
},
"6.9.98-51102-x64": {
"send": "4C953E8",
"recv": "4C97F98"
},
"6.9.99-51802-x64": {
"send": "5293B28",
"recv": "52966D8"
},
"7.0.0-52194-x64": {
"send": "53143C0",
"recv": "5316F70"
},
"7.0.1-52892-x64": {
"send": "54552F8",
"recv": "5457EA8"
},
"7.0.2-53644-x64": {
"send": "54F11F0",
"recv": "54F3DA8"
}
}
+9 -38
View File
@@ -1,45 +1,16 @@
import fsPromise from 'fs/promises';
import path from 'node:path';
import { randomUUID } from 'crypto';
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
async function guessDuration (pttPath: string, logger: LogWrapper) {
const pttFileInfo = await fsPromise.stat(pttPath);
const duration = Math.max(1, Math.floor(pttFileInfo.size / 1024 / 3)); // 3kb/s
logger.log('通过文件大小估算语音的时长:', duration);
return duration;
}
export async function encodeSilk (filePath: string, TEMP_DIR: string, logger: LogWrapper) {
try {
const pttPath = path.join(TEMP_DIR, randomUUID());
if (!(await FFmpegService.isSilk(filePath))) {
logger.log(`语音文件${filePath}需要转换成silk`);
await FFmpegService.convertToNTSilkTct(filePath, pttPath);
const duration = await FFmpegService.getDuration(filePath);
logger.log(`语音文件${filePath}转换成功!`, pttPath, '时长:', duration);
return {
converted: true,
path: pttPath,
duration,
};
} else {
let duration = 0;
try {
duration = await FFmpegService.getDuration(filePath);
} catch (e: unknown) {
logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, (e as Error).stack);
duration = await guessDuration(filePath, logger);
}
return {
converted: false,
path: filePath,
duration,
};
}
} catch (error: unknown) {
logger.logError('convert silk failed', error);
return {};
export async function encodeSilk (filePath: string, temporaryDirectory: string, logger: LogWrapper) {
const converted = !(await FFmpegService.isSilk(filePath));
const pttPath = converted ? path.join(temporaryDirectory, randomUUID()) : filePath;
if (converted) {
logger.log(`语音文件${filePath}需要转换成silk`);
await FFmpegService.convertToNTSilkTct(filePath, pttPath);
}
const duration = await FFmpegService.getDuration(pttPath);
logger.log('语音文件已就绪:', pttPath, '时长:', duration);
return { converted, path: pttPath, duration };
}
@@ -4,7 +4,8 @@
*/
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter';
import { FFmpegAddonAdapter, getAddonPath } from './ffmpeg-addon-adapter';
import { existsSync } from 'node:fs';
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
@@ -58,8 +59,8 @@ export class FFmpegAdapterFactory {
ffprobePath: string,
binaryPath?: string
): Promise<IFFmpegAdapter> {
// 1. 优先尝试使用 Native Addon
if (binaryPath) {
const useCommandLine = Boolean(process.env['FFMPEG_PATH'] || process.env['FFPROBE_PATH']);
if (binaryPath && !useCommandLine && existsSync(getAddonPath(binaryPath))) {
const addonAdapter = new FFmpegAddonAdapter(binaryPath);
logger.log('[FFmpeg] 检查 Native Addon 可用性...');
@@ -68,13 +69,10 @@ export class FFmpegAdapterFactory {
return addonAdapter;
}
logger.log('[FFmpeg] Native Addon 不可用,尝试使用命令行工具');
} else {
logger.log('[FFmpeg] 未提供 binaryPath,跳过 Native Addon 检测');
throw new Error('FFmpeg Native Addon 加载失败: ' + getAddonPath(binaryPath));
}
// 2. 降级到 execFile 实现
const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath, binaryPath, logger);
const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath);
logger.log(`[FFmpeg] 检查命令行工具可用性: ${ffmpegPath}`);
if (await execAdapter.isAvailable()) {
@@ -82,9 +80,7 @@ export class FFmpegAdapterFactory {
return execAdapter;
}
// 3. 都不可用,返回 execAdapter 但会在使用时报错
logger.logError('[FFmpeg] 警告: FFmpeg 不可用,将使用命令行适配器但可能失败');
return execAdapter;
throw new Error('FFmpeg 命令行工具不可用,请检查 ffmpeg 和 ffprobe 路径: ' + ffmpegPath + ', ' + ffprobePath);
}
/**
@@ -105,20 +101,14 @@ export class FFmpegAdapterFactory {
logger: LogWrapper,
ffmpegPath: string,
ffprobePath: string
): Promise<void> {
// 如果当前使用的是 Exec 适配器,更新路径
if (this.instance && this.instance instanceof FFmpegExecAdapter) {
logger.log(`[FFmpeg] 更新 FFmpeg 路径: ${ffmpegPath}`);
this.instance.setFFmpegPath(ffmpegPath);
this.instance.setFFprobePath(ffprobePath);
// 验证新路径是否可用
if (await this.instance.isAvailable()) {
logger.log('[FFmpeg] 新路径验证成功 ✓');
} else {
logger.logError('[FFmpeg] 警告: 新 FFmpeg 路径不可用');
}
): Promise<IFFmpegAdapter> {
const adapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath);
if (!await adapter.isAvailable()) {
throw new Error('FFmpeg 路径不可用: ' + ffmpegPath + ', ' + ffprobePath);
}
this.instance = adapter;
logger.log('[FFmpeg] 已更新命令行工具路径:', ffmpegPath, ffprobePath);
return adapter;
}
/**
@@ -3,9 +3,8 @@
* 使用原生 Node.js Addon 实现的 FFmpeg 适配器
*/
import { platform, arch } from 'node:os';
import path from 'node:path';
import { existsSync, openSync, readSync, closeSync } from 'node:fs';
import { openSync, readSync, closeSync } from 'node:fs';
import { writeFile } from 'node:fs/promises';
import type { FFmpeg } from './ffmpeg-addon';
import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface';
@@ -15,15 +14,9 @@ import { dlopen } from 'node:process';
* 获取 Native Addon 路径
* @param binaryPath 二进制文件路径(来自 pathWrapper.binaryPath)
*/
function getAddonPath (binaryPath: string): string {
const platformName = platform();
const archName = arch();
export function getAddonPath (binaryPath: string): string {
const addonFileName: string = process.platform + '.' + process.arch;
const addonPath = path.join(binaryPath, './native/ffmpeg/', `ffmpegAddon.${addonFileName}.node`);
if (!existsSync(addonPath)) {
throw new Error(`Unsupported platform: ${platformName} ${archName} - Addon not found at ${addonPath}`);
}
return addonPath;
}
@@ -130,9 +123,9 @@ export class FFmpegAddonAdapter implements IFFmpegAdapter {
/**
* 提取缩略图
*/
async extractThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
async extractThumbnail (videoPath: string, thumbnailPath: string, format: 'jpg' | 'png' = 'jpg'): Promise<void> {
const addon = this.ensureAddon();
const info = await addon.getVideoInfo(videoPath);
const info = await addon.getVideoInfo(videoPath, format);
// 将缩略图写入文件
await writeFile(thumbnailPath, info.image);
@@ -53,7 +53,7 @@ export interface FFmpeg {
/**
* Get video information including resolution, duration, format, codec and first frame thumbnail
*/
getVideoInfo (filePath: string, format?: 'bmp' | 'bmp24'): Promise<VideoInfo>;
getVideoInfo (filePath: string, format?: 'jpg' | 'png'): Promise<VideoInfo>;
/**
* Get duration of audio or video file in seconds
@@ -3,14 +3,10 @@
* 使用 execFile 调用 FFmpeg 命令行工具的适配器实现
*/
import { readFileSync, existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs';
import { dirname, join } from 'path';
import { existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs';
import { dirname } from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { fileTypeFromFile } from 'file-type';
import { imageSizeFallBack } from 'napcat-image-size/src/index';
import { downloadFFmpegIfNotExists } from './download-ffmpeg';
import { LogWrapper } from '@/napcat-core/helper/log';
import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface';
const execFileAsync = promisify(execFile);
@@ -30,52 +26,24 @@ function ensureDirExists (filePath: string): void {
*/
export class FFmpegExecAdapter implements IFFmpegAdapter {
public readonly name = 'FFmpegExec';
private downloadAttempted = false;
constructor (
private ffmpegPath: string = 'ffmpeg',
private ffprobePath: string = 'ffprobe',
private binaryPath?: string,
private logger?: LogWrapper
private ffprobePath: string = 'ffprobe'
) { }
/**
* 检查 FFmpeg 是否可用,如果不可用则尝试下载
* 检查 FFmpeg 和 FFprobe 是否可用
*/
async isAvailable (): Promise<boolean> {
// 首先检查当前路径
try {
await execFileAsync(this.ffmpegPath, ['-version']);
await Promise.all([
execFileAsync(this.ffmpegPath, ['-version'], { timeout: 10000, windowsHide: true }),
execFileAsync(this.ffprobePath, ['-version'], { timeout: 10000, windowsHide: true }),
]);
return true;
} catch {
// 如果失败且未尝试下载,尝试下载
if (!this.downloadAttempted && this.binaryPath && this.logger) {
this.downloadAttempted = true;
if (process.env['NAPCAT_DISABLE_FFMPEG_DOWNLOAD']) {
return false;
}
this.logger.log('[FFmpeg] 未找到可用的 FFmpeg,尝试自动下载...');
const result = await downloadFFmpegIfNotExists(this.logger);
if (result.path && result.reset) {
// 更新路径
if (process.platform === 'win32') {
this.ffmpegPath = join(result.path, 'ffmpeg.exe');
this.ffprobePath = join(result.path, 'ffprobe.exe');
this.logger.log('[FFmpeg] 已更新路径:', this.ffmpegPath);
// 再次检查
try {
await execFileAsync(this.ffmpegPath, ['-version']);
return true;
} catch {
return false;
}
}
}
}
return false;
}
}
@@ -98,40 +66,29 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
* 获取视频信息
*/
async getVideoInfo (videoPath: string): Promise<VideoInfoResult> {
// 获取文件大小和类型
const [fileType, duration] = await Promise.all([
fileTypeFromFile(videoPath).catch(() => null),
this.getDuration(videoPath).catch(() => 60),
const [probe, frame] = await Promise.all([
execFileAsync(this.ffprobePath, [
'-v', 'error', '-select_streams', 'v:0',
'-show_entries', 'stream=width,height:format=duration,format_name',
'-of', 'json', videoPath,
], { timeout: 30000, windowsHide: true }),
execFileAsync(this.ffmpegPath, [
'-v', 'error', '-i', videoPath, '-frames:v', '1',
'-f', 'image2pipe', '-vcodec', 'mjpeg', 'pipe:1',
], { encoding: 'buffer', maxBuffer: 16 * 1024 * 1024, timeout: 30000, windowsHide: true }),
]);
// 创建临时缩略图路径
const thumbnailPath = `${videoPath}.thumbnail.bmp`;
let width = 100;
let height = 100;
let thumbnail: Buffer | undefined;
try {
await this.extractThumbnail(videoPath, thumbnailPath);
// 获取图片尺寸
const dimensions = await imageSizeFallBack(thumbnailPath);
width = dimensions.width ?? 100;
height = dimensions.height ?? 100;
// 读取缩略图
if (existsSync(thumbnailPath)) {
thumbnail = readFileSync(thumbnailPath);
}
} catch (_error) {
// 使用默认值
const metadata = JSON.parse(probe.stdout);
const stream = metadata.streams[0];
const duration = Number(metadata.format.duration);
if (!stream || !Number.isFinite(duration) || duration < 0 || frame.stdout.length === 0) {
throw new Error('FFmpeg 无法读取视频信息或首帧: ' + videoPath);
}
return {
width,
height,
width: stream.width,
height: stream.height,
duration,
format: fileType?.ext ?? 'mp4',
thumbnail,
format: metadata.format.format_name,
thumbnail: frame.stdout,
};
}
@@ -147,10 +104,10 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
'-of',
'default=noprint_wrappers=1:nokey=1',
filePath,
]);
], { timeout: 30000, windowsHide: true });
const duration = parseFloat(stdout.trim());
if (isNaN(duration)) {
if (!Number.isFinite(duration) || duration < 0) {
throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`);
}
return duration;
@@ -186,7 +143,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
'-ac', '1',
'-f', 's16le',
pcmPath,
]);
], { timeout: 120000, windowsHide: true });
if (!existsSync(pcmPath)) {
throw new Error('转换PCM失败,输出文件不存在');
@@ -207,25 +164,22 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
const params = format === 'amr'
? [
'-f', 's16le',
'-ar', '24000',
'-ac', '1',
'-i', inputFile,
'-vn', '-ac', '1',
'-ar', '8000',
'-b:a', '12.2k',
'-y',
outputFile,
]
: [
'-f', 's16le',
'-ar', '24000',
'-ac', '1',
'-i', inputFile,
'-vn', '-ac', '1',
...(format === 'spx' ? ['-ar', '32000'] : []),
'-y',
outputFile,
];
await execFileAsync(this.ffmpegPath, params);
await execFileAsync(this.ffmpegPath, params, { timeout: 120000, windowsHide: true });
if (!existsSync(outputFile)) {
throw new Error('转换失败,输出文件不存在');
@@ -245,11 +199,10 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
const { stderr } = await execFileAsync(this.ffmpegPath, [
'-i', videoPath,
'-ss', '00:00:01.000',
'-vframes', '1',
'-y', // 覆盖输出文件
thumbnailPath,
]);
], { timeout: 30000, windowsHide: true });
if (!existsSync(thumbnailPath)) {
throw new Error(`提取缩略图失败,输出文件不存在: ${stderr}`);
@@ -260,7 +213,11 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
}
}
async convertToNTSilkTct (_inputFile: string, _outputFile: string): Promise<void> {
throw new Error('convertToNTSilkTct is not implemented in FFmpegExecAdapter');
async convertToNTSilkTct (inputFile: string, outputFile: string): Promise<void> {
ensureDirExists(outputFile);
await execFileAsync(this.ffmpegPath, [
'-v', 'error', '-y', '-i', inputFile, '-vn', '-ac', '1', '-ar', '24000',
'-c:a', 'ntsilk_s16le', '-f', 'ntsilk_s16le', outputFile,
], { timeout: 120000, windowsHide: true });
}
}
+56 -62
View File
@@ -1,21 +1,29 @@
import { statSync, existsSync, writeFileSync } from 'fs';
import path from 'path';
import type { VideoInfo } from './video';
import { fileTypeFromFile } from 'file-type';
import { platform } from 'node:os';
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory';
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter';
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
if (process.platform === 'win32' && binaryPath) {
const exeName = `${tool}.exe`;
const localPath = path.join(binaryPath, 'ffmpeg', exeName);
const isLocalExeExists = existsSync(localPath);
return isLocalExeExists ? localPath : exeName;
export const getFFmpegPath = (tool: 'ffmpeg' | 'ffprobe', binaryPath?: string): string => {
const configuredPath = process.env[tool === 'ffmpeg' ? 'FFMPEG_PATH' : 'FFPROBE_PATH'];
if (configuredPath) return configuredPath;
const executable = tool + (process.platform === 'win32' ? '.exe' : '');
if (binaryPath) {
const localPath = path.join(binaryPath, 'ffmpeg', executable);
if (existsSync(localPath)) return localPath;
}
return tool;
if (process.platform === 'darwin') {
const directories = (process.env['PATH'] ?? '').split(':').filter(Boolean);
directories.push(process.arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin');
for (const directory of directories) {
const candidate = path.join(directory, executable);
if (existsSync(candidate)) return candidate;
}
}
return executable;
};
export let FFMPEG_CMD = 'ffmpeg';
@@ -23,6 +31,7 @@ export let FFPROBE_CMD = 'ffprobe';
export class FFmpegService {
private static adapter: IFFmpegAdapter | null = null;
private static initialized = false;
private static initializationError: unknown;
/**
* 初始化 FFmpeg 服务
@@ -38,20 +47,24 @@ export class FFmpegService {
FFMPEG_CMD = getFFmpegPath('ffmpeg', binaryPath);
FFPROBE_CMD = getFFmpegPath('ffprobe', binaryPath);
// 立即初始化适配器(会触发自动下载等逻辑)
this.adapter = await FFmpegAdapterFactory.getAdapter(
logger,
FFMPEG_CMD,
FFPROBE_CMD,
binaryPath
);
try {
this.adapter = await FFmpegAdapterFactory.getAdapter(
logger,
FFMPEG_CMD,
FFPROBE_CMD,
binaryPath
);
} catch (error) {
this.initializationError = error;
logger.logError('[FFmpeg] 媒体功能初始化失败:', error);
}
this.initialized = true;
}
public static getAdapterName (): string {
if (!this.adapter) {
throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
}
return this.adapter.name;
}
@@ -61,7 +74,7 @@ export class FFmpegService {
*/
private static async getAdapter (): Promise<IFFmpegAdapter> {
if (!this.adapter) {
throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
}
return this.adapter;
}
@@ -76,15 +89,14 @@ export class FFmpegService {
* @deprecated 建议使用 init() 方法初始化
*/
public static async setFfmpegPath (ffmpegPath: string, logger: LogWrapper): Promise<void> {
if (platform() === 'win32') {
FFMPEG_CMD = path.join(ffmpegPath, 'ffmpeg.exe');
FFPROBE_CMD = path.join(ffmpegPath, 'ffprobe.exe');
logger.log('[Check] ffmpeg:', FFMPEG_CMD);
logger.log('[Check] ffprobe:', FFPROBE_CMD);
// 更新适配器路径
await FFmpegAdapterFactory.updateFFmpegPath(logger, FFMPEG_CMD, FFPROBE_CMD);
}
const suffix = process.platform === 'win32' ? '.exe' : '';
const ffmpegCommand = path.join(ffmpegPath, 'ffmpeg' + suffix);
const ffprobeCommand = path.join(ffmpegPath, 'ffprobe' + suffix);
this.adapter = await FFmpegAdapterFactory.updateFFmpegPath(logger, ffmpegCommand, ffprobeCommand);
FFMPEG_CMD = ffmpegCommand;
FFPROBE_CMD = ffprobeCommand;
this.initializationError = undefined;
this.initialized = true;
}
/**
@@ -100,6 +112,11 @@ export class FFmpegService {
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
*/
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
const currentAdapter = await this.getAdapter();
if (currentAdapter instanceof FFmpegAddonAdapter) {
await currentAdapter.extractThumbnail(videoPath, thumbnailPath, 'png');
return;
}
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
@@ -142,41 +159,18 @@ export class FFmpegService {
public static async getVideoInfo (videoPath: string, thumbnailPath: string): Promise<VideoInfo> {
const adapter = await this.getAdapter();
try {
// 获取文件大小
const fileSize = statSync(videoPath).size;
// 使用适配器获取视频信息
const videoInfo = await adapter.getVideoInfo(videoPath);
// 如果提供了缩略图路径且适配器返回了缩略图,保存到指定路径
if (thumbnailPath && videoInfo.thumbnail) {
writeFileSync(thumbnailPath, videoInfo.thumbnail);
}
const result: VideoInfo = {
width: videoInfo.width,
height: videoInfo.height,
time: videoInfo.duration,
format: videoInfo.format,
size: fileSize,
filePath: videoPath,
};
return result;
} catch (_error) {
// 降级处理:返回默认值
const fileType = await fileTypeFromFile(videoPath).catch(() => null);
const fileSize = statSync(videoPath).size;
return {
width: 100,
height: 100,
time: 60,
format: fileType?.ext ?? 'mp4',
size: fileSize,
filePath: videoPath,
};
const fileSize = statSync(videoPath).size;
const videoInfo = await adapter.getVideoInfo(videoPath);
if (thumbnailPath && videoInfo.thumbnail) {
writeFileSync(thumbnailPath, videoInfo.thumbnail);
}
return {
width: videoInfo.width,
height: videoInfo.height,
time: videoInfo.duration,
format: videoInfo.format,
size: fileSize,
filePath: videoPath,
};
}
}
+61
View File
@@ -0,0 +1,61 @@
import type { NodeIKernelRichMediaService } from '../services/NodeIKernelRichMediaService';
type GroupFileService = Pick<NodeIKernelRichMediaService, 'getGroupFileInfo' | 'deleteGroupFile'>;
function withTimeout<T> (promise: Promise<T>, operation: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`${operation}超时,请重新查询群文件列表确认文件状态`)), 15000);
promise.then(resolve, reject).finally(() => clearTimeout(timer));
});
}
function assertBusId (busId: number): void {
if (!Number.isInteger(busId) || busId <= 0 || busId > 0xFFFFFFFF) {
throw new Error('Invalid bus_id');
}
}
export async function deleteGroupFiles (service: GroupFileService, groupCode: string, files: string[], busIds?: number[]) {
if (!files.length || files.some(fileId => !fileId)) {
throw new Error('Invalid file_id');
}
if (busIds && busIds.length !== files.length) {
throw new Error('bus_id 数量必须与文件数量一致');
}
const resolvedBusIds: number[] = [];
for (const [index, fileId] of files.entries()) {
let busId = busIds?.[index];
if (busId === undefined) {
const info = await withTimeout(service.getGroupFileInfo(groupCode, fileId), '查询群文件信息');
if (info?.result !== 0) {
throw new Error(`查询群文件信息失败: ${info?.errMsg || info?.result}`);
}
const detail = info.groupFileInfoResult;
if (detail?.retCode !== 0 || detail.fileInfo?.fileId !== fileId) {
throw new Error(`查询群文件信息失败: ${detail?.clientWording || detail?.retMsg || '未返回目标文件信息'}`);
}
busId = detail.fileInfo.busId;
}
assertBusId(busId);
resolvedBusIds.push(busId);
}
const response = await withTimeout(service.deleteGroupFile(groupCode, resolvedBusIds, files), '删除群文件');
if (response?.result !== 0) {
throw new Error(`删除群文件失败: ${response?.errMsg || response?.result}`);
}
const detail = response.transGroupFileResult;
if (detail?.result?.retCode !== 0) {
throw new Error(`删除群文件失败: ${detail?.result?.clientWording || detail?.result?.retMsg || detail?.result?.retCode || '缺少删除结果'}`);
}
if (!Array.isArray(detail.successFileIdList) || !Array.isArray(detail.failFileIdList)) {
throw new Error('删除群文件失败: 缺少逐文件删除结果');
}
const missing = files.filter(fileId => !detail.successFileIdList.includes(fileId));
if (detail.failFileIdList.length || missing.length) {
const failed = [...new Set([...detail.failFileIdList, ...missing])];
throw new Error(`删除群文件失败: ${failed.join(', ')}`);
}
return response;
}
@@ -0,0 +1,24 @@
/** Self-reported profile region only; never infer a location from other fields. */
export interface ProfileRegion {
country?: string;
province?: string;
city?: string;
}
function text (value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
/** Keep one source together: mixing old/new components can invent a region. */
export function selectProfileRegion (fresh?: ProfileRegion, fallback?: ProfileRegion): Required<ProfileRegion> {
for (const source of [fresh, fallback]) {
const region = { country: text(source?.country), province: text(source?.province), city: text(source?.city) };
if (Object.values(region).some(Boolean)) return region;
}
return { country: '', province: '', city: '' };
}
export function profileRegionArea (source?: ProfileRegion): string {
const region = selectProfileRegion(source);
return [...new Set(Object.values(region).filter(Boolean))].join(' ');
}
@@ -38,7 +38,8 @@ export class NativePacketClient {
}
async init (_pid: number, recv: string, send: string): Promise<void> {
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
this.available = false;
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40768');
if (!isNewQQ) {
this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化');
return;
@@ -77,8 +78,9 @@ export class NativePacketClient {
data: (ret as { rspbuffer: Buffer; }).rspbuffer,
}));
let timeoutHandle: ReturnType<typeof setTimeout>;
const timeoutPromise = new Promise<RecvPacketData>((_resolve, reject) => {
setTimeout(
timeoutHandle = setTimeout(
() =>
reject(
new Error(
@@ -89,7 +91,11 @@ export class NativePacketClient {
);
});
return Promise.race([sendPromise, timeoutPromise]);
try {
return await Promise.race([sendPromise, timeoutPromise]);
} finally {
clearTimeout(timeoutHandle!);
}
}
async sendOidbPacket (pkt: OidbPacket, rsp = false, timeout = 5000): Promise<RecvPacketData> {
+11 -2
View File
@@ -14,7 +14,7 @@ interface OffsetType {
const typedOffset: OffsetType = offset;
// 0 send 1 recv
export interface NativePacketExportType {
initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => boolean;
initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => string;
}
export type PacketType = 0 | 1; // 0: send, 1: recv
@@ -38,10 +38,15 @@ export class NativePacketHandler {
this.logger = logger;
try {
const platform = process.platform + '.' + process.arch;
if (!this.supportedPlatforms.includes(platform)) {
this.logger.logWarn(`NativePacketClient: 不支持的平台: ${platform}`);
return;
}
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './native/packet/MoeHoo.' + platform + '.node');
if (!fs.existsSync(moehoo_path)) {
this.logger.logWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`);
this.loaded = false;
return;
}
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
this.loaded = true;
@@ -213,9 +218,13 @@ export class NativePacketHandler {
return false;
}
this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
const result = this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
this.emitPacket(type, uin, cmd, seq, hex_data);
}, o3HookMode);
if (result !== 'success') {
this.logger.logError(`[PacketHandler] 初始化失败: ${result}`);
return false;
}
this.logger.log('[PacketHandler] 初始化成功');
return true;
} catch (error) {
@@ -211,12 +211,14 @@ export class PacketMsgReplyElement extends IPacketMsgElement<SendReplyElement> {
export class PacketMsgFaceElement extends IPacketMsgElement<SendFaceElement> {
faceId: number;
faceText: string;
isLargeFace: boolean;
resultId?: string;
constructor (element: SendFaceElement) {
super(element);
this.faceId = element.faceElement.faceIndex;
this.faceText = element.faceElement.faceText || '[表情]';
this.resultId = element.faceElement.resultId;
this.isLargeFace = element.faceElement.faceType === FaceType.AniSticke;
}
@@ -237,6 +239,12 @@ export class PacketMsgFaceElement extends IPacketMsgElement<SendFaceElement> {
}),
businessType: 1,
},
}, {
// QQ consumes the element after an animated face as compatibility text.
// Without it, the next user-supplied message segment is discarded.
text: {
str: this.faceText,
},
}];
} else if (this.faceId < 260) {
return [{
@@ -1,5 +1,6 @@
import { GetFileListParam, MessageElement, Peer } from '@/napcat-core/types';
import { GeneralCallResult } from './common';
import type { GroupFileInfoUpdateItem } from '../listeners/NodeIKernelMsgListener';
export enum UrlFileDownloadType {
KUNKNOWN,
@@ -192,7 +193,14 @@ export interface NodeIKernelRichMediaService {
};
}>;
getGroupFileInfo (arg1: unknown, arg2: unknown): unknown;
getGroupFileInfo (groupCode: string, fileId: string): Promise<GeneralCallResult & {
groupFileInfoResult: {
retCode: number;
retMsg: string;
clientWording: string;
fileInfo: NonNullable<GroupFileInfoUpdateItem['fileInfo']>;
};
}>;
getGroupTransferList (arg1: string, arg2: unknown): unknown;
@@ -235,11 +243,16 @@ export interface NodeIKernelRichMediaService {
searchGroupFileByWord (arg1: unknown[], arg2: unknown[], arg3: string, arg4: string, arg5: number): unknown;
deleteGroupFile (GroupCode: string, params: Array<number>, Files: Array<string>): Promise<GeneralCallResult & {
deleteGroupFile (groupCode: string, busIds: Array<number>, files: Array<string>): Promise<GeneralCallResult & {
// QQ's NodeIDeleteGroupFileCallback also uses this property name.
transGroupFileResult: {
result: unknown;
successFileIdList: Array<unknown>;
failFileIdList: Array<unknown>;
result: {
retCode: number;
retMsg: string;
clientWording: string;
};
successFileIdList: Array<string>;
failFileIdList: Array<string>;
};
}>;
+5 -1
View File
@@ -1 +1,5 @@
node.exe ./index.js
@echo off
setlocal
cd /d "%~dp0" || exit /b 1
"%~dp0node.exe" "%~dp0index.js" %*
exit /b %errorlevel%
+2 -1
View File
@@ -1,6 +1,7 @@
const process = require('process');
const os = require('os');
const path = require('path');
const { pathToFileURL } = require('url');
// 保存原始dlopen
const dlopenOrig = process.dlopen;
@@ -50,7 +51,7 @@ async function initializeNapCat () {
console.log('[NapCat] [Info] 开始初始化NapCat');
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework, getWebUiUrl } = await import('file://' + path.join(currentPath, './napcat.mjs'));
const { NCoreInitFramework, getWebUiUrl } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
getWebUiUrlFunc = getWebUiUrl;
await NCoreInitFramework(wrapperSession, wrapperLoginService, (callback) => { ncCallback = callback; });
} catch (error) {
+2 -1
View File
@@ -1,5 +1,6 @@
// const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
async function initializeNapCat (session, loginService, registerCallback) {
// const logFile = path.join(currentPath, 'napcat.log');
@@ -12,7 +13,7 @@ async function initializeNapCat (session, loginService, registerCallback) {
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework } = await import('file://' + path.join(currentPath, './napcat.mjs'));
const { NCoreInitFramework } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
await NCoreInitFramework(session, loginService, (callback) => { registerCallback(callback); });
} catch (error) {
console.log('[NapCat] [Error] 初始化NapCat', error);
@@ -1,8 +1,10 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
set NAPCAT_DEBUG_CONSOLE=1
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
@@ -27,4 +29,4 @@ set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
pause
pause
+6 -4
View File
@@ -1,8 +1,10 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -24,4 +26,4 @@ if not exist "%QQpath%" (
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
Binary file not shown.
@@ -24,7 +24,7 @@ export const GoCQHTTPActionsExamples = {
response: { result: {}, groupItem: {} },
},
DeleteGroupFile: {
payload: { group_id: '123456', file_id: 'file_uuid_123' },
payload: { group_id: '123456', file_id: 'file_uuid_123', bus_id: 104 },
response: {},
},
DeleteGroupFileFolder: {
@@ -1,11 +1,12 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { ActionName, BaseCheckResult } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
export const DoGroupAlbumCommentPayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册 ID' }),
lloc: Type.String({ description: '图片 ID' }),
lloc: Type.Optional(Type.String({ description: '图片 ID;不传或为空时评论整个上传批次,此时必须提供 batch_id' })),
batch_id: Type.Optional(Type.String({ description: '上传批次 ID,可取自 get_group_album_media_list 返回的 batch.link_id 或 media[].batch_id' })),
content: Type.String({ description: '评论内容' }),
});
@@ -14,11 +15,12 @@ export type DoGroupAlbumCommentPayload = Static<typeof DoGroupAlbumCommentPayloa
export class DoGroupAlbumComment extends OneBotAction<DoGroupAlbumCommentPayload, any> {
override actionName = ActionName.DoGroupAlbumComment;
override actionSummary = '发表群相册评论';
override actionDescription = 'lloc 与 batch_id 至少提供一项。传入 lloc 时评论单张图片;仅传 batch_id 时评论整个上传批次。';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
lloc: 'media_id_1',
batch_id: '2147483658',
content: '很有意思',
};
@@ -29,12 +31,22 @@ export class DoGroupAlbumComment extends OneBotAction<DoGroupAlbumCommentPayload
override payloadSchema = DoGroupAlbumCommentPayloadSchema;
override returnSchema = Type.Any({ description: '评论结果' });
protected override async check (payload: DoGroupAlbumCommentPayload): Promise<BaseCheckResult> {
const result = await super.check(payload);
if (!result.valid) return result;
if (!payload.lloc && !payload.batch_id) {
return { valid: false, message: 'lloc 或 batch_id 至少需要提供一个' };
}
return { valid: true };
}
async _handle (payload: DoGroupAlbumCommentPayload) {
return await this.core.apis.WebApi.doAlbumMediaPlainCommentByNTQQ(
payload.group_id,
payload.album_id,
payload.lloc,
payload.content
payload.content,
payload.batch_id
);
}
}
@@ -2,6 +2,7 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import path from 'node:path';
import { DEFAULT_FLASH_VALIDITY_SECONDS } from '@/napcat-core/data/flash';
const richMediaList = [
'.mp4', '.mov', '.avi', '.wmv', '.mpeg', '.mpg', '.flv', '.mkv',
@@ -15,6 +16,7 @@ export const CreateFlashTaskPayloadSchema = Type.Object({
], { description: '文件列表或单个文件路径' }),
name: Type.Optional(Type.String({ description: '任务名称' })),
thumb_path: Type.Optional(Type.String({ description: '缩略图路径' })),
validitySeconds: Type.Optional(Type.Number({ description: '文件集有效期(秒),可选 14 天 1209600 / 90 天 7776000 / 180 天 15552000,默认 1209600' })),
});
export type CreateFlashTaskPayload = Static<typeof CreateFlashTaskPayloadSchema>;
@@ -27,6 +29,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
override payloadExample = {
files: 'C:\\test.jpg',
name: 'test_task',
validitySeconds: DEFAULT_FLASH_VALIDITY_SECONDS,
};
override returnExample = {
@@ -67,6 +70,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
} else {
normalPath = toPlatformPath(thumbPath);
}
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList, normalPath, payload.name || '');
const validitySeconds = payload.validitySeconds ?? DEFAULT_FLASH_VALIDITY_SECONDS;
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList, normalPath, payload.name || '', validitySeconds);
}
}
@@ -7,6 +7,8 @@ import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
file_id: Type.String({ description: '文件ID' }),
bus_id: Type.Optional(Type.Number({ minimum: 1, maximum: 0xFFFFFFFF, multipleOf: 1, description: '文件业务ID,默认使用文件列表中的 busid' })),
busid: Type.Optional(Type.Number({ minimum: 1, maximum: 0xFFFFFFFF, multipleOf: 1, description: '文件业务ID,兼容 busid 字段' })),
});
type PayloadType = Static<typeof PayloadSchema>;
@@ -28,6 +30,14 @@ export class DeleteGroupFile extends OneBotAction<PayloadType, ReturnType> {
async _handle (payload: PayloadType) {
const data = FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (!data || !data.fileId) throw new Error('Invalid file_id');
return await this.core.apis.GroupApi.delGroupFile(payload.group_id.toString(), [data.fileId]);
const groupCode = payload.group_id.toString();
if (data.peer.chatType !== 2 || data.peer.peerUid !== groupCode) {
throw new Error('file_id 不属于指定群');
}
if (payload.bus_id !== undefined && payload.busid !== undefined && payload.bus_id !== payload.busid) {
throw new Error('bus_id 与 busid 不一致');
}
const busId = payload.bus_id ?? payload.busid ?? data.busId;
return await this.core.apis.GroupApi.delGroupFile(groupCode, [data.fileId], busId === undefined ? undefined : [busId]);
}
}
@@ -43,7 +43,8 @@ export class GetGroupFilesByFolder extends OneBotAction<PayloadType, ReturnType>
return {
files: ret.filter(item => item.fileInfo)
.map(item => OB11Construct.file(item.peerId, item.fileInfo!)),
folders: [],
folders: ret.filter(item => item.folderInfo)
.map(item => OB11Construct.folder(item.peerId, item.folderInfo!)),
};
}
}
@@ -1,3 +1,4 @@
import { selectProfileRegion } from '@/napcat-core/helper/profile-region';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { OB11UserSex } from '@/napcat-onebot/index';
import { OB11Construct } from '@/napcat-onebot/helper/data';
@@ -56,6 +57,7 @@ export default class GoCQHTTPGetStrangerInfo extends OneBotAction<PayloadType, R
...extendData.detail.simpleInfo.baseInfo,
...extendData.detail.simpleInfo.relationFlags ?? {},
...extendData.detail.simpleInfo.status ?? {},
...selectProfileRegion(info, extendData.detail.commonExt),
user_id: parseInt(extendData.detail.uin) ?? 0,
uid: info.uid ?? uid,
nickname: extendData.detail.simpleInfo.coreInfo.nick ?? '',
@@ -26,7 +26,13 @@ export default class SetGroupLeave extends OneBotAction<PayloadType, ReturnType>
override returnExample = GroupActionsExamples.SetGroupLeave.response;
async _handle (payload: PayloadType): Promise<null> {
await this.core.apis.GroupApi.quitGroup(payload.group_id.toString());
const groupCode = payload.group_id.toString();
// is_dismiss 既可能是布尔值,也可能是字符串 'true'(与 approve 等字段保持一致)
if (payload.is_dismiss === true || payload.is_dismiss === 'true') {
await this.core.apis.GroupApi.destroyGroup(groupCode);
} else {
await this.core.apis.GroupApi.quitGroup(groupCode);
}
return null;
}
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { profileRegionArea } from '@/napcat-core/helper/profile-region';
import { calcQQLevel } from 'napcat-common/src/helper';
import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
import { FriendV2, Group, GroupFileInfoUpdateParamType, GroupMember, SelfInfo, NTSex } from 'napcat-core';
@@ -70,7 +71,7 @@ export class OB11Construct {
}[sex] || OB11UserSex.unknown;
}
static groupMember (group_id: string, member: GroupMember): OB11GroupMember {
static groupMember (group_id: string, member: GroupMember & { country?: string; province?: string; city?: string }): OB11GroupMember {
return {
group_id: +group_id,
user_id: +member.uin,
@@ -78,7 +79,7 @@ export class OB11Construct {
card: member.cardName,
sex: this.sex(member.sex),
age: member.age ?? 0,
area: '',
area: profileRegionArea(member),
level: member.memberRealLevel?.toString() ?? '0',
qq_level: (member.qqLevel && calcQQLevel(member.qqLevel)) || 0,
join_time: +member.joinTime,
@@ -111,7 +112,7 @@ export class OB11Construct {
static file (peerId: string, file: Exclude<GroupFileInfoUpdateParamType['item'][0]['fileInfo'], undefined>): OB11GroupFile {
return {
group_id: +peerId,
file_id: FileNapCatOneBotUUID.encodeModelId({ chatType: 2, peerUid: peerId }, file.fileModelId, file.fileId, file.fileId ?? ''),
file_id: FileNapCatOneBotUUID.encodeGroupFile({ chatType: 2, peerUid: peerId }, file),
file_name: file.fileName,
busid: file.busId,
size: +file.fileSize,
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,20 @@
$ErrorActionPreference = 'Stop'
$terminal = $args[0]
$payload = @{
script = $args[1]
arguments = @($args | Select-Object -Skip 2)
} | ConvertTo-Json -Compress
$encodedPayload = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($payload))
$command = @"
`$payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('$encodedPayload')) | ConvertFrom-Json
`$launchArguments = @(`$payload.arguments)
& `$payload.script @launchArguments
exit `$LASTEXITCODE
"@
$encodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
$commandArguments = "-NoProfile -ExecutionPolicy Bypass -EncodedCommand $encodedCommand"
if ($terminal -eq 'wt.exe') {
Start-Process -FilePath $terminal -ArgumentList "powershell.exe $commandArguments" -Verb RunAs
} else {
Start-Process -FilePath $terminal -ArgumentList $commandArguments -Verb RunAs
}
+14 -11
View File
@@ -1,15 +1,20 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
:loop_read
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
set "RetString="
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
goto :napcat_boot
)
echo QQ installation was not found in the registry.
pause
exit /b 1
:napcat_boot
for %%a in ("%RetString%") do (
@@ -21,12 +26,10 @@ set "QQPath=%pathWithoutUninstall%QQ.exe"
if not exist "%QQpath%" (
echo provided QQ path is invalid
pause
exit /b
exit /b 1
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
set "napcat_exit_code=%ERRORLEVEL%"
pause
exit /b %napcat_exit_code%
@@ -1,15 +1,20 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
:loop_read
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
set "RetString="
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
goto :napcat_boot
)
echo QQ installation was not found in the registry.
pause
exit /b 1
:napcat_boot
for %%a in ("%RetString%") do (
@@ -21,14 +26,13 @@ set "QQPath=%pathWithoutUninstall%QQ.exe"
if not exist "%QQpath%" (
echo provided QQ path is invalid
pause
exit /b
exit /b 1
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
set "napcat_exit_code=%ERRORLEVEL%"
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
REM Example: "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" -q 123456
pause
exit /b %napcat_exit_code%
+19 -17
View File
@@ -1,24 +1,28 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
echo Administrator mode detected.
) else (
echo Please run this script in administrator mode.
powershell -Command "Start-Process 'cmd.exe' -ArgumentList '/c cd /d \"%cd%\" && \"%~f0\" %*' -Verb runAs"
exit
)
if not errorlevel 1 goto :napcat_admin
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0launcher-elevate.ps1" powershell.exe "%~f0" %*
exit /b %ERRORLEVEL%
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
:loop_read
:napcat_admin
echo Administrator mode detected.
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
set "RetString="
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
goto :napcat_boot
)
echo QQ installation was not found in the registry.
pause
exit /b 1
:napcat_boot
for %%a in ("%RetString%") do (
@@ -30,12 +34,10 @@ set "QQPath=%pathWithoutUninstall%QQ.exe"
if not exist "%QQPath%" (
echo provided QQ path is invalid
pause
exit /b
exit /b 1
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
exit /b %ERRORLEVEL%
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
REM Example: "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" -q 123456
+19 -17
View File
@@ -1,24 +1,28 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
echo Administrator mode detected.
) else (
echo Please run this script in administrator mode.
powershell -Command "Start-Process 'wt.exe' -ArgumentList 'cmd /c cd /d \"%cd%\" && \"%~f0\" %*' -Verb runAs"
exit
)
if not errorlevel 1 goto :napcat_admin
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0launcher-elevate.ps1" wt.exe "%~f0" %*
exit /b %ERRORLEVEL%
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
:loop_read
:napcat_admin
echo Administrator mode detected.
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
set "RetString="
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
goto :napcat_boot
)
echo QQ installation was not found in the registry.
pause
exit /b 1
:napcat_boot
for %%a in ("%RetString%") do (
@@ -30,10 +34,8 @@ set "QQPath=%pathWithoutUninstall%QQ.exe"
if not exist "%QQPath%" (
echo provided QQ path is invalid
pause
exit /b
exit /b 1
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
exit /b %ERRORLEVEL%
+3 -2
View File
@@ -1,5 +1,6 @@
const path = require('path');
const CurrentPath = path.dirname(__filename);
const { pathToFileURL } = require('url');
const mainPath = process.env.NAPCAT_MAIN_PATH || path.join(__dirname, 'napcat.mjs');
(async () => {
await import('file://' + path.join(CurrentPath, './napcat/napcat.mjs'));
await import(pathToFileURL(mainPath).href);
})();
+6 -1
View File
@@ -41,6 +41,7 @@ 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';
import { migrateLegacyGlobalPath } from './global-migrate';
import { connectToNamedPipe } from './pipe';
// NapCat Shell App ES 入口文件
@@ -64,7 +65,10 @@ function getDataPaths (wrapper: WrapperNodeApi): [string, string] {
dataPath = path.resolve(os.homedir(), './.config/QQ');
fs.mkdirSync(dataPath, { recursive: true });
}
const dataPathGlobal = path.resolve(dataPath, './nt_qq/global');
// Linux: global 直接位于数据目录下; Windows: global 位于 nt_qq 子目录下
const dataPathGlobal = os.platform() === 'linux'
? path.resolve(dataPath, './global')
: path.resolve(dataPath, './nt_qq/global');
return [dataPath, dataPathGlobal];
}
@@ -714,6 +718,7 @@ export async function NCoreInitShell () {
}
}
const [dataPath, dataPathGlobal] = getDataPaths(wrapper);
migrateLegacyGlobalPath(dataPath, dataPathGlobal, logger);
WebUiDataRuntime.setQQDataPath(dataPath);
const systemPlatform = getPlatformType();
+53
View File
@@ -0,0 +1,53 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
export interface MigrationLogger {
log: (message: string) => void;
logError: (message: string, error?: unknown) => void;
}
/**
* 旧版 NapCat 在 Linux 上把 global 目录放在 `<dataPath>/nt_qq/global`,
* 新版对齐 QQ 官方 Linux 客户端改为 `<dataPath>/global`。
*
* 仅当新目录不存在、且旧目录存在时搬运一次:
* - 服务器仅跑 NapCat 的用户通常只有 `nt_qq/`, 迁移后即可复用原有登录凭据,
* 避免重新扫码以及出现两套 login.db / 两个 GUID;
* - 若 `QQ/global` 已存在(例如用户同时装了自用 QQ),则保持原样, 不覆盖也不改动,
* 避免覆盖两份不同的设备身份, 同时天然保证重复启动时不会二次迁移;
* - 两者都不存在时什么都不做, QQ 会在新路径自行重建。
*
* @param platform 目标平台, 便于测试注入
* @returns 是否执行了迁移
*/
export function migrateLegacyGlobalPath (
dataPath: string,
dataPathGlobal: string,
logger: MigrationLogger,
platform: NodeJS.Platform = os.platform()
): boolean {
if (platform !== 'linux') return false;
const legacyGlobalPath = path.resolve(dataPath, './nt_qq/global');
if (legacyGlobalPath === dataPathGlobal) return false;
// 新目录已存在: 不覆盖、不合并
if (fs.existsSync(dataPathGlobal)) return false;
// 没有旧数据: QQ 启动时会自行重建
if (!fs.existsSync(legacyGlobalPath)) return false;
try {
fs.mkdirSync(path.dirname(dataPathGlobal), { recursive: true });
try {
fs.renameSync(legacyGlobalPath, dataPathGlobal);
} catch {
// 跨文件系统时 rename 会失败, 退化为递归复制后删除旧目录
fs.cpSync(legacyGlobalPath, dataPathGlobal, { recursive: true });
fs.rmSync(legacyGlobalPath, { recursive: true, force: true });
}
logger.log(`[NapCat] [Core] 已迁移 Linux global 目录: ${legacyGlobalPath} -> ${dataPathGlobal}`);
return true;
} catch (e) {
logger.logError('[NapCat] [Core] 迁移 Linux global 目录失败, 将在新路径重建设备信息:', e);
return false;
}
}
@@ -0,0 +1,38 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { encodeSilk } from '@/napcat-core/helper/audio';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import type { LogWrapper } from '@/napcat-core/helper/log';
vi.mock('@/napcat-core/helper/ffmpeg/ffmpeg', () => ({
FFmpegService: { isSilk: vi.fn(), convertToNTSilkTct: vi.fn(), getDuration: vi.fn() },
}));
const logger = { log: vi.fn() } as unknown as LogWrapper;
beforeEach(() => vi.resetAllMocks());
describe('SILK encoding', () => {
it('reads duration from the encoded output including the final packet', async () => {
vi.mocked(FFmpegService.isSilk).mockResolvedValue(false);
vi.mocked(FFmpegService.getDuration).mockResolvedValue(0.02);
const result = await encodeSilk('/short.wav', '/temp', logger);
expect(result.converted).toBe(true);
expect(FFmpegService.convertToNTSilkTct).toHaveBeenCalledWith('/short.wav', result.path);
expect(FFmpegService.getDuration).toHaveBeenCalledWith(result.path);
expect(result.duration).toBe(0.02);
});
it('propagates a corrupt SILK error without estimating its duration', async () => {
vi.mocked(FFmpegService.isSilk).mockResolvedValue(true);
vi.mocked(FFmpegService.getDuration).mockRejectedValue(new Error('corrupt SILK packet'));
await expect(encodeSilk('/corrupt.silk', '/temp', logger)).rejects.toThrow('corrupt SILK packet');
expect(FFmpegService.convertToNTSilkTct).not.toHaveBeenCalled();
});
it('propagates conversion errors to the caller', async () => {
vi.mocked(FFmpegService.isSilk).mockResolvedValue(false);
vi.mocked(FFmpegService.convertToNTSilkTct).mockRejectedValue(new Error('encoder unavailable'));
await expect(encodeSilk('/audio.wav', '/temp', logger)).rejects.toThrow('encoder unavailable');
expect(FFmpegService.getDuration).not.toHaveBeenCalled();
});
});
+180
View File
@@ -0,0 +1,180 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
import { FFmpegAdapterFactory } from '@/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory';
import { FFmpegAddonAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter';
import { FFmpegExecAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter';
import { FFmpegService, getFFmpegPath } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import type { LogWrapper } from '@/napcat-core/helper/log';
const mocks = vi.hoisted(() => ({
execute: vi.fn(),
dlopen: vi.fn(),
exists: vi.fn(),
}));
vi.mock('fs', async (importOriginal) => {
const original = await importOriginal<typeof import('fs')>();
return { ...original, existsSync: mocks.exists };
});
vi.mock('child_process', async (importOriginal) => {
const original = await importOriginal<typeof import('child_process')>();
return {
...original,
execFile: Object.assign(vi.fn(), {
[Symbol.for('nodejs.util.promisify.custom')]: mocks.execute,
}),
};
});
vi.mock('node:process', async (importOriginal) => {
const original = await importOriginal<typeof import('node:process')>();
return { ...original, dlopen: mocks.dlopen };
});
const logger = { log: vi.fn(), logError: vi.fn() } as unknown as LogWrapper;
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
beforeEach(() => {
FFmpegAdapterFactory.reset();
vi.stubEnv('FFMPEG_PATH', '');
vi.stubEnv('FFPROBE_PATH', '');
mocks.execute.mockReset().mockResolvedValue({ stdout: '', stderr: '' });
mocks.dlopen.mockReset();
mocks.exists.mockReset().mockReturnValue(false);
});
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
Object.defineProperty(process, 'platform', platformDescriptor);
Object.defineProperty(process, 'arch', archDescriptor);
});
describe('FFmpeg platform paths', () => {
it.each(['arm64', 'x64'])('finds Homebrew for macOS %s outside GUI PATH', (arch) => {
Object.defineProperty(process, 'platform', { value: 'darwin' });
Object.defineProperty(process, 'arch', { value: arch });
vi.stubEnv('PATH', '/usr/bin:/bin');
const prefix = arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin';
mocks.exists.mockImplementation(candidate => String(candidate).startsWith(path.join(prefix)));
expect(getFFmpegPath('ffmpeg')).toBe(path.join(prefix, 'ffmpeg'));
expect(getFFmpegPath('ffprobe')).toBe(path.join(prefix, 'ffprobe'));
});
it('preserves explicit paths containing spaces without searching alternatives', () => {
vi.stubEnv('FFMPEG_PATH', '/private/My Tools/ffmpeg');
vi.stubEnv('FFPROBE_PATH', '/private/My Tools/ffprobe');
const exists = mocks.exists.mockReturnValue(true);
expect(getFFmpegPath('ffmpeg', '/app')).toBe('/private/My Tools/ffmpeg');
expect(getFFmpegPath('ffprobe', '/app')).toBe('/private/My Tools/ffprobe');
expect(exists).not.toHaveBeenCalled();
});
it('uses packaged Windows executables before PATH', () => {
Object.defineProperty(process, 'platform', { value: 'win32' });
mocks.exists.mockReturnValue(true);
expect(getFFmpegPath('ffmpeg', '/app')).toBe(path.join('/app', 'ffmpeg', 'ffmpeg.exe'));
});
});
describe('FFmpeg adapter selection', () => {
it.each(['arm64', 'x64'])('loads the packaged macOS %s addon', async (arch) => {
Object.defineProperty(process, 'platform', { value: 'darwin' });
Object.defineProperty(process, 'arch', { value: arch });
mocks.exists.mockReturnValue(true);
mocks.dlopen.mockImplementation(module => { module.exports = {}; });
const adapter = await FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app');
expect(adapter.name).toBe('FFmpegAddon');
expect(mocks.dlopen).toHaveBeenCalledWith(expect.anything(), path.join('/app', 'native/ffmpeg', 'ffmpegAddon.darwin.' + arch + '.node'));
expect(mocks.execute).not.toHaveBeenCalled();
});
it('does not hide a broken packaged addon behind another adapter', async () => {
vi.spyOn(console, 'log').mockImplementation(() => {});
mocks.exists.mockReturnValue(true);
mocks.dlopen.mockImplementation(() => { throw new Error('wrong architecture'); });
await expect(FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app')).rejects.toThrow('Native Addon');
expect(mocks.execute).not.toHaveBeenCalled();
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull();
});
it('honors an explicit command line configuration', async () => {
vi.stubEnv('FFMPEG_PATH', '/tools/ffmpeg');
mocks.exists.mockReturnValue(true);
const adapter = await FFmpegAdapterFactory.getAdapter(logger, '/tools/ffmpeg', '/tools/ffprobe', '/app');
expect(adapter.name).toBe('FFmpegExec');
expect(mocks.dlopen).not.toHaveBeenCalled();
expect(mocks.execute).toHaveBeenCalledWith('/tools/ffmpeg', ['-version'], expect.objectContaining({ timeout: 10000 }));
expect(mocks.execute).toHaveBeenCalledWith('/tools/ffprobe', ['-version'], expect.objectContaining({ timeout: 10000 }));
});
it('rejects a missing ffprobe and allows a corrected configuration', async () => {
mocks.exists.mockReturnValue(false);
mocks.execute.mockImplementation(async command => {
if (command === 'ffprobe') throw new Error('ENOENT');
return { stdout: '', stderr: '' };
});
await expect(FFmpegAdapterFactory.getAdapter(logger)).rejects.toThrow('ffprobe');
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull();
mocks.execute.mockResolvedValue({ stdout: '', stderr: '' });
expect((await FFmpegAdapterFactory.getAdapter(logger)).name).toBe('FFmpegExec');
});
it('validates replacement paths before changing the active adapter', async () => {
const adapter = await FFmpegAdapterFactory.getAdapter(logger);
mocks.execute.mockRejectedValue(new Error('EACCES'));
await expect(FFmpegAdapterFactory.updateFFmpegPath(logger, '/bad/ffmpeg', '/bad/ffprobe')).rejects.toThrow('/bad/ffprobe');
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBe(adapter);
});
});
describe('FFmpeg media operations', () => {
it('transcodes encoded audio without treating its bytes as raw PCM', async () => {
mocks.exists.mockReturnValue(true);
await new FFmpegExecAdapter().convertFile('/record.wav', '/record.mp3', 'mp3');
expect(mocks.execute).toHaveBeenCalledWith('ffmpeg', [
'-i', '/record.wav', '-vn', '-ac', '1', '-y', '/record.mp3',
], expect.objectContaining({ timeout: 120000, windowsHide: true }));
});
it('reports a corrupt video instead of inventing dimensions and duration', async () => {
mocks.execute.mockRejectedValue(new Error('invalid video'));
await expect(new FFmpegExecAdapter().getVideoInfo('/video.mp4')).rejects.toThrow('invalid video');
});
it('reads actual video metadata and JPEG bytes without a shared temporary file', async () => {
const thumbnail = Buffer.from([255, 216, 255, 217]);
mocks.execute.mockImplementation(async command => command === 'ffprobe'
? { stdout: JSON.stringify({ streams: [{ width: 360, height: 480 }], format: { duration: '0.5', format_name: 'mov,mp4' } }) }
: { stdout: thumbnail });
await expect(new FFmpegExecAdapter().getVideoInfo('/clip with spaces.mp4')).resolves.toEqual({
width: 360, height: 480, duration: 0.5, format: 'mov,mp4', thumbnail,
});
});
it('uses the native PNG encoder for legacy videos on macOS', async () => {
Object.defineProperty(process, 'platform', { value: 'darwin' });
const adapter = new FFmpegAddonAdapter('/app');
const extract = vi.spyOn(adapter, 'extractThumbnail').mockResolvedValue();
vi.spyOn(FFmpegAdapterFactory, 'getAdapter').mockResolvedValue(adapter);
await FFmpegService.init('/app', logger);
await FFmpegService.extractLegacyVideoThumbnail('/video.mp4', '/thumbnail.png');
expect(extract).toHaveBeenCalledWith('/video.mp4', '/thumbnail.png', 'png');
expect(mocks.execute).not.toHaveBeenCalled();
});
it('keeps startup available and reports unavailable media until paths are corrected', async () => {
vi.resetModules();
const { FFmpegService: service } = await import('@/napcat-core/helper/ffmpeg/ffmpeg');
mocks.exists.mockReturnValue(false);
mocks.execute.mockRejectedValue(new Error('ENOENT'));
await expect(service.init('/app', logger)).resolves.toBeUndefined();
await expect(service.getDuration('/audio.wav')).rejects.toThrow('ffprobe');
expect(logger.logError).toHaveBeenCalled();
mocks.execute.mockResolvedValue({ stdout: '1.5', stderr: '' });
await service.setFfmpegPath('/installed tools', logger);
await expect(service.getDuration('/audio.wav')).resolves.toBe(1.5);
});
});
+130
View File
@@ -0,0 +1,130 @@
import { gunzipSync, inflateSync } from 'node:zlib';
import { describe, expect, it, vi } from 'vitest';
import { NapProtoMsg } from 'napcat-protobuf';
import { ChatType, ElementType, FaceType } from '@/napcat-core/types/msg';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
import { PacketMsgFaceElement } from '@/napcat-core/packet/message/element';
import { LongMsgResult, QBigFaceExtra, SendLongMsgReq } from '@/napcat-core/packet/transformer/proto';
import UploadForwardMsgV2 from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
import { OneBotMsgApi } from '@/napcat-onebot/api/msg';
import { OB11MessageData, OB11MessageDataType } from '@/napcat-onebot/types/message';
// Keep the real message types without starting the adapter's WebUI/network modules.
vi.mock('@/napcat-onebot/index', async () => await import('@/napcat-onebot/types'));
vi.mock('napcat-core/packet/transformer/proto', async () => await import('@/napcat-core/packet/transformer/proto'));
const text = (value: string): OB11MessageData => ({
type: OB11MessageDataType.text,
data: { text: value },
});
const face = (id: string): OB11MessageData => ({
type: OB11MessageDataType.face,
data: { id },
});
async function buildForwardElements (content: OB11MessageData[], groupUin = 0) {
const api = new OneBotMsgApi(
{} as ConstructorParameters<typeof OneBotMsgApi>[0],
{} as ConstructorParameters<typeof OneBotMsgApi>[1]
);
const { sendElements } = await api.createSendElements(content, {
chatType: groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
peerUid: groupUin ? String(groupUin) : 'u_friend',
guildId: '',
});
const msg = new PacketMsgConverter().rawMsgWithSendMsgToPacketMsg({
senderUin: 123456,
senderName: '测试',
groupId: groupUin,
time: 1700000000,
msg: sendElements,
});
const packet = UploadForwardMsgV2.build('u_self', [{ actionCommand: 'MultiMsg', actionMsg: [msg] }], groupUin);
const request = new NapProtoMsg(SendLongMsgReq).decode(packet.data);
const payload = new NapProtoMsg(LongMsgResult).decode(gunzipSync(request.info.payload!));
return payload.action[0]!.actionData.msgBody[0]!.body!.richText!.elems;
}
describe.each([
{ name: 'private', groupUin: 0 },
{ name: 'group', groupUin: 654321 },
])('$name forward face encoding', ({ groupUin }) => {
it('keeps the text immediately after the animated face in issue #2097', async () => {
const elems = await buildForwardElements([text('1234'), face('317'), text('5678'), text('在')], groupUin);
expect(elems).toMatchObject([
{ text: { str: '1234' } },
{ commonElem: { serviceType: 37 } },
{ text: { str: '/菜汪' } },
{ text: { str: '5678' } },
{ text: { str: '在' } },
]);
expect(new NapProtoMsg(QBigFaceExtra).decode(elems[1]!.commonElem!.pbElem).faceId).toBe(317);
});
it('gives each consecutive animated face its own compatibility text', async () => {
const elems = await buildForwardElements([face('317'), face('318'), text('after')], groupUin);
expect(elems).toMatchObject([
{ commonElem: { serviceType: 37 } },
{ text: { str: '/菜汪' } },
{ commonElem: { serviceType: 37 } },
{ text: { str: '/崇拜' } },
{ text: { str: 'after' } },
]);
});
it('includes compatibility text when the animated face ends the node', async () => {
const elems = await buildForwardElements([face('317')], groupUin);
expect(elems).toMatchObject([
{ commonElem: { serviceType: 37 } },
{ text: { str: '/菜汪' } },
]);
});
it('keeps a non-text segment immediately after an animated face', async () => {
const json = JSON.stringify({ app: 'test', prompt: 'card' });
const elems = await buildForwardElements([
face('317'),
{ type: OB11MessageDataType.json, data: { data: json } },
text('after'),
], groupUin);
expect(elems).toMatchObject([
{ commonElem: { serviceType: 37 } },
{ text: { str: '/菜汪' } },
{ lightAppElem: {} },
{ text: { str: 'after' } },
]);
expect(inflateSync(elems[2]!.lightAppElem!.data.subarray(1)).toString()).toBe(json);
});
it('does not insert compatibility text after legacy or small faces', async () => {
const elems = await buildForwardElements([face('14'), text('legacy'), face('264'), text('small')], groupUin);
expect(elems).toMatchObject([
{ face: { index: 14 } },
{ text: { str: 'legacy' } },
{ commonElem: { serviceType: 33 } },
{ text: { str: 'small' } },
]);
});
});
it.each([undefined, ''])('provides non-empty compatibility text when faceText is %s', (faceText) => {
const face = new PacketMsgFaceElement({
elementType: ElementType.FACE,
elementId: '',
faceElement: {
faceIndex: 317,
faceType: FaceType.AniSticke,
faceText,
},
});
expect(face.buildElement()).toMatchObject([
{ commonElem: { serviceType: 37 } },
{ text: { str: '[表情]' } },
]);
});
@@ -0,0 +1,76 @@
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { migrateLegacyGlobalPath } from '@/napcat-shell/global-migrate';
const noopLogger = { log: () => {}, logError: () => {} };
function withTempDir (fn: (dir: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'napcat-migrate-test-'));
try {
fn(dir);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
describe('Linux legacy global migration', () => {
it('moves nt_qq/global to global when the new path is absent', () => {
withTempDir((dir) => {
const legacy = path.join(dir, 'nt_qq', 'global');
fs.mkdirSync(path.join(legacy, 'nt_data', 'msf'), { recursive: true });
fs.writeFileSync(path.join(legacy, 'nt_data', 'msf', 'machine-info'), Buffer.from('legacy-creds'));
const target = path.join(dir, 'global');
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(true);
expect(fs.existsSync(legacy)).toBe(false);
expect(fs.readFileSync(path.join(target, 'nt_data', 'msf', 'machine-info')).toString())
.toBe('legacy-creds');
});
});
it('does nothing when the new global path already exists (keeps both intact)', () => {
withTempDir((dir) => {
const legacy = path.join(dir, 'nt_qq', 'global');
const target = path.join(dir, 'global');
fs.mkdirSync(legacy, { recursive: true });
fs.mkdirSync(target, { recursive: true });
fs.writeFileSync(path.join(legacy, 'marker'), Buffer.from('legacy'));
fs.writeFileSync(path.join(target, 'marker'), Buffer.from('new'));
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(false);
expect(fs.readFileSync(path.join(legacy, 'marker')).toString()).toBe('legacy');
expect(fs.readFileSync(path.join(target, 'marker')).toString()).toBe('new');
});
});
it('does nothing when neither path exists', () => {
withTempDir((dir) => {
expect(migrateLegacyGlobalPath(dir, path.join(dir, 'global'), noopLogger, 'linux')).toBe(false);
expect(fs.existsSync(path.join(dir, 'global'))).toBe(false);
});
});
it('is idempotent across repeated startups', () => {
withTempDir((dir) => {
const legacy = path.join(dir, 'nt_qq', 'global');
fs.mkdirSync(legacy, { recursive: true });
fs.writeFileSync(path.join(legacy, 'login.db'), Buffer.from('creds'));
const target = path.join(dir, 'global');
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(true);
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(false);
expect(fs.readFileSync(path.join(target, 'login.db')).toString()).toBe('creds');
});
});
it('never touches non-Linux platforms', () => {
withTempDir((dir) => {
const legacy = path.join(dir, 'nt_qq', 'global');
fs.mkdirSync(legacy, { recursive: true });
expect(migrateLegacyGlobalPath(dir, path.join(dir, 'global'), noopLogger, 'win32')).toBe(false);
expect(fs.existsSync(legacy)).toBe(true);
});
});
});
@@ -0,0 +1,126 @@
// StreamBasic must be evaluated before OneBotAction because they import each other.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, test, vi } from 'vitest';
import { NTQQWebApi } from '../napcat-core/apis/webapi';
import { DoGroupAlbumComment } from '../napcat-onebot/action/extends/DoGroupAlbumComment';
const GROUP_ID = '123456';
const ALBUM_ID = 'album_id_1';
const BATCH_ID = '2147483658';
const LLOC = 'media_id_1';
const UIN = '654321';
const CONTENT = '很有意思';
const BASE_PAYLOAD = { group_id: GROUP_ID, album_id: ALBUM_ID, content: CONTENT };
function createAction () {
const nativeResult = { result: 0 };
const doQunComment = vi.fn().mockResolvedValue(nativeResult);
const context = {
session: { getAlbumService: () => ({ doQunComment }) },
logger: { logError: vi.fn() },
};
const webApi = new NTQQWebApi(context as never, { selfInfo: { uin: UIN } } as never);
const action = new DoGroupAlbumComment(undefined as never, {
context,
apis: { WebApi: webApi },
} as never);
return { action, webApi, doQunComment, nativeResult };
}
describe('do_group_album_comment', () => {
test.each([
{ name: '原有单图评论', target: { lloc: LLOC }, batchId: '', mediaItems: [{ image: { lloc: LLOC } }] },
{ name: '仅指定上传批次', target: { batch_id: BATCH_ID }, batchId: BATCH_ID, mediaItems: [] },
{ name: '批次评论允许空 lloc', target: { batch_id: BATCH_ID, lloc: '' }, batchId: BATCH_ID, mediaItems: [] },
{ name: '同时提供批次和图片时评论单图', target: { batch_id: BATCH_ID, lloc: LLOC }, batchId: BATCH_ID, mediaItems: [{ image: { lloc: LLOC } }] },
])('$name', async ({ target, batchId, mediaItems }) => {
const { action, doQunComment, nativeResult } = createAction();
const response = await action.handle({ ...BASE_PAYLOAD, ...target }, 'test', {} as never);
expect(response.status).toBe('ok');
expect(response.data).toBe(nativeResult);
expect(doQunComment).toHaveBeenCalledExactlyOnceWith(
expect.any(Number),
{ map_info: [], map_bytes_info: [], map_user_account: [] },
GROUP_ID,
2,
{
cell_common: { time: '' },
cell_user_info: { user: { uin: UIN } },
cell_media: { album_id: ALBUM_ID, batch_id: batchId, media_items: mediaItems },
},
expect.objectContaining({
client_key: expect.any(Number),
content: [{ type: 0, content: CONTENT, who: 0, uid: '', name: '', url: '' }],
user: { uin: UIN },
})
);
});
test.each([
{},
{ lloc: '' },
{ batch_id: '' },
{ lloc: '', batch_id: '' },
])('拒绝未指定有效评论目标的请求:%j', async (target) => {
const { action, doQunComment } = createAction();
const response = await action.handle({ ...BASE_PAYLOAD, ...target }, 'test', {} as never);
expect(response).toMatchObject({ status: 'failed', retcode: 400 });
expect(response.message).toContain('lloc');
expect(response.message).toContain('batch_id');
expect(doQunComment).not.toHaveBeenCalled();
});
test('WebSocket 请求同样校验评论目标并保留 echo', async () => {
const { action, doQunComment } = createAction();
const response = await action.websocketHandle(BASE_PAYLOAD, 'echo', 'test', {} as never);
expect(response).toMatchObject({ status: 'failed', retcode: 1400, echo: 'echo' });
expect(doQunComment).not.toHaveBeenCalled();
});
test('批次评论仍要求提供评论内容', async () => {
const { action, doQunComment } = createAction();
const response = await action.handle({ group_id: GROUP_ID, album_id: ALBUM_ID, batch_id: BATCH_ID } as never, 'test', {} as never);
expect(response).toMatchObject({ status: 'failed', retcode: 400 });
expect(doQunComment).not.toHaveBeenCalled();
});
test('底层评论失败时返回错误', async () => {
const { action, doQunComment } = createAction();
doQunComment.mockRejectedValue(new Error('comment failed'));
const response = await action.handle({ ...BASE_PAYLOAD, batch_id: BATCH_ID }, 'test', {} as never);
expect(response).toMatchObject({ status: 'failed', message: 'comment failed' });
expect(doQunComment).toHaveBeenCalledOnce();
});
});
describe('doAlbumMediaPlainCommentByNTQQ', () => {
test('保留原有四参数调用的单图评论行为', async () => {
const { webApi, doQunComment, nativeResult } = createAction();
await expect(webApi.doAlbumMediaPlainCommentByNTQQ(GROUP_ID, ALBUM_ID, LLOC, CONTENT)).resolves.toBe(nativeResult);
expect(doQunComment.mock.calls[0]?.[4].cell_media).toEqual({
album_id: ALBUM_ID,
batch_id: '',
media_items: [{ image: { lloc: LLOC } }],
});
});
test('直接调用核心 API 时也拒绝空评论目标', async () => {
const { webApi, doQunComment } = createAction();
await expect(webApi.doAlbumMediaPlainCommentByNTQQ(GROUP_ID, ALBUM_ID, undefined, CONTENT))
.rejects.toThrow('lloc 或 batch_id');
expect(doQunComment).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,85 @@
// StreamBasic must be evaluated before OneBotAction because of their circular import.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, it, vi } from 'vitest';
import { spawnSync } from 'node:child_process';
import { dirname, resolve } from 'node:path';
import { NTQQWebApi } from '@/napcat-core/apis/webapi';
import { createAlbumCommentRequest, createAlbumMediaFeed } from '@/napcat-core/data/album';
import type { NodeIKernelAlbumService } from '@/napcat-core/services/NodeIKernelAlbumService';
import { DoGroupAlbumComment } from '@/napcat-onebot/action/extends/DoGroupAlbumComment';
describe('do_group_album_comment native arguments', () => {
it('submits the documented payload with an empty like object required by QQNT', async () => {
const result = { result: 0, comment: { id: 'comment-id' } };
const doQunComment = vi.fn<NodeIKernelAlbumService['doQunComment']>().mockResolvedValue(result);
const core = { selfInfo: { uin: '10001' }, apis: {} as { WebApi: NTQQWebApi } };
core.apis.WebApi = new NTQQWebApi({
session: { getAlbumService: () => ({ doQunComment }) },
} as never, core as never);
const action = new DoGroupAlbumComment(undefined as never, core as never);
await expect(action._handle({
group_id: '12345',
album_id: 'album-id',
lloc: 'photo-id',
content: '测试评论',
})).resolves.toBe(result);
expect(doQunComment).toHaveBeenCalledExactlyOnceWith(
expect.any(Number),
{ map_info: [], map_bytes_info: [], map_user_account: [] },
'12345',
2,
expect.objectContaining({
cell_media: expect.objectContaining({
album_id: 'album-id',
media_items: [{ image: { lloc: 'photo-id' } }],
}),
}),
expect.objectContaining({
client_key: expect.any(Number),
content: [expect.objectContaining({ type: 0, content: '测试评论' })],
user: { uin: '10001' },
like: { id: '', count: 0, status: 0 },
})
);
});
// Optional native regression: point this at a QQ installation's wrapper.node.
// An unbound service parses arguments but cannot log in or submit a comment.
it.skipIf(!process.env['NAPCAT_TEST_QQ_WRAPPER'])('passes native argument conversion (issue #1979)', () => {
const wrapperPath = resolve(process.env['NAPCAT_TEST_QQ_WRAPPER']!);
const args = [
1234,
{ map_info: [], map_bytes_info: [], map_user_account: [] },
'12345',
2,
createAlbumMediaFeed('10001', 'album-id', 'photo-id'),
createAlbumCommentRequest('10001', '测试评论', 1234567890),
];
const probe = spawnSync(process.execPath, ['-e', `
const assert = require('node:assert/strict');
const fs = require('node:fs');
const { wrapperPath, args } = JSON.parse(fs.readFileSync(0, 'utf8'));
const native = { exports: {} };
process.dlopen(native, wrapperPath);
const service = new native.exports.NodeIKernelAlbumService();
const legacyArgs = args.slice();
legacyArgs[5] = { ...args[5] };
delete legacyArgs[5].like;
assert.throws(() => service.doQunComment(...legacyArgs), /Cannot convert undefined or null to object/);
// Reaching the unbound-service check proves all six arguments were converted.
assert.throws(() => service.doQunComment(...args), /implementation of IKernelAlbumService is not valid/);
process.exit(0);
`], {
cwd: dirname(wrapperPath),
input: JSON.stringify({ wrapperPath, args }),
encoding: 'utf8',
timeout: 10000,
windowsHide: true,
});
expect(probe.error).toBeUndefined();
expect(probe.status, probe.stderr || probe.stdout).toBe(0);
});
});
@@ -0,0 +1,67 @@
// 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 { GetGroupFilesByFolder } from '../napcat-onebot/action/go-cqhttp/GetGroupFilesByFolder';
const FOLDER_ITEM = {
peerId: '123',
folderInfo: {
folderId: 'sub_folder_1',
folderName: '子目录',
createTime: 1,
createUin: '9',
creatorName: '创建者',
totalFileCount: 2,
modifyTime: 2,
modifyUin: '9',
modifyName: '修改者',
},
};
function createAction (items: unknown[]) {
const getGroupFileList = vi.fn().mockResolvedValue(items);
const action = new GetGroupFilesByFolder(
undefined as never,
{
apis: {
MsgApi: { getGroupFileList },
},
} as never
);
return { action, getGroupFileList };
}
describe('get_group_files_by_folder subfolders', () => {
test('maps folderInfo entries into folders', async () => {
const { action } = createAction([FOLDER_ITEM]);
const res = await action._handle({ group_id: '123', file_count: 50 });
expect(res.folders).toHaveLength(1);
expect(res.folders[0]).toMatchObject({
group_id: 123,
folder_id: 'sub_folder_1',
folder_name: '子目录',
total_file_count: 2,
});
expect(res.files).toHaveLength(0);
});
test('returns empty arrays when the folder holds nothing', async () => {
const { action } = createAction([]);
const res = await action._handle({ group_id: '123', file_count: 50 });
expect(res.files).toHaveLength(0);
expect(res.folders).toHaveLength(0);
});
test('passes the requested folder id through to the core API', async () => {
const { action, getGroupFileList } = createAction([]);
await action._handle({ group_id: '123', file_count: 50, folder_id: 'parent_1' });
expect(getGroupFileList).toHaveBeenCalledWith('123', expect.objectContaining({ folderId: 'parent_1' }));
});
});
+89
View File
@@ -0,0 +1,89 @@
import { afterEach, describe, expect, test } from 'vitest';
import { copyFileSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { execFileSync, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
const fixtureRoots: string[] = [];
function createFixture () {
const fixtureRoot = mkdtempSync(path.join(tmpdir(), 'napcat-loader-'));
fixtureRoots.push(fixtureRoot);
const installDir = path.join(fixtureRoot, '中文 space # percent%');
mkdirSync(installDir);
return { fixtureRoot, installDir };
}
afterEach(() => {
for (const fixtureRoot of fixtureRoots.splice(0)) {
rmSync(fixtureRoot, { recursive: true, force: true });
}
});
describe('loader paths', () => {
test('Shell loads the flat package from an unrelated working directory', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(installDir, 'loadNapCat.cjs');
copyFileSync(path.join(packageRoot, 'napcat-shell-loader/loadNapCat.js'), loaderPath);
writeFileSync(path.join(installDir, 'napcat.mjs'), 'console.log("SHELL_LOADED");');
const environment = { ...process.env };
delete environment['NAPCAT_MAIN_PATH'];
const output = execFileSync(process.execPath, [loaderPath], { cwd: fixtureRoot, env: environment, encoding: 'utf8' });
expect(output).toContain('SHELL_LOADED');
});
test('Shell uses the actual entry path when the loader is redirected into QQ', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(fixtureRoot, 'loadNapCat.cjs');
const entryPath = path.join(installDir, 'napcat.mjs');
copyFileSync(path.join(packageRoot, 'napcat-shell-loader/loadNapCat.js'), loaderPath);
writeFileSync(entryPath, 'console.log("REDIRECTED_SHELL_LOADED");');
const output = execFileSync(process.execPath, [loaderPath], {
cwd: fixtureRoot,
env: { ...process.env, NAPCAT_MAIN_PATH: entryPath },
encoding: 'utf8',
});
expect(output).toContain('REDIRECTED_SHELL_LOADED');
});
test('Framework native loader preserves URL-sensitive path characters', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(installDir, 'nativeLoader.cjs');
copyFileSync(path.join(packageRoot, 'napcat-framework/nativeLoader.cjs'), loaderPath);
writeFileSync(path.join(installDir, 'napcat.mjs'), 'export async function NCoreInitFramework () { console.log("FRAMEWORK_LOADED"); }');
const output = execFileSync(process.execPath, ['-e', 'require(process.argv[1]).initializeNapCat({}, {}, () => {});', loaderPath], {
cwd: fixtureRoot,
encoding: 'utf8',
});
expect(output).toContain('FRAMEWORK_LOADED');
expect(output).not.toContain('[Error]');
});
test('Framework dlopen loader preserves URL-sensitive path characters', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(installDir, 'napcat.cjs');
copyFileSync(path.join(packageRoot, 'napcat-framework/napcat.cjs'), loaderPath);
writeFileSync(path.join(installDir, 'napcat.mjs'), 'export async function NCoreInitFramework () { console.log("DLOPEN_FRAMEWORK_LOADED"); } export function getWebUiUrl () { return ""; }');
const script = 'process.dlopen = (module) => { module.exports = { NodeIKernelLoginService: { get: () => ({}) }, NodeIQQNTWrapperSession: { create: () => ({}) } }; }; require(process.argv[1]); process.dlopen({ exports: {} }, "wrapper.node");';
const output = execFileSync(process.execPath, ['-e', script, loaderPath], { cwd: fixtureRoot, encoding: 'utf8' });
expect(output).toContain('DLOPEN_FRAMEWORK_LOADED');
expect(output).not.toContain('[Error]');
});
test.skipIf(process.platform !== 'win32')('Node batch uses the bundled runtime, forwards arguments and returns the exit code', () => {
const { fixtureRoot, installDir } = createFixture();
copyFileSync(process.execPath, path.join(installDir, 'node.exe'));
copyFileSync(path.join(packageRoot, 'napcat-develop/napcat.bat'), path.join(installDir, 'napcat.bat'));
writeFileSync(path.join(installDir, 'index.js'), 'console.log(JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(2) })); process.exitCode = 7;');
const result = spawnSync('cmd.exe', ['/d', '/s', '/c', `""${path.join(installDir, 'napcat.bat')}" -q 123456"`], {
cwd: fixtureRoot,
encoding: 'utf8',
windowsVerbatimArguments: true,
});
expect(result.error).toBeUndefined();
expect(result.status).toBe(7);
expect(JSON.parse(result.stdout)).toEqual({ cwd: installDir, args: ['-q', '123456'] });
});
});
+220
View File
@@ -0,0 +1,220 @@
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {
teaEncryptBlock,
teaDecryptBlock,
containerEncrypt,
containerDecrypt,
MacMachineInfoUtils,
MachineInfoUtils,
Registry20Utils,
resolveBackupPath,
} from '@/napcat-webui-backend/src/utils/guid';
// 参考实现: qq_guid_tool/macos (逆向自 macOS wrapper.node)
// 所有期望值均由该 Python 实现生成, 用于确保 TS 复刻逐字节一致。
const KEY = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex');
function prefixRng (n: number): Buffer {
return Buffer.from(Array.from({ length: n }, (_, i) => i));
}
function teaEncryptBlockG (block: Buffer, key = KEY): Buffer {
return teaEncryptBlock(block, key);
}
function teaDecryptBlockG (block: Buffer, key = KEY): Buffer {
return teaDecryptBlock(block, key);
}
describe('macOS TEA block', () => {
it('encrypts blocks identical to the python reference', () => {
expect(teaEncryptBlockG(Buffer.from('0001020304050607', 'hex')).toString('hex'))
.toBe('6328a50896bde3c8');
expect(teaEncryptBlockG(Buffer.from('ffffffffffffffff', 'hex')).toString('hex'))
.toBe('c79e81a2904419de');
expect(teaEncryptBlockG(Buffer.from('0011223344556677', 'hex')).toString('hex'))
.toBe('205f515574f0821c');
});
it('decrypts the reference ciphertext', () => {
expect(teaDecryptBlockG(Buffer.from('6328a50896bde3c8', 'hex')).toString('hex'))
.toBe('0001020304050607');
});
it('round-trips blocks', () => {
const block = Buffer.from('a1b2c3d4e5f60718', 'hex');
expect(teaDecryptBlockG(teaEncryptBlockG(block)).equals(block)).toBe(true);
});
});
describe('macOS TEA container', () => {
it('matches the reference for "hello world" with a deterministic rng', () => {
const blob = containerEncrypt(Buffer.from('hello world'), KEY, prefixRng);
expect(blob.toString('hex'))
.toBe('5e56df427ca3a4f56dfc8cbbd3438a437050558841226bb4');
expect(containerDecrypt(blob, KEY)!.toString('hex')).toBe('68656c6c6f20776f726c64');
});
it('matches the reference for an empty payload', () => {
const blob = containerEncrypt(Buffer.alloc(0), KEY, prefixRng);
expect(blob.toString('hex')).toBe('b00e46ba3e788626272ec631c28ab195');
expect(containerDecrypt(blob, KEY)!.length).toBe(0);
});
it('matches the reference for a 200 byte payload', () => {
const payload = Buffer.from(Array.from({ length: 200 }, (_, i) => i));
const blob = containerEncrypt(payload, KEY, prefixRng);
const expected = 'b00e46ba3e788626bea151d61ae65f4ee433279c69c420d5e86f2e9d9844f335' +
'fc3387a05609b7b3b294a99f8d5eb630e205a6b2d2778c01c2c860fc9b5cbcdaf07aacdece0b3a3' +
'760245fae521f96422044562bc913ce1ac90456d810a981430ed54f7cec55207b85d6b5d991b1aa0f' +
'4b033f9f8d2d86a06577c621d197a15c4c416efa3860f47b25bf71d8cfb6a08a6b3b158e1df47f950' +
'911ab355be47101f37f989b0fe0c8afc432891f761aeadc29a78eabfc8a0bbef190028f85357cbf' +
'489bb0c4a7353967dddb0254fa85f82122d4a003637bdc35';
expect(blob.toString('hex')).toBe(expected);
expect(containerDecrypt(blob, KEY)!.equals(payload)).toBe(true);
});
it('rejects a wrong key', () => {
const blob = containerEncrypt(Buffer.from('hello world'), KEY, prefixRng);
expect(containerDecrypt(blob, Buffer.alloc(16))).toBeNull();
});
});
describe('macOS machineid-info', () => {
// 真实样本: 取自 macOS 14.8.9 (x86_64 VM, IOPlatformUUID 全零),
// 源文件 ~/Library/Containers/com.tencent.qq/Data/.../global/nt_data/msf/machineid-info
const REAL_CIPHER = '062c59f4bd7972c3baeab0dd857d9482d57ecafe96b7ec4d566e416871d7e829' +
'0d117016cd94f644ea968bc641bae40d';
const REAL_PLAIN = '00000008525400c91827000000000014514d303030323120202020202020202020202020';
const REAL_KEY_UUID = '00000000-0000-0000-0000-000000000000';
it('decrypts a real QQ-generated machineid-info identically to the python reference', () => {
const key = MacMachineInfoUtils.keyFromUuid(REAL_KEY_UUID);
const plain = containerDecrypt(Buffer.from(REAL_CIPHER, 'hex'), key);
expect(plain).not.toBeNull();
expect(plain!.toString('hex')).toBe(REAL_PLAIN);
const parsed = MacMachineInfoUtils.parseMachineIdInfo(plain!);
expect(parsed.machineId.toString('hex')).toBe('525400c918270000');
expect(parsed.sn).toBe('QM00021 ');
expect(MacMachineInfoUtils.computeGuid(parsed.machineId, parsed.sn).toString('hex'))
.toBe('110cac8ab81e1b7dca6e3f48b1127d92');
});
it('re-encrypts the real payload to a byte-identical container', () => {
// 期望容器由参考 python 实现以相同 rng 生成
const key = MacMachineInfoUtils.keyFromUuid(REAL_KEY_UUID);
const plain = MacMachineInfoUtils.buildMachineIdInfo(
Buffer.from('525400c918270000', 'hex'), 'QM00021 ');
expect(plain.toString('hex')).toBe(REAL_PLAIN);
const blob = containerEncrypt(plain, key, prefixRng);
expect(blob.toString('hex'))
.toBe('b73dfc91350349448b9ca9a255de7bffd75a548719ab4fa6311a439386fed1c29fbf7a40d0b77b1c7699d27d11545ca7');
});
it('builds and parses fields like the reference', () => {
const plain = MacMachineInfoUtils.buildMachineIdInfo(
Buffer.from('aabbccddeeff0011', 'hex'), 'C02TEST');
expect(plain.toString('hex')).toBe('00000008aabbccddeeff00110000000743303254455354');
const parsed = MacMachineInfoUtils.parseMachineIdInfo(plain);
expect(parsed.machineId.toString('hex')).toBe('aabbccddeeff0011');
expect(parsed.sn).toBe('C02TEST');
});
it('computes the reference guid', () => {
const guid = MacMachineInfoUtils.computeGuid(Buffer.from('aabbccddeeff0011', 'hex'), 'C02TEST');
expect(guid.toString('hex')).toBe('99902c9e4658f3495eac9932da8de575');
});
it('computes the MAC fallback guid', () => {
const guid = MacMachineInfoUtils.computeGuid(
Buffer.concat([Buffer.from('aabbccddeeff', 'hex'), Buffer.from([0, 0])]), 'C02TEST');
expect(guid.toString('hex')).toBe('90daceec0ac283834cd1dba777e9d54a');
});
it('derives the TEA key from IOPlatformUUID', () => {
expect(MacMachineInfoUtils.keyFromUuid('0F1E2D3C-4B5A-6978-8E9F-A0B1C2D3E4F5').toString('hex'))
.toBe('30463145324433432d344235412d3639');
});
it('round-trips a container encrypt/decrypt', () => {
const key = MacMachineInfoUtils.keyFromUuid('0F1E2D3C-4B5A-6978-8E9F-A0B1C2D3E4F5');
const plain = MacMachineInfoUtils.buildMachineIdInfo(Buffer.from('0011223344556677', 'hex'), 'SN123456');
const blob = containerEncrypt(plain, key);
const back = containerDecrypt(blob, key);
expect(back!.equals(plain)).toBe(true);
const parsed = MacMachineInfoUtils.parseMachineIdInfo(back!);
expect(parsed.machineId.toString('hex')).toBe('0011223344556677');
expect(parsed.sn).toBe('SN123456');
});
});
function withTempDir (fn: (dir: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'napcat-guid-test-'));
try {
fn(dir);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
describe('backup naming', () => {
it('does not overwrite when creating backups in quick succession', () => {
withTempDir((dir) => {
const target = path.join(dir, 'machineid-info');
fs.writeFileSync(target, Buffer.from('payload'));
const first = MacMachineInfoUtils.backup(target);
const second = MacMachineInfoUtils.backup(target);
const third = MachineInfoUtils.backup(target);
expect(new Set([first, second, third]).size).toBe(3);
for (const backup of [first, second, third]) {
expect(fs.existsSync(backup)).toBe(true);
}
expect(MacMachineInfoUtils.getBackups(target)).toHaveLength(3);
});
});
});
describe('restore path validation', () => {
it('accepts legacy and new backup names present in the whitelist', () => {
withTempDir((dir) => {
const target = path.join(dir, 'Registry20');
fs.writeFileSync(target, Buffer.from('x'));
fs.writeFileSync(`${target}.bak.20251009123456`, Buffer.from('legacy'));
const created = Registry20Utils.backup(target);
const list = Registry20Utils.getBackups(target);
expect(resolveBackupPath(target, path.basename(`${target}.bak.20251009123456`), list))
.toBe(`${target}.bak.20251009123456`);
expect(resolveBackupPath(target, path.basename(created), list)).toBe(created);
});
});
it('rejects directory traversal and unknown backup names', () => {
withTempDir((dir) => {
const target = path.join(dir, 'machine-info');
fs.writeFileSync(target, Buffer.from('x'));
const list = MachineInfoUtils.getBackups(target);
expect(() => resolveBackupPath(target, '../../../non-backup.txt', list)).toThrow();
expect(() => resolveBackupPath(target, '../machine-info.bak.20251009123456', list)).toThrow();
expect(() => resolveBackupPath(target, 'machine-info.bak.20251009123456', list)).toThrow();
expect(() => resolveBackupPath(target, '/etc/passwd', list)).toThrow();
expect(() => resolveBackupPath(target, 'other.bak.20251009123456', list)).toThrow();
});
});
it('refuses to restore a backup whose content is not a valid device file', () => {
withTempDir((dir) => {
const target = path.join(dir, 'machine-info');
fs.writeFileSync(target, Buffer.from('x'));
const evil = `${target}.bak.20251009123456`;
fs.writeFileSync(evil, Buffer.from('not-a-machine-info'));
expect(() => MachineInfoUtils.restore(target, path.basename(evil))).toThrow();
// 原始文件未被破坏
expect(fs.readFileSync(target).toString()).toBe('x');
});
});
});
@@ -0,0 +1,104 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import { NativePacketHandler } from '@/napcat-core/packet/handler/client';
import { Napi2NativeLoader } from '@/napcat-core/packet/handler/napi2nativeLoader';
import { NativePacketClient } from '@/napcat-core/packet/client/nativeClient';
import type { LogWrapper } from '@/napcat-core/helper/log';
import type { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
import type { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
import type { LogStack } from '@/napcat-core/packet/context/clientContext';
import type { PacketBuf } from '@/napcat-core/packet/transformer/base';
const logger = { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn() } as unknown as LogWrapper;
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
beforeEach(() => {
Object.defineProperty(process, 'platform', { value: 'darwin' });
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
Object.defineProperty(process, 'platform', platformDescriptor);
Object.defineProperty(process, 'arch', archDescriptor);
});
describe('macOS native loaders', () => {
it.each(['arm64', 'x64'])('loads both packet modules for %s', async (arch) => {
Object.defineProperty(process, 'arch', { value: arch });
const dlopen = vi.spyOn(process, 'dlopen').mockImplementation((module) => {
Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue('success') } });
});
const handler = new NativePacketHandler({ logger });
expect(await handler.init('7.0.2-53644')).toBe(true);
expect(dlopen.mock.calls[0]![1]).toContain('MoeHoo.darwin.' + arch + '.node');
const loader = new Napi2NativeLoader({ logger });
expect(loader.loaded).toBe(true);
expect(dlopen.mock.calls[1]![1]).toContain('napi2native.darwin.' + arch + '.node');
});
it.each(['error hook', 'error search', undefined])('does not report native failure %s as success', async (result) => {
Object.defineProperty(process, 'arch', { value: 'arm64' });
vi.spyOn(process, 'dlopen').mockImplementation(module => {
Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue(result) } });
});
expect(await new NativePacketHandler({ logger }).init('7.0.2-53644')).toBe(false);
});
it('does not attempt dlopen when a native binary is absent', async () => {
vi.mocked(fs.existsSync).mockReturnValue(false);
const dlopen = vi.spyOn(process, 'dlopen').mockImplementation(() => {});
const handler = new NativePacketHandler({ logger });
expect(await handler.init('7.0.2-53644')).toBe(false);
expect(new Napi2NativeLoader({ logger }).loaded).toBe(false);
expect(dlopen).not.toHaveBeenCalled();
});
});
describe('NativePacketClient', () => {
function fixture () {
const send = vi.fn();
const minimum = vi.fn().mockImplementation(version => Number(version) <= 40768);
const native = { initHook: vi.fn().mockReturnValue(true) };
const core = { basicInfo: { requireMinNTQQBuild: minimum }, sendSsoCmdReqByContend: send };
const logs = { pushLogWarn: vi.fn(), pushLogInfo: vi.fn(), pushLogError: vi.fn() };
const client = new NativePacketClient(
core as unknown as NapCoreContext,
{ error: vi.fn() } as unknown as PacketLogger,
logs as unknown as LogStack,
native as unknown as Napi2NativeLoader
);
return { client, send, minimum, native };
}
it('initializes the oldest supported build and clears availability after failure', async () => {
const { client, minimum, native } = fixture();
await client.init(0, '10', '20');
expect(minimum).toHaveBeenCalledWith('40768');
expect(client.available).toBe(true);
native.initHook.mockReturnValue(false);
await client.init(0, '10', '20');
expect(client.available).toBe(false);
});
it.each(['success', 'failure', 'timeout'])('clears request timers after %s', async (outcome) => {
vi.useFakeTimers();
const { client, send } = fixture();
const payload = Buffer.from([0, 255, 128]) as PacketBuf;
if (outcome === 'success') send.mockResolvedValue({ rspbuffer: payload });
if (outcome === 'failure') send.mockRejectedValue(new Error('network unavailable'));
if (outcome === 'timeout') send.mockReturnValue(new Promise(() => {}));
const pending = client.sendPacket('Test.Command', payload, true, 50);
if (outcome === 'success') {
await expect(pending).resolves.toEqual({ seq: 0, cmd: 'Test.Command', data: payload });
} else {
const assertion = expect(pending).rejects.toThrow(outcome === 'timeout' ? '超时' : 'network unavailable');
if (outcome === 'timeout') await vi.advanceTimersByTimeAsync(50);
await assertion;
}
expect(vi.getTimerCount()).toBe(0);
expect(send).toHaveBeenCalledWith('Test.Command', payload);
});
});
@@ -0,0 +1,66 @@
// 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 SetGroupLeave from '../napcat-onebot/action/group/SetGroupLeave';
function createAction () {
const quitGroup = vi.fn().mockResolvedValue(undefined);
const destroyGroup = vi.fn().mockResolvedValue(undefined);
const action = new SetGroupLeave(
undefined as never,
{
apis: {
GroupApi: { quitGroup, destroyGroup },
},
} as never
);
return { action, quitGroup, destroyGroup };
}
describe('set_group_leave is_dismiss', () => {
test('leaves the group when is_dismiss is absent', async () => {
const { action, quitGroup, destroyGroup } = createAction();
await action._handle({ group_id: '123' });
expect(quitGroup).toHaveBeenCalledWith('123');
expect(destroyGroup).not.toHaveBeenCalled();
});
test('leaves the group when is_dismiss is false', async () => {
const { action, quitGroup, destroyGroup } = createAction();
await action._handle({ group_id: '123', is_dismiss: false });
expect(quitGroup).toHaveBeenCalledWith('123');
expect(destroyGroup).not.toHaveBeenCalled();
});
test("leaves the group when is_dismiss is the string 'false'", async () => {
const { action, quitGroup, destroyGroup } = createAction();
await action._handle({ group_id: '123', is_dismiss: 'false' });
expect(quitGroup).toHaveBeenCalledWith('123');
expect(destroyGroup).not.toHaveBeenCalled();
});
test('destroys the group when is_dismiss is true', async () => {
const { action, quitGroup, destroyGroup } = createAction();
await action._handle({ group_id: '123', is_dismiss: true });
expect(destroyGroup).toHaveBeenCalledWith('123');
expect(quitGroup).not.toHaveBeenCalled();
});
test("destroys the group when is_dismiss is the string 'true'", async () => {
const { action, quitGroup, destroyGroup } = createAction();
await action._handle({ group_id: '123', is_dismiss: 'true' });
expect(destroyGroup).toHaveBeenCalledWith('123');
expect(quitGroup).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,44 @@
import { afterEach, expect, test } from 'vitest';
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
const fixtures: string[] = [];
afterEach(() => {
for (const fixture of fixtures.splice(0)) {
rmSync(fixture, { recursive: true, force: true });
}
});
test('type post-build replaces complete nested generic and import types', () => {
const fixture = mkdtempSync(path.join(packageRoot, 'napcat-types/post-build-test-'));
fixtures.push(fixture);
mkdirSync(path.join(fixture, 'scripts'));
mkdirSync(path.join(fixture, 'dist'));
const script = path.join(fixture, 'scripts/post-build.mjs');
copyFileSync(path.join(packageRoot, 'napcat-types/scripts/post-build.mjs'), script);
writeFileSync(path.join(fixture, 'dist/fixture.d.ts'), `
import { NapProtoDecodeStructType } from 'napcat-protobuf';
export declare class Example {
parse(): import('napcat-protobuf').NapProtoDecodeStructType<() => { nested: Map<string, Array<number>> }>;
encode(): NapProtoEncodeStructType<{ fn: () => Promise<Array<string>> }>;
validate: ValidateFunction<Map<string, Array<number>>>;
unrelated: Promise<Array<string>>;
}
export declare enum ExampleKind { First = 1 }
`);
execFileSync(process.execPath, [script], { encoding: 'utf8' });
const output = readFileSync(path.join(fixture, 'dist/fixture.ts'), 'utf8');
const parsed = ts.transpileModule(output, { reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.Latest } });
expect(parsed.diagnostics).toHaveLength(0);
expect(output).toContain('parse(): any;');
expect(output).toContain('encode(): any;');
expect(output).toContain('validate: any;');
expect(output).toContain('unrelated: Promise<Array<string>>;');
expect(output).toContain('export enum ExampleKind');
expect(output).not.toContain("import('napcat-protobuf').any");
});
+2
View File
@@ -14,6 +14,8 @@ export default defineConfig({
'@/napcat-common': resolve(__dirname, '../napcat-common'),
'@/napcat-core': resolve(__dirname, '../napcat-core'),
'@/napcat-onebot': resolve(__dirname, '../napcat-onebot'),
'@/napcat-shell': resolve(__dirname, '../napcat-shell'),
'@/napcat-webui-backend': resolve(__dirname, '../napcat-webui-backend'),
'napcat-protobuf': resolve(__dirname, '../napcat-protobuf/NapProto.ts'),
},
},
+3 -2
View File
@@ -19,6 +19,7 @@
"devDependencies": {
"napcat-core": "workspace:*",
"napcat-onebot": "workspace:*",
"tsc-alias": "^1.8.16"
"tsc-alias": "^1.8.16",
"typescript": "^5.3.0"
}
}
}
+21 -3
View File
@@ -1,6 +1,7 @@
import { readdir, readFile, writeFile, rename } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
const __dirname = fileURLToPath(new URL('../', import.meta.url));
const distDir = join(__dirname, 'dist');
@@ -41,9 +42,21 @@ function replaceExternalTypes (content) {
let result = content;
// 替换带泛型的类型(先处理复杂的)
result = result.replace(/NapProtoDecodeStructType<[^>]+>/g, 'any');
result = result.replace(/NapProtoEncodeStructType<[^>]+>/g, 'any');
result = result.replace(/ValidateFunction<[^>]+>/g, 'any');
const sourceFile = ts.createSourceFile('declaration.d.ts', result, ts.ScriptTarget.Latest, true);
const genericTypeNames = new Set(['NapProtoDecodeStructType', 'NapProtoEncodeStructType', 'ValidateFunction']);
const replacements = [];
const visit = (node) => {
const typeName = ts.isTypeReferenceNode(node) ? node.typeName : ts.isImportTypeNode(node) ? node.qualifier : undefined;
if (typeName && genericTypeNames.has(typeName.getText(sourceFile).split('.').at(-1))) {
replacements.push({ start: node.getStart(sourceFile), end: node.getEnd() });
return;
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
for (const replacement of replacements.reverse()) {
result = result.slice(0, replacement.start) + 'any' + result.slice(replacement.end);
}
// 替换 winston.Logger 等带命名空间的类型
result = result.replace(/winston\.Logger/g, 'any');
@@ -103,6 +116,11 @@ async function processFile (filePath) {
// 3. Replace "export declare enum" with "export enum"
content = content.replace(/export declare enum/g, 'export enum');
const parsed = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
if (parsed.parseDiagnostics.length > 0) {
throw new Error(`Invalid generated declaration ${filePath}: ${parsed.parseDiagnostics.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')).join('\n')}`);
}
// Write back the modified content
await writeFile(filePath, content, 'utf-8');
+9 -1
View File
@@ -12,6 +12,12 @@
"napcat-core": [
"../../packages/napcat-core/index.ts"
],
"napcat-core/*": [
"../../packages/napcat-core/*"
],
"napcat-webui-backend/*": [
"../../packages/napcat-webui-backend/*"
],
"napcat-onebot": [
"../../packages/napcat-onebot/index.ts"
],
@@ -40,6 +46,8 @@
},
"include": [
"./index.ts",
"../napcat-pty/node-pty.d.ts",
"../napcat-pty/native.d.ts",
"../napcat-core/**/*.ts",
"../napcat-onebot/**/*.ts",
"../napcat-common/**/*.ts"
@@ -48,4 +56,4 @@
"node_modules",
"dist"
]
}
}
+147 -13
View File
@@ -5,7 +5,18 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { WebUiConfig } from '@/napcat-webui-backend/index';
import { isEmpty } from '@/napcat-webui-backend/src/utils/check';
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { Registry20Utils, MachineInfoUtils } from '@/napcat-webui-backend/src/utils/guid';
import {
Registry20Utils,
MachineInfoUtils,
getGlobalDataPath,
MacMachineInfoUtils,
computeMacGuidInfo,
getMacPlatformUuid,
getMacSn,
getMacSerialNumber,
getMacDiskSerial,
getMacPrimaryMac,
} from '@/napcat-webui-backend/src/utils/guid';
import os from 'node:os';
// oidb 新设备验证请求辅助函数
@@ -39,8 +50,8 @@ function oidbRequest (uid: string, body: Record<string, unknown>): Promise<Recor
});
}
// 获取 Registry20 路径的辅助函数
const getRegistryPath = () => {
// 获取 QQ 数据根目录 (dataPath)
const getQQDataPath = (): string => {
// 优先从 WebUiDataRuntime 获取早期设置的 dataPath
let dataPath = WebUiDataRuntime.getQQDataPath();
if (!dataPath) {
@@ -51,20 +62,17 @@ const getRegistryPath = () => {
if (!dataPath) {
throw new Error('QQ data path not available yet');
}
return Registry20Utils.getRegistryPath(dataPath);
return dataPath;
};
// 获取 Registry20 路径的辅助函数
const getRegistryPath = () => {
return Registry20Utils.getRegistryPath(getQQDataPath());
};
// 获取 machine-info 路径的辅助函数 (Linux)
const getMachineInfoPath = () => {
let dataPath = WebUiDataRuntime.getQQDataPath();
if (!dataPath) {
const oneBotContext = WebUiDataRuntime.getOneBotContext();
dataPath = oneBotContext?.core?.dataPath;
}
if (!dataPath) {
throw new Error('QQ data path not available yet');
}
return MachineInfoUtils.getMachineInfoPath(dataPath);
return MachineInfoUtils.getMachineInfoPath(getQQDataPath());
};
// 获取QQ登录二维码
@@ -515,6 +523,132 @@ export const QQResetLinuxDeviceIDHandler: RequestHandler = async (_, res) => {
}
};
// ============================================================
// macOS GUID 管理 (machineid-info / TEA)
// ============================================================
// macOS: 当前生效的 GUID 与来源信息
export const QQGetMacGUIDInfoHandler: RequestHandler = async (_, res) => {
try {
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
const info = await computeMacGuidInfo(dataPathGlobal);
return sendSuccess(res, info);
} catch (e) {
return sendError(res, `Failed to get macOS GUID: ${(e as Error).message}`);
}
};
// macOS: 本机硬件信息 (UUID / SN / 主网卡 MAC)
export const QQGetMacHardwareInfoHandler: RequestHandler = async (_, res) => {
try {
const [mac, platformUuid, serialNumber, diskSerial] = await Promise.all([
getMacPrimaryMac(),
getMacPlatformUuid(),
getMacSerialNumber(),
getMacDiskSerial(),
]);
return sendSuccess(res, {
platformUuid: platformUuid ?? '',
serialNumber: serialNumber ?? '',
diskSerial: diskSerial ?? '',
mac: mac ? mac.toString('hex') : '',
});
} catch (e) {
return sendError(res, `Failed to get macOS hardware info: ${(e as Error).message}`);
}
};
// macOS: 修改 machine_id (写入 TEA 加密的 machineid-info)
export const QQSetMacMachineIdHandler: RequestHandler = async (req, res) => {
const { machineId, sn } = req.body;
if (!machineId || typeof machineId !== 'string' || !/^[0-9a-fA-F]{16}$/.test(machineId)) {
return sendError(res, 'Invalid machine_id, must be 16 hex characters');
}
try {
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
const uuid = await getMacPlatformUuid();
if (!uuid) {
return sendError(res, 'IOPlatformUUID not available, cannot derive TEA key');
}
const key = MacMachineInfoUtils.keyFromUuid(uuid);
const machineIdInfoPath = MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal);
// SN 留空 = 沿用当前生效值: 优先 machineid-info 内已有 SN, 其次本机硬件 SN
let snValue: string;
if (typeof sn === 'string' && sn.length > 0) {
snValue = sn;
} else {
const existing = MacMachineInfoUtils.readMachineIdInfo(machineIdInfoPath, key);
snValue = existing?.sn || (await getMacSn());
}
// 自动备份
try {
MacMachineInfoUtils.backup(machineIdInfoPath);
} catch { }
MacMachineInfoUtils.writeMachineIdInfo(machineIdInfoPath, Buffer.from(machineId, 'hex'), snValue, key);
const guid = MacMachineInfoUtils.computeGuid(Buffer.from(machineId, 'hex'), snValue);
return sendSuccess(res, {
message: 'machine_id set successfully',
guid: guid.toString('hex'),
guidUuid: MacMachineInfoUtils.guidToUuidStyle(guid),
});
} catch (e) {
return sendError(res, `Failed to set machine_id: ${(e as Error).message}`);
}
};
// macOS: machineid-info 备份列表
export const QQGetMacInfoBackupsHandler: RequestHandler = async (_, res) => {
try {
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
const backups = MacMachineInfoUtils.getBackups(MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal));
return sendSuccess(res, backups);
} catch (e) {
return sendError(res, `Failed to get backups: ${(e as Error).message}`);
}
};
// macOS: 创建 machineid-info 备份
export const QQCreateMacInfoBackupHandler: RequestHandler = async (_, res) => {
try {
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
const backupPath = MacMachineInfoUtils.backup(MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal));
return sendSuccess(res, { message: 'Backup created', path: backupPath });
} catch (e) {
return sendError(res, `Failed to backup: ${(e as Error).message}`);
}
};
// macOS: 恢复 machineid-info 备份
export const QQRestoreMacInfoBackupHandler: RequestHandler = async (req, res) => {
const { backupName } = req.body;
if (!backupName) {
return sendError(res, 'Backup name is required');
}
try {
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
MacMachineInfoUtils.restore(MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal), backupName);
return sendSuccess(res, { message: 'Restored successfully' });
} catch (e) {
return sendError(res, `Failed to restore: ${(e as Error).message}`);
}
};
// macOS: 重置设备信息 (删除 machineid-info, 回退到 MAC)
export const QQResetMacDeviceIDHandler: RequestHandler = async (_, res) => {
try {
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
const machineIdInfoPath = MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal);
// 自动备份
try {
MacMachineInfoUtils.backup(machineIdInfoPath);
} catch { }
MacMachineInfoUtils.delete(machineIdInfoPath);
return sendSuccess(res, { message: 'Device ID reset successfully (machineid-info deleted)' });
} catch (e) {
return sendError(res, `Failed to reset Device ID: ${(e as Error).message}`);
}
};
// ============================================================
// OIDB 新设备 QR 验证
// ============================================================
@@ -31,6 +31,13 @@ import {
QQCreateLinuxMachineInfoBackupHandler,
QQRestoreLinuxMachineInfoBackupHandler,
QQResetLinuxDeviceIDHandler,
QQGetMacGUIDInfoHandler,
QQGetMacHardwareInfoHandler,
QQSetMacMachineIdHandler,
QQGetMacInfoBackupsHandler,
QQCreateMacInfoBackupHandler,
QQRestoreMacInfoBackupHandler,
QQResetMacDeviceIDHandler,
} from '@/napcat-webui-backend/src/api/QQLogin';
const router: Router = Router();
@@ -99,4 +106,22 @@ router.post('/RestoreLinuxMachineInfoBackup', QQRestoreLinuxMachineInfoBackupHan
// router:重置Linux设备信息
router.post('/ResetLinuxDeviceID', QQResetLinuxDeviceIDHandler);
// ============================================================
// macOS GUID 管理
// ============================================================
// router:获取macOS设备GUID信息
router.post('/GetMacGUIDInfo', QQGetMacGUIDInfoHandler);
// router:获取macOS硬件信息
router.post('/GetMacHardwareInfo', QQGetMacHardwareInfoHandler);
// router:设置macOS machine_id
router.post('/SetMacMachineId', QQSetMacMachineIdHandler);
// router:获取macOS machineid-info备份列表
router.post('/GetMacInfoBackups', QQGetMacInfoBackupsHandler);
// router:创建macOS machineid-info备份
router.post('/CreateMacInfoBackup', QQCreateMacInfoBackupHandler);
// router:恢复macOS machineid-info备份
router.post('/RestoreMacInfoBackup', QQRestoreMacInfoBackupHandler);
// router:重置macOS设备信息
router.post('/ResetMacDeviceID', QQResetMacDeviceIDHandler);
export { router as QQLoginRouter };
+612 -25
View File
@@ -2,11 +2,105 @@ import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import crypto from 'node:crypto';
import { execFile } from 'node:child_process';
import { protectData, unprotectData } from 'napcat-dpapi';
const GUID_HEADER = Buffer.from([0x00, 0x00, 0x00, 0x14]);
const XOR_KEY = 0x10;
/** 备份文件统一后缀,形如 `<原文件名>.bak.20251010031234567-1a2b3c4d` */
const BACKUP_SUFFIX = '.bak.';
/** 兼容历史命名(秒级、无随机后缀)以及新命名(毫秒级+随机后缀) */
const BACKUP_SUFFIX_PATTERN = /^\.bak\.\d{8,20}(?:-[0-9a-f]{1,32})?$/i;
/**
* 由 QQ 数据根目录推导 global 目录。
* Windows: <dataPath>/nt_qq/global
* Linux : <dataPath>/global
* macOS : <dataPath>/global
*/
export function getGlobalDataPath (dataPath: string): string {
if (os.platform() === 'win32') {
return path.join(dataPath, 'nt_qq', 'global');
}
return path.join(dataPath, 'global');
}
/**
* 生成毫秒级(UTC)时间戳,避免同一秒内的连续备份互相覆盖。
*/
function backupTimestamp (): string {
const now = new Date();
const pad = (value: number, width = 2) => String(value).padStart(width, '0');
return [
now.getUTCFullYear(),
pad(now.getUTCMonth() + 1),
pad(now.getUTCDate()),
pad(now.getUTCHours()),
pad(now.getUTCMinutes()),
pad(now.getUTCSeconds()),
pad(now.getUTCMilliseconds(), 3),
].join('');
}
/**
* 创建备份文件。使用 `COPYFILE_EXCL` 落盘,杜绝同秒/连击时的无感知覆盖。
*/
function createBackupFile (filePath: string, missingMessage: string): string {
if (!fs.existsSync(filePath)) {
throw new Error(missingMessage);
}
const timestamp = backupTimestamp();
for (let attempt = 0; attempt < 8; attempt++) {
const randomSuffix = crypto.randomBytes(4).toString('hex');
const backupPath = `${filePath}${BACKUP_SUFFIX}${timestamp}-${randomSuffix}`;
try {
fs.copyFileSync(filePath, backupPath, fs.constants.COPYFILE_EXCL);
return backupPath;
} catch (e) {
// 仅在同名冲突时重试,其余错误(权限/磁盘等)直接抛出
if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
}
}
throw new Error('Failed to create backup: too many name collisions');
}
/**
* 校验并解析备份文件名,返回可安全读取的绝对路径。
*
* 安全约束(防止目录穿越与任意文件覆盖):
* - 必须是纯文件名,不能包含路径分隔符或 `..`;
* - 必须匹配 `<原文件名>.bak.<时间戳>[-随机后缀]`;
* - 必须存在于调用方提供的备份白名单中(来自 `readdirSync`)。
*/
export function resolveBackupPath (filePath: string, backupFileName: string, backupList: string[]): string {
if (typeof backupFileName !== 'string' || backupFileName.length === 0) {
throw new Error('Backup name is required');
}
if (
backupFileName !== path.basename(backupFileName) ||
backupFileName.includes('/') ||
backupFileName.includes('\\') ||
backupFileName.includes('..')
) {
throw new Error('Invalid backup name');
}
const baseName = path.basename(filePath);
if (!backupFileName.startsWith(baseName)) {
throw new Error('Invalid backup name');
}
const suffix = backupFileName.slice(baseName.length);
if (!BACKUP_SUFFIX_PATTERN.test(suffix)) {
throw new Error('Invalid backup name');
}
if (!backupList.includes(backupFileName)) {
throw new Error('Backup file not found');
}
return path.join(path.dirname(filePath), backupFileName);
}
/**
* Unprotects data using Windows DPAPI via napcat-dpapi.
*/
@@ -25,7 +119,7 @@ function dpapiProtectAndWrite (filePath: string, data: Buffer): void {
export class Registry20Utils {
static getRegistryPath (dataPath: string): string {
return path.join(dataPath, 'nt_qq', 'global', 'nt_data', 'msf', 'Registry20');
return path.join(getGlobalDataPath(dataPath), 'nt_data', 'msf', 'Registry20');
}
static readGuid (registryPath: string): string {
@@ -91,20 +185,14 @@ export class Registry20Utils {
}
static backup (registryPath: string): string {
if (!fs.existsSync(registryPath)) {
throw new Error('Registry20 does not exist');
}
const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14);
const backupPath = `${registryPath}.bak.${timestamp}`;
fs.copyFileSync(registryPath, backupPath);
return backupPath;
return createBackupFile(registryPath, 'Registry20 does not exist');
}
static restore (registryPath: string, backupFileName: string): void {
const dir = path.dirname(registryPath);
const backupPath = path.join(dir, backupFileName);
if (!fs.existsSync(backupPath)) {
throw new Error('Backup file not found');
const backupPath = resolveBackupPath(registryPath, backupFileName, Registry20Utils.getBackups(registryPath));
// 内容校验: DPAPI 密文不可能为空
if (fs.statSync(backupPath).size === 0) {
throw new Error('Invalid backup content');
}
fs.copyFileSync(backupPath, registryPath);
}
@@ -147,7 +235,7 @@ export class MachineInfoUtils {
* 获取 machine-info 文件路径
*/
static getMachineInfoPath (dataPath: string): string {
return path.join(dataPath, 'nt_qq', 'global', 'nt_data', 'msf', 'machine-info');
return path.join(getGlobalDataPath(dataPath), 'nt_data', 'msf', 'machine-info');
}
/**
@@ -243,24 +331,20 @@ export class MachineInfoUtils {
* 创建备份
*/
static backup (machineInfoPath: string): string {
if (!fs.existsSync(machineInfoPath)) {
throw new Error('machine-info file does not exist');
}
const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14);
const backupPath = `${machineInfoPath}.bak.${timestamp}`;
fs.copyFileSync(machineInfoPath, backupPath);
return backupPath;
return createBackupFile(machineInfoPath, 'machine-info file does not exist');
}
/**
* 恢复备份
*/
static restore (machineInfoPath: string, backupFileName: string): void {
const dir = path.dirname(machineInfoPath);
const backupPath = path.join(dir, backupFileName);
if (!fs.existsSync(backupPath)) {
throw new Error('Backup file not found');
}
const backupPath = resolveBackupPath(
machineInfoPath,
backupFileName,
MachineInfoUtils.getBackups(machineInfoPath)
);
// 内容校验: 必须符合 machine-info 的 be32 长度 + ROT13 结构
MachineInfoUtils.readMac(backupPath);
fs.copyFileSync(backupPath, machineInfoPath);
}
@@ -273,3 +357,506 @@ export class MachineInfoUtils {
}
}
}
// ============================================================
// macOS TEA 容器 / machineid-info 工具类
// ============================================================
const TEA_DELTA = 0x9E3779B9;
function teaKeyWords (key: Buffer): [number, number, number, number] {
const padded = Buffer.concat([key, Buffer.alloc(Math.max(0, 16 - key.length))]).subarray(0, 16);
return [
padded.readUInt32BE(0),
padded.readUInt32BE(4),
padded.readUInt32BE(8),
padded.readUInt32BE(12),
];
}
/**
* 单块 TEA 加密 (16 轮, delta 0x9E3779B9, 密钥与数据均按大端处理)
* 逆向自 macOS wrapper.node sub_4127C1C
*/
export function teaEncryptBlock (block: Buffer, key: Buffer): Buffer {
if (block.length !== 8) {
throw new Error('TEA block must be 8 bytes');
}
let v0 = block.readUInt32BE(0);
let v1 = block.readUInt32BE(4);
const [k0, k1, k2, k3] = teaKeyWords(key);
let sum = TEA_DELTA;
for (let i = 0; i < 16; i++) {
v0 = (v0 + ((((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1)) >>> 0)) >>> 0;
v1 = (v1 + ((((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3)) >>> 0)) >>> 0;
sum = (sum + TEA_DELTA) >>> 0;
}
const out = Buffer.alloc(8);
out.writeUInt32BE(v0, 0);
out.writeUInt32BE(v1, 4);
return out;
}
/**
* 单块 TEA 解密 -> sub_4127CE5
*/
export function teaDecryptBlock (block: Buffer, key: Buffer): Buffer {
if (block.length !== 8) {
throw new Error('TEA block must be 8 bytes');
}
let v0 = block.readUInt32BE(0);
let v1 = block.readUInt32BE(4);
const [k0, k1, k2, k3] = teaKeyWords(key);
let sum = (TEA_DELTA * 16) >>> 0;
for (let i = 0; i < 16; i++) {
v1 = (v1 - ((((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3)) >>> 0)) >>> 0;
v0 = (v0 - ((((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1)) >>> 0)) >>> 0;
sum = (sum - TEA_DELTA) >>> 0;
}
const out = Buffer.alloc(8);
out.writeUInt32BE(v0, 0);
out.writeUInt32BE(v1, 4);
return out;
}
function xor8 (a: Buffer, b: Buffer): Buffer {
const out = Buffer.alloc(8);
for (let i = 0; i < 8; i++) out[i] = a[i]! ^ b[i]!;
return out;
}
/**
* QQ 加密容器封装 -> sub_414B658
* P_i = X_i XOR C_(i-1)
* C_i = E(P_i) XOR P_(i-1)
* X = [head][v8 random][2 random] + payload + 00*7
*/
export function containerEncrypt (payload: Buffer, key: Buffer, rng: (n: number) => Buffer = crypto.randomBytes): Buffer {
const n = payload.length;
// 注意: Python 的 % 结果非负, JS 对负数会返回负数, 这里手动取模
const v8 = ((8 - ((n + 10) % 8)) % 8);
const head = Buffer.from([(rng(1)[0]! & 0xF8) | v8]);
const stream = Buffer.concat([head, rng(v8), rng(2), payload, Buffer.alloc(7)]);
const out = Buffer.alloc(stream.length);
let pPrev: Buffer = Buffer.alloc(8);
let cPrev: Buffer = Buffer.alloc(8);
for (let i = 0; i < stream.length; i += 8) {
const xI = stream.subarray(i, i + 8);
const pI = xor8(xI, cPrev);
const cI = xor8(teaEncryptBlock(pI, key), pPrev);
cI.copy(out, i);
pPrev = pI;
cPrev = cI;
}
return out;
}
/**
* QQ 加密容器解封 -> sub_4128416, 失败返回 null
*/
export function containerDecrypt (data: Buffer, key: Buffer, checkTail = true): Buffer | null {
if (data.length < 16 || data.length % 8 !== 0) return null;
const stream = Buffer.alloc(data.length);
let pPrev: Buffer = Buffer.alloc(8);
let cPrev: Buffer = Buffer.alloc(8);
for (let i = 0; i < data.length; i += 8) {
const cI = data.subarray(i, i + 8);
const pI = i === 0 ? teaDecryptBlock(cI, key) : teaDecryptBlock(xor8(pPrev, cI), key);
xor8(pI, cPrev).copy(stream, i);
pPrev = pI;
cPrev = cI;
}
const v8 = stream[0]! & 0x07;
const n = data.length - v8 - 10;
if (n < 0) return null;
const start = v8 + 3;
const payload = stream.subarray(start, start + n);
const tail = stream.subarray(start + n);
if (checkTail && tail.some((b) => b !== 0)) return null;
return Buffer.from(payload);
}
function buildFields (...chunks: Buffer[]): Buffer {
const parts: Buffer[] = [];
for (const chunk of chunks) {
const len = Buffer.alloc(4);
len.writeUInt32BE(chunk.length, 0);
parts.push(len, chunk);
}
return Buffer.concat(parts);
}
function parseFields (plain: Buffer): Buffer[] {
const fields: Buffer[] = [];
let off = 0;
while (off + 4 <= plain.length) {
const len = plain.readUInt32BE(off);
off += 4;
if (off + len > plain.length) {
fields.push(plain.subarray(off));
break;
}
fields.push(plain.subarray(off, off + len));
off += len;
}
return fields;
}
export interface MacMachineInfo {
machineId: Buffer;
sn: string;
}
/**
* macOS machine-info 工具类
*
* 文件位置 (相对 QQ global 目录):
* nt_data/msf/machineid-info —— TEA 容器, 明文 = be32(8)+machine_id[8] + be32(len)+sn
* nt_data/msf/machine-info —— 明文 be32(8) + [MAC(6) + 00 00]
* nt_data/msf/machine-guid —— 明文 16 字节 guid
*/
export class MacMachineInfoUtils {
static getMsfDir (dataPathGlobal: string): string {
return path.join(dataPathGlobal, 'nt_data', 'msf');
}
static getMachineIdInfoPath (dataPathGlobal: string): string {
return path.join(MacMachineInfoUtils.getMsfDir(dataPathGlobal), 'machineid-info');
}
static getMachineInfoPath (dataPathGlobal: string): string {
return path.join(MacMachineInfoUtils.getMsfDir(dataPathGlobal), 'machine-info');
}
static getMachineGuidPath (dataPathGlobal: string): string {
return path.join(MacMachineInfoUtils.getMsfDir(dataPathGlobal), 'machine-guid');
}
/**
* TEA 密钥 = IOPlatformUUID 字符串前 16 字节 (不足补 0)
*/
static keyFromUuid (uuid: string): Buffer {
return Buffer.concat([Buffer.from(uuid, 'utf8').subarray(0, 16), Buffer.alloc(16)]).subarray(0, 16);
}
static guidToUuidStyle (guid: Buffer, upper = true): string {
const s = guid.toString('hex');
const out = `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20, 32)}`;
return upper ? out.toUpperCase() : out;
}
static buildMachineIdInfo (machineId: Buffer, sn: string): Buffer {
if (machineId.length !== 8) {
throw new Error('machine_id must be 8 bytes');
}
return buildFields(machineId, Buffer.from(sn, 'utf8'));
}
static parseMachineIdInfo (plain: Buffer): MacMachineInfo {
const fields = parseFields(plain);
const machineId = fields[0]?.subarray(0, 8) ?? Buffer.alloc(0);
const sn = fields[1] ? fields[1].toString('utf8') : '';
return { machineId: Buffer.from(machineId), sn };
}
/**
* guid = MD5(machine_id[8] || sn) -> sub_414E158
*/
static computeGuid (machineId: Buffer, sn: string): Buffer {
const md5 = crypto.createHash('md5');
md5.update(machineId.subarray(0, 8));
md5.update(sn, 'utf8');
return md5.digest();
}
static readMachineIdInfo (filePath: string, key: Buffer, checkTail = true): MacMachineInfo | null {
if (!fs.existsSync(filePath)) return null;
const plain = containerDecrypt(fs.readFileSync(filePath), key, checkTail);
if (!plain) return null;
return MacMachineInfoUtils.parseMachineIdInfo(plain);
}
static writeMachineIdInfo (filePath: string, machineId: Buffer, sn: string, key: Buffer): void {
const plain = MacMachineInfoUtils.buildMachineIdInfo(machineId, sn);
const encrypted = containerEncrypt(plain, key);
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(filePath, encrypted);
}
/**
* machine-info 是明文 be32(8) + 8 字节 (MAC(6) + 00 00)
*/
static readMachineId (filePath: string): Buffer | null {
if (!fs.existsSync(filePath)) return null;
const data = fs.readFileSync(filePath);
if (data.length < 4) return null;
const len = data.readUInt32BE(0);
if (len < 8 || data.length < 4 + len) return null;
return Buffer.from(data.subarray(4, 4 + 8));
}
static readMachineGuid (filePath: string): Buffer | null {
if (!fs.existsSync(filePath)) return null;
const data = fs.readFileSync(filePath);
if (data.length < 16) return null;
return Buffer.from(data.subarray(0, 16));
}
static getBackups (filePath: string): string[] {
const dir = path.dirname(filePath);
const baseName = path.basename(filePath);
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir)
.filter(f => f.startsWith(`${baseName}.bak.`))
.sort()
.reverse();
}
static backup (filePath: string): string {
return createBackupFile(filePath, 'machineid-info file does not exist');
}
static restore (filePath: string, backupFileName: string): void {
const backupPath = resolveBackupPath(filePath, backupFileName, MacMachineInfoUtils.getBackups(filePath));
// 内容校验: TEA 容器按 8 字节分组, 至少 16 字节
const size = fs.statSync(backupPath).size;
if (size < 16 || size % 8 !== 0) {
throw new Error('Invalid backup content');
}
fs.copyFileSync(backupPath, filePath);
}
static delete (filePath: string): void {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
}
}
// ============================================================
// macOS 本机硬件读取 (与 wrapper.node 的行为保持一致)
// ============================================================
interface HardwareCacheEntry<T> {
promise: Promise<T>;
}
const hardwareCache = new Map<string, HardwareCacheEntry<unknown>>();
/**
* 进程内硬件信息缓存。硬件标识在进程生命周期内不会变化,
* 缓存 `Promise` 可避免并发请求重复拉起 `ioreg`/`diskutil`。
*/
function cachedHardware<T> (key: string, factory: () => Promise<T>): Promise<T> {
const existing = hardwareCache.get(key);
if (existing) return existing.promise as Promise<T>;
const entry: HardwareCacheEntry<T> = { promise: factory() };
hardwareCache.set(key, entry as HardwareCacheEntry<unknown>);
return entry.promise;
}
function runCommand (file: string, args: string[]): Promise<string | null> {
return new Promise((resolve) => {
execFile(file, args, { timeout: 10000, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
if (error) {
resolve(null);
return;
}
resolve(stdout);
});
});
}
/**
* 从 `ioreg` 输出中解析 `"property" = <value>`。
*/
function parseIoregProperty (out: string, property: string): string | null {
for (const line of out.split('\n')) {
if (line.includes(`"${property}"`) && line.includes('=')) {
const raw = line.split('=').slice(1).join('=').trim();
return raw.replace(/^"|"$/g, '');
}
}
return null;
}
/**
* 运行 `ioreg -rd1 -c <className>` 并缓存结果。
*/
function ioregClassOutput (className: string): Promise<string | null> {
return cachedHardware(`ioreg:${className}`, () => runCommand('ioreg', ['-rd1', '-c', className]));
}
/**
* TEA 密钥来源: IOPlatformUUID
*/
export function getMacPlatformUuid (): Promise<string | null> {
return cachedHardware('mac:platformUuid', async () => {
const out = await ioregClassOutput('IOPlatformExpertDevice');
return out ? parseIoregProperty(out, 'IOPlatformUUID') : null;
});
}
/**
* 序列号回退: IOPlatformSerialNumber
*/
export function getMacSerialNumber (): Promise<string | null> {
return cachedHardware('mac:serialNumber', async () => {
const out = await ioregClassOutput('IOPlatformExpertDevice');
return out ? parseIoregProperty(out, 'IOPlatformSerialNumber') : null;
});
}
/**
* 优先 /dev/disk0 的序列号 (对应 wrapper.node sub_414CD1C)
*/
export function getMacDiskSerial (): Promise<string | null> {
return cachedHardware('mac:diskSerial', async () => {
const out = await runCommand('diskutil', ['info', '/dev/disk0']);
if (!out) return null;
for (const line of out.split('\n')) {
if (line.includes('Serial Number') || line.includes('设备序列号')) {
return line.split(':').slice(1).join(':').trim();
}
}
return null;
});
}
/**
* macOS 序列号: 优先 /dev/disk0, 失败回退 IOPlatformSerialNumber
*/
export async function getMacSn (): Promise<string> {
return (await getMacDiskSerial()) ?? (await getMacSerialNumber()) ?? '';
}
/**
* 从 ioreg 节点行中提取 `"IOMACAddress" = <...>` 的 6 字节 MAC。
*/
function parseIomacAddress (line: string): Buffer | null {
const blob = line.split('=').slice(1).join('=');
const hex = (blob.match(/[0-9a-fA-F]{2}/g) ?? []).join('');
if (hex.length >= 12) {
return Buffer.from(hex.slice(0, 12), 'hex');
}
return null;
}
/** 按 `+-o ` 节点行切分 ioreg 输出。 */
function splitIoregNodes (out: string): string[] {
const nodes: string[] = [];
let current: string[] = [];
for (const line of out.split('\n')) {
if (line.includes('+-o ')) {
if (current.length > 0) nodes.push(current.join('\n'));
current = [line];
} else if (current.length > 0) {
current.push(line);
}
}
if (current.length > 0) nodes.push(current.join('\n'));
return nodes;
}
/** 从节点文本中取 IOMACAddress。 */
function nodeMac (node: string): Buffer | null {
const line = node.split('\n').find((l) => l.includes('"IOMACAddress"'));
return line ? parseIomacAddress(line) : null;
}
/**
* 主网卡 MAC。
*
* wrapper.node 取的是 IOEthernetInterface 上(或其父控制器上)的 IOMACAddress。
* 真实 ioreg 层级里 IOMACAddress 通常挂在父级控制器(如 en0 对应的
* IOEthernetController)上,且同一层级下可能有多个接口,因此这里:
* 1. 优先匹配 BSD Name 为 en0 的接口;
* 2. 其次匹配第一个 USB/以太网控制器上的接口;
* 3. 若接口自身没有该属性,则回到 `ioreg -c IOEthernetInterface` 的整个子树中查找,
* 兼容 IOMACAddress 挂在父级控制器的情况。
*/
export function getMacPrimaryMac (): Promise<Buffer | null> {
return cachedHardware('mac:primaryMac', async () => {
const ifOut = await ioregClassOutput('IOEthernetInterface');
const nodes = ifOut ? splitIoregNodes(ifOut) : [];
const en0 = nodes.find((node) => node.includes('"BSD Name" = "en0"'));
// 1. en0 接口自身的 IOMACAddress
if (en0) {
const mac = nodeMac(en0);
if (mac) return mac;
}
// 2. 父级以太网控制器上的 IOMACAddress(真实机器上多数情况下挂在这里)
const controllerOut = await ioregClassOutput('IOEthernetController');
if (controllerOut) {
for (const node of splitIoregNodes(controllerOut)) {
const mac = nodeMac(node);
if (mac) return mac;
}
}
// 3. 任意 IOEthernetInterface 自身的 IOMACAddress
for (const node of nodes) {
const mac = nodeMac(node);
if (mac) return mac;
}
return null;
});
}
export interface MacGuidInfo {
guid: string;
guidUuid: string;
machineId: string;
sn: string;
mac: string;
platformUuid: string;
source: 'machineid-info' | 'mac-fallback';
}
/**
* 主流程 (对应 wrapper.node GetMachineGuid4MacOS):
* guid = MD5(machine_id[8] || sn)
* machine_id 优先从 machineid-info (TEA) 读取, 否则回退成 MAC + 00 00
*/
export async function computeMacGuidInfo (dataPathGlobal: string, uuidOverride?: string, snOverride?: string): Promise<MacGuidInfo> {
const platformUuid = uuidOverride ?? (await getMacPlatformUuid()) ?? '';
const key = MacMachineInfoUtils.keyFromUuid(platformUuid);
const sn = snOverride ?? (await getMacSn());
const machineIdInfoPath = MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal);
const primaryMac = await getMacPrimaryMac();
let machineId: Buffer | null = null;
let source: MacGuidInfo['source'] = 'machineid-info';
let snValue = sn;
const fromFile = MacMachineInfoUtils.readMachineIdInfo(machineIdInfoPath, key);
if (fromFile && fromFile.machineId.length === 8) {
machineId = fromFile.machineId;
if (!snOverride && fromFile.sn) snValue = fromFile.sn;
} else {
const mac = primaryMac;
if (!mac) {
throw new Error('Unable to determine machine_id (no machineid-info and no MAC)');
}
machineId = Buffer.concat([mac, Buffer.from([0, 0])]);
source = 'mac-fallback';
}
const guid = MacMachineInfoUtils.computeGuid(machineId, snValue);
return {
guid: guid.toString('hex'),
guidUuid: MacMachineInfoUtils.guidToUuidStyle(guid),
machineId: machineId.toString('hex'),
sn: snValue,
mac: primaryMac?.toString('hex') ?? '',
platformUuid,
source,
};
}
@@ -8,6 +8,8 @@ import { useEffect, useState, useCallback, useMemo } from 'react';
import toast from 'react-hot-toast';
import { MdContentCopy, MdDelete, MdRefresh, MdSave, MdRestorePage, MdBackup } from 'react-icons/md';
import MD5 from 'crypto-js/md5';
import Hex from 'crypto-js/enc-hex';
import Utf8 from 'crypto-js/enc-utf8';
import QQManager from '@/controllers/qq_manager';
import useDialog from '@/hooks/use-dialog';
@@ -40,6 +42,16 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
const [machineId, setMachineId] = useState<string>('');
const [linuxBackups, setLinuxBackups] = useState<string[]>([]);
// macOS 状态
const [macGuid, setMacGuid] = useState<string>('');
const [macSource, setMacSource] = useState<string>('');
const [macInfo, setMacInfo] = useState<{ machineId: string; sn: string; mac: string; platformUuid: string; }>({
machineId: '', sn: '', mac: '', platformUuid: '',
});
const [inputMachineId, setInputMachineId] = useState<string>('');
const [inputSn, setInputSn] = useState<string>('');
const [macBackups, setMacBackups] = useState<string[]>([]);
// 通用状态
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
@@ -47,6 +59,7 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
const isValidGUID = (guid: string) => /^[0-9a-fA-F]{32}$/.test(guid);
const isValidMAC = (mac: string) => /^[0-9a-fA-F]{2}(-[0-9a-fA-F]{2}){5}$/.test(mac.trim().toLowerCase());
const isValidMachineId = (id: string) => /^[0-9a-fA-F]{16}$/.test(id.trim());
// 前端实时计算 Linux GUID = MD5(machine-id + MAC)
const computedLinuxGUID = useMemo(() => {
@@ -62,6 +75,28 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
return MD5(machineId + currentMAC).toString();
}, [isLinux, machineId, currentMAC]);
// macOS: GUID = MD5(machine_id[8 字节] || sn)
const macGuidOf = useCallback((machineIdHex: string, sn: string) => {
if (!isValidMachineId(machineIdHex)) return '';
const mid = Hex.parse(machineIdHex.trim().toLowerCase());
return MD5(mid.concat(Utf8.parse(sn))).toString();
}, []);
// macOS: SN 留空 = 沿用当前生效值 (与后端一致)
const effectiveMacSn = inputSn === '' ? macInfo.sn : inputSn;
// macOS: 实时预览 (基于输入的 machine_id / 有效 SN)
const computedMacGUID = useMemo(() => {
if (!isMac) return '';
if (!isValidMachineId(inputMachineId)) return '';
return macGuidOf(inputMachineId, effectiveMacSn);
}, [isMac, inputMachineId, effectiveMacSn, macGuidOf]);
// macOS: machine_id 或 SN 任一与当前值不同即视为可保存
const macDirty = isValidMachineId(inputMachineId) && (
inputMachineId.trim().toLowerCase() !== macInfo.machineId || effectiveMacSn !== macInfo.sn
);
// 检测平台
const fetchPlatform = useCallback(async () => {
try {
@@ -131,6 +166,40 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
}
}, []);
// macOS: 获取 GUID 信息 + 硬件信息
const fetchMacInfo = useCallback(async () => {
setLoading(true);
try {
const info = await QQManager.getMacGUIDInfo();
setMacGuid(info.guid);
setMacSource(info.source);
setMacInfo({
machineId: info.machineId,
sn: info.sn,
mac: info.mac,
platformUuid: info.platformUuid,
});
setInputMachineId(info.machineId);
setInputSn(info.sn);
} catch (error) {
const msg = (error as Error).message;
setMacGuid('');
toast.error(`获取 GUID 失败: ${msg}`);
} finally {
setLoading(false);
}
}, []);
// macOS: 获取备份
const fetchMacBackups = useCallback(async () => {
try {
const data = await QQManager.getMacInfoBackups();
setMacBackups(data);
} catch {
// ignore
}
}, []);
useEffect(() => {
fetchPlatform();
}, [fetchPlatform]);
@@ -140,11 +209,14 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
if (isWindows) {
fetchGUID();
fetchBackups();
} else if (isMac) {
fetchMacInfo();
fetchMacBackups();
} else {
fetchLinuxInfo();
fetchLinuxBackups();
}
}, [platformDetected, isWindows, fetchGUID, fetchBackups, fetchLinuxInfo, fetchLinuxBackups]);
}, [platformDetected, isWindows, isMac, fetchGUID, fetchBackups, fetchLinuxInfo, fetchLinuxBackups, fetchMacInfo, fetchMacBackups]);
// ========== Windows 操作 ==========
@@ -310,6 +382,86 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
// ========== 重启 ==========
// ========== macOS 操作 ==========
const handleMacSave = async () => {
const mid = inputMachineId.trim().toLowerCase();
if (!isValidMachineId(mid)) {
toast.error('machine_id 格式无效,需要 16 位十六进制字符');
return;
}
setSaving(true);
try {
await QQManager.setMacMachineId(mid, inputSn);
toast.success('machine_id 已设置,重启后生效');
await fetchMacInfo();
await fetchMacBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`设置 machine_id 失败: ${msg}`);
} finally {
setSaving(false);
}
};
const handleMacCopy = (text: string, label: string) => {
if (text) {
navigator.clipboard.writeText(text);
toast.success(`${label} 已复制到剪贴板`);
}
};
const handleMacDelete = () => {
dialog.confirm({
title: '确认删除',
content: '删除 machineid-info 后,QQ 将回退到基于网卡 MAC 的设备标识。确定要删除吗?',
confirmText: '删除',
cancelText: '取消',
onConfirm: async () => {
try {
await QQManager.resetMacDeviceID();
toast.success('已删除,重启后生效');
await fetchMacInfo();
await fetchMacBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`删除失败: ${msg}`);
}
},
});
};
const handleMacBackup = async () => {
try {
await QQManager.createMacInfoBackup();
toast.success('备份已创建');
await fetchMacBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`备份失败: ${msg}`);
}
};
const handleMacRestore = (backupName: string) => {
dialog.confirm({
title: '确认恢复',
content: `确定要从备份 "${backupName}" 恢复吗?当前的 machineid-info 将被覆盖。`,
confirmText: '恢复',
cancelText: '取消',
onConfirm: async () => {
try {
await QQManager.restoreMacInfoBackup(backupName);
toast.success('已恢复,重启后生效');
await fetchMacInfo();
await fetchMacBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`恢复失败: ${msg}`);
}
},
});
};
const handleRestart = () => {
dialog.confirm({
title: '确认重启',
@@ -339,18 +491,200 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
);
}
// ========== macOS 不支持 ==========
// ========== macOS 渲染 ==========
if (isMac) {
return (
<div className={`flex flex-col gap-${compact ? '3' : '4'}`}>
<div className='flex flex-col items-center justify-center py-8 gap-2'>
<Chip variant='flat' color='warning' className='text-xs'>
macOS 平台暂不支持 GUID 管理
</Chip>
{/* 当前设备 GUID */}
<div className='flex flex-col gap-2'>
<div className='text-sm font-medium text-default-700'>当前设备 GUID</div>
<div className='flex items-center gap-2'>
{macGuid
? (
<Chip variant='flat' color='primary' className='font-mono text-xs max-w-full'>
{macGuid}
</Chip>
)
: (
<Chip variant='flat' color='warning' className='text-xs'>
未设置 / 不存在
</Chip>
)}
{macGuid && (
<Button
isIconOnly
size='sm'
variant='light'
onPress={() => handleMacCopy(macGuid, 'GUID')}
aria-label='复制GUID'
>
<MdContentCopy size={16} />
</Button>
)}
<Button
isIconOnly
size='sm'
variant='light'
onPress={fetchMacInfo}
aria-label='刷新'
>
<MdRefresh size={16} />
</Button>
</div>
<div className='text-xs text-default-400'>
该功能仅适用于 Windows 和 Linux 平台
GUID = MD5(machine_id + SN),machine_id 来自 TEA 加密的 machineid-info
{macSource === 'mac-fallback' && '(当前走网卡 MAC 回退)'}
</div>
</div>
<Divider />
{/* 硬件信息 */}
<div className='flex flex-col gap-1'>
<div className='text-sm font-medium text-default-700'>IOPlatformUUID(TEA 密钥来源)</div>
<Chip variant='flat' color='default' className='font-mono text-xs max-w-full'>
{macInfo.platformUuid || '未知'}
</Chip>
<div className='text-xs text-default-400'>不可修改,密钥为其前 16 字节</div>
</div>
<div className='flex flex-col gap-1'>
<div className='text-sm font-medium text-default-700'>序列号(SN)</div>
<Chip variant='flat' color='default' className='font-mono text-xs max-w-full'>
{macInfo.sn || '未知'}
</Chip>
</div>
<div className='flex flex-col gap-1'>
<div className='text-sm font-medium text-default-700'>主网卡 MAC</div>
<Chip variant='flat' color='secondary' className='font-mono text-xs max-w-full'>
{macInfo.mac || '未知'}
</Chip>
</div>
<Divider />
{/* 编辑 machine_id */}
<div className='flex flex-col gap-2'>
<div className='text-sm font-medium text-default-700'>设置 Machine ID</div>
<Input
size='sm'
variant='bordered'
placeholder='16 位十六进制 machine_id'
value={inputMachineId}
onValueChange={setInputMachineId}
isInvalid={inputMachineId.length > 0 && !isValidMachineId(inputMachineId)}
errorMessage={inputMachineId.length > 0 && !isValidMachineId(inputMachineId) ? '需要 16 位十六进制字符' : undefined}
classNames={{ input: 'font-mono text-sm' }}
maxLength={16}
/>
<Input
size='sm'
variant='bordered'
placeholder='序列号 SN(留空使用当前值)'
value={inputSn}
onValueChange={setInputSn}
classNames={{ input: 'font-mono text-sm' }}
/>
{/* 实时 GUID 预览 */}
{isValidMachineId(inputMachineId) && (
<div className='flex flex-col gap-1 p-2 rounded-lg bg-default-100'>
<div className='text-xs font-medium text-default-500'>预览 GUID</div>
<div className='font-mono text-xs text-primary break-all'>
{computedMacGUID}
</div>
{computedMacGUID !== macGuid && (
<div className='text-xs text-warning-500'>
与当前 GUID 不同,保存后重启生效
</div>
)}
</div>
)}
<div className='flex items-center gap-2'>
<Button
size='sm'
color='primary'
variant='flat'
isLoading={saving}
isDisabled={!macDirty}
onPress={handleMacSave}
startContent={<MdSave size={16} />}
>
保存 Machine ID
</Button>
<Button
size='sm'
color='danger'
variant='flat'
isDisabled={!macGuid}
onPress={handleMacDelete}
startContent={<MdDelete size={16} />}
>
删除
</Button>
<Button
size='sm'
color='secondary'
variant='flat'
onPress={handleMacBackup}
startContent={<MdBackup size={16} />}
>
手动备份
</Button>
</div>
<div className='text-xs text-default-400'>
修改 machine_id 后 GUID 将变化,需重启 NapCat 才能生效,操作前会自动备份
</div>
</div>
{/* 备份恢复 */}
{macBackups.length > 0 && (
<>
<Divider />
<div className='flex flex-col gap-2'>
<div className='text-sm font-medium text-default-700'>
备份列表
<span className='text-xs text-default-400 ml-2'>(点击恢复)</span>
</div>
<div className='max-h-[160px] overflow-y-auto rounded-lg border border-default-200'>
<Listbox
aria-label='备份列表'
selectionMode='none'
onAction={(key) => handleMacRestore(key as string)}
>
{macBackups.map((name) => (
<ListboxItem
key={name}
startContent={<MdRestorePage size={16} className='text-default-400' />}
className='font-mono text-xs'
>
{name}
</ListboxItem>
))}
</Listbox>
</div>
</div>
</>
)}
{/* 重启 */}
{showRestart && (
<>
<Divider />
<Button
size='sm'
color='warning'
variant='flat'
isLoading={restarting}
onPress={handleRestart}
startContent={<MdRefresh size={16} />}
>
重启 NapCat
</Button>
</>
)}
</div>
);
}
@@ -271,6 +271,57 @@ export default class QQManager {
await serverRequest.post<ServerResponse<null>>('/QQLogin/ResetLinuxDeviceID');
}
// ============================================================
// macOS GUID 管理
// ============================================================
public static async getMacGUIDInfo () {
const data = await serverRequest.post<ServerResponse<{
guid: string;
guidUuid: string;
machineId: string;
sn: string;
mac: string;
platformUuid: string;
source: 'machineid-info' | 'mac-fallback';
}>>('/QQLogin/GetMacGUIDInfo');
return data.data.data;
}
public static async getMacHardwareInfo () {
const data = await serverRequest.post<ServerResponse<{
platformUuid: string;
serialNumber: string;
diskSerial: string;
mac: string;
}>>('/QQLogin/GetMacHardwareInfo');
return data.data.data;
}
public static async setMacMachineId (machineId: string, sn?: string) {
const data = await serverRequest.post<ServerResponse<{ guid: string; guidUuid: string; }>>(
'/QQLogin/SetMacMachineId', { machineId, sn });
return data.data.data;
}
public static async getMacInfoBackups () {
const data = await serverRequest.post<ServerResponse<string[]>>('/QQLogin/GetMacInfoBackups');
return data.data.data;
}
public static async createMacInfoBackup () {
const data = await serverRequest.post<ServerResponse<{ path: string; }>>('/QQLogin/CreateMacInfoBackup');
return data.data.data;
}
public static async restoreMacInfoBackup (backupName: string) {
await serverRequest.post<ServerResponse<null>>('/QQLogin/RestoreMacInfoBackup', { backupName });
}
public static async resetMacDeviceID () {
await serverRequest.post<ServerResponse<null>>('/QQLogin/ResetMacDeviceID');
}
// ============================================================
// NapCat 配置管理
// ============================================================
@@ -221,7 +221,7 @@ const LoginConfigCard = () => {
<div className='flex-shrink-0 w-full mt-4'>
<div className='mb-3 text-sm text-default-600'>设备 GUID 管理</div>
<div className='text-xs text-default-400 mb-3'>
GUID 是设备登录唯一识别码,存储在 Registry20 文件中。修改后需重启生效。
GUID 是设备登录唯一识别码,Windows 存于 Registry20、Linux 存于 machine-info、macOS 存于 machineid-info。修改后需重启生效。
</div>
<GUIDManager showRestart={false} />
</div>
+3
View File
@@ -422,6 +422,9 @@ importers:
tsc-alias:
specifier: ^1.8.16
version: 1.8.16
typescript:
specifier: ^5.3.0
version: 5.9.3
packages/napcat-universal:
dependencies:
+8
View File
@@ -0,0 +1,8 @@
import assert from 'node:assert/strict';
import { selectProfileRegion as select, profileRegionArea as area } from './packages/napcat-core/helper/profile-region.ts';
assert.equal(area({country:'中国',province:'广东',city:'广州'}),'中国 广东 广州');
assert.equal(area({country:'',province:'',city:''}),'');
assert.equal(area({province:'北京',city:'北京'}),'北京');
assert.deepEqual(select({city:'广州'},{country:'旧国家',province:'旧省'}),{country:'',province:'',city:'广州'});
assert.equal(area(select({}, {country:'中国',city:'广州'})),'中国 广州');
console.log('PASS: 5 offline region cases; no QQ requests');