Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83c1d1d596 | ||
|
|
05feca9a2c | ||
|
|
f750d95545 | ||
|
|
ec6aadaeea | ||
|
|
463d3ea5b1 | ||
|
|
0d6ce7f509 | ||
|
|
4f1401da78 | ||
|
|
9109b8cfe2 | ||
|
|
297133a1b1 | ||
|
|
454cc0eda2 | ||
|
|
435cb7cf52 | ||
|
|
8005afebd2 | ||
|
|
a8f6a57311 | ||
|
|
c0fd089539 | ||
|
|
88643854a0 | ||
|
|
9a06abbbbd | ||
|
|
8371359677 | ||
|
|
651c15aa61 | ||
|
|
00729e4807 | ||
|
|
5ef4f6cb7c | ||
|
|
13a8a2b8dd | ||
|
|
8d69a8e086 | ||
|
|
26d7533e0f | ||
|
|
870a6060b8 | ||
|
|
0b4cfe65ed | ||
|
|
46e505f4ba | ||
|
|
2049e64260 | ||
|
|
7a35ef035a | ||
|
|
c75d2f7f86 | ||
|
|
fa3fe9fdb2 | ||
|
|
464bc3d4a7 | ||
|
|
3c03b162f5 | ||
|
|
4079214dc5 | ||
|
|
109d0c1dff | ||
|
|
96de2314b0 | ||
|
|
eecb02140f | ||
|
|
3ac54c181b | ||
|
|
0c4c371eee | ||
|
|
af07479351 | ||
|
|
c59a47a5a7 | ||
|
|
49ea8d5624 | ||
|
|
fe7a1f053a | ||
|
|
0fcd0e80e0 | ||
|
|
624ecf5b9a | ||
|
|
63a349d119 | ||
|
|
56549cd0f2 | ||
|
|
ead24423b5 | ||
|
|
f0e045df35 | ||
|
|
33ee94ab0f | ||
|
|
cbec362ed1 | ||
|
|
766ca6e071 | ||
|
|
7c2514be6c | ||
|
|
738e272d2c | ||
|
|
f7edbfd8d9 | ||
|
|
74dc33fee6 | ||
|
|
c95dd3d030 | ||
|
|
68e6a9bff9 | ||
|
|
5c18a62530 | ||
|
|
a82a5d5203 | ||
|
|
93efce86ca | ||
|
|
091c012427 | ||
|
|
8a3faf64f9 | ||
|
|
fbd70bbb04 | ||
|
|
c405b6d0a4 | ||
|
|
3a4b335062 | ||
|
|
9aa11fd7c4 | ||
|
|
8ae11bfdca | ||
|
|
6acf350613 | ||
|
|
0af6445d5a | ||
|
|
a716a1a185 | ||
|
|
8c9fc7edf4 | ||
|
|
1abad76ac9 | ||
|
|
484c181050 | ||
|
|
9d652be35d | ||
|
|
f226c83595 | ||
|
|
b565f876c5 | ||
|
|
19a5febb1a | ||
|
|
bbf822035f | ||
|
|
a2b0ac10a0 |
No files matched your search
@@ -5,12 +5,14 @@
|
||||
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
|
||||
**默认WebUi密钥为随机密码 控制台查看**
|
||||
|
||||
**[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)
|
||||
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
|
||||
|
||||
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
|
||||
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
|
||||
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
|
||||
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
|
||||
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
|
||||
**MacOS 暂不支持**
|
||||
## 如果WinX64缺少运行库或者xxx.dll?
|
||||
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
- **控制数量**:最终保持 5-15 条更新要点
|
||||
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
|
||||
|
||||
## 输出模板 - 必须严格遵守以下格式
|
||||
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
|
||||
|
||||
```
|
||||
# {VERSION}
|
||||
@@ -44,12 +44,14 @@ NapCat.Shell.Windows.OneKey.zip (无头)
|
||||
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
|
||||
**默认WebUi密钥为随机密码 控制台查看**
|
||||
|
||||
**[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)
|
||||
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
|
||||
|
||||
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
|
||||
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
|
||||
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
|
||||
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
|
||||
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
|
||||
**MacOS 暂不支持**
|
||||
## 如果WinX64缺少运行库或者xxx.dll?
|
||||
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
|
||||
|
||||
@@ -76,7 +78,7 @@ NapCat.Shell.Windows.OneKey.zip (无头)
|
||||
- "Windows 一键包"部分的文本必须完全一致,不要修改任何措辞
|
||||
- "警告"部分必须包含所有 QQ 版本下载链接,保持原有格式
|
||||
- "如果WinX64缺少运行库或者xxx.dll?"这一行必须保持原样
|
||||
- QQ 版本号和下载链接保持不变(40990 版本)
|
||||
- QQ 版本号、下载链接、"官方 CDN"标注和"MacOS 暂不支持"保持不变
|
||||
- 只有"## 更新"部分下面的内容需要根据实际 commit 生成
|
||||
|
||||
## 重要约束
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
|
||||
import { join, basename, resolve } from 'node:path';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
|
||||
import { toProxyUrl } from './lib/comment.ts';
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(NapCatWindowsLoaderTest LANGUAGES CXX)
|
||||
add_executable(windows-loader-test probe.cpp)
|
||||
@@ -0,0 +1,96 @@
|
||||
#include <windows.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
using QueryByName = BOOL(WINAPI *)(PCWSTR, FILE_INFO_BY_NAME_CLASS, PVOID, ULONG);
|
||||
|
||||
int wmain(int argumentCount, wchar_t **arguments)
|
||||
{
|
||||
if (argumentCount != 3)
|
||||
return 2;
|
||||
|
||||
const wchar_t *providers[] = {L"kernel32.dll", L"kernelbase.dll", L"api-ms-win-core-file-l2-1-4.dll"};
|
||||
HMODULE providerModules[3]{};
|
||||
QueryByName nativeQueries[3]{};
|
||||
unsigned char nativeCode[3][12]{};
|
||||
unsigned char nativeInfo[3][4][1024]{};
|
||||
BOOL nativeResults[3][4]{};
|
||||
DWORD nativeErrors[3][4]{};
|
||||
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
|
||||
{
|
||||
providerModules[providerIndex] = LoadLibraryW(providers[providerIndex]);
|
||||
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
|
||||
if (!query)
|
||||
return 3;
|
||||
nativeQueries[providerIndex] = query;
|
||||
std::memcpy(nativeCode[providerIndex], reinterpret_cast<void *>(query), sizeof(nativeCode[providerIndex]));
|
||||
for (int infoClass = 0; infoClass < 4; ++infoClass)
|
||||
{
|
||||
SetLastError(ERROR_SUCCESS);
|
||||
nativeResults[providerIndex][infoClass] = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), nativeInfo[providerIndex][infoClass], sizeof(nativeInfo[providerIndex][infoClass]));
|
||||
nativeErrors[providerIndex][infoClass] = GetLastError();
|
||||
}
|
||||
}
|
||||
|
||||
FILE_STAT_BASIC_INFORMATION expected{};
|
||||
if (!nativeQueries[0](arguments[2], FileStatBasicByNameInfo, &expected, sizeof(expected)))
|
||||
return 4;
|
||||
if (_wputenv_s(L"NAPCAT_LOAD_PATH", arguments[2]) || _wputenv_s(L"NAPCAT_PATCH_PACKAGE", arguments[2]))
|
||||
return 5;
|
||||
if (!LoadLibraryW(arguments[1]))
|
||||
{
|
||||
std::printf("LoadLibrary failed: %lu\n", GetLastError());
|
||||
return 6;
|
||||
}
|
||||
|
||||
const std::wstring missingRoot = L"C:\\napcat-loader-test-" + std::to_wstring(GetCurrentProcessId());
|
||||
const std::wstring loaderPath = missingRoot + L"\\loadNapCat.js";
|
||||
const std::wstring packagePath = missingRoot + L"\\resources\\app\\package.json";
|
||||
const std::wstring unrelatedPath = missingRoot + L"\\unrelated.txt";
|
||||
const wchar_t *redirectedPaths[] = {loaderPath.c_str(), packagePath.c_str()};
|
||||
int failures = 0;
|
||||
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
|
||||
{
|
||||
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
|
||||
bool preserved = std::memcmp(nativeCode[providerIndex], reinterpret_cast<void *>(nativeQueries[providerIndex]), sizeof(nativeCode[providerIndex])) == 0;
|
||||
std::wprintf(L"%ls native code preserved: %ls\n", providers[providerIndex], preserved ? L"PASS" : L"FAIL");
|
||||
failures += !preserved;
|
||||
for (int infoClass = 0; infoClass < 4; ++infoClass)
|
||||
{
|
||||
unsigned char actual[1024]{};
|
||||
SetLastError(ERROR_SUCCESS);
|
||||
BOOL result = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), actual, sizeof(actual));
|
||||
DWORD error = GetLastError();
|
||||
bool passed = result == nativeResults[providerIndex][infoClass] &&
|
||||
(result ? std::memcmp(actual, nativeInfo[providerIndex][infoClass], sizeof(actual)) == 0 : error == nativeErrors[providerIndex][infoClass]);
|
||||
std::wprintf(L"%ls information class %d native parity: %ls\n", providers[providerIndex], infoClass, passed ? L"PASS" : L"FAIL");
|
||||
failures += !passed;
|
||||
}
|
||||
for (const auto *redirectedPath : redirectedPaths)
|
||||
{
|
||||
FILE_STAT_BASIC_INFORMATION actual{};
|
||||
BOOL result = query(redirectedPath, FileStatBasicByNameInfo, &actual, sizeof(actual));
|
||||
bool passed = result && actual.EndOfFile.QuadPart == expected.EndOfFile.QuadPart &&
|
||||
actual.FileId.QuadPart == expected.FileId.QuadPart && actual.FileAttributes == expected.FileAttributes;
|
||||
std::wprintf(L"%ls redirect %ls: %ls\n", providers[providerIndex], redirectedPath, passed ? L"PASS" : L"FAIL");
|
||||
failures += !passed;
|
||||
}
|
||||
FILE_STAT_BASIC_INFORMATION missing{};
|
||||
SetLastError(ERROR_SUCCESS);
|
||||
BOOL nativeResult = nativeQueries[providerIndex](unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
|
||||
DWORD nativeError = GetLastError();
|
||||
SetLastError(ERROR_SUCCESS);
|
||||
BOOL result = query(unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
|
||||
bool passed = !result && result == nativeResult && GetLastError() == nativeError;
|
||||
std::wprintf(L"%ls unrelated missing file: %ls\n", providers[providerIndex], passed ? L"PASS" : L"FAIL");
|
||||
failures += !passed;
|
||||
}
|
||||
FILE_STAT_BASIC_INFORMATION direct{};
|
||||
BOOL result = GetFileInformationByName(loaderPath.c_str(), FileStatBasicByNameInfo, &direct, sizeof(direct));
|
||||
bool passed = result && direct.FileId.QuadPart == expected.FileId.QuadPart && direct.EndOfFile.QuadPart == expected.EndOfFile.QuadPart;
|
||||
std::printf("static import redirection: %s\n", passed ? "PASS" : "FAIL");
|
||||
failures += !passed;
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -9,6 +9,26 @@ on:
|
||||
permissions: write-all
|
||||
|
||||
jobs:
|
||||
windows-loader-test:
|
||||
name: Windows Loader Test
|
||||
needs: build
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: shell-dist
|
||||
- name: Verify Windows loader file queries
|
||||
shell: pwsh
|
||||
run: |
|
||||
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/shell-dist/NapCatWinBootHook.dll" "$pwd/shell-dist/loadNapCat.js"
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
typecheck-and-test:
|
||||
name: Type Check & Test
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -9,8 +9,8 @@ on:
|
||||
type: string
|
||||
|
||||
env:
|
||||
QQ_URL_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage'
|
||||
QQ_URL_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage'
|
||||
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.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'
|
||||
|
||||
jobs:
|
||||
get-version:
|
||||
|
||||
@@ -12,7 +12,7 @@ permissions: write-all
|
||||
|
||||
env:
|
||||
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
|
||||
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
|
||||
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
|
||||
RELEASE_NAME: "NapCat"
|
||||
|
||||
jobs:
|
||||
@@ -35,6 +35,11 @@ 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:
|
||||
@@ -42,8 +47,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 }}
|
||||
@@ -61,6 +66,11 @@ 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:
|
||||
@@ -76,12 +86,18 @@ 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: napcat-downloads-qq9.9.27.45627-node22.11.0
|
||||
key: ${{ steps.download-cache-key.outputs.key }}
|
||||
|
||||
- name: Download QQ and Node.js
|
||||
if: steps.cache-downloads.outputs.cache-hit != 'true'
|
||||
@@ -90,15 +106,20 @@ jobs:
|
||||
mkdir -p /tmp/napcat-downloads
|
||||
cd /tmp/napcat-downloads
|
||||
|
||||
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
|
||||
echo "Downloading QQ installer..."
|
||||
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
|
||||
# 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"
|
||||
|
||||
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..."
|
||||
NODE_URL="https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-win-x64.zip"
|
||||
echo "Downloading Node.js $NODE_VERSION..."
|
||||
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
|
||||
@@ -133,9 +154,14 @@ jobs:
|
||||
# -----------------------------
|
||||
# 5) 拷贝 QQ 文件到 NapCat.Shell.Windows.Node
|
||||
# -----------------------------
|
||||
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
|
||||
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "crypto.dll" "ssl.dll" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
|
||||
for name in "${QQ_TARGETS[@]}"; do
|
||||
find "$QQ_EXTRACT" -iname "$name" -exec cp -a {} "$OUT_DIR" \; || true
|
||||
source_file=$(find "$QQ_EXTRACT" -type f -iname "$name" -print -quit)
|
||||
if [ -z "$source_file" ]; then
|
||||
echo "Missing required QQ file: $name" >&2
|
||||
exit 1
|
||||
fi
|
||||
cp -a "$source_file" "$OUT_DIR/"
|
||||
done
|
||||
|
||||
# -----------------------------
|
||||
@@ -155,8 +181,7 @@ jobs:
|
||||
# -----------------------------
|
||||
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
|
||||
# -----------------------------
|
||||
NODE_VER="22.11.0"
|
||||
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
|
||||
cp -a "$NODE_EXTRACT/node-v$NODE_VERSION-win-x64/node.exe" "$OUT_DIR/" || true
|
||||
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
@@ -164,8 +189,39 @@ jobs:
|
||||
name: NapCat.Shell.Windows.Node
|
||||
path: NapCat.Shell.Windows.Node
|
||||
|
||||
validate-windows-node:
|
||||
needs: assemble-windows-node
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ inputs.version }}
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: NapCat.Shell.Windows.Node
|
||||
path: windows-node
|
||||
|
||||
- name: Verify bundled Node and QQ native dependencies
|
||||
shell: pwsh
|
||||
working-directory: windows-node
|
||||
run: |
|
||||
& .\node.exe --check .\index.js
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
& .\node.exe -e "const wrapper = require('./wrapper.node'); if (!wrapper.NodeQQNTWrapperUtil) throw new Error('Missing NodeQQNTWrapperUtil'); console.log('wrapper.node native-load PASS'); process.exit(0);"
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
- name: Verify Windows loader file queries
|
||||
shell: pwsh
|
||||
run: |
|
||||
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/windows-node/napcat/NapCatWinBootHook.dll" "$pwd/windows-node/napcat/loadNapCat.js"
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
release-napcat:
|
||||
needs: [build, assemble-windows-node]
|
||||
needs: [build, assemble-windows-node, validate-windows-node]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -414,12 +470,17 @@ 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
|
||||
pnpm i --ignore-scripts
|
||||
pnpm run build:openapi
|
||||
|
||||
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
|
||||
|
||||
@@ -21,3 +21,4 @@ tests/run/
|
||||
guild1.db-wal
|
||||
guild1.db-shm
|
||||
packages/napcat-develop/config/.env
|
||||
.claude
|
||||
@@ -11,15 +11,9 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
|
||||
---
|
||||
|
||||
## New Feature
|
||||
## New Framework ?
|
||||
|
||||
在 v4.8.115+ 版本开始
|
||||
|
||||
1. NapCatQQ 支持 [Stream Api](https://napneko.github.io/develop/file)
|
||||
2. NapCatQQ 推荐 message_id/user_id/group_id 均使用字符串类型
|
||||
|
||||
- [1] 解决 Docker/跨设备/大文件 的多媒体上下传问题
|
||||
- [2] 采用字符串可以解决扩展到int64的问题,同时也可以解决部分语言(如JavaScript)对大整数支持不佳的问题,增加极少成本。
|
||||
可以试试更新更好用的 [SnowLuma](https://github.com/SnowLuma/SnowLuma) 作为NapCat Gui替代品。
|
||||
|
||||
## Welcome
|
||||
|
||||
@@ -64,7 +58,7 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
|
||||
> QQ群因为特殊原因需要入群密钥,请在webui关于页面获取,仅最新的100个版本以内有效。
|
||||
|
||||
下面的QQ Group 无需密钥,随时清理不活跃人员和Bot,仅500人容量。
|
||||
社区相关日后会进一步加强审核,并严格限制一定时间的入群人数,请具备一定编程基础和问题解决能力再申请入群。
|
||||
|
||||
[困困猫猫的高中](https://qm.qq.com/q/14aUVclRUA)
|
||||
|
||||
|
||||
@@ -12,11 +12,17 @@ import {
|
||||
ShutUpGroupMember,
|
||||
Peer,
|
||||
ChatType,
|
||||
GroupManagementSettings,
|
||||
} from '@/napcat-core/index';
|
||||
import { isNumeric, solveAsyncProblem } from 'napcat-common/src/helper';
|
||||
import { LimitedHashTable } from 'napcat-common/src/message-unique';
|
||||
import { CancelableTask, TaskExecutor } from 'napcat-common/src/cancel-task';
|
||||
import { createGroupDetailInfoV2Param, createGroupExtFilter, createGroupExtInfo } from '../data';
|
||||
import {
|
||||
createGroupDetailInfoV2Param,
|
||||
createGroupExtFilter,
|
||||
createGroupExtInfo,
|
||||
createGroupManagementRequests,
|
||||
} from '../data';
|
||||
import { NTEventWrapper } from '../helper/event';
|
||||
|
||||
export class NTQQGroupApi {
|
||||
@@ -168,6 +174,54 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getGroupService().modifyGroupDetailInfoV2(param, 0);
|
||||
}
|
||||
|
||||
async setGroupMemberInvitePolicy (
|
||||
groupCode: string,
|
||||
policy: NonNullable<GroupManagementSettings['memberInvite']>
|
||||
) {
|
||||
return this.modifyGroupManagementSettings(groupCode, { memberInvite: policy });
|
||||
}
|
||||
|
||||
async setGroupMemberPermissions (
|
||||
groupCode: string,
|
||||
permissions: Pick<
|
||||
GroupManagementSettings,
|
||||
'allowMemberUploadAlbum' | 'allowMemberTemporarySession' | 'allowMemberCreateGroup'
|
||||
>
|
||||
) {
|
||||
return this.modifyGroupManagementSettings(groupCode, permissions);
|
||||
}
|
||||
|
||||
async setGroupNewMemberHistoryVisibility (groupCode: string, visible: boolean) {
|
||||
return this.modifyGroupManagementSettings(groupCode, { newMembersSeeRecentHistory: visible });
|
||||
}
|
||||
|
||||
private async modifyGroupManagementSettings (groupCode: string, settings: GroupManagementSettings) {
|
||||
const results: Array<{ setting: string, result: GeneralCallResult; }> = [];
|
||||
const changesKnownFlags = settings.memberInvite !== undefined ||
|
||||
settings.allowMemberUploadAlbum !== undefined ||
|
||||
settings.allowMemberTemporarySession !== undefined ||
|
||||
settings.allowMemberCreateGroup !== undefined ||
|
||||
settings.newMembersSeeRecentHistory !== undefined;
|
||||
const currentDetail = changesKnownFlags ? await this.fetchGroupDetail(groupCode) : undefined;
|
||||
|
||||
for (const request of createGroupManagementRequests(
|
||||
groupCode,
|
||||
settings,
|
||||
currentDetail?.privilegeFlag,
|
||||
currentDetail?.groupFlagExt4
|
||||
)) {
|
||||
results.push({
|
||||
setting: request.setting,
|
||||
result: await this.context.session.getGroupService().modifyGroupDetailInfoV2(
|
||||
request.param,
|
||||
request.operationType
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
async setGroupSearch (groupCode: string, option: {
|
||||
noCodeFingerOpenFlag?: number;
|
||||
noFingerOpenFlag?: number;
|
||||
@@ -243,6 +297,9 @@ 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}`);
|
||||
@@ -272,31 +329,57 @@ 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) {
|
||||
// 缓存里没有该成员(比如新入群),刷新一次;上面刚刷新过就不再重复拉取
|
||||
if (!member && cached) {
|
||||
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);
|
||||
}
|
||||
@@ -430,6 +513,24 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getRichMediaService().batchGetGroupFileCount(groupCodes);
|
||||
}
|
||||
|
||||
// getGroupFileList also carries the group's used/total space in its call
|
||||
// result's `groupSpaceResult`; a single-item fetch is enough to read it.
|
||||
async getGroupFileSpace (groupCode: string) {
|
||||
const [result] = await this.core.eventWrapper.callNormalEventV2(
|
||||
'NodeIKernelRichMediaService/getGroupFileList',
|
||||
'NodeIKernelMsgListener/onGroupFileInfoUpdate',
|
||||
[
|
||||
groupCode,
|
||||
{ sortType: 1, fileCount: 1, startIndex: 0, sortOrder: 1, showOnlinedocFolder: 0 },
|
||||
],
|
||||
() => true,
|
||||
() => true,
|
||||
1,
|
||||
5000
|
||||
);
|
||||
return result?.groupSpaceResult;
|
||||
}
|
||||
|
||||
async getArkJsonGroupShare (groupCode: string) {
|
||||
const ret = await this.core.eventWrapper.callNoListenerEvent(
|
||||
'NodeIKernelGroupService/getGroupRecommendContactArkJson',
|
||||
@@ -461,6 +562,10 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getGroupService().quitGroup(groupCode);
|
||||
}
|
||||
|
||||
async destroyGroup (groupCode: string) {
|
||||
return this.context.session.getGroupService().destroyGroup(groupCode);
|
||||
}
|
||||
|
||||
async kickMember (groupCode: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') {
|
||||
return this.context.session.getGroupService().kickMember(groupCode, kickUids, refuseForever, kickReason);
|
||||
}
|
||||
|
||||
@@ -67,6 +67,18 @@ export class NTQQMsgApi {
|
||||
return this.context.session.getMsgService().fetchFavEmojiList('', num, true, true);
|
||||
}
|
||||
|
||||
async addFavEmoji (req: Parameters<NodeIKernelMsgService['addFavEmoji']>[0]) {
|
||||
return this.context.session.getMsgService().addFavEmoji(req);
|
||||
}
|
||||
|
||||
async deleteFavEmoji (ids: string[]) {
|
||||
return this.context.session.getMsgService().deleteFavEmoji(ids);
|
||||
}
|
||||
|
||||
async modifyFavEmojiDesc (items: Parameters<NodeIKernelMsgService['modifyFavEmojiDesc']>[0]) {
|
||||
return this.context.session.getMsgService().modifyFavEmojiDesc(items);
|
||||
}
|
||||
|
||||
async queryMsgsWithFilterExWithSeq (peer: Peer, msgSeq: string) {
|
||||
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
||||
chatInfo: peer,
|
||||
|
||||
@@ -36,7 +36,7 @@ export class NTQQPacketApi {
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.logError(err);
|
||||
this.errStack.push(err);
|
||||
this.pushError(err);
|
||||
return false;
|
||||
})) && this.pkt?.available;
|
||||
}
|
||||
@@ -46,7 +46,15 @@ export class NTQQPacketApi {
|
||||
}
|
||||
|
||||
get clientLogStack () {
|
||||
return this.pkt?.clientLogStack + '\n' + this.errStack.join('\n');
|
||||
return [this.pkt?.clientLogStack, ...this.errStack].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
private pushError (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
this.errStack.push(error.stack || error.message);
|
||||
return;
|
||||
}
|
||||
this.errStack.push(String(error));
|
||||
}
|
||||
|
||||
async InitSendPacket (qqVer: string) {
|
||||
@@ -67,10 +75,17 @@ export class NTQQPacketApi {
|
||||
}
|
||||
this.pkt = new PacketClientSession(this.core);
|
||||
await this.pkt.init(process.pid, table.recv, table.send);
|
||||
if (!this.pkt.available) {
|
||||
const err = '[Core] [Packet] NativePacketClient 初始化失败,PacketBackend 发包能力不可用!';
|
||||
this.logger.logError(err);
|
||||
this.errStack.push(err);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this.pkt.operation.FetchRkey(3000);
|
||||
} catch (error) {
|
||||
this.logger.logError('测试Packet状态异常', error);
|
||||
this.pushError(error);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -198,6 +198,7 @@ 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(() => '');
|
||||
|
||||
@@ -8,11 +8,25 @@ import {
|
||||
WebHonorType, NapCatCore,
|
||||
} from '@/napcat-core/index';
|
||||
|
||||
import { createReadStream, readFileSync, statSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { basename } from 'node:path';
|
||||
import { qunAlbumControl } from '../data/webapi';
|
||||
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 { 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;
|
||||
@@ -24,6 +38,34 @@ 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;
|
||||
@@ -371,9 +413,11 @@ 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) {
|
||||
const img = readFileSync(path);
|
||||
const img_size = img.length;
|
||||
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;
|
||||
const img_name = basename(path);
|
||||
const GTK = this.getBknFromSKey(skey);
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
@@ -386,42 +430,76 @@ 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; }, ret: number, msg: string; }>(api, 'POST', body, {
|
||||
const post = await RequestUtil.HttpGetJson<{
|
||||
data: { session: string; slice_size?: number | string; },
|
||||
ret: number,
|
||||
msg: string;
|
||||
}>(api, 'POST', body, {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
return post;
|
||||
}
|
||||
|
||||
async uploadQunAlbumSlice (path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number) {
|
||||
// 服务端会在会话响应里给出建议的分片大小;取不到或异常时退回 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';
|
||||
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}`;
|
||||
|
||||
const stream = createReadStream(path, { highWaterMark: slice_size });
|
||||
// 只记分片位置,不预先读内容;再并发上传(串行上传在几 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++;
|
||||
}
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const end = Math.min(offset + chunk.length, img_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);
|
||||
const form = new FormData();
|
||||
form.append('uin', uin);
|
||||
form.append('appid', 'qun');
|
||||
form.append('appid', appid);
|
||||
form.append('session', session);
|
||||
form.append('offset', offset.toString());
|
||||
form.append('offset', slice.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', seq.toString());
|
||||
form.append('end', end.toString());
|
||||
form.append('cmd', 'FileUpload');
|
||||
form.append('seq', slice.seq.toString());
|
||||
form.append('end', slice.end.toString());
|
||||
form.append('cmd', cmd);
|
||||
form.append('slice_size', slice_size.toString());
|
||||
form.append('biz_req.iUploadType', '0');
|
||||
|
||||
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}`;
|
||||
// 分片路径必须与 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 response = await fetch(api, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -434,24 +512,153 @@ export class NTQQWebApi {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const post = await response.json() as { ret: number, msg: string; }; if (post.ret !== 0) {
|
||||
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
|
||||
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}`);
|
||||
}
|
||||
offset += chunk.length;
|
||||
seq++;
|
||||
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();
|
||||
}
|
||||
|
||||
return { success: true, message: '上传完成' };
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
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 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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getAlbumMediaListByNTQQ (gc: string, albumId: string, attach_info: string = '') {
|
||||
@@ -539,4 +746,113 @@ export class NTQQWebApi {
|
||||
createAlbumFeedPublish(qunId, uin, albumId, batchId)
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
const cookie = `p_uin=o${selfUin}; p_skey=${pSkey}; uin=o${selfUin}`;
|
||||
const post = await RequestUtil.HttpGetJson<{
|
||||
retCode: number,
|
||||
costTime: number,
|
||||
response: {
|
||||
ret?: {
|
||||
code: string,
|
||||
msg: string,
|
||||
},
|
||||
page?: {
|
||||
infos?: {
|
||||
uid: string,
|
||||
uidGroupNick: string,
|
||||
signedTimeStamp: string,
|
||||
signInRank: number,
|
||||
}[],
|
||||
offset: number,
|
||||
total: number,
|
||||
}[],
|
||||
},
|
||||
funcCode: number,
|
||||
}>(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${this.getBknFromPSKey(pSkey)}`, 'POST', {
|
||||
dayYmd: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
uid: selfUin,
|
||||
groupId: groupCode,
|
||||
}, {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
return post;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,142 @@
|
||||
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter } from '../types';
|
||||
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter, GroupManagementSettings } from '../types';
|
||||
|
||||
const MEMBER_INVITE_PRIVILEGE_MASK = 0x06100000;
|
||||
const MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK = 0x1;
|
||||
const MEMBER_CREATE_GROUP_FLAG = 0x8000;
|
||||
const MEMBER_TEMPORARY_SESSION_FLAG = 0x10000;
|
||||
const NEW_MEMBER_RECENT_HISTORY_FLAG = 0x4;
|
||||
|
||||
function mergeMaskedFlag (currentFlag: number, requestedFlag: number, maskValue: number): number {
|
||||
const mask = BigInt(maskValue);
|
||||
return Number((BigInt(currentFlag) & ~mask) | (BigInt(requestedFlag) & mask));
|
||||
}
|
||||
|
||||
export function applyGroupManagementSettings (
|
||||
param: GroupDetailInfoV2Param,
|
||||
settings: GroupManagementSettings
|
||||
): boolean {
|
||||
let changed = false;
|
||||
|
||||
if (settings.memberInvite !== undefined) {
|
||||
const privilegeByPolicy = {
|
||||
disabled: 0x04000000,
|
||||
require_approval: 0,
|
||||
no_approval: 0x00100000,
|
||||
no_approval_under_100: 0x02000000,
|
||||
} satisfies Record<NonNullable<GroupManagementSettings['memberInvite']>, number>;
|
||||
|
||||
param.filter.allowMemberInvite = 1;
|
||||
param.modifyInfo.allowMemberInvite = settings.memberInvite === 'disabled' ? 0 : 1;
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_INVITE_PRIVILEGE_MASK;
|
||||
param.modifyInfo.appPrivilegeFlag |= privilegeByPolicy[settings.memberInvite];
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.allowMemberUploadAlbum !== undefined) {
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
|
||||
if (!settings.allowMemberUploadAlbum) param.modifyInfo.appPrivilegeFlag |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.allowMemberTemporarySession !== undefined) {
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_TEMPORARY_SESSION_FLAG;
|
||||
if (!settings.allowMemberTemporarySession) param.modifyInfo.appPrivilegeFlag |= MEMBER_TEMPORARY_SESSION_FLAG;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.allowMemberCreateGroup !== undefined) {
|
||||
param.filter.appPrivilegeFlag = 1;
|
||||
param.filter.appPrivilegeMask = 1;
|
||||
param.modifyInfo.appPrivilegeMask |= MEMBER_CREATE_GROUP_FLAG;
|
||||
if (!settings.allowMemberCreateGroup) param.modifyInfo.appPrivilegeFlag |= MEMBER_CREATE_GROUP_FLAG;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (settings.newMembersSeeRecentHistory !== undefined) {
|
||||
param.filter.groupFlagExt4 = 1;
|
||||
param.filter.groupFlagExt4Mask = 1;
|
||||
param.modifyInfo.groupFlagExt4Mask |= NEW_MEMBER_RECENT_HISTORY_FLAG;
|
||||
if (settings.newMembersSeeRecentHistory) param.modifyInfo.groupFlagExt4 |= NEW_MEMBER_RECENT_HISTORY_FLAG;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
export function createGroupManagementRequests (
|
||||
groupCode: string,
|
||||
settings: GroupManagementSettings,
|
||||
initialAppPrivilegeFlag = 0,
|
||||
initialGroupFlagExt4 = 0
|
||||
) {
|
||||
const requests: Array<{ setting: string, param: GroupDetailInfoV2Param, operationType: number; }> = [];
|
||||
const requestSettings: Array<{
|
||||
setting: string,
|
||||
value: GroupManagementSettings,
|
||||
operationType: number;
|
||||
}> = [
|
||||
{ setting: 'member_invite', value: { memberInvite: settings.memberInvite }, operationType: 0 },
|
||||
{
|
||||
setting: 'new_members_see_recent_history',
|
||||
value: { newMembersSeeRecentHistory: settings.newMembersSeeRecentHistory },
|
||||
operationType: 0,
|
||||
},
|
||||
{
|
||||
setting: 'allow_member_upload_album',
|
||||
value: { allowMemberUploadAlbum: settings.allowMemberUploadAlbum },
|
||||
operationType: 8,
|
||||
},
|
||||
{
|
||||
setting: 'allow_member_temporary_session',
|
||||
value: { allowMemberTemporarySession: settings.allowMemberTemporarySession },
|
||||
operationType: 8,
|
||||
},
|
||||
{
|
||||
setting: 'allow_member_create_group',
|
||||
value: { allowMemberCreateGroup: settings.allowMemberCreateGroup },
|
||||
operationType: 8,
|
||||
},
|
||||
];
|
||||
|
||||
let currentAppPrivilegeFlag = initialAppPrivilegeFlag;
|
||||
let currentGroupFlagExt4 = initialGroupFlagExt4;
|
||||
for (const requestSetting of requestSettings) {
|
||||
const param = createGroupDetailInfoV2Param(groupCode);
|
||||
if (applyGroupManagementSettings(param, requestSetting.value)) {
|
||||
if (param.filter.appPrivilegeFlag) {
|
||||
const nextAppPrivilegeFlag = mergeMaskedFlag(
|
||||
currentAppPrivilegeFlag,
|
||||
param.modifyInfo.appPrivilegeFlag,
|
||||
param.modifyInfo.appPrivilegeMask
|
||||
);
|
||||
if (requestSetting.operationType === 8 && nextAppPrivilegeFlag === currentAppPrivilegeFlag) continue;
|
||||
currentAppPrivilegeFlag = nextAppPrivilegeFlag;
|
||||
// Linux NTQQ's wrapper builds this field from the current complete privilege value.
|
||||
// Supplying only the targeted bit makes zero-valued clears get acknowledged but ignored.
|
||||
param.modifyInfo.appPrivilegeFlag = currentAppPrivilegeFlag;
|
||||
}
|
||||
if (param.filter.groupFlagExt4) {
|
||||
const nextGroupFlagExt4 = mergeMaskedFlag(
|
||||
currentGroupFlagExt4,
|
||||
param.modifyInfo.groupFlagExt4,
|
||||
param.modifyInfo.groupFlagExt4Mask
|
||||
);
|
||||
if (nextGroupFlagExt4 === currentGroupFlagExt4) continue;
|
||||
currentGroupFlagExt4 = nextGroupFlagExt4;
|
||||
param.modifyInfo.groupFlagExt4 = currentGroupFlagExt4;
|
||||
}
|
||||
requests.push({ setting: requestSetting.setting, param, operationType: requestSetting.operationType });
|
||||
}
|
||||
}
|
||||
|
||||
return requests;
|
||||
}
|
||||
|
||||
export function createGroupDetailInfoV2Param (group_code: string): GroupDetailInfoV2Param {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* QQ空间(Qzone)发说说/上传图片相关的纯数据构造与解析函数
|
||||
* 不发起任何网络请求,方便单独测试
|
||||
*/
|
||||
|
||||
export interface QzoneUploadImageParams {
|
||||
uin: string;
|
||||
skey: string;
|
||||
pskey: string;
|
||||
g_tk: string;
|
||||
base64: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造上传图片到 QQ 空间的表单请求体 (application/x-www-form-urlencoded)
|
||||
* 对齐 https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image
|
||||
*/
|
||||
export function buildQzoneUploadImageBody (params: QzoneUploadImageParams): string {
|
||||
const { uin, skey, pskey, g_tk, base64 } = params;
|
||||
const backUrls = `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
|
||||
const query = new URLSearchParams({
|
||||
filename: 'filename',
|
||||
uin,
|
||||
skey,
|
||||
zzpaneluin: uin,
|
||||
p_uin: uin,
|
||||
p_skey: pskey,
|
||||
uploadtype: '1',
|
||||
albumtype: '7',
|
||||
exttype: '0',
|
||||
refer: 'shuoshuo',
|
||||
output_type: 'jsonhtml',
|
||||
charset: 'utf-8',
|
||||
output_charset: 'utf-8',
|
||||
upload_hd: '1',
|
||||
hd_width: '2048',
|
||||
hd_height: '10000',
|
||||
hd_quality: '96',
|
||||
backUrls,
|
||||
base64: '1',
|
||||
jsonhtml_callback: 'callback',
|
||||
picfile: base64,
|
||||
qzreferrer: `https://user.qzone.qq.com/${uin}/main`,
|
||||
});
|
||||
return query.toString();
|
||||
}
|
||||
|
||||
export interface QzoneUploadImageData {
|
||||
albumid: string;
|
||||
lloc: string;
|
||||
type: string;
|
||||
height: string;
|
||||
width: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface QzoneUploadImageRawResponse {
|
||||
code?: number;
|
||||
msg?: string;
|
||||
data?: QzoneUploadImageData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析上传图片接口返回的 `frameElement.callback({...});</script>` 包裹响应
|
||||
*/
|
||||
export function parseQzoneUploadImageResponseText (raw: string): QzoneUploadImageRawResponse {
|
||||
const startTag = 'frameElement.callback';
|
||||
const endTag = '</script>';
|
||||
const startIdx = raw.indexOf(startTag);
|
||||
const endIdx = raw.indexOf(endTag);
|
||||
if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {
|
||||
throw new Error('QQ空间图片上传响应格式异常');
|
||||
}
|
||||
const segment = raw.slice(startIdx + startTag.length, endIdx);
|
||||
const jsonStart = segment.indexOf('(');
|
||||
const jsonEnd = segment.lastIndexOf(')');
|
||||
if (jsonStart === -1 || jsonEnd === -1 || jsonEnd <= jsonStart) {
|
||||
throw new Error('QQ空间图片上传响应解析失败');
|
||||
}
|
||||
const jsonText = segment.slice(jsonStart + 1, jsonEnd);
|
||||
try {
|
||||
return JSON.parse(jsonText) as QzoneUploadImageRawResponse;
|
||||
} catch {
|
||||
throw new Error('QQ空间图片上传响应JSON解析失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 依据上传图片返回数据拼接 richval 字段
|
||||
* 格式: ,albumid,lloc,sloc,type,height,width,,height,width (sloc 与 lloc 一致)
|
||||
*/
|
||||
export function toQzoneRichval (data: QzoneUploadImageData): string {
|
||||
const { albumid, lloc, type, height, width } = data;
|
||||
return `,${albumid},${lloc},${lloc},${type},${height},${width},,${height},${width}`;
|
||||
}
|
||||
|
||||
export interface QzonePublishParams {
|
||||
hostuin: string;
|
||||
content: string;
|
||||
/** 多张图片使用 \t 拼接后的 richval,无图时不传 */
|
||||
richval?: string;
|
||||
ugcRight: number;
|
||||
/** ugc_right 为 16/128 时必填,多个QQ号使用 | 拼接 */
|
||||
allowUins?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造发表说说的表单请求体 (application/x-www-form-urlencoded)
|
||||
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6
|
||||
*/
|
||||
export function buildQzonePublishBody (params: QzonePublishParams): string {
|
||||
const { hostuin, content, richval, ugcRight, allowUins } = params;
|
||||
const fields: Record<string, string> = {
|
||||
syn_tweet_verson: '1',
|
||||
paramstr: '1',
|
||||
con: content,
|
||||
feedversion: '1',
|
||||
ver: '1',
|
||||
ugc_right: String(ugcRight),
|
||||
to_sign: '0',
|
||||
hostuin,
|
||||
code_version: '1',
|
||||
format: 'json',
|
||||
qzreferrer: `https://user.qzone.qq.com/${hostuin}/main`,
|
||||
};
|
||||
if (richval) {
|
||||
fields['richtype'] = '1';
|
||||
fields['richval'] = richval;
|
||||
}
|
||||
if (allowUins) {
|
||||
fields['allow_uins'] = allowUins;
|
||||
fields['who'] = '1';
|
||||
}
|
||||
return new URLSearchParams(fields).toString();
|
||||
}
|
||||
|
||||
export interface QzonePublishResponse {
|
||||
subcode?: number;
|
||||
code?: number;
|
||||
tid?: string;
|
||||
t1_tid?: string;
|
||||
message?: string;
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析发表说说接口返回的 JSON, 提取 tid
|
||||
*/
|
||||
export function parseQzonePublishResponse (json: QzonePublishResponse): { tid: string; } {
|
||||
const subcode = json.subcode ?? json.code;
|
||||
if (subcode !== undefined && subcode !== 0) {
|
||||
throw new Error(json.message || json.msg || `QQ空间发说说失败, subcode=${subcode}`);
|
||||
}
|
||||
const tid = json.t1_tid || json.tid;
|
||||
if (!tid) {
|
||||
throw new Error('QQ空间发说说失败, 未返回tid');
|
||||
}
|
||||
return { tid };
|
||||
}
|
||||
|
||||
export interface QzoneDeleteParams {
|
||||
hostuin: string;
|
||||
tid: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造删除说说的表单请求体 (application/x-www-form-urlencoded)
|
||||
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6
|
||||
*/
|
||||
export function buildQzoneDeleteBody (params: QzoneDeleteParams): string {
|
||||
const { hostuin, tid } = params;
|
||||
const fields: Record<string, string> = {
|
||||
hostuin,
|
||||
tid,
|
||||
t1_source: '1',
|
||||
code_version: '1',
|
||||
format: 'json',
|
||||
qzreferrer: `https://user.qzone.qq.com/${hostuin}`,
|
||||
};
|
||||
return new URLSearchParams(fields).toString();
|
||||
}
|
||||
|
||||
export interface QzoneDeleteResponse {
|
||||
subcode?: number;
|
||||
code?: number;
|
||||
message?: string;
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析删除说说接口返回的 JSON
|
||||
*/
|
||||
export function parseQzoneDeleteResponse (json: QzoneDeleteResponse): { success: true; } {
|
||||
const subcode = json.subcode ?? json.code;
|
||||
if (subcode !== undefined && subcode !== 0) {
|
||||
throw new Error(json.message || json.msg || `QQ空间删说说失败, subcode=${subcode}`);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
@@ -18,20 +18,64 @@ 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;
|
||||
mapExt?: MapExt;
|
||||
mutliPicInfo?: MutliPicInfo;
|
||||
sAlbumID: string;
|
||||
sAlbumName: string;
|
||||
sPicDesc: string;
|
||||
sPicPath: string;
|
||||
sPicTitle: string;
|
||||
stExtendInfo: StExtendInfo;
|
||||
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;
|
||||
}
|
||||
|
||||
export interface MapExt {
|
||||
@@ -47,6 +91,8 @@ export interface MapParams {
|
||||
batch_num: string;
|
||||
photo_num: string;
|
||||
video_num: string;
|
||||
// 视频封面二段上传时用它把封面挂到已上传的视频上
|
||||
vid?: string;
|
||||
}
|
||||
|
||||
export interface Env {
|
||||
@@ -60,6 +106,96 @@ 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,
|
||||
@@ -72,6 +208,8 @@ export function qunAlbumControl ({
|
||||
photo_num = '1',
|
||||
video_num = '0',
|
||||
batch_num = '1',
|
||||
batchId = nextQunAlbumBatchId(),
|
||||
batchIndex = '0',
|
||||
}: {
|
||||
uin: string,
|
||||
group_id: string,
|
||||
@@ -83,64 +221,21 @@ export function qunAlbumControl ({
|
||||
sAlbumID: string,
|
||||
photo_num?: string,
|
||||
video_num?: string,
|
||||
batch_num?: string
|
||||
batch_num?: string,
|
||||
batchId?: number,
|
||||
batchIndex?: string
|
||||
}
|
||||
): {
|
||||
control_req: ControlReq[]
|
||||
} {
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
|
||||
return {
|
||||
control_req: [
|
||||
control_req: [buildQunAlbumControlReq(
|
||||
{ uin, pskey, appid: 'qun', checksum: pic_md5, check_type: 0, file_len: img_size, cmd: 'FileUpload' },
|
||||
{
|
||||
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',
|
||||
}],
|
||||
...buildQunAlbumBizBase({ iUploadType: 0, sAlbumName, sAlbumID, iBatchID: batchId, sPicTitle: img_name }),
|
||||
...buildQunAlbumFeedFields(group_id, { photo_num, video_num, batch_num }, batchIndex),
|
||||
}
|
||||
)],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -174,3 +269,118 @@ 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: '',
|
||||
}
|
||||
)],
|
||||
};
|
||||
}
|
||||
+101
-1
@@ -582,5 +582,105 @@
|
||||
"9.9.31-49599": {
|
||||
"appid": 537355779,
|
||||
"qua": "V1_WIN_NQ_9.9.31_49599_GW_B"
|
||||
},
|
||||
"9.9.31-49738": {
|
||||
"appid": 537355830,
|
||||
"qua": "V1_WIN_NQ_9.9.31_49738_GW_B"
|
||||
},
|
||||
"3.2.29-49738": {
|
||||
"appid": 537355867,
|
||||
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
|
||||
},
|
||||
"9.9.32-50828": {
|
||||
"appid": 537358739,
|
||||
"qua": "V1_WIN_NQ_9.9.32_50828_GW_B"
|
||||
},
|
||||
"3.2.30-50828": {
|
||||
"appid": 537358775,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"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
@@ -2593,6 +2593,171 @@
|
||||
"AniStickerType": 1,
|
||||
"AniStickerPackId": "1",
|
||||
"AniStickerId": "59"
|
||||
},
|
||||
{
|
||||
"QSid": "450",
|
||||
"QDes": "/撇嘴",
|
||||
"EMCode": "10450"
|
||||
},
|
||||
{
|
||||
"QSid": "451",
|
||||
"QDes": "/色",
|
||||
"EMCode": "10451"
|
||||
},
|
||||
{
|
||||
"QSid": "452",
|
||||
"QDes": "/微笑",
|
||||
"EMCode": "10452"
|
||||
},
|
||||
{
|
||||
"QSid": "453",
|
||||
"QDes": "/发呆",
|
||||
"EMCode": "10453"
|
||||
},
|
||||
{
|
||||
"QSid": "454",
|
||||
"QDes": "/得意",
|
||||
"EMCode": "10454"
|
||||
},
|
||||
{
|
||||
"QSid": "455",
|
||||
"QDes": "/害羞",
|
||||
"EMCode": "10455"
|
||||
},
|
||||
{
|
||||
"QSid": "456",
|
||||
"QDes": "/闭嘴",
|
||||
"EMCode": "10456"
|
||||
},
|
||||
{
|
||||
"QSid": "457",
|
||||
"QDes": "/睡",
|
||||
"EMCode": "10457"
|
||||
},
|
||||
{
|
||||
"QSid": "458",
|
||||
"QDes": "/我吗",
|
||||
"EMCode": "10458"
|
||||
},
|
||||
{
|
||||
"QSid": "459",
|
||||
"QDes": "/优雅",
|
||||
"EMCode": "10459"
|
||||
},
|
||||
{
|
||||
"QSid": "460",
|
||||
"QDes": "/硬撑",
|
||||
"EMCode": "10460"
|
||||
},
|
||||
{
|
||||
"QSid": "461",
|
||||
"QDes": "/宕机",
|
||||
"EMCode": "10461"
|
||||
},
|
||||
{
|
||||
"QSid": "462",
|
||||
"QDes": "/无语",
|
||||
"EMCode": "10462"
|
||||
},
|
||||
{
|
||||
"QSid": "463",
|
||||
"QDes": "/新年快乐",
|
||||
"EMCode": "10463"
|
||||
},
|
||||
{
|
||||
"QSid": "464",
|
||||
"QDes": "/马上到",
|
||||
"EMCode": "10464"
|
||||
},
|
||||
{
|
||||
"QSid": "465",
|
||||
"QDes": "/拆红包",
|
||||
"EMCode": "10465"
|
||||
},
|
||||
{
|
||||
"QSid": "466",
|
||||
"QDes": "/羞羞哒",
|
||||
"EMCode": "10466"
|
||||
},
|
||||
{
|
||||
"QSid": "467",
|
||||
"QDes": "/摇花手",
|
||||
"EMCode": "10467"
|
||||
},
|
||||
{
|
||||
"QSid": "468",
|
||||
"QDes": "/失眠",
|
||||
"EMCode": "10468"
|
||||
},
|
||||
{
|
||||
"QSid": "469",
|
||||
"QDes": "/坚毅",
|
||||
"EMCode": "10469"
|
||||
},
|
||||
{
|
||||
"QSid": "470",
|
||||
"QDes": "/马到成功",
|
||||
"EMCode": "10470"
|
||||
},
|
||||
{
|
||||
"QSid": "472",
|
||||
"QDes": "/心动",
|
||||
"EMCode": "10472"
|
||||
},
|
||||
{
|
||||
"QSid": "474",
|
||||
"QDes": "/给你一拳",
|
||||
"EMCode": "10474"
|
||||
},
|
||||
{
|
||||
"QSid": "475",
|
||||
"QDes": "/干饭",
|
||||
"EMCode": "10475"
|
||||
},
|
||||
{
|
||||
"QSid": "476",
|
||||
"QDes": "/不是吧",
|
||||
"EMCode": "10476"
|
||||
},
|
||||
{
|
||||
"QSid": "477",
|
||||
"QDes": "/你懂的",
|
||||
"EMCode": "10477"
|
||||
},
|
||||
{
|
||||
"QSid": "478",
|
||||
"QDes": "/对的对的",
|
||||
"EMCode": "10478"
|
||||
},
|
||||
{
|
||||
"QSid": "479",
|
||||
"QDes": "/不对不对",
|
||||
"EMCode": "10479"
|
||||
},
|
||||
{
|
||||
"QSid": "480",
|
||||
"QDes": "/散味儿",
|
||||
"EMCode": "10480"
|
||||
},
|
||||
{
|
||||
"QSid": "481",
|
||||
"QDes": "/学习",
|
||||
"EMCode": "10481"
|
||||
},
|
||||
{
|
||||
"QSid": "482",
|
||||
"QDes": "/热化了",
|
||||
"EMCode": "10482"
|
||||
},
|
||||
{
|
||||
"QSid": "483",
|
||||
"QDes": "/略",
|
||||
"EMCode": "10483"
|
||||
},
|
||||
{
|
||||
"QSid": "484",
|
||||
"QDes": "/比爱心",
|
||||
"EMCode": "10484"
|
||||
}
|
||||
],
|
||||
"emoji": [
|
||||
|
||||
+105
-1
@@ -242,5 +242,109 @@
|
||||
"9.9.31-49599-x64": {
|
||||
"send": "0AF885C",
|
||||
"recv": "20058E1"
|
||||
},
|
||||
"9.9.31-49738-x64": {
|
||||
"send": "0AF9FCC",
|
||||
"recv": "2007901"
|
||||
},
|
||||
"3.2.29-49738-x64": {
|
||||
"send": "6234600",
|
||||
"recv": "33D89D0"
|
||||
},
|
||||
"3.2.29-49738-arm64": {
|
||||
"send": "426AA04",
|
||||
"recv": "1596254"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "0B245CC",
|
||||
"recv": "2073D65"
|
||||
},
|
||||
"3.2.30-50828-x64": {
|
||||
"send": "6340530",
|
||||
"recv": "346DA50"
|
||||
},
|
||||
"3.2.30-50828-arm64": {
|
||||
"send": "4327764",
|
||||
"recv": "15e3184"
|
||||
},
|
||||
"9.9.32-50969-x64": {
|
||||
"send": "0B2E2AC",
|
||||
"recv": "209C709"
|
||||
},
|
||||
"3.2.30-50969-x64": {
|
||||
"send": "63F47B0",
|
||||
"recv": "34B9E30"
|
||||
},
|
||||
"3.2.30-50969-arm64": {
|
||||
"send": "43A4804",
|
||||
"recv": "1608CC8"
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
+105
-1
@@ -750,5 +750,109 @@
|
||||
"9.9.31-49599-x64": {
|
||||
"send": "3082C40",
|
||||
"recv": "30861C8"
|
||||
},
|
||||
"9.9.31-49738-x64": {
|
||||
"send": "3086C80",
|
||||
"recv": "308A208"
|
||||
},
|
||||
"3.2.29-49738-x64": {
|
||||
"send": "B3B20A0",
|
||||
"recv": "B3B5B40"
|
||||
},
|
||||
"3.2.29-49738-arm64": {
|
||||
"send": "7342800",
|
||||
"recv": "73461B0"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "3155200",
|
||||
"recv": "3158788"
|
||||
},
|
||||
"3.2.30-50828-arm64": {
|
||||
"send": "74C3070",
|
||||
"recv": "74C6A20"
|
||||
},
|
||||
"3.2.30-50828-x64": {
|
||||
"send": "B5D0FC0",
|
||||
"recv": "B5D4A60"
|
||||
},
|
||||
"9.9.32-50969-x64": {
|
||||
"send": "31994E0",
|
||||
"recv": "319CA68"
|
||||
},
|
||||
"3.2.30-50969-x64": {
|
||||
"send": "B7394C0",
|
||||
"recv": "B73CF60"
|
||||
},
|
||||
"3.2.30-50969-arm64": {
|
||||
"send": "75BD1D0",
|
||||
"recv": "75C0B80"
|
||||
},
|
||||
"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;
|
||||
|
||||
/** Container format name (e.g., "mp4", "mkv", "avi") */
|
||||
/** Generated thumbnail image format */
|
||||
format: string;
|
||||
|
||||
/** Video codec name (e.g., "h264", "hevc", "vp9") */
|
||||
videoCodec: string;
|
||||
|
||||
/** First frame thumbnail as BMP image buffer */
|
||||
/** First frame thumbnail as JPEG image buffer */
|
||||
image: Buffer;
|
||||
}
|
||||
|
||||
|
||||
@@ -138,14 +138,14 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
/**
|
||||
* 获取时长
|
||||
*/
|
||||
async getDuration(filePath: string): Promise<number> {
|
||||
async getDuration (filePath: string): Promise<number> {
|
||||
const { stdout } = await execFileAsync(this.ffprobePath, [
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=duration",
|
||||
"-of",
|
||||
"default=noprint_wrappers=1:nokey=1",
|
||||
'-v',
|
||||
'error',
|
||||
'-show_entries',
|
||||
'format=duration',
|
||||
'-of',
|
||||
'default=noprint_wrappers=1:nokey=1',
|
||||
filePath,
|
||||
]);
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { platform } from 'node:os';
|
||||
import { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory';
|
||||
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
|
||||
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
|
||||
|
||||
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
|
||||
if (process.platform === 'win32' && binaryPath) {
|
||||
@@ -94,6 +95,15 @@ export class FFmpegService {
|
||||
await adapter.extractThumbnail(videoPath, thumbnailPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接发送到 QQ kernel 的旧视频元素使用 PNG 缩略图。
|
||||
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
|
||||
*/
|
||||
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
|
||||
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
|
||||
await adapter.extractThumbnail(videoPath, thumbnailPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换音频文件
|
||||
*/
|
||||
|
||||
@@ -187,14 +187,14 @@ export class LogWrapper implements ILogWrapper {
|
||||
|
||||
_log (level: LogLevel, ...args: any[]) {
|
||||
if (this.consoleLogEnabled || this.fileLogEnabled) {
|
||||
const message = this.formatMsg(args);
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const message = this.formatMsg(args).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|\x1B\[[0-?]*[ -/]*[@-~]|\x1B/g, '');
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
this.logger.log(level, message);
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
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;
|
||||
};
|
||||
}
|
||||
@@ -79,10 +79,11 @@ export class QQBasicInfoWrapper {
|
||||
|
||||
getAppidV2 (): { appid: string; qua: string; } {
|
||||
// 通过已有表 性能好
|
||||
const appidTbale = AppidTable as unknown as QQAppidTableType;
|
||||
const appidTable = AppidTable as unknown as QQAppidTableType;
|
||||
const fullVersion = this.getFullQQVersion();
|
||||
if (fullVersion) {
|
||||
const data = appidTbale[fullVersion];
|
||||
// 同一 Linux 版本的 x64 和 arm64 使用不同的 AppID,优先匹配架构。
|
||||
const data = appidTable[`${fullVersion}-${process.arch}`] ?? appidTable[fullVersion];
|
||||
if (data) {
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -107,10 +107,20 @@ export class RkeyManager {
|
||||
for (const url of availableUrls) {
|
||||
try {
|
||||
let temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
|
||||
if ('retcode' in temp) {
|
||||
if (typeof temp === 'object' && temp !== null && 'retcode' in temp) {
|
||||
// 支持Onebot Ret风格
|
||||
temp = (temp as unknown as OneBotApiRet).data;
|
||||
}
|
||||
if (
|
||||
typeof temp?.group_rkey !== 'string' ||
|
||||
typeof temp?.private_rkey !== 'string' ||
|
||||
typeof temp?.expired_time !== 'number' ||
|
||||
temp.group_rkey.length <= 6 ||
|
||||
temp.private_rkey.length <= 6 ||
|
||||
temp.expired_time <= 0
|
||||
) {
|
||||
throw new Error('Rkey 服务返回格式无效:group_rkey/private_rkey/expired_time 缺失或不合法');
|
||||
}
|
||||
this.rkeyData = {
|
||||
group_rkey: temp.group_rkey.slice(6),
|
||||
private_rkey: temp.private_rkey.slice(6),
|
||||
|
||||
@@ -59,12 +59,30 @@ 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']) {
|
||||
const wrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
|
||||
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
|
||||
process.dlopen(nativemodule, wrapperPath);
|
||||
return nativemodule.exports;
|
||||
return dlopenWrapper(process.env['NAPCAT_WRAPPER_PATH']);
|
||||
}
|
||||
if (!execPath) {
|
||||
throw new Error('无法加载Wrapper,execPath未定义');
|
||||
@@ -85,10 +103,9 @@ 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 nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
|
||||
process.dlopen(nativemodule, wrapperNodePath);
|
||||
const exports = dlopenWrapper(wrapperNodePath);
|
||||
process.env['NAPCAT_WRAPPER_PATH'] = wrapperNodePath;
|
||||
return nativemodule.exports;
|
||||
return exports;
|
||||
}
|
||||
export function getMajorPath (execPath: string, QQVersion: string): string {
|
||||
// major.node
|
||||
@@ -261,8 +278,14 @@ 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;
|
||||
}
|
||||
|
||||
@@ -39,12 +39,17 @@ export class NativePacketClient {
|
||||
|
||||
async init (_pid: number, recv: string, send: string): Promise<void> {
|
||||
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
|
||||
if (isNewQQ) {
|
||||
const success = this.napi2nativeLoader.initHook(send, recv);
|
||||
if (success) {
|
||||
this.available = true;
|
||||
}
|
||||
if (!isNewQQ) {
|
||||
this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化');
|
||||
return;
|
||||
}
|
||||
const success = this.napi2nativeLoader.initHook(send, recv);
|
||||
if (success) {
|
||||
this.available = true;
|
||||
this.logStack.pushLogInfo(`[PacketClient] NativePacketClient Hook 初始化成功 platform=${process.platform}.${process.arch}`);
|
||||
return;
|
||||
}
|
||||
this.logStack.pushLogError(`[PacketClient] NativePacketClient Hook 初始化失败 platform=${process.platform}.${process.arch} send=${send} recv=${recv}`);
|
||||
}
|
||||
|
||||
async sendPacket (
|
||||
|
||||
@@ -19,6 +19,7 @@ import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
|
||||
import { gunzipSync } from 'zlib';
|
||||
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
|
||||
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
|
||||
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
|
||||
|
||||
export class PacketOperationContext {
|
||||
private readonly context: PacketContext;
|
||||
@@ -105,15 +106,7 @@ export class PacketOperationContext {
|
||||
.filter(Boolean)
|
||||
);
|
||||
const res = await Promise.allSettled(reqList);
|
||||
const failedCount = res.filter((r) => r.status === 'rejected').length;
|
||||
if (failedCount > 0) {
|
||||
this.context.logger.warn(`上传资源${res.length}个,失败${failedCount}个`);
|
||||
res.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
assertUploadResults(res, this.context.logger);
|
||||
}
|
||||
|
||||
async UploadImage (img: PacketMsgPicElement) {
|
||||
@@ -240,9 +233,10 @@ export class PacketOperationContext {
|
||||
}
|
||||
|
||||
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
|
||||
// await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源(跳过已有原始数据的项)
|
||||
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
|
||||
await Promise.all(msg.filter(item => item.actionMsg).map(async (item) => {
|
||||
await this.SendPreprocess(item.actionMsg!, groupUin);
|
||||
}));
|
||||
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
@@ -370,11 +364,39 @@ 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;
|
||||
})
|
||||
);
|
||||
const isGroup = msg?.responseHead.grp !== undefined;
|
||||
const peerUin = isGroup
|
||||
? String(msg?.responseHead.grp?.groupUin ?? 0)
|
||||
: String(msg?.responseHead.fromUin ?? 0);
|
||||
const peerUid = isGroup
|
||||
? String(msg?.responseHead.grp?.groupUin ?? 0)
|
||||
: String(msg?.responseHead.fromUid ?? '');
|
||||
const sendNickName = isGroup
|
||||
? (msg?.responseHead.grp?.memberName ?? '')
|
||||
: (msg?.responseHead.forward?.friendName ?? '');
|
||||
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPEGROUP,
|
||||
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
elements,
|
||||
guildId: '',
|
||||
isOnlineMsg: false,
|
||||
@@ -385,18 +407,18 @@ export class PacketOperationContext {
|
||||
msgType: NTMsgType.KMSGTYPEMIX,
|
||||
parentMsgIdList: [],
|
||||
parentMsgPeer: {
|
||||
chatType: ChatType.KCHATTYPEGROUP,
|
||||
peerUid: String(msg?.responseHead.grp?.groupUin ?? 0),
|
||||
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
peerUid,
|
||||
},
|
||||
peerName: '',
|
||||
peerUid: '1094950020',
|
||||
peerUin: '1094950020',
|
||||
peerUid,
|
||||
peerUin,
|
||||
recallTime: '0',
|
||||
records: [],
|
||||
sendNickName: msg?.responseHead.grp?.memberName ?? '',
|
||||
sendRemarkName: msg?.responseHead.grp?.memberName ?? '',
|
||||
senderUid: '',
|
||||
senderUin: '1094950020',
|
||||
sendNickName,
|
||||
sendRemarkName: sendNickName,
|
||||
senderUid: msg?.responseHead.fromUid ?? '',
|
||||
senderUin: String(msg?.responseHead.fromUin ?? 0),
|
||||
sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
|
||||
subMsgType: 1,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface UploadResultLogger {
|
||||
warn (message: string): unknown;
|
||||
error (message: string): unknown;
|
||||
}
|
||||
|
||||
export function assertUploadResults (
|
||||
results: PromiseSettledResult<unknown>[],
|
||||
logger: UploadResultLogger
|
||||
): void {
|
||||
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
|
||||
if (failures.length === 0) return;
|
||||
|
||||
logger.warn(`上传资源${results.length}个,失败${failures.length}个`);
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
const reason = result.reason instanceof Error
|
||||
? result.reason.stack ?? result.reason.message
|
||||
: String(result.reason);
|
||||
logger.error(`上传第${index + 1}个资源失败:${reason}`);
|
||||
}
|
||||
});
|
||||
throw new AggregateError(
|
||||
failures.map(result => result.reason),
|
||||
`上传转发消息资源失败:${failures.length}/${results.length}`
|
||||
);
|
||||
}
|
||||
@@ -3,5 +3,7 @@ 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,8 +21,11 @@ import { PacketClientContext } from '@/napcat-core/packet/context/clientContext'
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
import { calculateFileMD5 } from 'napcat-common/src/file';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { imageSizeFallBack } from 'napcat-image-size/src/index';
|
||||
|
||||
export const BlockSize = 1024 * 1024;
|
||||
const VIDEO_THUMBNAIL_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
interface HighwayServerAddr {
|
||||
ip: string;
|
||||
@@ -110,22 +113,37 @@ export class PacketHighwayContext {
|
||||
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
|
||||
}
|
||||
|
||||
// 如果缺少视频缩略图,自动生成一个
|
||||
let tempThumbPath: string | null = null;
|
||||
let thumbExists = false;
|
||||
if (video.thumbPath) {
|
||||
try {
|
||||
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
|
||||
thumbExists = true;
|
||||
} catch {
|
||||
thumbExists = false;
|
||||
}
|
||||
}
|
||||
if (!video.thumbPath || !thumbExists) {
|
||||
tempThumbPath = await this.ensureVideoThumb(video);
|
||||
}
|
||||
|
||||
const cleanupThumbPaths: string[] = [];
|
||||
try {
|
||||
let thumbExists = false;
|
||||
if (video.thumbPath) {
|
||||
try {
|
||||
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
|
||||
thumbExists = true;
|
||||
} catch {
|
||||
thumbExists = false;
|
||||
}
|
||||
}
|
||||
|
||||
let shouldGenerateThumb = !video.thumbPath || !thumbExists;
|
||||
if (!shouldGenerateThumb) {
|
||||
try {
|
||||
await this.updateVideoThumbInfo(video);
|
||||
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
|
||||
this.logger.warn(`[Highway] Video thumbnail is too large: ${video.thumbSize} bytes, regenerating`);
|
||||
shouldGenerateThumb = true;
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`[Highway] Failed to inspect video thumbnail, regenerating. Reason: ${e instanceof Error ? e.message : e}`);
|
||||
shouldGenerateThumb = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldGenerateThumb) {
|
||||
cleanupThumbPaths.push(await this.ensureVideoThumb(video));
|
||||
}
|
||||
video.businessType = peer.chatType === ChatType.KCHATTYPEGROUP ? 21 : 11;
|
||||
|
||||
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
|
||||
await this.uploadGroupVideo(+peer.peerUid, video);
|
||||
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
|
||||
@@ -134,23 +152,21 @@ export class PacketHighwayContext {
|
||||
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
|
||||
}
|
||||
} finally {
|
||||
// 清理临时生成的缩略图文件
|
||||
if (tempThumbPath) {
|
||||
const thumbToClean = tempThumbPath;
|
||||
fs.promises.unlink(thumbToClean)
|
||||
.then(() => this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`))
|
||||
.catch((e) => {
|
||||
// 文件不存在时忽略错误
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
await Promise.allSettled(cleanupThumbPaths.map(async (thumbToClean) => {
|
||||
try {
|
||||
await fs.promises.unlink(thumbToClean);
|
||||
this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保视频缩略图存在,如果不存在则自动生成
|
||||
* 使用当前 FFmpeg 适配器生成符合 QQ 大小限制的视频缩略图
|
||||
* @returns 生成的临时缩略图路径,用于后续清理
|
||||
*/
|
||||
private async ensureVideoThumb (video: PacketMsgVideoElement): Promise<string> {
|
||||
@@ -161,9 +177,10 @@ export class PacketHighwayContext {
|
||||
// 生成缩略图路径
|
||||
const videoDir = path.dirname(video.filePath);
|
||||
const videoBasename = path.basename(video.filePath, path.extname(video.filePath));
|
||||
const thumbPath = path.join(videoDir, `${videoBasename}_thumb.png`);
|
||||
const thumbPath = path.join(videoDir, `${videoBasename}_thumb_${randomUUID()}.jpg`);
|
||||
|
||||
this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
|
||||
video.thumbPath = thumbPath;
|
||||
|
||||
try {
|
||||
// 尝试使用 FFmpeg 提取视频缩略图
|
||||
@@ -174,26 +191,36 @@ export class PacketHighwayContext {
|
||||
} catch {
|
||||
throw new Error('FFmpeg failed to generate thumbnail');
|
||||
}
|
||||
await this.updateVideoThumbInfo(video);
|
||||
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
|
||||
throw new Error(`generated thumbnail is too large: ${video.thumbSize} bytes`);
|
||||
}
|
||||
} catch (e) {
|
||||
// FFmpeg 失败时(包括未初始化的情况)使用默认缩略图
|
||||
this.logger.warn(`[Highway] Failed to extract thumbnail, using default. Reason: ${e instanceof Error ? e.message : e}`);
|
||||
await fs.promises.writeFile(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
|
||||
await this.updateVideoThumbInfo(video);
|
||||
}
|
||||
|
||||
// 更新视频元素的缩略图信息
|
||||
video.thumbPath = thumbPath;
|
||||
const thumbStat = await fs.promises.stat(thumbPath);
|
||||
video.thumbSize = thumbStat.size;
|
||||
video.thumbMd5 = await calculateFileMD5(thumbPath);
|
||||
// 默认缩略图尺寸(与 defaultVideoThumbB64 匹配的尺寸)
|
||||
if (!video.thumbWidth) video.thumbWidth = 240;
|
||||
if (!video.thumbHeight) video.thumbHeight = 383;
|
||||
|
||||
this.logger.debug(`[Highway] Video thumb info set: path=${thumbPath}, size=${video.thumbSize}, md5=${video.thumbMd5}`);
|
||||
|
||||
return thumbPath;
|
||||
}
|
||||
|
||||
private async updateVideoThumbInfo (video: PacketMsgVideoElement): Promise<void> {
|
||||
if (!video.thumbPath) {
|
||||
throw new Error('video.thumbPath is empty, cannot inspect thumbnail');
|
||||
}
|
||||
const [thumbStat, thumbMd5, dimensions] = await Promise.all([
|
||||
fs.promises.stat(video.thumbPath),
|
||||
calculateFileMD5(video.thumbPath),
|
||||
imageSizeFallBack(video.thumbPath),
|
||||
]);
|
||||
video.thumbSize = thumbStat.size;
|
||||
video.thumbMd5 = thumbMd5;
|
||||
video.thumbWidth = dimensions.width;
|
||||
video.thumbHeight = dimensions.height;
|
||||
this.logger.debug(`[Highway] Video thumbnail ready: ${dimensions.width}x${dimensions.height}, ${thumbStat.size} bytes`);
|
||||
}
|
||||
|
||||
async uploadPtt (peer: Peer, ptt: PacketMsgPttElement): Promise<void> {
|
||||
await this.checkAvailable();
|
||||
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
|
||||
@@ -296,13 +323,17 @@ export class PacketHighwayContext {
|
||||
const req = trans.UploadGroupVideo.build(groupUin, video);
|
||||
const resp = await this.client.sendOidbPacket(req, true);
|
||||
const preRespData = trans.UploadGroupVideo.parse(resp);
|
||||
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
|
||||
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
|
||||
if (!videoIndex || !thumbIndex) {
|
||||
throw new Error('[Highway] uploadGroupVideo response is missing video or thumbnail MsgInfo');
|
||||
}
|
||||
const ukey = preRespData.upload.uKey;
|
||||
if (ukey && ukey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
uKey: ukey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
|
||||
@@ -324,16 +355,15 @@ export class PacketHighwayContext {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
|
||||
}
|
||||
const subFile = preRespData.upload.subFileInfos[0];
|
||||
if (subFile!.uKey && subFile!.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
|
||||
if (subFile?.uKey && subFile.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
|
||||
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
uKey: subFile!.uKey,
|
||||
fileUuid: thumbIndex.fileUuid,
|
||||
uKey: subFile.uKey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
|
||||
},
|
||||
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
|
||||
blockSize: BlockSize,
|
||||
@@ -349,7 +379,7 @@ export class PacketHighwayContext {
|
||||
extend
|
||||
);
|
||||
} else {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
|
||||
}
|
||||
video.msgInfo = preRespData.upload.msgInfo;
|
||||
}
|
||||
@@ -361,13 +391,17 @@ export class PacketHighwayContext {
|
||||
const req = trans.UploadPrivateVideo.build(peerUid, video);
|
||||
const resp = await this.client.sendOidbPacket(req, true);
|
||||
const preRespData = trans.UploadPrivateVideo.parse(resp);
|
||||
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
|
||||
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
|
||||
if (!videoIndex || !thumbIndex) {
|
||||
throw new Error('[Highway] uploadC2CVideo response is missing video or thumbnail MsgInfo');
|
||||
}
|
||||
const ukey = preRespData.upload.uKey;
|
||||
if (ukey && ukey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
uKey: ukey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
|
||||
@@ -389,16 +423,15 @@ export class PacketHighwayContext {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
|
||||
}
|
||||
const subFile = preRespData.upload.subFileInfos[0];
|
||||
if (subFile!.uKey && subFile!.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
|
||||
if (subFile?.uKey && subFile.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
|
||||
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
uKey: subFile!.uKey,
|
||||
fileUuid: thumbIndex.fileUuid,
|
||||
uKey: subFile.uKey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
|
||||
},
|
||||
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
|
||||
blockSize: BlockSize,
|
||||
@@ -414,7 +447,7 @@ export class PacketHighwayContext {
|
||||
extend
|
||||
);
|
||||
} else {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
|
||||
}
|
||||
video.msgInfo = preRespData.upload.msgInfo;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
MessageElement,
|
||||
Peer,
|
||||
RawMessage,
|
||||
} from '@/napcat-core/types/msg';
|
||||
import {
|
||||
SendArkElement,
|
||||
SendFaceElement,
|
||||
SendFileElement,
|
||||
@@ -15,7 +17,7 @@ import {
|
||||
SendReplyElement,
|
||||
SendTextElement,
|
||||
SendVideoElement,
|
||||
} from '@/napcat-core/index';
|
||||
} from '@/napcat-core/types/element';
|
||||
import {
|
||||
IPacketMsgElement,
|
||||
PacketMsgAtElement,
|
||||
@@ -158,7 +160,8 @@ export class PacketMsgConverter {
|
||||
|
||||
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
|
||||
const converters = [PacketMsgTextElement.parseElement,
|
||||
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
|
||||
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement,
|
||||
PacketMsgVideoElement.parseElement, PacketMsgPicElement.parseElement];
|
||||
return msg.map((element) => {
|
||||
for (const converter of converters) {
|
||||
const result = converter(element);
|
||||
|
||||
@@ -20,7 +20,11 @@ import {
|
||||
FaceType,
|
||||
MessageElement,
|
||||
NTMsgAtType,
|
||||
NTVideoType,
|
||||
PicType,
|
||||
Peer,
|
||||
} from '@/napcat-core/types/msg';
|
||||
import {
|
||||
SendArkElement,
|
||||
SendFaceElement,
|
||||
SendFileElement,
|
||||
@@ -32,8 +36,7 @@ import {
|
||||
SendMultiForwardMsgElement,
|
||||
SendTextElement,
|
||||
SendVideoElement,
|
||||
Peer,
|
||||
} from '@/napcat-core/index';
|
||||
} from '@/napcat-core/types/element';
|
||||
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
|
||||
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
|
||||
|
||||
@@ -387,8 +390,10 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
}
|
||||
|
||||
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
|
||||
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
|
||||
if (elem?.commonElem?.serviceType === 48 &&
|
||||
[10, 20].includes(elem.commonElem.businessType ?? 0) &&
|
||||
elem.commonElem.pbElem) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
|
||||
const msgInfoBody = extra.msgInfoBody[0];
|
||||
const index = msgInfoBody?.index;
|
||||
return [{
|
||||
@@ -406,7 +411,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
summary: '[图片]',
|
||||
thumbPath: new Map(),
|
||||
},
|
||||
elementType: ElementType.UNKNOWN,
|
||||
elementType: ElementType.PIC,
|
||||
elementId: '',
|
||||
}, elem];
|
||||
}
|
||||
@@ -446,8 +451,13 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
}
|
||||
|
||||
export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
fileName: string;
|
||||
fileSize?: string;
|
||||
filePath?: string;
|
||||
fileTime: number;
|
||||
fileFormat: NTVideoType;
|
||||
fileWidth?: number;
|
||||
fileHeight?: number;
|
||||
thumbSize?: number;
|
||||
thumbPath?: string;
|
||||
fileMd5?: string;
|
||||
@@ -456,12 +466,18 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
thumbSha1?: string;
|
||||
thumbWidth?: number;
|
||||
thumbHeight?: number;
|
||||
businessType: 11 | 21 = 21;
|
||||
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
|
||||
|
||||
constructor (element: SendVideoElement) {
|
||||
super(element);
|
||||
this.fileName = element.videoElement.fileName;
|
||||
this.fileSize = element.videoElement.fileSize;
|
||||
this.filePath = element.videoElement.filePath;
|
||||
this.fileTime = Math.max(0, Math.round(element.videoElement.fileTime ?? 0));
|
||||
this.fileFormat = element.videoElement.fileFormat ?? NTVideoType.VIDEO_FORMAT_MP4;
|
||||
this.fileWidth = element.videoElement.fileWidth;
|
||||
this.fileHeight = element.videoElement.fileHeight;
|
||||
this.thumbSize = element.videoElement.thumbSize;
|
||||
this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
|
||||
this.fileMd5 = element.videoElement.videoMd5;
|
||||
@@ -480,11 +496,45 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
|
||||
businessType: 21,
|
||||
businessType: this.businessType,
|
||||
},
|
||||
}];
|
||||
}
|
||||
|
||||
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
|
||||
if (elem?.commonElem?.serviceType !== 48 ||
|
||||
![11, 21].includes(elem.commonElem.businessType ?? 0) ||
|
||||
!elem.commonElem.pbElem) {
|
||||
return undefined;
|
||||
}
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
|
||||
const videoIndex = extra.msgInfoBody[0]?.index;
|
||||
const thumbIndex = extra.msgInfoBody[1]?.index;
|
||||
if (!videoIndex) return undefined;
|
||||
return [{
|
||||
videoElement: {
|
||||
filePath: '',
|
||||
fileName: videoIndex.info.fileName || videoIndex.info.fileHash,
|
||||
videoMd5: videoIndex.info.fileHash,
|
||||
thumbMd5: thumbIndex?.info.fileHash,
|
||||
fileTime: videoIndex.info.time,
|
||||
fileFormat: (videoIndex.info.type.videoFormat || NTVideoType.VIDEO_FORMAT_MP4) as NTVideoType,
|
||||
fileSize: String(videoIndex.info.fileSize),
|
||||
fileWidth: videoIndex.info.width,
|
||||
fileHeight: videoIndex.info.height,
|
||||
thumbWidth: thumbIndex?.info.width,
|
||||
thumbHeight: thumbIndex?.info.height,
|
||||
thumbSize: thumbIndex?.info.fileSize,
|
||||
thumbPath: new Map(),
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
busiType: 0,
|
||||
subBusiType: 0,
|
||||
},
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: '',
|
||||
}, elem];
|
||||
};
|
||||
|
||||
override toPreview (): string {
|
||||
return '[视频]';
|
||||
}
|
||||
|
||||
@@ -33,16 +33,16 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
|
||||
fileSize: +video.fileSize,
|
||||
fileHash: video.fileMd5,
|
||||
fileSha1: video.fileSha1,
|
||||
fileName: 'nya.mp4',
|
||||
fileName: video.fileName || 'video.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
picFormat: 0,
|
||||
videoFormat: 0,
|
||||
videoFormat: video.fileFormat,
|
||||
voiceFormat: 0,
|
||||
},
|
||||
height: 0,
|
||||
width: 0,
|
||||
time: 0,
|
||||
height: video.fileHeight ?? 0,
|
||||
width: video.fileWidth ?? 0,
|
||||
time: video.fileTime,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
@@ -51,7 +51,7 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
|
||||
fileSize: +video.thumbSize,
|
||||
fileHash: video.thumbMd5,
|
||||
fileSha1: video.thumbSha1,
|
||||
fileName: 'nya.jpg',
|
||||
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
|
||||
@@ -34,16 +34,16 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
|
||||
fileSize: +video.fileSize,
|
||||
fileHash: video.fileMd5,
|
||||
fileSha1: video.fileSha1,
|
||||
fileName: 'nya.mp4',
|
||||
fileName: video.fileName || 'video.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
picFormat: 0,
|
||||
videoFormat: 0,
|
||||
videoFormat: video.fileFormat,
|
||||
voiceFormat: 0,
|
||||
},
|
||||
height: 0,
|
||||
width: 0,
|
||||
time: 0,
|
||||
height: video.fileHeight ?? 0,
|
||||
width: video.fileWidth ?? 0,
|
||||
time: video.fileTime,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
@@ -52,7 +52,7 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
|
||||
fileSize: +video.thumbSize,
|
||||
fileHash: video.thumbMd5,
|
||||
fileSha1: video.thumbSha1,
|
||||
fileName: 'nya.jpg',
|
||||
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
|
||||
@@ -369,7 +369,16 @@ export interface NodeIKernelMsgService {
|
||||
}>;
|
||||
}>;
|
||||
|
||||
addFavEmoji (arg: unknown): unknown;
|
||||
addFavEmoji (arg: {
|
||||
emojiId?: string,
|
||||
packageId?: number,
|
||||
emojiPath: string,
|
||||
fileSize: string,
|
||||
fileName: string,
|
||||
md5: string,
|
||||
isMarkFace?: boolean,
|
||||
isOrigin?: boolean,
|
||||
}): unknown;
|
||||
|
||||
fetchMarketEmoticonList (arg1: number, arg2: number): unknown;
|
||||
|
||||
@@ -397,9 +406,14 @@ export interface NodeIKernelMsgService {
|
||||
|
||||
downloadEmojiPic (arg1: number, arg2: Array<unknown>[], arg3: number, arg4: Map<unknown, unknown>): unknown;
|
||||
|
||||
deleteFavEmoji (arg: unknown): unknown;
|
||||
deleteFavEmoji (arg: string[]): unknown;
|
||||
|
||||
modifyFavEmojiDesc (arg: unknown): unknown;
|
||||
modifyFavEmojiDesc (arg: Array<{
|
||||
emojiId: number,
|
||||
resId: string,
|
||||
md5: string,
|
||||
desc: string,
|
||||
}>): unknown;
|
||||
|
||||
queryFavEmojiByDesc (arg: unknown): unknown;
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -118,6 +118,8 @@ export interface VideoElement {
|
||||
thumbSize?: number; // byte
|
||||
fileFormat?: NTVideoType; // 2表示mp4 参考下面条目
|
||||
fileSize?: string; // byte
|
||||
fileWidth?: number;
|
||||
fileHeight?: number;
|
||||
thumbWidth?: number;
|
||||
thumbHeight?: number;
|
||||
busiType?: 0; //
|
||||
|
||||
@@ -74,6 +74,20 @@ export interface EXTInfo {
|
||||
groupSquareSwitch: number;
|
||||
}
|
||||
|
||||
export type GroupMemberInvitePolicy =
|
||||
| 'disabled'
|
||||
| 'require_approval'
|
||||
| 'no_approval'
|
||||
| 'no_approval_under_100';
|
||||
|
||||
export interface GroupManagementSettings {
|
||||
memberInvite?: GroupMemberInvitePolicy;
|
||||
allowMemberUploadAlbum?: boolean;
|
||||
allowMemberTemporarySession?: boolean;
|
||||
allowMemberCreateGroup?: boolean;
|
||||
newMembersSeeRecentHistory?: boolean;
|
||||
}
|
||||
|
||||
export interface GroupGuildIDS {
|
||||
guildIds: any[];
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ 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;
|
||||
@@ -92,6 +93,7 @@ export interface WebApiGroupNoticeRet {
|
||||
read_only: number
|
||||
role: number
|
||||
feeds: WebApiGroupNoticeFeed[]
|
||||
inst?: WebApiGroupNoticeFeed[] // 「发给新成员」类公告,不在 feeds 里
|
||||
group: {
|
||||
group_id: number
|
||||
class_ext: number
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
node.exe ./index.js
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
"%~dp0node.exe" "%~dp0index.js" %*
|
||||
exit /b %errorlevel%
|
||||
@@ -1,6 +1,7 @@
|
||||
const process = require('process');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { pathToFileURL } = require('url');
|
||||
|
||||
// 保存原始dlopen
|
||||
const dlopenOrig = process.dlopen;
|
||||
@@ -50,7 +51,7 @@ async function initializeNapCat () {
|
||||
console.log('[NapCat] [Info] 开始初始化NapCat');
|
||||
try {
|
||||
const currentPath = path.dirname(__filename);
|
||||
const { NCoreInitFramework, getWebUiUrl } = await import('file://' + path.join(currentPath, './napcat.mjs'));
|
||||
const { NCoreInitFramework, getWebUiUrl } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
|
||||
getWebUiUrlFunc = getWebUiUrl;
|
||||
await NCoreInitFramework(wrapperSession, wrapperLoginService, (callback) => { ncCallback = callback; });
|
||||
} catch (error) {
|
||||
|
||||
@@ -9,6 +9,7 @@ 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';
|
||||
@@ -105,6 +106,13 @@ 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());
|
||||
});
|
||||
@@ -118,6 +126,8 @@ export async function NCoreInitFramework (
|
||||
|
||||
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
|
||||
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
WebUiDataRuntime.setQQLoginPhase('waiting_qrcode');
|
||||
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
|
||||
};
|
||||
|
||||
@@ -146,9 +156,14 @@ 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] 二维码已被扫描,等待确认...');
|
||||
};
|
||||
|
||||
@@ -194,7 +209,44 @@ 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;
|
||||
},
|
||||
});
|
||||
loaderObject.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
|
||||
loaderObject.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
|
||||
}
|
||||
|
||||
function registerWebUiLoginCallbacks (
|
||||
@@ -204,7 +256,22 @@ function registerWebUiLoginCallbacks (
|
||||
) {
|
||||
// 刷新二维码
|
||||
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
|
||||
loginService.getQRCodePicture();
|
||||
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 未接受二维码刷新请求');
|
||||
}
|
||||
});
|
||||
|
||||
// 快速登录
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { pathToFileURL } = require('url');
|
||||
|
||||
async function initializeNapCat (session, loginService, registerCallback) {
|
||||
// const logFile = path.join(currentPath, 'napcat.log');
|
||||
@@ -12,7 +13,7 @@ async function initializeNapCat (session, loginService, registerCallback) {
|
||||
|
||||
try {
|
||||
const currentPath = path.dirname(__filename);
|
||||
const { NCoreInitFramework } = await import('file://' + path.join(currentPath, './napcat.mjs'));
|
||||
const { NCoreInitFramework } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
|
||||
await NCoreInitFramework(session, loginService, (callback) => { registerCallback(callback); });
|
||||
} catch (error) {
|
||||
console.log('[NapCat] [Error] 初始化NapCat', error);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
chcp 65001
|
||||
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
|
||||
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
|
||||
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
|
||||
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
|
||||
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
|
||||
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
|
||||
set NAPCAT_DEBUG_CONSOLE=1
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
@@ -27,4 +29,4 @@ set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
|
||||
|
||||
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
|
||||
|
||||
pause
|
||||
pause
|
||||
@@ -1,8 +1,10 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
chcp 65001
|
||||
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
|
||||
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
|
||||
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
|
||||
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
|
||||
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
|
||||
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
set "RetString=%%~b"
|
||||
@@ -24,4 +26,4 @@ if not exist "%QQpath%" (
|
||||
|
||||
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
|
||||
|
||||
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
|
||||
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -42,4 +42,12 @@ export const ExtendsActionsExamples = {
|
||||
payload: { group_id: '123456', user_id: '123456789', special_title: '头衔' },
|
||||
response: null,
|
||||
},
|
||||
SendQzoneMsg: {
|
||||
payload: { content: '今天天气不错', images: [], ugc_right: 1, target_uins: [] },
|
||||
response: { tid: '1234567890abcdef1234567890' },
|
||||
},
|
||||
DeleteQzoneMsg: {
|
||||
payload: { tid: '1234567890abcdef1234567890' },
|
||||
response: null,
|
||||
},
|
||||
};
|
||||
@@ -1,4 +1,21 @@
|
||||
export const GroupActionsExamples = {
|
||||
SetGroupMemberInvitePolicy: {
|
||||
payload: { group_id: '123456', policy: 'require_approval' },
|
||||
response: null,
|
||||
},
|
||||
SetGroupMemberPermissions: {
|
||||
payload: {
|
||||
group_id: '123456',
|
||||
allow_member_upload_album: true,
|
||||
allow_member_temporary_session: true,
|
||||
allow_member_create_group: true,
|
||||
},
|
||||
response: null,
|
||||
},
|
||||
SetGroupNewMemberHistoryVisibility: {
|
||||
payload: { group_id: '123456', visible: true },
|
||||
response: null,
|
||||
},
|
||||
DelEssenceMsg: {
|
||||
payload: { message_id: 123456 },
|
||||
response: null,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { stat, readFile } from 'node:fs/promises';
|
||||
import { basename } from 'node:path';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
|
||||
const FetchCustomFaceDetailPayloadSchema = Type.Object({
|
||||
count: Type.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' }),
|
||||
});
|
||||
|
||||
type FetchCustomFaceDetailPayloadType = Static<typeof FetchCustomFaceDetailPayloadSchema>;
|
||||
|
||||
const FetchCustomFaceDetailReturnSchema = Type.Any({ description: '自定义表情详情列表' });
|
||||
|
||||
type FetchCustomFaceDetailReturnType = Static<typeof FetchCustomFaceDetailReturnSchema>;
|
||||
|
||||
export class FetchCustomFaceDetail extends OneBotAction<FetchCustomFaceDetailPayloadType, FetchCustomFaceDetailReturnType> {
|
||||
override actionName = ActionName.FetchCustomFaceDetail;
|
||||
override payloadSchema = FetchCustomFaceDetailPayloadSchema;
|
||||
override returnSchema = FetchCustomFaceDetailReturnSchema;
|
||||
override actionSummary = '获取自定义表情详情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
count: 10,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: FetchCustomFaceDetailPayloadType) {
|
||||
const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count);
|
||||
return ret.emojiInfoList;
|
||||
}
|
||||
}
|
||||
|
||||
const AddCustomFacePayloadSchema = Type.Object({
|
||||
file: Type.String({ description: '本地表情文件路径' }),
|
||||
emoji_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情ID,未提供时传空字符串' })),
|
||||
package_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情包ID,未提供时传0' })),
|
||||
file_name: Type.Optional(Type.String({ description: '文件名,未提供时从file路径取basename' })),
|
||||
file_size: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '文件大小,未提供时读取本地文件' })),
|
||||
md5: Type.Optional(Type.String({ description: '文件MD5,未提供时读取本地文件计算' })),
|
||||
is_mark_face: Type.Optional(Type.Boolean({ description: '是否商城表情' })),
|
||||
is_origin: Type.Optional(Type.Boolean({ description: '是否原图' })),
|
||||
});
|
||||
|
||||
type AddCustomFacePayloadType = Static<typeof AddCustomFacePayloadSchema>;
|
||||
|
||||
const AddCustomFaceReturnSchema = Type.Any({ description: '添加结果' });
|
||||
|
||||
type AddCustomFaceReturnType = Static<typeof AddCustomFaceReturnSchema>;
|
||||
|
||||
export class AddCustomFace extends OneBotAction<AddCustomFacePayloadType, AddCustomFaceReturnType> {
|
||||
override actionName = ActionName.AddCustomFace;
|
||||
override payloadSchema = AddCustomFacePayloadSchema;
|
||||
override returnSchema = AddCustomFaceReturnSchema;
|
||||
override actionSummary = '添加自定义表情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
file: 'C:\\Users\\Public\\face.png',
|
||||
is_origin: true,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: AddCustomFacePayloadType) {
|
||||
const fileStat = await stat(payload.file);
|
||||
const md5 = payload.md5 ?? createHash('md5').update(await readFile(payload.file)).digest('hex');
|
||||
return await this.core.apis.MsgApi.addFavEmoji({
|
||||
emojiId: payload.emoji_id?.toString() ?? '',
|
||||
packageId: payload.package_id === undefined ? 0 : Number(payload.package_id),
|
||||
emojiPath: payload.file,
|
||||
fileSize: payload.file_size?.toString() ?? fileStat.size.toString(),
|
||||
fileName: payload.file_name ?? basename(payload.file),
|
||||
md5,
|
||||
isMarkFace: payload.is_mark_face ?? false,
|
||||
isOrigin: payload.is_origin ?? true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const DeleteCustomFacePayloadSchema = Type.Object({
|
||||
res_id: Type.Optional(Type.Union([
|
||||
Type.String({ description: 'fetch_custom_face_detail返回的resId' }),
|
||||
Type.Array(Type.String({ description: 'fetch_custom_face_detail返回的resId' })),
|
||||
])),
|
||||
id: Type.Optional(Type.Union([
|
||||
Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' }),
|
||||
Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' })),
|
||||
])),
|
||||
ids: Type.Optional(Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID列表,通常为resId列表' }))),
|
||||
md5: Type.Optional(Type.Union([
|
||||
Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' }),
|
||||
Type.Array(Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' })),
|
||||
])),
|
||||
});
|
||||
|
||||
type DeleteCustomFacePayloadType = Static<typeof DeleteCustomFacePayloadSchema>;
|
||||
|
||||
const DeleteCustomFaceReturnSchema = Type.Any({ description: '删除结果' });
|
||||
|
||||
type DeleteCustomFaceReturnType = Static<typeof DeleteCustomFaceReturnSchema>;
|
||||
|
||||
export class DeleteCustomFace extends OneBotAction<DeleteCustomFacePayloadType, DeleteCustomFaceReturnType> {
|
||||
override actionName = ActionName.DeleteCustomFace;
|
||||
override payloadSchema = DeleteCustomFacePayloadSchema;
|
||||
override returnSchema = DeleteCustomFaceReturnSchema;
|
||||
override actionSummary = '删除自定义表情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
res_id: '2707600964_0_0_0_D8EAA70984B402EE10B0F33DB88F4173_0_0',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: DeleteCustomFacePayloadType) {
|
||||
const ids = payload.ids ??
|
||||
(Array.isArray(payload.res_id) ? payload.res_id : payload.res_id ? [payload.res_id] : undefined) ??
|
||||
(Array.isArray(payload.id) ? payload.id : payload.id ? [payload.id] : undefined) ??
|
||||
[];
|
||||
if (ids.length === 0) throw new Error('res_id or ids is required');
|
||||
return await this.core.apis.MsgApi.deleteFavEmoji(ids);
|
||||
}
|
||||
}
|
||||
|
||||
const SetCustomFaceDescPayloadSchema = Type.Object({
|
||||
emoji_id: Type.Union([Type.Number(), Type.String()], { description: '表情ID' }),
|
||||
res_id: Type.String({ description: '资源ID' }),
|
||||
md5: Type.String({ description: '表情MD5' }),
|
||||
desc: Type.String({ description: '新的表情描述' }),
|
||||
});
|
||||
|
||||
type SetCustomFaceDescPayloadType = Static<typeof SetCustomFaceDescPayloadSchema>;
|
||||
|
||||
const SetCustomFaceDescReturnSchema = Type.Any({ description: '修改结果' });
|
||||
|
||||
type SetCustomFaceDescReturnType = Static<typeof SetCustomFaceDescReturnSchema>;
|
||||
|
||||
export class SetCustomFaceDesc extends OneBotAction<SetCustomFaceDescPayloadType, SetCustomFaceDescReturnType> {
|
||||
override actionName = ActionName.SetCustomFaceDesc;
|
||||
override payloadSchema = SetCustomFaceDescPayloadSchema;
|
||||
override returnSchema = SetCustomFaceDescReturnSchema;
|
||||
override actionSummary = '修改自定义表情描述';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
emoji_id: 1,
|
||||
res_id: 'resource-id',
|
||||
md5: 'd41d8cd98f00b204e9800998ecf8427e',
|
||||
desc: '新的描述',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: SetCustomFaceDescPayloadType) {
|
||||
return await this.core.apis.MsgApi.modifyFavEmojiDesc([{
|
||||
emojiId: Number(payload.emoji_id),
|
||||
resId: payload.res_id,
|
||||
md5: payload.md5,
|
||||
desc: payload.desc,
|
||||
}]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
tid: Type.String({ description: '说说 tid (来自 get_qzone_msg_list / send_qzone_msg)' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
export class DeleteQzoneMsg extends OneBotAction<PayloadType, void> {
|
||||
override actionName = ActionName.DeleteQzoneMsg;
|
||||
override actionSummary = '删除QQ空间说说';
|
||||
override actionDescription = '删除QQ空间(Qzone)的一条说说, 按 tid 删除';
|
||||
override actionTags = ['扩展接口'];
|
||||
override payloadExample = ExtendsActionsExamples.DeleteQzoneMsg.payload;
|
||||
override returnExample = ExtendsActionsExamples.DeleteQzoneMsg.response;
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = Type.Null();
|
||||
|
||||
async _handle (payload: PayloadType): Promise<void> {
|
||||
await this.core.apis.WebApi.deleteQzoneMsg(payload.tid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.Union([Type.Number(), Type.String()], { description: '群号' }),
|
||||
need_short_url: Type.Optional(Type.Union([Type.Boolean(), Type.String()], { default: true, description: '是否返回短链 (qm.qq.com/q/xxx),false 返回完整 universal-share 链接' })),
|
||||
src_id: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 73, description: '分享来源 ID' })),
|
||||
additional_param: Type.Optional(Type.String({ default: '', description: '附加参数' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Object({
|
||||
url: Type.String({ description: '群分享链接' }),
|
||||
}, { description: '群分享链接' });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class GetGroupShareLink extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.GetGroupShareLink;
|
||||
override actionSummary = '获取群分享链接';
|
||||
override actionDescription = '通过 NTQQ 原生 getJoinGroupLink 获取群的 H5 分享/加群链接 (qm.qq.com/q/xxx 或 qun.qq.com/universal-share/share?...)';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
need_short_url: true,
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
url: 'https://qm.qq.com/q/xxxxxxxxxx',
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const needShortUrl = payload.need_short_url === undefined ? true : payload.need_short_url.toString() === 'true';
|
||||
const srcId = payload.src_id === undefined ? 73 : Number(payload.src_id);
|
||||
const ret = await this.core.apis.GroupApi.getJoinGroupLink(
|
||||
payload.group_id.toString(),
|
||||
needShortUrl,
|
||||
srcId,
|
||||
payload.additional_param ?? ''
|
||||
);
|
||||
if (!ret?.url) {
|
||||
throw new Error(`获取群分享链接失败: ${ret?.errMsg || JSON.stringify(ret)}`);
|
||||
}
|
||||
return { url: ret.url };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
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.String(), Type.Number()], { description: '群号' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Array(
|
||||
Type.Object({
|
||||
user_id: Type.Number({ description: '打卡者QQ' }),
|
||||
nick: Type.String({ description: '打卡者昵称' }),
|
||||
time: Type.Number({ description: '打卡时间' }),
|
||||
rank: Type.Number({ description: '打卡排名' }),
|
||||
}),
|
||||
{ description: '群组今日打卡列表' }
|
||||
);
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class GetGroupSignedList extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.GetGroupSignedList;
|
||||
override actionSummary = '获取群组今日打卡列表';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const data = await this.core.apis.WebApi.getDaySignedList(payload.group_id.toString());
|
||||
if (!data.response.page) throw new Error('无法获取该群组打卡列表');
|
||||
return data.response.page[0]?.infos?.map(info => ({
|
||||
user_id: +info.uid,
|
||||
nick: info.uidGroupNick,
|
||||
time: +info.signedTimeStamp,
|
||||
rank: (info.signInRank - 1) / 2 + 1,
|
||||
})) ?? [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { uriToLocalFile } from 'napcat-common/src/file';
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { unlink } from 'node:fs/promises';
|
||||
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
|
||||
|
||||
const ValidUgcRights = [1, 4, 16, 64, 128] as const;
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
content: Type.String({ description: '说说正文' }),
|
||||
images: Type.Optional(Type.Array(Type.String(), { description: '图片数组, 支持 file:// http(s):// base64:// , 自动上传' })),
|
||||
ugc_right: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '查看权限: 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见' })),
|
||||
target_uins: Type.Optional(Type.Array(Type.Union([Type.Number(), Type.String()]), { description: 'ugc_right为16/128时, 权限作用的QQ号数组' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Object({
|
||||
tid: Type.String({ description: '说说Tid' }),
|
||||
}, { description: '发说说结果' });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class SendQzoneMsg extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SendQzoneMsg;
|
||||
override actionSummary = '发表QQ空间说说';
|
||||
override actionDescription = '在QQ空间(Qzone)发表说说, 支持纯文字或带(多)图, 可设置查看权限';
|
||||
override actionTags = ['扩展接口'];
|
||||
override payloadExample = ExtendsActionsExamples.SendQzoneMsg.payload;
|
||||
override returnExample = ExtendsActionsExamples.SendQzoneMsg.response;
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const ugcRight = payload.ugc_right !== undefined ? +payload.ugc_right : 1;
|
||||
if (!ValidUgcRights.includes(ugcRight as typeof ValidUgcRights[number])) {
|
||||
throw new Error(`ugc_right 参数不合法, 允许的值为: ${ValidUgcRights.join(', ')}`);
|
||||
}
|
||||
const targetUins = payload.target_uins?.map((uin) => +uin).filter((uin) => !Number.isNaN(uin));
|
||||
if ((ugcRight === 16 || ugcRight === 128) && (!targetUins || targetUins.length === 0)) {
|
||||
throw new Error('ugc_right 为 16 或 128 时, target_uins 不能为空');
|
||||
}
|
||||
|
||||
const richvals: string[] = [];
|
||||
const cleanupPaths: string[] = [];
|
||||
try {
|
||||
for (const image of payload.images ?? []) {
|
||||
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, image);
|
||||
if (!downloadResult.success) {
|
||||
throw new Error(`图片${image}处理失败, ${downloadResult.errMsg}`);
|
||||
}
|
||||
if (!downloadResult.isLocal) {
|
||||
cleanupPaths.push(downloadResult.path);
|
||||
}
|
||||
const base64 = readFileSync(downloadResult.path).toString('base64');
|
||||
const richval = await this.core.apis.WebApi.uploadImageToQzone(base64);
|
||||
richvals.push(richval);
|
||||
}
|
||||
|
||||
const result = await this.core.apis.WebApi.publishQzoneMsg(payload.content, richvals, ugcRight, targetUins);
|
||||
return result;
|
||||
} finally {
|
||||
for (const p of cleanupPaths) {
|
||||
if (existsSync(p)) {
|
||||
await unlink(p).catch(() => { });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
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)))
|
||||
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply)))
|
||||
).filter((msg): msg is OB11Message => msg !== undefined);
|
||||
return { messages: ob11MsgList };
|
||||
}
|
||||
|
||||
@@ -29,15 +29,22 @@ export class GetGroupFileSystemInfo extends OneBotAction<PayloadType, ReturnType
|
||||
override returnExample = GoCQHTTPActionsExamples.GetGroupFileSystemInfo.response;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const groupFileCount = (await this.core.apis.GroupApi.getGroupFileCount([payload.group_id.toString()])).groupFileCounts[0];
|
||||
if (!groupFileCount) {
|
||||
const groupCode = payload.group_id.toString();
|
||||
const [countResult, space] = await Promise.all([
|
||||
this.core.apis.GroupApi.getGroupFileCount([groupCode]),
|
||||
this.core.apis.GroupApi.getGroupFileSpace(groupCode),
|
||||
]);
|
||||
const groupFileCount = countResult.groupFileCounts[0];
|
||||
if (groupFileCount === undefined) {
|
||||
throw new Error('Group not found');
|
||||
}
|
||||
return {
|
||||
file_count: groupFileCount,
|
||||
limit_count: 10000,
|
||||
used_space: 0,
|
||||
total_space: 10 * 1024 * 1024 * 1024,
|
||||
// Real values from the kernel's groupSpaceResult; fall back to the old
|
||||
// placeholders if the field is unexpectedly absent.
|
||||
used_space: space?.usedSpace ?? 0,
|
||||
total_space: space?.totalSpace ?? 10 * 1024 * 1024 * 1024,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,8 @@ export class GetGroupFilesByFolder extends OneBotAction<PayloadType, ReturnType>
|
||||
return {
|
||||
files: ret.filter(item => item.fileInfo)
|
||||
.map(item => OB11Construct.file(item.peerId, item.fileInfo!)),
|
||||
folders: [],
|
||||
folders: ret.filter(item => item.folderInfo)
|
||||
.map(item => OB11Construct.folder(item.peerId, item.folderInfo!)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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 ? payload?.sex.toString() : OldProfile?.sex!.toString()),
|
||||
sex: parseInt(payload.sex != null && 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_seq, msg_random);
|
||||
return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_random, msg_seq);
|
||||
}
|
||||
return await this.core.apis.GroupApi.removeGroupEssence(
|
||||
msg.Peer.peerUid,
|
||||
|
||||
@@ -21,6 +21,8 @@ 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>;
|
||||
@@ -44,30 +46,44 @@ export class GetGroupNotice extends OneBotAction<PayloadType, ReturnType> {
|
||||
throw new Error('获取公告失败');
|
||||
}
|
||||
const retNotices: ReturnType = [];
|
||||
for (const key in ret.feeds) {
|
||||
if (!ret.feeds[key]) {
|
||||
continue;
|
||||
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));
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { GeneralCallResult } from 'napcat-core';
|
||||
|
||||
export function assertGroupManagementResults (
|
||||
operation: string,
|
||||
results: Array<{ setting: string, result: GeneralCallResult; }>
|
||||
): void {
|
||||
const failure = results.find(item => item.result.result !== 0);
|
||||
if (!failure) return;
|
||||
throw new Error(
|
||||
`${operation}失败 Setting: ${failure.setting} ErrCode: ${failure.result.result} ` +
|
||||
`ErrMsg: ${failure.result.errMsg || '未知错误'}`
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { sleep } from '@/napcat-common/src/helper';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
|
||||
@@ -27,8 +28,24 @@ export default class SetGroupCard extends OneBotAction<PayloadType, ReturnType>
|
||||
override returnExample = GroupActionsExamples.SetGroupCard.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<null> {
|
||||
const member = await this.core.apis.GroupApi.getGroupMember(payload.group_id.toString(), payload.user_id.toString());
|
||||
if (member) await this.core.apis.GroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || '');
|
||||
return null;
|
||||
const groupId = payload.group_id.toString();
|
||||
const userId = payload.user_id.toString();
|
||||
const card = payload.card || '';
|
||||
|
||||
const member = await this.core.apis.GroupApi.getGroupMember(groupId, userId);
|
||||
if (!member) {
|
||||
throw new Error(`群(${groupId})成员${userId}不存在`);
|
||||
}
|
||||
|
||||
await this.core.apis.GroupApi.setMemberCard(groupId, member.uid, card);
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await sleep(1000);
|
||||
const updatedMember = await this.core.apis.GroupApi.refreshGroupMemberCachePartial(groupId, member.uid);
|
||||
if (updatedMember?.cardName === card) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
throw new Error('设置群名片未生效');
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,13 @@ export default class SetGroupLeave extends OneBotAction<PayloadType, ReturnType>
|
||||
override returnExample = GroupActionsExamples.SetGroupLeave.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<null> {
|
||||
await this.core.apis.GroupApi.quitGroup(payload.group_id.toString());
|
||||
const groupCode = payload.group_id.toString();
|
||||
// is_dismiss 既可能是布尔值,也可能是字符串 'true'(与 approve 等字段保持一致)
|
||||
if (payload.is_dismiss === true || payload.is_dismiss === 'true') {
|
||||
await this.core.apis.GroupApi.destroyGroup(groupCode);
|
||||
} else {
|
||||
await this.core.apis.GroupApi.quitGroup(groupCode);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
import { assertGroupManagementResults } from './GroupOperationHelpers';
|
||||
|
||||
const MemberInvitePolicySchema = Type.Union([
|
||||
Type.Literal('disabled'),
|
||||
Type.Literal('require_approval'),
|
||||
Type.Literal('no_approval'),
|
||||
Type.Literal('no_approval_under_100'),
|
||||
], {
|
||||
description: '成员邀请策略:禁止、需要管理员审核、无需审核、群成员少于100人时无需审核',
|
||||
});
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
policy: MemberInvitePolicySchema,
|
||||
});
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null({ description: '操作结果' });
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export default class SetGroupMemberInvitePolicy extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SetGroupMemberInvitePolicy;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '设置群成员邀请策略';
|
||||
override actionDescription = '设置是否允许群成员邀请好友进群,以及邀请是否需要管理员审核';
|
||||
override actionTags = ['群组接口'];
|
||||
override payloadExample = GroupActionsExamples.SetGroupMemberInvitePolicy.payload;
|
||||
override returnExample = GroupActionsExamples.SetGroupMemberInvitePolicy.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const results = await this.core.apis.GroupApi.setGroupMemberInvitePolicy(payload.group_id, payload.policy);
|
||||
assertGroupManagementResults('设置群成员邀请策略', results);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
import { assertGroupManagementResults } from './GroupOperationHelpers';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
allow_member_upload_album: Type.Optional(Type.Boolean({ description: '允许成员上传群相册' })),
|
||||
allow_member_temporary_session: Type.Optional(Type.Boolean({ description: '允许成员发起临时会话' })),
|
||||
allow_member_create_group: Type.Optional(Type.Boolean({ description: '允许成员发起新的群聊' })),
|
||||
});
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null({ description: '操作结果' });
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export default class SetGroupMemberPermissions extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SetGroupMemberPermissions;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '设置群成员功能权限';
|
||||
override actionDescription = '设置群成员上传相册、发起临时会话和发起新群聊的权限;未传入的项目保持不变';
|
||||
override actionTags = ['群组接口'];
|
||||
override payloadExample = GroupActionsExamples.SetGroupMemberPermissions.payload;
|
||||
override returnExample = GroupActionsExamples.SetGroupMemberPermissions.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const permissions = {
|
||||
allowMemberUploadAlbum: payload.allow_member_upload_album,
|
||||
allowMemberTemporarySession: payload.allow_member_temporary_session,
|
||||
allowMemberCreateGroup: payload.allow_member_create_group,
|
||||
};
|
||||
if (Object.values(permissions).every(value => value === undefined)) {
|
||||
throw new Error('至少需要提供一个群成员功能权限');
|
||||
}
|
||||
|
||||
const results = await this.core.apis.GroupApi.setGroupMemberPermissions(payload.group_id, permissions);
|
||||
assertGroupManagementResults('设置群成员功能权限', results);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
import { assertGroupManagementResults } from './GroupOperationHelpers';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
visible: Type.Boolean({ description: '新成员默认可见最近聊天记录' }),
|
||||
});
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null({ description: '操作结果' });
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export default class SetGroupNewMemberHistoryVisibility extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.SetGroupNewMemberHistoryVisibility;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '设置新成员历史消息可见性';
|
||||
override actionDescription = '设置新入群成员默认是否可以查看最近聊天记录';
|
||||
override actionTags = ['群组接口'];
|
||||
override payloadExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.payload;
|
||||
override returnExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const results = await this.core.apis.GroupApi.setGroupNewMemberHistoryVisibility(
|
||||
payload.group_id,
|
||||
payload.visible
|
||||
);
|
||||
assertGroupManagementResults('设置新成员历史消息可见性', results);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,7 @@ import GetRecentContact from './user/GetRecentContact';
|
||||
import { GetProfileLike } from './extends/GetProfileLike';
|
||||
import SetGroupPortrait from './go-cqhttp/SetGroupPortrait';
|
||||
import { FetchCustomFace } from './extends/FetchCustomFace';
|
||||
import { AddCustomFace, DeleteCustomFace, FetchCustomFaceDetail, SetCustomFaceDesc } from './extends/CustomFace';
|
||||
import GoCQHTTPUploadPrivateFile from './go-cqhttp/UploadPrivateFile';
|
||||
import { FetchEmojiLike } from './extends/FetchEmojiLike';
|
||||
import { GetEmojiLikes } from './extends/GetEmojiLikes';
|
||||
@@ -74,6 +75,7 @@ import { SetInputStatus } from './extends/SetInputStatus';
|
||||
import { GetCSRF } from './system/GetCSRF';
|
||||
import { DelGroupNotice } from './group/DelGroupNotice';
|
||||
import { GetGroupInfoEx } from './extends/GetGroupInfoEx';
|
||||
import { GetGroupShareLink } from './extends/GetGroupShareLink';
|
||||
import { DeleteGroupFile } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFile';
|
||||
import { CreateGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/CreateGroupFileFolder';
|
||||
import { DeleteGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFileFolder';
|
||||
@@ -132,6 +134,8 @@ 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';
|
||||
@@ -158,6 +162,12 @@ import { ReceiveOnlineFile } from './file/online/ReceiveOnlineFile';
|
||||
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 = [
|
||||
@@ -174,6 +184,8 @@ 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),
|
||||
@@ -189,6 +201,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetRkeyServer(obContext, core),
|
||||
new SetGroupRemark(obContext, core),
|
||||
new GetGroupInfoEx(obContext, core),
|
||||
new GetGroupShareLink(obContext, core),
|
||||
new FetchEmojiLike(obContext, core),
|
||||
new GetEmojiLikes(obContext, core),
|
||||
new FetchPttText(obContext, core),
|
||||
@@ -213,6 +226,12 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new MoveGroupFile(obContext, core),
|
||||
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),
|
||||
@@ -277,6 +296,10 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetProfileLike(obContext, core),
|
||||
new SetGroupPortrait(obContext, core),
|
||||
new FetchCustomFace(obContext, core),
|
||||
new FetchCustomFaceDetail(obContext, core),
|
||||
new AddCustomFace(obContext, core),
|
||||
new DeleteCustomFace(obContext, core),
|
||||
new SetCustomFaceDesc(obContext, core),
|
||||
new GoCQHTTPUploadPrivateFile(obContext, core),
|
||||
new GetGuildProfile(obContext, core),
|
||||
new GoCQHTTPGetModelShow(obContext, core),
|
||||
|
||||
@@ -84,6 +84,13 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
|
||||
}
|
||||
const isBuddy = await core.apis.FriendApi.isBuddy(Uid);
|
||||
if (!isBuddy) {
|
||||
if (payload.group_id) {
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
|
||||
peerUid: Uid,
|
||||
guildId: payload.group_id.toString(),
|
||||
};
|
||||
}
|
||||
const ret = await core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, Uid);
|
||||
if (ret.tmpChatInfo?.groupCode) {
|
||||
return {
|
||||
@@ -92,13 +99,6 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
|
||||
guildId: '',
|
||||
};
|
||||
}
|
||||
if (payload.group_id) {
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
|
||||
peerUid: Uid,
|
||||
guildId: payload.group_id.toString(),
|
||||
};
|
||||
}
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPEC2C,
|
||||
peerUid: Uid,
|
||||
@@ -245,7 +245,12 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
|
||||
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(
|
||||
OB11Data,
|
||||
msgPeer,
|
||||
[],
|
||||
{ usePacketVideoMetadata: true }
|
||||
);
|
||||
sendElements = sendElementsCreateReturn.sendElements;
|
||||
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ export abstract class BaseGroupTodoAction extends GetPacketStatusDepends<GroupTo
|
||||
override returnSchema = Type.Null();
|
||||
override actionTags = ['核心接口'];
|
||||
|
||||
protected abstract handleGroupTodo(groupId: number, msgSeq: string): Promise<void>;
|
||||
protected abstract handleGroupTodo (groupId: number, msgSeq: string): Promise<void>;
|
||||
|
||||
async _handle (payload: GroupTodoPayload) {
|
||||
const groupId = +payload.group_id;
|
||||
|
||||
@@ -4,6 +4,8 @@ import { Type } from '@sinclair/typebox';
|
||||
|
||||
export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT> {
|
||||
protected override async check (payload: PT): Promise<BaseCheckResult> {
|
||||
const schemaResult = await super.check(payload);
|
||||
if (!schemaResult.valid) return schemaResult;
|
||||
if (!this.core.apis.PacketApi.packetStatus) {
|
||||
return {
|
||||
valid: false,
|
||||
@@ -11,7 +13,22 @@ export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT
|
||||
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
|
||||
};
|
||||
}
|
||||
return await super.check(payload);
|
||||
return { valid: true };
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class PacketSendAvailableDepends<PT, RT> extends OneBotAction<PT, RT> {
|
||||
protected override async check (payload: PT): Promise<BaseCheckResult> {
|
||||
const schemaResult = await super.check(payload);
|
||||
if (!schemaResult.valid) return schemaResult;
|
||||
if (!this.core.apis.PacketApi.available) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'packetBackend发包能力不可用,请参照文档 https://napneko.github.io/config/advanced 和启动日志检查packetBackend状态或进行配置!' +
|
||||
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
|
||||
};
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
import { PacketSendAvailableDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { PacketActionsExamples } from '../example/PacketActionsExamples';
|
||||
@@ -11,7 +11,7 @@ export const SendPokePayloadSchema = Type.Object({
|
||||
});
|
||||
|
||||
export type SendPokePayload = Static<typeof SendPokePayloadSchema>;
|
||||
export class SendPokeBase extends GetPacketStatusDepends<SendPokePayload, void> {
|
||||
export class SendPokeBase extends PacketSendAvailableDepends<SendPokePayload, void> {
|
||||
override payloadSchema = SendPokePayloadSchema;
|
||||
override returnSchema = Type.Null();
|
||||
override actionSummary = '发送戳一戳';
|
||||
|
||||
@@ -28,6 +28,8 @@ 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',
|
||||
@@ -43,6 +45,9 @@ export const ActionName = {
|
||||
GetRkeyEx: 'get_rkey',
|
||||
GetRkeyServer: 'get_rkey_server',
|
||||
SetGroupRemark: 'set_group_remark',
|
||||
SetGroupMemberInvitePolicy: 'set_group_member_invite_policy',
|
||||
SetGroupMemberPermissions: 'set_group_member_permissions',
|
||||
SetGroupNewMemberHistoryVisibility: 'set_group_new_member_history_visibility',
|
||||
NapCat_GetPrivateFileUrl: 'get_private_file_url',
|
||||
ClickInlineKeyboardButton: 'click_inline_keyboard_button',
|
||||
GetUnidirectionalFriendList: 'get_unidirectional_friend_list',
|
||||
@@ -155,10 +160,15 @@ export const ActionName = {
|
||||
_MarkAllMsgAsRead: '_mark_all_as_read',
|
||||
GetProfileLike: 'get_profile_like',
|
||||
FetchCustomFace: 'fetch_custom_face',
|
||||
FetchCustomFaceDetail: 'fetch_custom_face_detail',
|
||||
AddCustomFace: 'add_custom_face',
|
||||
DeleteCustomFace: 'delete_custom_face',
|
||||
SetCustomFaceDesc: 'set_custom_face_desc',
|
||||
FetchEmojiLike: 'fetch_emoji_like',
|
||||
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',
|
||||
@@ -208,4 +218,10 @@ export const ActionName = {
|
||||
ReceiveOnlineFile: 'receive_online_file',
|
||||
RefuseOnlineFile: 'refuse_online_file',
|
||||
CancelOnlineFile: 'cancel_online_file',
|
||||
|
||||
GetGroupSignedList: 'get_group_signed_list',
|
||||
|
||||
// QQ 空间扩展
|
||||
SendQzoneMsg: 'send_qzone_msg',
|
||||
DeleteQzoneMsg: 'delete_qzone_msg',
|
||||
} as const;
|
||||
@@ -2,7 +2,7 @@ import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
|
||||
import { encodeSilk } from '@/napcat-core/helper/audio';
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { calculateFileMD5 } from 'napcat-common/src/file';
|
||||
import { ElementType, NapCatCore, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
|
||||
import { ElementType, NapCatCore, NTVideoType, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
|
||||
import { getFileTypeForSendType } from 'napcat-core/helper/msg';
|
||||
import { imageSizeFallBack } from 'napcat-image-size';
|
||||
import { SendMessageContext } from './msg';
|
||||
@@ -12,6 +12,21 @@ import fsPromises from 'fs/promises';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
|
||||
const videoFormatByExtension: Partial<Record<string, NTVideoType>> = {
|
||||
afs: NTVideoType.VIDEO_FORMAT_AFS,
|
||||
avi: NTVideoType.VIDEO_FORMAT_AVI,
|
||||
mkv: NTVideoType.VIDEO_FORMAT_MKV,
|
||||
mod: NTVideoType.VIDEO_FORMAT_MOD,
|
||||
mov: NTVideoType.VIDEO_FORMAT_MOV,
|
||||
mp4: NTVideoType.VIDEO_FORMAT_MP4,
|
||||
mts: NTVideoType.VIDEO_FORMAT_MTS,
|
||||
rm: NTVideoType.VIDEO_FORMAT_RM,
|
||||
rmvb: NTVideoType.VIDEO_FORMAT_RMVB,
|
||||
ts: NTVideoType.VIDEO_FORMAT_TS,
|
||||
wmv: NTVideoType.VIDEO_FORMAT_WMV,
|
||||
};
|
||||
|
||||
export class OneBotFileApi {
|
||||
obContext: NapCatOneBot11Adapter;
|
||||
core: NapCatCore;
|
||||
@@ -114,9 +129,16 @@ export class OneBotFileApi {
|
||||
}
|
||||
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
|
||||
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
|
||||
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
|
||||
const usePacketVideoMetadata = context.usePacketVideoMetadata === true;
|
||||
const thumbExtension = usePacketVideoMetadata ? 'jpg' : 'png';
|
||||
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.${thumbExtension}`);
|
||||
try {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
|
||||
if (usePacketVideoMetadata) {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
|
||||
} else {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, '');
|
||||
await FFmpegService.extractLegacyVideoThumbnail(filePath, thumbPath);
|
||||
}
|
||||
if (!fs.existsSync(thumbPath)) {
|
||||
this.core.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
|
||||
throw new Error('获取视频缩略图失败');
|
||||
@@ -135,9 +157,18 @@ export class OneBotFileApi {
|
||||
context.deleteAfterSentFiles.push(thumbPath);
|
||||
const thumbSize = (await fsPromises.stat(thumbPath)).size;
|
||||
const thumbMd5 = await calculateFileMD5(thumbPath);
|
||||
context.deleteAfterSentFiles.push(thumbPath);
|
||||
|
||||
const uploadName = (fileName || _fileName).toLocaleLowerCase().endsWith(`.${fileExt.toLocaleLowerCase()}`) ? (fileName || _fileName) : `${fileName || _fileName}.${fileExt}`;
|
||||
const videoMetadata = usePacketVideoMetadata
|
||||
? {
|
||||
fileTime: Math.max(0, Math.round(videoInfo.time)),
|
||||
fileFormat: videoFormatByExtension[fileExt.toLowerCase()] ?? NTVideoType.VIDEO_FORMAT_MP4,
|
||||
fileWidth: videoInfo.width,
|
||||
fileHeight: videoInfo.height,
|
||||
}
|
||||
: {
|
||||
fileTime: videoInfo.time,
|
||||
};
|
||||
return {
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: '',
|
||||
@@ -146,7 +177,7 @@ export class OneBotFileApi {
|
||||
filePath: path,
|
||||
videoMd5: md5,
|
||||
thumbMd5,
|
||||
fileTime: videoInfo.time,
|
||||
...videoMetadata,
|
||||
thumbPath: new Map([[0, thumbPath]]),
|
||||
thumbSize,
|
||||
thumbWidth: videoInfo.width,
|
||||
|
||||
@@ -74,6 +74,7 @@ type Ob11ToRawConverters = {
|
||||
export type SendMessageContext = {
|
||||
deleteAfterSentFiles: string[],
|
||||
peer: Peer;
|
||||
usePacketVideoMetadata?: boolean;
|
||||
};
|
||||
|
||||
export type RecvMessageContext = {
|
||||
@@ -278,7 +279,7 @@ export class OneBotMsgApi {
|
||||
};
|
||||
},
|
||||
|
||||
replyElement: async (element, msg, _, quick_reply) => {
|
||||
replyElement: async (element, msg, _, { quick_reply }) => {
|
||||
const peer = {
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
@@ -310,9 +311,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, msgTime, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
if (quick_reply) {
|
||||
@@ -327,9 +328,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, 1, true, true
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
@@ -341,9 +342,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
@@ -384,6 +385,30 @@ 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 {
|
||||
@@ -859,12 +884,23 @@ export class OneBotMsgApi {
|
||||
// 获取签名服务地址
|
||||
let signUrl = this.obContext.configLoader.configData.musicSignUrl;
|
||||
if (!signUrl) {
|
||||
signUrl = 'https://ss.xingzhige.com/music_card/card';// 感谢思思!已获思思许可 其余地方使用请自行询问
|
||||
signUrl = 'http://106.55.0.102:10087/'; // 首选,yibai音卡签名,已更换稳定签名服务器
|
||||
}
|
||||
|
||||
// 请求签名服务
|
||||
try {
|
||||
const musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
|
||||
let musicJson: string;
|
||||
try {
|
||||
musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
|
||||
} catch {
|
||||
// 首选失败,降级到备选
|
||||
this.core.context.logger.logError('[音乐卡片签名] 首选地址失败,尝试备选地址...');
|
||||
musicJson = await RequestUtil.HttpGetJson<string>(
|
||||
'https://ss.xingzhige.com/music_card/card', // 思思的音卡签名
|
||||
'POST',
|
||||
postData
|
||||
);
|
||||
}
|
||||
return this.ob11ToRawConverters.json({
|
||||
data: { data: musicJson },
|
||||
type: OB11MessageDataType.json,
|
||||
@@ -1129,8 +1165,8 @@ export class OneBotMsgApi {
|
||||
resMsg.sub_type = 'normal';
|
||||
resMsg.group_id = parseInt(msg.peerUin);
|
||||
resMsg.group_name = msg.peerName;
|
||||
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);
|
||||
// getGroupMember 找不到成员时内部已经刷新过一次缓存,这里不用再查第二遍
|
||||
const 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;
|
||||
@@ -1153,9 +1189,12 @@ export class OneBotMsgApi {
|
||||
resMsg.sub_type = 'group';
|
||||
const ret = await this.core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, msg.senderUid);
|
||||
if (ret.result === 0) {
|
||||
// 避免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);
|
||||
// 临时会话的 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);
|
||||
resMsg.sender.nickname = member?.nick ?? member?.cardName ?? '临时会话';
|
||||
resMsg.temp_source = 0;
|
||||
} else {
|
||||
@@ -1219,7 +1258,10 @@ export class OneBotMsgApi {
|
||||
async createSendElements (
|
||||
messageData: OB11MessageData[],
|
||||
peer: Peer,
|
||||
ignoreTypes: OB11MessageDataType[] = []
|
||||
ignoreTypes: OB11MessageDataType[] = [],
|
||||
options: {
|
||||
usePacketVideoMetadata?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
const deleteAfterSentFiles: string[] = [];
|
||||
const callResultList: Array<Promise<SendMessageElement | undefined>> = [];
|
||||
@@ -1236,7 +1278,11 @@ export class OneBotMsgApi {
|
||||
}
|
||||
const callResult = converter(
|
||||
sendMsg,
|
||||
{ peer, deleteAfterSentFiles }
|
||||
{
|
||||
peer,
|
||||
deleteAfterSentFiles,
|
||||
usePacketVideoMetadata: options.usePacketVideoMetadata,
|
||||
}
|
||||
)?.catch(undefined);
|
||||
callResultList.push(callResult);
|
||||
}
|
||||
|
||||
@@ -73,7 +73,12 @@ export function encodeCQCode (data: OB11MessageData) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const text = value?.toString();
|
||||
let text: string | undefined;
|
||||
if (typeof value === 'object' && value?.toString === Object.prototype.toString) {
|
||||
text = JSON.stringify(value);
|
||||
} else {
|
||||
text = value?.toString();
|
||||
}
|
||||
if (text) {
|
||||
result += `,${name}=${CQCodeEscape(text)}`;
|
||||
}
|
||||
|
||||
@@ -135,6 +135,9 @@ 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
+107
-27
@@ -65,6 +65,10 @@ interface ApiListType {
|
||||
QuickActionApi: OneBotQuickActionApi;
|
||||
FileApi: OneBotFileApi;
|
||||
}
|
||||
|
||||
const RECALL_EVENT_DEDUP_MAX_SIZE = 1_000;
|
||||
const RECALL_UPDATE_CLOCK_SKEW_SECONDS = 30;
|
||||
|
||||
// OneBot实现类
|
||||
export class NapCatOneBot11Adapter {
|
||||
readonly core: NapCatCore;
|
||||
@@ -76,6 +80,8 @@ export class NapCatOneBot11Adapter {
|
||||
actions: ActionMap;
|
||||
private readonly bootTime = Date.now() / 1000;
|
||||
recallEventCache = new Map<string, NodeJS.Timeout>();
|
||||
private readonly reportedRecallEventCache = new Map<string, true>();
|
||||
private readonly processingRecallEvents = new Map<string, Promise<void>>();
|
||||
constructor (core: NapCatCore, context: InstanceContext, pathWrapper: NapCatPathWrapper) {
|
||||
this.core = core;
|
||||
this.context = context;
|
||||
@@ -157,10 +163,6 @@ export class NapCatOneBot11Adapter {
|
||||
|
||||
// 创建NetWork服务
|
||||
|
||||
// 注册Plugin 如果需要基于NapCat进行快速开发
|
||||
// this.networkManager.registerAdapter(
|
||||
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
|
||||
// );
|
||||
// 检查插件目录是否存在,不存在则不加载插件管理器
|
||||
if (existsSync(this.context.pathWrapper.pluginPath)) {
|
||||
this.context.logger.log('[Plugins] 插件目录存在,开始加载插件');
|
||||
@@ -388,36 +390,34 @@ export class NapCatOneBot11Adapter {
|
||||
this.context.logger.logError('处理发送消息失败', error);
|
||||
}
|
||||
};
|
||||
|
||||
msgListener.onMsgInfoListUpdate = async (msgList: RawMessage[]) => {
|
||||
for (const msg of msgList) {
|
||||
const element = this.getRecallElement(msg);
|
||||
if (element && this.isCurrentRecallUpdate(msg)) {
|
||||
// The gray-tip update is authoritative; the recall callback's sequence query can return a newer message.
|
||||
await this.handleRecallMessage(msg, element);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
msgListener.onMsgRecall = async (chatType: ChatType, uid: string, msgSeq: string) => {
|
||||
const peer: Peer = {
|
||||
chatType,
|
||||
peerUid: uid,
|
||||
guildId: '',
|
||||
};
|
||||
let msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList.find(e => e.msgType === NTMsgType.KMSGTYPEGRAYTIPS);
|
||||
const element = msg?.elements.find(e => !!e.grayTipElement?.revokeElement);
|
||||
if (msg && element?.grayTipElement?.revokeElement.isSelfOperate) {
|
||||
const isSelfDevice = this.recallEventCache.has(msg.msgId);
|
||||
if (isSelfDevice) {
|
||||
await this.core.eventWrapper.registerListen('NodeIKernelMsgListener/onMsgRecall',
|
||||
(chatType: ChatType, uid: string, msgSeq: string) => {
|
||||
return chatType === msg?.chatType && uid === msg?.peerUid && msgSeq === msg?.msgSeq;
|
||||
}
|
||||
).catch(() => {
|
||||
msg = undefined;
|
||||
this.context.logger.logDebug('自操作消息撤回事件');
|
||||
});
|
||||
}
|
||||
}
|
||||
if (msg && element) {
|
||||
const recallEvent = await this.emitRecallMsg(msg, element);
|
||||
try {
|
||||
if (recallEvent) {
|
||||
await this.networkManager.emitEvent(recallEvent);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('处理消息撤回失败', e);
|
||||
try {
|
||||
const msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList
|
||||
.find(message => this.getRecallElement(message));
|
||||
const element = msg && this.getRecallElement(msg);
|
||||
if (msg && element) {
|
||||
await this.handleRecallMessage(msg, element);
|
||||
} else {
|
||||
this.context.logger.logDebug(`撤回回调暂未查询到灰条消息,等待消息更新: ${chatType}/${uid}/${msgSeq}`);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('查询撤回消息失败', e);
|
||||
}
|
||||
};
|
||||
msgListener.onKickedOffLine = async (kick) => {
|
||||
@@ -666,6 +666,86 @@ export class NapCatOneBot11Adapter {
|
||||
}
|
||||
}
|
||||
|
||||
private getRecallElement (message: RawMessage): MessageElement | undefined {
|
||||
if (message.msgType !== NTMsgType.KMSGTYPEGRAYTIPS) {
|
||||
return undefined;
|
||||
}
|
||||
return message.elements.find(element => !!element.grayTipElement?.revokeElement);
|
||||
}
|
||||
|
||||
private isCurrentRecallUpdate (message: RawMessage): boolean {
|
||||
const recallTime = Number(message.recallTime);
|
||||
if (!Number.isFinite(recallTime) || recallTime <= 0) {
|
||||
return false;
|
||||
}
|
||||
const recallTimeInSeconds = recallTime > 10_000_000_000 ? recallTime / 1000 : recallTime;
|
||||
return recallTimeInSeconds >= this.bootTime - RECALL_UPDATE_CLOCK_SKEW_SECONDS;
|
||||
}
|
||||
|
||||
private getRecallEventKey (message: RawMessage): string {
|
||||
return `${message.chatType}/${message.peerUid}/${message.msgId}`;
|
||||
}
|
||||
|
||||
private hasReportedRecallEvent (key: string): boolean {
|
||||
return this.reportedRecallEventCache.has(key);
|
||||
}
|
||||
|
||||
private markRecallEventReported (key: string): void {
|
||||
this.reportedRecallEventCache.delete(key);
|
||||
this.reportedRecallEventCache.set(key, true);
|
||||
while (this.reportedRecallEventCache.size > RECALL_EVENT_DEDUP_MAX_SIZE) {
|
||||
const oldestKey = this.reportedRecallEventCache.keys().next().value;
|
||||
if (oldestKey === undefined) break;
|
||||
this.reportedRecallEventCache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleRecallMessage (message: RawMessage, element: MessageElement): Promise<void> {
|
||||
const revokeElement = element.grayTipElement?.revokeElement;
|
||||
if (!revokeElement) return;
|
||||
|
||||
if (revokeElement.isSelfOperate) {
|
||||
const selfRecallTimeout = this.recallEventCache.get(message.msgId);
|
||||
if (selfRecallTimeout) {
|
||||
clearTimeout(selfRecallTimeout);
|
||||
this.recallEventCache.delete(message.msgId);
|
||||
this.context.logger.logDebug('自操作消息撤回事件');
|
||||
}
|
||||
}
|
||||
|
||||
const key = this.getRecallEventKey(message);
|
||||
while (!this.hasReportedRecallEvent(key)) {
|
||||
const processing = this.processingRecallEvents.get(key);
|
||||
if (processing) {
|
||||
// A duplicate callback becomes the retry path if the in-flight report fails.
|
||||
await processing;
|
||||
continue;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
const recallEvent = await this.emitRecallMsg(message, element);
|
||||
if (recallEvent) {
|
||||
await this.networkManager.emitEvent(recallEvent);
|
||||
this.markRecallEventReported(key);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('处理消息撤回失败', e);
|
||||
}
|
||||
})();
|
||||
|
||||
this.processingRecallEvents.set(key, task);
|
||||
try {
|
||||
await task;
|
||||
} finally {
|
||||
if (this.processingRecallEvents.get(key) === task) {
|
||||
this.processingRecallEvents.delete(key);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async emitRecallMsg (message: RawMessage, element: MessageElement) {
|
||||
const peer: Peer = { chatType: message.chatType, peerUid: message.peerUid, guildId: '' };
|
||||
const oriMessageId = MessageUnique.getShortIdByMsgId(message.msgId) ?? MessageUnique.createUniqueMsgId(peer, message.msgId);
|
||||
|
||||
@@ -250,7 +250,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
|
||||
|
||||
async httpApiRequest (req: Request, res: Response, request_sse: boolean = false) {
|
||||
let payload = req.body;
|
||||
if (req.method === 'get') {
|
||||
if (req.method === 'GET') {
|
||||
payload = req.query;
|
||||
} else if (req.query) {
|
||||
payload = { ...req.body, ...req.query };
|
||||
@@ -307,6 +307,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
|
||||
async reload (newConfig: HttpServerConfig) {
|
||||
const wasEnabled = this.isEnable;
|
||||
const oldPort = this.config.port;
|
||||
const oldHost = this.config.host;
|
||||
const oldEnableWebsocket = this.config.enableWebsocket;
|
||||
this.config = newConfig;
|
||||
|
||||
@@ -318,7 +319,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
|
||||
return OB11NetworkReloadType.NetWorkClose;
|
||||
}
|
||||
|
||||
if (oldPort !== newConfig.port || oldEnableWebsocket !== newConfig.enableWebsocket) {
|
||||
if (oldPort !== newConfig.port || oldHost !== newConfig.host || oldEnableWebsocket !== newConfig.enableWebsocket) {
|
||||
this.close();
|
||||
if (newConfig.enable) {
|
||||
this.open();
|
||||
|
||||
@@ -1,378 +0,0 @@
|
||||
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
|
||||
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
|
||||
import { NapCatCore } from 'napcat-core';
|
||||
import { PluginConfig } from '../config/config';
|
||||
import { ActionMap } from '../action';
|
||||
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export interface PluginPackageJson {
|
||||
name?: string;
|
||||
plugin?: string;
|
||||
version?: string;
|
||||
main?: string;
|
||||
}
|
||||
|
||||
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
|
||||
plugin_init: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
plugin_onmessage?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: OB11Message, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
plugin_onevent?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: T, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
plugin_cleanup?: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface LoadedPlugin {
|
||||
name: string;
|
||||
version?: string;
|
||||
pluginPath: string;
|
||||
entryPath: string;
|
||||
packageJson?: PluginPackageJson;
|
||||
module: PluginModule;
|
||||
}
|
||||
|
||||
export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
private readonly pluginPath: string;
|
||||
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
|
||||
declare config: PluginConfig;
|
||||
override get isActive (): boolean {
|
||||
return this.isEnable && this.loadedPlugins.size > 0;
|
||||
}
|
||||
|
||||
constructor (
|
||||
name: string, core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap
|
||||
) {
|
||||
const config = {
|
||||
name,
|
||||
messagePostFormat: 'array',
|
||||
reportSelfMessage: true,
|
||||
enable: true,
|
||||
debug: true,
|
||||
};
|
||||
super(name, config, core, obContext, actions);
|
||||
this.pluginPath = this.core.context.pathWrapper.pluginPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描并加载插件
|
||||
*/
|
||||
private async loadPlugins (): Promise<void> {
|
||||
try {
|
||||
// 确保插件目录存在
|
||||
if (!fs.existsSync(this.pluginPath)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin directory does not exist: ${this.pluginPath}`);
|
||||
fs.mkdirSync(this.pluginPath, { recursive: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
|
||||
|
||||
// 扫描文件和目录
|
||||
for (const item of items) {
|
||||
if (item.isFile()) {
|
||||
// 处理单文件插件
|
||||
await this.loadFilePlugin(item.name);
|
||||
} else if (item.isDirectory()) {
|
||||
// 处理目录插件
|
||||
await this.loadDirectoryPlugin(item.name);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.log(`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`);
|
||||
} catch (error) {
|
||||
this.logger.logError('[Plugin Adapter] Error loading plugins:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载单文件插件 (.mjs, .js)
|
||||
*/
|
||||
private async loadFilePlugin (filename: string): Promise<void> {
|
||||
// 只处理支持的文件类型
|
||||
if (!this.isSupportedFile(filename)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(this.pluginPath, filename);
|
||||
const pluginName = path.parse(filename).name;
|
||||
|
||||
try {
|
||||
const module = await this.importModule(filePath);
|
||||
if (!this.isValidPluginModule(module)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const plugin: LoadedPlugin = {
|
||||
name: pluginName,
|
||||
pluginPath: this.pluginPath,
|
||||
entryPath: filePath,
|
||||
module,
|
||||
};
|
||||
|
||||
await this.registerPlugin(plugin);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error loading file plugin ${filename}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载目录插件
|
||||
*/
|
||||
private async loadDirectoryPlugin (dirname: string): Promise<void> {
|
||||
const pluginDir = path.join(this.pluginPath, dirname);
|
||||
|
||||
try {
|
||||
// 尝试读取 package.json
|
||||
let packageJson: PluginPackageJson | undefined;
|
||||
const packageJsonPath = path.join(pluginDir, 'package.json');
|
||||
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
try {
|
||||
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
|
||||
packageJson = JSON.parse(packageContent);
|
||||
} catch (error) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Invalid package.json in ${dirname}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 确定入口文件
|
||||
const entryFile = this.findEntryFile(pluginDir, packageJson);
|
||||
if (!entryFile) {
|
||||
this.logger.logWarn(`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const entryPath = path.join(pluginDir, entryFile);
|
||||
const module = await this.importModule(entryPath);
|
||||
|
||||
if (!this.isValidPluginModule(module)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`);
|
||||
return;
|
||||
}
|
||||
|
||||
const plugin: LoadedPlugin = {
|
||||
name: packageJson?.name || dirname,
|
||||
version: packageJson?.version,
|
||||
pluginPath: pluginDir,
|
||||
entryPath,
|
||||
packageJson,
|
||||
module,
|
||||
};
|
||||
|
||||
await this.registerPlugin(plugin);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error loading directory plugin ${dirname}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找插件目录的入口文件
|
||||
*/
|
||||
private findEntryFile (pluginDir: string, packageJson?: PluginPackageJson): string | null {
|
||||
// 优先级:package.json main > 默认文件名
|
||||
const possibleEntries = [
|
||||
packageJson?.main,
|
||||
'index.mjs',
|
||||
'index.js',
|
||||
'main.mjs',
|
||||
'main.js',
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
for (const entry of possibleEntries) {
|
||||
const entryPath = path.join(pluginDir, entry);
|
||||
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为支持的文件类型
|
||||
*/
|
||||
private isSupportedFile (filename: string): boolean {
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
return ['.mjs', '.js'].includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态导入模块
|
||||
*/
|
||||
private async importModule (filePath: string): Promise<any> {
|
||||
const fileUrl = `file://${filePath.replace(/\\/g, '/')}`;
|
||||
return await import(fileUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查模块是否为有效的插件模块
|
||||
*/
|
||||
private isValidPluginModule (module: any): module is PluginModule {
|
||||
return module && typeof module.plugin_init === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册插件
|
||||
*/
|
||||
private async registerPlugin (plugin: LoadedPlugin): Promise<void> {
|
||||
// 检查名称冲突
|
||||
if (this.loadedPlugins.has(plugin.name)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.loadedPlugins.set(plugin.name, plugin);
|
||||
this.logger.log(`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''}`);
|
||||
|
||||
// 调用插件初始化方法(必须存在)
|
||||
try {
|
||||
await plugin.module.plugin_init(this.core, this.obContext, this.actions, this);
|
||||
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error initializing plugin ${plugin.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载插件
|
||||
*/
|
||||
private async unloadPlugin (pluginName: string): Promise<void> {
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
if (!plugin) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 调用插件清理方法
|
||||
if (typeof plugin.module.plugin_cleanup === 'function') {
|
||||
try {
|
||||
await plugin.module.plugin_cleanup(this.core, this.obContext, this.actions, this);
|
||||
this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error cleaning up plugin ${pluginName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
this.loadedPlugins.delete(pluginName);
|
||||
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
|
||||
}
|
||||
|
||||
async onEvent<T extends OB11EmitEventContent> (event: T) {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 遍历所有已加载的插件,调用它们的事件处理方法
|
||||
for (const [, plugin] of this.loadedPlugins) {
|
||||
this.callPluginEventHandler(plugin, event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用插件的事件处理方法
|
||||
*/
|
||||
private async callPluginEventHandler (plugin: LoadedPlugin, event: OB11EmitEventContent): Promise<void> {
|
||||
try {
|
||||
// 优先使用 plugin_onevent 方法
|
||||
if (typeof plugin.module.plugin_onevent === 'function') {
|
||||
await plugin.module.plugin_onevent(this.name, this.core, this.obContext, event, this.actions, this);
|
||||
}
|
||||
|
||||
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
|
||||
if ((event as any).message_type && typeof plugin.module.plugin_onmessage === 'function') {
|
||||
await plugin.module.plugin_onmessage(this.name, this.core, this.obContext, event as OB11Message, this.actions, this);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
async open () {
|
||||
if (this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[Plugin Adapter] Opening plugin adapter...');
|
||||
this.isEnable = true;
|
||||
|
||||
// 加载所有插件
|
||||
await this.loadPlugins();
|
||||
|
||||
this.logger.log(`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`);
|
||||
}
|
||||
|
||||
async close () {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[Plugin Adapter] Closing plugin adapter...');
|
||||
this.isEnable = false;
|
||||
|
||||
// 卸载所有插件
|
||||
const pluginNames = Array.from(this.loadedPlugins.keys());
|
||||
for (const pluginName of pluginNames) {
|
||||
await this.unloadPlugin(pluginName);
|
||||
}
|
||||
|
||||
this.logger.log('[Plugin Adapter] Plugin adapter closed');
|
||||
}
|
||||
|
||||
async reload () {
|
||||
this.logger.log('[Plugin Adapter] Reloading plugin adapter...');
|
||||
|
||||
// 先关闭然后重新打开
|
||||
await this.close();
|
||||
await this.open();
|
||||
|
||||
this.logger.log('[Plugin Adapter] Plugin adapter reloaded');
|
||||
return OB11NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的插件列表
|
||||
*/
|
||||
public getLoadedPlugins (): LoadedPlugin[] {
|
||||
return Array.from(this.loadedPlugins.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件信息
|
||||
*/
|
||||
public getPluginInfo (pluginName: string): LoadedPlugin | undefined {
|
||||
return this.loadedPlugins.get(pluginName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载指定插件
|
||||
*/
|
||||
public async reloadPlugin (pluginName: string): Promise<boolean> {
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
if (!plugin) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginName} not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 卸载插件
|
||||
await this.unloadPlugin(pluginName);
|
||||
|
||||
// 重新加载插件
|
||||
const isDirectory = fs.statSync(plugin.pluginPath).isDirectory() &&
|
||||
plugin.pluginPath !== this.pluginPath;
|
||||
|
||||
if (isDirectory) {
|
||||
const dirname = path.basename(plugin.pluginPath);
|
||||
await this.loadDirectoryPlugin(dirname);
|
||||
} else {
|
||||
const filename = path.basename(plugin.entryPath);
|
||||
await this.loadFilePlugin(filename);
|
||||
}
|
||||
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error reloading plugin ${pluginName}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,31 @@ import {
|
||||
} from './types';
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
/** 允许加载的官方插件 ID 白名单。不在表内的插件一律拒绝加载。 */
|
||||
const OFFICIAL_PLUGIN_IDS = new Set<string>([
|
||||
'napcat-plugin-builtin',
|
||||
'napcat-plugin-cleaner',
|
||||
'napcat-plugin-ssqq',
|
||||
'napcat-plugin-qce',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 敏感词表:插件源码命中(黑灰产 / 支付发卡相关)即拒绝加载。
|
||||
* 仅作启发式威慑,混淆/编码可绕过,并非唯一防线。
|
||||
*/
|
||||
const SENSITIVE_KEYWORDS: string[] = [
|
||||
'发卡', '卡密', '卡网', '自动发卡', '寄售', '代刷', '刷单', '跑分',
|
||||
'四件套', '洗钱', '黑产', '灰产', '博彩', '赌博', '菠菜', '涉黄',
|
||||
'色情', '收款码', '代付', '担保交易', '第三方支付', 'USDT',
|
||||
];
|
||||
|
||||
/** 纳入敏感词检测的源码扩展名 */
|
||||
const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts']);
|
||||
/** 跳过敏感词扫描的目录名 */
|
||||
const SCAN_SKIP_DIRS = new Set(['data', 'node_modules', '.git']);
|
||||
/** 单文件扫描大小上限,避免超大文件拖慢启动 */
|
||||
const SCAN_MAX_FILE_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 插件加载器
|
||||
* 负责扫描、加载和导入插件模块
|
||||
@@ -121,6 +146,15 @@ export class PluginLoader {
|
||||
// 获取插件 ID(包名或目录名)
|
||||
const pluginId = packageJson?.name || dirname;
|
||||
|
||||
// 官方白名单 + 敏感词校验:被拒绝的插件视为不可见,
|
||||
// 不入列表、不加载、更不会被动态导入执行。
|
||||
// 该检查置于此处统一拦截 scanPlugins 与 rescanPlugin(安装/重载)两条路径。
|
||||
const rejectReason = this.getRejectReason(pluginId, pluginDir);
|
||||
if (rejectReason) {
|
||||
this.logger.logWarn(`[PluginLoader] Rejected ${pluginId} (${dirname}): ${rejectReason}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 确定入口文件
|
||||
const entryFile = this.findEntryFile(pluginDir, packageJson);
|
||||
const entryPath = entryFile ? path.join(pluginDir, entryFile) : undefined;
|
||||
@@ -184,7 +218,12 @@ export class PluginLoader {
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
for (const entry of possibleEntries) {
|
||||
const entryPath = path.join(pluginDir, entry);
|
||||
const root = path.resolve(pluginDir);
|
||||
const entryPath = path.resolve(pluginDir, entry);
|
||||
// 拒绝 package.json main 指向插件目录之外(防路径穿越)
|
||||
if (entryPath !== root && !entryPath.startsWith(root + path.sep)) {
|
||||
continue;
|
||||
}
|
||||
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
|
||||
return entry;
|
||||
}
|
||||
@@ -193,6 +232,75 @@ export class PluginLoader {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 是否为白名单内的官方插件 */
|
||||
isOfficialPlugin (pluginId: string): boolean {
|
||||
return OFFICIAL_PLUGIN_IDS.has(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断插件是否应被拒绝(非官方 / 命中敏感词)。
|
||||
* @returns 拒绝原因;通过校验返回 null
|
||||
*/
|
||||
private getRejectReason (pluginId: string, pluginDir: string): string | null {
|
||||
const hit = this.scanSensitiveWords(pluginDir);
|
||||
if (this.isOfficialPlugin(pluginId)) {
|
||||
return null;
|
||||
}
|
||||
if (hit) {
|
||||
return `sensitive keyword "${hit}"`;
|
||||
}
|
||||
return 'not in official plugin whitelist';
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归扫描插件目录内源码是否命中敏感词(黑灰产 / 支付发卡)。
|
||||
* @returns 命中的敏感词;未命中返回 null
|
||||
*/
|
||||
scanSensitiveWords (pluginDir: string): string | null {
|
||||
const visit = (dir: string): string | null => {
|
||||
let items: fs.Dirent[];
|
||||
try {
|
||||
items = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.isDirectory()) {
|
||||
if (SCAN_SKIP_DIRS.has(item.name)) {
|
||||
continue;
|
||||
}
|
||||
const hit = visit(path.join(dir, item.name));
|
||||
if (hit) {
|
||||
return hit;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!item.isFile()) {
|
||||
continue;
|
||||
}
|
||||
if (!SCAN_EXTS.has(path.extname(item.name).toLowerCase())) {
|
||||
continue;
|
||||
}
|
||||
const filePath = path.join(dir, item.name);
|
||||
try {
|
||||
if (fs.statSync(filePath).size > SCAN_MAX_FILE_BYTES) {
|
||||
continue;
|
||||
}
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
for (const word of SENSITIVE_KEYWORDS) {
|
||||
if (content.includes(word)) {
|
||||
return word;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 读取失败忽略该文件
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
return visit(pluginDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态导入模块
|
||||
*/
|
||||
|
||||
@@ -1,529 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { ActionMap } from '@/napcat-onebot/action';
|
||||
import { NapCatCore } from 'napcat-core';
|
||||
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
|
||||
import { OB11EmitEventContent, OB11NetworkReloadType } from '@/napcat-onebot/network/index';
|
||||
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
|
||||
import { PluginConfig } from '@/napcat-onebot/config/config';
|
||||
import { NapCatConfig } from './config';
|
||||
import { PluginLoader } from './loader';
|
||||
import { PluginRouterRegistryImpl } from './router-registry';
|
||||
import {
|
||||
PluginEntry,
|
||||
PluginLogger,
|
||||
PluginStatusConfig,
|
||||
NapCatPluginContext,
|
||||
IPluginManager,
|
||||
} from './types';
|
||||
|
||||
export class OB11PluginManager extends IOB11NetworkAdapter<PluginConfig> implements IPluginManager {
|
||||
private readonly pluginPath: string;
|
||||
private readonly configPath: string;
|
||||
private readonly loader: PluginLoader;
|
||||
|
||||
/** 插件注册表: ID -> 插件条目 */
|
||||
private plugins: Map<string, PluginEntry> = new Map();
|
||||
|
||||
/** 插件路由注册表: pluginId -> PluginRouterRegistry */
|
||||
private pluginRouters: Map<string, PluginRouterRegistryImpl> = new Map();
|
||||
|
||||
declare config: PluginConfig;
|
||||
public NapCatConfig = NapCatConfig;
|
||||
|
||||
override get isActive (): boolean {
|
||||
return this.isEnable && this.getLoadedPlugins().length > 0;
|
||||
}
|
||||
|
||||
constructor (
|
||||
name: string,
|
||||
core: NapCatCore,
|
||||
obContext: NapCatOneBot11Adapter,
|
||||
actions: ActionMap
|
||||
) {
|
||||
const config = {
|
||||
name,
|
||||
messagePostFormat: 'array',
|
||||
reportSelfMessage: true,
|
||||
enable: true,
|
||||
debug: true,
|
||||
};
|
||||
super(name, config, core, obContext, actions);
|
||||
this.pluginPath = this.core.context.pathWrapper.pluginPath;
|
||||
this.configPath = path.join(this.core.context.pathWrapper.configPath, 'plugins.json');
|
||||
this.loader = new PluginLoader(this.pluginPath, this.configPath, this.logger);
|
||||
}
|
||||
|
||||
// ==================== 插件状态配置 ====================
|
||||
|
||||
public getPluginConfig (): PluginStatusConfig {
|
||||
return this.loader.loadPluginStatusConfig();
|
||||
}
|
||||
|
||||
private savePluginConfig (config: PluginStatusConfig): void {
|
||||
this.loader.savePluginStatusConfig(config);
|
||||
}
|
||||
|
||||
// ==================== 插件扫描与加载 ====================
|
||||
|
||||
/**
|
||||
* 扫描并加载所有插件
|
||||
*/
|
||||
private async scanAndLoadPlugins (): Promise<void> {
|
||||
// 扫描所有插件目录
|
||||
const entries = await this.loader.scanPlugins();
|
||||
|
||||
// 清空现有注册表
|
||||
this.plugins.clear();
|
||||
|
||||
// 注册所有插件条目
|
||||
for (const entry of entries) {
|
||||
this.plugins.set(entry.id, entry);
|
||||
}
|
||||
|
||||
this.logger.log(`[PluginManager] Scanned ${this.plugins.size} plugins`);
|
||||
|
||||
// 加载启用的插件
|
||||
for (const entry of this.plugins.values()) {
|
||||
if (entry.enable && entry.runtime.status !== 'error') {
|
||||
await this.loadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
const loadedCount = this.getLoadedPlugins().length;
|
||||
this.logger.log(`[PluginManager] Loaded ${loadedCount} plugins`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载单个插件
|
||||
*/
|
||||
private async loadPlugin (entry: PluginEntry): Promise<boolean> {
|
||||
if (entry.loaded) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (entry.runtime.status === 'error') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 加载模块
|
||||
const module = await this.loader.loadPluginModule(entry);
|
||||
if (!module) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 创建上下文
|
||||
const context = this.createPluginContext(entry);
|
||||
|
||||
// 初始化插件
|
||||
try {
|
||||
await module.plugin_init(context);
|
||||
|
||||
entry.loaded = true;
|
||||
entry.runtime = {
|
||||
status: 'loaded',
|
||||
module,
|
||||
context,
|
||||
};
|
||||
|
||||
this.logger.log(`[PluginManager] Initialized plugin: ${entry.id}${entry.version ? ` v${entry.version}` : ''}`);
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
entry.loaded = false;
|
||||
entry.runtime = {
|
||||
status: 'error',
|
||||
error: error.message || 'Initialization failed',
|
||||
};
|
||||
|
||||
this.logger.logError(`[PluginManager] Error initializing plugin ${entry.id}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载单个插件
|
||||
*/
|
||||
private async unloadPlugin (entry: PluginEntry): Promise<void> {
|
||||
if (!entry.loaded || entry.runtime.status !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
const { module, context } = entry.runtime;
|
||||
|
||||
// 调用清理方法
|
||||
if (module && context && typeof module.plugin_cleanup === 'function') {
|
||||
try {
|
||||
await module.plugin_cleanup(context);
|
||||
this.logger.log(`[PluginManager] Cleaned up plugin: ${entry.id}`);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[PluginManager] Error cleaning up plugin ${entry.id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
entry.loaded = false;
|
||||
entry.runtime = {
|
||||
status: 'unloaded',
|
||||
};
|
||||
|
||||
this.logger.log(`[PluginManager] Unloaded plugin: ${entry.id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建插件上下文
|
||||
*/
|
||||
private createPluginContext (entry: PluginEntry): NapCatPluginContext {
|
||||
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', entry.id);
|
||||
const configPath = path.join(dataPath, 'config.json');
|
||||
|
||||
// 确保插件配置目录存在
|
||||
if (!fs.existsSync(dataPath)) {
|
||||
fs.mkdirSync(dataPath, { recursive: true });
|
||||
}
|
||||
|
||||
// 创建插件专用日志器
|
||||
const pluginPrefix = `[Plugin: ${entry.id}]`;
|
||||
const coreLogger = this.logger;
|
||||
const pluginLogger: PluginLogger = {
|
||||
log: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
|
||||
debug: (...args: any[]) => coreLogger.logDebug(pluginPrefix, ...args),
|
||||
info: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
|
||||
warn: (...args: any[]) => coreLogger.logWarn(pluginPrefix, ...args),
|
||||
error: (...args: any[]) => coreLogger.logError(pluginPrefix, ...args),
|
||||
};
|
||||
|
||||
// 创建或获取插件路由注册器
|
||||
let router = this.pluginRouters.get(entry.id);
|
||||
if (!router) {
|
||||
router = new PluginRouterRegistryImpl(entry.id, entry.pluginPath);
|
||||
this.pluginRouters.set(entry.id, router);
|
||||
}
|
||||
|
||||
// 创建获取其他插件导出的方法
|
||||
const getPluginExports = <T = any> (pluginId: string): T | undefined => {
|
||||
const targetEntry = this.plugins.get(pluginId);
|
||||
if (!targetEntry || !targetEntry.loaded || targetEntry.runtime.status !== 'loaded') {
|
||||
return undefined;
|
||||
}
|
||||
return targetEntry.runtime.module as T;
|
||||
};
|
||||
|
||||
return {
|
||||
core: this.core,
|
||||
oneBot: this.obContext,
|
||||
actions: this.actions,
|
||||
pluginName: entry.id,
|
||||
pluginPath: entry.pluginPath,
|
||||
dataPath,
|
||||
configPath,
|
||||
NapCatConfig,
|
||||
adapterName: this.name,
|
||||
pluginManager: this,
|
||||
logger: pluginLogger,
|
||||
router,
|
||||
getPluginExports,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 公共 API ====================
|
||||
|
||||
/**
|
||||
* 获取插件目录路径
|
||||
*/
|
||||
public getPluginPath (): string {
|
||||
return this.pluginPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有插件条目
|
||||
*/
|
||||
public getAllPlugins (): PluginEntry[] {
|
||||
return Array.from(this.plugins.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的插件列表
|
||||
*/
|
||||
public getLoadedPlugins (): PluginEntry[] {
|
||||
return Array.from(this.plugins.values()).filter(p => p.loaded);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 ID 获取插件信息
|
||||
*/
|
||||
public getPluginInfo (pluginId: string): PluginEntry | undefined {
|
||||
return this.plugins.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置插件状态(启用/禁用)
|
||||
*/
|
||||
public async setPluginStatus (pluginId: string, enable: boolean): Promise<void> {
|
||||
const config = this.getPluginConfig();
|
||||
config[pluginId] = enable;
|
||||
this.savePluginConfig(config);
|
||||
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (entry) {
|
||||
entry.enable = enable;
|
||||
|
||||
if (enable && !entry.loaded) {
|
||||
// 启用插件
|
||||
await this.loadPlugin(entry);
|
||||
} else if (!enable && entry.loaded) {
|
||||
// 禁用插件
|
||||
await this.unloadPlugin(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 ID 加载插件
|
||||
*/
|
||||
public async loadPluginById (pluginId: string): Promise<boolean> {
|
||||
let entry = this.plugins.get(pluginId);
|
||||
|
||||
if (!entry) {
|
||||
// 尝试查找并扫描
|
||||
const dirname = this.loader.findPluginDirById(pluginId);
|
||||
if (!dirname) {
|
||||
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found in filesystem`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const newEntry = this.loader.rescanPlugin(dirname);
|
||||
if (!newEntry) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.plugins.set(newEntry.id, newEntry);
|
||||
entry = newEntry;
|
||||
}
|
||||
|
||||
if (!entry.enable) {
|
||||
this.logger.log(`[PluginManager] Skipping loading disabled plugin: ${pluginId}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
return await this.loadPlugin(entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载插件(仅从内存卸载)
|
||||
*/
|
||||
public async unregisterPlugin (pluginId: string): Promise<void> {
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (entry) {
|
||||
await this.unloadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载并删除插件
|
||||
*/
|
||||
public async uninstallPlugin (pluginId: string, cleanData: boolean = false): Promise<void> {
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (!entry) {
|
||||
throw new Error(`Plugin ${pluginId} not found`);
|
||||
}
|
||||
|
||||
const pluginPath = entry.pluginPath;
|
||||
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
|
||||
|
||||
// 先卸载插件
|
||||
await this.unloadPlugin(entry);
|
||||
|
||||
// 从注册表移除
|
||||
this.plugins.delete(pluginId);
|
||||
|
||||
// 删除插件目录
|
||||
if (fs.existsSync(pluginPath)) {
|
||||
fs.rmSync(pluginPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// 清理插件配置数据
|
||||
if (cleanData && fs.existsSync(dataPath)) {
|
||||
fs.rmSync(dataPath, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载指定插件
|
||||
*/
|
||||
public async reloadPlugin (pluginId: string): Promise<boolean> {
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (!entry) {
|
||||
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 卸载插件
|
||||
await this.unloadPlugin(entry);
|
||||
|
||||
// 重新扫描
|
||||
const newEntry = this.loader.rescanPlugin(entry.fileId);
|
||||
if (!newEntry) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 更新注册表
|
||||
this.plugins.set(newEntry.id, newEntry);
|
||||
|
||||
// 重新加载
|
||||
if (newEntry.enable) {
|
||||
await this.loadPlugin(newEntry);
|
||||
}
|
||||
|
||||
this.logger.log(`[PluginManager] Plugin ${pluginId} reloaded successfully`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.logError(`[PluginManager] Error reloading plugin ${pluginId}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载目录插件(用于新安装的插件)
|
||||
*/
|
||||
public async loadDirectoryPlugin (dirname: string): Promise<void> {
|
||||
const entry = this.loader.rescanPlugin(dirname);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否已存在
|
||||
if (this.plugins.has(entry.id)) {
|
||||
this.logger.logWarn(`[PluginManager] Plugin ${entry.id} already exists`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.plugins.set(entry.id, entry);
|
||||
|
||||
if (entry.enable && entry.runtime.status !== 'error') {
|
||||
await this.loadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件数据目录路径
|
||||
*/
|
||||
public getPluginDataPath (pluginId: string): string {
|
||||
return path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件配置文件路径
|
||||
*/
|
||||
public getPluginConfigPath (pluginId: string): string {
|
||||
return path.join(this.getPluginDataPath(pluginId), 'config.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件路由注册器
|
||||
*/
|
||||
public getPluginRouter (pluginId: string): PluginRouterRegistryImpl | undefined {
|
||||
return this.pluginRouters.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有插件路由注册器
|
||||
*/
|
||||
public getAllPluginRouters (): Map<string, PluginRouterRegistryImpl> {
|
||||
return this.pluginRouters;
|
||||
}
|
||||
|
||||
// ==================== 事件处理 ====================
|
||||
|
||||
async onEvent<T extends OB11EmitEventContent> (event: T): Promise<void> {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.allSettled(
|
||||
this.getLoadedPlugins().map((entry) =>
|
||||
this.callPluginEventHandler(entry, event)
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.logError('[PluginManager] Error handling event:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用插件的事件处理方法
|
||||
*/
|
||||
private async callPluginEventHandler (
|
||||
entry: PluginEntry,
|
||||
event: OB11EmitEventContent
|
||||
): Promise<void> {
|
||||
if (entry.runtime.status !== 'loaded' || !entry.runtime.module || !entry.runtime.context) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { module, context } = entry.runtime;
|
||||
|
||||
try {
|
||||
// 优先使用 plugin_onevent 方法
|
||||
if (typeof module.plugin_onevent === 'function') {
|
||||
await module.plugin_onevent(context, event);
|
||||
}
|
||||
|
||||
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
|
||||
if (
|
||||
(event as any).message_type &&
|
||||
typeof module.plugin_onmessage === 'function'
|
||||
) {
|
||||
await module.plugin_onmessage(context, event as OB11Message);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.logError(`[PluginManager] Error calling plugin ${entry.id} event handler:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 生命周期 ====================
|
||||
|
||||
async open (): Promise<void> {
|
||||
if (this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[PluginManager] Opening plugin manager...');
|
||||
this.isEnable = true;
|
||||
|
||||
// 扫描并加载所有插件
|
||||
await this.scanAndLoadPlugins();
|
||||
|
||||
this.logger.log(`[PluginManager] Plugin manager opened with ${this.getLoadedPlugins().length} plugins loaded`);
|
||||
}
|
||||
|
||||
async close (): Promise<void> {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[PluginManager] Closing plugin manager...');
|
||||
this.isEnable = false;
|
||||
|
||||
// 卸载所有已加载的插件
|
||||
for (const entry of this.plugins.values()) {
|
||||
if (entry.loaded) {
|
||||
await this.unloadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.log('[PluginManager] Plugin manager closed');
|
||||
}
|
||||
|
||||
async reload (): Promise<OB11NetworkReloadType> {
|
||||
this.logger.log('[PluginManager] Reloading plugin manager...');
|
||||
|
||||
// 先关闭然后重新打开
|
||||
await this.close();
|
||||
await this.open();
|
||||
|
||||
this.logger.log('[PluginManager] Plugin manager reloaded');
|
||||
return OB11NetworkReloadType.Normal;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "../../packages"
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -105,4 +105,7 @@ export interface OB11GroupFileFolder {
|
||||
creator: number; // 创建者ID
|
||||
creator_name: string; // 创建者名称
|
||||
total_file_count: number; // 文件总数
|
||||
modify_time: number; // 最后修改时间
|
||||
modifier: number; // 最后修改者ID
|
||||
modifier_name: string; // 最后修改者名称
|
||||
}
|
||||
@@ -2,84 +2,10 @@ import { defineConfig } from 'vite';
|
||||
import { resolve } from 'path';
|
||||
import nodeResolve from '@rollup/plugin-node-resolve';
|
||||
import { builtinModules } from 'module';
|
||||
import fs from 'fs';
|
||||
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
||||
// 依赖排除
|
||||
const external = [];
|
||||
// 构建后拷贝插件
|
||||
function copyToShellPlugin () {
|
||||
return {
|
||||
name: 'copy-to-shell',
|
||||
writeBundle () {
|
||||
try {
|
||||
const sourceDir = resolve(__dirname, 'dist');
|
||||
const targetDir = resolve(__dirname, '../napcat-shell/dist/plugins/napcat-plugin-builtin');
|
||||
const packageJsonSource = resolve(__dirname, 'package.json');
|
||||
const webuiSourceDir = resolve(__dirname, 'webui');
|
||||
const webuiTargetDir = resolve(targetDir, 'webui');
|
||||
|
||||
// 确保目标目录存在
|
||||
if (!fs.existsSync(targetDir)) {
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
console.log(`[copy-to-shell] Created directory: ${targetDir}`);
|
||||
}
|
||||
|
||||
// 拷贝 dist 目录下的所有文件
|
||||
const files = fs.readdirSync(sourceDir);
|
||||
let copiedCount = 0;
|
||||
|
||||
files.forEach(file => {
|
||||
const sourcePath = resolve(sourceDir, file);
|
||||
const targetPath = resolve(targetDir, file);
|
||||
|
||||
if (fs.statSync(sourcePath).isFile()) {
|
||||
fs.copyFileSync(sourcePath, targetPath);
|
||||
copiedCount++;
|
||||
}
|
||||
});
|
||||
|
||||
// 拷贝 package.json
|
||||
if (fs.existsSync(packageJsonSource)) {
|
||||
const packageJsonTarget = resolve(targetDir, 'package.json');
|
||||
fs.copyFileSync(packageJsonSource, packageJsonTarget);
|
||||
copiedCount++;
|
||||
}
|
||||
|
||||
// 拷贝 webui 目录
|
||||
if (fs.existsSync(webuiSourceDir)) {
|
||||
copyDirRecursive(webuiSourceDir, webuiTargetDir);
|
||||
console.log(`[copy-to-shell] Copied webui directory to ${webuiTargetDir}`);
|
||||
}
|
||||
|
||||
console.log(`[copy-to-shell] Successfully copied ${copiedCount} file(s) to ${targetDir}`);
|
||||
} catch (error) {
|
||||
console.error('[copy-to-shell] Failed to copy files:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 递归复制目录
|
||||
function copyDirRecursive (src: string, dest: string) {
|
||||
if (!fs.existsSync(dest)) {
|
||||
fs.mkdirSync(dest, { recursive: true });
|
||||
}
|
||||
|
||||
const entries = fs.readdirSync(src, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const srcPath = resolve(src, entry.name);
|
||||
const destPath = resolve(dest, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
copyDirRecursive(srcPath, destPath);
|
||||
} else {
|
||||
fs.copyFileSync(srcPath, destPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
@@ -102,5 +28,5 @@ export default defineConfig({
|
||||
external: [...nodeModules, ...external],
|
||||
},
|
||||
},
|
||||
plugins: [nodeResolve(), copyToShellPlugin()],
|
||||
plugins: [nodeResolve()],
|
||||
});
|
||||
@@ -14,6 +14,7 @@
|
||||
"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.
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user