mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2025-07-19 12:03:37 +00:00
Compare commits
23 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
c4cbac4331 | ||
![]() |
ac26a99143 | ||
![]() |
640252d391 | ||
![]() |
258a1dda5e | ||
![]() |
53a7ce2e46 | ||
![]() |
291e2fd8fd | ||
![]() |
f180c7698f | ||
![]() |
183d6f3011 | ||
![]() |
ba71d7ad03 | ||
![]() |
26cfaac3bd | ||
![]() |
556c8b24c0 | ||
![]() |
31f0f527b7 | ||
![]() |
b2e0cab702 | ||
![]() |
3e3609e0f2 | ||
![]() |
83e73d9842 | ||
![]() |
673a175ddf | ||
![]() |
12eacd3530 | ||
![]() |
030f0551fd | ||
![]() |
47f5947410 | ||
![]() |
aaefa2e83c | ||
![]() |
f8e92f7c8d | ||
![]() |
b6430e6eb6 | ||
![]() |
e60605c7bb |
4
.vscode/settings.json
vendored
4
.vscode/settings.json
vendored
@@ -6,5 +6,7 @@
|
||||
"tsconfig.json": "tsconfig.*.json, env.d.ts, vite.config.ts",
|
||||
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, manifest.json, logo.png, .gitignore, LICENSE"
|
||||
},
|
||||
"css.customData": [".vscode/tailwindcss.json"],
|
||||
"css.customData": [
|
||||
".vscode/tailwindcss.json"
|
||||
],
|
||||
}
|
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "qq-chat",
|
||||
"version": "9.9.18-32793",
|
||||
"verHash": "d43f097e",
|
||||
"linuxVersion": "3.2.16-32793",
|
||||
"linuxVerHash": "ee4bd910",
|
||||
"version": "9.9.18-32869",
|
||||
"verHash": "e735296c",
|
||||
"linuxVersion": "3.2.16-32869",
|
||||
"linuxVerHash": "4c192ba9",
|
||||
"private": true,
|
||||
"description": "QQ",
|
||||
"productName": "QQ",
|
||||
@@ -34,9 +34,9 @@
|
||||
"vuex@4.1.0": "patches/vuex@4.1.0.patch"
|
||||
}
|
||||
},
|
||||
"buildVersion": "32793",
|
||||
"buildVersion": "32869",
|
||||
"isPureShell": true,
|
||||
"isByteCodeShell": true,
|
||||
"platform": "win32",
|
||||
"eleArch": "x64"
|
||||
}
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@
|
||||
"name": "NapCatQQ",
|
||||
"slug": "NapCat.Framework",
|
||||
"description": "高性能的 OneBot 11 协议实现",
|
||||
"version": "4.7.6",
|
||||
"version": "4.7.11",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
|
@@ -79,6 +79,7 @@ export default function WebLoginPage() {
|
||||
<CardBody className="flex gap-5 py-5 px-5 md:px-10">
|
||||
<Input
|
||||
isClearable
|
||||
type="password"
|
||||
classNames={{
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
|
@@ -2,7 +2,7 @@
|
||||
"name": "napcat",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "4.7.6",
|
||||
"version": "4.7.11",
|
||||
"scripts": {
|
||||
"build:universal": "npm run build:webui && vite build --mode universal || exit 1",
|
||||
"build:framework": "npm run build:webui && vite build --mode framework || exit 1",
|
||||
|
229
src/common/clean-task.ts
Normal file
229
src/common/clean-task.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import fs from 'fs';
|
||||
// generate Claude 3.7 Sonet Thinking
|
||||
|
||||
interface FileRecord {
|
||||
filePath: string;
|
||||
addedTime: number;
|
||||
retries: number;
|
||||
}
|
||||
|
||||
interface CleanupTask {
|
||||
fileRecord: FileRecord;
|
||||
timer: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
class CleanupQueue {
|
||||
private tasks: Map<string, CleanupTask> = new Map();
|
||||
private readonly MAX_RETRIES = 3;
|
||||
private isProcessing: boolean = false;
|
||||
private pendingOperations: Array<() => void> = [];
|
||||
|
||||
/**
|
||||
* 执行队列中的待处理操作,确保异步安全
|
||||
*/
|
||||
private executeNextOperation(): void {
|
||||
if (this.pendingOperations.length === 0) {
|
||||
this.isProcessing = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.isProcessing = true;
|
||||
const operation = this.pendingOperations.shift();
|
||||
operation?.();
|
||||
|
||||
// 使用 setImmediate 允许事件循环继续,防止阻塞
|
||||
setImmediate(() => this.executeNextOperation());
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全执行操作,防止竞态条件
|
||||
* @param operation 要执行的操作
|
||||
*/
|
||||
private safeExecute(operation: () => void): void {
|
||||
this.pendingOperations.push(operation);
|
||||
if (!this.isProcessing) {
|
||||
this.executeNextOperation();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否存在
|
||||
* @param filePath 文件路径
|
||||
* @returns 文件是否存在
|
||||
*/
|
||||
private fileExists(filePath: string): boolean {
|
||||
try {
|
||||
return fs.existsSync(filePath);
|
||||
} catch (error) {
|
||||
//console.log(`检查文件存在出错: ${filePath}`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加文件到清理队列
|
||||
* @param filePath 文件路径
|
||||
* @param cleanupDelay 清理延迟时间(毫秒)
|
||||
*/
|
||||
addFile(filePath: string, cleanupDelay: number): void {
|
||||
this.safeExecute(() => {
|
||||
// 如果文件已在队列中,取消原来的计时器
|
||||
if (this.tasks.has(filePath)) {
|
||||
this.cancelCleanup(filePath);
|
||||
}
|
||||
|
||||
// 创建新的文件记录
|
||||
const fileRecord: FileRecord = {
|
||||
filePath,
|
||||
addedTime: Date.now(),
|
||||
retries: 0
|
||||
};
|
||||
|
||||
// 设置计时器
|
||||
const timer = setTimeout(() => {
|
||||
this.cleanupFile(fileRecord, cleanupDelay);
|
||||
}, cleanupDelay);
|
||||
|
||||
// 添加到任务队列
|
||||
this.tasks.set(filePath, { fileRecord, timer });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量添加文件到清理队列
|
||||
* @param filePaths 文件路径数组
|
||||
* @param cleanupDelay 清理延迟时间(毫秒)
|
||||
*/
|
||||
addFiles(filePaths: string[], cleanupDelay: number): void {
|
||||
this.safeExecute(() => {
|
||||
for (const filePath of filePaths) {
|
||||
// 内部直接处理,不通过 safeExecute 以保证批量操作的原子性
|
||||
if (this.tasks.has(filePath)) {
|
||||
// 取消已有的计时器,但不使用 cancelCleanup 方法以避免重复的安全检查
|
||||
const existingTask = this.tasks.get(filePath);
|
||||
if (existingTask) {
|
||||
clearTimeout(existingTask.timer);
|
||||
}
|
||||
}
|
||||
|
||||
const fileRecord: FileRecord = {
|
||||
filePath,
|
||||
addedTime: Date.now(),
|
||||
retries: 0
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this.cleanupFile(fileRecord, cleanupDelay);
|
||||
}, cleanupDelay);
|
||||
|
||||
this.tasks.set(filePath, { fileRecord, timer });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理文件
|
||||
* @param record 文件记录
|
||||
* @param delay 延迟时间,用于重试
|
||||
*/
|
||||
private cleanupFile(record: FileRecord, delay: number): void {
|
||||
this.safeExecute(() => {
|
||||
// 首先检查文件是否存在,不存在则视为清理成功
|
||||
if (!this.fileExists(record.filePath)) {
|
||||
//console.log(`文件已不存在,跳过清理: ${record.filePath}`);
|
||||
this.tasks.delete(record.filePath);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 尝试删除文件
|
||||
fs.unlinkSync(record.filePath);
|
||||
// 删除成功,从队列中移除任务
|
||||
this.tasks.delete(record.filePath);
|
||||
} catch (error) {
|
||||
const err = error as NodeJS.ErrnoException;
|
||||
|
||||
// 明确处理文件不存在的情况
|
||||
if (err.code === 'ENOENT') {
|
||||
//console.log(`文件在删除时不存在,视为清理成功: ${record.filePath}`);
|
||||
this.tasks.delete(record.filePath);
|
||||
return;
|
||||
}
|
||||
|
||||
// 文件没有访问权限等情况
|
||||
if (err.code === 'EACCES' || err.code === 'EPERM') {
|
||||
//console.error(`没有权限删除文件: ${record.filePath}`, err);
|
||||
}
|
||||
|
||||
// 其他删除失败情况,考虑重试
|
||||
if (record.retries < this.MAX_RETRIES - 1) {
|
||||
// 还有重试机会,增加重试次数
|
||||
record.retries++;
|
||||
//console.log(`清理文件失败,将重试(${record.retries}/${this.MAX_RETRIES}): ${record.filePath}`);
|
||||
|
||||
// 设置相同的延迟时间再次尝试
|
||||
const timer = setTimeout(() => {
|
||||
this.cleanupFile(record, delay);
|
||||
}, delay);
|
||||
|
||||
// 更新任务
|
||||
this.tasks.set(record.filePath, { fileRecord: record, timer });
|
||||
} else {
|
||||
// 已达到最大重试次数,从队列中移除任务
|
||||
this.tasks.delete(record.filePath);
|
||||
//console.error(`清理文件失败,已达最大重试次数(${this.MAX_RETRIES}): ${record.filePath}`, error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消文件的清理任务
|
||||
* @param filePath 文件路径
|
||||
* @returns 是否成功取消
|
||||
*/
|
||||
cancelCleanup(filePath: string): boolean {
|
||||
let cancelled = false;
|
||||
this.safeExecute(() => {
|
||||
const task = this.tasks.get(filePath);
|
||||
if (task) {
|
||||
clearTimeout(task.timer);
|
||||
this.tasks.delete(filePath);
|
||||
cancelled = true;
|
||||
}
|
||||
});
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取队列中的文件数量
|
||||
* @returns 文件数量
|
||||
*/
|
||||
getQueueSize(): number {
|
||||
return this.tasks.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有待清理的文件
|
||||
* @returns 文件路径数组
|
||||
*/
|
||||
getPendingFiles(): string[] {
|
||||
return Array.from(this.tasks.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有清理任务
|
||||
*/
|
||||
clearAll(): void {
|
||||
this.safeExecute(() => {
|
||||
// 取消所有定时器
|
||||
for (const task of this.tasks.values()) {
|
||||
clearTimeout(task.timer);
|
||||
}
|
||||
this.tasks.clear();
|
||||
//console.log('已清空所有清理任务');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const cleanTaskQueue = new CleanupQueue();
|
@@ -16,6 +16,9 @@ export function recvTask<T>(cb: (taskData: T) => Promise<unknown>) {
|
||||
}
|
||||
});
|
||||
}
|
||||
export function sendLog(_log: string) {
|
||||
//parentPort?.postMessage({ log });
|
||||
}
|
||||
class FFmpegService {
|
||||
public static async extractThumbnail(videoPath: string, thumbnailPath: string): Promise<void> {
|
||||
const ffmpegInstance = await FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' });
|
||||
@@ -107,35 +110,175 @@ class FFmpegService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static async getVideoInfo(videoPath: string, thumbnailPath: string): Promise<VideoInfo> {
|
||||
await FFmpegService.extractThumbnail(videoPath, thumbnailPath);
|
||||
const fileType = (await fileTypeFromFile(videoPath))?.ext ?? 'mp4';
|
||||
const inputFileName = `${randomUUID()}.${fileType}`;
|
||||
const ffmpegInstance = await FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' });
|
||||
ffmpegInstance.fs.writeFile(inputFileName, readFileSync(videoPath));
|
||||
ffmpegInstance.setLogging(true);
|
||||
let duration = 60;
|
||||
ffmpegInstance.setLogger((_level, ...msg) => {
|
||||
const message = msg.join(' ');
|
||||
const durationMatch = message.match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
|
||||
if (durationMatch) {
|
||||
const hours = parseInt(durationMatch[1] ?? '0', 10);
|
||||
const minutes = parseInt(durationMatch[2] ?? '0', 10);
|
||||
const seconds = parseFloat(durationMatch[3] ?? '0');
|
||||
duration = hours * 3600 + minutes * 60 + seconds;
|
||||
}
|
||||
});
|
||||
await ffmpegInstance.run('-i', inputFileName);
|
||||
const image = imageSize(thumbnailPath);
|
||||
ffmpegInstance.fs.unlink(inputFileName);
|
||||
const fileSize = statSync(videoPath).size;
|
||||
const startTime = Date.now();
|
||||
sendLog(`开始获取视频信息: ${videoPath}`);
|
||||
|
||||
// 创建一个超时包装函数
|
||||
const withTimeout = <T>(promise: Promise<T>, timeoutMs: number, taskName: string): Promise<T> => {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise<T>((_, reject) => {
|
||||
setTimeout(() => reject(new Error(`任务超时: ${taskName} (${timeoutMs}ms)`)), timeoutMs);
|
||||
})
|
||||
]);
|
||||
};
|
||||
|
||||
// 并行执行多个任务
|
||||
const [fileInfo, durationInfo] = await Promise.all([
|
||||
// 任务1: 获取文件信息和提取缩略图
|
||||
(async () => {
|
||||
sendLog(`开始任务1: 获取文件信息和提取缩略图`);
|
||||
|
||||
// 获取文件信息 (并行)
|
||||
const fileInfoStartTime = Date.now();
|
||||
const [fileType, fileSize] = await Promise.all([
|
||||
withTimeout(fileTypeFromFile(videoPath), 10000, '获取文件类型')
|
||||
.then(result => {
|
||||
sendLog(`获取文件类型完成,耗时: ${Date.now() - fileInfoStartTime}ms`);
|
||||
return result;
|
||||
}),
|
||||
(async () => {
|
||||
const result = statSync(videoPath).size;
|
||||
sendLog(`获取文件大小完成,耗时: ${Date.now() - fileInfoStartTime}ms`);
|
||||
return result;
|
||||
})()
|
||||
]);
|
||||
|
||||
// 直接实现缩略图提取 (不调用extractThumbnail方法)
|
||||
const thumbStartTime = Date.now();
|
||||
sendLog(`开始提取缩略图`);
|
||||
|
||||
const ffmpegInstance = await withTimeout(
|
||||
FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' }),
|
||||
15000,
|
||||
'创建FFmpeg实例(缩略图)'
|
||||
);
|
||||
|
||||
const videoFileName = `${randomUUID()}.mp4`;
|
||||
const outputFileName = `${randomUUID()}.jpg`;
|
||||
|
||||
try {
|
||||
// 写入视频文件到FFmpeg
|
||||
const writeFileStartTime = Date.now();
|
||||
ffmpegInstance.fs.writeFile(videoFileName, readFileSync(videoPath));
|
||||
sendLog(`写入视频文件到FFmpeg完成,耗时: ${Date.now() - writeFileStartTime}ms`);
|
||||
|
||||
// 提取缩略图
|
||||
const extractStartTime = Date.now();
|
||||
const code = await withTimeout(
|
||||
ffmpegInstance.run('-i', videoFileName, '-ss', '00:00:01.000', '-vframes', '1', outputFileName),
|
||||
30000,
|
||||
'提取缩略图'
|
||||
);
|
||||
sendLog(`FFmpeg提取缩略图命令执行完成,耗时: ${Date.now() - extractStartTime}ms`);
|
||||
|
||||
if (code !== 0) {
|
||||
throw new Error('Error extracting thumbnail: FFmpeg process exited with code ' + code);
|
||||
}
|
||||
|
||||
// 读取并保存缩略图
|
||||
const saveStartTime = Date.now();
|
||||
const thumbnail = ffmpegInstance.fs.readFile(outputFileName);
|
||||
writeFileSync(thumbnailPath, thumbnail);
|
||||
sendLog(`读取并保存缩略图完成,耗时: ${Date.now() - saveStartTime}ms`);
|
||||
|
||||
// 获取缩略图尺寸
|
||||
const imageSizeStartTime = Date.now();
|
||||
const image = imageSize(thumbnailPath);
|
||||
sendLog(`获取缩略图尺寸完成,耗时: ${Date.now() - imageSizeStartTime}ms`);
|
||||
|
||||
sendLog(`提取缩略图完成,总耗时: ${Date.now() - thumbStartTime}ms`);
|
||||
|
||||
return {
|
||||
format: fileType?.ext ?? 'mp4',
|
||||
size: fileSize,
|
||||
width: image.width ?? 100,
|
||||
height: image.height ?? 100
|
||||
};
|
||||
} finally {
|
||||
// 清理资源
|
||||
try {
|
||||
ffmpegInstance.fs.unlink(outputFileName);
|
||||
} catch (error) {
|
||||
sendLog(`清理输出文件失败: ${(error as Error).message}`);
|
||||
}
|
||||
|
||||
try {
|
||||
ffmpegInstance.fs.unlink(videoFileName);
|
||||
} catch (error) {
|
||||
sendLog(`清理视频文件失败: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
})(),
|
||||
|
||||
// 任务2: 获取视频时长
|
||||
(async () => {
|
||||
const task2StartTime = Date.now();
|
||||
sendLog(`开始任务2: 获取视频时长`);
|
||||
|
||||
// 创建FFmpeg实例
|
||||
const ffmpegCreateStartTime = Date.now();
|
||||
const ffmpegInstance = await withTimeout(
|
||||
FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' }),
|
||||
15000,
|
||||
'创建FFmpeg实例(时长)'
|
||||
);
|
||||
sendLog(`创建FFmpeg实例完成,耗时: ${Date.now() - ffmpegCreateStartTime}ms`);
|
||||
|
||||
const inputFileName = `${randomUUID()}.mp4`;
|
||||
|
||||
try {
|
||||
// 写入文件
|
||||
const writeStartTime = Date.now();
|
||||
ffmpegInstance.fs.writeFile(inputFileName, readFileSync(videoPath));
|
||||
sendLog(`写入文件到FFmpeg完成,耗时: ${Date.now() - writeStartTime}ms`);
|
||||
|
||||
ffmpegInstance.setLogging(true);
|
||||
let duration = 60; // 默认值
|
||||
|
||||
ffmpegInstance.setLogger((_level, ...msg) => {
|
||||
const message = msg.join(' ');
|
||||
const durationMatch = message.match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
|
||||
if (durationMatch) {
|
||||
const hours = parseInt(durationMatch[1] ?? '0', 10);
|
||||
const minutes = parseInt(durationMatch[2] ?? '0', 10);
|
||||
const seconds = parseFloat(durationMatch[3] ?? '0');
|
||||
duration = hours * 3600 + minutes * 60 + seconds;
|
||||
}
|
||||
});
|
||||
|
||||
// 执行FFmpeg
|
||||
const runStartTime = Date.now();
|
||||
await withTimeout(
|
||||
ffmpegInstance.run('-i', inputFileName),
|
||||
20000,
|
||||
'获取视频时长'
|
||||
);
|
||||
sendLog(`执行FFmpeg命令完成,耗时: ${Date.now() - runStartTime}ms`);
|
||||
|
||||
sendLog(`任务2(获取视频时长)完成,总耗时: ${Date.now() - task2StartTime}ms`);
|
||||
return { time: duration };
|
||||
} finally {
|
||||
try {
|
||||
ffmpegInstance.fs.unlink(inputFileName);
|
||||
} catch (error) {
|
||||
sendLog(`清理输入文件失败: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
})()
|
||||
]);
|
||||
|
||||
// 合并结果并返回
|
||||
const totalDuration = Date.now() - startTime;
|
||||
sendLog(`获取视频信息完成,总耗时: ${totalDuration}ms`);
|
||||
|
||||
return {
|
||||
width: image.width ?? 100,
|
||||
height: image.height ?? 100,
|
||||
time: duration,
|
||||
format: fileType,
|
||||
size: fileSize,
|
||||
width: fileInfo.width,
|
||||
height: fileInfo.height,
|
||||
time: durationInfo.time,
|
||||
format: fileInfo.format,
|
||||
size: fileInfo.size,
|
||||
filePath: videoPath
|
||||
};
|
||||
}
|
||||
|
@@ -30,7 +30,7 @@ export class FFmpegService {
|
||||
}
|
||||
|
||||
public static async getVideoInfo(videoPath: string, thumbnailPath: string): Promise<VideoInfo> {
|
||||
const result = await await runTask<EncodeArgs, EncodeResult>(getWorkerPath(), { method: 'getVideoInfo', args: [videoPath, thumbnailPath] });
|
||||
const result = await runTask<EncodeArgs, EncodeResult>(getWorkerPath(), { method: 'getVideoInfo', args: [videoPath, thumbnailPath] });
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@@ -76,7 +76,7 @@ export function calculateFileMD5(filePath: string): Promise<string> {
|
||||
const stream = fs.createReadStream(filePath);
|
||||
const hash = crypto.createHash('md5');
|
||||
|
||||
stream.on('data', (data: Buffer) => {
|
||||
stream.on('data', (data) => {
|
||||
// 当读取到数据时,更新哈希对象的状态
|
||||
hash.update(data);
|
||||
});
|
||||
@@ -182,28 +182,28 @@ export async function uriToLocalFile(dir: string, uri: string, filename: string
|
||||
const filePath = path.join(dir, filename);
|
||||
|
||||
switch (UriType) {
|
||||
case FileUriType.Local: {
|
||||
const fileExt = path.extname(HandledUri);
|
||||
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
|
||||
const tempFilePath = path.join(dir, filename + fileExt);
|
||||
fs.copyFileSync(HandledUri, tempFilePath);
|
||||
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
|
||||
}
|
||||
case FileUriType.Local: {
|
||||
const fileExt = path.extname(HandledUri);
|
||||
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
|
||||
const tempFilePath = path.join(dir, filename + fileExt);
|
||||
fs.copyFileSync(HandledUri, tempFilePath);
|
||||
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
|
||||
}
|
||||
|
||||
case FileUriType.Remote: {
|
||||
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {} });
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
}
|
||||
case FileUriType.Remote: {
|
||||
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {} });
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
}
|
||||
|
||||
case FileUriType.Base64: {
|
||||
const base64 = HandledUri.replace(/^base64:\/\//, '');
|
||||
const base64Buffer = Buffer.from(base64, 'base64');
|
||||
fs.writeFileSync(filePath, base64Buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
}
|
||||
case FileUriType.Base64: {
|
||||
const base64 = HandledUri.replace(/^base64:\/\//, '');
|
||||
const base64Buffer = Buffer.from(base64, 'base64');
|
||||
fs.writeFileSync(filePath, base64Buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
}
|
||||
|
||||
default:
|
||||
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
|
||||
default:
|
||||
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
|
||||
}
|
||||
}
|
||||
|
@@ -1 +1 @@
|
||||
export const napCatVersion = '4.7.6';
|
||||
export const napCatVersion = '4.7.11';
|
||||
|
@@ -5,6 +5,12 @@ export async function runTask<T, R>(workerScript: string, taskData: T): Promise<
|
||||
try {
|
||||
return await new Promise<R>((resolve, reject) => {
|
||||
worker.on('message', (result: R) => {
|
||||
if ((result as any)?.log) {
|
||||
console.error('Worker Log--->:', (result as { log: string }).log);
|
||||
}
|
||||
if ((result as any)?.error) {
|
||||
reject(new Error("Worker error: " + (result as { error: string }).error));
|
||||
}
|
||||
resolve(result);
|
||||
});
|
||||
|
||||
|
@@ -44,7 +44,7 @@ export class NTQQFileApi {
|
||||
'https://ss.xingzhige.com/music_card/rkey', // 国内
|
||||
'https://secret-service.bietiaop.com/rkeys',//国内
|
||||
],
|
||||
this.context.logger
|
||||
this.context.logger
|
||||
);
|
||||
}
|
||||
|
||||
@@ -188,17 +188,23 @@ export class NTQQFileApi {
|
||||
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
|
||||
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
|
||||
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
|
||||
try {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
|
||||
} catch {
|
||||
fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
|
||||
}
|
||||
if (_diyThumbPath) {
|
||||
try {
|
||||
await this.copyFile(_diyThumbPath, thumbPath);
|
||||
} catch (e) {
|
||||
this.context.logger.logError('复制自定义缩略图失败', e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
|
||||
if (!fs.existsSync(thumbPath)) {
|
||||
this.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
|
||||
throw new Error('获取视频缩略图失败');
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('获取视频信息失败', e);
|
||||
fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
|
||||
}
|
||||
}
|
||||
context.deleteAfterSentFiles.push(thumbPath);
|
||||
const thumbSize = (await fsPromises.stat(thumbPath)).size;
|
||||
@@ -301,18 +307,18 @@ export class NTQQFileApi {
|
||||
element.elementType === ElementType.FILE
|
||||
) {
|
||||
switch (element.elementType) {
|
||||
case ElementType.PIC:
|
||||
case ElementType.PIC:
|
||||
element.picElement!.sourcePath = elementResults?.[elementIndex] ?? '';
|
||||
break;
|
||||
case ElementType.VIDEO:
|
||||
break;
|
||||
case ElementType.VIDEO:
|
||||
element.videoElement!.filePath = elementResults?.[elementIndex] ?? '';
|
||||
break;
|
||||
case ElementType.PTT:
|
||||
break;
|
||||
case ElementType.PTT:
|
||||
element.pttElement!.filePath = elementResults?.[elementIndex] ?? '';
|
||||
break;
|
||||
case ElementType.FILE:
|
||||
break;
|
||||
case ElementType.FILE:
|
||||
element.fileElement!.filePath = elementResults?.[elementIndex] ?? '';
|
||||
break;
|
||||
break;
|
||||
}
|
||||
elementIndex++;
|
||||
}
|
||||
|
@@ -90,7 +90,30 @@ export class NTQQUserApi {
|
||||
() => true,
|
||||
(profile) => profile.uid === uid,
|
||||
);
|
||||
const RetUser: User = {
|
||||
return profile;
|
||||
}
|
||||
|
||||
async getUserDetailInfo(uid: string, no_cache: boolean = false): Promise<User> {
|
||||
let profile = await solveAsyncProblem(async (uid) => this.fetchUserDetailInfo(uid, no_cache ? UserDetailSource.KSERVER : UserDetailSource.KDB), uid);
|
||||
if (profile && profile.uin !== '0' && profile.commonExt) {
|
||||
return {
|
||||
...profile.simpleInfo.status,
|
||||
...profile.simpleInfo.vasInfo,
|
||||
...profile.commonExt,
|
||||
...profile.simpleInfo.baseInfo,
|
||||
...profile.simpleInfo.coreInfo,
|
||||
qqLevel: profile.commonExt?.qqLevel,
|
||||
age: profile.simpleInfo.baseInfo.age,
|
||||
pendantId: '',
|
||||
nick: profile.simpleInfo.coreInfo.nick || '',
|
||||
};
|
||||
}
|
||||
this.context.logger.logDebug('[NapCat] [Mark] getUserDetailInfo Mode1 Failed.');
|
||||
profile = await this.fetchUserDetailInfo(uid, UserDetailSource.KSERVER);
|
||||
if (profile && profile.uin === '0') {
|
||||
profile.uin = await this.core.apis.UserApi.getUidByUinV2(uid) ?? '0';
|
||||
}
|
||||
return {
|
||||
...profile.simpleInfo.status,
|
||||
...profile.simpleInfo.vasInfo,
|
||||
...profile.commonExt,
|
||||
@@ -101,33 +124,6 @@ export class NTQQUserApi {
|
||||
pendantId: '',
|
||||
nick: profile.simpleInfo.coreInfo.nick || '',
|
||||
};
|
||||
return RetUser;
|
||||
}
|
||||
|
||||
async getUserDetailInfo(uid: string): Promise<User> {
|
||||
let retUser = await solveAsyncProblem(async (uid) => this.fetchUserDetailInfo(uid, UserDetailSource.KDB), uid);
|
||||
if (retUser && retUser.uin !== '0') {
|
||||
return retUser;
|
||||
}
|
||||
this.context.logger.logDebug('[NapCat] [Mark] getUserDetailInfo Mode1 Failed.');
|
||||
retUser = await this.fetchUserDetailInfo(uid, UserDetailSource.KSERVER);
|
||||
if (retUser && retUser.uin === '0') {
|
||||
retUser.uin = await this.core.apis.UserApi.getUidByUinV2(uid) ?? '0';
|
||||
}
|
||||
return retUser;
|
||||
}
|
||||
|
||||
async getUserDetailInfoV2(uid: string): Promise<User> {
|
||||
const fallback = new Fallback<User>((user) => FallbackUtil.boolchecker(user, user !== undefined && user.uin !== '0'))
|
||||
.add(() => this.fetchUserDetailInfo(uid, UserDetailSource.KDB))
|
||||
.add(() => this.fetchUserDetailInfo(uid, UserDetailSource.KSERVER));
|
||||
const retUser = await fallback.run().then(async (user) => {
|
||||
if (user && user.uin === '0') {
|
||||
user.uin = await this.core.apis.UserApi.getUidByUinV2(uid) ?? '0';
|
||||
}
|
||||
return user;
|
||||
});
|
||||
return retUser;
|
||||
}
|
||||
|
||||
async modifySelfProfile(param: ModifyProfileParams) {
|
||||
|
8
src/core/external/appid.json
vendored
8
src/core/external/appid.json
vendored
@@ -226,5 +226,13 @@
|
||||
"9.9.18-33139": {
|
||||
"appid": 537273874,
|
||||
"qua": "V1_WIN_NQ_9.9.18_33139_GW_B"
|
||||
},
|
||||
"9.9.18-33800": {
|
||||
"appid": 537273974,
|
||||
"qua": "V1_WIN_NQ_9.9.18_33800_GW_B"
|
||||
},
|
||||
"3.2.16-33800": {
|
||||
"appid": 537274009,
|
||||
"qua": "V1_LNX_NQ_3.2.16_33800_GW_B"
|
||||
}
|
||||
}
|
12
src/core/external/offset.json
vendored
12
src/core/external/offset.json
vendored
@@ -302,5 +302,17 @@
|
||||
"3.2.16-33139-arm64": {
|
||||
"send": "7262BB0",
|
||||
"recv": "72664E0"
|
||||
},
|
||||
"9.9.18-33800-x64": {
|
||||
"send": "39F5870",
|
||||
"recv": "39FA070"
|
||||
},
|
||||
"3.2.16-33800-x64": {
|
||||
"send": "A634F60",
|
||||
"recv": "A638980"
|
||||
},
|
||||
"3.2.16-33800-arm64": {
|
||||
"send": "7262BB0",
|
||||
"recv": "72664E0"
|
||||
}
|
||||
}
|
@@ -38,12 +38,12 @@ export class NativePacketClient extends IPacketClient {
|
||||
return true;
|
||||
}
|
||||
|
||||
async init(pid: number, recv: string, send: string): Promise<void> {
|
||||
async init(_pid: number, recv: string, send: string): Promise<void> {
|
||||
const platform = process.platform + '.' + process.arch;
|
||||
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './moehoo/MoeHoo.' + platform + '.node');
|
||||
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
|
||||
|
||||
this.MoeHooExport.exports.InitHook?.(send, recv, (type: number, uin: string, cmd: string, seq: number, hex_data: string) => {
|
||||
|
||||
this.MoeHooExport.exports.InitHook?.(send, recv, (type: number, _uin: string, cmd: string, seq: number, hex_data: string) => {
|
||||
const trace_id = createHash('md5').update(Buffer.from(hex_data, 'hex')).digest('hex');
|
||||
if (type === 0 && this.cb.get(trace_id + 'recv')) {
|
||||
//此时为send 提取seq
|
||||
|
@@ -1,113 +0,0 @@
|
||||
import { Data, WebSocket, ErrorEvent } from 'ws';
|
||||
import { IPacketClient, RecvPacket } from '@/core/packet/client/baseClient';
|
||||
import { LogStack } from '@/core/packet/context/clientContext';
|
||||
import { NapCoreContext } from '@/core/packet/context/napCoreContext';
|
||||
import { PacketLogger } from '@/core/packet/context/loggerContext';
|
||||
|
||||
export class WsPacketClient extends IPacketClient {
|
||||
private websocket: WebSocket | null = null;
|
||||
private reconnectAttempts: number = 0;
|
||||
private readonly maxReconnectAttempts: number = 60; // 现在暂时不可配置
|
||||
private readonly clientUrl: string;
|
||||
private readonly clientUrlWrap: (url: string) => string = (url: string) => `ws://${url}/ws`;
|
||||
|
||||
private isInitialized: boolean = false;
|
||||
private initPayload: { pid: number, recv: string, send: string } | null = null;
|
||||
|
||||
constructor(napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) {
|
||||
super(napCore, logger, logStack);
|
||||
this.clientUrl = this.napcore.config.packetServer
|
||||
? this.clientUrlWrap(this.napcore.config.packetServer)
|
||||
: this.clientUrlWrap('127.0.0.1:8083');
|
||||
}
|
||||
|
||||
check(): boolean {
|
||||
if (!this.napcore.config.packetServer) {
|
||||
this.logStack.pushLogWarn('wsPacketClient 未配置服务器地址');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async init(pid: number, recv: string, send: string): Promise<void> {
|
||||
this.initPayload = { pid, recv, send };
|
||||
await this.connectWithRetry();
|
||||
}
|
||||
|
||||
sendCommandImpl(cmd: string, data: string, trace_id: string): void {
|
||||
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
|
||||
this.websocket.send(JSON.stringify({
|
||||
action: 'send',
|
||||
cmd,
|
||||
data,
|
||||
trace_id
|
||||
}));
|
||||
} else {
|
||||
this.logStack.pushLogWarn(`WebSocket 未连接,无法发送命令: ${cmd}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async connectWithRetry(): Promise<void> {
|
||||
while (this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
try {
|
||||
await this.connect();
|
||||
return;
|
||||
} catch {
|
||||
this.reconnectAttempts++;
|
||||
this.logStack.pushLogWarn(`第 ${this.reconnectAttempts}/${this.maxReconnectAttempts} 次尝试重连失败!`);
|
||||
await this.delay(5000);
|
||||
}
|
||||
}
|
||||
this.logStack.pushLogError(`wsPacketClient 在 ${this.clientUrl} 达到最大重连次数 (${this.maxReconnectAttempts})!`);
|
||||
throw new Error(`无法连接到 WebSocket 服务器:${this.clientUrl}`);
|
||||
}
|
||||
|
||||
private connect(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.websocket = new WebSocket(this.clientUrl);
|
||||
this.websocket.onopen = () => {
|
||||
this.available = true;
|
||||
this.reconnectAttempts = 0;
|
||||
this.logger.info(`wsPacketClient 已连接到 ${this.clientUrl}`);
|
||||
if (!this.isInitialized && this.initPayload) {
|
||||
this.websocket!.send(JSON.stringify({
|
||||
action: 'init',
|
||||
...this.initPayload
|
||||
}));
|
||||
this.isInitialized = true;
|
||||
}
|
||||
resolve();
|
||||
};
|
||||
this.websocket.onclose = () => {
|
||||
this.available = false;
|
||||
this.logger.warn('WebSocket 连接关闭,尝试重连...');
|
||||
reject(new Error('WebSocket 连接关闭'));
|
||||
};
|
||||
this.websocket.onmessage = (event) => this.handleMessage(event.data).catch(err => {
|
||||
this.logger.error(`处理消息时出错: ${err}`);
|
||||
});
|
||||
this.websocket.onerror = (event: ErrorEvent) => {
|
||||
this.available = false;
|
||||
this.logger.error(`WebSocket 出错: ${event.message}`);
|
||||
this.websocket?.close();
|
||||
reject(new Error(`WebSocket 出错: ${event.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
private async handleMessage(message: Data): Promise<void> {
|
||||
try {
|
||||
const json: RecvPacket = JSON.parse(message.toString());
|
||||
const trace_id_md5 = json.trace_id_md5;
|
||||
const action = json?.type ?? 'init';
|
||||
const event = this.cb.get(`${trace_id_md5}${action}`);
|
||||
if (event) await event(json.data);
|
||||
} catch (error) {
|
||||
this.logger.error(`解析ws消息时出错: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,6 +1,5 @@
|
||||
import { IPacketClient } from '@/core/packet/client/baseClient';
|
||||
import { NativePacketClient } from '@/core/packet/client/nativeClient';
|
||||
import { WsPacketClient } from '@/core/packet/client/wsClient';
|
||||
import { OidbPacket } from '@/core/packet/transformer/base';
|
||||
import { PacketLogger } from '@/core/packet/context/loggerContext';
|
||||
import { NapCoreContext } from '@/core/packet/context/napCoreContext';
|
||||
@@ -10,8 +9,7 @@ type clientPriorityType = {
|
||||
}
|
||||
|
||||
const clientPriority: clientPriorityType = {
|
||||
10: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new NativePacketClient(napCore, logger, logStack),
|
||||
1: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new WsPacketClient(napCore, logger, logStack),
|
||||
10: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new NativePacketClient(napCore, logger, logStack)
|
||||
};
|
||||
|
||||
export class LogStack {
|
||||
@@ -88,10 +86,6 @@ export class PacketClientContext {
|
||||
this.logger.info('使用指定的 NativePacketClient 作为后端');
|
||||
client = new NativePacketClient(this.napCore, this.logger, this.logStack);
|
||||
break;
|
||||
case 'frida':
|
||||
this.logger.info('[Core] [Packet] 使用指定的 FridaPacketClient 作为后端');
|
||||
client = new WsPacketClient(this.napCore, this.logger, this.logStack);
|
||||
break;
|
||||
case 'auto':
|
||||
case undefined:
|
||||
client = this.judgeClient();
|
||||
|
@@ -16,7 +16,7 @@ export interface NodeIKernelBuddyService {
|
||||
|
||||
getBuddyListFromCache(reqType: BuddyListReqType): Promise<Array<
|
||||
{
|
||||
categoryId: number,//9999应该跳过 那是兜底数据吧
|
||||
categoryId: number,//9999为特别关心
|
||||
categorySortId: number,//排序方式
|
||||
categroyName: string,//分类名
|
||||
categroyMbCount: number,//不懂
|
||||
|
@@ -207,6 +207,7 @@ interface PhotoWall {
|
||||
|
||||
// 简单信息
|
||||
export interface SimpleInfo {
|
||||
qqLevel?: QQLevel;//临时添加
|
||||
uid?: string;
|
||||
uin?: string;
|
||||
coreInfo: CoreInfo;
|
||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -7,6 +7,7 @@ import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
const SchemaData = Type.Object({
|
||||
user_id: Type.Union([Type.Number(), Type.String()]),
|
||||
no_cache: Type.Union([Type.Boolean(), Type.String()], { default: false }),
|
||||
});
|
||||
|
||||
type Payload = Static<typeof SchemaData>;
|
||||
@@ -16,10 +17,11 @@ export default class GoCQHTTPGetStrangerInfo extends OneBotAction<Payload, OB11U
|
||||
override payloadSchema = SchemaData;
|
||||
async _handle(payload: Payload) {
|
||||
const user_id = payload.user_id.toString();
|
||||
const isNocache = typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache;
|
||||
const extendData = await this.core.apis.UserApi.getUserDetailInfoByUin(user_id);
|
||||
let uid = (await this.core.apis.UserApi.getUidByUinV2(user_id));
|
||||
if (!uid) uid = extendData.detail.uid;
|
||||
const info = (await this.core.apis.UserApi.getUserDetailInfo(uid));
|
||||
const info = (await this.core.apis.UserApi.getUserDetailInfo(uid, isNocache));
|
||||
return {
|
||||
...extendData.detail.simpleInfo.coreInfo,
|
||||
...extendData.detail.commonExt ?? {},
|
||||
|
@@ -32,7 +32,7 @@ class GetGroupMemberInfo extends OneBotAction<Payload, OB11GroupMember> {
|
||||
|
||||
const [member, info] = await Promise.all([
|
||||
this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), uid, isNocache),
|
||||
this.core.apis.UserApi.getUserDetailInfo(uid),
|
||||
this.core.apis.UserApi.getUserDetailInfo(uid, isNocache),
|
||||
]);
|
||||
|
||||
if (!member || !groupMember) throw new Error(`群(${payload.group_id})成员${payload.user_id}不存在`);
|
||||
|
@@ -14,8 +14,22 @@ export default class GetFriendList extends OneBotAction<Payload, OB11User[]> {
|
||||
override actionName = ActionName.GetFriendList;
|
||||
override payloadSchema = SchemaData;
|
||||
|
||||
async _handle(payload: Payload) {
|
||||
//全新逻辑
|
||||
return OB11Construct.friends(await this.core.apis.FriendApi.getBuddy(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache));
|
||||
async _handle(_payload: Payload) {
|
||||
const buddyMap = await this.core.apis.FriendApi.getBuddyV2SimpleInfoMap();
|
||||
const isNocache = typeof _payload.no_cache === 'string' ? _payload.no_cache === 'true' : !!_payload.no_cache;
|
||||
await Promise.all(
|
||||
Array.from(buddyMap.values()).map(async (buddyInfo) => {
|
||||
try {
|
||||
const userDetail = await this.core.apis.UserApi.getUserDetailInfo(buddyInfo.coreInfo.uid, isNocache);
|
||||
const data = buddyMap.get(buddyInfo.coreInfo.uid);
|
||||
if (data) {
|
||||
data.qqLevel = userDetail.qqLevel;
|
||||
}
|
||||
} catch (error) {
|
||||
this.core.context.logger.logError('获取好友详细信息失败', error);
|
||||
}
|
||||
})
|
||||
);
|
||||
return OB11Construct.friends(Array.from(buddyMap.values()));
|
||||
}
|
||||
}
|
||||
}
|
@@ -34,7 +34,7 @@ import { EventType } from '@/onebot/event/OneBotEvent';
|
||||
import { encodeCQCode } from '@/onebot/helper/cqcode';
|
||||
import { uriToLocalFile } from '@/common/file';
|
||||
import { RequestUtil } from '@/common/request';
|
||||
import fsPromise, { constants } from 'node:fs/promises';
|
||||
import fsPromise from 'node:fs/promises';
|
||||
import { OB11FriendAddNoticeEvent } from '@/onebot/event/notice/OB11FriendAddNoticeEvent';
|
||||
import { ForwardMsgBuilder } from '@/common/forward-msg-builder';
|
||||
import { NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
@@ -45,6 +45,7 @@ import { OB11GroupAdminNoticeEvent } from '../event/notice/OB11GroupAdminNoticeE
|
||||
import { GroupChange, GroupChangeInfo, GroupInvite, PushMsgBody } from '@/core/packet/transformer/proto';
|
||||
import { OB11GroupRequestEvent } from '../event/request/OB11GroupRequest';
|
||||
import { LRUCache } from '@/common/lru-cache';
|
||||
import { cleanTaskQueue } from '@/common/clean-task';
|
||||
|
||||
type RawToOb11Converters = {
|
||||
[Key in keyof MessageElement as Key extends `${string}Element` ? Key : never]: (
|
||||
@@ -970,7 +971,6 @@ export class OneBotMsgApi {
|
||||
});
|
||||
|
||||
const timeout = 10000 + (totalSize / 1024 / 256 * 1000);
|
||||
|
||||
try {
|
||||
const returnMsg = await this.core.apis.MsgApi.sendMsg(peer, sendElements, timeout);
|
||||
if (!returnMsg) throw new Error('发送消息失败');
|
||||
@@ -983,18 +983,19 @@ export class OneBotMsgApi {
|
||||
} catch (error) {
|
||||
throw new Error((error as Error).message);
|
||||
} finally {
|
||||
setTimeout(async () => {
|
||||
const deletePromises = deleteAfterSentFiles.map(async file => {
|
||||
try {
|
||||
if (await fsPromise.access(file, constants.W_OK).then(() => true).catch(() => false)) {
|
||||
await fsPromise.unlink(file);
|
||||
}
|
||||
} catch (e) {
|
||||
this.core.context.logger.logError('发送消息删除文件失败', e);
|
||||
}
|
||||
});
|
||||
await Promise.all(deletePromises);
|
||||
}, 60000);
|
||||
cleanTaskQueue.addFiles(deleteAfterSentFiles, timeout);
|
||||
// setTimeout(async () => {
|
||||
// const deletePromises = deleteAfterSentFiles.map(async file => {
|
||||
// try {
|
||||
// if (await fsPromise.access(file, constants.W_OK).then(() => true).catch(() => false)) {
|
||||
// await fsPromise.unlink(file);
|
||||
// }
|
||||
// } catch (e) {
|
||||
// this.core.context.logger.logError('发送消息删除文件失败', e);
|
||||
// }
|
||||
// });
|
||||
// await Promise.all(deletePromises);
|
||||
// }, 60000);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -20,16 +20,36 @@ export class OB11Construct {
|
||||
|
||||
static friends(friends: FriendV2[]): OB11User[] {
|
||||
return friends.map(rawFriend => ({
|
||||
...rawFriend.baseInfo,
|
||||
...rawFriend.coreInfo,
|
||||
birthday_year: rawFriend.baseInfo.birthday_year,
|
||||
birthday_month: rawFriend.baseInfo.birthday_month,
|
||||
birthday_day: rawFriend.baseInfo.birthday_day,
|
||||
user_id: parseInt(rawFriend.coreInfo.uin),
|
||||
age: rawFriend.baseInfo.age,
|
||||
phone_num: rawFriend.baseInfo.phoneNum,
|
||||
email: rawFriend.baseInfo.eMail,
|
||||
category_id: rawFriend.baseInfo.categoryId,
|
||||
nickname: rawFriend.coreInfo.nick ?? '',
|
||||
remark: rawFriend.coreInfo.remark ?? rawFriend.coreInfo.nick,
|
||||
sex: this.sex(rawFriend.baseInfo.sex),
|
||||
level: 0,
|
||||
level: rawFriend.qqLevel && calcQQLevel(rawFriend.qqLevel) || 0,
|
||||
}));
|
||||
}
|
||||
|
||||
static friend(friends: FriendV2): OB11User {
|
||||
return {
|
||||
birthday_year: friends.baseInfo.birthday_year,
|
||||
birthday_month: friends.baseInfo.birthday_month,
|
||||
birthday_day: friends.baseInfo.birthday_day,
|
||||
user_id: parseInt(friends.coreInfo.uin),
|
||||
age: friends.baseInfo.age,
|
||||
phone_num: friends.baseInfo.phoneNum,
|
||||
email: friends.baseInfo.eMail,
|
||||
category_id: friends.baseInfo.categoryId,
|
||||
nickname: friends.coreInfo.nick ?? '',
|
||||
remark: friends.coreInfo.remark ?? friends.coreInfo.nick,
|
||||
sex: this.sex(friends.baseInfo.sex),
|
||||
level: 0,
|
||||
};
|
||||
}
|
||||
static groupMemberRole(role: number): OB11GroupMemberRole | undefined {
|
||||
return {
|
||||
4: OB11GroupMemberRole.owner,
|
||||
|
@@ -100,7 +100,7 @@ export class NapCatOneBot11Adapter {
|
||||
const selfInfo = this.core.selfInfo;
|
||||
const ob11Config = this.configLoader.configData;
|
||||
|
||||
this.core.apis.UserApi.getUserDetailInfo(selfInfo.uid)
|
||||
this.core.apis.UserApi.getUserDetailInfo(selfInfo.uid, false)
|
||||
.then((user) => {
|
||||
selfInfo.nick = user.nick;
|
||||
this.context.logger.setLogSelfInfo(selfInfo);
|
||||
|
@@ -37,7 +37,13 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
|
||||
}, this.config.heartInterval);
|
||||
}
|
||||
this.isEnable = true;
|
||||
await this.tryConnect();
|
||||
try {
|
||||
await this.tryConnect();
|
||||
} catch (error) {
|
||||
this.logger.logError('[OneBot] [WebSocket Client] TryConnect Error , info -> ', error);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
close() {
|
||||
|
@@ -1,4 +1,10 @@
|
||||
export interface OB11User {
|
||||
birthday_year?: number; // 生日
|
||||
birthday_month?: number; // 生日
|
||||
birthday_day?: number; // 生日
|
||||
phone_num?: string; // 手机号
|
||||
email?: string; // 邮箱
|
||||
category_id?: number; // 分组ID
|
||||
user_id: number; // 用户ID
|
||||
nickname: string; // 昵称
|
||||
remark?: string; // 备注
|
||||
|
@@ -139,6 +139,7 @@ async function handleLogin(
|
||||
loginListener.onLoginConnected = () => {
|
||||
waitForNetworkConnection(loginService, logger).then(() => {
|
||||
handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList).then().catch(e => logger.logError(e));
|
||||
loginListener.onLoginConnected = () => { };
|
||||
});
|
||||
}
|
||||
loginListener.onQRCodeGetPicture = ({ pngBase64QrcodeData, qrcodeUrl }) => {
|
||||
@@ -222,6 +223,11 @@ async function handleLoginInner(context: { isLogined: boolean }, logger: LogWrap
|
||||
}`);
|
||||
}
|
||||
loginService.getQRCodePicture();
|
||||
try {
|
||||
await WebUiDataRuntime.runWebUiConfigQuickFunction();
|
||||
} catch (error) {
|
||||
logger.logError('WebUi 快速登录失败 执行失败', error);
|
||||
}
|
||||
}
|
||||
|
||||
loginService.getLoginList().then((res) => {
|
||||
|
@@ -50,20 +50,21 @@ export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapp
|
||||
logger.log('[NapCat] [WebUi] Current WebUi is not run.');
|
||||
return;
|
||||
}
|
||||
setTimeout(async () => {
|
||||
let autoLoginAccount = process.env['NAPCAT_QUICK_ACCOUNT'] || WebUiConfig.getAutoLoginAccount();
|
||||
if (autoLoginAccount) {
|
||||
try {
|
||||
const { result, message } = await WebUiDataRuntime.requestQuickLogin(autoLoginAccount);
|
||||
if (!result) {
|
||||
throw new Error(message);
|
||||
WebUiDataRuntime.setWebUiConfigQuickFunction(
|
||||
async () => {
|
||||
let autoLoginAccount = process.env['NAPCAT_QUICK_ACCOUNT'] || WebUiConfig.getAutoLoginAccount();
|
||||
if (autoLoginAccount) {
|
||||
try {
|
||||
const { result, message } = await WebUiDataRuntime.requestQuickLogin(autoLoginAccount);
|
||||
if (!result) {
|
||||
throw new Error(message);
|
||||
}
|
||||
console.log(`[NapCat] [WebUi] Auto login account: ${autoLoginAccount}`);
|
||||
} catch (error) {
|
||||
console.log(`[NapCat] [WebUi] Auto login account failed.` + error);
|
||||
}
|
||||
console.log(`[NapCat] [WebUi] Auto login account: ${autoLoginAccount}`);
|
||||
} catch (error) {
|
||||
console.log(`[NapCat] [WebUi] Auto login account failed.` + error);
|
||||
}
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
// ------------注册中间件------------
|
||||
// 使用express的json中间件
|
||||
app.use(express.json());
|
||||
|
@@ -25,6 +25,9 @@ const LoginRuntime: LoginRuntimeType = {
|
||||
NewQQLoginList: [],
|
||||
},
|
||||
packageJson: packageJson,
|
||||
WebUiConfigQuickFunction: async () => {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
export const WebUiDataRuntime = {
|
||||
@@ -118,4 +121,11 @@ export const WebUiDataRuntime = {
|
||||
getQQVersion() {
|
||||
return LoginRuntime.QQVersion;
|
||||
},
|
||||
|
||||
setWebUiConfigQuickFunction(func: LoginRuntimeType['WebUiConfigQuickFunction']): void {
|
||||
LoginRuntime.WebUiConfigQuickFunction = func;
|
||||
},
|
||||
runWebUiConfigQuickFunction: async function () {
|
||||
await LoginRuntime.WebUiConfigQuickFunction();
|
||||
}
|
||||
};
|
||||
|
1
src/webui/src/types/data.d.ts
vendored
1
src/webui/src/types/data.d.ts
vendored
@@ -9,6 +9,7 @@ interface LoginRuntimeType {
|
||||
QQLoginUin: string;
|
||||
QQLoginInfo: SelfInfo;
|
||||
QQVersion: string;
|
||||
WebUiConfigQuickFunction: () => Promise<void>;
|
||||
NapCatHelper: {
|
||||
onQuickLoginRequested: (uin: string) => Promise<{ result: boolean; message: string }>;
|
||||
onOB11ConfigChanged: (ob11: OneBotConfig) => Promise<void>;
|
||||
|
Reference in New Issue
Block a user