Compare commits

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

No files matched your search

+6 -8
View File
@@ -5,14 +5,12 @@
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
+8 -10
View File
@@ -24,7 +24,7 @@
- **控制数量**:最终保持 5-15 条更新要点
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
## 输出模板 - 必须严格遵守以下格式
```
# {VERSION}
@@ -44,14 +44,12 @@ NapCat.Shell.Windows.OneKey.zip (无头)
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
@@ -78,7 +76,7 @@ NapCat.Shell.Windows.OneKey.zip (无头)
- "Windows 一键包"部分的文本必须完全一致,不要修改任何措辞
- "警告"部分必须包含所有 QQ 版本下载链接,保持原有格式
- "如果WinX64缺少运行库或者xxx.dll?"这一行必须保持原样
- QQ 版本号、下载链接、"官方 CDN"标注和"MacOS 暂不支持"保持不变
- QQ 版本号和下载链接保持不变(40990 版本)
- 只有"## 更新"部分下面的内容需要根据实际 commit 生成
## 重要约束
@@ -1,3 +0,0 @@
cmake_minimum_required(VERSION 3.20)
project(NapCatWindowsLoaderTest LANGUAGES CXX)
add_executable(windows-loader-test probe.cpp)
-96
View File
@@ -1,96 +0,0 @@
#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;
}
-20
View File
@@ -9,26 +9,6 @@ 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
+2 -2
View File
@@ -9,8 +9,8 @@ on:
type: string
env:
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.AppImage'
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.AppImage'
QQ_URL_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage'
QQ_URL_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage'
jobs:
get-version:
+14 -75
View File
@@ -12,7 +12,7 @@ permissions: write-all
env:
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
RELEASE_NAME: "NapCat"
jobs:
@@ -35,11 +35,6 @@ jobs:
uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
@@ -47,8 +42,8 @@ jobs:
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ inputs.version }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run ${{ matrix.target.build_cmd }}
@@ -66,11 +61,6 @@ jobs:
assemble-windows-node:
needs: build
runs-on: ubuntu-latest
env:
# QQ 9.9.31.49738; SHA256 matches the microsoft/winget-pkgs installer manifest.
QQ_URL: https://github.com/Rodert/qq-versions/releases/download/qq-packages-20260528-3e8913a2/QQ_9.9.31_260528_x64_01.exe
QQ_SHA256: 0beb5cb4ff776cba822caa0abadbd53f5892f12628a86dabea1b372c82c086bc
NODE_VERSION: '22.11.0'
steps:
- uses: actions/checkout@v5
with:
@@ -86,18 +76,12 @@ jobs:
sudo apt update
sudo apt install -y aria2 unzip zip p7zip-full curl jq
- name: Generate download cache key
id: download-cache-key
run: |
DOWNLOAD_HASH=$(printf '%s\n' "$QQ_URL" "$QQ_SHA256" "$NODE_VERSION" | sha256sum | cut -d ' ' -f 1)
echo "key=napcat-downloads-v2-$DOWNLOAD_HASH" >> "$GITHUB_OUTPUT"
- name: Cache QQ and Node.js downloads
id: cache-downloads
uses: actions/cache@v4
with:
path: /tmp/napcat-downloads
key: ${{ steps.download-cache-key.outputs.key }}
key: napcat-downloads-qq9.9.27.45627-node22.11.0
- name: Download QQ and Node.js
if: steps.cache-downloads.outputs.cache-hit != 'true'
@@ -106,20 +90,15 @@ jobs:
mkdir -p /tmp/napcat-downloads
cd /tmp/napcat-downloads
NT_URL="https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/a33ab721/QQ9.9.32.50969_x64.exe"
echo "Downloading QQ installer..."
# Retry download errors, including HTTP 404 responses.
curl --fail --location --retry 5 --retry-all-errors --retry-delay 5 \
--connect-timeout 30 --max-time 600 --user-agent "Mozilla/5.0" \
--output "QQ_x64.exe" "$QQ_URL"
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
NODE_URL="https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-win-x64.zip"
echo "Downloading Node.js $NODE_VERSION..."
NODE_VER="22.11.0"
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
echo "Downloading Node.js $NODE_VER..."
aria2c -x1 -s1 -k1M -o "node-win-x64.zip" "$NODE_URL"
- name: Verify QQ installer
run: |
echo "$QQ_SHA256 /tmp/napcat-downloads/QQ_x64.exe" | sha256sum --check --strict -
- name: Assemble NapCat.Shell.Windows.Node.zip
run: |
set -euo pipefail
@@ -154,14 +133,9 @@ jobs:
# -----------------------------
# 5) 拷贝 QQ 文件到 NapCat.Shell.Windows.Node
# -----------------------------
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")
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")
for name in "${QQ_TARGETS[@]}"; do
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/"
find "$QQ_EXTRACT" -iname "$name" -exec cp -a {} "$OUT_DIR" \; || true
done
# -----------------------------
@@ -181,7 +155,8 @@ jobs:
# -----------------------------
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
# -----------------------------
cp -a "$NODE_EXTRACT/node-v$NODE_VERSION-win-x64/node.exe" "$OUT_DIR/" || true
NODE_VER="22.11.0"
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
- name: Upload Artifact
uses: actions/upload-artifact@v6
@@ -189,39 +164,8 @@ 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, validate-windows-node]
needs: [build, assemble-windows-node]
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -470,16 +414,11 @@ jobs:
NapCat.Shell.Windows.OneKey.zip
draft: false
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Update apifox
env:
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
run: |
npm i -g pnpm
pnpm i --ignore-scripts
pnpm run build:openapi
+5 -92
View File
@@ -12,17 +12,11 @@ import {
ShutUpGroupMember,
Peer,
ChatType,
GroupManagementSettings,
} from '@/napcat-core/index';
import { isNumeric, solveAsyncProblem } from 'napcat-common/src/helper';
import { LimitedHashTable } from 'napcat-common/src/message-unique';
import { CancelableTask, TaskExecutor } from 'napcat-common/src/cancel-task';
import {
createGroupDetailInfoV2Param,
createGroupExtFilter,
createGroupExtInfo,
createGroupManagementRequests,
} from '../data';
import { createGroupDetailInfoV2Param, createGroupExtFilter, createGroupExtInfo } from '../data';
import { NTEventWrapper } from '../helper/event';
export class NTQQGroupApi {
@@ -174,54 +168,6 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().modifyGroupDetailInfoV2(param, 0);
}
async setGroupMemberInvitePolicy (
groupCode: string,
policy: NonNullable<GroupManagementSettings['memberInvite']>
) {
return this.modifyGroupManagementSettings(groupCode, { memberInvite: policy });
}
async setGroupMemberPermissions (
groupCode: string,
permissions: Pick<
GroupManagementSettings,
'allowMemberUploadAlbum' | 'allowMemberTemporarySession' | 'allowMemberCreateGroup'
>
) {
return this.modifyGroupManagementSettings(groupCode, permissions);
}
async setGroupNewMemberHistoryVisibility (groupCode: string, visible: boolean) {
return this.modifyGroupManagementSettings(groupCode, { newMembersSeeRecentHistory: visible });
}
private async modifyGroupManagementSettings (groupCode: string, settings: GroupManagementSettings) {
const results: Array<{ setting: string, result: GeneralCallResult; }> = [];
const changesKnownFlags = settings.memberInvite !== undefined ||
settings.allowMemberUploadAlbum !== undefined ||
settings.allowMemberTemporarySession !== undefined ||
settings.allowMemberCreateGroup !== undefined ||
settings.newMembersSeeRecentHistory !== undefined;
const currentDetail = changesKnownFlags ? await this.fetchGroupDetail(groupCode) : undefined;
for (const request of createGroupManagementRequests(
groupCode,
settings,
currentDetail?.privilegeFlag,
currentDetail?.groupFlagExt4
)) {
results.push({
setting: request.setting,
result: await this.context.session.getGroupService().modifyGroupDetailInfoV2(
request.param,
request.operationType
),
});
}
return results;
}
async setGroupSearch (groupCode: string, option: {
noCodeFingerOpenFlag?: number;
noFingerOpenFlag?: number;
@@ -297,9 +243,6 @@ export class NTQQGroupApi {
const updateCache = async () => {
try {
const members = await this.getGroupMemberAll(groupCode, true);
if (!members?.result?.infos) {
throw new Error(`errCode: ${members?.errCode}, errMsg: ${members?.errMsg}`);
}
this.groupMemberCache.set(groupCode, members.result.infos);
} catch (e) {
this.context.logger.logError(`刷新群成员缓存失败, 群号: ${groupCode}, 错误: ${e}`);
@@ -329,57 +272,31 @@ export class NTQQGroupApi {
// 获取群成员缓存
let members = this.groupMemberCache.get(groupCodeStr);
const cached = !!members;
if (!members) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
}
// 刚入的群可能拉不到成员列表,这时 members 为空,不能直接抛错,否则整条群消息都上报不出去
const getMember = () => {
if (!members) {
return undefined;
}
if (isNumeric(memberUinOrUidStr)) {
return Array.from(members.values()).find(member => member.uin === memberUinOrUidStr);
return Array.from(members!.values()).find(member => member.uin === memberUinOrUidStr);
} else {
return members.get(memberUinOrUidStr);
return members!.get(memberUinOrUidStr);
}
};
let member = getMember();
// 缓存里没有该成员(比如新入群),刷新一次;上面刚刷新过就不再重复拉取
if (!member && cached) {
// 如果缓存中不存在该成员,尝试刷新缓存
if (!member) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
member = getMember();
}
return member;
}
// 从已缓存的群成员里按 QQ 号找 uid,供 uin 转 uid 兜底
getUidFromMemberCache (uin: string) {
for (const members of this.groupMemberCache.values()) {
for (const [uid, member] of members) {
if (member.uin === uin) {
return uid;
}
}
}
return undefined;
}
async getGroupRecommendContactArkJson (groupCode: string) {
return this.context.session.getGroupService().getGroupRecommendContactArkJson(groupCode);
}
async getJoinGroupLink (groupCode: string, needShortUrl = true, srcId = 73, additionalParam = '') {
return this.context.session.getGroupService().getJoinGroupLink({
groupCode,
srcId,
needShortUrl,
additionalParam,
});
}
async creatGroupFileFolder (groupCode: string, folderName: string) {
return this.context.session.getRichMediaService().createGroupFolder(groupCode, folderName);
}
@@ -562,10 +479,6 @@ 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);
}
-1
View File
@@ -198,7 +198,6 @@ export class NTQQUserApi {
.add(() => this.context.session.getUixConvertService().getUid([uin]).then((data) => data.uidInfo.get(uin)))
.add(() => this.context.session.getProfileService().getUidByUin('FriendsServiceImpl', [uin]).get(uin))
.add(() => this.context.session.getGroupService().getUidByUins([uin]).then((data) => data.uids.get(uin)))
.add(() => this.core.apis.GroupApi.getUidFromMemberCache(uin))
.add(() => this.getUserDetailInfoByUin(uin).then((data) => data.detail.uid));
const uid = await fallback.run().catch(() => '');
+29 -308
View File
@@ -8,25 +8,11 @@ import {
WebHonorType, NapCatCore,
} from '@/napcat-core/index';
import { createReadStream, existsSync, statSync } from 'node:fs';
import { open, unlink, writeFile, type FileHandle } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
import { basename, join } from 'node:path';
import { qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl, QunAlbumBatch, nextQunAlbumBatchId } from '../data/webapi';
import { createReadStream, readFileSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { basename } from 'node:path';
import { qunAlbumControl } from '../data/webapi';
import { createAlbumCommentRequest, createAlbumFeedPublish, createAlbumMediaFeed } from '../data/album';
import { FFmpegService } from '../helper/ffmpeg/ffmpeg';
import { defaultVideoThumbB64 } from '../helper/ffmpeg/video';
import {
buildQzoneDeleteBody,
buildQzonePublishBody,
buildQzoneUploadImageBody,
parseQzoneDeleteResponse,
parseQzonePublishResponse,
parseQzoneUploadImageResponseText,
toQzoneRichval,
QzoneDeleteResponse,
QzonePublishResponse,
} from '../data/qzone';
export interface SetNoticeRetSuccess {
ec: number;
em: string;
@@ -38,34 +24,6 @@ export interface SetNoticeRetSuccess {
srv_code: number;
}
// 群相册分片上传的并发数
const QUN_ALBUM_SLICE_CONCURRENCY = 8;
// 服务端没给分片大小时的下限,以及防止异常值的上限
const QUN_ALBUM_SLICE_MIN = 16384;
const QUN_ALBUM_SLICE_MAX = 4 * 1024 * 1024;
// 流式计算文件摘要,避免为了算 MD5/SHA1 把整个文件读进内存(视频可能有几十上百 MB)
function hashFile (path: string, algorithm: 'md5' | 'sha1'): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash(algorithm);
createReadStream(path)
.on('data', chunk => hash.update(chunk))
.on('end', () => resolve(hash.digest('hex')))
.on('error', reject);
});
}
// 按需读取单个分片:并发上传时的内存占用只有「并发数 × 分片大小」
async function readSlice (handle: FileHandle, offset: number, length: number): Promise<Buffer> {
const buffer = Buffer.alloc(length);
const { bytesRead } = await handle.read(buffer, 0, length, offset);
// 读不满说明文件在上传过程中被改短了,继续传只会传上去一段补零的数据
if (bytesRead !== length) {
throw new Error(`读取分片失败: offset=${offset} 预期 ${length} 字节,实际 ${bytesRead} 字节`);
}
return buffer;
}
export class NTQQWebApi {
context: InstanceContext;
core: NapCatCore;
@@ -413,11 +371,9 @@ export class NTQQWebApi {
return response.data.album;
}
async createQunAlbumSession (
gc: string, sAlbumID: string, sAlbumName: string, path: string,
skey: string, pskey: string, img_md5: string, uin: string, batch?: QunAlbumBatch
) {
const img_size = statSync(path).size;
async createQunAlbumSession (gc: string, sAlbumID: string, sAlbumName: string, path: string, skey: string, pskey: string, img_md5: string, uin: string) {
const img = readFileSync(path);
const img_size = img.length;
const img_name = basename(path);
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
@@ -430,76 +386,42 @@ export class NTQQWebApi {
img_name,
sAlbumName,
sAlbumID,
// 同批多图共用 batchId,并按「第几张 / 共几张」上报,相册里才会合并成同一条
batchId: batch?.batchId,
batchIndex: batch?.index,
photo_num: batch?.count,
batch_num: batch?.count,
});
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${img_md5}?g_tk=${GTK}`;
const post = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(api, 'POST', body, {
const post = await RequestUtil.HttpGetJson<{ data: { session: string; }, ret: number, msg: string; }>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/json',
});
return post;
}
// 服务端会在会话响应里给出建议的分片大小;取不到或异常时退回 16384。
private resolveQunAlbumSliceSize (raw: unknown) {
const value = Number(raw);
if (!Number.isFinite(value) || value < QUN_ALBUM_SLICE_MIN) return QUN_ALBUM_SLICE_MIN;
return Math.min(value, QUN_ALBUM_SLICE_MAX);
}
async uploadQunAlbumSlice (
path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number,
options: { appid?: string, cmd?: string; } = {}
) {
const appid = options.appid ?? 'qun';
const cmd = options.cmd ?? 'FileUpload';
async uploadQunAlbumSlice (path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number) {
const img_size = statSync(path).size;
let seq = 0;
let offset = 0;
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
// 只记分片位置,不预先读内容;再并发上传(串行上传在几 MB 的图上要几十秒)
const slices: { seq: number, offset: number, end: number; }[] = [];
let seq = 0;
let offset = 0;
while (offset < img_size) {
const end = Math.min(offset + slice_size, img_size);
slices.push({ seq, offset, end });
offset = end;
seq++;
}
const stream = createReadStream(path, { highWaterMark: slice_size });
// 视频分片响应里会带 sVid,封面二段上传要靠它把封面挂到视频上
let sVid: string | undefined;
const handle = await open(path, 'r');
const uploadSlice = async (slice: { seq: number, offset: number, end: number; }) => {
const chunk = await readSlice(handle, slice.offset, slice.end - slice.offset);
for await (const chunk of stream) {
const end = Math.min(offset + chunk.length, img_size);
const form = new FormData();
form.append('uin', uin);
form.append('appid', appid);
form.append('appid', 'qun');
form.append('session', session);
form.append('offset', slice.offset.toString());
form.append('offset', offset.toString());
form.append('data', new Blob([chunk], { type: 'application/octet-stream' }), 'blob');
form.append('checksum', '');
form.append('check_type', '0');
form.append('retry', '0');
form.append('seq', slice.seq.toString());
form.append('end', slice.end.toString());
form.append('cmd', cmd);
form.append('seq', seq.toString());
form.append('end', end.toString());
form.append('cmd', 'FileUpload');
form.append('slice_size', slice_size.toString());
form.append('biz_req.iUploadType', '0');
// 分片路径必须与 cmd 一致:视频走 /sliceUpload/FileUploadVideo,
// 否则服务端按图片处理,分片会「成功」但响应里没有 sVid
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/${cmd}?seq=${slice.seq}&retry=0&offset=${slice.offset}&end=${slice.end}&total=${img_size}&type=form&g_tk=${GTK}`;
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${GTK}`;
const response = await fetch(api, {
method: 'POST',
headers: {
@@ -512,153 +434,24 @@ export class NTQQWebApi {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json() as { ret: number, msg: string, data?: { biz?: { sVid?: string; }; }; };
if (post.ret !== 0) {
throw new Error(`分片 ${slice.seq} 上传失败: ${post.msg}`);
const post = await response.json() as { ret: number, msg: string; }; if (post.ret !== 0) {
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
}
if (!sVid && typeof post.data?.biz?.sVid === 'string' && post.data.biz.sVid) {
sVid = post.data.biz.sVid;
}
};
try {
// 最后一片要等前面的全部传完再发:服务端收到最后一片就认为文件传完了,
// 并发时它可能比前面的分片先到
const lastSlice = slices.pop();
let next = 0;
let failure: { error: unknown; } | undefined;
// 固定数量的 worker 各自领下一片,慢的分片不会拖住整批
const worker = async () => {
while (!failure) {
const slice = slices[next++];
if (!slice) break;
try {
await uploadSlice(slice);
} catch (error) {
if (!failure) failure = { error };
}
}
};
await Promise.all(Array.from({ length: Math.min(QUN_ALBUM_SLICE_CONCURRENCY, slices.length) }, worker));
if (failure) throw failure.error;
if (lastSlice) await uploadSlice(lastSlice);
} finally {
await handle.close();
offset += chunk.length;
seq++;
}
return { success: true, message: '上传完成', sVid };
}
// 多张图片一次上传:共用同一个 batchId,相册里显示为同一条
async uploadImagesToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, paths: string[]) {
if (!paths.length) throw new Error('上传列表为空');
const skey = await this.core.apis.UserApi.getSKey() || '';
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
const uin = this.core.selfInfo.uin || '10001';
const batchId = nextQunAlbumBatchId();
const count = paths.length.toString();
for (const [index, path] of paths.entries()) {
const img_md5 = await hashFile(path, 'md5');
const post = await this.createQunAlbumSession(
gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin,
{ batchId, count, index: index.toString() }
);
if (!post.data?.session) throw new Error(`创建群相册会话失败: ${post.msg || post.ret}`);
await this.uploadQunAlbumSlice(path, post.data.session, skey, pskey, uin, this.resolveQunAlbumSliceSize(post.data.slice_size));
}
return { success: true, message: '上传完成' };
}
async uploadImageToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
await this.uploadImagesToQunAlbum(gc, sAlbumID, sAlbumName, [path]);
}
/**
* 上传视频到群相册。
*
* 分三步:
* 1. 建视频会话:appid=video_qun / cmd=FileUploadVideo / SHA1 校验,此时不带相册
* 2. 分片上传视频,从分片响应里拿 sVid
* 3. 按图片上传封面并用 vid 关联视频,相册和批次号在这一步带上,视频随封面进相册
*/
async uploadVideoToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
const skey = await this.core.apis.UserApi.getSKey() || '';
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
const img_md5 = createHash('md5').update(readFileSync(path)).digest('hex');
const uin = this.core.selfInfo.uin || '10001';
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const video_sha1 = await hashFile(path, 'sha1');
// 时长:ffmpeg 不可用时上报 0
let playTime = 0;
try {
playTime = Math.max(0, Math.round(await FFmpegService.getDuration(path)));
} catch (e) {
this.context.logger.logWarn('获取视频时长失败,iPlayTime 上报 0', e);
}
// 1) 视频主体(不带相册,只传成素材)
const videoSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${video_sha1}?g_tk=${GTK}`, 'POST', qunAlbumVideoControl({
uin,
group_id: gc,
pskey,
video_sha1,
video_size: statSync(path).size,
play_time: playTime,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!videoSession.data?.session) throw new Error(`创建群相册视频会话失败: ${videoSession.msg || videoSession.ret}`);
const uploaded = await this.uploadQunAlbumSlice(path, videoSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(videoSession.data.slice_size), { appid: 'video_qun', cmd: 'FileUploadVideo' });
if (!uploaded.sVid) throw new Error('视频上传完成但未取得 sVid,无法挂进相册');
// 2) 封面:抽首帧,失败(含 ffmpeg 不可用)回落内置默认封面
// 用 .png:Native Addon 路径产出的就是 png(日志里可见 Detected format: png),
// 而命令行路径会按扩展名编码,两条路都能得到真正的 PNG
const coverPath = join(this.core.NapCatTempPath, `${randomUUID()}.png`);
try {
try {
await FFmpegService.extractThumbnail(path, coverPath);
} catch (e) {
this.context.logger.logWarn('提取视频封面失败,使用默认封面', e);
await writeFile(coverPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
// 3) 封面二段上传:这一步才带相册和批次号,视频靠它进相册
const cover_md5 = await hashFile(coverPath, 'md5');
const coverSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${cover_md5}?g_tk=${GTK}`, 'POST', qunAlbumVideoCoverControl({
uin,
group_id: gc,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size: statSync(coverPath).size,
vid: uploaded.sVid,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!coverSession.data?.session) throw new Error(`创建群相册视频封面会话失败: ${coverSession.msg || coverSession.ret}`);
await this.uploadQunAlbumSlice(coverPath, coverSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(coverSession.data.slice_size));
} finally {
if (existsSync(coverPath)) {
await unlink(coverPath);
}
}
const session = (await this.createQunAlbumSession(gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin)).data.session;
if (!session) throw new Error('创建群相册会话失败');
await this.uploadQunAlbumSlice(path, session, skey, pskey, uin, 16384);
}
async getAlbumMediaListByNTQQ (gc: string, albumId: string, attach_info: string = '') {
@@ -747,78 +540,6 @@ export class NTQQWebApi {
);
}
private async getQzoneAuth () {
const skey = await this.core.apis.UserApi.getSKey() || '';
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
const uin = this.core.selfInfo.uin || '10001';
const g_tk = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
return { skey, pskey, uin, g_tk, cookie };
}
/**
* 上传图片到 QQ 空间相册, 返回可用于发说说的 richval 字符串
* @param base64 图片Base64编码内容(不带data:前缀)
*/
async uploadImageToQzone (base64: string): Promise<string> {
const { skey, pskey, uin, g_tk, cookie } = await this.getQzoneAuth();
const body = buildQzoneUploadImageBody({ uin, skey, pskey, g_tk, base64 });
const api = `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
const resultText = await RequestUtil.HttpGetText(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
});
const parsed = parseQzoneUploadImageResponseText(resultText);
if (parsed.code !== undefined && parsed.code !== 0) {
throw new Error(parsed.msg || `QQ空间图片上传失败, code=${parsed.code}`);
}
if (!parsed.data) {
throw new Error('QQ空间图片上传失败, 响应缺少data字段');
}
return toQzoneRichval(parsed.data);
}
/**
* 发表QQ空间说说
* @param content 说说正文
* @param richvals 每张图片对应的richval数组, 为空表示纯文字说说
* @param ugcRight 查看权限 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见
* @param targetUins 权限作用QQ号数组, ugcRight为16/128时使用
*/
async publishQzoneMsg (content: string, richvals: string[], ugcRight: number, targetUins?: number[]) {
const { uin, g_tk, cookie } = await this.getQzoneAuth();
const richval = richvals.length > 0 ? richvals.join('\t') : undefined;
const allowUins = targetUins && targetUins.length > 0 ? targetUins.join('|') : undefined;
const body = buildQzonePublishBody({
hostuin: uin,
content,
richval,
ugcRight,
allowUins,
});
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${g_tk}`;
const result = await RequestUtil.HttpGetJson<QzonePublishResponse>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
}, true, false);
return parseQzonePublishResponse(result);
}
/**
* 删除QQ空间说说
* @param tid 说说Tid, 来自 publishQzoneMsg 的返回值
*/
async deleteQzoneMsg (tid: string) {
const { uin, g_tk, cookie } = await this.getQzoneAuth();
const body = buildQzoneDeleteBody({ hostuin: uin, tid });
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6?g_tk=${g_tk}`;
const result = await RequestUtil.HttpGetJson<QzoneDeleteResponse>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
}, true, false);
return parseQzoneDeleteResponse(result);
}
async getDaySignedList (groupCode: string) {
const pSkey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const selfUin = this.core.selfInfo.uin;
+1 -139
View File
@@ -1,142 +1,4 @@
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter, GroupManagementSettings } from '../types';
const MEMBER_INVITE_PRIVILEGE_MASK = 0x06100000;
const MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK = 0x1;
const MEMBER_CREATE_GROUP_FLAG = 0x8000;
const MEMBER_TEMPORARY_SESSION_FLAG = 0x10000;
const NEW_MEMBER_RECENT_HISTORY_FLAG = 0x4;
function mergeMaskedFlag (currentFlag: number, requestedFlag: number, maskValue: number): number {
const mask = BigInt(maskValue);
return Number((BigInt(currentFlag) & ~mask) | (BigInt(requestedFlag) & mask));
}
export function applyGroupManagementSettings (
param: GroupDetailInfoV2Param,
settings: GroupManagementSettings
): boolean {
let changed = false;
if (settings.memberInvite !== undefined) {
const privilegeByPolicy = {
disabled: 0x04000000,
require_approval: 0,
no_approval: 0x00100000,
no_approval_under_100: 0x02000000,
} satisfies Record<NonNullable<GroupManagementSettings['memberInvite']>, number>;
param.filter.allowMemberInvite = 1;
param.modifyInfo.allowMemberInvite = settings.memberInvite === 'disabled' ? 0 : 1;
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_INVITE_PRIVILEGE_MASK;
param.modifyInfo.appPrivilegeFlag |= privilegeByPolicy[settings.memberInvite];
changed = true;
}
if (settings.allowMemberUploadAlbum !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
if (!settings.allowMemberUploadAlbum) param.modifyInfo.appPrivilegeFlag |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
changed = true;
}
if (settings.allowMemberTemporarySession !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_TEMPORARY_SESSION_FLAG;
if (!settings.allowMemberTemporarySession) param.modifyInfo.appPrivilegeFlag |= MEMBER_TEMPORARY_SESSION_FLAG;
changed = true;
}
if (settings.allowMemberCreateGroup !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_CREATE_GROUP_FLAG;
if (!settings.allowMemberCreateGroup) param.modifyInfo.appPrivilegeFlag |= MEMBER_CREATE_GROUP_FLAG;
changed = true;
}
if (settings.newMembersSeeRecentHistory !== undefined) {
param.filter.groupFlagExt4 = 1;
param.filter.groupFlagExt4Mask = 1;
param.modifyInfo.groupFlagExt4Mask |= NEW_MEMBER_RECENT_HISTORY_FLAG;
if (settings.newMembersSeeRecentHistory) param.modifyInfo.groupFlagExt4 |= NEW_MEMBER_RECENT_HISTORY_FLAG;
changed = true;
}
return changed;
}
export function createGroupManagementRequests (
groupCode: string,
settings: GroupManagementSettings,
initialAppPrivilegeFlag = 0,
initialGroupFlagExt4 = 0
) {
const requests: Array<{ setting: string, param: GroupDetailInfoV2Param, operationType: number; }> = [];
const requestSettings: Array<{
setting: string,
value: GroupManagementSettings,
operationType: number;
}> = [
{ setting: 'member_invite', value: { memberInvite: settings.memberInvite }, operationType: 0 },
{
setting: 'new_members_see_recent_history',
value: { newMembersSeeRecentHistory: settings.newMembersSeeRecentHistory },
operationType: 0,
},
{
setting: 'allow_member_upload_album',
value: { allowMemberUploadAlbum: settings.allowMemberUploadAlbum },
operationType: 8,
},
{
setting: 'allow_member_temporary_session',
value: { allowMemberTemporarySession: settings.allowMemberTemporarySession },
operationType: 8,
},
{
setting: 'allow_member_create_group',
value: { allowMemberCreateGroup: settings.allowMemberCreateGroup },
operationType: 8,
},
];
let currentAppPrivilegeFlag = initialAppPrivilegeFlag;
let currentGroupFlagExt4 = initialGroupFlagExt4;
for (const requestSetting of requestSettings) {
const param = createGroupDetailInfoV2Param(groupCode);
if (applyGroupManagementSettings(param, requestSetting.value)) {
if (param.filter.appPrivilegeFlag) {
const nextAppPrivilegeFlag = mergeMaskedFlag(
currentAppPrivilegeFlag,
param.modifyInfo.appPrivilegeFlag,
param.modifyInfo.appPrivilegeMask
);
if (requestSetting.operationType === 8 && nextAppPrivilegeFlag === currentAppPrivilegeFlag) continue;
currentAppPrivilegeFlag = nextAppPrivilegeFlag;
// Linux NTQQ's wrapper builds this field from the current complete privilege value.
// Supplying only the targeted bit makes zero-valued clears get acknowledged but ignored.
param.modifyInfo.appPrivilegeFlag = currentAppPrivilegeFlag;
}
if (param.filter.groupFlagExt4) {
const nextGroupFlagExt4 = mergeMaskedFlag(
currentGroupFlagExt4,
param.modifyInfo.groupFlagExt4,
param.modifyInfo.groupFlagExt4Mask
);
if (nextGroupFlagExt4 === currentGroupFlagExt4) continue;
currentGroupFlagExt4 = nextGroupFlagExt4;
param.modifyInfo.groupFlagExt4 = currentGroupFlagExt4;
}
requests.push({ setting: requestSetting.setting, param, operationType: requestSetting.operationType });
}
}
return requests;
}
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter } from '../types';
export function createGroupDetailInfoV2Param (group_code: string): GroupDetailInfoV2Param {
return {
-199
View File
@@ -1,199 +0,0 @@
/**
* QQ空间(Qzone)发说说/上传图片相关的纯数据构造与解析函数
* 不发起任何网络请求,方便单独测试
*/
export interface QzoneUploadImageParams {
uin: string;
skey: string;
pskey: string;
g_tk: string;
base64: string;
}
/**
* 构造上传图片到 QQ 空间的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image
*/
export function buildQzoneUploadImageBody (params: QzoneUploadImageParams): string {
const { uin, skey, pskey, g_tk, base64 } = params;
const backUrls = `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
const query = new URLSearchParams({
filename: 'filename',
uin,
skey,
zzpaneluin: uin,
p_uin: uin,
p_skey: pskey,
uploadtype: '1',
albumtype: '7',
exttype: '0',
refer: 'shuoshuo',
output_type: 'jsonhtml',
charset: 'utf-8',
output_charset: 'utf-8',
upload_hd: '1',
hd_width: '2048',
hd_height: '10000',
hd_quality: '96',
backUrls,
base64: '1',
jsonhtml_callback: 'callback',
picfile: base64,
qzreferrer: `https://user.qzone.qq.com/${uin}/main`,
});
return query.toString();
}
export interface QzoneUploadImageData {
albumid: string;
lloc: string;
type: string;
height: string;
width: string;
url?: string;
}
export interface QzoneUploadImageRawResponse {
code?: number;
msg?: string;
data?: QzoneUploadImageData;
}
/**
* 解析上传图片接口返回的 `frameElement.callback({...});</script>` 包裹响应
*/
export function parseQzoneUploadImageResponseText (raw: string): QzoneUploadImageRawResponse {
const startTag = 'frameElement.callback';
const endTag = '</script>';
const startIdx = raw.indexOf(startTag);
const endIdx = raw.indexOf(endTag);
if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {
throw new Error('QQ空间图片上传响应格式异常');
}
const segment = raw.slice(startIdx + startTag.length, endIdx);
const jsonStart = segment.indexOf('(');
const jsonEnd = segment.lastIndexOf(')');
if (jsonStart === -1 || jsonEnd === -1 || jsonEnd <= jsonStart) {
throw new Error('QQ空间图片上传响应解析失败');
}
const jsonText = segment.slice(jsonStart + 1, jsonEnd);
try {
return JSON.parse(jsonText) as QzoneUploadImageRawResponse;
} catch {
throw new Error('QQ空间图片上传响应JSON解析失败');
}
}
/**
* 依据上传图片返回数据拼接 richval 字段
* 格式: ,albumid,lloc,sloc,type,height,width,,height,width (sloc 与 lloc 一致)
*/
export function toQzoneRichval (data: QzoneUploadImageData): string {
const { albumid, lloc, type, height, width } = data;
return `,${albumid},${lloc},${lloc},${type},${height},${width},,${height},${width}`;
}
export interface QzonePublishParams {
hostuin: string;
content: string;
/** 多张图片使用 \t 拼接后的 richval,无图时不传 */
richval?: string;
ugcRight: number;
/** ugc_right 为 16/128 时必填,多个QQ号使用 | 拼接 */
allowUins?: string;
}
/**
* 构造发表说说的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6
*/
export function buildQzonePublishBody (params: QzonePublishParams): string {
const { hostuin, content, richval, ugcRight, allowUins } = params;
const fields: Record<string, string> = {
syn_tweet_verson: '1',
paramstr: '1',
con: content,
feedversion: '1',
ver: '1',
ugc_right: String(ugcRight),
to_sign: '0',
hostuin,
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostuin}/main`,
};
if (richval) {
fields['richtype'] = '1';
fields['richval'] = richval;
}
if (allowUins) {
fields['allow_uins'] = allowUins;
fields['who'] = '1';
}
return new URLSearchParams(fields).toString();
}
export interface QzonePublishResponse {
subcode?: number;
code?: number;
tid?: string;
t1_tid?: string;
message?: string;
msg?: string;
}
/**
* 解析发表说说接口返回的 JSON, 提取 tid
*/
export function parseQzonePublishResponse (json: QzonePublishResponse): { tid: string; } {
const subcode = json.subcode ?? json.code;
if (subcode !== undefined && subcode !== 0) {
throw new Error(json.message || json.msg || `QQ空间发说说失败, subcode=${subcode}`);
}
const tid = json.t1_tid || json.tid;
if (!tid) {
throw new Error('QQ空间发说说失败, 未返回tid');
}
return { tid };
}
export interface QzoneDeleteParams {
hostuin: string;
tid: string;
}
/**
* 构造删除说说的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6
*/
export function buildQzoneDeleteBody (params: QzoneDeleteParams): string {
const { hostuin, tid } = params;
const fields: Record<string, string> = {
hostuin,
tid,
t1_source: '1',
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostuin}`,
};
return new URLSearchParams(fields).toString();
}
export interface QzoneDeleteResponse {
subcode?: number;
code?: number;
message?: string;
msg?: string;
}
/**
* 解析删除说说接口返回的 JSON
*/
export function parseQzoneDeleteResponse (json: QzoneDeleteResponse): { success: true; } {
const subcode = json.subcode ?? json.code;
if (subcode !== undefined && subcode !== 0) {
throw new Error(json.message || json.msg || `QQ空间删说说失败, subcode=${subcode}`);
}
return { success: true };
}
+55 -265
View File
@@ -18,64 +18,20 @@ export interface BizReq {
iBatchID: number;
iBitmap: number;
iDistinctUse: number;
iNeedFeeds?: number;
iNeedFeeds: number;
iPicHight: number;
iPicWidth: number;
iUploadTime: number;
iUploadType: number;
iUpPicType: number;
iWaterType: number;
mapExt?: MapExt;
mutliPicInfo?: MutliPicInfo;
mapExt: MapExt;
sAlbumID: string;
sAlbumName: string;
sPicDesc: string;
sPicPath: string;
sPicTitle: string;
stExtendInfo?: StExtendInfo;
// 视频主体上传专用
extend_info?: VideoExtendInfo;
iFlag?: number;
iIsFormatF20?: number;
iIsNew?: number;
iIsOriginalVideo?: number;
iPlayTime?: number;
sCoverUrl?: string;
sDesc?: string;
sTitle?: string;
// 视频封面二段上传专用
stExternalMapExt?: StExternalMapExt;
sExif_CameraMaker?: string;
sExif_CameraModel?: string;
sExif_Latitude?: string;
sExif_LatitudeRef?: string;
sExif_Longitude?: string;
sExif_LongitudeRef?: string;
sExif_Time?: string;
}
// 多图同批上传时描述「本批共几张 / 当前第几张」,相册里据此合并成同一条
export interface MutliPicInfo {
iBatUploadNum: string;
iCurUpload: string;
iSuccNum: number;
iFailNum: number;
}
// 视频主体上传用(视频不走 stExtendInfo.mapParams,而是这段扩展信息)
export interface VideoExtendInfo {
video_type: string;
domainid: string;
photo_num: string;
video_num: string;
batch_num: string;
qun_id: string;
}
// 视频封面二段上传用:声明这是客户端上传的封面,且与图片混合在同一条动态里
export interface StExternalMapExt {
is_client_upload_cover: string;
is_pic_video_mix_feeds: string;
stExtendInfo: StExtendInfo;
}
export interface MapExt {
@@ -91,8 +47,6 @@ export interface MapParams {
batch_num: string;
photo_num: string;
video_num: string;
// 视频封面二段上传时用它把封面挂到已上传的视频上
vid?: string;
}
export interface Env {
@@ -106,96 +60,6 @@ export interface Token {
type: number;
}
// 一次上传的批次信息:同批的多张图必须共用 batchId,相册里才会显示成同一条。
export interface QunAlbumBatch {
batchId: number,
count: string,
index: string
}
let lastQunAlbumBatchId = 0;
// 批次号取秒级时间戳。同一秒里发起的两次上传要错开,不然会被相册并成同一条
export function nextQunAlbumBatchId () {
lastQunAlbumBatchId = Math.max(Math.floor(Date.now() / 1000), lastQunAlbumBatchId + 1);
return lastQunAlbumBatchId;
}
// control_req 的外层(鉴权、来源、会话),图片、视频、封面都一样
function buildQunAlbumControlReq (
{ uin, pskey, appid, checksum, check_type, file_len, refer = 'qzone', cmd }: {
uin: string,
pskey: string,
appid: string,
checksum: string,
check_type: number,
file_len: number,
refer?: string,
cmd?: string
},
biz_req: BizReq
): ControlReq {
const req: ControlReq = {
uin,
token: { type: 4, data: pskey, appid: 5 },
appid,
checksum,
check_type,
file_len,
env: { refer, deviceInfo: 'h5' },
model: 0,
biz_req,
session: '',
asy_upload: 0,
};
if (cmd) req.cmd = cmd;
return req;
}
// biz_req 里三种上传都要带的基础字段
function buildQunAlbumBizBase (
{ iUploadType, sAlbumName = '', sAlbumID = '', iBatchID = 0, sPicTitle = '' }: {
iUploadType: number,
sAlbumName?: string,
sAlbumID?: string,
iBatchID?: number,
sPicTitle?: string
}
): BizReq {
return {
sPicTitle,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType,
iUpPicType: 0,
iBatchID,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iUploadTime: Math.floor(Date.now() / 1000),
};
}
// 进相册的那一步(图片、视频封面)要带的群与批次信息
function buildQunAlbumFeedFields (group_id: string, mapParams: MapParams, batchIndex: string) {
return {
iNeedFeeds: 1,
mapExt: { appid: 'qun', userid: group_id },
stExtendInfo: { mapParams },
mutliPicInfo: {
iBatUploadNum: mapParams.batch_num,
iCurUpload: batchIndex,
iSuccNum: 0,
iFailNum: 0,
},
};
}
export function qunAlbumControl ({
uin,
group_id,
@@ -208,8 +72,6 @@ export function qunAlbumControl ({
photo_num = '1',
video_num = '0',
batch_num = '1',
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
}: {
uin: string,
group_id: string,
@@ -221,21 +83,64 @@ export function qunAlbumControl ({
sAlbumID: string,
photo_num?: string,
video_num?: string,
batch_num?: string,
batchId?: number,
batchIndex?: string
batch_num?: string
}
): {
control_req: ControlReq[]
} {
const timestamp = Math.floor(Date.now() / 1000);
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: pic_md5, check_type: 0, file_len: img_size, cmd: 'FileUpload' },
control_req: [
{
...buildQunAlbumBizBase({ iUploadType: 0, sAlbumName, sAlbumID, iBatchID: batchId, sPicTitle: img_name }),
...buildQunAlbumFeedFields(group_id, { photo_num, video_num, batch_num }, batchIndex),
}
)],
uin,
token: {
type: 4,
data: pskey,
appid: 5,
},
appid: 'qun',
checksum: pic_md5,
check_type: 0,
file_len: img_size,
env: {
refer: 'qzone',
deviceInfo: 'h5',
},
model: 0,
biz_req: {
sPicTitle: img_name,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType: 0,
iUpPicType: 0,
iBatchID: timestamp,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iNeedFeeds: 1,
iUploadTime: timestamp,
mapExt: {
appid: 'qun',
userid: group_id,
},
stExtendInfo: {
mapParams: {
photo_num,
video_num,
batch_num,
},
},
},
session: '',
asy_upload: 0,
cmd: 'FileUpload',
}],
};
}
@@ -269,118 +174,3 @@ export function createStreamUpload (
},
};
}
/**
* 视频主体上传的控制体。
*
* 视频这一步不进相册(相册留空,iBatchID 为 0),只是先把视频传成素材;
* 分片响应里拿到 sVid 后,再由封面上传(qunAlbumVideoCoverControl)把视频挂进相册。
*/
export function qunAlbumVideoControl ({
uin,
group_id,
pskey,
video_sha1,
video_size,
play_time = 0,
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
video_sha1: string,
video_size: number,
play_time?: number,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'video_qun', checksum: video_sha1, check_type: 1, file_len: video_size, cmd: 'FileUploadVideo' },
{
...buildQunAlbumBizBase({ iUploadType: 3 }),
sTitle: '',
sDesc: '',
sCoverUrl: '',
iFlag: 0,
iPlayTime: play_time,
iIsNew: 111,
iIsOriginalVideo: 0,
iIsFormatF20: 0,
extend_info: {
video_type: '3',
domainid: '5',
photo_num,
video_num,
batch_num,
qun_id: group_id,
},
}
)],
};
}
/**
* 视频封面上传的控制体。
*
* 按图片上传,但 iUploadType 为 2,并用 mapParams.vid 指向已上传的视频。
* 相册和批次号只在这一步出现,视频是靠封面进的相册。
*/
export function qunAlbumVideoCoverControl ({
uin,
group_id,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size,
vid,
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
sAlbumName: string,
sAlbumID: string,
cover_md5: string,
cover_size: number,
vid: string,
batchId?: number,
batchIndex?: string,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: cover_md5, check_type: 0, file_len: cover_size, refer: 'huodong' },
{
...buildQunAlbumBizBase({ iUploadType: 2, sAlbumName, sAlbumID, iBatchID: batchId }),
...buildQunAlbumFeedFields(group_id, { vid, photo_num, video_num, batch_num }, batchIndex),
// 标明封面由客户端上传,且允许和图片出现在同一条动态里
stExternalMapExt: {
is_client_upload_cover: '1',
is_pic_video_mix_feeds: '1',
},
sExif_CameraMaker: '',
sExif_CameraModel: '',
sExif_Time: '',
sExif_LatitudeRef: '',
sExif_Latitude: '',
sExif_LongitudeRef: '',
sExif_Longitude: '',
}
)],
};
}
+1 -77
View File
@@ -599,10 +599,6 @@
"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"
@@ -610,77 +606,5 @@
"3.2.30-50969": {
"appid": 537376344,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"3.2.30-50969-arm64": {
"appid": 537376345,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"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"
},
"9.9.32-51246": {
"appid": 537376512,
"qua": "V1_WIN_NQ_9.9.32_51246_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"
},
"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"
},
"3.2.32-52194": {
"appid": 537379447,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"3.2.32-52194-arm64": {
"appid": 537379448,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"9.9.35-52804": {
"appid": 537382717,
"qua": "V1_WIN_NQ_9.9.35_52804_GW_B"
},
"9.9.35-52892": {
"appid": 537382819,
"qua": "V1_WIN_NQ_9.9.35_52892_GW_B"
},
"9.9.36-53489": {
"appid": 537391475,
"qua": "V1_WIN_NQ_9.9.36_53489_GW_B"
},
"3.2.33-52892": {
"appid": 537382855,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"3.2.33-52892-arm64": {
"appid": 537382856,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"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"
},
"9.9.36-53644": {
"appid": 537391628,
"qua": "V1_WIN_NQ_9.9.36_53644_GW_B"
}
}
}
-165
View File
@@ -2593,171 +2593,6 @@
"AniStickerType": 1,
"AniStickerPackId": "1",
"AniStickerId": "59"
},
{
"QSid": "450",
"QDes": "/撇嘴",
"EMCode": "10450"
},
{
"QSid": "451",
"QDes": "/色",
"EMCode": "10451"
},
{
"QSid": "452",
"QDes": "/微笑",
"EMCode": "10452"
},
{
"QSid": "453",
"QDes": "/发呆",
"EMCode": "10453"
},
{
"QSid": "454",
"QDes": "/得意",
"EMCode": "10454"
},
{
"QSid": "455",
"QDes": "/害羞",
"EMCode": "10455"
},
{
"QSid": "456",
"QDes": "/闭嘴",
"EMCode": "10456"
},
{
"QSid": "457",
"QDes": "/睡",
"EMCode": "10457"
},
{
"QSid": "458",
"QDes": "/我吗",
"EMCode": "10458"
},
{
"QSid": "459",
"QDes": "/优雅",
"EMCode": "10459"
},
{
"QSid": "460",
"QDes": "/硬撑",
"EMCode": "10460"
},
{
"QSid": "461",
"QDes": "/宕机",
"EMCode": "10461"
},
{
"QSid": "462",
"QDes": "/无语",
"EMCode": "10462"
},
{
"QSid": "463",
"QDes": "/新年快乐",
"EMCode": "10463"
},
{
"QSid": "464",
"QDes": "/马上到",
"EMCode": "10464"
},
{
"QSid": "465",
"QDes": "/拆红包",
"EMCode": "10465"
},
{
"QSid": "466",
"QDes": "/羞羞哒",
"EMCode": "10466"
},
{
"QSid": "467",
"QDes": "/摇花手",
"EMCode": "10467"
},
{
"QSid": "468",
"QDes": "/失眠",
"EMCode": "10468"
},
{
"QSid": "469",
"QDes": "/坚毅",
"EMCode": "10469"
},
{
"QSid": "470",
"QDes": "/马到成功",
"EMCode": "10470"
},
{
"QSid": "472",
"QDes": "/心动",
"EMCode": "10472"
},
{
"QSid": "474",
"QDes": "/给你一拳",
"EMCode": "10474"
},
{
"QSid": "475",
"QDes": "/干饭",
"EMCode": "10475"
},
{
"QSid": "476",
"QDes": "/不是吧",
"EMCode": "10476"
},
{
"QSid": "477",
"QDes": "/你懂的",
"EMCode": "10477"
},
{
"QSid": "478",
"QDes": "/对的对的",
"EMCode": "10478"
},
{
"QSid": "479",
"QDes": "/不对不对",
"EMCode": "10479"
},
{
"QSid": "480",
"QDes": "/散味儿",
"EMCode": "10480"
},
{
"QSid": "481",
"QDes": "/学习",
"EMCode": "10481"
},
{
"QSid": "482",
"QDes": "/热化了",
"EMCode": "10482"
},
{
"QSid": "483",
"QDes": "/略",
"EMCode": "10483"
},
{
"QSid": "484",
"QDes": "/比爱心",
"EMCode": "10484"
}
],
"emoji": [
+1 -69
View File
@@ -278,73 +278,5 @@
"3.2.30-50969-arm64": {
"send": "43A4804",
"recv": "1608CC8"
},
"3.2.31-51102-x64": {
"send": "63F4910",
"recv": "34B9F90"
},
"3.2.31-51102-arm64": {
"send": "43A48E4",
"recv": "1608D98"
},
"9.9.32-51246-x64": {
"send": "B2E37C",
"recv": "209C7D9"
},
"3.2.32-51802-x64": {
"send": "6B9B790",
"recv": "38F68F0"
},
"3.2.32-51802-arm64": {
"send": "48CB078",
"recv": "17D620C"
},
"9.9.33-51802-x64": {
"send": "BDE15F",
"recv": "237BC91"
},
"9.9.33-52230-x64": {
"send": "BF2B5F",
"recv": "23BB4DD"
},
"3.2.32-52194-x64": {
"send": "6C45D20",
"recv": "393DE00"
},
"3.2.32-52194-arm64": {
"send": "493FAD8",
"recv": "17EA1DC"
},
"9.9.35-52804-x64": {
"send": "C3614F",
"recv": "246F481"
},
"9.9.35-52892-x64": {
"send": "C361DF",
"recv": "246F3A1"
},
"9.9.36-53489-x64": {
"send": "C3ED0F",
"recv": "24A6235"
},
"3.2.33-52892-x64": {
"send": "6DDB4C0",
"recv": "39DA860"
},
"3.2.33-52892-arm64": {
"send": "4A5D658",
"recv": "1813A34"
},
"3.2.34-53644-x64": {
"send": "6E5AB20",
"recv": "3A12CD0"
},
"3.2.34-53644-arm64": {
"send": "4AABA5C",
"recv": "182C534"
},
"9.9.36-53644-x64": {
"send": "C3EE2F",
"recv": "24A6355"
}
}
}
+4 -72
View File
@@ -767,9 +767,9 @@
"send": "3155200",
"recv": "3158788"
},
"3.2.30-50828-arm64": {
"send": "74C3070",
"recv": "74C6A20"
"9.9.32-50828-arm64": {
"send": "4327764",
"recv": "15E3184"
},
"3.2.30-50828-x64": {
"send": "B5D0FC0",
@@ -786,73 +786,5 @@
"3.2.30-50969-arm64": {
"send": "75BD1D0",
"recv": "75C0B80"
},
"3.2.31-51102-x64": {
"send": "B739780",
"recv": "B73D220"
},
"3.2.31-51102-arm64": {
"send": "75BD390",
"recv": "75C0D40"
},
"9.9.32-51246-x64": {
"send": "3199680",
"recv": "319CC08"
},
"3.2.32-51802-x64": {
"send": "C687460",
"recv": "C68AF00"
},
"3.2.32-51802-arm64": {
"send": "800A230",
"recv": "800DBE0"
},
"9.9.33-51802-x64": {
"send": "360A0D8",
"recv": "360D88C"
},
"9.9.33-52230-x64": {
"send": "367FE18",
"recv": "36835CC"
},
"3.2.32-52194-x64": {
"send": "C7DBF80",
"recv": "C7DFA20"
},
"3.2.32-52194-arm64": {
"send": "80F36D0",
"recv": "80F7080"
},
"9.9.35-52804-x64": {
"send": "37C3298",
"recv": "37C6A4C"
},
"9.9.35-52892-x64": {
"send": "37C30D8",
"recv": "37C688C"
},
"9.9.36-53489-x64": {
"send": "38253B0",
"recv": "3828BF0"
},
"3.2.33-52892-x64": {
"send": "CB06D60",
"recv": "CB0A800"
},
"3.2.33-52892-arm64": {
"send": "832ECA0",
"recv": "8332650"
},
"3.2.34-53644-x64": {
"send": "CBF25A0",
"recv": "CBF60E0"
},
"3.2.34-53644-arm64": {
"send": "83D1BD0",
"recv": "83D5610"
},
"9.9.36-53644-x64": {
"send": "38255F0",
"recv": "3828E30"
}
}
}
@@ -21,13 +21,13 @@ export interface VideoInfo {
/** Video duration in seconds */
duration: number;
/** Generated thumbnail image format */
/** Container format name (e.g., "mp4", "mkv", "avi") */
format: string;
/** Video codec name (e.g., "h264", "hevc", "vp9") */
videoCodec: string;
/** First frame thumbnail as JPEG image buffer */
/** First frame thumbnail as BMP image buffer */
image: Buffer;
}
@@ -6,7 +6,6 @@ import { platform } from 'node:os';
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory';
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
if (process.platform === 'win32' && binaryPath) {
@@ -95,15 +94,6 @@ export class FFmpegService {
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 直接发送到 QQ kernel 的旧视频元素使用 PNG 缩略图。
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
*/
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 转换音频文件
*/
+3 -3
View File
@@ -187,14 +187,14 @@ export class LogWrapper implements ILogWrapper {
_log (level: LogLevel, ...args: any[]) {
if (this.consoleLogEnabled || this.fileLogEnabled) {
// eslint-disable-next-line no-control-regex
const message = this.formatMsg(args).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|\x1B\[[0-?]*[ -/]*[@-~]|\x1B/g, '');
const message = this.formatMsg(args);
if (this.consoleLogEnabled && this.fileLogEnabled) {
this.logger.log(level, message);
} else if (this.consoleLogEnabled) {
this.logger.log(level, message);
} else if (this.fileLogEnabled) {
this.logger.log(level, message);
// eslint-disable-next-line no-control-regex
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
}
logSubscription.notify(JSON.stringify({ level, message }));
}
@@ -1,58 +0,0 @@
export interface OfflineRecoveryOptions {
// 当前账号是否在线
isOnline: () => boolean;
// 刚下线:同步 WebUI 状态
onOffline: (tips: string) => void;
// 静默离线期间账号自己恢复了,不需要重启
onRecovered: () => void;
// 重启 Worker;返回 false 或抛错表示失败,之后可以再次触发
restart: (tips: string) => Promise<boolean>;
// 被踢下线后多久重启。常规状态轮询为 3 秒,留出一个轮询周期,确保浏览器先清除旧二维码
kickedDelayMs?: number;
// 静默离线后多久重启。网络短暂断开时 QQ 也可能报离线,先给它自己重连的机会,
// 不然一次网络抖动就会把整个 Worker 重启掉
selfOfflineDelayMs?: number;
}
/**
* 下线恢复:被踢下线(KickedOffLine)和静默离线(SelfOffline)共用。
* 返回的函数在每次收到下线事件时调用,allowSelfRecovery 为 true 表示静默离线。
*/
export function createOfflineRecovery ({
isOnline,
onOffline,
onRecovered,
restart,
kickedDelayMs = 3_500,
selfOfflineDelayMs = 60_000,
}: OfflineRecoveryOptions) {
let restartRequested = false;
let selfRecoveryTimer: ReturnType<typeof setTimeout> | undefined;
return (tips: string, allowSelfRecovery: boolean) => {
onOffline(tips);
if (restartRequested) {
// 被踢时离线状态可能先到:还在等静默离线自行恢复的话,不用再等了
if (allowSelfRecovery || !selfRecoveryTimer) return;
clearTimeout(selfRecoveryTimer);
}
restartRequested = true;
// 不在 RefreshQRcode 请求里直接重启 Worker,否则请求在返回前就被中断,
// 浏览器只能得到 ERR_EMPTY_RESPONSE;延后调度也让前端先看到「二维码已清空、正在恢复」
const timer = setTimeout(() => {
selfRecoveryTimer = undefined;
if (allowSelfRecovery && isOnline()) {
restartRequested = false;
onRecovered();
return;
}
restart(tips).then((ok) => {
if (!ok) restartRequested = false;
}, () => {
restartRequested = false;
});
}, allowSelfRecovery ? selfOfflineDelayMs : kickedDelayMs);
selfRecoveryTimer = allowSelfRecovery ? timer : undefined;
};
}
+2 -3
View File
@@ -79,11 +79,10 @@ export class QQBasicInfoWrapper {
getAppidV2 (): { appid: string; qua: string; } {
// 通过已有表 性能好
const appidTable = AppidTable as unknown as QQAppidTableType;
const appidTbale = AppidTable as unknown as QQAppidTableType;
const fullVersion = this.getFullQQVersion();
if (fullVersion) {
// 同一 Linux 版本的 x64 和 arm64 使用不同的 AppID,优先匹配架构。
const data = appidTable[`${fullVersion}-${process.arch}`] ?? appidTable[fullVersion];
const data = appidTbale[fullVersion];
if (data) {
return data;
}
+1 -11
View File
@@ -107,20 +107,10 @@ export class RkeyManager {
for (const url of availableUrls) {
try {
let temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
if (typeof temp === 'object' && temp !== null && 'retcode' in temp) {
if ('retcode' in temp) {
// 支持Onebot Ret风格
temp = (temp as unknown as OneBotApiRet).data;
}
if (
typeof temp?.group_rkey !== 'string' ||
typeof temp?.private_rkey !== 'string' ||
typeof temp?.expired_time !== 'number' ||
temp.group_rkey.length <= 6 ||
temp.private_rkey.length <= 6 ||
temp.expired_time <= 0
) {
throw new Error('Rkey 服务返回格式无效:group_rkey/private_rkey/expired_time 缺失或不合法');
}
this.rkeyData = {
group_rkey: temp.group_rkey.slice(6),
private_rkey: temp.private_rkey.slice(6),
+7 -30
View File
@@ -59,30 +59,12 @@ export enum NapCatCoreWorkingEnv {
Framework = 2,
}
function dlopenWrapper (wrapperPath: string): WrapperNodeApi {
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
try {
process.dlopen(nativemodule, wrapperPath);
} catch (error) {
// QQNT.dll 依赖媒体基础(mfplat.dll 等),Windows Server 默认不装这个组件。
// 缺了它系统只会报 The specified module could not be found,看不出缺的是什么
const mfplatPath = path.join(process.env['SystemRoot'] || 'C:\\Windows', 'System32', 'mfplat.dll');
if (os.platform() === 'win32' && !fs.existsSync(mfplatPath)) {
throw new Error(
'加载 wrapper.node 失败:系统缺少「媒体基础」组件(找不到 mfplat.dll),Windows Server 默认不安装它。' +
'请在服务器管理器的「添加角色和功能」里勾选「媒体基础」,' +
'或在管理员 PowerShell 中执行 Install-WindowsFeature Server-Media-Foundation,重启后再启动。' +
`原始错误:${(error as Error).message}`
);
}
throw error;
}
return nativemodule.exports;
}
export function loadQQWrapper (execPath: string | undefined, QQVersion: string): WrapperNodeApi {
if (process.env['NAPCAT_WRAPPER_PATH']) {
return dlopenWrapper(process.env['NAPCAT_WRAPPER_PATH']);
const wrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperPath);
return nativemodule.exports;
}
if (!execPath) {
throw new Error('无法加载Wrapper,execPath未定义');
@@ -103,9 +85,10 @@ export function loadQQWrapper (execPath: string | undefined, QQVersion: string):
if (!fs.existsSync(wrapperNodePath)) {
wrapperNodePath = path.join(path.dirname(execPath), `./resources/app/versions/${QQVersion}/wrapper.node`);
}
const exports = dlopenWrapper(wrapperNodePath);
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperNodePath);
process.env['NAPCAT_WRAPPER_PATH'] = wrapperNodePath;
return exports;
return nativemodule.exports;
}
export function getMajorPath (execPath: string, QQVersion: string): string {
// major.node
@@ -278,14 +261,8 @@ export class NapCatCore {
};
profileListener.onSelfStatusChanged = (Info: SelfStatusInfo) => {
if (Info.status === 20) {
// 静默离线:服务端判定会话失效,但不会下发 KickedOffLine 通知。
// 仅在 在线 -> 离线 的跳变上广播一次,供上层复用下线恢复链路。
const wasOnline = this.selfInfo.online === true;
this.selfInfo.online = false;
this.context.logger.log('账号状态变更为离线');
if (wasOnline) {
this.event.emit('SelfOffline', '[SelfOffline] 账号状态变更为离线(未收到 KickedOffLine 通知)');
}
} else {
this.selfInfo.online = true;
}
@@ -19,7 +19,6 @@ import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
import { gunzipSync } from 'zlib';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
export class PacketOperationContext {
private readonly context: PacketContext;
@@ -106,7 +105,15 @@ export class PacketOperationContext {
.filter(Boolean)
);
const res = await Promise.allSettled(reqList);
assertUploadResults(res, this.context.logger);
const failedCount = res.filter((r) => r.status === 'rejected').length;
if (failedCount > 0) {
this.context.logger.warn(`上传资源${res.length}个,失败${failedCount}个`);
res.forEach((result, index) => {
if (result.status === 'rejected') {
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
}
});
}
}
async UploadImage (img: PacketMsgPicElement) {
@@ -233,10 +240,9 @@ export class PacketOperationContext {
}
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
// await this.SendPreprocess(msg, groupUin);
// 遍历上传资源(跳过已有原始数据的项)
await Promise.all(msg.filter(item => item.actionMsg).map(async (item) => {
await this.SendPreprocess(item.actionMsg!, groupUin);
}));
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.UploadForwardMsg.parse(resp);
@@ -364,23 +370,6 @@ export class PacketOperationContext {
}
return element;
}
if (element.videoElement && rawElem?.commonElem?.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(rawElem.commonElem.pbElem);
const index = extra?.msgInfoBody[0]?.index;
if (!index) return element;
if (msg?.responseHead.grp !== undefined) {
element.videoElement = {
...element.videoElement,
filePath: await this.GetGroupVideoUrl(msg.responseHead.grp.groupUin ?? 0, index),
};
} else {
element.videoElement = {
...element.videoElement,
filePath: await this.GetVideoUrl(this.context.napcore.basicInfo.uid, index),
};
}
return element;
}
return element;
})
);
@@ -1,26 +0,0 @@
export interface UploadResultLogger {
warn (message: string): unknown;
error (message: string): unknown;
}
export function assertUploadResults (
results: PromiseSettledResult<unknown>[],
logger: UploadResultLogger
): void {
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failures.length === 0) return;
logger.warn(`上传资源${results.length}个,失败${failures.length}个`);
results.forEach((result, index) => {
if (result.status === 'rejected') {
const reason = result.reason instanceof Error
? result.reason.stack ?? result.reason.message
: String(result.reason);
logger.error(`上传第${index + 1}个资源失败:${reason}`);
}
});
throw new AggregateError(
failures.map(result => result.reason),
`上传转发消息资源失败:${failures.length}/${results.length}`
);
}
@@ -3,7 +3,5 @@ import { TypedEventEmitter } from './typeEvent';
export interface AppEvents {
'event:emoji_like': { groupId: string; senderUin: string; emojiId: string, msgSeq: string, isAdd: boolean, count: number; };
KickedOffLine: string;
// 静默离线:服务端会话已失效,但没有下发 KickedOffLine 通知
SelfOffline: string;
}
export const appEvent = new TypedEventEmitter<AppEvents>();
@@ -21,11 +21,8 @@ import { PacketClientContext } from '@/napcat-core/packet/context/clientContext'
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
import { calculateFileMD5 } from 'napcat-common/src/file';
import { randomUUID } from 'node:crypto';
import { imageSizeFallBack } from 'napcat-image-size/src/index';
export const BlockSize = 1024 * 1024;
const VIDEO_THUMBNAIL_MAX_BYTES = 1024 * 1024;
interface HighwayServerAddr {
ip: string;
@@ -113,37 +110,22 @@ export class PacketHighwayContext {
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
}
const cleanupThumbPaths: string[] = [];
// 如果缺少视频缩略图,自动生成一个
let tempThumbPath: string | null = null;
let thumbExists = false;
if (video.thumbPath) {
try {
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
thumbExists = true;
} catch {
thumbExists = false;
}
}
if (!video.thumbPath || !thumbExists) {
tempThumbPath = await this.ensureVideoThumb(video);
}
try {
let thumbExists = false;
if (video.thumbPath) {
try {
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
thumbExists = true;
} catch {
thumbExists = false;
}
}
let shouldGenerateThumb = !video.thumbPath || !thumbExists;
if (!shouldGenerateThumb) {
try {
await this.updateVideoThumbInfo(video);
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
this.logger.warn(`[Highway] Video thumbnail is too large: ${video.thumbSize} bytes, regenerating`);
shouldGenerateThumb = true;
}
} catch (e) {
this.logger.warn(`[Highway] Failed to inspect video thumbnail, regenerating. Reason: ${e instanceof Error ? e.message : e}`);
shouldGenerateThumb = true;
}
}
if (shouldGenerateThumb) {
cleanupThumbPaths.push(await this.ensureVideoThumb(video));
}
video.businessType = peer.chatType === ChatType.KCHATTYPEGROUP ? 21 : 11;
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
await this.uploadGroupVideo(+peer.peerUid, video);
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
@@ -152,21 +134,23 @@ export class PacketHighwayContext {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
} finally {
await Promise.allSettled(cleanupThumbPaths.map(async (thumbToClean) => {
try {
await fs.promises.unlink(thumbToClean);
this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
}
}
}));
// 清理临时生成的缩略图文件
if (tempThumbPath) {
const thumbToClean = tempThumbPath;
fs.promises.unlink(thumbToClean)
.then(() => this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`))
.catch((e) => {
// 文件不存在时忽略错误
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
}
});
}
}
}
/**
* 使用当前 FFmpeg 适配器生成符合 QQ 大小限制的视频缩略图
* 确保视频缩略图存在,如果不存在则自动生成
* @returns 生成的临时缩略图路径,用于后续清理
*/
private async ensureVideoThumb (video: PacketMsgVideoElement): Promise<string> {
@@ -177,10 +161,9 @@ export class PacketHighwayContext {
// 生成缩略图路径
const videoDir = path.dirname(video.filePath);
const videoBasename = path.basename(video.filePath, path.extname(video.filePath));
const thumbPath = path.join(videoDir, `${videoBasename}_thumb_${randomUUID()}.jpg`);
const thumbPath = path.join(videoDir, `${videoBasename}_thumb.png`);
this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
video.thumbPath = thumbPath;
try {
// 尝试使用 FFmpeg 提取视频缩略图
@@ -191,36 +174,26 @@ export class PacketHighwayContext {
} catch {
throw new Error('FFmpeg failed to generate thumbnail');
}
await this.updateVideoThumbInfo(video);
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
throw new Error(`generated thumbnail is too large: ${video.thumbSize} bytes`);
}
} catch (e) {
// FFmpeg 失败时(包括未初始化的情况)使用默认缩略图
this.logger.warn(`[Highway] Failed to extract thumbnail, using default. Reason: ${e instanceof Error ? e.message : e}`);
await fs.promises.writeFile(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
await this.updateVideoThumbInfo(video);
}
// 更新视频元素的缩略图信息
video.thumbPath = thumbPath;
const thumbStat = await fs.promises.stat(thumbPath);
video.thumbSize = thumbStat.size;
video.thumbMd5 = await calculateFileMD5(thumbPath);
// 默认缩略图尺寸(与 defaultVideoThumbB64 匹配的尺寸)
if (!video.thumbWidth) video.thumbWidth = 240;
if (!video.thumbHeight) video.thumbHeight = 383;
this.logger.debug(`[Highway] Video thumb info set: path=${thumbPath}, size=${video.thumbSize}, md5=${video.thumbMd5}`);
return thumbPath;
}
private async updateVideoThumbInfo (video: PacketMsgVideoElement): Promise<void> {
if (!video.thumbPath) {
throw new Error('video.thumbPath is empty, cannot inspect thumbnail');
}
const [thumbStat, thumbMd5, dimensions] = await Promise.all([
fs.promises.stat(video.thumbPath),
calculateFileMD5(video.thumbPath),
imageSizeFallBack(video.thumbPath),
]);
video.thumbSize = thumbStat.size;
video.thumbMd5 = thumbMd5;
video.thumbWidth = dimensions.width;
video.thumbHeight = dimensions.height;
this.logger.debug(`[Highway] Video thumbnail ready: ${dimensions.width}x${dimensions.height}, ${thumbStat.size} bytes`);
}
async uploadPtt (peer: Peer, ptt: PacketMsgPttElement): Promise<void> {
await this.checkAvailable();
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
@@ -323,17 +296,13 @@ export class PacketHighwayContext {
const req = trans.UploadGroupVideo.build(groupUin, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadGroupVideo.parse(resp);
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
if (!videoIndex || !thumbIndex) {
throw new Error('[Highway] uploadGroupVideo response is missing video or thumbnail MsgInfo');
}
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: videoIndex.fileUuid,
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -355,15 +324,16 @@ export class PacketHighwayContext {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile?.uKey && subFile.uKey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -379,7 +349,7 @@ export class PacketHighwayContext {
extend
);
} else {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
@@ -391,17 +361,13 @@ export class PacketHighwayContext {
const req = trans.UploadPrivateVideo.build(peerUid, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadPrivateVideo.parse(resp);
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
if (!videoIndex || !thumbIndex) {
throw new Error('[Highway] uploadC2CVideo response is missing video or thumbnail MsgInfo');
}
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: videoIndex.fileUuid,
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -423,15 +389,16 @@ export class PacketHighwayContext {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile?.uKey && subFile.uKey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -447,7 +414,7 @@ export class PacketHighwayContext {
extend
);
} else {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
@@ -4,8 +4,6 @@ import {
MessageElement,
Peer,
RawMessage,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -17,7 +15,7 @@ import {
SendReplyElement,
SendTextElement,
SendVideoElement,
} from '@/napcat-core/types/element';
} from '@/napcat-core/index';
import {
IPacketMsgElement,
PacketMsgAtElement,
@@ -160,8 +158,7 @@ export class PacketMsgConverter {
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
const converters = [PacketMsgTextElement.parseElement,
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement,
PacketMsgVideoElement.parseElement, PacketMsgPicElement.parseElement];
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
return msg.map((element) => {
for (const converter of converters) {
const result = converter(element);
+6 -56
View File
@@ -20,11 +20,7 @@ import {
FaceType,
MessageElement,
NTMsgAtType,
NTVideoType,
PicType,
Peer,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -36,7 +32,8 @@ import {
SendMultiForwardMsgElement,
SendTextElement,
SendVideoElement,
} from '@/napcat-core/types/element';
Peer,
} from '@/napcat-core/index';
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
@@ -390,10 +387,8 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem?.commonElem?.serviceType === 48 &&
[10, 20].includes(elem.commonElem.businessType ?? 0) &&
elem.commonElem.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
const msgInfoBody = extra.msgInfoBody[0];
const index = msgInfoBody?.index;
return [{
@@ -411,7 +406,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
summary: '[图片]',
thumbPath: new Map(),
},
elementType: ElementType.PIC,
elementType: ElementType.UNKNOWN,
elementId: '',
}, elem];
}
@@ -451,13 +446,8 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
}
export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
fileName: string;
fileSize?: string;
filePath?: string;
fileTime: number;
fileFormat: NTVideoType;
fileWidth?: number;
fileHeight?: number;
thumbSize?: number;
thumbPath?: string;
fileMd5?: string;
@@ -466,18 +456,12 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
thumbSha1?: string;
thumbWidth?: number;
thumbHeight?: number;
businessType: 11 | 21 = 21;
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
constructor (element: SendVideoElement) {
super(element);
this.fileName = element.videoElement.fileName;
this.fileSize = element.videoElement.fileSize;
this.filePath = element.videoElement.filePath;
this.fileTime = Math.max(0, Math.round(element.videoElement.fileTime ?? 0));
this.fileFormat = element.videoElement.fileFormat ?? NTVideoType.VIDEO_FORMAT_MP4;
this.fileWidth = element.videoElement.fileWidth;
this.fileHeight = element.videoElement.fileHeight;
this.thumbSize = element.videoElement.thumbSize;
this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
this.fileMd5 = element.videoElement.videoMd5;
@@ -496,45 +480,11 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
commonElem: {
serviceType: 48,
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
businessType: this.businessType,
businessType: 21,
},
}];
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem?.commonElem?.serviceType !== 48 ||
![11, 21].includes(elem.commonElem.businessType ?? 0) ||
!elem.commonElem.pbElem) {
return undefined;
}
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
const videoIndex = extra.msgInfoBody[0]?.index;
const thumbIndex = extra.msgInfoBody[1]?.index;
if (!videoIndex) return undefined;
return [{
videoElement: {
filePath: '',
fileName: videoIndex.info.fileName || videoIndex.info.fileHash,
videoMd5: videoIndex.info.fileHash,
thumbMd5: thumbIndex?.info.fileHash,
fileTime: videoIndex.info.time,
fileFormat: (videoIndex.info.type.videoFormat || NTVideoType.VIDEO_FORMAT_MP4) as NTVideoType,
fileSize: String(videoIndex.info.fileSize),
fileWidth: videoIndex.info.width,
fileHeight: videoIndex.info.height,
thumbWidth: thumbIndex?.info.width,
thumbHeight: thumbIndex?.info.height,
thumbSize: thumbIndex?.info.fileSize,
thumbPath: new Map(),
fileUuid: videoIndex.fileUuid,
busiType: 0,
subBusiType: 0,
},
elementType: ElementType.VIDEO,
elementId: '',
}, elem];
};
override toPreview (): string {
return '[视频]';
}
@@ -33,16 +33,16 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: video.fileName || 'video.mp4',
fileName: 'nya.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: video.fileFormat,
videoFormat: 0,
voiceFormat: 0,
},
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
height: 0,
width: 0,
time: 0,
original: 0,
},
subFileType: 0,
@@ -51,7 +51,7 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
fileName: 'nya.jpg',
type: {
type: 1,
picFormat: 0,
@@ -34,16 +34,16 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: video.fileName || 'video.mp4',
fileName: 'nya.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: video.fileFormat,
videoFormat: 0,
voiceFormat: 0,
},
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
height: 0,
width: 0,
time: 0,
original: 0,
},
subFileType: 0,
@@ -52,7 +52,7 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
fileName: 'nya.jpg',
type: {
type: 1,
picFormat: 0,
-2
View File
@@ -118,8 +118,6 @@ export interface VideoElement {
thumbSize?: number; // byte
fileFormat?: NTVideoType; // 2表示mp4 参考下面条目
fileSize?: string; // byte
fileWidth?: number;
fileHeight?: number;
thumbWidth?: number;
thumbHeight?: number;
busiType?: 0; //
-14
View File
@@ -74,20 +74,6 @@ export interface EXTInfo {
groupSquareSwitch: number;
}
export type GroupMemberInvitePolicy =
| 'disabled'
| 'require_approval'
| 'no_approval'
| 'no_approval_under_100';
export interface GroupManagementSettings {
memberInvite?: GroupMemberInvitePolicy;
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
allowMemberCreateGroup?: boolean;
newMembersSeeRecentHistory?: boolean;
}
export interface GroupGuildIDS {
guildIds: any[];
}
-2
View File
@@ -78,7 +78,6 @@ export interface WebApiGroupNoticeFeed {
remind_ts: number
tip_window_type: number
confirm_required: number
inst_no_pinned?: number // 仅 inst 条目有:0 = 置顶中,1 = 未置顶
};
read_num: number;
is_read: number;
@@ -93,7 +92,6 @@ export interface WebApiGroupNoticeRet {
read_only: number
role: number
feeds: WebApiGroupNoticeFeed[]
inst?: WebApiGroupNoticeFeed[] // 「发给新成员」类公告,不在 feeds 里
group: {
group_id: number
class_ext: number
+1 -5
View File
@@ -1,5 +1 @@
@echo off
setlocal
cd /d "%~dp0" || exit /b 1
"%~dp0node.exe" "%~dp0index.js" %*
exit /b %errorlevel%
node.exe ./index.js
+1 -2
View File
@@ -1,7 +1,6 @@
const process = require('process');
const os = require('os');
const path = require('path');
const { pathToFileURL } = require('url');
// 保存原始dlopen
const dlopenOrig = process.dlopen;
@@ -51,7 +50,7 @@ async function initializeNapCat () {
console.log('[NapCat] [Info] 开始初始化NapCat');
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework, getWebUiUrl } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
const { NCoreInitFramework, getWebUiUrl } = await import('file://' + path.join(currentPath, './napcat.mjs'));
getWebUiUrlFunc = getWebUiUrl;
await NCoreInitFramework(wrapperSession, wrapperLoginService, (callback) => { ncCallback = callback; });
} catch (error) {
+4 -66
View File
@@ -9,7 +9,6 @@ import { logSubscription, LogWrapper } from 'napcat-core/helper/log';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
import { InstanceContext, loadQQWrapper, NapCatCore, NapCatCoreWorkingEnv, NodeIKernelLoginListener, NodeIKernelLoginService, NodeIQQNTWrapperSession, SelfInfo, WrapperNodeApi } from '@/napcat-core';
import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
import { createOfflineRecovery } from '@/napcat-core/helper/offline-recovery';
import { statusHelperSubscription } from '@/napcat-core/helper/status';
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
@@ -106,13 +105,6 @@ export async function NCoreInitFramework (
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
const oneBotContext = WebUiDataRuntime.getOneBotContext();
if (oneBotContext?.core?.selfInfo) {
oneBotContext.core.selfInfo.online = true;
WebUiDataRuntime.setQQLoginPhase('ready');
} else {
WebUiDataRuntime.setQQLoginPhase('initializing');
}
await new Promise<void>(resolve => {
registerInitCallback(() => resolve());
});
@@ -126,8 +118,6 @@ export async function NCoreInitFramework (
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('waiting_qrcode');
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
};
@@ -156,14 +146,9 @@ export async function NCoreInitFramework (
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
WebUiDataRuntime.setQQNewLoginList(list);
}).catch(e => logger.logError('[NapCat] [Framework] 获取登录列表失败:', e));
if (!loginContext.isLogined) {
const requested = loginService.getQRCodePicture();
logger.logWarn('[NapCat] [Framework] 登录服务连接完成,正在获取二维码', { requested, msfStatus: loginService.getMsfStatus() });
}
};
loginListener.onQRCodeSessionUserScaned = () => {
WebUiDataRuntime.setQQLoginPhase('qrcode_scanned');
logger.log('[NapCat] [Framework] 二维码已被扫描,等待确认...');
};
@@ -209,44 +194,12 @@ export async function NCoreInitFramework (
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
// 监听下线并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
// KickedOffLine:账号被踢下线;SelfOffline:静默离线(服务端会话语义失效但无通知)。
// 两者复用同一条恢复链路:同步 WebUI -> 重启 Worker -> 快速登录。
const handleOffline = createOfflineRecovery({
isOnline: () => loaderObject.core.selfInfo.online === true,
onOffline: (tips) => {
WebUiDataRuntime.setQQLoginStatus(false);
// 下线后的二维码已失效,绝不能继续交给页面展示或扫码。
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
},
onRecovered: () => {
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('ready');
},
restart: async (tips) => {
try {
const restartResult = await WebUiDataRuntime.requestRestartProcess();
logger.logWarn('[NapCat] [Framework] 账号已离线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (restartResult.result) return true;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
} catch (error) {
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
}
return false;
},
// 监听下线通知并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
loaderObject.core.event.on('KickedOffLine', () => {
WebUiDataRuntime.setQQLoginStatus(false);
});
loaderObject.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
loaderObject.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
}
function registerWebUiLoginCallbacks (
@@ -256,22 +209,7 @@ function registerWebUiLoginCallbacks (
) {
// 刷新二维码
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
loginContext.isLogined = false;
const msfStatus = loginService.getMsfStatus();
if (msfStatus === 2) {
WebUiDataRuntime.setQQLoginPhase('reconnecting');
const connected = loginService.connect();
logger.logWarn('[NapCat] [Framework] 登录服务离线,正在重连以获取二维码', { connected, msfStatus });
if (!connected) {
throw new Error('QQ 登录服务无法重新连接');
}
return;
}
const requested = loginService.getQRCodePicture();
logger.logWarn('[NapCat] [Framework] 请求刷新二维码', { requested, msfStatus });
if (!requested) {
throw new Error('QQ 未接受二维码刷新请求');
}
loginService.getQRCodePicture();
});
// 快速登录
+1 -2
View File
@@ -1,6 +1,5 @@
// 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');
@@ -13,7 +12,7 @@ async function initializeNapCat (session, loginService, registerCallback) {
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
const { NCoreInitFramework } = await import('file://' + path.join(currentPath, './napcat.mjs'));
await NCoreInitFramework(session, loginService, (callback) => { registerCallback(callback); });
} catch (error) {
console.log('[NapCat] [Error] 初始化NapCat', error);
@@ -1,10 +1,8 @@
@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 (
@@ -29,4 +27,4 @@ set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
pause
pause
+4 -6
View File
@@ -1,10 +1,8 @@
@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"
@@ -26,4 +24,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.
Binary file not shown.
@@ -42,12 +42,4 @@ export const ExtendsActionsExamples = {
payload: { group_id: '123456', user_id: '123456789', special_title: '头衔' },
response: null,
},
SendQzoneMsg: {
payload: { content: '今天天气不错', images: [], ugc_right: 1, target_uins: [] },
response: { tid: '1234567890abcdef1234567890' },
},
DeleteQzoneMsg: {
payload: { tid: '1234567890abcdef1234567890' },
response: null,
},
};
@@ -1,21 +1,4 @@
export const GroupActionsExamples = {
SetGroupMemberInvitePolicy: {
payload: { group_id: '123456', policy: 'require_approval' },
response: null,
},
SetGroupMemberPermissions: {
payload: {
group_id: '123456',
allow_member_upload_album: true,
allow_member_temporary_session: true,
allow_member_create_group: true,
},
response: null,
},
SetGroupNewMemberHistoryVisibility: {
payload: { group_id: '123456', visible: true },
response: null,
},
DelEssenceMsg: {
payload: { message_id: 123456 },
response: null,
@@ -1,26 +0,0 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
tid: Type.String({ description: '说说 tid (来自 get_qzone_msg_list / send_qzone_msg)' }),
});
type PayloadType = Static<typeof PayloadSchema>;
export class DeleteQzoneMsg extends OneBotAction<PayloadType, void> {
override actionName = ActionName.DeleteQzoneMsg;
override actionSummary = '删除QQ空间说说';
override actionDescription = '删除QQ空间(Qzone)的一条说说, 按 tid 删除';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.DeleteQzoneMsg.payload;
override returnExample = ExtendsActionsExamples.DeleteQzoneMsg.response;
override payloadSchema = PayloadSchema;
override returnSchema = Type.Null();
async _handle (payload: PayloadType): Promise<void> {
await this.core.apis.WebApi.deleteQzoneMsg(payload.tid);
}
}
@@ -1,51 +0,0 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()], { description: '群号' }),
need_short_url: Type.Optional(Type.Union([Type.Boolean(), Type.String()], { default: true, description: '是否返回短链 (qm.qq.com/q/xxx),false 返回完整 universal-share 链接' })),
src_id: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 73, description: '分享来源 ID' })),
additional_param: Type.Optional(Type.String({ default: '', description: '附加参数' })),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
url: Type.String({ description: '群分享链接' }),
}, { description: '群分享链接' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupShareLink extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetGroupShareLink;
override actionSummary = '获取群分享链接';
override actionDescription = '通过 NTQQ 原生 getJoinGroupLink 获取群的 H5 分享/加群链接 (qm.qq.com/q/xxx 或 qun.qq.com/universal-share/share?...)';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
need_short_url: true,
};
override returnExample = {
url: 'https://qm.qq.com/q/xxxxxxxxxx',
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const needShortUrl = payload.need_short_url === undefined ? true : payload.need_short_url.toString() === 'true';
const srcId = payload.src_id === undefined ? 73 : Number(payload.src_id);
const ret = await this.core.apis.GroupApi.getJoinGroupLink(
payload.group_id.toString(),
needShortUrl,
srcId,
payload.additional_param ?? ''
);
if (!ret?.url) {
throw new Error(`获取群分享链接失败: ${ret?.errMsg || JSON.stringify(ret)}`);
}
return { url: ret.url };
}
}
@@ -1,73 +0,0 @@
import { uriToLocalFile } from 'napcat-common/src/file';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { existsSync, readFileSync } from 'node:fs';
import { unlink } from 'node:fs/promises';
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const ValidUgcRights = [1, 4, 16, 64, 128] as const;
const PayloadSchema = Type.Object({
content: Type.String({ description: '说说正文' }),
images: Type.Optional(Type.Array(Type.String(), { description: '图片数组, 支持 file:// http(s):// base64:// , 自动上传' })),
ugc_right: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '查看权限: 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见' })),
target_uins: Type.Optional(Type.Array(Type.Union([Type.Number(), Type.String()]), { description: 'ugc_right为16/128时, 权限作用的QQ号数组' })),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
tid: Type.String({ description: '说说Tid' }),
}, { description: '发说说结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SendQzoneMsg extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SendQzoneMsg;
override actionSummary = '发表QQ空间说说';
override actionDescription = '在QQ空间(Qzone)发表说说, 支持纯文字或带(多)图, 可设置查看权限';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.SendQzoneMsg.payload;
override returnExample = ExtendsActionsExamples.SendQzoneMsg.response;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType): Promise<ReturnType> {
const ugcRight = payload.ugc_right !== undefined ? +payload.ugc_right : 1;
if (!ValidUgcRights.includes(ugcRight as typeof ValidUgcRights[number])) {
throw new Error(`ugc_right 参数不合法, 允许的值为: ${ValidUgcRights.join(', ')}`);
}
const targetUins = payload.target_uins?.map((uin) => +uin).filter((uin) => !Number.isNaN(uin));
if ((ugcRight === 16 || ugcRight === 128) && (!targetUins || targetUins.length === 0)) {
throw new Error('ugc_right 为 16 或 128 时, target_uins 不能为空');
}
const richvals: string[] = [];
const cleanupPaths: string[] = [];
try {
for (const image of payload.images ?? []) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, image);
if (!downloadResult.success) {
throw new Error(`图片${image}处理失败, ${downloadResult.errMsg}`);
}
if (!downloadResult.isLocal) {
cleanupPaths.push(downloadResult.path);
}
const base64 = readFileSync(downloadResult.path).toString('base64');
const richval = await this.core.apis.WebApi.uploadImageToQzone(base64);
richvals.push(richval);
}
const result = await this.core.apis.WebApi.publishQzoneMsg(payload.content, richvals, ugcRight, targetUins);
return result;
} finally {
for (const p of cleanupPaths) {
if (existsSync(p)) {
await unlink(p).catch(() => { });
}
}
}
}
}
@@ -1,66 +0,0 @@
import { uriToLocalFile } from 'napcat-common/src/file';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { existsSync } from 'node:fs';
import { unlink } from 'node:fs/promises';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
album_name: Type.String({ description: '相册名称' }),
files: Type.Array(Type.String(), { description: '图片路径、URL或Base64 数组,一次上传多张' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Any({ description: '上传结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class UploadImagesToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.UploadImagesToQunAlbum;
override actionSummary = '上传多张图片到群相册';
override actionDescription = '一次上传多张图片,这些图片在群相册里显示为同一条上传';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
album_name: '相册1',
files: ['/path/to/1.jpg', '/path/to/2.jpg'],
};
override returnExample = {
result: null,
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
if (!payload.files.length) throw new Error('files 不能为空');
const localPaths: string[] = [];
const tempPaths: string[] = [];
try {
for (const file of payload.files) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, file);
localPaths.push(downloadResult.path);
if (!downloadResult.isLocal && downloadResult.path) {
tempPaths.push(downloadResult.path);
}
}
return await this.core.apis.WebApi.uploadImagesToQunAlbum(
payload.group_id,
payload.album_id,
payload.album_name,
localPaths
);
} finally {
for (const path of tempPaths) {
if (existsSync(path)) {
await unlink(path);
}
}
}
}
}
@@ -1,55 +0,0 @@
import { uriToLocalFile } from 'napcat-common/src/file';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { existsSync } from 'node:fs';
import { unlink } from 'node:fs/promises';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
album_name: Type.String({ description: '相册名称' }),
file: Type.String({ description: '视频路径、URL或Base64' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Any({ description: '上传结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class UploadVideoToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.UploadVideoToQunAlbum;
override actionSummary = '上传视频到群相册';
override actionDescription = '上传视频到群相册,封面自动抽取首帧(失败时使用内置默认封面)';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
album_name: '相册1',
file: '/path/to/video.mp4',
};
override returnExample = {
result: null,
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
try {
return await this.core.apis.WebApi.uploadVideoToQunAlbum(
payload.group_id,
payload.album_id,
payload.album_name,
downloadResult.path
);
} finally {
if (!downloadResult.isLocal && downloadResult.path && existsSync(downloadResult.path)) {
await unlink(downloadResult.path);
}
}
}
}
@@ -55,7 +55,7 @@ export default class GetFriendMsgHistory extends OneBotAction<PayloadType, Retur
}));
// 烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url)))
).filter((msg): msg is OB11Message => msg !== undefined);
return { messages: ob11MsgList };
}
@@ -43,8 +43,7 @@ export class GetGroupFilesByFolder extends OneBotAction<PayloadType, ReturnType>
return {
files: ret.filter(item => item.fileInfo)
.map(item => OB11Construct.file(item.peerId, item.fileInfo!)),
folders: ret.filter(item => item.folderInfo)
.map(item => OB11Construct.folder(item.peerId, item.folderInfo!)),
folders: [],
};
}
}
@@ -26,7 +26,7 @@ export class SetQQProfile extends OneBotAction<SetQQProfilePayload, any> {
return await this.core.apis.UserApi.modifySelfProfile({
nick: payload.nickname,
longNick: (payload?.personal_note ?? OldProfile?.longNick) || '',
sex: parseInt(payload.sex != null && payload.sex !== '' ? payload.sex.toString() : OldProfile?.sex!.toString()),
sex: parseInt(payload?.sex ? payload?.sex.toString() : OldProfile?.sex!.toString()),
birthday: {
birthday_year: OldProfile?.birthday_year!.toString(),
birthday_month: OldProfile?.birthday_month!.toString(),
@@ -48,7 +48,7 @@ export default class DelEssenceMsg extends OneBotAction<PayloadType, ReturnType>
const data = this.core.apis.GroupApi.essenceLRU.getValue(+payload.message_id);
if (!data) throw new Error('消息不存在');
const { msg_seq, msg_random, group_id } = JSON.parse(data) as { msg_seq: string, msg_random: string, group_id: string; };
return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_random, msg_seq);
return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_seq, msg_random);
}
return await this.core.apis.GroupApi.removeGroupEssence(
msg.Peer.peerUid,
@@ -21,8 +21,6 @@ const ReturnSchema = Type.Array(Type.Object({
}, { description: '公告内容' }),
settings: Type.Optional(Type.Any({ description: '设置项' })),
read_num: Type.Optional(Type.Number({ description: '阅读数' })),
send_to_new_member: Type.Optional(Type.Boolean({ description: '是否为「发给新成员」公告' })),
pinned: Type.Optional(Type.Boolean({ description: '是否置顶(仅「发给新成员」公告可读到)' })),
}), { description: '群公告列表' });
type ReturnType = Static<typeof ReturnSchema>;
@@ -46,44 +44,30 @@ export class GetGroupNotice extends OneBotAction<PayloadType, ReturnType> {
throw new Error('获取公告失败');
}
const retNotices: ReturnType = [];
const seen = new Set<string>();
// 「发给新成员」类公告只出现在 inst 里,追加在 feeds 之后,保持原有条目的顺序不变
for (const [list, sendToNewMember] of [[ret.feeds, false], [ret.inst, true]] as const) {
for (const retApiNotice of Array.isArray(list) ? list : []) {
if (!retApiNotice || seen.has(retApiNotice.fid)) {
continue;
}
seen.add(retApiNotice.fid);
retNotices.push(this.toNotice(retApiNotice, sendToNewMember));
for (const key in ret.feeds) {
if (!ret.feeds[key]) {
continue;
}
const retApiNotice: WebApiGroupNoticeFeed = ret.feeds[key];
const image = retApiNotice.msg.pics?.map((pic) => {
return { id: pic.id, height: pic.h, width: pic.w };
}) || [];
const retNotice: ReturnType[number] = {
notice_id: retApiNotice.fid,
sender_id: retApiNotice.u,
publish_time: retApiNotice.pubt,
message: {
text: retApiNotice.msg.text,
image,
images: image,
},
settings: retApiNotice.settings,
read_num: retApiNotice.read_num,
};
retNotices.push(retNotice);
}
return retNotices;
}
private toNotice (retApiNotice: WebApiGroupNoticeFeed, sendToNewMember: boolean): ReturnType[number] {
const image = retApiNotice.msg.pics?.map((pic) => {
return { id: pic.id, height: pic.h, width: pic.w };
}) || [];
const retNotice: ReturnType[number] = {
notice_id: retApiNotice.fid,
sender_id: retApiNotice.u,
publish_time: retApiNotice.pubt,
message: {
text: retApiNotice.msg.text,
image,
images: image,
},
settings: retApiNotice.settings,
read_num: retApiNotice.read_num,
send_to_new_member: sendToNewMember,
};
// 置顶状态只在 inst 条目的 settings.inst_no_pinned 里:0 = 置顶中,1 = 未置顶
const instNoPinned = retApiNotice.settings?.inst_no_pinned;
if (typeof instNoPinned === 'number') {
retNotice.pinned = instNoPinned === 0;
}
return retNotice;
}
}
@@ -1,13 +0,0 @@
import type { GeneralCallResult } from 'napcat-core';
export function assertGroupManagementResults (
operation: string,
results: Array<{ setting: string, result: GeneralCallResult; }>
): void {
const failure = results.find(item => item.result.result !== 0);
if (!failure) return;
throw new Error(
`${operation}失败 Setting: ${failure.setting} ErrCode: ${failure.result.result} ` +
`ErrMsg: ${failure.result.errMsg || '未知错误'}`
);
}
@@ -26,13 +26,7 @@ export default class SetGroupLeave extends OneBotAction<PayloadType, ReturnType>
override returnExample = GroupActionsExamples.SetGroupLeave.response;
async _handle (payload: PayloadType): Promise<null> {
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);
}
await this.core.apis.GroupApi.quitGroup(payload.group_id.toString());
return null;
}
}
@@ -1,41 +0,0 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
import { assertGroupManagementResults } from './GroupOperationHelpers';
const MemberInvitePolicySchema = Type.Union([
Type.Literal('disabled'),
Type.Literal('require_approval'),
Type.Literal('no_approval'),
Type.Literal('no_approval_under_100'),
], {
description: '成员邀请策略:禁止、需要管理员审核、无需审核、群成员少于100人时无需审核',
});
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
policy: MemberInvitePolicySchema,
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Null({ description: '操作结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupMemberInvitePolicy extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupMemberInvitePolicy;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置群成员邀请策略';
override actionDescription = '设置是否允许群成员邀请好友进群,以及邀请是否需要管理员审核';
override actionTags = ['群组接口'];
override payloadExample = GroupActionsExamples.SetGroupMemberInvitePolicy.payload;
override returnExample = GroupActionsExamples.SetGroupMemberInvitePolicy.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const results = await this.core.apis.GroupApi.setGroupMemberInvitePolicy(payload.group_id, payload.policy);
assertGroupManagementResults('设置群成员邀请策略', results);
return null;
}
}
@@ -1,43 +0,0 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
import { assertGroupManagementResults } from './GroupOperationHelpers';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
allow_member_upload_album: Type.Optional(Type.Boolean({ description: '允许成员上传群相册' })),
allow_member_temporary_session: Type.Optional(Type.Boolean({ description: '允许成员发起临时会话' })),
allow_member_create_group: Type.Optional(Type.Boolean({ description: '允许成员发起新的群聊' })),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Null({ description: '操作结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupMemberPermissions extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupMemberPermissions;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置群成员功能权限';
override actionDescription = '设置群成员上传相册、发起临时会话和发起新群聊的权限;未传入的项目保持不变';
override actionTags = ['群组接口'];
override payloadExample = GroupActionsExamples.SetGroupMemberPermissions.payload;
override returnExample = GroupActionsExamples.SetGroupMemberPermissions.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const permissions = {
allowMemberUploadAlbum: payload.allow_member_upload_album,
allowMemberTemporarySession: payload.allow_member_temporary_session,
allowMemberCreateGroup: payload.allow_member_create_group,
};
if (Object.values(permissions).every(value => value === undefined)) {
throw new Error('至少需要提供一个群成员功能权限');
}
const results = await this.core.apis.GroupApi.setGroupMemberPermissions(payload.group_id, permissions);
assertGroupManagementResults('设置群成员功能权限', results);
return null;
}
}
@@ -1,35 +0,0 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
import { assertGroupManagementResults } from './GroupOperationHelpers';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
visible: Type.Boolean({ description: '新成员默认可见最近聊天记录' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Null({ description: '操作结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupNewMemberHistoryVisibility extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupNewMemberHistoryVisibility;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置新成员历史消息可见性';
override actionDescription = '设置新入群成员默认是否可以查看最近聊天记录';
override actionTags = ['群组接口'];
override payloadExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.payload;
override returnExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const results = await this.core.apis.GroupApi.setGroupNewMemberHistoryVisibility(
payload.group_id,
payload.visible
);
assertGroupManagementResults('设置新成员历史消息可见性', results);
return null;
}
}
-16
View File
@@ -75,7 +75,6 @@ import { SetInputStatus } from './extends/SetInputStatus';
import { GetCSRF } from './system/GetCSRF';
import { DelGroupNotice } from './group/DelGroupNotice';
import { GetGroupInfoEx } from './extends/GetGroupInfoEx';
import { GetGroupShareLink } from './extends/GetGroupShareLink';
import { DeleteGroupFile } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFile';
import { CreateGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/CreateGroupFileFolder';
import { DeleteGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFileFolder';
@@ -134,8 +133,6 @@ import { CancelGroupTodo } from './packet/CancelGroupTodo';
import { SetGroupTodo } from './packet/SetGroupTodo';
import { GetQunAlbumList } from './extends/GetQunAlbumList';
import { UploadImageToQunAlbum } from './extends/UploadImageToQunAlbum';
import { UploadImagesToQunAlbum } from './extends/UploadImagesToQunAlbum';
import { UploadVideoToQunAlbum } from './extends/UploadVideoToQunAlbum';
import { DoGroupAlbumComment } from './extends/DoGroupAlbumComment';
import { GetGroupAlbumMediaList } from './extends/GetGroupAlbumMediaList';
import { SetGroupAlbumMediaLike, CancelGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
@@ -163,11 +160,6 @@ import { RefuseOnlineFile } from './file/online/RefuseOnlineFile';
import { GetFilesetId } from './file/flash/GetFilesetIdByCode';
import { FetchPttText } from '@/napcat-onebot/action/msg/FetchPttText';
import { GetGroupSignedList } from './extends/GetGroupSignedList';
import { SendQzoneMsg } from './extends/SendQzoneMsg';
import { DeleteQzoneMsg } from './extends/DeleteQzoneMsg';
import SetGroupMemberInvitePolicy from './group/SetGroupMemberInvitePolicy';
import SetGroupMemberPermissions from './group/SetGroupMemberPermissions';
import SetGroupNewMemberHistoryVisibility from './group/SetGroupNewMemberHistoryVisibility';
export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCore) {
const actionHandlers = [
@@ -184,8 +176,6 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetGroupAlbumMediaList(obContext, core),
new GetQunAlbumList(obContext, core),
new UploadImageToQunAlbum(obContext, core),
new UploadImagesToQunAlbum(obContext, core),
new UploadVideoToQunAlbum(obContext, core),
new SetGroupTodo(obContext, core),
new CompleteGroupTodo(obContext, core),
new CancelGroupTodo(obContext, core),
@@ -201,7 +191,6 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetRkeyServer(obContext, core),
new SetGroupRemark(obContext, core),
new GetGroupInfoEx(obContext, core),
new GetGroupShareLink(obContext, core),
new FetchEmojiLike(obContext, core),
new GetEmojiLikes(obContext, core),
new FetchPttText(obContext, core),
@@ -227,11 +216,6 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new RenameGroupFile(obContext, core),
new TransGroupFile(obContext, core),
new GetGroupSignedList(obContext, core),
new SendQzoneMsg(obContext, core),
new DeleteQzoneMsg(obContext, core),
new SetGroupMemberInvitePolicy(obContext, core),
new SetGroupMemberPermissions(obContext, core),
new SetGroupNewMemberHistoryVisibility(obContext, core),
// onebot11
new SendLike(obContext, core),
new GetMsg(obContext, core),
+1 -6
View File
@@ -245,12 +245,7 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
});
}
} else {
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(
OB11Data,
msgPeer,
[],
{ usePacketVideoMetadata: true }
);
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
sendElements = sendElementsCreateReturn.sendElements;
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
}
-10
View File
@@ -28,8 +28,6 @@ export const ActionName = {
DoGroupAlbumComment: 'do_group_album_comment',
GetGroupAlbumMediaList: 'get_group_album_media_list',
UploadImageToQunAlbum: 'upload_image_to_qun_album',
UploadImagesToQunAlbum: 'upload_images_to_qun_album',
UploadVideoToQunAlbum: 'upload_video_to_qun_album',
GetQunAlbumList: 'get_qun_album_list',
SetGroupTodo: 'set_group_todo',
CompleteGroupTodo: 'complete_group_todo',
@@ -45,9 +43,6 @@ export const ActionName = {
GetRkeyEx: 'get_rkey',
GetRkeyServer: 'get_rkey_server',
SetGroupRemark: 'set_group_remark',
SetGroupMemberInvitePolicy: 'set_group_member_invite_policy',
SetGroupMemberPermissions: 'set_group_member_permissions',
SetGroupNewMemberHistoryVisibility: 'set_group_new_member_history_visibility',
NapCat_GetPrivateFileUrl: 'get_private_file_url',
ClickInlineKeyboardButton: 'click_inline_keyboard_button',
GetUnidirectionalFriendList: 'get_unidirectional_friend_list',
@@ -168,7 +163,6 @@ export const ActionName = {
GetEmojiLikes: 'get_emoji_likes',
SetInputStatus: 'set_input_status',
GetGroupInfoEx: 'get_group_info_ex',
GetGroupShareLink: 'get_group_share_link',
GetGroupDetailInfo: 'get_group_detail_info',
GetGroupIgnoreAddRequest: 'get_group_ignore_add_request',
DelGroupNotice: '_del_group_notice',
@@ -220,8 +214,4 @@ export const ActionName = {
CancelOnlineFile: 'cancel_online_file',
GetGroupSignedList: 'get_group_signed_list',
// QQ 空间扩展
SendQzoneMsg: 'send_qzone_msg',
DeleteQzoneMsg: 'delete_qzone_msg',
} as const;
+5 -36
View File
@@ -2,7 +2,7 @@ import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
import { encodeSilk } from '@/napcat-core/helper/audio';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { calculateFileMD5 } from 'napcat-common/src/file';
import { ElementType, NapCatCore, NTVideoType, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
import { ElementType, NapCatCore, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
import { getFileTypeForSendType } from 'napcat-core/helper/msg';
import { imageSizeFallBack } from 'napcat-image-size';
import { SendMessageContext } from './msg';
@@ -12,21 +12,6 @@ import fsPromises from 'fs/promises';
import fs from 'fs';
import { randomUUID } from 'crypto';
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
const videoFormatByExtension: Partial<Record<string, NTVideoType>> = {
afs: NTVideoType.VIDEO_FORMAT_AFS,
avi: NTVideoType.VIDEO_FORMAT_AVI,
mkv: NTVideoType.VIDEO_FORMAT_MKV,
mod: NTVideoType.VIDEO_FORMAT_MOD,
mov: NTVideoType.VIDEO_FORMAT_MOV,
mp4: NTVideoType.VIDEO_FORMAT_MP4,
mts: NTVideoType.VIDEO_FORMAT_MTS,
rm: NTVideoType.VIDEO_FORMAT_RM,
rmvb: NTVideoType.VIDEO_FORMAT_RMVB,
ts: NTVideoType.VIDEO_FORMAT_TS,
wmv: NTVideoType.VIDEO_FORMAT_WMV,
};
export class OneBotFileApi {
obContext: NapCatOneBot11Adapter;
core: NapCatCore;
@@ -129,16 +114,9 @@ export class OneBotFileApi {
}
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
const usePacketVideoMetadata = context.usePacketVideoMetadata === true;
const thumbExtension = usePacketVideoMetadata ? 'jpg' : 'png';
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.${thumbExtension}`);
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
try {
if (usePacketVideoMetadata) {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
} else {
videoInfo = await FFmpegService.getVideoInfo(filePath, '');
await FFmpegService.extractLegacyVideoThumbnail(filePath, thumbPath);
}
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
if (!fs.existsSync(thumbPath)) {
this.core.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
throw new Error('获取视频缩略图失败');
@@ -157,18 +135,9 @@ export class OneBotFileApi {
context.deleteAfterSentFiles.push(thumbPath);
const thumbSize = (await fsPromises.stat(thumbPath)).size;
const thumbMd5 = await calculateFileMD5(thumbPath);
context.deleteAfterSentFiles.push(thumbPath);
const uploadName = (fileName || _fileName).toLocaleLowerCase().endsWith(`.${fileExt.toLocaleLowerCase()}`) ? (fileName || _fileName) : `${fileName || _fileName}.${fileExt}`;
const videoMetadata = usePacketVideoMetadata
? {
fileTime: Math.max(0, Math.round(videoInfo.time)),
fileFormat: videoFormatByExtension[fileExt.toLowerCase()] ?? NTVideoType.VIDEO_FORMAT_MP4,
fileWidth: videoInfo.width,
fileHeight: videoInfo.height,
}
: {
fileTime: videoInfo.time,
};
return {
elementType: ElementType.VIDEO,
elementId: '',
@@ -177,7 +146,7 @@ export class OneBotFileApi {
filePath: path,
videoMd5: md5,
thumbMd5,
...videoMetadata,
fileTime: videoInfo.time,
thumbPath: new Map([[0, thumbPath]]),
thumbSize,
thumbWidth: videoInfo.width,
+9 -55
View File
@@ -74,7 +74,6 @@ type Ob11ToRawConverters = {
export type SendMessageContext = {
deleteAfterSentFiles: string[],
peer: Peer;
usePacketVideoMetadata?: boolean;
};
export type RecvMessageContext = {
@@ -385,30 +384,6 @@ export class OneBotMsgApi {
this.core.context.logger.logError('所有查找方法均失败,获取不到旧客户端的引用消息', element.replayMsgSeq);
}
// 私聊引用:replayMsgSeq 常为 0(客户端未填序号),seq 查询链与协议兜底都会落空,
// 而引用元素里的 replyMsgClientSeq / replyMsgTime 此时依然准确,用它反查被引用消息。
if (element.replyMsgClientSeq) {
try {
const replyMsgTime = element.replyMsgTime ?? records?.msgTime;
if (replyMsgTime) {
const byClientSeq = await this.core.apis.MsgApi.getMsgByClientSeqAndTime(
peer,
element.replyMsgClientSeq,
replyMsgTime
);
const replyMsg = byClientSeq.msgList?.find(msg => msg.msgId);
if (replyMsg) {
return createReplyData(replyMsg.msgId);
}
this.core.context.logger.logWarn(
`按 clientSeq 查询未命中,序号: ${element.replayMsgSeq}, clientSeq: ${element.replyMsgClientSeq}`
);
}
} catch (error) {
this.core.context.logger.logError('按 clientSeq 查询引用消息出错', error);
}
}
// 协议兜底:尝试通过协议直接获取消息
if (this.core.apis.PacketApi.packetStatus) {
try {
@@ -884,23 +859,12 @@ export class OneBotMsgApi {
// 获取签名服务地址
let signUrl = this.obContext.configLoader.configData.musicSignUrl;
if (!signUrl) {
signUrl = 'http://106.55.0.102:10087/'; // 首选,yibai音卡签名,已更换稳定签名服务器
signUrl = 'https://ss.xingzhige.com/music_card/card';// 感谢思思!已获思思许可 其余地方使用请自行询问
}
// 请求签名服务
try {
let musicJson: string;
try {
musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
} catch {
// 首选失败,降级到备选
this.core.context.logger.logError('[音乐卡片签名] 首选地址失败,尝试备选地址...');
musicJson = await RequestUtil.HttpGetJson<string>(
'https://ss.xingzhige.com/music_card/card', // 思思的音卡签名
'POST',
postData
);
}
const musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
return this.ob11ToRawConverters.json({
data: { data: musicJson },
type: OB11MessageDataType.json,
@@ -1165,8 +1129,8 @@ export class OneBotMsgApi {
resMsg.sub_type = 'normal';
resMsg.group_id = parseInt(msg.peerUin);
resMsg.group_name = msg.peerName;
// getGroupMember 找不到成员时内部已经刷新过一次缓存,这里不用再查第二遍
const member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
let member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
if (!member) member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
if (member) {
resMsg.sender.role = OB11Construct.groupMemberRole(member.role);
resMsg.sender.nickname = member.nick;
@@ -1189,12 +1153,9 @@ export class OneBotMsgApi {
resMsg.sub_type = 'group';
const ret = await this.core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, msg.senderUid);
if (ret.result === 0) {
// 临时会话的 peerUin 是对方 QQ 号,成员要去来源群里找;uid 一般不空,优先用 uid 查
const groupCode = ret.tmpChatInfo!.groupCode;
const member = groupCode
? await this.core.apis.GroupApi.getGroupMember(groupCode, msg.senderUid || msg.senderUin)
: undefined;
resMsg.group_id = parseInt(groupCode);
// 避免uin:'' uid非空,uid一般不空
const member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, await this.core.apis.UserApi.getUinByUidV2(msg.senderUid));
resMsg.group_id = parseInt(ret.tmpChatInfo!.groupCode);
resMsg.sender.nickname = member?.nick ?? member?.cardName ?? '临时会话';
resMsg.temp_source = 0;
} else {
@@ -1258,10 +1219,7 @@ export class OneBotMsgApi {
async createSendElements (
messageData: OB11MessageData[],
peer: Peer,
ignoreTypes: OB11MessageDataType[] = [],
options: {
usePacketVideoMetadata?: boolean;
} = {}
ignoreTypes: OB11MessageDataType[] = []
) {
const deleteAfterSentFiles: string[] = [];
const callResultList: Array<Promise<SendMessageElement | undefined>> = [];
@@ -1278,11 +1236,7 @@ export class OneBotMsgApi {
}
const callResult = converter(
sendMsg,
{
peer,
deleteAfterSentFiles,
usePacketVideoMetadata: options.usePacketVideoMetadata,
}
{ peer, deleteAfterSentFiles }
)?.catch(undefined);
callResultList.push(callResult);
}
-3
View File
@@ -135,9 +135,6 @@ export class OB11Construct {
creator: +folder.createUin,
creator_name: folder.creatorName,
total_file_count: folder.totalFileCount,
modify_time: folder.modifyTime,
modifier: +folder.modifyUin,
modifier_name: folder.modifyName,
};
}
}
+23 -107
View File
@@ -65,10 +65,6 @@ interface ApiListType {
QuickActionApi: OneBotQuickActionApi;
FileApi: OneBotFileApi;
}
const RECALL_EVENT_DEDUP_MAX_SIZE = 1_000;
const RECALL_UPDATE_CLOCK_SKEW_SECONDS = 30;
// OneBot实现类
export class NapCatOneBot11Adapter {
readonly core: NapCatCore;
@@ -80,8 +76,6 @@ export class NapCatOneBot11Adapter {
actions: ActionMap;
private readonly bootTime = Date.now() / 1000;
recallEventCache = new Map<string, NodeJS.Timeout>();
private readonly reportedRecallEventCache = new Map<string, true>();
private readonly processingRecallEvents = new Map<string, Promise<void>>();
constructor (core: NapCatCore, context: InstanceContext, pathWrapper: NapCatPathWrapper) {
this.core = core;
this.context = context;
@@ -390,34 +384,36 @@ export class NapCatOneBot11Adapter {
this.context.logger.logError('处理发送消息失败', error);
}
};
msgListener.onMsgInfoListUpdate = async (msgList: RawMessage[]) => {
for (const msg of msgList) {
const element = this.getRecallElement(msg);
if (element && this.isCurrentRecallUpdate(msg)) {
// The gray-tip update is authoritative; the recall callback's sequence query can return a newer message.
await this.handleRecallMessage(msg, element);
}
}
};
msgListener.onMsgRecall = async (chatType: ChatType, uid: string, msgSeq: string) => {
const peer: Peer = {
chatType,
peerUid: uid,
guildId: '',
};
try {
const msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList
.find(message => this.getRecallElement(message));
const element = msg && this.getRecallElement(msg);
if (msg && element) {
await this.handleRecallMessage(msg, element);
} else {
this.context.logger.logDebug(`撤回回调暂未查询到灰条消息,等待消息更新: ${chatType}/${uid}/${msgSeq}`);
let msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList.find(e => e.msgType === NTMsgType.KMSGTYPEGRAYTIPS);
const element = msg?.elements.find(e => !!e.grayTipElement?.revokeElement);
if (msg && element?.grayTipElement?.revokeElement.isSelfOperate) {
const isSelfDevice = this.recallEventCache.has(msg.msgId);
if (isSelfDevice) {
await this.core.eventWrapper.registerListen('NodeIKernelMsgListener/onMsgRecall',
(chatType: ChatType, uid: string, msgSeq: string) => {
return chatType === msg?.chatType && uid === msg?.peerUid && msgSeq === msg?.msgSeq;
}
).catch(() => {
msg = undefined;
this.context.logger.logDebug('自操作消息撤回事件');
});
}
}
if (msg && element) {
const recallEvent = await this.emitRecallMsg(msg, element);
try {
if (recallEvent) {
await this.networkManager.emitEvent(recallEvent);
}
} catch (e) {
this.context.logger.logError('处理消息撤回失败', e);
}
} catch (e) {
this.context.logger.logError('查询撤回消息失败', e);
}
};
msgListener.onKickedOffLine = async (kick) => {
@@ -666,86 +662,6 @@ export class NapCatOneBot11Adapter {
}
}
private getRecallElement (message: RawMessage): MessageElement | undefined {
if (message.msgType !== NTMsgType.KMSGTYPEGRAYTIPS) {
return undefined;
}
return message.elements.find(element => !!element.grayTipElement?.revokeElement);
}
private isCurrentRecallUpdate (message: RawMessage): boolean {
const recallTime = Number(message.recallTime);
if (!Number.isFinite(recallTime) || recallTime <= 0) {
return false;
}
const recallTimeInSeconds = recallTime > 10_000_000_000 ? recallTime / 1000 : recallTime;
return recallTimeInSeconds >= this.bootTime - RECALL_UPDATE_CLOCK_SKEW_SECONDS;
}
private getRecallEventKey (message: RawMessage): string {
return `${message.chatType}/${message.peerUid}/${message.msgId}`;
}
private hasReportedRecallEvent (key: string): boolean {
return this.reportedRecallEventCache.has(key);
}
private markRecallEventReported (key: string): void {
this.reportedRecallEventCache.delete(key);
this.reportedRecallEventCache.set(key, true);
while (this.reportedRecallEventCache.size > RECALL_EVENT_DEDUP_MAX_SIZE) {
const oldestKey = this.reportedRecallEventCache.keys().next().value;
if (oldestKey === undefined) break;
this.reportedRecallEventCache.delete(oldestKey);
}
}
private async handleRecallMessage (message: RawMessage, element: MessageElement): Promise<void> {
const revokeElement = element.grayTipElement?.revokeElement;
if (!revokeElement) return;
if (revokeElement.isSelfOperate) {
const selfRecallTimeout = this.recallEventCache.get(message.msgId);
if (selfRecallTimeout) {
clearTimeout(selfRecallTimeout);
this.recallEventCache.delete(message.msgId);
this.context.logger.logDebug('自操作消息撤回事件');
}
}
const key = this.getRecallEventKey(message);
while (!this.hasReportedRecallEvent(key)) {
const processing = this.processingRecallEvents.get(key);
if (processing) {
// A duplicate callback becomes the retry path if the in-flight report fails.
await processing;
continue;
}
const task = (async () => {
try {
const recallEvent = await this.emitRecallMsg(message, element);
if (recallEvent) {
await this.networkManager.emitEvent(recallEvent);
this.markRecallEventReported(key);
}
} catch (e) {
this.context.logger.logError('处理消息撤回失败', e);
}
})();
this.processingRecallEvents.set(key, task);
try {
await task;
} finally {
if (this.processingRecallEvents.get(key) === task) {
this.processingRecallEvents.delete(key);
}
}
return;
}
}
private async emitRecallMsg (message: RawMessage, element: MessageElement) {
const peer: Peer = { chatType: message.chatType, peerUid: message.peerUid, guildId: '' };
const oriMessageId = MessageUnique.getShortIdByMsgId(message.msgId) ?? MessageUnique.createUniqueMsgId(peer, message.msgId);
@@ -249,7 +249,7 @@ export class PluginLoader {
if (hit) {
return `sensitive keyword "${hit}"`;
}
return 'not in official plugin whitelist';
return "not in official plugin whitelist";
}
/**
-3
View File
@@ -105,7 +105,4 @@ export interface OB11GroupFileFolder {
creator: number; // 创建者ID
creator_name: string; // 创建者名称
total_file_count: number; // 文件总数
modify_time: number; // 最后修改时间
modifier: number; // 最后修改者ID
modifier_name: string; // 最后修改者名称
}
-1
View File
@@ -14,7 +14,6 @@
"napcat-vite": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.1",
"tsx": "^4.7.1",
"vite": "^6.0.0"
}
Binary file not shown.
Binary file not shown.
@@ -1,12 +1,10 @@
@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"
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
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -26,6 +24,9 @@ if not exist "%QQpath%" (
exit /b
)
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%" %*
pause
@@ -1,12 +1,10 @@
@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"
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
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -25,6 +23,9 @@ if not exist "%QQpath%" (
pause
exit /b
)
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%" %*
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
@@ -1,6 +1,4 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
@@ -11,11 +9,11 @@ if %ERRORLEVEL% == 0 (
exit
)
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 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
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -34,6 +32,9 @@ if not exist "%QQPath%" (
pause
exit /b
)
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%" %*
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
+8 -7
View File
@@ -1,6 +1,4 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
@@ -11,11 +9,11 @@ if %ERRORLEVEL% == 0 (
exit
)
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 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
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -35,4 +33,7 @@ if not exist "%QQPath%" (
exit /b
)
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%" %*
+2 -3
View File
@@ -1,6 +1,5 @@
const path = require('path');
const { pathToFileURL } = require('url');
const mainPath = process.env.NAPCAT_MAIN_PATH || path.join(__dirname, 'napcat.mjs');
const CurrentPath = path.dirname(__filename);
(async () => {
await import(pathToFileURL(mainPath).href);
await import('file://' + path.join(CurrentPath, './napcat/napcat.mjs'));
})();
+13 -92
View File
@@ -37,7 +37,6 @@ import { OidbSvcTrpcTcpBase, OidbSvcTrpcTcp0XCDE_2RespBody } from '@/napcat-core
import { loadNapcatConfig } from '@/napcat-core/helper/config';
import { logSubscription, LogWrapper } from '@/napcat-core/helper/log';
import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
import { createOfflineRecovery } from '@/napcat-core/helper/offline-recovery';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
import { statusHelperSubscription } from '@/napcat-core/helper/status';
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
@@ -127,7 +126,7 @@ async function handleLogin (
quickLoginUin: string | undefined,
historyLoginList: LoginListItem[]
): Promise<SelfInfo> {
const context = { isLogined: false, loginFlowInitialized: false };
const context = { isLogined: false };
let inner_resolve: (value: SelfInfo) => void;
const selfInfo: Promise<SelfInfo> = new Promise((resolve) => {
inner_resolve = resolve;
@@ -143,14 +142,6 @@ async function handleLogin (
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
context.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
const oneBotContext = WebUiDataRuntime.getOneBotContext();
if (oneBotContext?.core?.selfInfo) {
oneBotContext.core.selfInfo.online = true;
WebUiDataRuntime.setQQLoginPhase('ready');
} else {
WebUiDataRuntime.setQQLoginPhase('initializing');
}
inner_resolve({
uid: loginResult.uid,
uin: loginResult.uin,
@@ -158,35 +149,14 @@ async function handleLogin (
online: true,
});
};
loginListener.onLoginDisConnected = () => {
context.isLogined = false;
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginPhase('offline');
logger.logWarn('[Core] [Login] 登录服务已断开,将允许重新获取二维码');
};
loginListener.onLogoutSucceed = () => {
context.isLogined = false;
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginPhase('offline');
};
loginListener.onLoginConnected = () => {
waitForNetworkConnection(loginService, logger).then(async () => {
if (!context.loginFlowInitialized) {
context.loginFlowInitialized = true;
await handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList);
return;
}
if (!context.isLogined) {
WebUiDataRuntime.setQQLoginPhase('generating_qrcode');
const requested = loginService.getQRCodePicture();
logger.logWarn('[Core] [Login] 登录服务重连完成,正在获取二维码', { requested, msfStatus: loginService.getMsfStatus() });
}
}).catch(e => logger.logError(e));
waitForNetworkConnection(loginService, logger).then(() => {
handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList).then().catch(e => logger.logError(e));
loginListener.onLoginConnected = () => { };
});
};
loginListener.onQRCodeGetPicture = ({ pngBase64QrcodeData, qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('waiting_qrcode');
const realBase64 = pngBase64QrcodeData.replace(/^data:image\/\w+;base64,/, '');
const buffer = Buffer.from(realBase64, 'base64');
@@ -205,20 +175,14 @@ async function handleLogin (
});
};
loginListener.onQRCodeSessionUserScaned = () => {
WebUiDataRuntime.setQQLoginPhase('qrcode_scanned');
logger.log('[Core] [Login] 二维码已被扫描,等待确认...');
};
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
if (!context.isLogined) {
logger.logError('[Core] [Login] Login Error,ErrType: ', errType, ' ErrCode:', errCode);
if (errType === 1 && errCode === 3) {
// 仅二维码过期时自动请求下一张二维码。账号被踢下线等其他错误
// 需要由用户触发刷新,避免每两秒重复创建原生登录会话。
// 二维码过期刷新
WebUiDataRuntime.setQQLoginError('二维码已过期,请刷新');
loginService.getQRCodePicture();
}
loginService.getQRCodePicture();
}
};
@@ -232,7 +196,7 @@ async function handleLogin (
loginService.connect();
return await selfInfo;
}
async function handleLoginInner (context: { isLogined: boolean; loginFlowInitialized: boolean; }, logger: LogWrapper, loginService: NodeIKernelLoginService, quickLoginUin: string | undefined, historyLoginList: LoginListItem[]) {
async function handleLoginInner (context: { isLogined: boolean; }, logger: LogWrapper, loginService: NodeIKernelLoginService, quickLoginUin: string | undefined, historyLoginList: LoginListItem[]) {
const resolveQuickPasswordMd5 = (): string | undefined => {
const quickPasswordMd5 = process.env['NAPCAT_QUICK_PASSWORD_MD5']?.trim();
if (quickPasswordMd5) {
@@ -253,19 +217,7 @@ async function handleLoginInner (context: { isLogined: boolean; loginFlowInitial
// 注册刷新二维码回调
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
context.isLogined = false;
const msfStatus = loginService.getMsfStatus();
if (msfStatus === 2) {
// KickedOffLine 会在后台负责重启 Worker。这里不能重启:该回调由
// RefreshQRcode HTTP 请求触发,重启会中断正在等待响应的请求。
WebUiDataRuntime.setQQLoginPhase('reconnecting');
throw new Error('QQ_LOGIN_SERVICE_RESTARTING');
}
const requested = loginService.getQRCodePicture();
logger.logWarn('[Core] [Login] 请求刷新二维码', { requested, msfStatus });
if (!requested) {
throw new Error('QQ 未接受二维码刷新请求');
}
loginService.getQRCodePicture();
});
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
@@ -840,39 +792,11 @@ export class NapCatShell {
// }
// }
// 监听下线并同步到 WebUI
// KickedOffLine:账号被踢下线;SelfOffline:静默离线(服务端会话语义失效但无通知)。
// 两者复用同一条恢复链路:同步 WebUI -> 重启 Worker -> 快速登录。
const handleOffline = createOfflineRecovery({
isOnline: () => this.core.selfInfo.online === true,
onOffline: (tips) => {
WebUiDataRuntime.setQQLoginStatus(false);
// 下线后的二维码已失效,绝不能继续交给页面展示或扫码。
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
},
onRecovered: () => {
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('ready');
},
restart: async (tips) => {
try {
const restartResult = await WebUiDataRuntime.requestRestartProcess();
this.context.logger.logWarn('[Core] [Login] 账号已离线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (restartResult.result) return true;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
} catch (error) {
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
}
return false;
},
// 监听下线通知并同步到 WebUI
this.core.event.on('KickedOffLine', (tips: string) => {
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginError(tips);
});
this.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
this.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
// 使用 NapCatAdapterManager 统一管理协议适配器
const adapterManager = new NapCatAdapterManager(this.core, this.context, this.context.pathWrapper);
await adapterManager.initAdapters()
@@ -881,9 +805,6 @@ export class NapCatShell {
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
}
}
-8
View File
@@ -247,14 +247,6 @@ async function startWorker (passQuickLogin: boolean = true, secretKey?: string,
...(preferredPort ? { NAPCAT_WEBUI_PREFERRED_PORT: String(preferredPort) } : {}),
},
stdio: isElectron ? 'pipe' : ['inherit', 'pipe', 'pipe', 'ipc'],
// --no-sandbox 是 Chromium 开关,仅当子进程完整引导 Electron(未设 ELECTRON_RUN_AS_NODE)时
// 才会被解析;纯 Node / Electron node 模式子进程会因 bad option 以退出码 9 拒绝启动
// (ELECTRON_RUN_AS_NODE 变量存在即触发 node 模式,与取值无关)
...(!isElectron &&
process.versions['electron'] &&
process.env['ELECTRON_RUN_AS_NODE'] === undefined
? { execArgv: ['--no-sandbox'] }
: {}),
});
currentWorker = child;
+1 -2
View File
@@ -34,7 +34,6 @@ export interface IWorkerProcess {
export interface ProcessOptions {
env: NodeJS.ProcessEnv;
stdio: 'pipe' | 'ignore' | 'inherit' | Array<'pipe' | 'ignore' | 'inherit' | 'ipc'>;
execArgv?: string[];
}
/**
@@ -169,7 +168,7 @@ export async function createProcessManager (): Promise<{
manager: IProcessManager;
isElectron: boolean;
}> {
const isElectron = process.env['NAPCAT_FORCE_NODE_PROCESS'] !== '1' && typeof process.versions['electron'] !== 'undefined';
const isElectron = typeof process.versions['electron'] !== 'undefined';
if (isElectron) {
// @ts-ignore - electron 运行时存在但类型声明可能缺失
@@ -1,53 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { MessageUnique } from '../napcat-common/src/message-unique';
import DelEssenceMsg from '../napcat-onebot/action/group/DelEssenceMsg';
function createAction (essenceLRUValue: string | undefined) {
const removeGroupEssenceBySeq = vi.fn().mockResolvedValue({ result: 0 });
const action = new DelEssenceMsg(
undefined as never,
{
apis: {
GroupApi: {
essenceLRU: { getValue: vi.fn().mockReturnValue(essenceLRUValue) },
removeGroupEssenceBySeq,
},
},
} as never
);
return { action, removeGroupEssenceBySeq };
}
describe('delete_essence_msg argument order', () => {
afterEach(() => {
vi.restoreAllMocks();
});
test('passes msg_random before msg_seq for explicitly supplied parameters', async () => {
const { action, removeGroupEssenceBySeq } = createAction(undefined);
await action._handle({ group_id: '33', msg_seq: '11', msg_random: '22' });
// GroupApi.removeGroupEssenceBySeq(groupCode, msgRandom, msgSeq)
expect(removeGroupEssenceBySeq).toHaveBeenCalledWith('33', '22', '11');
});
test('passes msg_random before msg_seq for the essence LRU fallback', async () => {
// get_essence_msg_list stores this payload under a synthetic message_id when the
// original message can no longer be resolved from the local message cache.
const { action, removeGroupEssenceBySeq } = createAction(JSON.stringify({
msg_seq: '11',
msg_random: '22',
group_id: '33',
}));
vi.spyOn(MessageUnique, 'getMsgIdAndPeerByShortId').mockReturnValue(undefined);
await action._handle({ message_id: 12345 });
// GroupApi.removeGroupEssenceBySeq(groupCode, msgRandom, msgSeq)
expect(removeGroupEssenceBySeq).toHaveBeenCalledWith('33', '22', '11');
});
});
@@ -1,89 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { afterEach, describe, expect, test, vi } from 'vitest';
import type { NetworkAdapterConfig } from '../napcat-onebot/config/config';
import GetFriendMsgHistory from '../napcat-onebot/action/go-cqhttp/GetFriendMsgHistory';
// `GetFriendMsgHistory` imports `napcat-core/types` via the bare package subpath,
// which Node exports resolution cannot map in this workspace (`./*` pattern cannot
// target an extensionless directory). Remap it onto the aliased source tree.
vi.mock('napcat-core/types', async () => await vi.importActual('@/napcat-core/types/index'));
vi.mock('napcat-common/src/message-unique', async () => await vi.importActual('@/napcat-common/src/message-unique'));
const SAMPLE_MSG = {
msgId: '100',
msgSeq: '1',
chatType: 1,
peerUid: 'friend-uid',
peerUin: '42',
senderUin: '42',
msgTime: '1700000000',
msgRandom: '1',
elements: [],
} as never;
const TEST_ADAPTER = 'test';
const TEST_CONFIG = { messagePostFormat: 'array' } as NetworkAdapterConfig;
function createHistoryAction () {
const parseMessage = vi.fn().mockResolvedValue({ message: [], raw_message: '' });
const core = {
selfInfo: { uid: 'self-uid', uin: '1' },
apis: {
UserApi: { getUidByUinV2: vi.fn().mockResolvedValue('friend-uid') },
FriendApi: { isBuddy: vi.fn().mockResolvedValue(true) },
MsgApi: {
getAioFirstViewLatestMsgs: vi.fn().mockResolvedValue({ msgList: [SAMPLE_MSG] }),
},
},
};
const obContext = {
apis: { MsgApi: { parseMessage } },
};
const action = new GetFriendMsgHistory(obContext as never, core as never);
return { action, parseMessage };
}
describe('get_friend_msg_history quick_reply forwarding', () => {
afterEach(() => {
vi.restoreAllMocks();
});
test('forwards quick_reply: true to parseMessage', async () => {
const { action, parseMessage } = createHistoryAction();
await action._handle(
{ user_id: '42', count: 20, reverse_order: false, disable_get_url: false, parse_mult_msg: true, quick_reply: true, reverseOrder: false },
TEST_ADAPTER,
TEST_CONFIG
);
expect(parseMessage).toHaveBeenCalledWith(
SAMPLE_MSG,
'array',
true,
false,
true
);
});
test('forwards quick_reply: false (default) to parseMessage', async () => {
const { action, parseMessage } = createHistoryAction();
await action._handle(
{ user_id: '42', count: 20, reverse_order: false, disable_get_url: false, parse_mult_msg: true, quick_reply: false, reverseOrder: false },
TEST_ADAPTER,
TEST_CONFIG
);
expect(parseMessage).toHaveBeenCalledWith(
SAMPLE_MSG,
'array',
true,
false,
false
);
});
});
@@ -1,71 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, test, vi } from 'vitest';
import { GetGroupNotice } from '../napcat-onebot/action/group/GetGroupNotice';
function feed (fid: string, settings?: Record<string, number>) {
return {
u: 10001,
fid,
pubt: 1750000000,
msg: { text: `notice ${fid}`, text_face: '', title: '' },
type: 1,
fn: 0,
cn: 0,
vn: 0,
settings,
read_num: 3,
is_read: 0,
is_all_confirm: 0,
};
}
function createAction (ret: unknown) {
return new GetGroupNotice(
undefined as never,
{ apis: { WebApi: { getGroupNotice: vi.fn().mockResolvedValue(ret) } } } as never
);
}
describe('_get_group_notice', () => {
test('returns "send to new member" notices from inst after feeds', async () => {
const action = createAction({
ec: 0,
feeds: [feed('feed-1'), feed('feed-2')],
inst: [feed('inst-1', { inst_no_pinned: 0 })],
});
const notices = await action._handle({ group_id: '123' });
expect(notices.map(n => n.notice_id)).toEqual(['feed-1', 'feed-2', 'inst-1']);
expect(notices.map(n => n.send_to_new_member)).toEqual([false, false, true]);
expect(notices[2]?.message.text).toBe('notice inst-1');
});
test('maps inst_no_pinned to pinned only when the field is present', async () => {
const action = createAction({
ec: 0,
feeds: [feed('feed-1', { tip_window_type: 1 })],
inst: [feed('pinned', { inst_no_pinned: 0 }), feed('unpinned', { inst_no_pinned: 1 })],
});
const notices = await action._handle({ group_id: '123' });
expect(notices.find(n => n.notice_id === 'feed-1')?.pinned).toBeUndefined();
expect(notices.find(n => n.notice_id === 'pinned')?.pinned).toBe(true);
expect(notices.find(n => n.notice_id === 'unpinned')?.pinned).toBe(false);
});
test('keeps working when inst is missing and skips duplicated notices', async () => {
const withoutInst = await createAction({ ec: 0, feeds: [feed('feed-1')] })._handle({ group_id: '123' });
expect(withoutInst.map(n => n.notice_id)).toEqual(['feed-1']);
const duplicated = await createAction({
ec: 0,
feeds: [feed('same')],
inst: [feed('same', { inst_no_pinned: 0 })],
})._handle({ group_id: '123' });
expect(duplicated.map(n => n.notice_id)).toEqual(['same']);
});
});
@@ -1,282 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { NTQQWebApi } from '@/napcat-core/apis/webapi';
import { nextQunAlbumBatchId, qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl } from '@/napcat-core/data/webapi';
const GROUP_ID = '2161015335';
const ALBUM_ID = 'V624Oe3c1Dk7pX4et6lh4703uM49iGAR';
const ALBUM_NAME = '水哥';
const UIN = '2965296625';
// control_req 在严格模式(noUncheckedIndexedAccess)下是可选元素,这里统一收敛掉
const firstReq = (body: { control_req: unknown[] }) => {
const req = body.control_req[0];
if (!req) throw new Error('control_req 为空');
return req as NonNullable<ReturnType<typeof qunAlbumControl>['control_req'][0]>;
};
const imageReq = (overrides: Record<string, unknown> = {}) => firstReq(qunAlbumControl({
uin: UIN,
group_id: GROUP_ID,
pskey: 'PSKEY',
pic_md5: 'MD5A',
img_size: 12345,
img_name: 'a.jpg',
sAlbumName: ALBUM_NAME,
sAlbumID: ALBUM_ID,
...overrides,
}));
describe('群相册图片组包', () => {
it('单图:字段与改动前一致,批次号为秒级时间戳', () => {
const req = imageReq();
expect(req.appid).toBe('qun');
expect(req.cmd).toBe('FileUpload');
expect(req.check_type).toBe(0);
expect(req.checksum).toBe('MD5A');
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
expect(req.biz_req?.sPicTitle).toBe('a.jpg');
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
expect(req.biz_req?.iUploadType).toBe(0);
expect(req.biz_req?.iNeedFeeds).toBe(1);
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: '1', video_num: '0', batch_num: '1' });
// 每张图各自成批时,批次号仍是 10 位秒级时间戳
expect(String(req.biz_req?.iBatchID)).toHaveLength(10);
});
it('同一秒内的两次上传批次号不同,不会被相册并成一条', () => {
const first = imageReq().biz_req?.iBatchID;
const second = imageReq().biz_req?.iBatchID;
expect(second).toBeGreaterThan(first ?? Infinity);
expect(nextQunAlbumBatchId()).toBeGreaterThan(second ?? Infinity);
});
it('多图同批:共用批次号,张数与序号按批上报', () => {
const batchId = 1791038000;
const total = '3';
const reqs = [0, 1, 2].map(i => imageReq({
pic_md5: `MD5${i}`,
batchId,
batchIndex: String(i),
photo_num: total,
batch_num: total,
}));
expect(new Set(reqs.map(r => r.biz_req?.iBatchID)).size).toBe(1);
expect(reqs[0]?.biz_req?.iBatchID).toBe(batchId);
reqs.forEach((req, i) => {
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: total, video_num: '0', batch_num: total });
expect(req.biz_req?.mutliPicInfo).toEqual({
iBatUploadNum: total,
iCurUpload: String(i),
iSuccNum: 0,
iFailNum: 0,
});
expect(req.checksum).toBe(`MD5${i}`);
});
});
});
describe('群相册视频组包', () => {
it('视频主体:video_qun / FileUploadVideo / SHA1,且不带相册与批次号', () => {
const req = firstReq(qunAlbumVideoControl({
uin: UIN,
group_id: GROUP_ID,
pskey: 'PSKEY',
video_sha1: 'SHA1A',
video_size: 1048576,
play_time: 37,
}));
expect(req.appid).toBe('video_qun');
expect(req.cmd).toBe('FileUploadVideo');
expect(req.check_type).toBe(1);
expect(req.checksum).toBe('SHA1A');
expect(req.file_len).toBe(1048576);
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
expect(req.biz_req?.iUploadType).toBe(3);
expect(req.biz_req?.iPlayTime).toBe(37);
expect(req.biz_req?.iIsNew).toBe(111);
// 视频主体不参与批次:iBatchID 固定 0,相册留空,也没有 mutliPicInfo
expect(req.biz_req?.iBatchID).toBe(0);
expect(req.biz_req?.sAlbumID).toBe('');
expect(req.biz_req?.sAlbumName).toBe('');
expect(req.biz_req?.mutliPicInfo).toBeUndefined();
expect(req.biz_req?.stExtendInfo).toBeUndefined();
expect(req.biz_req?.mapExt).toBeUndefined();
expect(req.biz_req?.extend_info).toEqual({
video_type: '3',
domainid: '5',
photo_num: '0',
video_num: '1',
batch_num: '1',
qun_id: GROUP_ID,
});
});
it('封面二段:走图片口径带相册与批次号,并用 vid 绑定视频', () => {
const batchId = 1791038000;
const req = firstReq(qunAlbumVideoCoverControl({
uin: UIN,
group_id: GROUP_ID,
pskey: 'PSKEY',
sAlbumName: ALBUM_NAME,
sAlbumID: ALBUM_ID,
cover_md5: 'COVERMD5',
cover_size: 20000,
vid: 'SV123',
batchId,
}));
expect(req.appid).toBe('qun');
expect(req.cmd).toBeUndefined();
expect(req.check_type).toBe(0);
expect(req.checksum).toBe('COVERMD5');
// 封面这一步才带相册和批次号——视频靠它进相册
expect(req.env).toEqual({ refer: 'huodong', deviceInfo: 'h5' });
expect(req.biz_req?.iUploadType).toBe(2);
expect(req.biz_req?.iBatchID).toBe(batchId);
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
expect(req.biz_req?.iNeedFeeds).toBe(1);
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({
vid: 'SV123',
photo_num: '0',
video_num: '1',
batch_num: '1',
});
expect(req.biz_req?.stExternalMapExt).toEqual({
is_client_upload_cover: '1',
is_pic_video_mix_feeds: '1',
});
expect(req.biz_req?.mutliPicInfo).toEqual({
iBatUploadNum: '1',
iCurUpload: '0',
iSuccNum: 0,
iFailNum: 0,
});
expect(req.biz_req?.mapExt).toEqual({ appid: 'qun', userid: GROUP_ID });
});
});
describe('群相册分片上传', () => {
let tempDir: string;
let sliceFile: string;
const createApi = () => new NTQQWebApi(
{ logger: { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn(), logDebug: vi.fn() } } as never,
{ NapCatTempPath: tempDir } as never
);
beforeEach(async () => {
tempDir = await mkdtemp(path.join(tmpdir(), 'napcat-album-slice-'));
sliceFile = path.join(tempDir, 'payload.bin');
// 40000 字节 / 16384 分片 = 3 片
await writeFile(sliceFile, Buffer.alloc(40000, 7));
});
afterEach(async () => {
vi.unstubAllGlobals();
await rm(tempDir, { recursive: true, force: true });
});
it('按分片大小切片,把 appid/cmd 透传到每个分片请求,并回收 sVid', async () => {
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({
ret: 0,
msg: '',
data: { biz: { sVid: 'SV123' } },
}), { status: 200 }));
vi.stubGlobal('fetch', fetchMock);
const result = await createApi().uploadQunAlbumSlice(
sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384,
{ appid: 'video_qun', cmd: 'FileUploadVideo' }
);
expect(fetchMock).toHaveBeenCalledTimes(3);
expect(result).toMatchObject({ success: true, sVid: 'SV123' });
// 分片是并发发出的,调用顺序不确定,按 seq 建索引再断言
const forms = new Map(fetchMock.mock.calls.map((call) => {
const form = call[1]?.body as unknown as FormData;
return [form.get('seq'), form] as const;
}));
const first = forms.get('0');
expect(first).toBeDefined();
expect(first?.get('appid')).toBe('video_qun');
expect(first?.get('cmd')).toBe('FileUploadVideo');
expect(first?.get('session')).toBe('SESSION');
expect(first?.get('offset')).toBe('0');
expect(first?.get('end')).toBe('16384');
expect(first?.get('slice_size')).toBe('16384');
const urls = fetchMock.mock.calls.map(call => String(call[0]));
expect(urls.some(url => url.includes('seq=0&retry=0&offset=0&end=16384&total=40000'))).toBe(true);
expect(urls.some(url => url.includes('seq=2&retry=0&offset=32768&end=40000&total=40000'))).toBe(true);
// 路径必须跟随 cmd:视频走 /sliceUpload/FileUploadVideo,否则服务端不返回 sVid
expect(urls.every(url => url.includes('/webapp/json/sliceUpload/FileUploadVideo?'))).toBe(true);
});
it('不传 appid/cmd 时退回图片口径(路径也是 FileUpload)', async () => {
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 }));
vi.stubGlobal('fetch', fetchMock);
const result = await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
const form = fetchMock.mock.calls[0]?.[1]?.body as unknown as FormData;
expect(form.get('appid')).toBe('qun');
expect(form.get('cmd')).toBe('FileUpload');
expect(String(fetchMock.mock.calls[0]?.[0])).toContain('/webapp/json/sliceUpload/FileUpload?');
expect(result.sVid).toBeUndefined();
});
it('最后一片等其它分片全部传完才发', async () => {
// 100000 字节 / 16384 = 7 片(seq 0~6)
await writeFile(sliceFile, Buffer.alloc(100000, 7));
let finished = 0;
let finishedWhenLastSent = -1;
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
const seq = Number((init.body as unknown as FormData).get('seq'));
if (seq === 6) {
finishedWhenLastSent = finished;
} else {
// 前面的分片故意慢一点、倒序完成
await new Promise(resolve => setTimeout(resolve, (6 - seq) * 5));
finished++;
}
return new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 });
});
vi.stubGlobal('fetch', fetchMock);
await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
expect(fetchMock).toHaveBeenCalledTimes(7);
expect(finishedWhenLastSent).toBe(6);
});
it('前面的分片失败时不再发最后一片', async () => {
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
const seq = (init.body as unknown as FormData).get('seq');
return new Response(JSON.stringify(seq === '1' ? { ret: -1, msg: 'boom' } : { ret: 0, msg: '' }), { status: 200 });
});
vi.stubGlobal('fetch', fetchMock);
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
.rejects.toThrow('分片 1 上传失败: boom');
const seqs = fetchMock.mock.calls.map(call => (call[1]?.body as unknown as FormData).get('seq'));
expect(seqs).not.toContain('2');
});
it('分片失败时抛出带序号与原因的错误', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ ret: -1, msg: 'boom' }), { status: 200 })));
// 分片是并发上传的,Promise.all 抛出的是最先失败的那一片,序号不确定
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
.rejects.toThrow(/分片 \d+ 上传失败: boom/);
});
});
@@ -1,67 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, test, vi } from 'vitest';
import { 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' }));
});
});
-29
View File
@@ -1,29 +0,0 @@
import { describe, expect, test } from 'vitest';
import { OB11Construct } from '../napcat-onebot/helper/data';
describe('group file folder construction', () => {
test('exposes the last modification time and modifier of a folder', () => {
const folder = OB11Construct.folder('123', {
folderId: '/folder-1',
parentFolderId: '/',
folderName: '资料',
createTime: 1700000000,
modifyTime: 1750000000,
createUin: '10001',
creatorName: 'creator',
totalFileCount: 2,
modifyUin: '10002',
modifyName: 'uploader',
usedSpace: '0',
});
expect(folder).toMatchObject({
group_id: 123,
folder_id: '/folder-1',
creator: 10001,
modify_time: 1750000000,
modifier: 10002,
modifier_name: 'uploader',
});
});
});
@@ -1,140 +0,0 @@
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, test, vi } from 'vitest';
import { ChatType, type GroupMember, type RawMessage } from 'napcat-core';
import { NTQQGroupApi } from '../napcat-core/apis/group';
import { NTQQUserApi } from '../napcat-core/apis/user';
import { OneBotMsgApi } from '../napcat-onebot/api/msg';
vi.mock('../napcat-webui-backend/index', () => ({
pendingTokenToSend: undefined,
}));
vi.mock('../napcat-webui-backend/src/helper/Data', () => ({
WebUiDataRuntime: {},
}));
vi.mock('@/napcat-onebot/network', () => ({
OB11HttpClientAdapter: class {},
OB11WebSocketClientAdapter: class {},
OB11NetworkManager: class {},
OB11NetworkReloadType: {},
OB11HttpServerAdapter: class {},
OB11WebSocketServerAdapter: class {},
}));
vi.mock('@/napcat-onebot/api', () => ({
OneBotFriendApi: class {},
OneBotGroupApi: class {},
OneBotMsgApi: class {},
OneBotQuickActionApi: class {},
OneBotUserApi: class {},
}));
vi.mock('@/napcat-onebot/action', () => ({
createActionMap: vi.fn(),
}));
vi.mock('@/napcat-onebot/network/http-server-sse', () => ({
OB11HttpSSEServerAdapter: class {},
}));
vi.mock('@/napcat-onebot/network/plugin-manger', () => ({
OB11PluginMangerAdapter: class {},
}));
// msg.ts 按目录导入 proto,vitest 解析不了;这里用不到,给个空模块
vi.mock('napcat-core/packet/transformer/proto', () => ({}));
function member (uid: string, uin: string, nick: string) {
return { uid, uin, nick, cardName: '', role: 2 } as unknown as GroupMember;
}
function memberList (...members: GroupMember[]) {
return {
errCode: 0,
errMsg: '',
result: { ids: [], infos: new Map(members.map(m => [m.uid, m])), finish: true, hasRobot: false },
};
}
function createGroupApi (getAllMemberList: ReturnType<typeof vi.fn>) {
const context = {
session: { getGroupService: () => ({ getAllMemberList }) },
logger: { logError: vi.fn() },
};
return new NTQQGroupApi(context as never, {} as never);
}
describe('group member lookup', () => {
test('returns undefined instead of throwing when the member list of a new group cannot be fetched', async () => {
const getAllMemberList = vi.fn()
.mockRejectedValueOnce(new Error('timeout'))
.mockResolvedValueOnce({ errCode: 1, errMsg: 'not ready', result: undefined });
const groupApi = createGroupApi(getAllMemberList);
await expect(groupApi.getGroupMember('1053882091', '2060875951')).resolves.toBeUndefined();
await expect(groupApi.getGroupMember('1053882091', 'u_member')).resolves.toBeUndefined();
// 拉不到的结果不能写进缓存,否则之后一直拿到空成员表
expect(groupApi.groupMemberCache.has('1053882091')).toBe(false);
// 每次调用只拉一次,不会为同一条消息重复强制刷新
expect(getAllMemberList).toHaveBeenCalledTimes(2);
});
test('refreshes a cached group once when a new member is not in the cache yet', async () => {
const oldMember = member('u_old', '10001', 'old');
const newMember = member('u_new', '10002', 'new');
const getAllMemberList = vi.fn().mockResolvedValue(memberList(oldMember, newMember));
const groupApi = createGroupApi(getAllMemberList);
groupApi.groupMemberCache.set('123', new Map([[oldMember.uid, oldMember]]));
await expect(groupApi.getGroupMember('123', '10002')).resolves.toBe(newMember);
await expect(groupApi.getGroupMember('123', 'u_new')).resolves.toBe(newMember);
expect(getAllMemberList).toHaveBeenCalledTimes(1);
});
test('uin to uid falls back to the cached group members before the network lookup', async () => {
const groupApi = createGroupApi(vi.fn());
groupApi.groupMemberCache.set('123', new Map([['u_new', member('u_new', '3680714873', 'new')]]));
const callNoListenerEvent = vi.fn();
const context = {
session: {
getUixConvertService: () => ({ getUid: vi.fn().mockResolvedValue({ uidInfo: new Map() }) }),
getProfileService: () => ({ getUidByUin: vi.fn().mockReturnValue(new Map()) }),
getGroupService: () => ({ getUidByUins: vi.fn().mockResolvedValue({ uids: new Map() }) }),
},
};
const userApi = new NTQQUserApi(context as never, {
apis: { GroupApi: groupApi },
eventWrapper: { callNoListenerEvent },
} as never);
await expect(userApi.getUidByUinV2('3680714873')).resolves.toBe('u_new');
expect(callNoListenerEvent).not.toHaveBeenCalled();
});
test('temp messages look up the sender in the source group instead of using the sender QQ as group', async () => {
const getGroupMember = vi.fn().mockResolvedValue(member('u_temp', '3680714873', 'temp sender'));
const msgApi = new OneBotMsgApi(undefined as never, {
apis: {
MsgApi: { getTempChatInfo: vi.fn().mockResolvedValue({ result: 0, tmpChatInfo: { groupCode: '603036233' } }) },
GroupApi: { getGroupMember },
},
} as never);
const resMsg = { sender: {} } as Record<string, unknown> & { sender: Record<string, unknown>; };
const msg = {
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
senderUid: 'u_temp',
senderUin: '3680714873',
peerUid: 'u_temp',
peerUin: '3680714873',
} as RawMessage;
await (msgApi as unknown as { handleTempGroupMessage (r: unknown, m: RawMessage): Promise<void>; })
.handleTempGroupMessage(resMsg, msg);
expect(getGroupMember).toHaveBeenCalledWith('603036233', 'u_temp');
expect(resMsg).toMatchObject({ sub_type: 'group', group_id: 603036233, sender: { nickname: 'temp sender' } });
});
});
@@ -1,126 +0,0 @@
import { describe, expect, test } from 'vitest';
import type { GeneralCallResultStatus } from '../napcat-core/services/common';
import {
applyGroupManagementSettings,
createGroupDetailInfoV2Param,
createGroupManagementRequests,
} from '../napcat-core/data/group';
import { assertGroupManagementResults } from '../napcat-onebot/action/group/GroupOperationHelpers';
describe('NTQQ group operations', () => {
test('reports the exact native setting that failed', () => {
expect(() => assertGroupManagementResults('设置群成员功能权限', [{
setting: 'allow_member_create_group',
// 枚举里只有 OK/ERROR,这里刻意用一个任意的原生错误码
result: { result: 1006 as GeneralCallResultStatus, errMsg: '未知错误' },
}])).toThrow(/allow_member_create_group.*1006.*未知错误/);
expect(() => assertGroupManagementResults('设置群成员功能权限', []))
.not.toThrow();
});
test('builds the NTQQ permission masks without changing unrelated flags', async () => {
const request = createGroupDetailInfoV2Param('123456');
expect(applyGroupManagementSettings(request, {
memberInvite: 'no_approval',
allowMemberUploadAlbum: false,
allowMemberTemporarySession: true,
allowMemberCreateGroup: false,
newMembersSeeRecentHistory: true,
})).toBe(true);
expect(request.groupCode).toBe('123456');
expect(request.filter).toMatchObject({
allowMemberInvite: 1,
appPrivilegeFlag: 1,
appPrivilegeMask: 1,
groupFlagExt4: 1,
groupFlagExt4Mask: 1,
});
expect(request.modifyInfo).toMatchObject({
allowMemberInvite: 1,
appPrivilegeFlag: 0x00108001,
appPrivilegeMask: 0x06118001,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
groupFlagExt4: 0x4,
groupFlagExt4Mask: 0x4,
});
});
test('maps every member invite policy to the native app privilege value', async () => {
const expected = {
disabled: 0x04000000,
require_approval: 0,
no_approval: 0x00100000,
no_approval_under_100: 0x02000000,
} as const;
for (const [memberInvite, privilegeFlag] of Object.entries(expected)) {
const request = createGroupDetailInfoV2Param('123456');
applyGroupManagementSettings(request, { memberInvite: memberInvite as keyof typeof expected });
expect(request.modifyInfo.allowMemberInvite).toBe(memberInvite === 'disabled' ? 0 : 1);
expect(request.modifyInfo.appPrivilegeFlag).toBe(privilegeFlag);
expect(request.modifyInfo.appPrivilegeMask).toBe(0x06100000);
}
});
test('uses NTQQ privilege operation type 8 for album, temporary-session, and create-group flags', () => {
const requests = createGroupManagementRequests('123456', {
memberInvite: 'require_approval',
allowMemberUploadAlbum: true,
allowMemberTemporarySession: true,
allowMemberCreateGroup: true,
}, 0x18001);
expect(requests.map(request => request.operationType)).toEqual([0, 8, 8, 8]);
expect(requests.map(request => request.setting)).toEqual([
'member_invite',
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
]);
expect(requests.slice(1).map(request => request.param.modifyInfo.appPrivilegeMask))
.toEqual([0x1, 0x10000, 0x8000]);
expect(requests[1]?.param.modifyInfo).toMatchObject({
appPrivilegeFlag: 0x18000,
appPrivilegeMask: 0x1,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
});
expect(requests[2]?.param.modifyInfo).toMatchObject({
appPrivilegeFlag: 0x8000,
appPrivilegeMask: 0x10000,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
});
expect(requests[3]?.param.modifyInfo).toMatchObject({
appPrivilegeFlag: 0,
appPrivilegeMask: 0x8000,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
});
});
test('preserves the complete privilege value when clearing Linux NTQQ permission bits', () => {
const requests = createGroupManagementRequests('123456', {
allowMemberUploadAlbum: false,
allowMemberTemporarySession: false,
allowMemberCreateGroup: false,
}, 0);
expect(requests.map(request => request.param.modifyInfo.appPrivilegeFlag))
.toEqual([0x1, 0x10001, 0x18001]);
expect(requests.map(request => request.param.modifyInfo.appPrivilegeMask))
.toEqual([0x1, 0x10000, 0x8000]);
});
test('skips privilege requests whose effective value is already current', () => {
const requests = createGroupManagementRequests('123456', {
allowMemberUploadAlbum: true,
allowMemberTemporarySession: true,
allowMemberCreateGroup: true,
newMembersSeeRecentHistory: true,
}, 0x00100000, 0x4);
expect(requests).toEqual([]);
});
});
@@ -1,46 +0,0 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import { loadQQWrapper } from '../napcat-core/index';
describe('loadQQWrapper', () => {
const originalWrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
beforeEach(() => {
process.env['NAPCAT_WRAPPER_PATH'] = 'E:\\NapCat\\wrapper.node';
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw new Error('The specified module could not be found.\r\n\\\\?\\E:\\NapCat\\wrapper.node');
});
});
afterEach(() => {
vi.restoreAllMocks();
if (originalWrapperPath === undefined) {
delete process.env['NAPCAT_WRAPPER_PATH'];
} else {
process.env['NAPCAT_WRAPPER_PATH'] = originalWrapperPath;
}
});
test('explains the missing Media Foundation feature on Windows Server', () => {
vi.spyOn(os, 'platform').mockReturnValue('win32');
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(() => loadQQWrapper(undefined, '9.9.33-52230'))
.toThrow(/媒体基础.*Install-WindowsFeature Server-Media-Foundation.*The specified module could not be found/s);
});
test('keeps the original error when Media Foundation is installed', () => {
vi.spyOn(os, 'platform').mockReturnValue('win32');
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(() => loadQQWrapper(undefined, '9.9.33-52230')).toThrow(/^The specified module could not be found/);
});
test('keeps the original error on other platforms', () => {
vi.spyOn(os, 'platform').mockReturnValue('linux');
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(() => loadQQWrapper(undefined, '3.2.32-52194')).toThrow(/^The specified module could not be found/);
});
});
-89
View File
@@ -1,89 +0,0 @@
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'] });
});
});
@@ -1,98 +0,0 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { createOfflineRecovery } from '../napcat-core/helper/offline-recovery';
function setup (restartResult: boolean | Error = true) {
const state = { online: false };
const onOffline = vi.fn();
const onRecovered = vi.fn();
const restart = vi.fn(async () => {
if (restartResult instanceof Error) throw restartResult;
return restartResult;
});
const handleOffline = createOfflineRecovery({
isOnline: () => state.online,
onOffline,
onRecovered,
restart,
});
return { state, onOffline, onRecovered, restart, handleOffline };
}
describe('offline recovery', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
test('kicked offline restarts after a short delay', async () => {
const { restart, onOffline, handleOffline } = setup();
handleOffline('kicked', false);
expect(onOffline).toHaveBeenCalledWith('kicked');
await vi.advanceTimersByTimeAsync(3_000);
expect(restart).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(500);
expect(restart).toHaveBeenCalledTimes(1);
expect(restart).toHaveBeenCalledWith('kicked');
});
test('silent offline waits for the account to reconnect before restarting', async () => {
const { restart, handleOffline } = setup();
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(60_000);
expect(restart).toHaveBeenCalledTimes(1);
});
test('silent offline that recovers on its own does not restart', async () => {
const { state, restart, onRecovered, handleOffline } = setup();
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(10_000);
state.online = true;
await vi.advanceTimersByTimeAsync(60_000);
expect(restart).not.toHaveBeenCalled();
expect(onRecovered).toHaveBeenCalledTimes(1);
});
test('a kick during the silent-offline wait restarts without waiting the full minute', async () => {
const { restart, handleOffline } = setup();
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(1_000);
handleOffline('kicked', false);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).toHaveBeenCalledTimes(1);
expect(restart).toHaveBeenCalledWith('kicked');
await vi.advanceTimersByTimeAsync(120_000);
expect(restart).toHaveBeenCalledTimes(1);
});
test('repeated offline events schedule only one restart', async () => {
const { restart, onOffline, handleOffline } = setup();
handleOffline('kicked', false);
handleOffline('kicked again', false);
handleOffline('silent', true);
await vi.advanceTimersByTimeAsync(120_000);
expect(restart).toHaveBeenCalledTimes(1);
expect(onOffline).toHaveBeenCalledTimes(3);
});
test.each([false, new Error('boom')])('a failed restart (%s) can be retried by the next offline event', async (result) => {
const { restart, handleOffline } = setup(result);
handleOffline('kicked', false);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).toHaveBeenCalledTimes(1);
handleOffline('kicked', false);
await vi.advanceTimersByTimeAsync(3_500);
expect(restart).toHaveBeenCalledTimes(2);
});
});
@@ -1,123 +0,0 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { NapCatCore } from '../napcat-core/index';
import type { SelfStatusInfo, SelfInfo } from '../napcat-core/types';
interface FakeProfileListener {
onSelfStatusChanged: (info: SelfStatusInfo) => void;
}
interface FakeMessageListener {
onKickedOffLine: (info: { tipsTitle: string; tipsDesc: string; }) => void;
}
function status (value: number): SelfStatusInfo {
return {
uid: 'self-uid',
status: value,
extStatus: 0,
termType: 0,
netType: 0,
iconType: 0,
customStatus: undefined,
setTime: '0',
};
}
function createCore (online: boolean | undefined) {
let profileListener: FakeProfileListener | undefined;
let messageListener: FakeMessageListener | undefined;
const session = {
getMsgService: () => ({
addKernelMsgListener: vi.fn((listener: FakeMessageListener) => {
messageListener = listener;
}),
}),
getProfileService: () => ({
addKernelProfileListener: vi.fn((listener: FakeProfileListener) => {
profileListener = listener;
}),
}),
};
const logger = {
log: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
logDebug: vi.fn(),
};
const emit = vi.fn();
// NapCatCore's constructor loads the native wrapper, which is unavailable in tests.
// Only the listener wiring is under test, so the instance is built field-by-field.
const core = Object.create(NapCatCore.prototype) as NapCatCore;
Object.assign(core, {
context: { logger, session },
selfInfo: { uid: 'self-uid', uin: '1', online } as SelfInfo,
event: { emit },
});
return {
core,
emit,
profileListener: () => profileListener,
messageListener: () => messageListener,
};
}
describe('silent offline (SelfOffline) event', () => {
afterEach(() => {
vi.restoreAllMocks();
});
test('emits SelfOffline when the account transitions online -> offline', async () => {
const { core, emit, profileListener } = createCore(true);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).toHaveBeenCalledTimes(1);
expect(emit).toHaveBeenCalledWith('SelfOffline', expect.stringContaining('账号状态变更为离线'));
expect(core.selfInfo.online).toBe(false);
});
test('does not emit again while the account stays offline', async () => {
const { core, emit, profileListener } = createCore(true);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
profileListener()!.onSelfStatusChanged(status(20));
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).toHaveBeenCalledTimes(1);
});
test('emits again after the account recovered and went offline once more', async () => {
const { core, emit, profileListener } = createCore(true);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
profileListener()!.onSelfStatusChanged(status(10));
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).toHaveBeenCalledTimes(2);
expect(core.selfInfo.online).toBe(false);
});
test('does not emit during startup when the account was never online', async () => {
const { core, emit, profileListener } = createCore(undefined);
await core.initNapCatCoreListeners();
profileListener()!.onSelfStatusChanged(status(20));
expect(emit).not.toHaveBeenCalled();
expect(core.selfInfo.online).toBe(false);
});
test('keeps emitting KickedOffLine as before', async () => {
const { core, emit, messageListener } = createCore(true);
await core.initNapCatCoreListeners();
messageListener()!.onKickedOffLine({ tipsTitle: '下线通知', tipsDesc: '当前账号已在其它设备登录' });
expect(emit).toHaveBeenCalledTimes(1);
expect(emit).toHaveBeenCalledWith('KickedOffLine', expect.stringContaining('当前账号已在其它设备登录'));
expect(core.selfInfo.online).toBe(false);
});
});
+1 -3
View File
@@ -5,11 +5,9 @@
"type": "module",
"scripts": {
"test": "vitest",
"test:ui": "vitest --ui",
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
"test:ui": "vitest --ui"
},
"devDependencies": {
"@types/node": "^22.0.1",
"vitest": "^4.0.9"
},
"dependencies": {
-72
View File
@@ -1,72 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
vi.mock('@/napcat-core/index', () => ({ getMajorPath: vi.fn() }));
describe('QQ AppID lookup', () => {
let info: QQBasicInfoWrapper;
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
beforeEach(() => {
Object.defineProperty(process, 'arch', { ...archDescriptor, value: 'x64' });
info = Object.create(QQBasicInfoWrapper.prototype);
info.context = { logger: { log: vi.fn() } } as unknown as QQBasicInfoWrapper['context'];
vi.spyOn(info, 'getFullQQVersion');
vi.spyOn(info, 'getAppidV2ByMajor').mockReturnValue('537999999');
});
afterEach(() => {
Object.defineProperty(process, 'arch', archDescriptor);
vi.restoreAllMocks();
});
it.each([
['3.2.30-50969', 'x64', 537376344],
['3.2.30-50969', 'arm64', 537376345],
['3.2.32-52194', 'x64', 537379447],
['3.2.32-52194', 'arm64', 537379448],
['3.2.33-52892', 'x64', 537382855],
['3.2.33-52892', 'arm64', 537382856],
] as const)('uses the scanned AppID for Linux %s %s', (version, arch, appid) => {
Object.defineProperty(process, 'arch', { ...archDescriptor, value: arch });
vi.mocked(info.getFullQQVersion).mockReturnValue(version);
expect(info.getAppidV2()).toEqual({
appid,
qua: `V1_LNX_NQ_${version.replace('-', '_')}_GW_B`,
});
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
});
it.each([
['9.9.33-52230', 537379411],
['9.9.35-52892', 537382819],
] as const)('finds Windows %s by its actual package version', (version, appid) => {
vi.mocked(info.getFullQQVersion).mockReturnValue(version);
expect(info.getAppidV2()).toEqual({
appid,
qua: `V1_WIN_NQ_${version.replace('-', '_')}_GW_B`,
});
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
});
it('preserves version-only entries when an architecture override is absent', () => {
Object.defineProperty(process, 'arch', { ...archDescriptor, value: 'arm64' });
vi.mocked(info.getFullQQVersion).mockReturnValue('3.2.29-49738');
expect(info.getAppidV2()).toEqual({
appid: 537355867,
qua: 'V1_LNX_NQ_3.2.29_49738_GW_B',
});
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
});
it('still scans major.node for an unknown version', () => {
vi.mocked(info.getFullQQVersion).mockReturnValue('3.2.99-99999');
vi.spyOn(info, 'getQUAFallback').mockReturnValue('fallback-qua');
expect(info.getAppidV2()).toEqual({ appid: '537999999', qua: 'fallback-qua' });
expect(info.getAppidV2ByMajor).toHaveBeenCalledWith('3.2.99-99999');
});
});
-120
View File
@@ -1,120 +0,0 @@
import { describe, expect, test } from 'vitest';
import {
buildQzoneDeleteBody,
buildQzonePublishBody,
buildQzoneUploadImageBody,
parseQzoneDeleteResponse,
parseQzonePublishResponse,
parseQzoneUploadImageResponseText,
toQzoneRichval,
} from '@/napcat-core/data/qzone';
describe('Qzone data helpers', () => {
test('buildQzoneUploadImageBody encodes required fields', () => {
const body = buildQzoneUploadImageBody({
uin: '123456',
skey: 'sk',
pskey: 'pk',
g_tk: '999',
base64: 'AAAA',
});
const params = new URLSearchParams(body);
expect(params.get('uin')).toBe('123456');
expect(params.get('skey')).toBe('sk');
expect(params.get('p_skey')).toBe('pk');
expect(params.get('picfile')).toBe('AAAA');
expect(params.get('uploadtype')).toBe('1');
expect(params.get('albumtype')).toBe('7');
expect(params.get('base64')).toBe('1');
expect(params.get('qzreferrer')).toContain('123456');
});
test('parseQzoneUploadImageResponseText parses valid callback wrapper', () => {
const raw = 'frameElement.callback({"code":0,"data":{"albumid":"a1","lloc":"l1","type":"22","height":"100","width":"200"}});</script>';
const parsed = parseQzoneUploadImageResponseText(raw);
expect(parsed.code).toBe(0);
expect(parsed.data?.albumid).toBe('a1');
expect(parsed.data?.lloc).toBe('l1');
});
test('parseQzoneUploadImageResponseText throws on malformed response', () => {
expect(() => parseQzoneUploadImageResponseText('not a valid response')).toThrow();
});
test('toQzoneRichval builds expected format', () => {
const richval = toQzoneRichval({ albumid: 'a1', lloc: 'l1', type: '22', height: '100', width: '200' });
expect(richval).toBe(',a1,l1,l1,22,100,200,,100,200');
});
test('buildQzonePublishBody without images omits richval/richtype', () => {
const body = buildQzonePublishBody({
hostuin: '123456',
content: 'hello world',
ugcRight: 1,
});
const params = new URLSearchParams(body);
expect(params.get('con')).toBe('hello world');
expect(params.get('ugc_right')).toBe('1');
expect(params.has('richval')).toBe(false);
expect(params.has('richtype')).toBe(false);
expect(params.has('allow_uins')).toBe(false);
});
test('buildQzonePublishBody with images and allow_uins sets richtype and who', () => {
const body = buildQzonePublishBody({
hostuin: '123456',
content: 'with pic',
richval: ',a1,l1,l1,22,100,200,,100,200\t,a2,l2,l2,22,100,200,,100,200',
ugcRight: 16,
allowUins: '10001|10002',
});
const params = new URLSearchParams(body);
expect(params.get('richtype')).toBe('1');
expect(params.get('richval')).toContain('\t');
expect(params.get('ugc_right')).toBe('16');
expect(params.get('allow_uins')).toBe('10001|10002');
expect(params.get('who')).toBe('1');
});
test('parseQzonePublishResponse extracts tid on success', () => {
const result = parseQzonePublishResponse({ subcode: 0, tid: 'tid123' });
expect(result.tid).toBe('tid123');
});
test('parseQzonePublishResponse prefers t1_tid over tid', () => {
const result = parseQzonePublishResponse({ subcode: 0, tid: 'tid123', t1_tid: 't1tid456' });
expect(result.tid).toBe('t1tid456');
});
test('parseQzonePublishResponse throws when subcode indicates failure', () => {
expect(() => parseQzonePublishResponse({ subcode: -200, message: '权限不足' })).toThrow('权限不足');
});
test('parseQzonePublishResponse throws when tid missing', () => {
expect(() => parseQzonePublishResponse({ subcode: 0 })).toThrow();
});
test('buildQzoneDeleteBody encodes required fields', () => {
const body = buildQzoneDeleteBody({ hostuin: '123456', tid: 'tid123' });
const params = new URLSearchParams(body);
expect(params.get('hostuin')).toBe('123456');
expect(params.get('tid')).toBe('tid123');
expect(params.get('t1_source')).toBe('1');
expect(params.get('code_version')).toBe('1');
expect(params.get('format')).toBe('json');
expect(params.get('qzreferrer')).toContain('123456');
});
test('parseQzoneDeleteResponse succeeds when subcode is 0', () => {
const result = parseQzoneDeleteResponse({ subcode: 0 });
expect(result.success).toBe(true);
});
test('parseQzoneDeleteResponse throws when subcode indicates failure', () => {
expect(() => parseQzoneDeleteResponse({ subcode: -200, message: '权限不足' })).toThrow('权限不足');
});
test('parseQzoneDeleteResponse throws with default message when subcode indicates failure without message', () => {
expect(() => parseQzoneDeleteResponse({ subcode: -200 })).toThrow('subcode=-200');
});
});
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more