Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
abda6a96de | ||
|
|
4e2c48624a | ||
|
|
1c0f7cce4f | ||
|
|
b31e1c0f0c | ||
|
|
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 |
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)
|
||||
|
||||
|
||||
@@ -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 生成
|
||||
|
||||
## 重要约束
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const { join } = require('node:path');
|
||||
const { test } = require('node:test');
|
||||
|
||||
const nativePath = join(__dirname, '../../../packages/napcat-native');
|
||||
const napiPath = join(nativePath, 'napi2native', 'napi2native.darwin.' + process.arch + '.node');
|
||||
const packetPath = join(nativePath, 'packet', 'MoeHoo.darwin.' + process.arch + '.node');
|
||||
|
||||
async function probe (mode) {
|
||||
if (mode === 'missing-wrapper') {
|
||||
const napi = require(napiPath);
|
||||
assert.throws(() => napi.initHook('1', '2'), /Failed to initialize send hook/);
|
||||
const packet = require(packetPath);
|
||||
assert.equal(packet.initHook('2', '4', () => {}, false), 'error search');
|
||||
return;
|
||||
}
|
||||
|
||||
const wrapper = require('./wrapper.node');
|
||||
const addresses = wrapper.addresses();
|
||||
const napi = require(napiPath);
|
||||
assert.equal(napi.initHook(addresses.coerce, addresses.resolver), true);
|
||||
const lengths = [0, 1, 21, 22, 23, 24, 255, 4096];
|
||||
for (const length of lengths) {
|
||||
const payload = Buffer.from(Array.from({ length }, (_, index) => index % 256));
|
||||
assert.deepEqual(wrapper.convert(payload), payload, 'convert length ' + length);
|
||||
const error = Buffer.from('e'.repeat(length));
|
||||
const result = await wrapper.resolve(-17, error, payload);
|
||||
assert.equal(result.result, -17);
|
||||
assert.equal(result.errMsg, error.toString());
|
||||
assert.equal(result.rsp, payload.toString());
|
||||
assert.deepEqual(result.rspbuffer, payload, 'resolve length ' + length);
|
||||
}
|
||||
for (const value of ['', '文🙂'.repeat(20), 12345, null, true]) {
|
||||
assert.deepEqual(wrapper.convert(value), Buffer.from(String(value)));
|
||||
}
|
||||
const responses = await Promise.all(Array.from({ length: 64 }, (_, index) => {
|
||||
const payload = Buffer.from([0, index, 255, 128]);
|
||||
return wrapper.resolve(index, Buffer.alloc(0), payload).then(result => {
|
||||
assert.equal(result.result, index);
|
||||
assert.deepEqual(result.rspbuffer, payload);
|
||||
});
|
||||
}));
|
||||
assert.equal(responses.length, 64);
|
||||
|
||||
const packet = require(packetPath);
|
||||
const received = [];
|
||||
assert.equal(packet.initHook(addresses.send, addresses.recv, (...args) => received.push(args), false), 'success');
|
||||
assert.equal(wrapper.emptyPackets(), 7);
|
||||
const expected = [];
|
||||
for (const length of lengths) {
|
||||
const uin = Buffer.from('1'.repeat(length));
|
||||
const command = Buffer.from('C'.repeat(length));
|
||||
const payload = Buffer.from(Array.from({ length }, (_, index) => index % 256));
|
||||
for (const direction of [0, 1]) {
|
||||
const sequence = length + 3000;
|
||||
const result = wrapper.packet(direction, uin, command, sequence, payload);
|
||||
assert.equal(result.returned, direction === 0 ? 102 : 209);
|
||||
assert.deepEqual(result.command, command);
|
||||
expected.push([direction, direction === 0 ? '0' : uin.toString(), command.toString(), sequence, payload.toString('hex').toUpperCase()]);
|
||||
}
|
||||
}
|
||||
const embeddedNull = Buffer.from('A\0B');
|
||||
wrapper.packet(1, embeddedNull, embeddedNull, 99, Buffer.from([255, 0, 128]));
|
||||
expected.push([1, 'A\0B', 'A\0B', 99, 'FF0080']);
|
||||
packet.setO3Setting(true);
|
||||
const replaced = wrapper.packet(0, Buffer.from('1'), Buffer.from('trpc.o3.report.Report.SsoReport'), 0, Buffer.alloc(0));
|
||||
assert.equal(replaced.command.toString(), 'fuck.trpc.o3');
|
||||
packet.setO3Setting(false);
|
||||
for (let attempt = 0; received.length < expected.length && attempt < 100; attempt++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
assert.deepEqual(received, expected);
|
||||
}
|
||||
|
||||
if (process.argv[2] === '--probe') {
|
||||
probe(process.argv[3]).catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
} else {
|
||||
for (const mode of ['missing-wrapper', 'hooks']) {
|
||||
test('macOS ' + process.arch + ' native ' + mode, () => {
|
||||
const result = spawnSync(process.execPath, [__filename, '--probe', mode], {
|
||||
encoding: 'utf8',
|
||||
timeout: 20000,
|
||||
});
|
||||
assert.ifError(result.error);
|
||||
assert.equal(result.signal, null, result.stderr);
|
||||
assert.equal(result.status, 0, result.stderr + result.stdout);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
#include <node_api.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct alignas(8) QQString
|
||||
{
|
||||
std::array<uint8_t, 24> bytes{};
|
||||
};
|
||||
|
||||
#if defined(__aarch64__)
|
||||
constexpr size_t flagOffset = 23;
|
||||
constexpr size_t dataOffset = 0;
|
||||
constexpr uint8_t heapMask = 0x80;
|
||||
#else
|
||||
constexpr size_t flagOffset = 0;
|
||||
constexpr size_t dataOffset = 16;
|
||||
constexpr uint8_t heapMask = 1;
|
||||
#endif
|
||||
|
||||
static uint64_t ReadWord(const QQString &value, size_t offset)
|
||||
{
|
||||
uint64_t word;
|
||||
std::memcpy(&word, value.bytes.data() + offset, sizeof(word));
|
||||
return word;
|
||||
}
|
||||
|
||||
static void WriteWord(QQString &value, size_t offset, uint64_t word)
|
||||
{
|
||||
std::memcpy(value.bytes.data() + offset, &word, sizeof(word));
|
||||
}
|
||||
|
||||
static QQString MakeString(const void *data, size_t length)
|
||||
{
|
||||
QQString value;
|
||||
if (length <= 22)
|
||||
{
|
||||
#if defined(__aarch64__)
|
||||
std::memcpy(value.bytes.data(), data, length);
|
||||
value.bytes[23] = length;
|
||||
#else
|
||||
std::memcpy(value.bytes.data() + 1, data, length);
|
||||
value.bytes[0] = length * 2;
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t capacity = (length | 15) + 1;
|
||||
auto buffer = static_cast<uint8_t *>(std::calloc(capacity, 1));
|
||||
std::memcpy(buffer, data, length);
|
||||
WriteWord(value, dataOffset, reinterpret_cast<uintptr_t>(buffer));
|
||||
WriteWord(value, 8, length);
|
||||
#if defined(__aarch64__)
|
||||
WriteWord(value, 16, capacity | (uint64_t{1} << 63));
|
||||
#else
|
||||
WriteWord(value, 0, capacity | 1);
|
||||
#endif
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static std::string ReadString(const QQString &value)
|
||||
{
|
||||
if ((value.bytes[flagOffset] & heapMask) != 0)
|
||||
return {reinterpret_cast<const char *>(ReadWord(value, dataOffset)), ReadWord(value, 8)};
|
||||
#if defined(__aarch64__)
|
||||
return {reinterpret_cast<const char *>(value.bytes.data()), value.bytes[23]};
|
||||
#else
|
||||
return {reinterpret_cast<const char *>(value.bytes.data() + 1), static_cast<size_t>(value.bytes[0] / 2)};
|
||||
#endif
|
||||
}
|
||||
|
||||
static void FreeString(const QQString &value)
|
||||
{
|
||||
if ((value.bytes[flagOffset] & heapMask) != 0)
|
||||
std::free(reinterpret_cast<void *>(ReadWord(value, dataOffset)));
|
||||
}
|
||||
|
||||
static QQString FromBuffer(napi_env env, napi_value input)
|
||||
{
|
||||
void *data;
|
||||
size_t length;
|
||||
napi_get_buffer_info(env, input, &data, &length);
|
||||
return MakeString(data, length);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((noinline)) QQString MockCoerce(napi_env env, napi_value input)
|
||||
{
|
||||
napi_value text;
|
||||
napi_coerce_to_string(env, input, &text);
|
||||
size_t length;
|
||||
napi_get_value_string_utf8(env, text, nullptr, 0, &length);
|
||||
std::vector<char> bytes(length + 1);
|
||||
napi_get_value_string_utf8(env, text, bytes.data(), bytes.size(), &length);
|
||||
return MakeString(bytes.data(), length);
|
||||
}
|
||||
|
||||
struct Context
|
||||
{
|
||||
uint8_t padding[24]{};
|
||||
napi_env env;
|
||||
napi_deferred deferred;
|
||||
};
|
||||
|
||||
struct AsyncResult
|
||||
{
|
||||
uint8_t padding[16]{};
|
||||
Context *context;
|
||||
int32_t result;
|
||||
int32_t alignment{};
|
||||
QQString error;
|
||||
QQString response;
|
||||
};
|
||||
|
||||
extern "C" __attribute__((noinline)) void MockResolver(AsyncResult *result)
|
||||
{
|
||||
napi_throw_error(result->context->env, nullptr, "Resolver was not intercepted");
|
||||
}
|
||||
|
||||
static volatile int64_t sendCalls = 0;
|
||||
static volatile int64_t recvCalls = 0;
|
||||
|
||||
extern "C" __attribute__((noinline)) int64_t MockSend(void *self, void **packet)
|
||||
{
|
||||
sendCalls += 1;
|
||||
return 101 + (self != nullptr) + (packet != nullptr);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((noinline)) int64_t MockRecv(void *self, void **packet, uint32_t marker)
|
||||
{
|
||||
recvCalls += 1;
|
||||
return 201 + marker + (self != nullptr) + (packet != nullptr);
|
||||
}
|
||||
|
||||
static napi_value Convert(napi_env env, napi_callback_info info)
|
||||
{
|
||||
size_t argc = 1;
|
||||
napi_value input;
|
||||
napi_get_cb_info(env, info, &argc, &input, nullptr, nullptr);
|
||||
auto output = MockCoerce(env, input);
|
||||
auto bytes = ReadString(output);
|
||||
napi_value result;
|
||||
napi_create_buffer_copy(env, bytes.size(), bytes.data(), nullptr, &result);
|
||||
FreeString(output);
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value Resolve(napi_env env, napi_callback_info info)
|
||||
{
|
||||
size_t argc = 3;
|
||||
napi_value args[3];
|
||||
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
|
||||
Context context{};
|
||||
context.env = env;
|
||||
napi_value promise;
|
||||
napi_create_promise(env, &context.deferred, &promise);
|
||||
AsyncResult result{};
|
||||
result.context = &context;
|
||||
napi_get_value_int32(env, args[0], &result.result);
|
||||
result.error = FromBuffer(env, args[1]);
|
||||
result.response = FromBuffer(env, args[2]);
|
||||
MockResolver(&result);
|
||||
FreeString(result.error);
|
||||
FreeString(result.response);
|
||||
return promise;
|
||||
}
|
||||
|
||||
struct ByteVector
|
||||
{
|
||||
uint8_t *begin;
|
||||
uint8_t *end;
|
||||
};
|
||||
|
||||
struct SendInner
|
||||
{
|
||||
QQString command;
|
||||
uint64_t padding{};
|
||||
ByteVector *payload;
|
||||
};
|
||||
|
||||
struct SendPacket
|
||||
{
|
||||
SendInner *inner;
|
||||
uint8_t padding[48]{};
|
||||
QQString uin;
|
||||
uint64_t alignment{};
|
||||
int64_t sequence;
|
||||
uint8_t tail[16]{};
|
||||
};
|
||||
|
||||
struct RecvPacket
|
||||
{
|
||||
QQString uin;
|
||||
int64_t sequence;
|
||||
QQString command;
|
||||
ByteVector *payload;
|
||||
};
|
||||
|
||||
static_assert(offsetof(AsyncResult, error) == 32);
|
||||
static_assert(offsetof(AsyncResult, response) == 56);
|
||||
static_assert(offsetof(SendPacket, uin) == 56);
|
||||
static_assert(offsetof(SendPacket, sequence) == 88);
|
||||
static_assert(offsetof(RecvPacket, payload) == 56);
|
||||
|
||||
static napi_value Packet(napi_env env, napi_callback_info info)
|
||||
{
|
||||
size_t argc = 5;
|
||||
napi_value args[5];
|
||||
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
|
||||
int32_t direction;
|
||||
int64_t sequence;
|
||||
napi_get_value_int32(env, args[0], &direction);
|
||||
napi_get_value_int64(env, args[3], &sequence);
|
||||
auto uin = FromBuffer(env, args[1]);
|
||||
auto command = FromBuffer(env, args[2]);
|
||||
void *payloadData;
|
||||
size_t payloadLength;
|
||||
napi_get_buffer_info(env, args[4], &payloadData, &payloadLength);
|
||||
uint8_t emptyPayload = 0;
|
||||
auto bytes = payloadLength ? static_cast<uint8_t *>(payloadData) : &emptyPayload;
|
||||
ByteVector payload{bytes, bytes + payloadLength};
|
||||
int64_t returnValue;
|
||||
if (direction == 0)
|
||||
{
|
||||
SendInner inner{command, 0, &payload};
|
||||
SendPacket packet{};
|
||||
packet.inner = &inner;
|
||||
packet.uin = uin;
|
||||
packet.sequence = sequence;
|
||||
void *pointer = &packet;
|
||||
returnValue = MockSend(nullptr, &pointer);
|
||||
command = inner.command;
|
||||
}
|
||||
else
|
||||
{
|
||||
RecvPacket packet{uin, sequence, command, &payload};
|
||||
void *pointer = &packet;
|
||||
returnValue = MockRecv(nullptr, &pointer, 7);
|
||||
}
|
||||
napi_value result;
|
||||
napi_create_object(env, &result);
|
||||
napi_value returned;
|
||||
napi_create_int64(env, returnValue, &returned);
|
||||
napi_set_named_property(env, result, "returned", returned);
|
||||
auto commandBytes = ReadString(command);
|
||||
napi_value outputCommand;
|
||||
napi_create_buffer_copy(env, commandBytes.size(), commandBytes.data(), nullptr, &outputCommand);
|
||||
napi_set_named_property(env, result, "command", outputCommand);
|
||||
FreeString(uin);
|
||||
FreeString(command);
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value EmptyPackets(napi_env env, napi_callback_info info)
|
||||
{
|
||||
void *missing = nullptr;
|
||||
MockSend(nullptr, nullptr);
|
||||
MockSend(nullptr, &missing);
|
||||
SendPacket send{};
|
||||
void *sendPointer = &send;
|
||||
MockSend(nullptr, &sendPointer);
|
||||
SendInner inner{};
|
||||
send.inner = &inner;
|
||||
MockSend(nullptr, &sendPointer);
|
||||
MockRecv(nullptr, nullptr, 0);
|
||||
MockRecv(nullptr, &missing, 0);
|
||||
RecvPacket recv{};
|
||||
void *recvPointer = &recv;
|
||||
MockRecv(nullptr, &recvPointer, 0);
|
||||
napi_value result;
|
||||
napi_create_int64(env, sendCalls + recvCalls, &result);
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value Addresses(napi_env env, napi_callback_info info)
|
||||
{
|
||||
Dl_info image{};
|
||||
dladdr(reinterpret_cast<void *>(MockCoerce), &image);
|
||||
uintptr_t base = reinterpret_cast<uintptr_t>(image.dli_fbase);
|
||||
napi_value result;
|
||||
napi_create_object(env, &result);
|
||||
const std::pair<const char *, uintptr_t> functions[] = {
|
||||
{"coerce", reinterpret_cast<uintptr_t>(MockCoerce) - base},
|
||||
{"resolver", reinterpret_cast<uintptr_t>(MockResolver) - base},
|
||||
{"send", (reinterpret_cast<uintptr_t>(MockSend) - base) * 2},
|
||||
{"recv", (reinterpret_cast<uintptr_t>(MockRecv) - base) * 2},
|
||||
};
|
||||
for (const auto &entry : functions)
|
||||
{
|
||||
std::ostringstream hex;
|
||||
hex << std::hex << entry.second;
|
||||
napi_value value;
|
||||
napi_create_string_utf8(env, hex.str().c_str(), NAPI_AUTO_LENGTH, &value);
|
||||
napi_set_named_property(env, result, entry.first, value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value Init(napi_env env, napi_value exports)
|
||||
{
|
||||
const napi_property_descriptor properties[] = {
|
||||
{"addresses", nullptr, Addresses, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"convert", nullptr, Convert, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"resolve", nullptr, Resolve, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"packet", nullptr, Packet, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"emptyPackets", nullptr, EmptyPackets, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
};
|
||||
napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties);
|
||||
return exports;
|
||||
}
|
||||
|
||||
NAPI_MODULE(wrapper, Init)
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
name: macOS native compatibility
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- packages/napcat-native/**
|
||||
- .github/tests/macos-native/**
|
||||
- .github/workflows/macos-native.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- packages/napcat-native/**
|
||||
- .github/tests/macos-native/**
|
||||
- .github/workflows/macos-native.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
native:
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: macos-15
|
||||
arch: arm64
|
||||
- runner: macos-15-intel
|
||||
arch: x64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
architecture: ${{ matrix.arch }}
|
||||
- name: Build QQ ABI mock
|
||||
working-directory: .github/tests/macos-native
|
||||
run: |
|
||||
npm install --prefix headers --ignore-scripts --no-package-lock node-api-headers@1.6.0
|
||||
clang++ -std=c++17 -O0 -g -bundle -undefined dynamic_lookup -I headers/node_modules/node-api-headers/include wrapper.cpp -o wrapper.node
|
||||
codesign --force --sign - wrapper.node
|
||||
- name: Exercise native packet hooks
|
||||
run: node --test .github/tests/macos-native/hooks.test.cjs
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: NapNeko/ffmpegAddon
|
||||
ref: 7a68e99b52921a47f7f6d99864ed6217a0a90e7d
|
||||
path: ffmpeg-native-tests
|
||||
- name: Verify packaged FFmpeg
|
||||
working-directory: ffmpeg-native-tests
|
||||
env:
|
||||
FFMPEG_ADDON_PATH: ${{ github.workspace }}/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.${{ matrix.arch }}.node
|
||||
run: |
|
||||
npm ci --ignore-scripts
|
||||
npm test
|
||||
@@ -9,8 +9,8 @@ on:
|
||||
type: string
|
||||
|
||||
env:
|
||||
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_x86_64.AppImage'
|
||||
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_arm64.AppImage'
|
||||
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.36/beta/9ee04bef/linuxqq_3.2.34-53644_x86_64.AppImage'
|
||||
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.36/beta/9ee04bef/linuxqq_3.2.34-53644_arm64.AppImage'
|
||||
|
||||
jobs:
|
||||
get-version:
|
||||
@@ -86,17 +86,19 @@ jobs:
|
||||
git push
|
||||
|
||||
shell-docker:
|
||||
needs: get-version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\"}}"
|
||||
|
||||
framework-docker:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -47,6 +47,7 @@ jobs:
|
||||
- name: Build NapCat.${{ matrix.target.name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
@@ -65,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:
|
||||
@@ -80,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'
|
||||
@@ -94,15 +106,20 @@ jobs:
|
||||
mkdir -p /tmp/napcat-downloads
|
||||
cd /tmp/napcat-downloads
|
||||
|
||||
NT_URL="https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/a33ab721/QQ9.9.32.50969_x64.exe"
|
||||
echo "Downloading QQ installer..."
|
||||
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
|
||||
@@ -137,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
|
||||
|
||||
# -----------------------------
|
||||
@@ -159,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
|
||||
@@ -168,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
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { GeneralCallResult, InstanceContext, NapCatCore } from '@/napcat-core';
|
||||
import {
|
||||
createFlashTransferResult,
|
||||
DEFAULT_FLASH_VALIDITY_SECONDS,
|
||||
FileListResponse,
|
||||
FlashFileSetInfo,
|
||||
SendStatus,
|
||||
@@ -22,8 +23,9 @@ export class NTQQFlashApi {
|
||||
* @param fileListToUpload 上传文件绝对路径的列表,可以是文件夹!!
|
||||
* @param thumbnailPath
|
||||
* @param filesetName
|
||||
* @param validitySeconds 文件集有效期(秒),默认 1209600(14 天),可选 90 天 / 180 天,必须传否则新版内核段错误
|
||||
*/
|
||||
async createFlashTransferUploadTask (fileListToUpload: string[], thumbnailPath: string, filesetName: string): Promise<GeneralCallResult & {
|
||||
async createFlashTransferUploadTask (fileListToUpload: string[], thumbnailPath: string, filesetName: string, validitySeconds: number = DEFAULT_FLASH_VALIDITY_SECONDS): Promise<GeneralCallResult & {
|
||||
createFlashTransferResult: createFlashTransferResult;
|
||||
seq: number;
|
||||
}> {
|
||||
@@ -33,14 +35,17 @@ export class NTQQFlashApi {
|
||||
const selfInfo = this.core.selfInfo;
|
||||
|
||||
const fileUploadArg = {
|
||||
screen: 1, // 1
|
||||
scene: 1, // 1
|
||||
name: filesetName,
|
||||
uploaders: [{
|
||||
uin: selfInfo.uin,
|
||||
nickname: selfInfo.nick,
|
||||
uid: selfInfo.uid,
|
||||
sendEntrance: '',
|
||||
nickname: selfInfo.nick,
|
||||
}],
|
||||
permission: {
|
||||
code: 0,
|
||||
},
|
||||
coverPath: thumbnailPath,
|
||||
paths: fileListToUpload,
|
||||
excludePaths: [],
|
||||
@@ -56,8 +61,15 @@ export class NTQQFlashApi {
|
||||
uploadSceneType: UploadSceneType.KUPLOADSCENEAIOFILESELECTOR, // 不知道怎么枚举 先硬编码吧 (PC QQ 10)
|
||||
detectPrivacyInfoResult: {
|
||||
exists: false,
|
||||
allDetectResults: new Map(),
|
||||
allDetectResults: {},
|
||||
},
|
||||
announcement: {
|
||||
announcementSegments: [],
|
||||
modifyTime: '',
|
||||
avatarUrl: '',
|
||||
},
|
||||
albumFilePathList: [],
|
||||
validitySeconds,
|
||||
};
|
||||
|
||||
const uploadResult = await flashService.createFlashTransferUploadTask(timestamp, fileUploadArg);
|
||||
|
||||
@@ -297,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}`);
|
||||
@@ -326,27 +329,44 @@ 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);
|
||||
}
|
||||
@@ -542,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);
|
||||
}
|
||||
|
||||
@@ -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,14 @@ 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,
|
||||
@@ -35,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;
|
||||
@@ -382,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}`;
|
||||
@@ -397,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: {
|
||||
@@ -445,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 = '') {
|
||||
|
||||
@@ -214,15 +214,19 @@ export enum UploadSceneType {
|
||||
KUPLOADSCENEAIOFILESELECTOR,
|
||||
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV,
|
||||
}
|
||||
/** 闪传文件集默认有效期(秒):14 天 */
|
||||
export const DEFAULT_FLASH_VALIDITY_SECONDS = 1209600;
|
||||
|
||||
export interface StartFlashTaskRequests {
|
||||
screen: number; // 1 PC-QQ
|
||||
scene: number; // 1 PC-QQ
|
||||
name?: string;
|
||||
uploaders: UploaderInfo[];
|
||||
permission?: {};
|
||||
permission?: { code: number; };
|
||||
coverPath?: string;
|
||||
paths: string[]; // 文件的绝对路径,可以是文件夹
|
||||
excludePaths?: string[];
|
||||
expireLeftTime?: number, // 0
|
||||
validitySeconds: number, // 文件集有效期(秒):14 天 1209600 / 90 天 7776000 / 180 天 15552000,必须传,否则新版内核段错误
|
||||
isNeedDelDeviceInfo: boolean,
|
||||
isNeedDelLocation: boolean,
|
||||
coverOriginalInfos?: {
|
||||
@@ -234,6 +238,12 @@ export interface StartFlashTaskRequests {
|
||||
exists: boolean,
|
||||
allDetectResults: {};
|
||||
};
|
||||
announcement: {
|
||||
announcementSegments: unknown[],
|
||||
modifyTime: string,
|
||||
avatarUrl: string;
|
||||
};
|
||||
albumFilePathList: unknown[];
|
||||
}
|
||||
export enum BusiScene {
|
||||
KBUSISCENEINVALID,
|
||||
|
||||
@@ -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: '',
|
||||
}
|
||||
)],
|
||||
};
|
||||
}
|
||||
+184
-16
@@ -395,12 +395,16 @@
|
||||
"appid": 537319840,
|
||||
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
|
||||
},
|
||||
"3.2.20-40768-arm64": {
|
||||
"appid": 537319841,
|
||||
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
|
||||
},
|
||||
"9.9.22-40768": {
|
||||
"appid": 537319804,
|
||||
"qua": "V1_WIN_NQ_9.9.22_40768_GW_B"
|
||||
},
|
||||
"6.9.82-40768": {
|
||||
"appid": 537319829,
|
||||
"appid": 537319828,
|
||||
"qua": "V1_MAC_NQ_6.9.82_40768_GW_B"
|
||||
},
|
||||
"3.2.20-40824": {
|
||||
@@ -416,23 +420,27 @@
|
||||
"qua": "V1_MAC_NQ_6.9.82_40824_GW_B"
|
||||
},
|
||||
"6.9.82-40990": {
|
||||
"appid": 537319880,
|
||||
"appid": 537319879,
|
||||
"qua": "V1_MAC_NQ_6.9.82_40990_GW_B"
|
||||
},
|
||||
"9.9.22-40990": {
|
||||
"appid": 537319855,
|
||||
"qua": "V1_WIN_NQ_9.9.22.40990_GW_B"
|
||||
"qua": "V1_WIN_NQ_9.9.22_40990_GW_B"
|
||||
},
|
||||
"3.2.20-40990": {
|
||||
"appid": 537319891,
|
||||
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
|
||||
},
|
||||
"3.2.20-40990-arm64": {
|
||||
"appid": 537319892,
|
||||
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
|
||||
},
|
||||
"9.9.23-41679": {
|
||||
"appid": 537320110,
|
||||
"qua": "V1_WIN_NQ_9.9.23_41679_GW_B"
|
||||
},
|
||||
"6.9.83-41679": {
|
||||
"appid": 537320135,
|
||||
"appid": 537320134,
|
||||
"qua": "V1_MAC_NQ_6.9.83_41679_GW_B"
|
||||
},
|
||||
"9.9.23-41785": {
|
||||
@@ -440,7 +448,7 @@
|
||||
"qua": "V1_WIN_NQ_9.9.23_41785_GW_B"
|
||||
},
|
||||
"6.9.83-41785": {
|
||||
"appid": 537320135,
|
||||
"appid": 537320134,
|
||||
"qua": "V1_MAC_NQ_6.9.83_41785_GW_B"
|
||||
},
|
||||
"9.9.23-41857": {
|
||||
@@ -451,20 +459,28 @@
|
||||
"appid": 537320197,
|
||||
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
|
||||
},
|
||||
"3.2.21-41857-arm64": {
|
||||
"appid": 537320198,
|
||||
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
|
||||
},
|
||||
"6.9.83-41857": {
|
||||
"appid": 537320186,
|
||||
"appid": 537320185,
|
||||
"qua": "V1_MAC_NQ_6.9.83_41857_GW_B"
|
||||
},
|
||||
"3.2.21-42086": {
|
||||
"appid": 537320248,
|
||||
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
|
||||
},
|
||||
"3.2.21-42086-arm64": {
|
||||
"appid": 537320249,
|
||||
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
|
||||
},
|
||||
"9.9.23-42086": {
|
||||
"appid": 537320212,
|
||||
"qua": "V1_WIN_NQ_9.9.23_42086_GW_B"
|
||||
},
|
||||
"6.9.85-42086": {
|
||||
"appid": 537320237,
|
||||
"appid": 537320236,
|
||||
"qua": "V1_MAC_NQ_6.9.85_42086_GW_B"
|
||||
},
|
||||
"9.9.23-42430": {
|
||||
@@ -473,30 +489,34 @@
|
||||
},
|
||||
"9.9.25-42744": {
|
||||
"appid": 537328470,
|
||||
"qua": "V1_WIN_NQ_9.9.23_42744_GW_B"
|
||||
"qua": "V1_WIN_NQ_9.9.25_42744_GW_B"
|
||||
},
|
||||
"6.9.86-42744": {
|
||||
"appid": 537328495,
|
||||
"qua": "V1_MAC_NQ_6.9.85_42744_GW_B"
|
||||
"appid": 537328494,
|
||||
"qua": "V1_MAC_NQ_6.9.86_42744_GW_B"
|
||||
},
|
||||
"9.9.25-42905": {
|
||||
"appid": 537328521,
|
||||
"qua": "V1_WIN_NQ_9.9.25_42905_GW_B"
|
||||
},
|
||||
"6.9.86-42905": {
|
||||
"appid": 537328546,
|
||||
"appid": 537328545,
|
||||
"qua": "V1_MAC_NQ_6.9.86_42905_GW_B"
|
||||
},
|
||||
"3.2.22-42941": {
|
||||
"appid": 537328659,
|
||||
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
|
||||
},
|
||||
"3.2.22-42941-arm64": {
|
||||
"appid": 537328660,
|
||||
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
|
||||
},
|
||||
"9.9.25-42941": {
|
||||
"appid": 537328623,
|
||||
"qua": "V1_WIN_NQ_9.9.25_42941_GW_B"
|
||||
},
|
||||
"6.9.86-42941": {
|
||||
"appid": 537328648,
|
||||
"appid": 537328647,
|
||||
"qua": "V1_MAC_NQ_6.9.86_42941_GW_B"
|
||||
},
|
||||
"9.9.26-44175": {
|
||||
@@ -511,6 +531,14 @@
|
||||
"appid": 537336639,
|
||||
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
|
||||
},
|
||||
"3.2.23-44343-arm64": {
|
||||
"appid": 537336640,
|
||||
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
|
||||
},
|
||||
"6.9.87-44343": {
|
||||
"appid": 537336627,
|
||||
"qua": "V1_MAC_NQ_6.9.87_44343_GW_B"
|
||||
},
|
||||
"9.9.26-44498": {
|
||||
"appid": 537337416,
|
||||
"qua": "V1_WIN_NQ_9.9.26_44498_GW_B"
|
||||
@@ -524,13 +552,21 @@
|
||||
"qua": "V1_WIN_NQ_9.9.27_45627_GW_B"
|
||||
},
|
||||
"6.9.88-44725": {
|
||||
"appid": 537337594,
|
||||
"appid": 537337593,
|
||||
"qua": "V1_MAC_NQ_6.9.88_44725_GW_B"
|
||||
},
|
||||
"3.2.25-45758": {
|
||||
"appid": 537340249,
|
||||
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
|
||||
},
|
||||
"3.2.25-45758-arm64": {
|
||||
"appid": 537340250,
|
||||
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
|
||||
},
|
||||
"6.9.89-45758": {
|
||||
"appid": 537340237,
|
||||
"qua": "V1_MAC_NQ_6.9.89_45758_GW_B"
|
||||
},
|
||||
"9.9.27-45758": {
|
||||
"appid": 537340213,
|
||||
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
|
||||
@@ -539,6 +575,10 @@
|
||||
"appid": 537345891,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
|
||||
},
|
||||
"3.2.26-46494-arm64": {
|
||||
"appid": 537345892,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
|
||||
},
|
||||
"9.9.28-46494": {
|
||||
"appid": 537345855,
|
||||
"qua": "V1_WIN_NQ_9.9.28_46494_GW_B"
|
||||
@@ -548,13 +588,25 @@
|
||||
"qua": "V1_MAC_NQ_6.9.90_46494_GW_B"
|
||||
},
|
||||
"3.2.26-46928": {
|
||||
"appid": 537345993,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
|
||||
},
|
||||
"3.2.26-46928-arm64": {
|
||||
"appid": 537345994,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
|
||||
},
|
||||
"6.9.91-46928": {
|
||||
"appid": 537345981,
|
||||
"qua": "V1_MAC_NQ_6.9.91_46928_GW_B"
|
||||
},
|
||||
"9.9.28-46928": {
|
||||
"appid": 537345957,
|
||||
"qua": "V1_WIN_NQ_9.9.28_46928_GW_B"
|
||||
},
|
||||
"3.2.27-47256": {
|
||||
"appid": 537346857,
|
||||
"qua": "V1_LNX_NQ_3.2.27_47256_GW_B"
|
||||
},
|
||||
"3.2.27-47354": {
|
||||
"appid": 537346908,
|
||||
"qua": "V1_LNX_NQ_3.2.27_47354_GW_B"
|
||||
@@ -575,6 +627,14 @@
|
||||
"appid": 537352510,
|
||||
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
|
||||
},
|
||||
"3.2.28-48517-arm64": {
|
||||
"appid": 537352511,
|
||||
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
|
||||
},
|
||||
"6.9.95-48517": {
|
||||
"appid": 537352498,
|
||||
"qua": "V1_MAC_NQ_6.9.95_48517_GW_B"
|
||||
},
|
||||
"9.9.30-48762": {
|
||||
"appid": 537352525,
|
||||
"qua": "V1_WIN_NQ_9.9.30_48762_GW_B"
|
||||
@@ -588,9 +648,17 @@
|
||||
"qua": "V1_WIN_NQ_9.9.31_49738_GW_B"
|
||||
},
|
||||
"3.2.29-49738": {
|
||||
"appid": 537355866,
|
||||
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
|
||||
},
|
||||
"3.2.29-49738-arm64": {
|
||||
"appid": 537355867,
|
||||
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
|
||||
},
|
||||
"6.9.96-49738": {
|
||||
"appid": 537355854,
|
||||
"qua": "V1_MAC_NQ_6.9.96_49738_GW_B"
|
||||
},
|
||||
"9.9.32-50828": {
|
||||
"appid": 537358739,
|
||||
"qua": "V1_WIN_NQ_9.9.32_50828_GW_B"
|
||||
@@ -599,6 +667,10 @@
|
||||
"appid": 537358775,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
|
||||
},
|
||||
"3.2.30-50828-arm64": {
|
||||
"appid": 537358776,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
|
||||
},
|
||||
"9.9.32-50969": {
|
||||
"appid": 537376308,
|
||||
"qua": "V1_WIN_NQ_9.9.32_50969_GW_B"
|
||||
@@ -607,8 +679,104 @@
|
||||
"appid": 537376344,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
|
||||
},
|
||||
"9.9.32-55230": {
|
||||
"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"
|
||||
},
|
||||
"6.9.98-51102": {
|
||||
"appid": 537376485,
|
||||
"qua": "V1_MAC_NQ_6.9.98_51102_GW_B"
|
||||
},
|
||||
"9.9.32-51246": {
|
||||
"appid": 537376512,
|
||||
"qua": "V1_WIN_NQ_9.9.32_51246_GW_B"
|
||||
},
|
||||
"3.2.32-51728": {
|
||||
"appid": 537376803,
|
||||
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
|
||||
},
|
||||
"3.2.32-51728-arm64": {
|
||||
"appid": 537376804,
|
||||
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
|
||||
},
|
||||
"3.2.32-51802": {
|
||||
"appid": 537376854,
|
||||
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
|
||||
},
|
||||
"3.2.32-51802-arm64": {
|
||||
"appid": 537376855,
|
||||
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
|
||||
},
|
||||
"6.9.99-51802": {
|
||||
"appid": 537376842,
|
||||
"qua": "V1_MAC_NQ_6.9.99_51802_GW_B"
|
||||
},
|
||||
"9.9.33-51802": {
|
||||
"appid": 537376818,
|
||||
"qua": "V1_WIN_NQ_9.9.33_51802_GW_B"
|
||||
},
|
||||
"9.9.33-52230": {
|
||||
"appid": 537379411,
|
||||
"qua": "V1_WIN_NQ_9.9.32_55230_GW_B"
|
||||
"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"
|
||||
},
|
||||
"7.0.0-52194": {
|
||||
"appid": 537379435,
|
||||
"qua": "V1_MAC_NQ_7.0.0_52194_GW_B"
|
||||
},
|
||||
"9.9.35-52804": {
|
||||
"appid": 537382717,
|
||||
"qua": "V1_WIN_NQ_9.9.35_52804_GW_B"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"7.0.1-52892": {
|
||||
"appid": 537382843,
|
||||
"qua": "V1_MAC_NQ_7.0.1_52892_GW_B"
|
||||
},
|
||||
"3.2.34-53644": {
|
||||
"appid": 537391664,
|
||||
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
|
||||
},
|
||||
"3.2.34-53644-arm64": {
|
||||
"appid": 537391665,
|
||||
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
|
||||
},
|
||||
"7.0.2-53644": {
|
||||
"appid": 537391652,
|
||||
"qua": "V1_MAC_NQ_7.0.2_53644_GW_B"
|
||||
},
|
||||
"9.9.36-53644": {
|
||||
"appid": 537391628,
|
||||
"qua": "V1_WIN_NQ_9.9.36_53644_GW_B"
|
||||
}
|
||||
}
|
||||
}
|
||||
+209
-9
@@ -64,7 +64,7 @@
|
||||
"recv": "1D19FF9"
|
||||
},
|
||||
"6.9.83-41857-arm64": {
|
||||
"send": "0815774",
|
||||
"send": "23B41F0",
|
||||
"recv": "0958B3C"
|
||||
},
|
||||
"3.2.21-41857-x64": {
|
||||
@@ -85,7 +85,7 @@
|
||||
},
|
||||
"6.9.85-42086-arm64": {
|
||||
"send": "23B0330",
|
||||
"recv": "0957648"
|
||||
"recv": "9556B8"
|
||||
},
|
||||
"3.2.21-42086-arm64": {
|
||||
"send": "3D6D98C",
|
||||
@@ -103,7 +103,7 @@
|
||||
"send": "0A0D104",
|
||||
"recv": "1D3E7F9"
|
||||
},
|
||||
"6.9.85-42744-arm64": {
|
||||
"6.9.86-42744-arm64": {
|
||||
"send": "23DFEF0",
|
||||
"recv": "095FD80"
|
||||
},
|
||||
@@ -147,6 +147,10 @@
|
||||
"send": "59A27B0",
|
||||
"recv": "2FFBE90"
|
||||
},
|
||||
"6.9.87-44343-arm64": {
|
||||
"send": "2311B68",
|
||||
"recv": "9673A4"
|
||||
},
|
||||
"9.9.26-44498-x64": {
|
||||
"send": "0A1051C",
|
||||
"recv": "1D3BC0D"
|
||||
@@ -161,7 +165,7 @@
|
||||
},
|
||||
"6.9.88-44725-x64": {
|
||||
"send": "2756EF6",
|
||||
"recv": "0A36152"
|
||||
"recv": "A36152"
|
||||
},
|
||||
"6.9.88-44725-arm64": {
|
||||
"send": "2313C68",
|
||||
@@ -175,6 +179,10 @@
|
||||
"send": "3EB6554",
|
||||
"recv": "149AF0C"
|
||||
},
|
||||
"6.9.89-45758-arm64": {
|
||||
"send": "2425228",
|
||||
"recv": "9B6770"
|
||||
},
|
||||
"9.9.27-45758-x64": {
|
||||
"send": "0A6A6BC",
|
||||
"recv": "1E87EC1"
|
||||
@@ -191,6 +199,10 @@
|
||||
"send": "3EDC654",
|
||||
"recv": "14A3124"
|
||||
},
|
||||
"6.9.90-46494-arm64": {
|
||||
"send": "2438B4C",
|
||||
"recv": "9BBE00"
|
||||
},
|
||||
"3.2.26-46928-x64": {
|
||||
"send": "5D30910",
|
||||
"recv": "31814B0"
|
||||
@@ -199,10 +211,18 @@
|
||||
"send": "3EDC654",
|
||||
"recv": "14A3124"
|
||||
},
|
||||
"6.9.91-46928-arm64": {
|
||||
"send": "2438B4C",
|
||||
"recv": "9BBE00"
|
||||
},
|
||||
"9.9.28-46928-x64": {
|
||||
"send": "0A6D66C",
|
||||
"recv": "1E9890D"
|
||||
},
|
||||
"3.2.27-47256-x64": {
|
||||
"send": "5D389C0",
|
||||
"recv": "318D090"
|
||||
},
|
||||
"3.2.27-47354-x64": {
|
||||
"send": "5D38930",
|
||||
"recv": "318D090"
|
||||
@@ -221,7 +241,7 @@
|
||||
},
|
||||
"6.9.93-47354-x64": {
|
||||
"send": "28ADE46",
|
||||
"recv": "0A8FD5A"
|
||||
"recv": "A8FD5A"
|
||||
},
|
||||
"9.9.30-48517-x64": {
|
||||
"send": "0A9B1BC",
|
||||
@@ -235,6 +255,10 @@
|
||||
"send": "3F9C7E4",
|
||||
"recv": "14E1AA8"
|
||||
},
|
||||
"6.9.95-48517-arm64": {
|
||||
"send": "25120A8",
|
||||
"recv": "9DB00C"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "0A9B1BC",
|
||||
"recv": "1F0324D"
|
||||
@@ -255,6 +279,10 @@
|
||||
"send": "426AA04",
|
||||
"recv": "1596254"
|
||||
},
|
||||
"6.9.96-49738-arm64": {
|
||||
"send": "2785BB8",
|
||||
"recv": "A29880"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "0B245CC",
|
||||
"recv": "2073D65"
|
||||
@@ -279,8 +307,180 @@
|
||||
"send": "43A4804",
|
||||
"recv": "1608CC8"
|
||||
},
|
||||
"9.9.32-55230-x64": {
|
||||
"send": "367FE18",
|
||||
"recv": "36835CC"
|
||||
"3.2.31-51102-x64": {
|
||||
"send": "63F4910",
|
||||
"recv": "34B9F90"
|
||||
},
|
||||
"3.2.31-51102-arm64": {
|
||||
"send": "43A48E4",
|
||||
"recv": "1608D98"
|
||||
},
|
||||
"6.9.98-51102-arm64": {
|
||||
"send": "2849378",
|
||||
"recv": "A66CFC"
|
||||
},
|
||||
"9.9.32-51246-x64": {
|
||||
"send": "B2E37C",
|
||||
"recv": "209C7D9"
|
||||
},
|
||||
"3.2.32-51728-arm64": {
|
||||
"send": "48CA8F8",
|
||||
"recv": "17D5A78"
|
||||
},
|
||||
"3.2.32-51728-x64": {
|
||||
"send": "6B9ADD0",
|
||||
"recv": "38F5F30"
|
||||
},
|
||||
"3.2.32-51802-x64": {
|
||||
"send": "6B9B790",
|
||||
"recv": "38F68F0"
|
||||
},
|
||||
"3.2.32-51802-arm64": {
|
||||
"send": "48CB078",
|
||||
"recv": "17D620C"
|
||||
},
|
||||
"6.9.99-51802-arm64": {
|
||||
"send": "2B0B384",
|
||||
"recv": "B4526C"
|
||||
},
|
||||
"9.9.33-51802-x64": {
|
||||
"send": "BDE15F",
|
||||
"recv": "237BC91"
|
||||
},
|
||||
"9.9.33-52230-x64": {
|
||||
"send": "BF2B5F",
|
||||
"recv": "23BB4DD"
|
||||
},
|
||||
"3.2.32-52194-x64": {
|
||||
"send": "6C45D20",
|
||||
"recv": "393DE00"
|
||||
},
|
||||
"3.2.32-52194-arm64": {
|
||||
"send": "493FAD8",
|
||||
"recv": "17EA1DC"
|
||||
},
|
||||
"7.0.0-52194-arm64": {
|
||||
"send": "2B3FBA4",
|
||||
"recv": "B4E85C"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"7.0.1-52892-arm64": {
|
||||
"send": "2B3FBCC",
|
||||
"recv": "B64170"
|
||||
},
|
||||
"3.2.34-53644-x64": {
|
||||
"send": "6E5AB20",
|
||||
"recv": "3A12CD0"
|
||||
},
|
||||
"3.2.34-53644-arm64": {
|
||||
"send": "4AABA5C",
|
||||
"recv": "182C534"
|
||||
},
|
||||
"7.0.2-53644-arm64": {
|
||||
"send": "2B82DEC",
|
||||
"recv": "B71088"
|
||||
},
|
||||
"9.9.36-53644-x64": {
|
||||
"send": "C3EE2F",
|
||||
"recv": "24A6355"
|
||||
},
|
||||
"6.9.82-40768-x64": {
|
||||
"send": "6587B8",
|
||||
"recv": "C45C6E"
|
||||
},
|
||||
"6.9.82-40990-x64": {
|
||||
"send": "6587B8",
|
||||
"recv": "C45C6E"
|
||||
},
|
||||
"6.9.83-41679-x64": {
|
||||
"send": "271A206",
|
||||
"recv": "A1E04A"
|
||||
},
|
||||
"6.9.83-41785-x64": {
|
||||
"send": "2744756",
|
||||
"recv": "A1DE4A"
|
||||
},
|
||||
"6.9.83-41857-x64": {
|
||||
"send": "2745186",
|
||||
"recv": "A1E96E"
|
||||
},
|
||||
"6.9.85-42086-x64": {
|
||||
"send": "27462F6",
|
||||
"recv": "A1FC0A"
|
||||
},
|
||||
"6.9.86-42744-x64": {
|
||||
"send": "27770E6",
|
||||
"recv": "A2725A"
|
||||
},
|
||||
"6.9.86-42905-x64": {
|
||||
"send": "2786206",
|
||||
"recv": "A2D6A6"
|
||||
},
|
||||
"6.9.86-42941-x64": {
|
||||
"send": "2786366",
|
||||
"recv": "A2D2E2"
|
||||
},
|
||||
"6.9.87-44343-x64": {
|
||||
"send": "2750306",
|
||||
"recv": "A2F432"
|
||||
},
|
||||
"6.9.89-45758-x64": {
|
||||
"send": "288CBB6",
|
||||
"recv": "A87816"
|
||||
},
|
||||
"6.9.90-46494-x64": {
|
||||
"send": "28A2F96",
|
||||
"recv": "A8D2FE"
|
||||
},
|
||||
"6.9.91-46928-x64": {
|
||||
"send": "28A2F96",
|
||||
"recv": "A8D2FE"
|
||||
},
|
||||
"6.9.95-48517-x64": {
|
||||
"send": "28DC616",
|
||||
"recv": "AAED2A"
|
||||
},
|
||||
"6.9.96-49738-x64": {
|
||||
"send": "2B8C936",
|
||||
"recv": "AFF03E"
|
||||
},
|
||||
"6.9.98-51102-x64": {
|
||||
"send": "2C6CD06",
|
||||
"recv": "B42922"
|
||||
},
|
||||
"6.9.99-51802-x64": {
|
||||
"send": "2F6C1AB",
|
||||
"recv": "C16A4A"
|
||||
},
|
||||
"7.0.0-52194-x64": {
|
||||
"send": "2FAC58B",
|
||||
"recv": "C20DB2"
|
||||
},
|
||||
"7.0.1-52892-x64": {
|
||||
"send": "304CC8B",
|
||||
"recv": "C3A54E"
|
||||
},
|
||||
"7.0.2-53644-x64": {
|
||||
"send": "309B1BB",
|
||||
"recv": "C47262"
|
||||
}
|
||||
}
|
||||
}
|
||||
+218
-10
@@ -528,8 +528,8 @@
|
||||
"recv": "7D4D4A8"
|
||||
},
|
||||
"6.9.82-40768-arm64": {
|
||||
"send": "202A198",
|
||||
"recv": "202B718"
|
||||
"send": "4054330",
|
||||
"recv": "4056E30"
|
||||
},
|
||||
"9.9.22-40824-x64": {
|
||||
"send": "31C1838",
|
||||
@@ -540,8 +540,8 @@
|
||||
"recv": "7D4D4A8"
|
||||
},
|
||||
"6.9.82-40824-arm64": {
|
||||
"send": "202A198",
|
||||
"recv": "202B718"
|
||||
"send": "4054330",
|
||||
"recv": "4056E30"
|
||||
},
|
||||
"3.2.20-40990-x64": {
|
||||
"send": "B69CFE0",
|
||||
@@ -556,8 +556,8 @@
|
||||
"recv": "31C4FDC"
|
||||
},
|
||||
"6.9.82-40990-arm64": {
|
||||
"send": "202A198",
|
||||
"recv": "202B718"
|
||||
"send": "4054330",
|
||||
"recv": "4056E30"
|
||||
},
|
||||
"9.9.23-41679-x64": {
|
||||
"send": "2C94520",
|
||||
@@ -603,6 +603,10 @@
|
||||
"send": "6B13038",
|
||||
"recv": "6B169C8"
|
||||
},
|
||||
"6.9.85-42086-arm64": {
|
||||
"send": "3D6D028",
|
||||
"recv": "3D6F938"
|
||||
},
|
||||
"9.9.23-42430-x64": {
|
||||
"send": "2C9A4A0",
|
||||
"recv": "2C9DA20"
|
||||
@@ -655,6 +659,10 @@
|
||||
"send": "6926F60",
|
||||
"recv": "692A910"
|
||||
},
|
||||
"6.9.87-44343-arm64": {
|
||||
"send": "3D74F50",
|
||||
"recv": "3D77860"
|
||||
},
|
||||
"9.9.26-44498-x64": {
|
||||
"send": "2CDAE40",
|
||||
"recv": "2CDE3C0"
|
||||
@@ -687,6 +695,10 @@
|
||||
"send": "6D6F9A0",
|
||||
"recv": "6D73350"
|
||||
},
|
||||
"6.9.89-45758-arm64": {
|
||||
"send": "3F9BD68",
|
||||
"recv": "3F9E678"
|
||||
},
|
||||
"3.2.26-46494-x64": {
|
||||
"send": "AB341C0",
|
||||
"recv": "AB37C60"
|
||||
@@ -699,6 +711,10 @@
|
||||
"send": "6DBBBB0",
|
||||
"recv": "6DBF560"
|
||||
},
|
||||
"6.9.90-46494-arm64": {
|
||||
"send": "3FC2CD0",
|
||||
"recv": "3FC55E0"
|
||||
},
|
||||
"3.2.26-46928-arm64": {
|
||||
"send": "6DBBBB0",
|
||||
"recv": "6DBF560"
|
||||
@@ -707,10 +723,18 @@
|
||||
"send": "AB341C0",
|
||||
"recv": "AB37C60"
|
||||
},
|
||||
"6.9.91-46928-arm64": {
|
||||
"send": "3FC2CD0",
|
||||
"recv": "3FC55E0"
|
||||
},
|
||||
"9.9.28-46928-x64": {
|
||||
"send": "2E77C20",
|
||||
"recv": "2E7B1A0"
|
||||
},
|
||||
"3.2.27-47256-x64": {
|
||||
"send": "AB6A7E0",
|
||||
"recv": "AB6E280"
|
||||
},
|
||||
"3.2.27-47354-x64": {
|
||||
"send": "AB6A6C0",
|
||||
"recv": "AB6E160"
|
||||
@@ -743,6 +767,10 @@
|
||||
"send": "6F48B70",
|
||||
"recv": "6F4C520"
|
||||
},
|
||||
"6.9.95-48517-arm64": {
|
||||
"send": "40A0438",
|
||||
"recv": "40A2D48"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "2F3B960",
|
||||
"recv": "2F3EEE0"
|
||||
@@ -763,13 +791,17 @@
|
||||
"send": "7342800",
|
||||
"recv": "73461B0"
|
||||
},
|
||||
"6.9.96-49738-arm64": {
|
||||
"send": "428B660",
|
||||
"recv": "428DF70"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "3155200",
|
||||
"recv": "3158788"
|
||||
},
|
||||
"9.9.32-50828-arm64": {
|
||||
"send": "4327764",
|
||||
"recv": "15E3184"
|
||||
"3.2.30-50828-arm64": {
|
||||
"send": "74C3070",
|
||||
"recv": "74C6A20"
|
||||
},
|
||||
"3.2.30-50828-x64": {
|
||||
"send": "B5D0FC0",
|
||||
@@ -786,5 +818,181 @@
|
||||
"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"
|
||||
},
|
||||
"6.9.98-51102-arm64": {
|
||||
"send": "4419468",
|
||||
"recv": "441BD78"
|
||||
},
|
||||
"9.9.32-51246-x64": {
|
||||
"send": "3199680",
|
||||
"recv": "319CC08"
|
||||
},
|
||||
"3.2.32-51728-arm64": {
|
||||
"send": "8009330",
|
||||
"recv": "800CCE0"
|
||||
},
|
||||
"3.2.32-51728-x64": {
|
||||
"send": "C6860E0",
|
||||
"recv": "C689B80"
|
||||
},
|
||||
"3.2.32-51802-x64": {
|
||||
"send": "C687460",
|
||||
"recv": "C68AF00"
|
||||
},
|
||||
"3.2.32-51802-arm64": {
|
||||
"send": "800A230",
|
||||
"recv": "800DBE0"
|
||||
},
|
||||
"6.9.99-51802-arm64": {
|
||||
"send": "499CF40",
|
||||
"recv": "499FA40"
|
||||
},
|
||||
"9.9.33-51802-x64": {
|
||||
"send": "360A0D8",
|
||||
"recv": "360D88C"
|
||||
},
|
||||
"9.9.33-52230-x64": {
|
||||
"send": "367FE18",
|
||||
"recv": "36835CC"
|
||||
},
|
||||
"3.2.32-52194-x64": {
|
||||
"send": "C7DBF80",
|
||||
"recv": "C7DFA20"
|
||||
},
|
||||
"3.2.32-52194-arm64": {
|
||||
"send": "80F36D0",
|
||||
"recv": "80F7080"
|
||||
},
|
||||
"7.0.0-52194-arm64": {
|
||||
"send": "4A05FB0",
|
||||
"recv": "4A08AB0"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"7.0.1-52892-arm64": {
|
||||
"send": "4B1E4B8",
|
||||
"recv": "4B20FB8"
|
||||
},
|
||||
"3.2.34-53644-x64": {
|
||||
"send": "CBF25A0",
|
||||
"recv": "CBF60E0"
|
||||
},
|
||||
"3.2.34-53644-arm64": {
|
||||
"send": "83D1BD0",
|
||||
"recv": "83D5610"
|
||||
},
|
||||
"7.0.2-53644-arm64": {
|
||||
"send": "4BA3870",
|
||||
"recv": "4BA6388"
|
||||
},
|
||||
"9.9.36-53644-x64": {
|
||||
"send": "38255F0",
|
||||
"recv": "3828E30"
|
||||
},
|
||||
"6.9.82-40768-x64": {
|
||||
"send": "489A168",
|
||||
"recv": "489CD18"
|
||||
},
|
||||
"6.9.82-40990-x64": {
|
||||
"send": "489A168",
|
||||
"recv": "489CD18"
|
||||
},
|
||||
"6.9.83-41679-x64": {
|
||||
"send": "450C8E0",
|
||||
"recv": "450F490"
|
||||
},
|
||||
"6.9.83-41785-x64": {
|
||||
"send": "450C540",
|
||||
"recv": "450F0F0"
|
||||
},
|
||||
"6.9.83-41857-x64": {
|
||||
"send": "450D998",
|
||||
"recv": "4510548"
|
||||
},
|
||||
"6.9.85-42086-x64": {
|
||||
"send": "450E430",
|
||||
"recv": "4510FE0"
|
||||
},
|
||||
"6.9.86-42744-x64": {
|
||||
"send": "4570018",
|
||||
"recv": "4572BC8"
|
||||
},
|
||||
"6.9.86-42905-x64": {
|
||||
"send": "457E7C0",
|
||||
"recv": "4581370"
|
||||
},
|
||||
"6.9.86-42941-x64": {
|
||||
"send": "457EA78",
|
||||
"recv": "4581628"
|
||||
},
|
||||
"6.9.87-44343-x64": {
|
||||
"send": "45126C0",
|
||||
"recv": "4515270"
|
||||
},
|
||||
"6.9.89-45758-x64": {
|
||||
"send": "478B860",
|
||||
"recv": "478E410"
|
||||
},
|
||||
"6.9.90-46494-x64": {
|
||||
"send": "47B8018",
|
||||
"recv": "47BABC8"
|
||||
},
|
||||
"6.9.91-46928-x64": {
|
||||
"send": "47B8018",
|
||||
"recv": "47BABC8"
|
||||
},
|
||||
"6.9.95-48517-x64": {
|
||||
"send": "48A92C0",
|
||||
"recv": "48ABE70"
|
||||
},
|
||||
"6.9.96-49738-x64": {
|
||||
"send": "4ACD9D8",
|
||||
"recv": "4AD0588"
|
||||
},
|
||||
"6.9.98-51102-x64": {
|
||||
"send": "4C953E8",
|
||||
"recv": "4C97F98"
|
||||
},
|
||||
"6.9.99-51802-x64": {
|
||||
"send": "5293B28",
|
||||
"recv": "52966D8"
|
||||
},
|
||||
"7.0.0-52194-x64": {
|
||||
"send": "53143C0",
|
||||
"recv": "5316F70"
|
||||
},
|
||||
"7.0.1-52892-x64": {
|
||||
"send": "54552F8",
|
||||
"recv": "5457EA8"
|
||||
},
|
||||
"7.0.2-53644-x64": {
|
||||
"send": "54F11F0",
|
||||
"recv": "54F3DA8"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,16 @@
|
||||
import fsPromise from 'fs/promises';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
|
||||
async function guessDuration (pttPath: string, logger: LogWrapper) {
|
||||
const pttFileInfo = await fsPromise.stat(pttPath);
|
||||
const duration = Math.max(1, Math.floor(pttFileInfo.size / 1024 / 3)); // 3kb/s
|
||||
logger.log('通过文件大小估算语音的时长:', duration);
|
||||
return duration;
|
||||
}
|
||||
|
||||
export async function encodeSilk (filePath: string, TEMP_DIR: string, logger: LogWrapper) {
|
||||
try {
|
||||
const pttPath = path.join(TEMP_DIR, randomUUID());
|
||||
if (!(await FFmpegService.isSilk(filePath))) {
|
||||
logger.log(`语音文件${filePath}需要转换成silk`);
|
||||
await FFmpegService.convertToNTSilkTct(filePath, pttPath);
|
||||
const duration = await FFmpegService.getDuration(filePath);
|
||||
logger.log(`语音文件${filePath}转换成功!`, pttPath, '时长:', duration);
|
||||
return {
|
||||
converted: true,
|
||||
path: pttPath,
|
||||
duration,
|
||||
};
|
||||
} else {
|
||||
let duration = 0;
|
||||
try {
|
||||
duration = await FFmpegService.getDuration(filePath);
|
||||
} catch (e: unknown) {
|
||||
logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, (e as Error).stack);
|
||||
duration = await guessDuration(filePath, logger);
|
||||
}
|
||||
return {
|
||||
converted: false,
|
||||
path: filePath,
|
||||
duration,
|
||||
};
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
logger.logError('convert silk failed', error);
|
||||
return {};
|
||||
export async function encodeSilk (filePath: string, temporaryDirectory: string, logger: LogWrapper) {
|
||||
const converted = !(await FFmpegService.isSilk(filePath));
|
||||
const pttPath = converted ? path.join(temporaryDirectory, randomUUID()) : filePath;
|
||||
if (converted) {
|
||||
logger.log(`语音文件${filePath}需要转换成silk`);
|
||||
await FFmpegService.convertToNTSilkTct(filePath, pttPath);
|
||||
}
|
||||
const duration = await FFmpegService.getDuration(pttPath);
|
||||
logger.log('语音文件已就绪:', pttPath, '时长:', duration);
|
||||
return { converted, path: pttPath, duration };
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
*/
|
||||
|
||||
import { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter';
|
||||
import { FFmpegAddonAdapter, getAddonPath } from './ffmpeg-addon-adapter';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
|
||||
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
|
||||
|
||||
@@ -58,8 +59,8 @@ export class FFmpegAdapterFactory {
|
||||
ffprobePath: string,
|
||||
binaryPath?: string
|
||||
): Promise<IFFmpegAdapter> {
|
||||
// 1. 优先尝试使用 Native Addon
|
||||
if (binaryPath) {
|
||||
const useCommandLine = Boolean(process.env['FFMPEG_PATH'] || process.env['FFPROBE_PATH']);
|
||||
if (binaryPath && !useCommandLine && existsSync(getAddonPath(binaryPath))) {
|
||||
const addonAdapter = new FFmpegAddonAdapter(binaryPath);
|
||||
|
||||
logger.log('[FFmpeg] 检查 Native Addon 可用性...');
|
||||
@@ -68,13 +69,10 @@ export class FFmpegAdapterFactory {
|
||||
return addonAdapter;
|
||||
}
|
||||
|
||||
logger.log('[FFmpeg] Native Addon 不可用,尝试使用命令行工具');
|
||||
} else {
|
||||
logger.log('[FFmpeg] 未提供 binaryPath,跳过 Native Addon 检测');
|
||||
throw new Error('FFmpeg Native Addon 加载失败: ' + getAddonPath(binaryPath));
|
||||
}
|
||||
|
||||
// 2. 降级到 execFile 实现
|
||||
const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath, binaryPath, logger);
|
||||
const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath);
|
||||
|
||||
logger.log(`[FFmpeg] 检查命令行工具可用性: ${ffmpegPath}`);
|
||||
if (await execAdapter.isAvailable()) {
|
||||
@@ -82,9 +80,7 @@ export class FFmpegAdapterFactory {
|
||||
return execAdapter;
|
||||
}
|
||||
|
||||
// 3. 都不可用,返回 execAdapter 但会在使用时报错
|
||||
logger.logError('[FFmpeg] 警告: FFmpeg 不可用,将使用命令行适配器但可能失败');
|
||||
return execAdapter;
|
||||
throw new Error('FFmpeg 命令行工具不可用,请检查 ffmpeg 和 ffprobe 路径: ' + ffmpegPath + ', ' + ffprobePath);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,20 +101,14 @@ export class FFmpegAdapterFactory {
|
||||
logger: LogWrapper,
|
||||
ffmpegPath: string,
|
||||
ffprobePath: string
|
||||
): Promise<void> {
|
||||
// 如果当前使用的是 Exec 适配器,更新路径
|
||||
if (this.instance && this.instance instanceof FFmpegExecAdapter) {
|
||||
logger.log(`[FFmpeg] 更新 FFmpeg 路径: ${ffmpegPath}`);
|
||||
this.instance.setFFmpegPath(ffmpegPath);
|
||||
this.instance.setFFprobePath(ffprobePath);
|
||||
|
||||
// 验证新路径是否可用
|
||||
if (await this.instance.isAvailable()) {
|
||||
logger.log('[FFmpeg] 新路径验证成功 ✓');
|
||||
} else {
|
||||
logger.logError('[FFmpeg] 警告: 新 FFmpeg 路径不可用');
|
||||
}
|
||||
): Promise<IFFmpegAdapter> {
|
||||
const adapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath);
|
||||
if (!await adapter.isAvailable()) {
|
||||
throw new Error('FFmpeg 路径不可用: ' + ffmpegPath + ', ' + ffprobePath);
|
||||
}
|
||||
this.instance = adapter;
|
||||
logger.log('[FFmpeg] 已更新命令行工具路径:', ffmpegPath, ffprobePath);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
* 使用原生 Node.js Addon 实现的 FFmpeg 适配器
|
||||
*/
|
||||
|
||||
import { platform, arch } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { existsSync, openSync, readSync, closeSync } from 'node:fs';
|
||||
import { openSync, readSync, closeSync } from 'node:fs';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import type { FFmpeg } from './ffmpeg-addon';
|
||||
import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface';
|
||||
@@ -15,15 +14,9 @@ import { dlopen } from 'node:process';
|
||||
* 获取 Native Addon 路径
|
||||
* @param binaryPath 二进制文件路径(来自 pathWrapper.binaryPath)
|
||||
*/
|
||||
function getAddonPath (binaryPath: string): string {
|
||||
const platformName = platform();
|
||||
const archName = arch();
|
||||
|
||||
export function getAddonPath (binaryPath: string): string {
|
||||
const addonFileName: string = process.platform + '.' + process.arch;
|
||||
const addonPath = path.join(binaryPath, './native/ffmpeg/', `ffmpegAddon.${addonFileName}.node`);
|
||||
if (!existsSync(addonPath)) {
|
||||
throw new Error(`Unsupported platform: ${platformName} ${archName} - Addon not found at ${addonPath}`);
|
||||
}
|
||||
return addonPath;
|
||||
}
|
||||
|
||||
@@ -130,9 +123,9 @@ export class FFmpegAddonAdapter implements IFFmpegAdapter {
|
||||
/**
|
||||
* 提取缩略图
|
||||
*/
|
||||
async extractThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
|
||||
async extractThumbnail (videoPath: string, thumbnailPath: string, format: 'jpg' | 'png' = 'jpg'): Promise<void> {
|
||||
const addon = this.ensureAddon();
|
||||
const info = await addon.getVideoInfo(videoPath);
|
||||
const info = await addon.getVideoInfo(videoPath, format);
|
||||
|
||||
// 将缩略图写入文件
|
||||
await writeFile(thumbnailPath, info.image);
|
||||
|
||||
@@ -53,7 +53,7 @@ export interface FFmpeg {
|
||||
/**
|
||||
* Get video information including resolution, duration, format, codec and first frame thumbnail
|
||||
*/
|
||||
getVideoInfo (filePath: string, format?: 'bmp' | 'bmp24'): Promise<VideoInfo>;
|
||||
getVideoInfo (filePath: string, format?: 'jpg' | 'png'): Promise<VideoInfo>;
|
||||
|
||||
/**
|
||||
* Get duration of audio or video file in seconds
|
||||
|
||||
@@ -3,14 +3,10 @@
|
||||
* 使用 execFile 调用 FFmpeg 命令行工具的适配器实现
|
||||
*/
|
||||
|
||||
import { readFileSync, existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs';
|
||||
import { dirname } from 'path';
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { fileTypeFromFile } from 'file-type';
|
||||
import { imageSizeFallBack } from 'napcat-image-size/src/index';
|
||||
import { downloadFFmpegIfNotExists } from './download-ffmpeg';
|
||||
import { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -30,52 +26,24 @@ function ensureDirExists (filePath: string): void {
|
||||
*/
|
||||
export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
public readonly name = 'FFmpegExec';
|
||||
private downloadAttempted = false;
|
||||
|
||||
constructor (
|
||||
private ffmpegPath: string = 'ffmpeg',
|
||||
private ffprobePath: string = 'ffprobe',
|
||||
private binaryPath?: string,
|
||||
private logger?: LogWrapper
|
||||
private ffprobePath: string = 'ffprobe'
|
||||
) { }
|
||||
|
||||
/**
|
||||
* 检查 FFmpeg 是否可用,如果不可用则尝试下载
|
||||
* 检查 FFmpeg 和 FFprobe 是否可用
|
||||
*/
|
||||
async isAvailable (): Promise<boolean> {
|
||||
// 首先检查当前路径
|
||||
try {
|
||||
await execFileAsync(this.ffmpegPath, ['-version']);
|
||||
await Promise.all([
|
||||
execFileAsync(this.ffmpegPath, ['-version'], { timeout: 10000, windowsHide: true }),
|
||||
execFileAsync(this.ffprobePath, ['-version'], { timeout: 10000, windowsHide: true }),
|
||||
]);
|
||||
return true;
|
||||
} catch {
|
||||
// 如果失败且未尝试下载,尝试下载
|
||||
if (!this.downloadAttempted && this.binaryPath && this.logger) {
|
||||
this.downloadAttempted = true;
|
||||
|
||||
if (process.env['NAPCAT_DISABLE_FFMPEG_DOWNLOAD']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.logger.log('[FFmpeg] 未找到可用的 FFmpeg,尝试自动下载...');
|
||||
const result = await downloadFFmpegIfNotExists(this.logger);
|
||||
|
||||
if (result.path && result.reset) {
|
||||
// 更新路径
|
||||
if (process.platform === 'win32') {
|
||||
this.ffmpegPath = join(result.path, 'ffmpeg.exe');
|
||||
this.ffprobePath = join(result.path, 'ffprobe.exe');
|
||||
this.logger.log('[FFmpeg] 已更新路径:', this.ffmpegPath);
|
||||
|
||||
// 再次检查
|
||||
try {
|
||||
await execFileAsync(this.ffmpegPath, ['-version']);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -98,40 +66,29 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
* 获取视频信息
|
||||
*/
|
||||
async getVideoInfo (videoPath: string): Promise<VideoInfoResult> {
|
||||
// 获取文件大小和类型
|
||||
const [fileType, duration] = await Promise.all([
|
||||
fileTypeFromFile(videoPath).catch(() => null),
|
||||
this.getDuration(videoPath).catch(() => 60),
|
||||
const [probe, frame] = await Promise.all([
|
||||
execFileAsync(this.ffprobePath, [
|
||||
'-v', 'error', '-select_streams', 'v:0',
|
||||
'-show_entries', 'stream=width,height:format=duration,format_name',
|
||||
'-of', 'json', videoPath,
|
||||
], { timeout: 30000, windowsHide: true }),
|
||||
execFileAsync(this.ffmpegPath, [
|
||||
'-v', 'error', '-i', videoPath, '-frames:v', '1',
|
||||
'-f', 'image2pipe', '-vcodec', 'mjpeg', 'pipe:1',
|
||||
], { encoding: 'buffer', maxBuffer: 16 * 1024 * 1024, timeout: 30000, windowsHide: true }),
|
||||
]);
|
||||
|
||||
// 创建临时缩略图路径
|
||||
const thumbnailPath = `${videoPath}.thumbnail.bmp`;
|
||||
let width = 100;
|
||||
let height = 100;
|
||||
let thumbnail: Buffer | undefined;
|
||||
|
||||
try {
|
||||
await this.extractThumbnail(videoPath, thumbnailPath);
|
||||
|
||||
// 获取图片尺寸
|
||||
const dimensions = await imageSizeFallBack(thumbnailPath);
|
||||
width = dimensions.width ?? 100;
|
||||
height = dimensions.height ?? 100;
|
||||
|
||||
// 读取缩略图
|
||||
if (existsSync(thumbnailPath)) {
|
||||
thumbnail = readFileSync(thumbnailPath);
|
||||
}
|
||||
} catch (_error) {
|
||||
// 使用默认值
|
||||
const metadata = JSON.parse(probe.stdout);
|
||||
const stream = metadata.streams[0];
|
||||
const duration = Number(metadata.format.duration);
|
||||
if (!stream || !Number.isFinite(duration) || duration < 0 || frame.stdout.length === 0) {
|
||||
throw new Error('FFmpeg 无法读取视频信息或首帧: ' + videoPath);
|
||||
}
|
||||
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
width: stream.width,
|
||||
height: stream.height,
|
||||
duration,
|
||||
format: fileType?.ext ?? 'mp4',
|
||||
thumbnail,
|
||||
format: metadata.format.format_name,
|
||||
thumbnail: frame.stdout,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -147,10 +104,10 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
'-of',
|
||||
'default=noprint_wrappers=1:nokey=1',
|
||||
filePath,
|
||||
]);
|
||||
], { timeout: 30000, windowsHide: true });
|
||||
|
||||
const duration = parseFloat(stdout.trim());
|
||||
if (isNaN(duration)) {
|
||||
if (!Number.isFinite(duration) || duration < 0) {
|
||||
throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`);
|
||||
}
|
||||
return duration;
|
||||
@@ -186,7 +143,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
'-ac', '1',
|
||||
'-f', 's16le',
|
||||
pcmPath,
|
||||
]);
|
||||
], { timeout: 120000, windowsHide: true });
|
||||
|
||||
if (!existsSync(pcmPath)) {
|
||||
throw new Error('转换PCM失败,输出文件不存在');
|
||||
@@ -207,25 +164,22 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
|
||||
const params = format === 'amr'
|
||||
? [
|
||||
'-f', 's16le',
|
||||
'-ar', '24000',
|
||||
'-ac', '1',
|
||||
'-i', inputFile,
|
||||
'-vn', '-ac', '1',
|
||||
'-ar', '8000',
|
||||
'-b:a', '12.2k',
|
||||
'-y',
|
||||
outputFile,
|
||||
]
|
||||
: [
|
||||
'-f', 's16le',
|
||||
'-ar', '24000',
|
||||
'-ac', '1',
|
||||
'-i', inputFile,
|
||||
'-vn', '-ac', '1',
|
||||
...(format === 'spx' ? ['-ar', '32000'] : []),
|
||||
'-y',
|
||||
outputFile,
|
||||
];
|
||||
|
||||
await execFileAsync(this.ffmpegPath, params);
|
||||
await execFileAsync(this.ffmpegPath, params, { timeout: 120000, windowsHide: true });
|
||||
|
||||
if (!existsSync(outputFile)) {
|
||||
throw new Error('转换失败,输出文件不存在');
|
||||
@@ -245,11 +199,10 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
|
||||
const { stderr } = await execFileAsync(this.ffmpegPath, [
|
||||
'-i', videoPath,
|
||||
'-ss', '00:00:01.000',
|
||||
'-vframes', '1',
|
||||
'-y', // 覆盖输出文件
|
||||
thumbnailPath,
|
||||
]);
|
||||
], { timeout: 30000, windowsHide: true });
|
||||
|
||||
if (!existsSync(thumbnailPath)) {
|
||||
throw new Error(`提取缩略图失败,输出文件不存在: ${stderr}`);
|
||||
@@ -260,7 +213,11 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
async convertToNTSilkTct (_inputFile: string, _outputFile: string): Promise<void> {
|
||||
throw new Error('convertToNTSilkTct is not implemented in FFmpegExecAdapter');
|
||||
async convertToNTSilkTct (inputFile: string, outputFile: string): Promise<void> {
|
||||
ensureDirExists(outputFile);
|
||||
await execFileAsync(this.ffmpegPath, [
|
||||
'-v', 'error', '-y', '-i', inputFile, '-vn', '-ac', '1', '-ar', '24000',
|
||||
'-c:a', 'ntsilk_s16le', '-f', 'ntsilk_s16le', outputFile,
|
||||
], { timeout: 120000, windowsHide: true });
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,29 @@
|
||||
import { statSync, existsSync, writeFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import type { VideoInfo } from './video';
|
||||
import { fileTypeFromFile } from 'file-type';
|
||||
import { platform } from 'node:os';
|
||||
import { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory';
|
||||
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
|
||||
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
|
||||
import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter';
|
||||
|
||||
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
|
||||
if (process.platform === 'win32' && binaryPath) {
|
||||
const exeName = `${tool}.exe`;
|
||||
const localPath = path.join(binaryPath, 'ffmpeg', exeName);
|
||||
const isLocalExeExists = existsSync(localPath);
|
||||
return isLocalExeExists ? localPath : exeName;
|
||||
export const getFFmpegPath = (tool: 'ffmpeg' | 'ffprobe', binaryPath?: string): string => {
|
||||
const configuredPath = process.env[tool === 'ffmpeg' ? 'FFMPEG_PATH' : 'FFPROBE_PATH'];
|
||||
if (configuredPath) return configuredPath;
|
||||
const executable = tool + (process.platform === 'win32' ? '.exe' : '');
|
||||
if (binaryPath) {
|
||||
const localPath = path.join(binaryPath, 'ffmpeg', executable);
|
||||
if (existsSync(localPath)) return localPath;
|
||||
}
|
||||
return tool;
|
||||
if (process.platform === 'darwin') {
|
||||
const directories = (process.env['PATH'] ?? '').split(':').filter(Boolean);
|
||||
directories.push(process.arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin');
|
||||
for (const directory of directories) {
|
||||
const candidate = path.join(directory, executable);
|
||||
if (existsSync(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
return executable;
|
||||
};
|
||||
|
||||
export let FFMPEG_CMD = 'ffmpeg';
|
||||
@@ -23,6 +31,7 @@ export let FFPROBE_CMD = 'ffprobe';
|
||||
export class FFmpegService {
|
||||
private static adapter: IFFmpegAdapter | null = null;
|
||||
private static initialized = false;
|
||||
private static initializationError: unknown;
|
||||
|
||||
/**
|
||||
* 初始化 FFmpeg 服务
|
||||
@@ -38,20 +47,24 @@ export class FFmpegService {
|
||||
FFMPEG_CMD = getFFmpegPath('ffmpeg', binaryPath);
|
||||
FFPROBE_CMD = getFFmpegPath('ffprobe', binaryPath);
|
||||
|
||||
// 立即初始化适配器(会触发自动下载等逻辑)
|
||||
this.adapter = await FFmpegAdapterFactory.getAdapter(
|
||||
logger,
|
||||
FFMPEG_CMD,
|
||||
FFPROBE_CMD,
|
||||
binaryPath
|
||||
);
|
||||
try {
|
||||
this.adapter = await FFmpegAdapterFactory.getAdapter(
|
||||
logger,
|
||||
FFMPEG_CMD,
|
||||
FFPROBE_CMD,
|
||||
binaryPath
|
||||
);
|
||||
} catch (error) {
|
||||
this.initializationError = error;
|
||||
logger.logError('[FFmpeg] 媒体功能初始化失败:', error);
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
public static getAdapterName (): string {
|
||||
if (!this.adapter) {
|
||||
throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
|
||||
throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
|
||||
}
|
||||
return this.adapter.name;
|
||||
}
|
||||
@@ -61,7 +74,7 @@ export class FFmpegService {
|
||||
*/
|
||||
private static async getAdapter (): Promise<IFFmpegAdapter> {
|
||||
if (!this.adapter) {
|
||||
throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
|
||||
throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
|
||||
}
|
||||
return this.adapter;
|
||||
}
|
||||
@@ -76,15 +89,14 @@ export class FFmpegService {
|
||||
* @deprecated 建议使用 init() 方法初始化
|
||||
*/
|
||||
public static async setFfmpegPath (ffmpegPath: string, logger: LogWrapper): Promise<void> {
|
||||
if (platform() === 'win32') {
|
||||
FFMPEG_CMD = path.join(ffmpegPath, 'ffmpeg.exe');
|
||||
FFPROBE_CMD = path.join(ffmpegPath, 'ffprobe.exe');
|
||||
logger.log('[Check] ffmpeg:', FFMPEG_CMD);
|
||||
logger.log('[Check] ffprobe:', FFPROBE_CMD);
|
||||
|
||||
// 更新适配器路径
|
||||
await FFmpegAdapterFactory.updateFFmpegPath(logger, FFMPEG_CMD, FFPROBE_CMD);
|
||||
}
|
||||
const suffix = process.platform === 'win32' ? '.exe' : '';
|
||||
const ffmpegCommand = path.join(ffmpegPath, 'ffmpeg' + suffix);
|
||||
const ffprobeCommand = path.join(ffmpegPath, 'ffprobe' + suffix);
|
||||
this.adapter = await FFmpegAdapterFactory.updateFFmpegPath(logger, ffmpegCommand, ffprobeCommand);
|
||||
FFMPEG_CMD = ffmpegCommand;
|
||||
FFPROBE_CMD = ffprobeCommand;
|
||||
this.initializationError = undefined;
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,6 +112,11 @@ export class FFmpegService {
|
||||
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
|
||||
*/
|
||||
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
|
||||
const currentAdapter = await this.getAdapter();
|
||||
if (currentAdapter instanceof FFmpegAddonAdapter) {
|
||||
await currentAdapter.extractThumbnail(videoPath, thumbnailPath, 'png');
|
||||
return;
|
||||
}
|
||||
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
|
||||
await adapter.extractThumbnail(videoPath, thumbnailPath);
|
||||
}
|
||||
@@ -142,41 +159,18 @@ export class FFmpegService {
|
||||
public static async getVideoInfo (videoPath: string, thumbnailPath: string): Promise<VideoInfo> {
|
||||
const adapter = await this.getAdapter();
|
||||
|
||||
try {
|
||||
// 获取文件大小
|
||||
const fileSize = statSync(videoPath).size;
|
||||
|
||||
// 使用适配器获取视频信息
|
||||
const videoInfo = await adapter.getVideoInfo(videoPath);
|
||||
|
||||
// 如果提供了缩略图路径且适配器返回了缩略图,保存到指定路径
|
||||
if (thumbnailPath && videoInfo.thumbnail) {
|
||||
writeFileSync(thumbnailPath, videoInfo.thumbnail);
|
||||
}
|
||||
|
||||
const result: VideoInfo = {
|
||||
width: videoInfo.width,
|
||||
height: videoInfo.height,
|
||||
time: videoInfo.duration,
|
||||
format: videoInfo.format,
|
||||
size: fileSize,
|
||||
filePath: videoPath,
|
||||
};
|
||||
|
||||
return result;
|
||||
} catch (_error) {
|
||||
// 降级处理:返回默认值
|
||||
const fileType = await fileTypeFromFile(videoPath).catch(() => null);
|
||||
const fileSize = statSync(videoPath).size;
|
||||
|
||||
return {
|
||||
width: 100,
|
||||
height: 100,
|
||||
time: 60,
|
||||
format: fileType?.ext ?? 'mp4',
|
||||
size: fileSize,
|
||||
filePath: videoPath,
|
||||
};
|
||||
const fileSize = statSync(videoPath).size;
|
||||
const videoInfo = await adapter.getVideoInfo(videoPath);
|
||||
if (thumbnailPath && videoInfo.thumbnail) {
|
||||
writeFileSync(thumbnailPath, videoInfo.thumbnail);
|
||||
}
|
||||
return {
|
||||
width: videoInfo.width,
|
||||
height: videoInfo.height,
|
||||
time: videoInfo.duration,
|
||||
format: videoInfo.format,
|
||||
size: fileSize,
|
||||
filePath: videoPath,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,8 @@ export class NativePacketClient {
|
||||
}
|
||||
|
||||
async init (_pid: number, recv: string, send: string): Promise<void> {
|
||||
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
|
||||
this.available = false;
|
||||
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40768');
|
||||
if (!isNewQQ) {
|
||||
this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化');
|
||||
return;
|
||||
@@ -77,8 +78,9 @@ export class NativePacketClient {
|
||||
data: (ret as { rspbuffer: Buffer; }).rspbuffer,
|
||||
}));
|
||||
|
||||
let timeoutHandle: ReturnType<typeof setTimeout>;
|
||||
const timeoutPromise = new Promise<RecvPacketData>((_resolve, reject) => {
|
||||
setTimeout(
|
||||
timeoutHandle = setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new Error(
|
||||
@@ -89,7 +91,11 @@ export class NativePacketClient {
|
||||
);
|
||||
});
|
||||
|
||||
return Promise.race([sendPromise, timeoutPromise]);
|
||||
try {
|
||||
return await Promise.race([sendPromise, timeoutPromise]);
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle!);
|
||||
}
|
||||
}
|
||||
|
||||
async sendOidbPacket (pkt: OidbPacket, rsp = false, timeout = 5000): Promise<RecvPacketData> {
|
||||
|
||||
@@ -14,7 +14,7 @@ interface OffsetType {
|
||||
const typedOffset: OffsetType = offset;
|
||||
// 0 send 1 recv
|
||||
export interface NativePacketExportType {
|
||||
initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => boolean;
|
||||
initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => string;
|
||||
}
|
||||
|
||||
export type PacketType = 0 | 1; // 0: send, 1: recv
|
||||
@@ -38,10 +38,15 @@ export class NativePacketHandler {
|
||||
this.logger = logger;
|
||||
try {
|
||||
const platform = process.platform + '.' + process.arch;
|
||||
if (!this.supportedPlatforms.includes(platform)) {
|
||||
this.logger.logWarn(`NativePacketClient: 不支持的平台: ${platform}`);
|
||||
return;
|
||||
}
|
||||
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './native/packet/MoeHoo.' + platform + '.node');
|
||||
if (!fs.existsSync(moehoo_path)) {
|
||||
this.logger.logWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`);
|
||||
this.loaded = false;
|
||||
return;
|
||||
}
|
||||
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
|
||||
this.loaded = true;
|
||||
@@ -213,9 +218,13 @@ export class NativePacketHandler {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
|
||||
const result = this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
|
||||
this.emitPacket(type, uin, cmd, seq, hex_data);
|
||||
}, o3HookMode);
|
||||
if (result !== 'success') {
|
||||
this.logger.logError(`[PacketHandler] 初始化失败: ${result}`);
|
||||
return false;
|
||||
}
|
||||
this.logger.log('[PacketHandler] 初始化成功');
|
||||
return true;
|
||||
} catch (error) {
|
||||
|
||||
@@ -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>();
|
||||
@@ -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';
|
||||
@@ -213,30 +214,39 @@ export async function NCoreInitFramework (
|
||||
}
|
||||
}
|
||||
|
||||
// 监听下线通知并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
|
||||
let restartRequested = false;
|
||||
loaderObject.core.event.on('KickedOffLine', (tips: string) => {
|
||||
WebUiDataRuntime.setQQLoginStatus(false);
|
||||
WebUiDataRuntime.setQQLoginQrcodeURL('');
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
WebUiDataRuntime.setQQLoginPhase('reconnecting');
|
||||
if (restartRequested) return;
|
||||
restartRequested = true;
|
||||
setTimeout(() => {
|
||||
WebUiDataRuntime.requestRestartProcess().then((restartResult) => {
|
||||
logger.logWarn('[NapCat] [Framework] 账号被踢下线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
|
||||
if (!restartResult.result) {
|
||||
restartRequested = false;
|
||||
WebUiDataRuntime.setQQLoginPhase('offline');
|
||||
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
|
||||
}
|
||||
}).catch((error) => {
|
||||
restartRequested = false;
|
||||
// 监听下线并同步到 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}`);
|
||||
});
|
||||
}, 3_500);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
loaderObject.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
|
||||
loaderObject.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
|
||||
}
|
||||
|
||||
function registerWebUiLoginCallbacks (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { pathToFileURL } = require('url');
|
||||
|
||||
async function initializeNapCat (session, loginService, registerCallback) {
|
||||
// const logFile = path.join(currentPath, 'napcat.log');
|
||||
@@ -12,7 +13,7 @@ async function initializeNapCat (session, loginService, registerCallback) {
|
||||
|
||||
try {
|
||||
const currentPath = path.dirname(__filename);
|
||||
const { NCoreInitFramework } = await import('file://' + path.join(currentPath, './napcat.mjs'));
|
||||
const { NCoreInitFramework } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
|
||||
await NCoreInitFramework(session, loginService, (callback) => { registerCallback(callback); });
|
||||
} catch (error) {
|
||||
console.log('[NapCat] [Error] 初始化NapCat', error);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
chcp 65001
|
||||
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
|
||||
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
|
||||
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
|
||||
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
|
||||
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
|
||||
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
|
||||
set NAPCAT_DEBUG_CONSOLE=1
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
@@ -27,4 +29,4 @@ set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
|
||||
|
||||
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
|
||||
|
||||
pause
|
||||
pause
|
||||
@@ -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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import path from 'node:path';
|
||||
import { DEFAULT_FLASH_VALIDITY_SECONDS } from '@/napcat-core/data/flash';
|
||||
|
||||
const richMediaList = [
|
||||
'.mp4', '.mov', '.avi', '.wmv', '.mpeg', '.mpg', '.flv', '.mkv',
|
||||
@@ -15,6 +16,7 @@ export const CreateFlashTaskPayloadSchema = Type.Object({
|
||||
], { description: '文件列表或单个文件路径' }),
|
||||
name: Type.Optional(Type.String({ description: '任务名称' })),
|
||||
thumb_path: Type.Optional(Type.String({ description: '缩略图路径' })),
|
||||
validitySeconds: Type.Optional(Type.Number({ description: '文件集有效期(秒),可选 14 天 1209600 / 90 天 7776000 / 180 天 15552000,默认 1209600' })),
|
||||
});
|
||||
export type CreateFlashTaskPayload = Static<typeof CreateFlashTaskPayloadSchema>;
|
||||
|
||||
@@ -27,6 +29,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
|
||||
override payloadExample = {
|
||||
files: 'C:\\test.jpg',
|
||||
name: 'test_task',
|
||||
validitySeconds: DEFAULT_FLASH_VALIDITY_SECONDS,
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
@@ -67,6 +70,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
|
||||
} else {
|
||||
normalPath = toPlatformPath(thumbPath);
|
||||
}
|
||||
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList, normalPath, payload.name || '');
|
||||
const validitySeconds = payload.validitySeconds ?? DEFAULT_FLASH_VALIDITY_SECONDS;
|
||||
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList, normalPath, payload.name || '', validitySeconds);
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -134,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';
|
||||
@@ -182,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),
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -385,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 {
|
||||
@@ -1141,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;
|
||||
@@ -1165,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 {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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; // 最后修改者名称
|
||||
}
|
||||
@@ -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.
@@ -1,10 +1,12 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
chcp 65001 >nul
|
||||
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
|
||||
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
|
||||
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
|
||||
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
|
||||
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
|
||||
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
|
||||
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
|
||||
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
|
||||
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
|
||||
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
set "RetString=%%~b"
|
||||
@@ -24,9 +26,6 @@ if not exist "%QQpath%" (
|
||||
exit /b
|
||||
)
|
||||
|
||||
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
|
||||
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
|
||||
|
||||
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
|
||||
|
||||
pause
|
||||
@@ -1,10 +1,12 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
chcp 65001 >nul
|
||||
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
|
||||
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
|
||||
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
|
||||
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
|
||||
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
|
||||
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
|
||||
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
|
||||
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
|
||||
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
|
||||
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
set "RetString=%%~b"
|
||||
@@ -23,9 +25,6 @@ if not exist "%QQpath%" (
|
||||
pause
|
||||
exit /b
|
||||
)
|
||||
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
|
||||
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
|
||||
|
||||
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
|
||||
|
||||
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
chcp 65001 >nul
|
||||
net session >nul 2>&1
|
||||
if %ERRORLEVEL% == 0 (
|
||||
@@ -9,11 +11,11 @@ if %ERRORLEVEL% == 0 (
|
||||
exit
|
||||
)
|
||||
|
||||
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
|
||||
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
|
||||
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
|
||||
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
|
||||
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
|
||||
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
|
||||
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
|
||||
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
|
||||
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
|
||||
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
set "RetString=%%~b"
|
||||
@@ -32,9 +34,6 @@ if not exist "%QQPath%" (
|
||||
pause
|
||||
exit /b
|
||||
)
|
||||
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
|
||||
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
|
||||
|
||||
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
|
||||
|
||||
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0" || exit /b 1
|
||||
chcp 65001 >nul
|
||||
net session >nul 2>&1
|
||||
if %ERRORLEVEL% == 0 (
|
||||
@@ -9,11 +11,11 @@ if %ERRORLEVEL% == 0 (
|
||||
exit
|
||||
)
|
||||
|
||||
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
|
||||
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
|
||||
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
|
||||
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
|
||||
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
|
||||
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
|
||||
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
|
||||
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
|
||||
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
|
||||
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
set "RetString=%%~b"
|
||||
@@ -33,7 +35,4 @@ if not exist "%QQPath%" (
|
||||
exit /b
|
||||
)
|
||||
|
||||
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
|
||||
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
|
||||
|
||||
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
|
||||
@@ -1,5 +1,6 @@
|
||||
const path = require('path');
|
||||
const CurrentPath = path.dirname(__filename);
|
||||
const { pathToFileURL } = require('url');
|
||||
const mainPath = process.env.NAPCAT_MAIN_PATH || path.join(__dirname, 'napcat.mjs');
|
||||
(async () => {
|
||||
await import('file://' + path.join(CurrentPath, './napcat/napcat.mjs'));
|
||||
await import(pathToFileURL(mainPath).href);
|
||||
})();
|
||||
@@ -37,6 +37,7 @@ import { OidbSvcTrpcTcpBase, OidbSvcTrpcTcp0XCDE_2RespBody } from '@/napcat-core
|
||||
import { loadNapcatConfig } from '@/napcat-core/helper/config';
|
||||
import { logSubscription, LogWrapper } from '@/napcat-core/helper/log';
|
||||
import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
|
||||
import { createOfflineRecovery } from '@/napcat-core/helper/offline-recovery';
|
||||
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
|
||||
import { statusHelperSubscription } from '@/napcat-core/helper/status';
|
||||
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
|
||||
@@ -839,36 +840,39 @@ export class NapCatShell {
|
||||
// }
|
||||
// }
|
||||
|
||||
// 监听下线通知并同步到 WebUI
|
||||
let restartRequested = false;
|
||||
this.core.event.on('KickedOffLine', (tips: string) => {
|
||||
WebUiDataRuntime.setQQLoginStatus(false);
|
||||
// 被踢后的二维码已失效,绝不能继续交给页面展示或扫码。
|
||||
WebUiDataRuntime.setQQLoginQrcodeURL('');
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
WebUiDataRuntime.setQQLoginPhase('reconnecting');
|
||||
|
||||
if (restartRequested) return;
|
||||
restartRequested = true;
|
||||
// 不从 RefreshQRcode 请求中重启 Worker;否则请求会在返回前被中断,
|
||||
// 浏览器只能得到 ERR_EMPTY_RESPONSE。KickedOffLine 是独立事件,
|
||||
// 在此异步调度可让前端先观察到“二维码已清空、正在恢复”的状态。
|
||||
setTimeout(() => {
|
||||
WebUiDataRuntime.requestRestartProcess().then((restartResult) => {
|
||||
this.context.logger.logWarn('[Core] [Login] 账号被踢下线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
|
||||
if (!restartResult.result) {
|
||||
restartRequested = false;
|
||||
WebUiDataRuntime.setQQLoginPhase('offline');
|
||||
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
|
||||
}
|
||||
}).catch((error) => {
|
||||
restartRequested = false;
|
||||
// 监听下线并同步到 WebUI
|
||||
// KickedOffLine:账号被踢下线;SelfOffline:静默离线(服务端会话语义失效但无通知)。
|
||||
// 两者复用同一条恢复链路:同步 WebUI -> 重启 Worker -> 快速登录。
|
||||
const handleOffline = createOfflineRecovery({
|
||||
isOnline: () => this.core.selfInfo.online === true,
|
||||
onOffline: (tips) => {
|
||||
WebUiDataRuntime.setQQLoginStatus(false);
|
||||
// 下线后的二维码已失效,绝不能继续交给页面展示或扫码。
|
||||
WebUiDataRuntime.setQQLoginQrcodeURL('');
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
WebUiDataRuntime.setQQLoginPhase('reconnecting');
|
||||
},
|
||||
onRecovered: () => {
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
WebUiDataRuntime.setQQLoginPhase('ready');
|
||||
},
|
||||
restart: async (tips) => {
|
||||
try {
|
||||
const restartResult = await WebUiDataRuntime.requestRestartProcess();
|
||||
this.context.logger.logWarn('[Core] [Login] 账号已离线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
|
||||
if (restartResult.result) return true;
|
||||
WebUiDataRuntime.setQQLoginPhase('offline');
|
||||
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
|
||||
} catch (error) {
|
||||
WebUiDataRuntime.setQQLoginPhase('offline');
|
||||
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
|
||||
});
|
||||
// 常规状态轮询为 3 秒;留出一个轮询周期,确保浏览器先清除旧二维码。
|
||||
}, 3_500);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
this.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
|
||||
this.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
|
||||
// 使用 NapCatAdapterManager 统一管理协议适配器
|
||||
const adapterManager = new NapCatAdapterManager(this.core, this.context, this.context.pathWrapper);
|
||||
await adapterManager.initAdapters()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { encodeSilk } from '@/napcat-core/helper/audio';
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import type { LogWrapper } from '@/napcat-core/helper/log';
|
||||
|
||||
vi.mock('@/napcat-core/helper/ffmpeg/ffmpeg', () => ({
|
||||
FFmpegService: { isSilk: vi.fn(), convertToNTSilkTct: vi.fn(), getDuration: vi.fn() },
|
||||
}));
|
||||
|
||||
const logger = { log: vi.fn() } as unknown as LogWrapper;
|
||||
|
||||
beforeEach(() => vi.resetAllMocks());
|
||||
|
||||
describe('SILK encoding', () => {
|
||||
it('reads duration from the encoded output including the final packet', async () => {
|
||||
vi.mocked(FFmpegService.isSilk).mockResolvedValue(false);
|
||||
vi.mocked(FFmpegService.getDuration).mockResolvedValue(0.02);
|
||||
const result = await encodeSilk('/short.wav', '/temp', logger);
|
||||
expect(result.converted).toBe(true);
|
||||
expect(FFmpegService.convertToNTSilkTct).toHaveBeenCalledWith('/short.wav', result.path);
|
||||
expect(FFmpegService.getDuration).toHaveBeenCalledWith(result.path);
|
||||
expect(result.duration).toBe(0.02);
|
||||
});
|
||||
|
||||
it('propagates a corrupt SILK error without estimating its duration', async () => {
|
||||
vi.mocked(FFmpegService.isSilk).mockResolvedValue(true);
|
||||
vi.mocked(FFmpegService.getDuration).mockRejectedValue(new Error('corrupt SILK packet'));
|
||||
await expect(encodeSilk('/corrupt.silk', '/temp', logger)).rejects.toThrow('corrupt SILK packet');
|
||||
expect(FFmpegService.convertToNTSilkTct).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('propagates conversion errors to the caller', async () => {
|
||||
vi.mocked(FFmpegService.isSilk).mockResolvedValue(false);
|
||||
vi.mocked(FFmpegService.convertToNTSilkTct).mockRejectedValue(new Error('encoder unavailable'));
|
||||
await expect(encodeSilk('/audio.wav', '/temp', logger)).rejects.toThrow('encoder unavailable');
|
||||
expect(FFmpegService.getDuration).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
|
||||
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
|
||||
import '../napcat-onebot/action/stream/StreamBasic';
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { MessageUnique } from '../napcat-common/src/message-unique';
|
||||
import DelEssenceMsg from '../napcat-onebot/action/group/DelEssenceMsg';
|
||||
|
||||
function createAction (essenceLRUValue: string | undefined) {
|
||||
const removeGroupEssenceBySeq = vi.fn().mockResolvedValue({ result: 0 });
|
||||
const action = new DelEssenceMsg(
|
||||
undefined as never,
|
||||
{
|
||||
apis: {
|
||||
GroupApi: {
|
||||
essenceLRU: { getValue: vi.fn().mockReturnValue(essenceLRUValue) },
|
||||
removeGroupEssenceBySeq,
|
||||
},
|
||||
},
|
||||
} as never
|
||||
);
|
||||
return { action, removeGroupEssenceBySeq };
|
||||
}
|
||||
|
||||
describe('delete_essence_msg argument order', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('passes msg_random before msg_seq for explicitly supplied parameters', async () => {
|
||||
const { action, removeGroupEssenceBySeq } = createAction(undefined);
|
||||
|
||||
await action._handle({ group_id: '33', msg_seq: '11', msg_random: '22' });
|
||||
|
||||
// GroupApi.removeGroupEssenceBySeq(groupCode, msgRandom, msgSeq)
|
||||
expect(removeGroupEssenceBySeq).toHaveBeenCalledWith('33', '22', '11');
|
||||
});
|
||||
|
||||
test('passes msg_random before msg_seq for the essence LRU fallback', async () => {
|
||||
// get_essence_msg_list stores this payload under a synthetic message_id when the
|
||||
// original message can no longer be resolved from the local message cache.
|
||||
const { action, removeGroupEssenceBySeq } = createAction(JSON.stringify({
|
||||
msg_seq: '11',
|
||||
msg_random: '22',
|
||||
group_id: '33',
|
||||
}));
|
||||
vi.spyOn(MessageUnique, 'getMsgIdAndPeerByShortId').mockReturnValue(undefined);
|
||||
|
||||
await action._handle({ message_id: 12345 });
|
||||
|
||||
// GroupApi.removeGroupEssenceBySeq(groupCode, msgRandom, msgSeq)
|
||||
expect(removeGroupEssenceBySeq).toHaveBeenCalledWith('33', '22', '11');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import path from 'node:path';
|
||||
import { FFmpegAdapterFactory } from '@/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory';
|
||||
import { FFmpegAddonAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter';
|
||||
import { FFmpegExecAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter';
|
||||
import { FFmpegService, getFFmpegPath } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import type { LogWrapper } from '@/napcat-core/helper/log';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
execute: vi.fn(),
|
||||
dlopen: vi.fn(),
|
||||
exists: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('fs')>();
|
||||
return { ...original, existsSync: mocks.exists };
|
||||
});
|
||||
|
||||
vi.mock('child_process', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('child_process')>();
|
||||
return {
|
||||
...original,
|
||||
execFile: Object.assign(vi.fn(), {
|
||||
[Symbol.for('nodejs.util.promisify.custom')]: mocks.execute,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('node:process', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('node:process')>();
|
||||
return { ...original, dlopen: mocks.dlopen };
|
||||
});
|
||||
|
||||
const logger = { log: vi.fn(), logError: vi.fn() } as unknown as LogWrapper;
|
||||
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
|
||||
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
|
||||
|
||||
beforeEach(() => {
|
||||
FFmpegAdapterFactory.reset();
|
||||
vi.stubEnv('FFMPEG_PATH', '');
|
||||
vi.stubEnv('FFPROBE_PATH', '');
|
||||
mocks.execute.mockReset().mockResolvedValue({ stdout: '', stderr: '' });
|
||||
mocks.dlopen.mockReset();
|
||||
mocks.exists.mockReset().mockReturnValue(false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
Object.defineProperty(process, 'platform', platformDescriptor);
|
||||
Object.defineProperty(process, 'arch', archDescriptor);
|
||||
});
|
||||
|
||||
describe('FFmpeg platform paths', () => {
|
||||
it.each(['arm64', 'x64'])('finds Homebrew for macOS %s outside GUI PATH', (arch) => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
Object.defineProperty(process, 'arch', { value: arch });
|
||||
vi.stubEnv('PATH', '/usr/bin:/bin');
|
||||
const prefix = arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin';
|
||||
mocks.exists.mockImplementation(candidate => String(candidate).startsWith(path.join(prefix)));
|
||||
expect(getFFmpegPath('ffmpeg')).toBe(path.join(prefix, 'ffmpeg'));
|
||||
expect(getFFmpegPath('ffprobe')).toBe(path.join(prefix, 'ffprobe'));
|
||||
});
|
||||
|
||||
it('preserves explicit paths containing spaces without searching alternatives', () => {
|
||||
vi.stubEnv('FFMPEG_PATH', '/private/My Tools/ffmpeg');
|
||||
vi.stubEnv('FFPROBE_PATH', '/private/My Tools/ffprobe');
|
||||
const exists = mocks.exists.mockReturnValue(true);
|
||||
expect(getFFmpegPath('ffmpeg', '/app')).toBe('/private/My Tools/ffmpeg');
|
||||
expect(getFFmpegPath('ffprobe', '/app')).toBe('/private/My Tools/ffprobe');
|
||||
expect(exists).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses packaged Windows executables before PATH', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32' });
|
||||
mocks.exists.mockReturnValue(true);
|
||||
expect(getFFmpegPath('ffmpeg', '/app')).toBe(path.join('/app', 'ffmpeg', 'ffmpeg.exe'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('FFmpeg adapter selection', () => {
|
||||
it.each(['arm64', 'x64'])('loads the packaged macOS %s addon', async (arch) => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
Object.defineProperty(process, 'arch', { value: arch });
|
||||
mocks.exists.mockReturnValue(true);
|
||||
mocks.dlopen.mockImplementation(module => { module.exports = {}; });
|
||||
const adapter = await FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app');
|
||||
expect(adapter.name).toBe('FFmpegAddon');
|
||||
expect(mocks.dlopen).toHaveBeenCalledWith(expect.anything(), path.join('/app', 'native/ffmpeg', 'ffmpegAddon.darwin.' + arch + '.node'));
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not hide a broken packaged addon behind another adapter', async () => {
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
mocks.exists.mockReturnValue(true);
|
||||
mocks.dlopen.mockImplementation(() => { throw new Error('wrong architecture'); });
|
||||
await expect(FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app')).rejects.toThrow('Native Addon');
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull();
|
||||
});
|
||||
|
||||
it('honors an explicit command line configuration', async () => {
|
||||
vi.stubEnv('FFMPEG_PATH', '/tools/ffmpeg');
|
||||
mocks.exists.mockReturnValue(true);
|
||||
const adapter = await FFmpegAdapterFactory.getAdapter(logger, '/tools/ffmpeg', '/tools/ffprobe', '/app');
|
||||
expect(adapter.name).toBe('FFmpegExec');
|
||||
expect(mocks.dlopen).not.toHaveBeenCalled();
|
||||
expect(mocks.execute).toHaveBeenCalledWith('/tools/ffmpeg', ['-version'], expect.objectContaining({ timeout: 10000 }));
|
||||
expect(mocks.execute).toHaveBeenCalledWith('/tools/ffprobe', ['-version'], expect.objectContaining({ timeout: 10000 }));
|
||||
});
|
||||
|
||||
it('rejects a missing ffprobe and allows a corrected configuration', async () => {
|
||||
mocks.exists.mockReturnValue(false);
|
||||
mocks.execute.mockImplementation(async command => {
|
||||
if (command === 'ffprobe') throw new Error('ENOENT');
|
||||
return { stdout: '', stderr: '' };
|
||||
});
|
||||
await expect(FFmpegAdapterFactory.getAdapter(logger)).rejects.toThrow('ffprobe');
|
||||
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull();
|
||||
mocks.execute.mockResolvedValue({ stdout: '', stderr: '' });
|
||||
expect((await FFmpegAdapterFactory.getAdapter(logger)).name).toBe('FFmpegExec');
|
||||
});
|
||||
|
||||
it('validates replacement paths before changing the active adapter', async () => {
|
||||
const adapter = await FFmpegAdapterFactory.getAdapter(logger);
|
||||
mocks.execute.mockRejectedValue(new Error('EACCES'));
|
||||
await expect(FFmpegAdapterFactory.updateFFmpegPath(logger, '/bad/ffmpeg', '/bad/ffprobe')).rejects.toThrow('/bad/ffprobe');
|
||||
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBe(adapter);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FFmpeg media operations', () => {
|
||||
it('transcodes encoded audio without treating its bytes as raw PCM', async () => {
|
||||
mocks.exists.mockReturnValue(true);
|
||||
await new FFmpegExecAdapter().convertFile('/record.wav', '/record.mp3', 'mp3');
|
||||
expect(mocks.execute).toHaveBeenCalledWith('ffmpeg', [
|
||||
'-i', '/record.wav', '-vn', '-ac', '1', '-y', '/record.mp3',
|
||||
], expect.objectContaining({ timeout: 120000, windowsHide: true }));
|
||||
});
|
||||
|
||||
it('reports a corrupt video instead of inventing dimensions and duration', async () => {
|
||||
mocks.execute.mockRejectedValue(new Error('invalid video'));
|
||||
await expect(new FFmpegExecAdapter().getVideoInfo('/video.mp4')).rejects.toThrow('invalid video');
|
||||
});
|
||||
|
||||
it('reads actual video metadata and JPEG bytes without a shared temporary file', async () => {
|
||||
const thumbnail = Buffer.from([255, 216, 255, 217]);
|
||||
mocks.execute.mockImplementation(async command => command === 'ffprobe'
|
||||
? { stdout: JSON.stringify({ streams: [{ width: 360, height: 480 }], format: { duration: '0.5', format_name: 'mov,mp4' } }) }
|
||||
: { stdout: thumbnail });
|
||||
await expect(new FFmpegExecAdapter().getVideoInfo('/clip with spaces.mp4')).resolves.toEqual({
|
||||
width: 360, height: 480, duration: 0.5, format: 'mov,mp4', thumbnail,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the native PNG encoder for legacy videos on macOS', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
const adapter = new FFmpegAddonAdapter('/app');
|
||||
const extract = vi.spyOn(adapter, 'extractThumbnail').mockResolvedValue();
|
||||
vi.spyOn(FFmpegAdapterFactory, 'getAdapter').mockResolvedValue(adapter);
|
||||
await FFmpegService.init('/app', logger);
|
||||
await FFmpegService.extractLegacyVideoThumbnail('/video.mp4', '/thumbnail.png');
|
||||
expect(extract).toHaveBeenCalledWith('/video.mp4', '/thumbnail.png', 'png');
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps startup available and reports unavailable media until paths are corrected', async () => {
|
||||
vi.resetModules();
|
||||
const { FFmpegService: service } = await import('@/napcat-core/helper/ffmpeg/ffmpeg');
|
||||
mocks.exists.mockReturnValue(false);
|
||||
mocks.execute.mockRejectedValue(new Error('ENOENT'));
|
||||
await expect(service.init('/app', logger)).resolves.toBeUndefined();
|
||||
await expect(service.getDuration('/audio.wav')).rejects.toThrow('ffprobe');
|
||||
expect(logger.logError).toHaveBeenCalled();
|
||||
mocks.execute.mockResolvedValue({ stdout: '1.5', stderr: '' });
|
||||
await service.setFfmpegPath('/installed tools', logger);
|
||||
await expect(service.getDuration('/audio.wav')).resolves.toBe(1.5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
|
||||
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
|
||||
import '../napcat-onebot/action/stream/StreamBasic';
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { NetworkAdapterConfig } from '../napcat-onebot/config/config';
|
||||
|
||||
import GetFriendMsgHistory from '../napcat-onebot/action/go-cqhttp/GetFriendMsgHistory';
|
||||
|
||||
// `GetFriendMsgHistory` imports `napcat-core/types` via the bare package subpath,
|
||||
// which Node exports resolution cannot map in this workspace (`./*` pattern cannot
|
||||
// target an extensionless directory). Remap it onto the aliased source tree.
|
||||
vi.mock('napcat-core/types', async () => await vi.importActual('@/napcat-core/types/index'));
|
||||
vi.mock('napcat-common/src/message-unique', async () => await vi.importActual('@/napcat-common/src/message-unique'));
|
||||
|
||||
const SAMPLE_MSG = {
|
||||
msgId: '100',
|
||||
msgSeq: '1',
|
||||
chatType: 1,
|
||||
peerUid: 'friend-uid',
|
||||
peerUin: '42',
|
||||
senderUin: '42',
|
||||
msgTime: '1700000000',
|
||||
msgRandom: '1',
|
||||
elements: [],
|
||||
} as never;
|
||||
|
||||
const TEST_ADAPTER = 'test';
|
||||
const TEST_CONFIG = { messagePostFormat: 'array' } as NetworkAdapterConfig;
|
||||
|
||||
function createHistoryAction () {
|
||||
const parseMessage = vi.fn().mockResolvedValue({ message: [], raw_message: '' });
|
||||
const core = {
|
||||
selfInfo: { uid: 'self-uid', uin: '1' },
|
||||
apis: {
|
||||
UserApi: { getUidByUinV2: vi.fn().mockResolvedValue('friend-uid') },
|
||||
FriendApi: { isBuddy: vi.fn().mockResolvedValue(true) },
|
||||
MsgApi: {
|
||||
getAioFirstViewLatestMsgs: vi.fn().mockResolvedValue({ msgList: [SAMPLE_MSG] }),
|
||||
},
|
||||
},
|
||||
};
|
||||
const obContext = {
|
||||
apis: { MsgApi: { parseMessage } },
|
||||
};
|
||||
const action = new GetFriendMsgHistory(obContext as never, core as never);
|
||||
return { action, parseMessage };
|
||||
}
|
||||
|
||||
describe('get_friend_msg_history quick_reply forwarding', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('forwards quick_reply: true to parseMessage', async () => {
|
||||
const { action, parseMessage } = createHistoryAction();
|
||||
|
||||
await action._handle(
|
||||
{ user_id: '42', count: 20, reverse_order: false, disable_get_url: false, parse_mult_msg: true, quick_reply: true, reverseOrder: false },
|
||||
TEST_ADAPTER,
|
||||
TEST_CONFIG
|
||||
);
|
||||
|
||||
expect(parseMessage).toHaveBeenCalledWith(
|
||||
SAMPLE_MSG,
|
||||
'array',
|
||||
true,
|
||||
false,
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('forwards quick_reply: false (default) to parseMessage', async () => {
|
||||
const { action, parseMessage } = createHistoryAction();
|
||||
|
||||
await action._handle(
|
||||
{ user_id: '42', count: 20, reverse_order: false, disable_get_url: false, parse_mult_msg: true, quick_reply: false, reverseOrder: false },
|
||||
TEST_ADAPTER,
|
||||
TEST_CONFIG
|
||||
);
|
||||
|
||||
expect(parseMessage).toHaveBeenCalledWith(
|
||||
SAMPLE_MSG,
|
||||
'array',
|
||||
true,
|
||||
false,
|
||||
false
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
|
||||
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
|
||||
import '../napcat-onebot/action/stream/StreamBasic';
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import { GetGroupNotice } from '../napcat-onebot/action/group/GetGroupNotice';
|
||||
|
||||
function feed (fid: string, settings?: Record<string, number>) {
|
||||
return {
|
||||
u: 10001,
|
||||
fid,
|
||||
pubt: 1750000000,
|
||||
msg: { text: `notice ${fid}`, text_face: '', title: '' },
|
||||
type: 1,
|
||||
fn: 0,
|
||||
cn: 0,
|
||||
vn: 0,
|
||||
settings,
|
||||
read_num: 3,
|
||||
is_read: 0,
|
||||
is_all_confirm: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function createAction (ret: unknown) {
|
||||
return new GetGroupNotice(
|
||||
undefined as never,
|
||||
{ apis: { WebApi: { getGroupNotice: vi.fn().mockResolvedValue(ret) } } } as never
|
||||
);
|
||||
}
|
||||
|
||||
describe('_get_group_notice', () => {
|
||||
test('returns "send to new member" notices from inst after feeds', async () => {
|
||||
const action = createAction({
|
||||
ec: 0,
|
||||
feeds: [feed('feed-1'), feed('feed-2')],
|
||||
inst: [feed('inst-1', { inst_no_pinned: 0 })],
|
||||
});
|
||||
|
||||
const notices = await action._handle({ group_id: '123' });
|
||||
|
||||
expect(notices.map(n => n.notice_id)).toEqual(['feed-1', 'feed-2', 'inst-1']);
|
||||
expect(notices.map(n => n.send_to_new_member)).toEqual([false, false, true]);
|
||||
expect(notices[2]?.message.text).toBe('notice inst-1');
|
||||
});
|
||||
|
||||
test('maps inst_no_pinned to pinned only when the field is present', async () => {
|
||||
const action = createAction({
|
||||
ec: 0,
|
||||
feeds: [feed('feed-1', { tip_window_type: 1 })],
|
||||
inst: [feed('pinned', { inst_no_pinned: 0 }), feed('unpinned', { inst_no_pinned: 1 })],
|
||||
});
|
||||
|
||||
const notices = await action._handle({ group_id: '123' });
|
||||
|
||||
expect(notices.find(n => n.notice_id === 'feed-1')?.pinned).toBeUndefined();
|
||||
expect(notices.find(n => n.notice_id === 'pinned')?.pinned).toBe(true);
|
||||
expect(notices.find(n => n.notice_id === 'unpinned')?.pinned).toBe(false);
|
||||
});
|
||||
|
||||
test('keeps working when inst is missing and skips duplicated notices', async () => {
|
||||
const withoutInst = await createAction({ ec: 0, feeds: [feed('feed-1')] })._handle({ group_id: '123' });
|
||||
expect(withoutInst.map(n => n.notice_id)).toEqual(['feed-1']);
|
||||
|
||||
const duplicated = await createAction({
|
||||
ec: 0,
|
||||
feeds: [feed('same')],
|
||||
inst: [feed('same', { inst_no_pinned: 0 })],
|
||||
})._handle({ group_id: '123' });
|
||||
expect(duplicated.map(n => n.notice_id)).toEqual(['same']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { NTQQWebApi } from '@/napcat-core/apis/webapi';
|
||||
import { nextQunAlbumBatchId, qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl } from '@/napcat-core/data/webapi';
|
||||
|
||||
const GROUP_ID = '2161015335';
|
||||
const ALBUM_ID = 'V624Oe3c1Dk7pX4et6lh4703uM49iGAR';
|
||||
const ALBUM_NAME = '水哥';
|
||||
const UIN = '2965296625';
|
||||
|
||||
// control_req 在严格模式(noUncheckedIndexedAccess)下是可选元素,这里统一收敛掉
|
||||
const firstReq = (body: { control_req: unknown[] }) => {
|
||||
const req = body.control_req[0];
|
||||
if (!req) throw new Error('control_req 为空');
|
||||
return req as NonNullable<ReturnType<typeof qunAlbumControl>['control_req'][0]>;
|
||||
};
|
||||
|
||||
const imageReq = (overrides: Record<string, unknown> = {}) => firstReq(qunAlbumControl({
|
||||
uin: UIN,
|
||||
group_id: GROUP_ID,
|
||||
pskey: 'PSKEY',
|
||||
pic_md5: 'MD5A',
|
||||
img_size: 12345,
|
||||
img_name: 'a.jpg',
|
||||
sAlbumName: ALBUM_NAME,
|
||||
sAlbumID: ALBUM_ID,
|
||||
...overrides,
|
||||
}));
|
||||
|
||||
describe('群相册图片组包', () => {
|
||||
it('单图:字段与改动前一致,批次号为秒级时间戳', () => {
|
||||
const req = imageReq();
|
||||
|
||||
expect(req.appid).toBe('qun');
|
||||
expect(req.cmd).toBe('FileUpload');
|
||||
expect(req.check_type).toBe(0);
|
||||
expect(req.checksum).toBe('MD5A');
|
||||
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
|
||||
expect(req.biz_req?.sPicTitle).toBe('a.jpg');
|
||||
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
|
||||
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
|
||||
expect(req.biz_req?.iUploadType).toBe(0);
|
||||
expect(req.biz_req?.iNeedFeeds).toBe(1);
|
||||
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: '1', video_num: '0', batch_num: '1' });
|
||||
// 每张图各自成批时,批次号仍是 10 位秒级时间戳
|
||||
expect(String(req.biz_req?.iBatchID)).toHaveLength(10);
|
||||
});
|
||||
|
||||
it('同一秒内的两次上传批次号不同,不会被相册并成一条', () => {
|
||||
const first = imageReq().biz_req?.iBatchID;
|
||||
const second = imageReq().biz_req?.iBatchID;
|
||||
expect(second).toBeGreaterThan(first ?? Infinity);
|
||||
expect(nextQunAlbumBatchId()).toBeGreaterThan(second ?? Infinity);
|
||||
});
|
||||
|
||||
it('多图同批:共用批次号,张数与序号按批上报', () => {
|
||||
const batchId = 1791038000;
|
||||
const total = '3';
|
||||
const reqs = [0, 1, 2].map(i => imageReq({
|
||||
pic_md5: `MD5${i}`,
|
||||
batchId,
|
||||
batchIndex: String(i),
|
||||
photo_num: total,
|
||||
batch_num: total,
|
||||
}));
|
||||
|
||||
expect(new Set(reqs.map(r => r.biz_req?.iBatchID)).size).toBe(1);
|
||||
expect(reqs[0]?.biz_req?.iBatchID).toBe(batchId);
|
||||
reqs.forEach((req, i) => {
|
||||
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: total, video_num: '0', batch_num: total });
|
||||
expect(req.biz_req?.mutliPicInfo).toEqual({
|
||||
iBatUploadNum: total,
|
||||
iCurUpload: String(i),
|
||||
iSuccNum: 0,
|
||||
iFailNum: 0,
|
||||
});
|
||||
expect(req.checksum).toBe(`MD5${i}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('群相册视频组包', () => {
|
||||
it('视频主体:video_qun / FileUploadVideo / SHA1,且不带相册与批次号', () => {
|
||||
const req = firstReq(qunAlbumVideoControl({
|
||||
uin: UIN,
|
||||
group_id: GROUP_ID,
|
||||
pskey: 'PSKEY',
|
||||
video_sha1: 'SHA1A',
|
||||
video_size: 1048576,
|
||||
play_time: 37,
|
||||
}));
|
||||
|
||||
expect(req.appid).toBe('video_qun');
|
||||
expect(req.cmd).toBe('FileUploadVideo');
|
||||
expect(req.check_type).toBe(1);
|
||||
expect(req.checksum).toBe('SHA1A');
|
||||
expect(req.file_len).toBe(1048576);
|
||||
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
|
||||
|
||||
expect(req.biz_req?.iUploadType).toBe(3);
|
||||
expect(req.biz_req?.iPlayTime).toBe(37);
|
||||
expect(req.biz_req?.iIsNew).toBe(111);
|
||||
// 视频主体不参与批次:iBatchID 固定 0,相册留空,也没有 mutliPicInfo
|
||||
expect(req.biz_req?.iBatchID).toBe(0);
|
||||
expect(req.biz_req?.sAlbumID).toBe('');
|
||||
expect(req.biz_req?.sAlbumName).toBe('');
|
||||
expect(req.biz_req?.mutliPicInfo).toBeUndefined();
|
||||
expect(req.biz_req?.stExtendInfo).toBeUndefined();
|
||||
expect(req.biz_req?.mapExt).toBeUndefined();
|
||||
expect(req.biz_req?.extend_info).toEqual({
|
||||
video_type: '3',
|
||||
domainid: '5',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
batch_num: '1',
|
||||
qun_id: GROUP_ID,
|
||||
});
|
||||
});
|
||||
|
||||
it('封面二段:走图片口径带相册与批次号,并用 vid 绑定视频', () => {
|
||||
const batchId = 1791038000;
|
||||
const req = firstReq(qunAlbumVideoCoverControl({
|
||||
uin: UIN,
|
||||
group_id: GROUP_ID,
|
||||
pskey: 'PSKEY',
|
||||
sAlbumName: ALBUM_NAME,
|
||||
sAlbumID: ALBUM_ID,
|
||||
cover_md5: 'COVERMD5',
|
||||
cover_size: 20000,
|
||||
vid: 'SV123',
|
||||
batchId,
|
||||
}));
|
||||
|
||||
expect(req.appid).toBe('qun');
|
||||
expect(req.cmd).toBeUndefined();
|
||||
expect(req.check_type).toBe(0);
|
||||
expect(req.checksum).toBe('COVERMD5');
|
||||
// 封面这一步才带相册和批次号——视频靠它进相册
|
||||
expect(req.env).toEqual({ refer: 'huodong', deviceInfo: 'h5' });
|
||||
expect(req.biz_req?.iUploadType).toBe(2);
|
||||
expect(req.biz_req?.iBatchID).toBe(batchId);
|
||||
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
|
||||
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
|
||||
expect(req.biz_req?.iNeedFeeds).toBe(1);
|
||||
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({
|
||||
vid: 'SV123',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
batch_num: '1',
|
||||
});
|
||||
expect(req.biz_req?.stExternalMapExt).toEqual({
|
||||
is_client_upload_cover: '1',
|
||||
is_pic_video_mix_feeds: '1',
|
||||
});
|
||||
expect(req.biz_req?.mutliPicInfo).toEqual({
|
||||
iBatUploadNum: '1',
|
||||
iCurUpload: '0',
|
||||
iSuccNum: 0,
|
||||
iFailNum: 0,
|
||||
});
|
||||
expect(req.biz_req?.mapExt).toEqual({ appid: 'qun', userid: GROUP_ID });
|
||||
});
|
||||
});
|
||||
|
||||
describe('群相册分片上传', () => {
|
||||
let tempDir: string;
|
||||
let sliceFile: string;
|
||||
|
||||
const createApi = () => new NTQQWebApi(
|
||||
{ logger: { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn(), logDebug: vi.fn() } } as never,
|
||||
{ NapCatTempPath: tempDir } as never
|
||||
);
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(path.join(tmpdir(), 'napcat-album-slice-'));
|
||||
sliceFile = path.join(tempDir, 'payload.bin');
|
||||
// 40000 字节 / 16384 分片 = 3 片
|
||||
await writeFile(sliceFile, Buffer.alloc(40000, 7));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('按分片大小切片,把 appid/cmd 透传到每个分片请求,并回收 sVid', async () => {
|
||||
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({
|
||||
ret: 0,
|
||||
msg: '',
|
||||
data: { biz: { sVid: 'SV123' } },
|
||||
}), { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const result = await createApi().uploadQunAlbumSlice(
|
||||
sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384,
|
||||
{ appid: 'video_qun', cmd: 'FileUploadVideo' }
|
||||
);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
expect(result).toMatchObject({ success: true, sVid: 'SV123' });
|
||||
|
||||
// 分片是并发发出的,调用顺序不确定,按 seq 建索引再断言
|
||||
const forms = new Map(fetchMock.mock.calls.map((call) => {
|
||||
const form = call[1]?.body as unknown as FormData;
|
||||
return [form.get('seq'), form] as const;
|
||||
}));
|
||||
const first = forms.get('0');
|
||||
expect(first).toBeDefined();
|
||||
expect(first?.get('appid')).toBe('video_qun');
|
||||
expect(first?.get('cmd')).toBe('FileUploadVideo');
|
||||
expect(first?.get('session')).toBe('SESSION');
|
||||
expect(first?.get('offset')).toBe('0');
|
||||
expect(first?.get('end')).toBe('16384');
|
||||
expect(first?.get('slice_size')).toBe('16384');
|
||||
|
||||
const urls = fetchMock.mock.calls.map(call => String(call[0]));
|
||||
expect(urls.some(url => url.includes('seq=0&retry=0&offset=0&end=16384&total=40000'))).toBe(true);
|
||||
expect(urls.some(url => url.includes('seq=2&retry=0&offset=32768&end=40000&total=40000'))).toBe(true);
|
||||
// 路径必须跟随 cmd:视频走 /sliceUpload/FileUploadVideo,否则服务端不返回 sVid
|
||||
expect(urls.every(url => url.includes('/webapp/json/sliceUpload/FileUploadVideo?'))).toBe(true);
|
||||
});
|
||||
|
||||
it('不传 appid/cmd 时退回图片口径(路径也是 FileUpload)', async () => {
|
||||
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const result = await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
|
||||
|
||||
const form = fetchMock.mock.calls[0]?.[1]?.body as unknown as FormData;
|
||||
expect(form.get('appid')).toBe('qun');
|
||||
expect(form.get('cmd')).toBe('FileUpload');
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toContain('/webapp/json/sliceUpload/FileUpload?');
|
||||
expect(result.sVid).toBeUndefined();
|
||||
});
|
||||
|
||||
it('最后一片等其它分片全部传完才发', async () => {
|
||||
// 100000 字节 / 16384 = 7 片(seq 0~6)
|
||||
await writeFile(sliceFile, Buffer.alloc(100000, 7));
|
||||
let finished = 0;
|
||||
let finishedWhenLastSent = -1;
|
||||
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
|
||||
const seq = Number((init.body as unknown as FormData).get('seq'));
|
||||
if (seq === 6) {
|
||||
finishedWhenLastSent = finished;
|
||||
} else {
|
||||
// 前面的分片故意慢一点、倒序完成
|
||||
await new Promise(resolve => setTimeout(resolve, (6 - seq) * 5));
|
||||
finished++;
|
||||
}
|
||||
return new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(7);
|
||||
expect(finishedWhenLastSent).toBe(6);
|
||||
});
|
||||
|
||||
it('前面的分片失败时不再发最后一片', async () => {
|
||||
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
|
||||
const seq = (init.body as unknown as FormData).get('seq');
|
||||
return new Response(JSON.stringify(seq === '1' ? { ret: -1, msg: 'boom' } : { ret: 0, msg: '' }), { status: 200 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
|
||||
.rejects.toThrow('分片 1 上传失败: boom');
|
||||
const seqs = fetchMock.mock.calls.map(call => (call[1]?.body as unknown as FormData).get('seq'));
|
||||
expect(seqs).not.toContain('2');
|
||||
});
|
||||
|
||||
it('分片失败时抛出带序号与原因的错误', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ ret: -1, msg: 'boom' }), { status: 200 })));
|
||||
|
||||
// 分片是并发上传的,Promise.all 抛出的是最先失败的那一片,序号不确定
|
||||
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
|
||||
.rejects.toThrow(/分片 \d+ 上传失败: boom/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
|
||||
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
|
||||
import '../napcat-onebot/action/stream/StreamBasic';
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import { GetGroupFilesByFolder } from '../napcat-onebot/action/go-cqhttp/GetGroupFilesByFolder';
|
||||
|
||||
const FOLDER_ITEM = {
|
||||
peerId: '123',
|
||||
folderInfo: {
|
||||
folderId: 'sub_folder_1',
|
||||
folderName: '子目录',
|
||||
createTime: 1,
|
||||
createUin: '9',
|
||||
creatorName: '创建者',
|
||||
totalFileCount: 2,
|
||||
modifyTime: 2,
|
||||
modifyUin: '9',
|
||||
modifyName: '修改者',
|
||||
},
|
||||
};
|
||||
|
||||
function createAction (items: unknown[]) {
|
||||
const getGroupFileList = vi.fn().mockResolvedValue(items);
|
||||
const action = new GetGroupFilesByFolder(
|
||||
undefined as never,
|
||||
{
|
||||
apis: {
|
||||
MsgApi: { getGroupFileList },
|
||||
},
|
||||
} as never
|
||||
);
|
||||
return { action, getGroupFileList };
|
||||
}
|
||||
|
||||
describe('get_group_files_by_folder subfolders', () => {
|
||||
test('maps folderInfo entries into folders', async () => {
|
||||
const { action } = createAction([FOLDER_ITEM]);
|
||||
|
||||
const res = await action._handle({ group_id: '123', file_count: 50 });
|
||||
|
||||
expect(res.folders).toHaveLength(1);
|
||||
expect(res.folders[0]).toMatchObject({
|
||||
group_id: 123,
|
||||
folder_id: 'sub_folder_1',
|
||||
folder_name: '子目录',
|
||||
total_file_count: 2,
|
||||
});
|
||||
expect(res.files).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('returns empty arrays when the folder holds nothing', async () => {
|
||||
const { action } = createAction([]);
|
||||
|
||||
const res = await action._handle({ group_id: '123', file_count: 50 });
|
||||
|
||||
expect(res.files).toHaveLength(0);
|
||||
expect(res.folders).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('passes the requested folder id through to the core API', async () => {
|
||||
const { action, getGroupFileList } = createAction([]);
|
||||
|
||||
await action._handle({ group_id: '123', file_count: 50, folder_id: 'parent_1' });
|
||||
|
||||
expect(getGroupFileList).toHaveBeenCalledWith('123', expect.objectContaining({ folderId: 'parent_1' }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { OB11Construct } from '../napcat-onebot/helper/data';
|
||||
|
||||
describe('group file folder construction', () => {
|
||||
test('exposes the last modification time and modifier of a folder', () => {
|
||||
const folder = OB11Construct.folder('123', {
|
||||
folderId: '/folder-1',
|
||||
parentFolderId: '/',
|
||||
folderName: '资料',
|
||||
createTime: 1700000000,
|
||||
modifyTime: 1750000000,
|
||||
createUin: '10001',
|
||||
creatorName: 'creator',
|
||||
totalFileCount: 2,
|
||||
modifyUin: '10002',
|
||||
modifyName: 'uploader',
|
||||
usedSpace: '0',
|
||||
});
|
||||
|
||||
expect(folder).toMatchObject({
|
||||
group_id: 123,
|
||||
folder_id: '/folder-1',
|
||||
creator: 10001,
|
||||
modify_time: 1750000000,
|
||||
modifier: 10002,
|
||||
modifier_name: 'uploader',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
|
||||
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
|
||||
import '../napcat-onebot/action/stream/StreamBasic';
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import { ChatType, type GroupMember, type RawMessage } from 'napcat-core';
|
||||
import { NTQQGroupApi } from '../napcat-core/apis/group';
|
||||
import { NTQQUserApi } from '../napcat-core/apis/user';
|
||||
import { OneBotMsgApi } from '../napcat-onebot/api/msg';
|
||||
|
||||
vi.mock('../napcat-webui-backend/index', () => ({
|
||||
pendingTokenToSend: undefined,
|
||||
}));
|
||||
|
||||
vi.mock('../napcat-webui-backend/src/helper/Data', () => ({
|
||||
WebUiDataRuntime: {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network', () => ({
|
||||
OB11HttpClientAdapter: class {},
|
||||
OB11WebSocketClientAdapter: class {},
|
||||
OB11NetworkManager: class {},
|
||||
OB11NetworkReloadType: {},
|
||||
OB11HttpServerAdapter: class {},
|
||||
OB11WebSocketServerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/api', () => ({
|
||||
OneBotFriendApi: class {},
|
||||
OneBotGroupApi: class {},
|
||||
OneBotMsgApi: class {},
|
||||
OneBotQuickActionApi: class {},
|
||||
OneBotUserApi: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/action', () => ({
|
||||
createActionMap: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/http-server-sse', () => ({
|
||||
OB11HttpSSEServerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/plugin-manger', () => ({
|
||||
OB11PluginMangerAdapter: class {},
|
||||
}));
|
||||
|
||||
// msg.ts 按目录导入 proto,vitest 解析不了;这里用不到,给个空模块
|
||||
vi.mock('napcat-core/packet/transformer/proto', () => ({}));
|
||||
|
||||
function member (uid: string, uin: string, nick: string) {
|
||||
return { uid, uin, nick, cardName: '', role: 2 } as unknown as GroupMember;
|
||||
}
|
||||
|
||||
function memberList (...members: GroupMember[]) {
|
||||
return {
|
||||
errCode: 0,
|
||||
errMsg: '',
|
||||
result: { ids: [], infos: new Map(members.map(m => [m.uid, m])), finish: true, hasRobot: false },
|
||||
};
|
||||
}
|
||||
|
||||
function createGroupApi (getAllMemberList: ReturnType<typeof vi.fn>) {
|
||||
const context = {
|
||||
session: { getGroupService: () => ({ getAllMemberList }) },
|
||||
logger: { logError: vi.fn() },
|
||||
};
|
||||
return new NTQQGroupApi(context as never, {} as never);
|
||||
}
|
||||
|
||||
describe('group member lookup', () => {
|
||||
test('returns undefined instead of throwing when the member list of a new group cannot be fetched', async () => {
|
||||
const getAllMemberList = vi.fn()
|
||||
.mockRejectedValueOnce(new Error('timeout'))
|
||||
.mockResolvedValueOnce({ errCode: 1, errMsg: 'not ready', result: undefined });
|
||||
const groupApi = createGroupApi(getAllMemberList);
|
||||
|
||||
await expect(groupApi.getGroupMember('1053882091', '2060875951')).resolves.toBeUndefined();
|
||||
await expect(groupApi.getGroupMember('1053882091', 'u_member')).resolves.toBeUndefined();
|
||||
// 拉不到的结果不能写进缓存,否则之后一直拿到空成员表
|
||||
expect(groupApi.groupMemberCache.has('1053882091')).toBe(false);
|
||||
// 每次调用只拉一次,不会为同一条消息重复强制刷新
|
||||
expect(getAllMemberList).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('refreshes a cached group once when a new member is not in the cache yet', async () => {
|
||||
const oldMember = member('u_old', '10001', 'old');
|
||||
const newMember = member('u_new', '10002', 'new');
|
||||
const getAllMemberList = vi.fn().mockResolvedValue(memberList(oldMember, newMember));
|
||||
const groupApi = createGroupApi(getAllMemberList);
|
||||
groupApi.groupMemberCache.set('123', new Map([[oldMember.uid, oldMember]]));
|
||||
|
||||
await expect(groupApi.getGroupMember('123', '10002')).resolves.toBe(newMember);
|
||||
await expect(groupApi.getGroupMember('123', 'u_new')).resolves.toBe(newMember);
|
||||
expect(getAllMemberList).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('uin to uid falls back to the cached group members before the network lookup', async () => {
|
||||
const groupApi = createGroupApi(vi.fn());
|
||||
groupApi.groupMemberCache.set('123', new Map([['u_new', member('u_new', '3680714873', 'new')]]));
|
||||
const callNoListenerEvent = vi.fn();
|
||||
const context = {
|
||||
session: {
|
||||
getUixConvertService: () => ({ getUid: vi.fn().mockResolvedValue({ uidInfo: new Map() }) }),
|
||||
getProfileService: () => ({ getUidByUin: vi.fn().mockReturnValue(new Map()) }),
|
||||
getGroupService: () => ({ getUidByUins: vi.fn().mockResolvedValue({ uids: new Map() }) }),
|
||||
},
|
||||
};
|
||||
const userApi = new NTQQUserApi(context as never, {
|
||||
apis: { GroupApi: groupApi },
|
||||
eventWrapper: { callNoListenerEvent },
|
||||
} as never);
|
||||
|
||||
await expect(userApi.getUidByUinV2('3680714873')).resolves.toBe('u_new');
|
||||
expect(callNoListenerEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('temp messages look up the sender in the source group instead of using the sender QQ as group', async () => {
|
||||
const getGroupMember = vi.fn().mockResolvedValue(member('u_temp', '3680714873', 'temp sender'));
|
||||
const msgApi = new OneBotMsgApi(undefined as never, {
|
||||
apis: {
|
||||
MsgApi: { getTempChatInfo: vi.fn().mockResolvedValue({ result: 0, tmpChatInfo: { groupCode: '603036233' } }) },
|
||||
GroupApi: { getGroupMember },
|
||||
},
|
||||
} as never);
|
||||
const resMsg = { sender: {} } as Record<string, unknown> & { sender: Record<string, unknown>; };
|
||||
const msg = {
|
||||
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
|
||||
senderUid: 'u_temp',
|
||||
senderUin: '3680714873',
|
||||
peerUid: 'u_temp',
|
||||
peerUin: '3680714873',
|
||||
} as RawMessage;
|
||||
|
||||
await (msgApi as unknown as { handleTempGroupMessage (r: unknown, m: RawMessage): Promise<void>; })
|
||||
.handleTempGroupMessage(resMsg, msg);
|
||||
|
||||
expect(getGroupMember).toHaveBeenCalledWith('603036233', 'u_temp');
|
||||
expect(resMsg).toMatchObject({ sub_type: 'group', group_id: 603036233, sender: { nickname: 'temp sender' } });
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { GeneralCallResultStatus } from '../napcat-core/services/common';
|
||||
import {
|
||||
applyGroupManagementSettings,
|
||||
createGroupDetailInfoV2Param,
|
||||
@@ -10,7 +11,8 @@ describe('NTQQ group operations', () => {
|
||||
test('reports the exact native setting that failed', () => {
|
||||
expect(() => assertGroupManagementResults('设置群成员功能权限', [{
|
||||
setting: 'allow_member_create_group',
|
||||
result: { result: 1006, errMsg: '未知错误' },
|
||||
// 枚举里只有 OK/ERROR,这里刻意用一个任意的原生错误码
|
||||
result: { result: 1006 as GeneralCallResultStatus, errMsg: '未知错误' },
|
||||
}])).toThrow(/allow_member_create_group.*1006.*未知错误/);
|
||||
expect(() => assertGroupManagementResults('设置群成员功能权限', []))
|
||||
.not.toThrow();
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import { loadQQWrapper } from '../napcat-core/index';
|
||||
|
||||
describe('loadQQWrapper', () => {
|
||||
const originalWrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
|
||||
|
||||
beforeEach(() => {
|
||||
process.env['NAPCAT_WRAPPER_PATH'] = 'E:\\NapCat\\wrapper.node';
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw new Error('The specified module could not be found.\r\n\\\\?\\E:\\NapCat\\wrapper.node');
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
if (originalWrapperPath === undefined) {
|
||||
delete process.env['NAPCAT_WRAPPER_PATH'];
|
||||
} else {
|
||||
process.env['NAPCAT_WRAPPER_PATH'] = originalWrapperPath;
|
||||
}
|
||||
});
|
||||
|
||||
test('explains the missing Media Foundation feature on Windows Server', () => {
|
||||
vi.spyOn(os, 'platform').mockReturnValue('win32');
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
|
||||
|
||||
expect(() => loadQQWrapper(undefined, '9.9.33-52230'))
|
||||
.toThrow(/媒体基础.*Install-WindowsFeature Server-Media-Foundation.*The specified module could not be found/s);
|
||||
});
|
||||
|
||||
test('keeps the original error when Media Foundation is installed', () => {
|
||||
vi.spyOn(os, 'platform').mockReturnValue('win32');
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
|
||||
|
||||
expect(() => loadQQWrapper(undefined, '9.9.33-52230')).toThrow(/^The specified module could not be found/);
|
||||
});
|
||||
|
||||
test('keeps the original error on other platforms', () => {
|
||||
vi.spyOn(os, 'platform').mockReturnValue('linux');
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
|
||||
|
||||
expect(() => loadQQWrapper(undefined, '3.2.32-52194')).toThrow(/^The specified module could not be found/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { afterEach, describe, expect, test } from 'vitest';
|
||||
import { copyFileSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
|
||||
const fixtureRoots: string[] = [];
|
||||
|
||||
function createFixture () {
|
||||
const fixtureRoot = mkdtempSync(path.join(tmpdir(), 'napcat-loader-'));
|
||||
fixtureRoots.push(fixtureRoot);
|
||||
const installDir = path.join(fixtureRoot, '中文 space # percent%');
|
||||
mkdirSync(installDir);
|
||||
return { fixtureRoot, installDir };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const fixtureRoot of fixtureRoots.splice(0)) {
|
||||
rmSync(fixtureRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('loader paths', () => {
|
||||
test('Shell loads the flat package from an unrelated working directory', () => {
|
||||
const { fixtureRoot, installDir } = createFixture();
|
||||
const loaderPath = path.join(installDir, 'loadNapCat.cjs');
|
||||
copyFileSync(path.join(packageRoot, 'napcat-shell-loader/loadNapCat.js'), loaderPath);
|
||||
writeFileSync(path.join(installDir, 'napcat.mjs'), 'console.log("SHELL_LOADED");');
|
||||
const environment = { ...process.env };
|
||||
delete environment['NAPCAT_MAIN_PATH'];
|
||||
const output = execFileSync(process.execPath, [loaderPath], { cwd: fixtureRoot, env: environment, encoding: 'utf8' });
|
||||
expect(output).toContain('SHELL_LOADED');
|
||||
});
|
||||
|
||||
test('Shell uses the actual entry path when the loader is redirected into QQ', () => {
|
||||
const { fixtureRoot, installDir } = createFixture();
|
||||
const loaderPath = path.join(fixtureRoot, 'loadNapCat.cjs');
|
||||
const entryPath = path.join(installDir, 'napcat.mjs');
|
||||
copyFileSync(path.join(packageRoot, 'napcat-shell-loader/loadNapCat.js'), loaderPath);
|
||||
writeFileSync(entryPath, 'console.log("REDIRECTED_SHELL_LOADED");');
|
||||
const output = execFileSync(process.execPath, [loaderPath], {
|
||||
cwd: fixtureRoot,
|
||||
env: { ...process.env, NAPCAT_MAIN_PATH: entryPath },
|
||||
encoding: 'utf8',
|
||||
});
|
||||
expect(output).toContain('REDIRECTED_SHELL_LOADED');
|
||||
});
|
||||
|
||||
test('Framework native loader preserves URL-sensitive path characters', () => {
|
||||
const { fixtureRoot, installDir } = createFixture();
|
||||
const loaderPath = path.join(installDir, 'nativeLoader.cjs');
|
||||
copyFileSync(path.join(packageRoot, 'napcat-framework/nativeLoader.cjs'), loaderPath);
|
||||
writeFileSync(path.join(installDir, 'napcat.mjs'), 'export async function NCoreInitFramework () { console.log("FRAMEWORK_LOADED"); }');
|
||||
const output = execFileSync(process.execPath, ['-e', 'require(process.argv[1]).initializeNapCat({}, {}, () => {});', loaderPath], {
|
||||
cwd: fixtureRoot,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
expect(output).toContain('FRAMEWORK_LOADED');
|
||||
expect(output).not.toContain('[Error]');
|
||||
});
|
||||
|
||||
test('Framework dlopen loader preserves URL-sensitive path characters', () => {
|
||||
const { fixtureRoot, installDir } = createFixture();
|
||||
const loaderPath = path.join(installDir, 'napcat.cjs');
|
||||
copyFileSync(path.join(packageRoot, 'napcat-framework/napcat.cjs'), loaderPath);
|
||||
writeFileSync(path.join(installDir, 'napcat.mjs'), 'export async function NCoreInitFramework () { console.log("DLOPEN_FRAMEWORK_LOADED"); } export function getWebUiUrl () { return ""; }');
|
||||
const script = 'process.dlopen = (module) => { module.exports = { NodeIKernelLoginService: { get: () => ({}) }, NodeIQQNTWrapperSession: { create: () => ({}) } }; }; require(process.argv[1]); process.dlopen({ exports: {} }, "wrapper.node");';
|
||||
const output = execFileSync(process.execPath, ['-e', script, loaderPath], { cwd: fixtureRoot, encoding: 'utf8' });
|
||||
expect(output).toContain('DLOPEN_FRAMEWORK_LOADED');
|
||||
expect(output).not.toContain('[Error]');
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== 'win32')('Node batch uses the bundled runtime, forwards arguments and returns the exit code', () => {
|
||||
const { fixtureRoot, installDir } = createFixture();
|
||||
copyFileSync(process.execPath, path.join(installDir, 'node.exe'));
|
||||
copyFileSync(path.join(packageRoot, 'napcat-develop/napcat.bat'), path.join(installDir, 'napcat.bat'));
|
||||
writeFileSync(path.join(installDir, 'index.js'), 'console.log(JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(2) })); process.exitCode = 7;');
|
||||
const result = spawnSync('cmd.exe', ['/d', '/s', '/c', `""${path.join(installDir, 'napcat.bat')}" -q 123456"`], {
|
||||
cwd: fixtureRoot,
|
||||
encoding: 'utf8',
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(7);
|
||||
expect(JSON.parse(result.stdout)).toEqual({ cwd: installDir, args: ['-q', '123456'] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import { NativePacketHandler } from '@/napcat-core/packet/handler/client';
|
||||
import { Napi2NativeLoader } from '@/napcat-core/packet/handler/napi2nativeLoader';
|
||||
import { NativePacketClient } from '@/napcat-core/packet/client/nativeClient';
|
||||
import type { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import type { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
|
||||
import type { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
|
||||
import type { LogStack } from '@/napcat-core/packet/context/clientContext';
|
||||
import type { PacketBuf } from '@/napcat-core/packet/transformer/base';
|
||||
|
||||
const logger = { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn() } as unknown as LogWrapper;
|
||||
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
|
||||
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
Object.defineProperty(process, 'platform', platformDescriptor);
|
||||
Object.defineProperty(process, 'arch', archDescriptor);
|
||||
});
|
||||
|
||||
describe('macOS native loaders', () => {
|
||||
it.each(['arm64', 'x64'])('loads both packet modules for %s', async (arch) => {
|
||||
Object.defineProperty(process, 'arch', { value: arch });
|
||||
const dlopen = vi.spyOn(process, 'dlopen').mockImplementation((module) => {
|
||||
Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue('success') } });
|
||||
});
|
||||
const handler = new NativePacketHandler({ logger });
|
||||
expect(await handler.init('7.0.2-53644')).toBe(true);
|
||||
expect(dlopen.mock.calls[0]![1]).toContain('MoeHoo.darwin.' + arch + '.node');
|
||||
const loader = new Napi2NativeLoader({ logger });
|
||||
expect(loader.loaded).toBe(true);
|
||||
expect(dlopen.mock.calls[1]![1]).toContain('napi2native.darwin.' + arch + '.node');
|
||||
});
|
||||
|
||||
it.each(['error hook', 'error search', undefined])('does not report native failure %s as success', async (result) => {
|
||||
Object.defineProperty(process, 'arch', { value: 'arm64' });
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(module => {
|
||||
Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue(result) } });
|
||||
});
|
||||
expect(await new NativePacketHandler({ logger }).init('7.0.2-53644')).toBe(false);
|
||||
});
|
||||
|
||||
it('does not attempt dlopen when a native binary is absent', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
const dlopen = vi.spyOn(process, 'dlopen').mockImplementation(() => {});
|
||||
const handler = new NativePacketHandler({ logger });
|
||||
expect(await handler.init('7.0.2-53644')).toBe(false);
|
||||
expect(new Napi2NativeLoader({ logger }).loaded).toBe(false);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('NativePacketClient', () => {
|
||||
function fixture () {
|
||||
const send = vi.fn();
|
||||
const minimum = vi.fn().mockImplementation(version => Number(version) <= 40768);
|
||||
const native = { initHook: vi.fn().mockReturnValue(true) };
|
||||
const core = { basicInfo: { requireMinNTQQBuild: minimum }, sendSsoCmdReqByContend: send };
|
||||
const logs = { pushLogWarn: vi.fn(), pushLogInfo: vi.fn(), pushLogError: vi.fn() };
|
||||
const client = new NativePacketClient(
|
||||
core as unknown as NapCoreContext,
|
||||
{ error: vi.fn() } as unknown as PacketLogger,
|
||||
logs as unknown as LogStack,
|
||||
native as unknown as Napi2NativeLoader
|
||||
);
|
||||
return { client, send, minimum, native };
|
||||
}
|
||||
|
||||
it('initializes the oldest supported build and clears availability after failure', async () => {
|
||||
const { client, minimum, native } = fixture();
|
||||
await client.init(0, '10', '20');
|
||||
expect(minimum).toHaveBeenCalledWith('40768');
|
||||
expect(client.available).toBe(true);
|
||||
native.initHook.mockReturnValue(false);
|
||||
await client.init(0, '10', '20');
|
||||
expect(client.available).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['success', 'failure', 'timeout'])('clears request timers after %s', async (outcome) => {
|
||||
vi.useFakeTimers();
|
||||
const { client, send } = fixture();
|
||||
const payload = Buffer.from([0, 255, 128]) as PacketBuf;
|
||||
if (outcome === 'success') send.mockResolvedValue({ rspbuffer: payload });
|
||||
if (outcome === 'failure') send.mockRejectedValue(new Error('network unavailable'));
|
||||
if (outcome === 'timeout') send.mockReturnValue(new Promise(() => {}));
|
||||
const pending = client.sendPacket('Test.Command', payload, true, 50);
|
||||
if (outcome === 'success') {
|
||||
await expect(pending).resolves.toEqual({ seq: 0, cmd: 'Test.Command', data: payload });
|
||||
} else {
|
||||
const assertion = expect(pending).rejects.toThrow(outcome === 'timeout' ? '超时' : 'network unavailable');
|
||||
if (outcome === 'timeout') await vi.advanceTimersByTimeAsync(50);
|
||||
await assertion;
|
||||
}
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(send).toHaveBeenCalledWith('Test.Command', payload);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import { createOfflineRecovery } from '../napcat-core/helper/offline-recovery';
|
||||
|
||||
function setup (restartResult: boolean | Error = true) {
|
||||
const state = { online: false };
|
||||
const onOffline = vi.fn();
|
||||
const onRecovered = vi.fn();
|
||||
const restart = vi.fn(async () => {
|
||||
if (restartResult instanceof Error) throw restartResult;
|
||||
return restartResult;
|
||||
});
|
||||
const handleOffline = createOfflineRecovery({
|
||||
isOnline: () => state.online,
|
||||
onOffline,
|
||||
onRecovered,
|
||||
restart,
|
||||
});
|
||||
return { state, onOffline, onRecovered, restart, handleOffline };
|
||||
}
|
||||
|
||||
describe('offline recovery', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('kicked offline restarts after a short delay', async () => {
|
||||
const { restart, onOffline, handleOffline } = setup();
|
||||
handleOffline('kicked', false);
|
||||
|
||||
expect(onOffline).toHaveBeenCalledWith('kicked');
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
expect(restart).toHaveBeenCalledWith('kicked');
|
||||
});
|
||||
|
||||
test('silent offline waits for the account to reconnect before restarting', async () => {
|
||||
const { restart, handleOffline } = setup();
|
||||
handleOffline('silent', true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3_500);
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('silent offline that recovers on its own does not restart', async () => {
|
||||
const { state, restart, onRecovered, handleOffline } = setup();
|
||||
handleOffline('silent', true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
state.online = true;
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
expect(onRecovered).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('a kick during the silent-offline wait restarts without waiting the full minute', async () => {
|
||||
const { restart, handleOffline } = setup();
|
||||
handleOffline('silent', true);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
handleOffline('kicked', false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3_500);
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
expect(restart).toHaveBeenCalledWith('kicked');
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('repeated offline events schedule only one restart', async () => {
|
||||
const { restart, onOffline, handleOffline } = setup();
|
||||
handleOffline('kicked', false);
|
||||
handleOffline('kicked again', false);
|
||||
handleOffline('silent', true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
expect(onOffline).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
test.each([false, new Error('boom')])('a failed restart (%s) can be retried by the next offline event', async (result) => {
|
||||
const { restart, handleOffline } = setup(result);
|
||||
handleOffline('kicked', false);
|
||||
await vi.advanceTimersByTimeAsync(3_500);
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
|
||||
handleOffline('kicked', false);
|
||||
await vi.advanceTimersByTimeAsync(3_500);
|
||||
expect(restart).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { NapCatCore } from '../napcat-core/index';
|
||||
import type { SelfStatusInfo, SelfInfo } from '../napcat-core/types';
|
||||
|
||||
interface FakeProfileListener {
|
||||
onSelfStatusChanged: (info: SelfStatusInfo) => void;
|
||||
}
|
||||
|
||||
interface FakeMessageListener {
|
||||
onKickedOffLine: (info: { tipsTitle: string; tipsDesc: string; }) => void;
|
||||
}
|
||||
|
||||
function status (value: number): SelfStatusInfo {
|
||||
return {
|
||||
uid: 'self-uid',
|
||||
status: value,
|
||||
extStatus: 0,
|
||||
termType: 0,
|
||||
netType: 0,
|
||||
iconType: 0,
|
||||
customStatus: undefined,
|
||||
setTime: '0',
|
||||
};
|
||||
}
|
||||
|
||||
function createCore (online: boolean | undefined) {
|
||||
let profileListener: FakeProfileListener | undefined;
|
||||
let messageListener: FakeMessageListener | undefined;
|
||||
const session = {
|
||||
getMsgService: () => ({
|
||||
addKernelMsgListener: vi.fn((listener: FakeMessageListener) => {
|
||||
messageListener = listener;
|
||||
}),
|
||||
}),
|
||||
getProfileService: () => ({
|
||||
addKernelProfileListener: vi.fn((listener: FakeProfileListener) => {
|
||||
profileListener = listener;
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const logger = {
|
||||
log: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
};
|
||||
const emit = vi.fn();
|
||||
// NapCatCore's constructor loads the native wrapper, which is unavailable in tests.
|
||||
// Only the listener wiring is under test, so the instance is built field-by-field.
|
||||
const core = Object.create(NapCatCore.prototype) as NapCatCore;
|
||||
Object.assign(core, {
|
||||
context: { logger, session },
|
||||
selfInfo: { uid: 'self-uid', uin: '1', online } as SelfInfo,
|
||||
event: { emit },
|
||||
});
|
||||
return {
|
||||
core,
|
||||
emit,
|
||||
profileListener: () => profileListener,
|
||||
messageListener: () => messageListener,
|
||||
};
|
||||
}
|
||||
|
||||
describe('silent offline (SelfOffline) event', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('emits SelfOffline when the account transitions online -> offline', async () => {
|
||||
const { core, emit, profileListener } = createCore(true);
|
||||
await core.initNapCatCoreListeners();
|
||||
|
||||
profileListener()!.onSelfStatusChanged(status(20));
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(1);
|
||||
expect(emit).toHaveBeenCalledWith('SelfOffline', expect.stringContaining('账号状态变更为离线'));
|
||||
expect(core.selfInfo.online).toBe(false);
|
||||
});
|
||||
|
||||
test('does not emit again while the account stays offline', async () => {
|
||||
const { core, emit, profileListener } = createCore(true);
|
||||
await core.initNapCatCoreListeners();
|
||||
|
||||
profileListener()!.onSelfStatusChanged(status(20));
|
||||
profileListener()!.onSelfStatusChanged(status(20));
|
||||
profileListener()!.onSelfStatusChanged(status(20));
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('emits again after the account recovered and went offline once more', async () => {
|
||||
const { core, emit, profileListener } = createCore(true);
|
||||
await core.initNapCatCoreListeners();
|
||||
|
||||
profileListener()!.onSelfStatusChanged(status(20));
|
||||
profileListener()!.onSelfStatusChanged(status(10));
|
||||
profileListener()!.onSelfStatusChanged(status(20));
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(2);
|
||||
expect(core.selfInfo.online).toBe(false);
|
||||
});
|
||||
|
||||
test('does not emit during startup when the account was never online', async () => {
|
||||
const { core, emit, profileListener } = createCore(undefined);
|
||||
await core.initNapCatCoreListeners();
|
||||
|
||||
profileListener()!.onSelfStatusChanged(status(20));
|
||||
|
||||
expect(emit).not.toHaveBeenCalled();
|
||||
expect(core.selfInfo.online).toBe(false);
|
||||
});
|
||||
|
||||
test('keeps emitting KickedOffLine as before', async () => {
|
||||
const { core, emit, messageListener } = createCore(true);
|
||||
await core.initNapCatCoreListeners();
|
||||
|
||||
messageListener()!.onKickedOffLine({ tipsTitle: '下线通知', tipsDesc: '当前账号已在其它设备登录' });
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(1);
|
||||
expect(emit).toHaveBeenCalledWith('KickedOffLine', expect.stringContaining('当前账号已在其它设备登录'));
|
||||
expect(core.selfInfo.online).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -5,9 +5,11 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "vitest",
|
||||
"test:ui": "vitest --ui"
|
||||
"test:ui": "vitest --ui",
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1",
|
||||
"vitest": "^4.0.9"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
|
||||
|
||||
vi.mock('@/napcat-core/index', () => ({ getMajorPath: vi.fn() }));
|
||||
|
||||
describe('QQ AppID lookup', () => {
|
||||
let info: QQBasicInfoWrapper;
|
||||
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'arch', { ...archDescriptor, value: 'x64' });
|
||||
info = Object.create(QQBasicInfoWrapper.prototype);
|
||||
info.context = { logger: { log: vi.fn() } } as unknown as QQBasicInfoWrapper['context'];
|
||||
vi.spyOn(info, 'getFullQQVersion');
|
||||
vi.spyOn(info, 'getAppidV2ByMajor').mockReturnValue('537999999');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'arch', archDescriptor);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['3.2.30-50969', 'x64', 537376344],
|
||||
['3.2.30-50969', 'arm64', 537376345],
|
||||
['3.2.32-52194', 'x64', 537379447],
|
||||
['3.2.32-52194', 'arm64', 537379448],
|
||||
['3.2.33-52892', 'x64', 537382855],
|
||||
['3.2.33-52892', 'arm64', 537382856],
|
||||
] as const)('uses the scanned AppID for Linux %s %s', (version, arch, appid) => {
|
||||
Object.defineProperty(process, 'arch', { ...archDescriptor, value: arch });
|
||||
vi.mocked(info.getFullQQVersion).mockReturnValue(version);
|
||||
|
||||
expect(info.getAppidV2()).toEqual({
|
||||
appid,
|
||||
qua: `V1_LNX_NQ_${version.replace('-', '_')}_GW_B`,
|
||||
});
|
||||
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['9.9.33-52230', 537379411],
|
||||
['9.9.35-52892', 537382819],
|
||||
] as const)('finds Windows %s by its actual package version', (version, appid) => {
|
||||
vi.mocked(info.getFullQQVersion).mockReturnValue(version);
|
||||
|
||||
expect(info.getAppidV2()).toEqual({
|
||||
appid,
|
||||
qua: `V1_WIN_NQ_${version.replace('-', '_')}_GW_B`,
|
||||
});
|
||||
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves version-only entries when an architecture override is absent', () => {
|
||||
Object.defineProperty(process, 'arch', { ...archDescriptor, value: 'arm64' });
|
||||
vi.mocked(info.getFullQQVersion).mockReturnValue('3.2.29-49738');
|
||||
|
||||
expect(info.getAppidV2()).toEqual({
|
||||
appid: 537355867,
|
||||
qua: 'V1_LNX_NQ_3.2.29_49738_GW_B',
|
||||
});
|
||||
expect(info.getAppidV2ByMajor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still scans major.node for an unknown version', () => {
|
||||
vi.mocked(info.getFullQQVersion).mockReturnValue('3.2.99-99999');
|
||||
vi.spyOn(info, 'getQUAFallback').mockReturnValue('fallback-qua');
|
||||
|
||||
expect(info.getAppidV2()).toEqual({ appid: '537999999', qua: 'fallback-qua' });
|
||||
expect(info.getAppidV2ByMajor).toHaveBeenCalledWith('3.2.99-99999');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
|
||||
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
|
||||
import '../napcat-onebot/action/stream/StreamBasic';
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import SetGroupLeave from '../napcat-onebot/action/group/SetGroupLeave';
|
||||
|
||||
function createAction () {
|
||||
const quitGroup = vi.fn().mockResolvedValue(undefined);
|
||||
const destroyGroup = vi.fn().mockResolvedValue(undefined);
|
||||
const action = new SetGroupLeave(
|
||||
undefined as never,
|
||||
{
|
||||
apis: {
|
||||
GroupApi: { quitGroup, destroyGroup },
|
||||
},
|
||||
} as never
|
||||
);
|
||||
return { action, quitGroup, destroyGroup };
|
||||
}
|
||||
|
||||
describe('set_group_leave is_dismiss', () => {
|
||||
test('leaves the group when is_dismiss is absent', async () => {
|
||||
const { action, quitGroup, destroyGroup } = createAction();
|
||||
|
||||
await action._handle({ group_id: '123' });
|
||||
|
||||
expect(quitGroup).toHaveBeenCalledWith('123');
|
||||
expect(destroyGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('leaves the group when is_dismiss is false', async () => {
|
||||
const { action, quitGroup, destroyGroup } = createAction();
|
||||
|
||||
await action._handle({ group_id: '123', is_dismiss: false });
|
||||
|
||||
expect(quitGroup).toHaveBeenCalledWith('123');
|
||||
expect(destroyGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("leaves the group when is_dismiss is the string 'false'", async () => {
|
||||
const { action, quitGroup, destroyGroup } = createAction();
|
||||
|
||||
await action._handle({ group_id: '123', is_dismiss: 'false' });
|
||||
|
||||
expect(quitGroup).toHaveBeenCalledWith('123');
|
||||
expect(destroyGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('destroys the group when is_dismiss is true', async () => {
|
||||
const { action, quitGroup, destroyGroup } = createAction();
|
||||
|
||||
await action._handle({ group_id: '123', is_dismiss: true });
|
||||
|
||||
expect(destroyGroup).toHaveBeenCalledWith('123');
|
||||
expect(quitGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("destroys the group when is_dismiss is the string 'true'", async () => {
|
||||
const { action, quitGroup, destroyGroup } = createAction();
|
||||
|
||||
await action._handle({ group_id: '123', is_dismiss: 'true' });
|
||||
|
||||
expect(destroyGroup).toHaveBeenCalledWith('123');
|
||||
expect(quitGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// StreamBasic must be evaluated before OneBotAction: the two modules import each other,
|
||||
// and loading OneBotAction first leaves BasicStream extending an uninitialized binding.
|
||||
import '../napcat-onebot/action/stream/StreamBasic';
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { SetQQProfile } from '../napcat-onebot/action/go-cqhttp/SetQQProfile';
|
||||
|
||||
const OLD_PROFILE = {
|
||||
sex: 1,
|
||||
longNick: 'old note',
|
||||
birthday_year: 2000,
|
||||
birthday_month: 1,
|
||||
birthday_day: 1,
|
||||
};
|
||||
|
||||
function createAction () {
|
||||
const modifySelfProfile = vi.fn().mockResolvedValue({});
|
||||
const action = new SetQQProfile(undefined as never, {
|
||||
selfInfo: { uid: 'u1' },
|
||||
apis: {
|
||||
UserApi: {
|
||||
getUserDetailInfo: vi.fn().mockResolvedValue(OLD_PROFILE),
|
||||
modifySelfProfile,
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
return { action, modifySelfProfile };
|
||||
}
|
||||
|
||||
describe('set_qq_profile sex handling', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
// NTSex.GENDER_UNKOWN === 0, and the payload schema documents "0: 未知".
|
||||
test('forwards sex: 0 instead of falling back to the current profile', async () => {
|
||||
const { action, modifySelfProfile } = createAction();
|
||||
|
||||
await action._handle({ nickname: 'newnick', sex: 0 });
|
||||
|
||||
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ nick: 'newnick', sex: 0 }));
|
||||
});
|
||||
|
||||
test('forwards sex: 2', async () => {
|
||||
const { action, modifySelfProfile } = createAction();
|
||||
|
||||
await action._handle({ nickname: 'newnick', sex: 2 });
|
||||
|
||||
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ sex: 2 }));
|
||||
});
|
||||
|
||||
test('falls back to the current profile when sex is omitted', async () => {
|
||||
const { action, modifySelfProfile } = createAction();
|
||||
|
||||
await action._handle({ nickname: 'newnick' });
|
||||
|
||||
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ sex: OLD_PROFILE.sex }));
|
||||
});
|
||||
|
||||
test('falls back to the current profile when sex is an empty string', async () => {
|
||||
const { action, modifySelfProfile } = createAction();
|
||||
|
||||
await action._handle({ nickname: 'newnick', sex: '' });
|
||||
|
||||
expect(modifySelfProfile).toHaveBeenCalledWith(expect.objectContaining({ sex: OLD_PROFILE.sex }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { afterEach, expect, test } from 'vitest';
|
||||
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import ts from 'typescript';
|
||||
|
||||
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
|
||||
const fixtures: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const fixture of fixtures.splice(0)) {
|
||||
rmSync(fixture, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('type post-build replaces complete nested generic and import types', () => {
|
||||
const fixture = mkdtempSync(path.join(packageRoot, 'napcat-types/post-build-test-'));
|
||||
fixtures.push(fixture);
|
||||
mkdirSync(path.join(fixture, 'scripts'));
|
||||
mkdirSync(path.join(fixture, 'dist'));
|
||||
const script = path.join(fixture, 'scripts/post-build.mjs');
|
||||
copyFileSync(path.join(packageRoot, 'napcat-types/scripts/post-build.mjs'), script);
|
||||
writeFileSync(path.join(fixture, 'dist/fixture.d.ts'), `
|
||||
import { NapProtoDecodeStructType } from 'napcat-protobuf';
|
||||
export declare class Example {
|
||||
parse(): import('napcat-protobuf').NapProtoDecodeStructType<() => { nested: Map<string, Array<number>> }>;
|
||||
encode(): NapProtoEncodeStructType<{ fn: () => Promise<Array<string>> }>;
|
||||
validate: ValidateFunction<Map<string, Array<number>>>;
|
||||
unrelated: Promise<Array<string>>;
|
||||
}
|
||||
export declare enum ExampleKind { First = 1 }
|
||||
`);
|
||||
execFileSync(process.execPath, [script], { encoding: 'utf8' });
|
||||
const output = readFileSync(path.join(fixture, 'dist/fixture.ts'), 'utf8');
|
||||
const parsed = ts.transpileModule(output, { reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.Latest } });
|
||||
expect(parsed.diagnostics).toHaveLength(0);
|
||||
expect(output).toContain('parse(): any;');
|
||||
expect(output).toContain('encode(): any;');
|
||||
expect(output).toContain('validate: any;');
|
||||
expect(output).toContain('unrelated: Promise<Array<string>>;');
|
||||
expect(output).toContain('export enum ExampleKind');
|
||||
expect(output).not.toContain("import('napcat-protobuf').any");
|
||||
});
|
||||
@@ -19,6 +19,7 @@
|
||||
"devDependencies": {
|
||||
"napcat-core": "workspace:*",
|
||||
"napcat-onebot": "workspace:*",
|
||||
"tsc-alias": "^1.8.16"
|
||||
"tsc-alias": "^1.8.16",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readdir, readFile, writeFile, rename } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import ts from 'typescript';
|
||||
|
||||
const __dirname = fileURLToPath(new URL('../', import.meta.url));
|
||||
const distDir = join(__dirname, 'dist');
|
||||
@@ -41,9 +42,21 @@ function replaceExternalTypes (content) {
|
||||
let result = content;
|
||||
|
||||
// 替换带泛型的类型(先处理复杂的)
|
||||
result = result.replace(/NapProtoDecodeStructType<[^>]+>/g, 'any');
|
||||
result = result.replace(/NapProtoEncodeStructType<[^>]+>/g, 'any');
|
||||
result = result.replace(/ValidateFunction<[^>]+>/g, 'any');
|
||||
const sourceFile = ts.createSourceFile('declaration.d.ts', result, ts.ScriptTarget.Latest, true);
|
||||
const genericTypeNames = new Set(['NapProtoDecodeStructType', 'NapProtoEncodeStructType', 'ValidateFunction']);
|
||||
const replacements = [];
|
||||
const visit = (node) => {
|
||||
const typeName = ts.isTypeReferenceNode(node) ? node.typeName : ts.isImportTypeNode(node) ? node.qualifier : undefined;
|
||||
if (typeName && genericTypeNames.has(typeName.getText(sourceFile).split('.').at(-1))) {
|
||||
replacements.push({ start: node.getStart(sourceFile), end: node.getEnd() });
|
||||
return;
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sourceFile);
|
||||
for (const replacement of replacements.reverse()) {
|
||||
result = result.slice(0, replacement.start) + 'any' + result.slice(replacement.end);
|
||||
}
|
||||
|
||||
// 替换 winston.Logger 等带命名空间的类型
|
||||
result = result.replace(/winston\.Logger/g, 'any');
|
||||
@@ -103,6 +116,11 @@ async function processFile (filePath) {
|
||||
// 3. Replace "export declare enum" with "export enum"
|
||||
content = content.replace(/export declare enum/g, 'export enum');
|
||||
|
||||
const parsed = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
|
||||
if (parsed.parseDiagnostics.length > 0) {
|
||||
throw new Error(`Invalid generated declaration ${filePath}: ${parsed.parseDiagnostics.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')).join('\n')}`);
|
||||
}
|
||||
|
||||
// Write back the modified content
|
||||
await writeFile(filePath, content, 'utf-8');
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@
|
||||
"napcat-core": [
|
||||
"../../packages/napcat-core/index.ts"
|
||||
],
|
||||
"napcat-core/*": [
|
||||
"../../packages/napcat-core/*"
|
||||
],
|
||||
"napcat-webui-backend/*": [
|
||||
"../../packages/napcat-webui-backend/*"
|
||||
],
|
||||
"napcat-onebot": [
|
||||
"../../packages/napcat-onebot/index.ts"
|
||||
],
|
||||
@@ -40,6 +46,8 @@
|
||||
},
|
||||
"include": [
|
||||
"./index.ts",
|
||||
"../napcat-pty/node-pty.d.ts",
|
||||
"../napcat-pty/native.d.ts",
|
||||
"../napcat-core/**/*.ts",
|
||||
"../napcat-onebot/**/*.ts",
|
||||
"../napcat-common/**/*.ts"
|
||||
@@ -48,4 +56,4 @@
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,10 @@ import { Card, CardProps } from '@heroui/card';
|
||||
import clsx from 'clsx';
|
||||
import React from 'react';
|
||||
|
||||
// Firefox 里 backdrop-filter 和 3D transform 作用在同一个元素上时,卡片内容会画不出来
|
||||
// (#2083,macOS 上的 Firefox 157 复现),所以 Firefox 下不做倾斜,只保留光晕。
|
||||
const tiltEnabled = !/firefox/i.test(navigator.userAgent);
|
||||
|
||||
export interface HoverEffectCardProps extends CardProps {
|
||||
children: React.ReactNode
|
||||
maxXRotation?: number
|
||||
@@ -36,20 +40,22 @@ const HoverEffectCard: React.FC<HoverEffectCardProps> = (props) => {
|
||||
'relative overflow-hidden bg-opacity-50 backdrop-blur-lg',
|
||||
className
|
||||
)}
|
||||
style={{
|
||||
willChange: 'transform',
|
||||
transform:
|
||||
'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)',
|
||||
...style,
|
||||
}}
|
||||
style={tiltEnabled
|
||||
? {
|
||||
willChange: 'transform',
|
||||
transform:
|
||||
'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)',
|
||||
...style,
|
||||
}
|
||||
: style}
|
||||
onMouseEnter={() => {
|
||||
if (cardRef.current) {
|
||||
if (tiltEnabled && cardRef.current) {
|
||||
cardRef.current.style.transition = 'transform 0.3s ease-out';
|
||||
}
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
setIsShowLight(false);
|
||||
if (cardRef.current) {
|
||||
if (tiltEnabled && cardRef.current) {
|
||||
cardRef.current.style.transition = 'transform 0.5s';
|
||||
cardRef.current.style.transform =
|
||||
'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)';
|
||||
@@ -78,6 +84,10 @@ const HoverEffectCard: React.FC<HoverEffectCardProps> = (props) => {
|
||||
top,
|
||||
});
|
||||
|
||||
if (!tiltEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
cardRef.current.style.transition = 'transform 0.1s';
|
||||
|
||||
const rangeX = 400 / 2;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { CardBody, CardHeader } from '@heroui/card';
|
||||
import { Image } from '@heroui/image';
|
||||
import { Input } from '@heroui/input';
|
||||
import { useLocalStorage } from '@uidotdev/usehooks';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { IoKeyOutline, IoArrowBack } from 'react-icons/io5';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
@@ -20,6 +20,10 @@ import WebUIManager from '@/controllers/webui_manager';
|
||||
import PureLayout from '@/layouts/pure';
|
||||
import { motion } from 'motion/react';
|
||||
|
||||
// Passkey 检查的最长等待时间。部分手机浏览器在本机没有对应 Passkey 时,
|
||||
// navigator.credentials.get 会一直不返回,不能让它无限期占住登录流程。
|
||||
const PASSKEY_TIMEOUT_MS = 30_000;
|
||||
|
||||
export default function WebLoginPage () {
|
||||
const urlSearchParams = new URLSearchParams(window.location.search);
|
||||
const token = urlSearchParams.get('token');
|
||||
@@ -27,6 +31,7 @@ export default function WebLoginPage () {
|
||||
const [tokenValue, setTokenValue] = useState<string>(token || '');
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [isPasskeyLoading, setIsPasskeyLoading] = useState<boolean>(true); // 初始为true,表示正在检查passkey
|
||||
const passkeyAbortRef = useRef<AbortController | null>(null);
|
||||
const [, setLocalToken] = useLocalStorage<string>(key.token, '');
|
||||
|
||||
// 2FA相关状态
|
||||
@@ -57,6 +62,9 @@ export default function WebLoginPage () {
|
||||
// toast.error('当前浏览器/环境不支持 Passkey 登录。');
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
passkeyAbortRef.current = controller;
|
||||
const timer = setTimeout(() => controller.abort(), PASSKEY_TIMEOUT_MS);
|
||||
try {
|
||||
// 检查是否有passkey
|
||||
const options = await WebUIManager.generatePasskeyAuthenticationOptions();
|
||||
@@ -71,7 +79,9 @@ export default function WebLoginPage () {
|
||||
transports: cred.transports,
|
||||
})),
|
||||
userVerification: options.userVerification,
|
||||
timeout: PASSKEY_TIMEOUT_MS,
|
||||
},
|
||||
signal: controller.signal,
|
||||
}) as PublicKeyCredential;
|
||||
|
||||
if (!credential) {
|
||||
@@ -95,6 +105,10 @@ export default function WebLoginPage () {
|
||||
// 验证认证
|
||||
const data = await WebUIManager.verifyPasskeyAuthentication(response);
|
||||
|
||||
// 用户已改用 Token 登录,不再用 Passkey 的结果覆盖
|
||||
if (controller.signal.aborted) {
|
||||
return false;
|
||||
}
|
||||
if (data && data.Credential) {
|
||||
setLocalToken(data.Credential);
|
||||
navigate('/qq_login', { replace: true });
|
||||
@@ -103,6 +117,11 @@ export default function WebLoginPage () {
|
||||
} catch (error) {
|
||||
// passkey登录失败,继续显示token登录界面
|
||||
console.log('Passkey login failed or not available:', error);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (passkeyAbortRef.current === controller) {
|
||||
passkeyAbortRef.current = null;
|
||||
}
|
||||
}
|
||||
return false; // 登录失败
|
||||
};
|
||||
@@ -113,6 +132,8 @@ export default function WebLoginPage () {
|
||||
toast.error('请输入token');
|
||||
return;
|
||||
}
|
||||
// 改用 Token 登录时放弃仍在等待的 Passkey 验证
|
||||
passkeyAbortRef.current?.abort();
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await WebUIManager.loginWithToken(tokenValue);
|
||||
@@ -169,7 +190,7 @@ export default function WebLoginPage () {
|
||||
|
||||
// 处理全局键盘事件
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isLoading && !isPasskeyLoading) {
|
||||
if (e.key === 'Enter' && !isLoading) {
|
||||
if (require2FA) {
|
||||
onSubmit2FA();
|
||||
} else {
|
||||
@@ -185,7 +206,7 @@ export default function WebLoginPage () {
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [tokenValue, totpCode, isLoading, isPasskeyLoading, require2FA]); // 依赖项包含用于登录的状态
|
||||
}, [tokenValue, totpCode, isLoading, require2FA]); // 依赖项包含用于登录的状态
|
||||
|
||||
useEffect(() => {
|
||||
// 如果URL中有token,直接登录
|
||||
@@ -200,6 +221,9 @@ export default function WebLoginPage () {
|
||||
tryPasskeyLogin().finally(() => {
|
||||
setIsPasskeyLoading(false);
|
||||
});
|
||||
return () => {
|
||||
passkeyAbortRef.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
@@ -233,7 +257,7 @@ export default function WebLoginPage () {
|
||||
<CardBody className='flex gap-5 py-5 px-5 md:px-10'>
|
||||
{isPasskeyLoading && (
|
||||
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
|
||||
🔐 正在检查Passkey...
|
||||
🔐 正在检查Passkey,也可以直接输入Token登录
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -354,7 +378,7 @@ export default function WebLoginPage () {
|
||||
'!cursor-text',
|
||||
],
|
||||
}}
|
||||
isDisabled={isLoading || isPasskeyLoading}
|
||||
isDisabled={isLoading}
|
||||
label='Token'
|
||||
placeholder='请输入token'
|
||||
radius='lg'
|
||||
|
||||
Generated
+9
@@ -332,6 +332,9 @@ importers:
|
||||
specifier: workspace:*
|
||||
version: link:../napcat-vite
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.1
|
||||
version: 22.19.1
|
||||
tsx:
|
||||
specifier: ^4.7.1
|
||||
version: 4.21.0
|
||||
@@ -394,6 +397,9 @@ importers:
|
||||
specifier: workspace:*
|
||||
version: link:../napcat-rpc
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.1
|
||||
version: 22.19.1
|
||||
vitest:
|
||||
specifier: ^4.0.9
|
||||
version: 4.0.9(@types/debug@4.1.12)(@types/node@22.19.1)(@vitest/ui@4.0.9)(jiti@1.21.7)(tsx@4.21.0)(yaml@2.8.2)
|
||||
@@ -416,6 +422,9 @@ importers:
|
||||
tsc-alias:
|
||||
specifier: ^1.8.16
|
||||
version: 1.8.16
|
||||
typescript:
|
||||
specifier: ^5.3.0
|
||||
version: 5.9.3
|
||||
|
||||
packages/napcat-universal:
|
||||
dependencies:
|
||||
|
||||
Reference in new issue
Block a user