style: 强类型大法

This commit is contained in:
手瓜一十雪
2025-02-02 23:22:21 +08:00
parent ac193cc94a
commit 15854c605b
191 changed files with 923 additions and 806 deletions

View File

@@ -12,7 +12,7 @@ insert_final_newline = true
# Set default charset # Set default charset
charset = utf-8 charset = utf-8
# 2 space indentation # 4 space indentation
[*.{cjs,mjs,js,jsx,ts,tsx,css,scss,sass,html,json}] [*.{cjs,mjs,js,jsx,ts,tsx,css,scss,sass,html,json}]
indent_style = space indent_style = space
indent_size = 4 indent_size = 4

View File

@@ -12,6 +12,7 @@ const customTsFlatConfig = [
globals: { globals: {
...globals.browser, ...globals.browser,
...globals.node, ...globals.node,
NodeJS: 'readonly', // 添加 NodeJS 全局变量
}, },
}, },
files: ['**/*.{ts,tsx}'], files: ['**/*.{ts,tsx}'],
@@ -24,6 +25,7 @@ const customTsFlatConfig = [
plugins: { plugins: {
'@typescript-eslint': tsEslintPlugin, '@typescript-eslint': tsEslintPlugin,
}, },
ignores: ['src/webui/**'], // 忽略 src/webui/ 目录所有文件
}, },
]; ];

View File

@@ -164,7 +164,7 @@ interface CommonExt {
address: string address: string
regTime: number regTime: number
interest: string interest: string
labels: unknown[] labels: string[]
qqLevel: QQLevel qqLevel: QQLevel
} }

View File

@@ -27,8 +27,7 @@ async function guessDuration(pttPath: string, logger: LogWrapper) {
async function handleWavFile( async function handleWavFile(
file: Buffer, file: Buffer,
filePath: string, filePath: string,
pcmPath: string, pcmPath: string
_logger: LogWrapper
): Promise<{ input: Buffer; sampleRate: number }> { ): Promise<{ input: Buffer; sampleRate: number }> {
const { fmt } = getWavFileInfo(file); const { fmt } = getWavFileInfo(file);
if (!ALLOW_SAMPLE_RATE.includes(fmt.sampleRate)) { if (!ALLOW_SAMPLE_RATE.includes(fmt.sampleRate)) {
@@ -45,7 +44,7 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
logger.log(`语音文件${filePath}需要转换成silk`); logger.log(`语音文件${filePath}需要转换成silk`);
const pcmPath = `${pttPath}.pcm`; const pcmPath = `${pttPath}.pcm`;
const { input, sampleRate } = isWav(file) const { input, sampleRate } = isWav(file)
? (await handleWavFile(file, filePath, pcmPath, logger)) ? (await handleWavFile(file, filePath, pcmPath))
: { input: await FFmpegService.convert(filePath, pcmPath), sampleRate: 24000 }; : { input: await FFmpegService.convert(filePath, pcmPath), sampleRate: 24000 };
const silk = await piscina.run({ input: input, sampleRate: sampleRate }); const silk = await piscina.run({ input: input, sampleRate: sampleRate });
await fsPromise.writeFile(pttPath, Buffer.from(silk.data)); await fsPromise.writeFile(pttPath, Buffer.from(silk.data));
@@ -59,8 +58,8 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
let duration = 0; let duration = 0;
try { try {
duration = getDuration(file) / 1000; duration = getDuration(file) / 1000;
} catch (e: any) { } catch (e: unknown) {
logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, e.stack); logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, (e as Error).stack);
duration = await guessDuration(filePath, logger); duration = await guessDuration(filePath, logger);
} }
return { return {
@@ -69,8 +68,8 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
duration, duration,
}; };
} }
} catch (error: any) { } catch (error: unknown) {
logger.logError('convert silk failed', error.stack); logger.logError('convert silk failed', (error as Error).stack);
return {}; return {};
} }
} }

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
export type TaskExecutor<T> = (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void, onCancel: (callback: () => void) => void) => void | Promise<void>; export type TaskExecutor<T> = (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void, onCancel: (callback: () => void) => void) => void | Promise<void>;
export class CancelableTask<T> { export class CancelableTask<T> {
@@ -7,30 +8,34 @@ export class CancelableTask<T> {
private cancelListeners: Array<() => void> = []; private cancelListeners: Array<() => void> = [];
constructor(executor: TaskExecutor<T>) { constructor(executor: TaskExecutor<T>) {
this.promise = new Promise<T>(async (resolve, reject) => { this.promise = new Promise<T>((resolve, reject) => {
const onCancel = (callback: () => void) => { const onCancel = (callback: () => void) => {
this.cancelCallback = callback; this.cancelCallback = callback;
}; };
try { const execute = async () => {
await executor( try {
(value) => { await executor(
if (!this.isCanceled) { (value) => {
resolve(value); if (!this.isCanceled) {
} resolve(value);
}, }
(reason) => { },
if (!this.isCanceled) { (reason) => {
reject(reason); if (!this.isCanceled) {
} reject(reason);
}, }
onCancel },
); onCancel
} catch (error) { );
if (!this.isCanceled) { } catch (error) {
reject(error); if (!this.isCanceled) {
reject(error);
}
} }
} };
execute();
}); });
} }

View File

@@ -40,8 +40,8 @@ export abstract class ConfigBase<T> {
try { try {
fs.writeFileSync(configPath, fs.readFileSync(this.getConfigPath(undefined), 'utf-8')); fs.writeFileSync(configPath, fs.readFileSync(this.getConfigPath(undefined), 'utf-8'));
this.core.context.logger.log('[Core] [Config] 配置文件创建成功!\n'); this.core.context.logger.log('[Core] [Config] 配置文件创建成功!\n');
} catch (e: any) { } catch (e: unknown) {
this.core.context.logger.logError('[Core] [Config] 创建配置文件时发生错误:', e.message); this.core.context.logger.logError('[Core] [Config] 创建配置文件时发生错误:', (e as Error).message);
} }
} else if (!fs.existsSync(configPath) && !copy_default) { } else if (!fs.existsSync(configPath) && !copy_default) {
fs.writeFileSync(configPath, '{}'); fs.writeFileSync(configPath, '{}');
@@ -50,11 +50,11 @@ export abstract class ConfigBase<T> {
this.configData = json5.parse(fs.readFileSync(configPath, 'utf-8')); this.configData = json5.parse(fs.readFileSync(configPath, 'utf-8'));
this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData); this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData);
return this.configData; return this.configData;
} catch (e: any) { } catch (e: unknown) {
if (e instanceof SyntaxError) { if (e instanceof SyntaxError) {
this.core.context.logger.logError('[Core] [Config] 配置文件格式错误,请检查配置文件:', e.message); this.core.context.logger.logError('[Core] [Config] 配置文件格式错误,请检查配置文件:', e.message);
} else { } else {
this.core.context.logger.logError('[Core] [Config] 读取配置文件时发生错误:', e.message); this.core.context.logger.logError('[Core] [Config] 读取配置文件时发生错误:', (e as Error).message);
} }
return {} as T; return {} as T;
} }
@@ -67,8 +67,8 @@ export abstract class ConfigBase<T> {
const configPath = this.getConfigPath(selfInfo.uin); const configPath = this.getConfigPath(selfInfo.uin);
try { try {
fs.writeFileSync(configPath, JSON.stringify(newConfigData, this.getKeys(), 2)); fs.writeFileSync(configPath, JSON.stringify(newConfigData, this.getKeys(), 2));
} catch (e: any) { } catch (e: unknown) {
this.core.context.logger.logError(`保存配置文件 ${configPath} 时发生错误:`, e.message); this.core.context.logger.logError(`保存配置文件 ${configPath} 时发生错误:`, (e as Error).message);
} }
} }
} }

View File

@@ -1,22 +0,0 @@
// decoratorAsyncMethod(this,function,wrapper)
async function decoratorMethod<T, R>(
target: T,
method: () => Promise<R>,
wrapper: (result: R) => Promise<any>,
executeImmediately: boolean = true
): Promise<any> {
const execute = async () => {
try {
const result = await method.call(target);
return wrapper(result);
} catch (error) {
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
}
};
if (executeImmediately) {
return execute();
} else {
return execute;
}
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { NodeIQQNTWrapperSession } from '@/core/wrapper'; import { NodeIQQNTWrapperSession } from '@/core/wrapper';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { ListenerNamingMapping, ServiceNamingMapping } from '@/core'; import { ListenerNamingMapping, ServiceNamingMapping } from '@/core';
@@ -75,6 +76,7 @@ export class NTEventWrapper {
} }
return undefined; return undefined;
} }
return undefined;
} }
createListenerFunction<T>(listenerMainName: string, uniqueCode: string = ''): T { createListenerFunction<T>(listenerMainName: string, uniqueCode: string = ''): T {

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { FFmpeg } from '@ffmpeg.wasm/main'; import { FFmpeg } from '@ffmpeg.wasm/main';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { readFileSync, statSync, writeFileSync } from 'fs'; import { readFileSync, statSync, writeFileSync } from 'fs';

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import Piscina from 'piscina'; import Piscina from 'piscina';
import { VideoInfo } from './video'; import { VideoInfo } from './video';

View File

@@ -58,8 +58,8 @@ function timeoutPromise(timeout: number, errorMsg: string): Promise<void> {
async function checkFile(path: string): Promise<void> { async function checkFile(path: string): Promise<void> {
try { try {
await stat(path); await stat(path);
} catch (error: any) { } catch (error: unknown) {
if (error.code === 'ENOENT') { if ((error as Error & { code: string }).code === 'ENOENT') {
// 如果文件不存在,则抛出一个错误 // 如果文件不存在,则抛出一个错误
throw new Error(`文件不存在: ${path}`); throw new Error(`文件不存在: ${path}`);
} else { } else {
@@ -169,6 +169,7 @@ export async function checkUriType(Uri: string) {
const data = uri.split(',')[1]; const data = uri.split(',')[1];
if (data) return { Uri: data, Type: FileUriType.Base64 }; if (data) return { Uri: data, Type: FileUriType.Base64 };
} }
return;
}, Uri); }, Uri);
if (OtherFileRet) return OtherFileRet; if (OtherFileRet) return OtherFileRet;

View File

@@ -1,14 +1,16 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import path from 'node:path'; import path from 'node:path';
import fs from 'fs'; import fs from 'fs';
import os from 'node:os'; import os from 'node:os';
import { QQLevel } from '@/core'; import { QQLevel } from '@/core';
import { QQVersionConfigType } from './types';
export async function solveProblem<T extends (...arg: any[]) => any>(func: T, ...args: Parameters<T>): Promise<ReturnType<T> | undefined> { export async function solveProblem<T extends (...arg: any[]) => any>(func: T, ...args: Parameters<T>): Promise<ReturnType<T> | undefined> {
return new Promise<ReturnType<T> | undefined>((resolve) => { return new Promise<ReturnType<T> | undefined>((resolve) => {
try { try {
const result = func(...args); const result = func(...args);
resolve(result); resolve(result);
} catch (e) { } catch {
resolve(undefined); resolve(undefined);
} }
}); });
@@ -193,7 +195,7 @@ export function parseAppidFromMajor(nodeMajor: string): string | undefined {
if (!content.every(byte => byte === 0x00)) { if (!content.every(byte => byte === 0x00)) {
try { try {
return content.toString('utf-8'); return content.toString('utf-8');
} catch (error) { } catch {
break; break;
} }
} }

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import winston, { format, transports } from 'winston'; import winston, { format, transports } from 'winston';
import { truncateString } from '@/common/helper'; import { truncateString } from '@/common/helper';
import path from 'node:path'; import path from 'node:path';
@@ -34,7 +35,7 @@ class Subscription {
for (const history of Subscription.history) { for (const history of Subscription.history) {
try { try {
listener(history); listener(history);
} catch (_) { } catch {
// ignore // ignore
} }
} }
@@ -68,7 +69,7 @@ export class LogWrapper {
format: format.combine( format: format.combine(
format.timestamp({ format: 'MM-DD HH:mm:ss' }), format.timestamp({ format: 'MM-DD HH:mm:ss' }),
format.printf(({ timestamp, level, message, ...meta }) => { format.printf(({ timestamp, level, message, ...meta }) => {
const userInfo = meta.userInfo ? `${meta.userInfo} | ` : ''; const userInfo = meta['userInfo'] ? `${meta['userInfo']} | ` : '';
return `${timestamp} [${level}] ${userInfo}${message}`; return `${timestamp} [${level}] ${userInfo}${message}`;
}) })
), ),
@@ -83,7 +84,7 @@ export class LogWrapper {
format: format.combine( format: format.combine(
format.colorize(), format.colorize(),
format.printf(({ timestamp, level, message, ...meta }) => { format.printf(({ timestamp, level, message, ...meta }) => {
const userInfo = meta.userInfo ? `${meta.userInfo} | ` : ''; const userInfo = meta['userInfo'] ? `${meta['userInfo']} | ` : '';
return `${timestamp} [${level}] ${userInfo}${message}`; return `${timestamp} [${level}] ${userInfo}${message}`;
}) })
), ),

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { LogWrapper } from '@/common/log'; import { LogWrapper } from '@/common/log';
export function proxyHandlerOf(logger: LogWrapper) { export function proxyHandlerOf(logger: LogWrapper) {
@@ -5,6 +6,7 @@ export function proxyHandlerOf(logger: LogWrapper) {
get(target: any, prop: any, receiver: any) { get(target: any, prop: any, receiver: any) {
if (typeof target[prop] === 'undefined') { if (typeof target[prop] === 'undefined') {
// 如果方法不存在返回一个函数这个函数调用existentMethod // 如果方法不存在返回一个函数这个函数调用existentMethod
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return (..._args: unknown[]) => { return (..._args: unknown[]) => {
logger.logDebug(`${target.constructor.name} has no method ${prop}`); logger.logDebug(`${target.constructor.name} has no method ${prop}`);
}; };

View File

@@ -4,6 +4,7 @@ import { getDefaultQQVersionConfigInfo, getQQPackageInfoPath, getQQVersionConfig
import AppidTable from '@/core/external/appid.json'; import AppidTable from '@/core/external/appid.json';
import { LogWrapper } from '@/common/log'; import { LogWrapper } from '@/common/log';
import { getMajorPath } from '@/core'; import { getMajorPath } from '@/core';
import { QQAppidTableType, QQPackageInfoType, QQVersionConfigType } from './types';
export class QQBasicInfoWrapper { export class QQBasicInfoWrapper {
QQMainPath: string | undefined; QQMainPath: string | undefined;
@@ -89,7 +90,7 @@ export class QQBasicInfoWrapper {
this.context.logger.log('[QQ版本兼容性检测] 当前版本Appid未内置 通过Major获取 为了更好的性能请尝试更新NapCat'); this.context.logger.log('[QQ版本兼容性检测] 当前版本Appid未内置 通过Major获取 为了更好的性能请尝试更新NapCat');
return { appid: majorAppid, qua: this.getQUAFallback() }; return { appid: majorAppid, qua: this.getQUAFallback() };
} }
} catch (error) { } catch {
this.context.logger.log('[QQ版本兼容性检测] 通过Major 获取Appid异常 请检测NapCat/QQNT是否正常'); this.context.logger.log('[QQ版本兼容性检测] 通过Major 获取Appid异常 请检测NapCat/QQNT是否正常');
} }
// 最终兜底为老版本 // 最终兜底为老版本

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import https from 'node:https'; import https from 'node:https';
import http from 'node:http'; import http from 'node:http';

View File

@@ -54,10 +54,10 @@ class Store {
// 分批次扫描 // 分批次扫描
while (scanned < this.scanLimit && this.scanCursor < keys.length) { while (scanned < this.scanLimit && this.scanCursor < keys.length) {
const key = keys[this.scanCursor++]; const key = keys[this.scanCursor++];
const entry = this.store.get(key)!; const entry = this.store.get(key!)!;
if (entry.expiresAt && entry.expiresAt < now) { if (entry.expiresAt && entry.expiresAt < now) {
this.store.delete(key); this.store.delete(key!);
} }
scanned++; scanned++;

View File

@@ -6,7 +6,7 @@ let osName: string;
try { try {
osName = os.hostname(); osName = os.hostname();
} catch (e) { } catch {
osName = 'NapCat'; // + crypto.randomUUID().substring(0, 4); osName = 'NapCat'; // + crypto.randomUUID().substring(0, 4);
} }

View File

@@ -1,17 +1,17 @@
//QQVersionType //QQVersionType
type QQPackageInfoType = { export type QQPackageInfoType = {
version: string; version: string;
buildVersion: string; buildVersion: string;
platform: string; platform: string;
eleArch: string; eleArch: string;
} }
type QQVersionConfigType = { export type QQVersionConfigType = {
baseVersion: string; baseVersion: string;
curVersion: string; curVersion: string;
prevVersion: string; prevVersion: string;
onErrorVersions: Array<any>; onErrorVersions: Array<unknown>;
buildId: string; buildId: string;
} }
type QQAppidTableType = { export type QQAppidTableType = {
[key: string]: { appid: string, qua: string }; [key: string]: { appid: string, qua: string };
} }

View File

@@ -1,15 +1,16 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { MsfChangeReasonType, MsfStatusType } from '@/core/types/adapter'; import { MsfChangeReasonType, MsfStatusType } from '@/core/types/adapter';
export class NodeIDependsAdapter { export class NodeIDependsAdapter {
onMSFStatusChange(statusType: MsfStatusType, changeReasonType: MsfChangeReasonType) { onMSFStatusChange(_statusType: MsfStatusType, _changeReasonType: MsfChangeReasonType) {
} }
onMSFSsoError(args: unknown) { onMSFSsoError(_args: unknown) {
} }
getGroupCode(args: unknown) { getGroupCode(_args: unknown) {
} }
} }

View File

@@ -1,10 +1,11 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
export class NodeIDispatcherAdapter { export class NodeIDispatcherAdapter {
dispatchRequest(arg: unknown) { dispatchRequest(_arg: unknown) {
} }
dispatchCall(arg: unknown) { dispatchCall(_arg: unknown) {
} }
dispatchCallWithJson(arg: unknown) { dispatchCallWithJson(_arg: unknown) {
} }
} }

View File

@@ -1,25 +1,26 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
export class NodeIGlobalAdapter { export class NodeIGlobalAdapter {
onLog(...args: unknown[]) { onLog(..._args: unknown[]) {
} }
onGetSrvCalTime(...args: unknown[]) { onGetSrvCalTime(..._args: unknown[]) {
} }
onShowErrUITips(...args: unknown[]) { onShowErrUITips(..._args: unknown[]) {
} }
fixPicImgType(...args: unknown[]) { fixPicImgType(..._args: unknown[]) {
} }
getAppSetting(...args: unknown[]) { getAppSetting(..._args: unknown[]) {
} }
onInstallFinished(...args: unknown[]) { onInstallFinished(..._args: unknown[]) {
} }
onUpdateGeneralFlag(...args: unknown[]) { onUpdateGeneralFlag(..._args: unknown[]) {
} }
onGetOfflineMsg(...args: unknown[]) { onGetOfflineMsg(..._args: unknown[]) {
} }
} }

View File

@@ -27,6 +27,7 @@ import { encodeSilk } from '@/common/audio';
import { SendMessageContext } from '@/onebot/api'; import { SendMessageContext } from '@/onebot/api';
import { getFileTypeForSendType } from '../helper/msg'; import { getFileTypeForSendType } from '../helper/msg';
import { FFmpegService } from '@/common/ffmpeg'; import { FFmpegService } from '@/common/ffmpeg';
import { rkeyDataType } from '../types/file';
export class NTQQFileApi { export class NTQQFileApi {
context: InstanceContext; context: InstanceContext;
@@ -61,7 +62,7 @@ export class NTQQFileApi {
async uploadFile(filePath: string, elementType: ElementType = ElementType.PIC, elementSubType: number = 0) { async uploadFile(filePath: string, elementType: ElementType = ElementType.PIC, elementSubType: number = 0) {
const fileMd5 = await calculateFileMD5(filePath); const fileMd5 = await calculateFileMD5(filePath);
const extOrEmpty = await fileTypeFromFile(filePath).then(e => e?.ext ?? '').catch(e => ''); const extOrEmpty = await fileTypeFromFile(filePath).then(e => e?.ext ?? '').catch(() => '');
const ext = extOrEmpty ? `.${extOrEmpty}` : ''; const ext = extOrEmpty ? `.${extOrEmpty}` : '';
let fileName = `${path.basename(filePath)}`; let fileName = `${path.basename(filePath)}`;
if (fileName.indexOf('.') === -1) { if (fileName.indexOf('.') === -1) {
@@ -140,7 +141,7 @@ export class NTQQFileApi {
}; };
} }
async createValidSendVideoElement(context: SendMessageContext, filePath: string, fileName: string = '', diyThumbPath: string = ''): Promise<SendVideoElement> { async createValidSendVideoElement(context: SendMessageContext, filePath: string, fileName: string = '', _diyThumbPath: string = ''): Promise<SendVideoElement> {
let videoInfo = { let videoInfo = {
width: 1920, width: 1920,
height: 1080, height: 1080,
@@ -170,10 +171,16 @@ export class NTQQFileApi {
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`); const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
try { try {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath); videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
} catch (error) { } catch {
fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64')); fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
} }
if (_diyThumbPath) {
try {
await this.copyFile(_diyThumbPath, thumbPath);
} catch (e) {
this.context.logger.logError('复制自定义缩略图失败', e);
}
}
const thumbSize = (await fsPromises.stat(thumbPath)).size; const thumbSize = (await fsPromises.stat(thumbPath)).size;
const thumbMd5 = await calculateFileMD5(thumbPath); const thumbMd5 = await calculateFileMD5(thumbPath);
context.deleteAfterSentFiles.push(path); context.deleteAfterSentFiles.push(path);
@@ -275,16 +282,16 @@ export class NTQQFileApi {
) { ) {
switch (element.elementType) { switch (element.elementType) {
case ElementType.PIC: case ElementType.PIC:
element.picElement!.sourcePath = elementResults[elementIndex]; element.picElement!.sourcePath = elementResults?.[elementIndex] ?? '';
break; break;
case ElementType.VIDEO: case ElementType.VIDEO:
element.videoElement!.filePath = elementResults[elementIndex]; element.videoElement!.filePath = elementResults?.[elementIndex] ?? '';
break; break;
case ElementType.PTT: case ElementType.PTT:
element.pttElement!.filePath = elementResults[elementIndex]; element.pttElement!.filePath = elementResults?.[elementIndex] ?? '';
break; break;
case ElementType.FILE: case ElementType.FILE:
element.fileElement!.filePath = elementResults[elementIndex]; element.fileElement!.filePath = elementResults?.[elementIndex] ?? '';
break; break;
} }
elementIndex++; elementIndex++;
@@ -299,7 +306,7 @@ export class NTQQFileApi {
if (force) { if (force) {
try { try {
await fsPromises.unlink(sourcePath); await fsPromises.unlink(sourcePath);
} catch (e) { } catch {
// //
} }
} else { } else {
@@ -401,27 +408,27 @@ export class NTQQFileApi {
} }
private async getRkeyData() { private async getRkeyData() {
const rkeyData = { const rkeyData: rkeyDataType = {
private_rkey: 'CAQSKAB6JWENi5LM_xp9vumLbuThJSaYf-yzMrbZsuq7Uz2qEc3Rbib9LP4', private_rkey: 'CAQSKAB6JWENi5LM_xp9vumLbuThJSaYf-yzMrbZsuq7Uz2qEc3Rbib9LP4',
group_rkey: 'CAQSKAB6JWENi5LM_xp9vumLbuThJSaYf-yzMrbZsuq7Uz2qffcqm614gds', group_rkey: 'CAQSKAB6JWENi5LM_xp9vumLbuThJSaYf-yzMrbZsuq7Uz2qffcqm614gds',
online_rkey: false online_rkey: false
}; };
try { try {
if (this.core.apis.PacketApi.available) { if (this.core.apis.PacketApi.available && this.packetRkey?.[0] && this.packetRkey?.[1]) {
const rkey_expired_private = !this.packetRkey || this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000; const rkey_expired_private = !this.packetRkey || this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000;
const rkey_expired_group = !this.packetRkey || this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000; const rkey_expired_group = !this.packetRkey || this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000;
if (rkey_expired_private || rkey_expired_group) { if (rkey_expired_private || rkey_expired_group) {
this.packetRkey = await this.core.apis.PacketApi.pkt.operation.FetchRkey(); this.packetRkey = await this.core.apis.PacketApi.pkt.operation.FetchRkey();
} }
if (this.packetRkey && this.packetRkey.length > 0) { if (this.packetRkey && this.packetRkey.length > 0) {
rkeyData.group_rkey = this.packetRkey[1].rkey.slice(6); rkeyData.group_rkey = this.packetRkey[1]?.rkey.slice(6) ?? '';
rkeyData.private_rkey = this.packetRkey[0].rkey.slice(6); rkeyData.private_rkey = this.packetRkey[0]?.rkey.slice(6) ?? '';
rkeyData.online_rkey = true; rkeyData.online_rkey = true;
} }
} }
} catch (error: any) { } catch (error: unknown) {
this.context.logger.logError('获取rkey失败', error.message); this.context.logger.logError('获取rkey失败', (error as Error).message);
} }
if (!rkeyData.online_rkey) { if (!rkeyData.online_rkey) {
@@ -438,7 +445,7 @@ export class NTQQFileApi {
return rkeyData; return rkeyData;
} }
private getImageUrlFromParsedUrl(imageFileId: string, appid: string, rkeyData: any): string { private getImageUrlFromParsedUrl(imageFileId: string, appid: string, rkeyData: rkeyDataType): string {
const rkey = appid === '1406' ? rkeyData.private_rkey : rkeyData.group_rkey; const rkey = appid === '1406' ? rkeyData.private_rkey : rkeyData.group_rkey;
if (rkeyData.online_rkey) { if (rkeyData.online_rkey) {
return IMAGE_HTTP_HOST_NT + `/download?appid=${appid}&fileid=${imageFileId}&rkey=${rkey}`; return IMAGE_HTTP_HOST_NT + `/download?appid=${appid}&fileid=${imageFileId}&rkey=${rkey}`;

View File

@@ -13,7 +13,7 @@ export class NTQQFriendApi {
async setBuddyRemark(uid: string, remark: string) { async setBuddyRemark(uid: string, remark: string) {
return this.context.session.getBuddyService().setBuddyRemark({ uid, remark }); return this.context.session.getBuddyService().setBuddyRemark({ uid, remark });
} }
async getBuddyV2SimpleInfoMap(refresh = false) { async getBuddyV2SimpleInfoMap() {
const buddyService = this.context.session.getBuddyService(); const buddyService = this.context.session.getBuddyService();
const buddyListV2 = await buddyService.getBuddyListV2('0', BuddyListReqType.KNOMAL); const buddyListV2 = await buddyService.getBuddyListV2('0', BuddyListReqType.KNOMAL);
const uids = buddyListV2.data.flatMap(item => item.buddyUids); const uids = buddyListV2.data.flatMap(item => item.buddyUids);
@@ -24,13 +24,13 @@ export class NTQQFriendApi {
); );
} }
async getBuddy(refresh = false): Promise<FriendV2[]> { async getBuddy(): Promise<FriendV2[]> {
return Array.from((await this.getBuddyV2SimpleInfoMap(refresh)).values()); return Array.from((await this.getBuddyV2SimpleInfoMap()).values());
} }
async getBuddyIdMap(refresh = false): Promise<LimitedHashTable<string, string>> { async getBuddyIdMap(): Promise<LimitedHashTable<string, string>> {
const retMap: LimitedHashTable<string, string> = new LimitedHashTable<string, string>(5000); const retMap: LimitedHashTable<string, string> = new LimitedHashTable<string, string>(5000);
const data = await this.getBuddyV2SimpleInfoMap(refresh); const data = await this.getBuddyV2SimpleInfoMap();
data.forEach((value) => retMap.set(value.uin!, value.uid!)); data.forEach((value) => retMap.set(value.uin!, value.uid!));
return retMap; return retMap;
} }

View File

@@ -59,7 +59,7 @@ export class NTQQGroupApi {
}, pskey); }, pskey);
} }
async getGroupShutUpMemberList(groupCode: string) { async getGroupShutUpMemberList(groupCode: string): Promise<ShutUpGroupMember[]> {
const executor: TaskExecutor<ShutUpGroupMember[]> = async (resolve, reject, onCancel) => { const executor: TaskExecutor<ShutUpGroupMember[]> = async (resolve, reject, onCancel) => {
this.core.eventWrapper.registerListen( this.core.eventWrapper.registerListen(
'NodeIKernelGroupListener/onShutUpMemberListChanged', 'NodeIKernelGroupListener/onShutUpMemberListChanged',
@@ -215,6 +215,9 @@ export class NTQQGroupApi {
guildId: '', guildId: '',
peerUid: groupCode, peerUid: groupCode,
}, msgId, 1, false); }, msgId, 1, false);
if (!MsgData.msgList[0]) {
throw new Error('消息不存在');
}
const param = { const param = {
groupCode: groupCode, groupCode: groupCode,
msgRandom: parseInt(MsgData.msgList[0].msgRandom), msgRandom: parseInt(MsgData.msgList[0].msgRandom),
@@ -255,6 +258,9 @@ export class NTQQGroupApi {
guildId: '', guildId: '',
peerUid: groupCode, peerUid: groupCode,
}, msgId, 1, false); }, msgId, 1, false);
if (!MsgData.msgList[0]) {
throw new Error('消息不存在');
}
const param = { const param = {
groupCode: groupCode, groupCode: groupCode,
msgRandom: parseInt(MsgData.msgList[0].msgRandom), msgRandom: parseInt(MsgData.msgList[0].msgRandom),

View File

@@ -5,3 +5,5 @@ export * from './msg';
export * from './user'; export * from './user';
export * from './webapi'; export * from './webapi';
export * from './system'; export * from './system';
export * from './packet';
export * from './file';

View File

@@ -201,7 +201,7 @@ export class NTQQMsgApi {
return this.context.session.getMsgService().getTempChatInfo(chatType, peerUid); return this.context.session.getMsgService().getTempChatInfo(chatType, peerUid);
} }
async sendMsg(peer: Peer, msgElements: SendMessageElement[], waitComplete = true, timeout = 10000) { async sendMsg(peer: Peer, msgElements: SendMessageElement[], timeout = 10000) {
//唉?!我有个想法 //唉?!我有个想法
if (peer.chatType === ChatType.KCHATTYPETEMPC2CFROMGROUP && peer.guildId && peer.guildId !== '') { if (peer.chatType === ChatType.KCHATTYPETEMPC2CFROMGROUP && peer.guildId && peer.guildId !== '') {
const member = await this.core.apis.GroupApi.getGroupMember(peer.guildId, peer.peerUid); const member = await this.core.apis.GroupApi.getGroupMember(peer.guildId, peer.peerUid);
@@ -268,7 +268,7 @@ export class NTQQMsgApi {
if (!arkElement) { if (!arkElement) {
continue; continue;
} }
const forwardData: any = JSON.parse(arkElement.arkElement?.bytesData ?? ''); const forwardData: { app: string } = JSON.parse(arkElement.arkElement?.bytesData ?? '');
if (forwardData.app != 'com.tencent.multimsg') { if (forwardData.app != 'com.tencent.multimsg') {
continue; continue;
} }

View File

@@ -25,7 +25,7 @@ export class NTQQSystemApi {
this.context.session.getMsgService().getOnLineDev(); this.context.session.getMsgService().getOnLineDev();
} }
async getArkJsonCollection(cid: string) { async getArkJsonCollection() {
return await this.core.eventWrapper.callNoListenerEvent('NodeIKernelCollectionService/collectionArkShare', '1717662698058'); return await this.core.eventWrapper.callNoListenerEvent('NodeIKernelCollectionService/collectionArkShare', '1717662698058');
} }

View File

@@ -69,7 +69,7 @@ export class NTQQUserApi {
} }
async fetchUserDetailInfo(uid: string, mode: UserDetailSource = UserDetailSource.KDB) { async fetchUserDetailInfo(uid: string, mode: UserDetailSource = UserDetailSource.KDB) {
const [_retData, profile] = await this.core.eventWrapper.callNormalEventV2( const [, profile] = await this.core.eventWrapper.callNormalEventV2(
'NodeIKernelProfileService/fetchUserDetailInfo', 'NodeIKernelProfileService/fetchUserDetailInfo',
'NodeIKernelProfileListener/onUserDetailInfoChanged', 'NodeIKernelProfileListener/onUserDetailInfoChanged',
[ [
@@ -130,10 +130,10 @@ export class NTQQUserApi {
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + this.core.selfInfo.uin + const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + this.core.selfInfo.uin +
'&clientkey=' + ClientKeyData.clientKey + '&u1=https%3A%2F%2F' + domain + '%2F' + this.core.selfInfo.uin + '%2Finfocenter&keyindex=19%27'; '&clientkey=' + ClientKeyData.clientKey + '&u1=https%3A%2F%2F' + domain + '%2F' + this.core.selfInfo.uin + '%2Finfocenter&keyindex=19%27';
const data = await RequestUtil.HttpsGetCookies(requestUrl); const data = await RequestUtil.HttpsGetCookies(requestUrl);
if (!data.p_skey || data.p_skey.length == 0) { if (!data['p_skey'] || data['p_skey'].length == 0) {
try { try {
const pskey = (await this.getPSkey([domain])).domainPskeyMap.get(domain); const pskey = (await this.getPSkey([domain])).domainPskeyMap.get(domain);
if (pskey) data.p_skey = pskey; if (pskey) data['p_skey'] = pskey;
} catch { } catch {
return data; return data;
} }
@@ -145,7 +145,7 @@ export class NTQQUserApi {
return await this.context.session.getTipOffService().getPskey(domainList, true); return await this.context.session.getTipOffService().getPskey(domainList, true);
} }
async getRobotUinRange(): Promise<Array<any>> { async getRobotUinRange(): Promise<Array<unknown>> {
const robotUinRanges = await this.context.session.getRobotService().getRobotUinRange({ const robotUinRanges = await this.context.session.getRobotService().getRobotUinRange({
justFetchMsgConfig: '1', justFetchMsgConfig: '1',
type: 1, type: 1,

View File

@@ -32,7 +32,7 @@ export class NTQQWebApi {
}).toString()}`; }).toString()}`;
try { try {
return RequestUtil.HttpGetText(url, 'GET', '', { 'Cookie': this.cookieToString(cookieObject) }); return RequestUtil.HttpGetText(url, 'GET', '', { 'Cookie': this.cookieToString(cookieObject) });
} catch (e) { } catch {
return undefined; return undefined;
} }
} }
@@ -67,7 +67,7 @@ export class NTQQWebApi {
} }
} }
async getGroupMembers(GroupCode: string, cached: boolean = true): Promise<WebApiGroupMember[]> { async getGroupMembers(GroupCode: string): Promise<WebApiGroupMember[]> {
//logDebug('webapi 获取群成员', GroupCode); //logDebug('webapi 获取群成员', GroupCode);
const memberData: Array<WebApiGroupMember> = new Array<WebApiGroupMember>(); const memberData: Array<WebApiGroupMember> = new Array<WebApiGroupMember>();
const cookieObject = await this.core.apis.UserApi.getCookies('qun.qq.com'); const cookieObject = await this.core.apis.UserApi.getCookies('qun.qq.com');
@@ -88,7 +88,9 @@ export class NTQQWebApi {
return []; return [];
} else { } else {
for (const key in fastRet.mems) { for (const key in fastRet.mems) {
memberData.push(fastRet.mems[key]); if (fastRet.mems[key]) {
memberData.push(fastRet.mems[key]);
}
} }
} }
//初始化获取PageNum //初始化获取PageNum
@@ -116,7 +118,9 @@ export class NTQQWebApi {
continue; continue;
} }
for (const key in ret.mems) { for (const key in ret.mems) {
memberData.push(ret.mems[key]); if (ret.mems[key]) {
memberData.push(ret.mems[key]);
}
} }
} }
return memberData; return memberData;
@@ -185,7 +189,7 @@ export class NTQQWebApi {
{ 'Cookie': this.cookieToString(cookieObject) } { 'Cookie': this.cookieToString(cookieObject) }
); );
return ret; return ret;
} catch (e) { } catch {
return undefined; return undefined;
} }
} }
@@ -210,12 +214,12 @@ export class NTQQWebApi {
{ 'Cookie': this.cookieToString(cookieObject) } { 'Cookie': this.cookieToString(cookieObject) }
); );
return ret?.ec === 0 ? ret : undefined; return ret?.ec === 0 ? ret : undefined;
} catch (e) { } catch {
return undefined; return undefined;
} }
} }
private async getDataInternal(cookieObject: any, groupCode: string, type: number) { private async getDataInternal(cookieObject: { [key: string]: string }, groupCode: string, type: number) {
let resJson; let resJson;
try { try {
const res = await RequestUtil.HttpGetText( const res = await RequestUtil.HttpGetText(
@@ -228,7 +232,7 @@ export class NTQQWebApi {
{ 'Cookie': this.cookieToString(cookieObject) } { 'Cookie': this.cookieToString(cookieObject) }
); );
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res); const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
if (match) { if (match?.[1]) {
resJson = JSON.parse(match[1].trim()); resJson = JSON.parse(match[1].trim());
} }
return type === 1 ? resJson?.talkativeList : resJson?.actorList; return type === 1 ? resJson?.talkativeList : resJson?.actorList;
@@ -238,13 +242,18 @@ export class NTQQWebApi {
} }
} }
private async getHonorList(cookieObject: any, groupCode: string, type: number) { private async getHonorList(cookieObject: { [key: string]: string }, groupCode: string, type: number) {
const data = await this.getDataInternal(cookieObject, groupCode, type); const data = await this.getDataInternal(cookieObject, groupCode, type);
if (!data) { if (!data) {
this.context.logger.logError(`获取类型 ${type} 的荣誉信息失败`); this.context.logger.logError(`获取类型 ${type} 的荣誉信息失败`);
return []; return [];
} }
return data.map((item: any) => ({ return data.map((item: {
uin: string,
name: string,
avatar: string,
desc: string,
}) => ({
user_id: item?.uin, user_id: item?.uin,
nickname: item?.name, nickname: item?.name,
avatar: item?.avatar, avatar: item?.avatar,
@@ -254,7 +263,15 @@ export class NTQQWebApi {
async getGroupHonorInfo(groupCode: string, getType: WebHonorType) { async getGroupHonorInfo(groupCode: string, getType: WebHonorType) {
const cookieObject = await this.core.apis.UserApi.getCookies('qun.qq.com'); const cookieObject = await this.core.apis.UserApi.getCookies('qun.qq.com');
const HonorInfo: any = { group_id: groupCode }; let HonorInfo = {
group_id: groupCode,
current_talkative: {},
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
if (getType === WebHonorType.TALKATIVE || getType === WebHonorType.ALL) { if (getType === WebHonorType.TALKATIVE || getType === WebHonorType.ALL) {
const talkativeList = await this.getHonorList(cookieObject, groupCode, 1); const talkativeList = await this.getHonorList(cookieObject, groupCode, 1);
@@ -284,12 +301,12 @@ export class NTQQWebApi {
return HonorInfo; return HonorInfo;
} }
private cookieToString(cookieObject: any) { private cookieToString(cookieObject: { [key: string]: string }) {
return Object.entries(cookieObject).map(([key, value]) => `${key}=${value}`).join('; '); return Object.entries(cookieObject).map(([key, value]) => `${key}=${value}`).join('; ');
} }
public getBknFromCookie(cookieObject: any) { public getBknFromCookie(cookieObject: { [key: string]: string }) {
const sKey = cookieObject.skey as string; const sKey = cookieObject['skey'] as string;
let hash = 5381; let hash = 5381;
for (let i = 0; i < sKey.length; i++) { for (let i = 0; i < sKey.length; i++) {

View File

@@ -51,7 +51,7 @@ export class RkeyManager {
return now > this.rkeyData.expired_time; return now > this.rkeyData.expired_time;
} }
async refreshRkey(): Promise<any> { async refreshRkey() {
//刷新rkey //刷新rkey
for (const url of this.serverUrl) { for (const url of this.serverUrl) {
try { try {

View File

@@ -35,9 +35,9 @@ export class StatusHelper {
const { total, active } = currentTimes.map((times, index) => { const { total, active } = currentTimes.map((times, index) => {
const prevTimes = this.cpuTimes[index]; const prevTimes = this.cpuTimes[index];
const totalCurrent = times.user + times.nice + times.sys + times.idle + times.irq; const totalCurrent = times.user + times.nice + times.sys + times.idle + times.irq;
const totalPrev = prevTimes.user + prevTimes.nice + prevTimes.sys + prevTimes.idle + prevTimes.irq; const totalPrev = (prevTimes?.user ?? 0) + (prevTimes?.nice ?? 0) + (prevTimes?.sys ?? 0) + (prevTimes?.idle ?? 0) + (prevTimes?.irq ?? 0);
const activeCurrent = totalCurrent - times.idle; const activeCurrent = totalCurrent - times.idle;
const activePrev = totalPrev - prevTimes.idle; const activePrev = totalPrev - (prevTimes?.idle ?? 0);
return { return {
total: totalCurrent - totalPrev, total: totalCurrent - totalPrev,
active: activeCurrent - activePrev active: activeCurrent - activePrev
@@ -49,8 +49,8 @@ export class StatusHelper {
this.cpuTimes = currentTimes; this.cpuTimes = currentTimes;
return { return {
usage: this.replaceNaN(((active / total) * 100)).toFixed(2), usage: this.replaceNaN(((active / total) * 100)).toFixed(2),
model: os.cpus()[0].model, model: os.cpus()[0]?.model ?? 'none',
speed: os.cpus()[0].speed, speed: os.cpus()[0]?.speed ?? 0,
core: os.cpus().length core: os.cpus().length
}; };
} }

View File

@@ -24,7 +24,7 @@ import path from 'node:path';
import fs from 'node:fs'; import fs from 'node:fs';
import { hostname, systemName, systemVersion } from '@/common/system'; import { hostname, systemName, systemVersion } from '@/common/system';
import { NTEventWrapper } from '@/common/event'; import { NTEventWrapper } from '@/common/event';
import { GroupMember, KickedOffLineInfo, SelfInfo, SelfStatusInfo } from '@/core/types'; import { KickedOffLineInfo, SelfInfo, SelfStatusInfo } from '@/core/types';
import { NapCatConfigLoader } from '@/core/helper/config'; import { NapCatConfigLoader } from '@/core/helper/config';
import os from 'node:os'; import os from 'node:os';
import { NodeIKernelMsgListener, NodeIKernelProfileListener } from '@/core/listeners'; import { NodeIKernelMsgListener, NodeIKernelProfileListener } from '@/core/listeners';
@@ -58,7 +58,7 @@ export function loadQQWrapper(QQVersion: string): WrapperNodeApi {
if (!fs.existsSync(wrapperNodePath)) { if (!fs.existsSync(wrapperNodePath)) {
wrapperNodePath = path.join(path.dirname(process.execPath), `./resources/app/versions/${QQVersion}/wrapper.node`); wrapperNodePath = path.join(path.dirname(process.execPath), `./resources/app/versions/${QQVersion}/wrapper.node`);
} }
const nativemodule: any = { exports: {} }; const nativemodule: { exports: WrapperNodeApi } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperNodePath); process.dlopen(nativemodule, wrapperNodePath);
return nativemodule.exports; return nativemodule.exports;
} }

View File

@@ -52,7 +52,7 @@ export class WsPacketClient extends IPacketClient {
try { try {
await this.connect(); await this.connect();
return; return;
} catch (error) { } catch {
this.reconnectAttempts++; this.reconnectAttempts++;
this.logStack.pushLogWarn(`${this.reconnectAttempts}/${this.maxReconnectAttempts} 次尝试重连失败!`); this.logStack.pushLogWarn(`${this.reconnectAttempts}/${this.maxReconnectAttempts} 次尝试重连失败!`);
await this.delay(5000); await this.delay(5000);

View File

@@ -5,11 +5,11 @@ import { OidbPacket } from '@/core/packet/transformer/base';
import { PacketLogger } from '@/core/packet/context/loggerContext'; import { PacketLogger } from '@/core/packet/context/loggerContext';
import { NapCoreContext } from '@/core/packet/context/napCoreContext'; import { NapCoreContext } from '@/core/packet/context/napCoreContext';
type clientPriority = { type clientPriorityType = {
[key: number]: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => IPacketClient; [key: number]: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => IPacketClient;
} }
const clientPriority: clientPriority = { const clientPriority: clientPriorityType = {
10: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new NativePacketClient(napCore, logger, logStack), 10: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new NativePacketClient(napCore, logger, logStack),
1: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new WsPacketClient(napCore, logger, logStack), 1: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new WsPacketClient(napCore, logger, logStack),
}; };

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { LogLevel, LogWrapper } from '@/common/log'; import { LogLevel, LogWrapper } from '@/common/log';
import { NapCoreContext } from '@/core/packet/context/napCoreContext'; import { NapCoreContext } from '@/core/packet/context/napCoreContext';

View File

@@ -61,7 +61,7 @@ export class PacketOperationContext {
} }
status = Number((extBigInt & 0xff00n) + ((extBigInt >> 16n) & 0xffn)); status = Number((extBigInt & 0xff00n) + ((extBigInt >> 16n) & 0xffn));
return { status: 10, ext_status: status }; return { status: 10, ext_status: status };
} catch (e) { } catch {
return undefined; return undefined;
} }
} }

View File

@@ -27,7 +27,8 @@ export class PacketHighwayClient {
port: number = 80; port: number = 80;
logger: PacketLogger; logger: PacketLogger;
constructor(sig: PacketHighwaySig, logger: PacketLogger, server: string = 'htdata3.qq.com', port: number = 80) { // eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(sig: PacketHighwaySig, logger: PacketLogger, _server: string = 'htdata3.qq.com', _port: number = 80) {
this.sig = sig; this.sig = sig;
this.logger = logger; this.logger = logger;
} }

View File

@@ -17,7 +17,8 @@ class HighwayTcpUploaderTransform extends stream.Transform {
this.offset = 0; this.offset = 0;
} }
_transform(data: Buffer, _: BufferEncoding, callback: stream.TransformCallback) { // eslint-disable-next-line no-undef
override _transform(data: Buffer, _: BufferEncoding, callback: stream.TransformCallback) {
let chunkOffset = 0; let chunkOffset = 0;
while (chunkOffset < data.length) { while (chunkOffset < data.length) {
const chunkSize = Math.min(BlockSize, data.length - chunkOffset); const chunkSize = Math.min(BlockSize, data.length - chunkOffset);
@@ -60,6 +61,7 @@ export class HighwayTcpUploader extends IHighwayUploader {
socket.end(); socket.end();
reject(new Error('Upload aborted due to timeout')); reject(new Error('Upload aborted due to timeout'));
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [head, _] = Frame.unpack(chunk); const [head, _] = Frame.unpack(chunk);
handleRspHeader(head); handleRspHeader(head);
}); });

View File

@@ -14,7 +14,6 @@ import {
GroupFileExtra GroupFileExtra
} from '@/core/packet/transformer/proto'; } from '@/core/packet/transformer/proto';
import { import {
BaseEmojiType,
FaceType, FaceType,
NTMsgAtType, NTMsgAtType,
PicType, PicType,
@@ -36,7 +35,8 @@ import { PacketMsg, PacketSendMsgElement } from '@/core/packet/message/message';
// raw <-> packet // raw <-> packet
// TODO: SendStructLongMsgElement // TODO: SendStructLongMsgElement
export abstract class IPacketMsgElement<T extends PacketSendMsgElement> { export abstract class IPacketMsgElement<T extends PacketSendMsgElement> {
protected constructor(rawElement: T) { // eslint-disable-next-line @typescript-eslint/no-unused-vars
protected constructor(_rawElement: T) {
} }
get valid(): boolean { get valid(): boolean {
@@ -64,7 +64,7 @@ export class PacketMsgTextElement extends IPacketMsgElement<SendTextElement> {
this.text = element.textElement.content; this.text = element.textElement.content;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return [{ return [{
text: { text: {
str: this.text str: this.text
@@ -72,7 +72,7 @@ export class PacketMsgTextElement extends IPacketMsgElement<SendTextElement> {
}]; }];
} }
toPreview(): string { override toPreview(): string {
return this.text; return this.text;
} }
} }
@@ -87,7 +87,7 @@ export class PacketMsgAtElement extends PacketMsgTextElement {
this.atAll = element.textElement.atType === NTMsgAtType.ATTYPEALL; this.atAll = element.textElement.atType === NTMsgAtType.ATTYPEALL;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return [{ return [{
text: { text: {
str: this.text, str: this.text,
@@ -127,7 +127,7 @@ export class PacketMsgReplyElement extends IPacketMsgElement<SendReplyElement> {
return this.messageClientSeq === 0; return this.messageClientSeq === 0;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return [{ return [{
srcMsg: { srcMsg: {
origSeqs: [this.isGroupReply ? this.messageClientSeq : this.messageSeq], origSeqs: [this.isGroupReply ? this.messageClientSeq : this.messageSeq],
@@ -152,7 +152,7 @@ export class PacketMsgReplyElement extends IPacketMsgElement<SendReplyElement> {
}]; }];
} }
toPreview(): string { override toPreview(): string {
return '[回复消息]'; return '[回复消息]';
} }
} }
@@ -169,7 +169,7 @@ export class PacketMsgFaceElement extends IPacketMsgElement<SendFaceElement> {
this.isLargeFace = element.faceElement.faceType === FaceType.AniSticke; this.isLargeFace = element.faceElement.faceType === FaceType.AniSticke;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
if (this.isLargeFace) { if (this.isLargeFace) {
return [{ return [{
commonElem: { commonElem: {
@@ -207,7 +207,7 @@ export class PacketMsgFaceElement extends IPacketMsgElement<SendFaceElement> {
} }
} }
toPreview(): string { override toPreview(): string {
return '[表情]'; return '[表情]';
} }
} }
@@ -226,7 +226,7 @@ export class PacketMsgMarkFaceElement extends IPacketMsgElement<SendMarketFaceEl
this.emojiKey = element.marketFaceElement.key; this.emojiKey = element.marketFaceElement.key;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return [{ return [{
marketFace: { marketFace: {
faceName: this.emojiName, faceName: this.emojiName,
@@ -245,7 +245,7 @@ export class PacketMsgMarkFaceElement extends IPacketMsgElement<SendMarketFaceEl
}]; }];
} }
toPreview(): string { override toPreview(): string {
return `${this.emojiName}`; return `${this.emojiName}`;
} }
} }
@@ -280,11 +280,11 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
) : element.picElement.summary; ) : element.picElement.summary;
} }
get valid(): boolean { override get valid(): boolean {
return !!this.msgInfo; return !!this.msgInfo;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
if (!this.msgInfo) return []; if (!this.msgInfo) return [];
return [{ return [{
commonElem: { commonElem: {
@@ -295,7 +295,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
}]; }];
} }
toPreview(): string { override toPreview(): string {
return this.summary; return this.summary;
} }
} }
@@ -318,18 +318,18 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
this.fileSize = element.videoElement.fileSize; this.fileSize = element.videoElement.fileSize;
this.filePath = element.videoElement.filePath; this.filePath = element.videoElement.filePath;
this.thumbSize = element.videoElement.thumbSize; this.thumbSize = element.videoElement.thumbSize;
this.thumbPath = element.videoElement.thumbPath?.get(0); this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
this.fileMd5 = element.videoElement.videoMd5; this.fileMd5 = element.videoElement.videoMd5;
this.thumbMd5 = element.videoElement.thumbMd5; this.thumbMd5 = element.videoElement.thumbMd5;
this.thumbWidth = element.videoElement.thumbWidth; this.thumbWidth = element.videoElement.thumbWidth;
this.thumbHeight = element.videoElement.thumbHeight; this.thumbHeight = element.videoElement.thumbHeight;
} }
get valid(): boolean { override get valid(): boolean {
return !!this.msgInfo; return !!this.msgInfo;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
if (!this.msgInfo) return []; if (!this.msgInfo) return [];
return [{ return [{
commonElem: { commonElem: {
@@ -340,7 +340,7 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
}]; }];
} }
toPreview(): string { override toPreview(): string {
return '[视频]'; return '[视频]';
} }
} }
@@ -361,11 +361,11 @@ export class PacketMsgPttElement extends IPacketMsgElement<SendPttElement> {
this.fileDuration = Math.round(element.pttElement.duration); // TODO: cc this.fileDuration = Math.round(element.pttElement.duration); // TODO: cc
} }
get valid(): boolean { override get valid(): boolean {
return false; return false;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return []; return [];
// if (!this.msgInfo) return []; // if (!this.msgInfo) return [];
// return [{ // return [{
@@ -377,7 +377,7 @@ export class PacketMsgPttElement extends IPacketMsgElement<SendPttElement> {
// }]; // }];
} }
toPreview(): string { override toPreview(): string {
return '[语音]'; return '[语音]';
} }
} }
@@ -402,11 +402,11 @@ export class PacketMsgFileElement extends IPacketMsgElement<SendFileElement> {
this.fileSize = +element.fileElement.fileSize; this.fileSize = +element.fileElement.fileSize;
} }
get valid(): boolean { override get valid(): boolean {
return this.isGroupFile || Boolean(this._e37_800_rsp); return this.isGroupFile || Boolean(this._e37_800_rsp);
} }
buildContent(): Uint8Array | undefined { override buildContent(): Uint8Array | undefined {
if (this.isGroupFile || !this._e37_800_rsp) return undefined; if (this.isGroupFile || !this._e37_800_rsp) return undefined;
return new NapProtoMsg(FileExtra).encode({ return new NapProtoMsg(FileExtra).encode({
file: { file: {
@@ -437,7 +437,7 @@ export class PacketMsgFileElement extends IPacketMsgElement<SendFileElement> {
}); });
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
if (!this.isGroupFile) return []; if (!this.isGroupFile) return [];
const lb = Buffer.alloc(2); const lb = Buffer.alloc(2);
const transElemVal = new NapProtoMsg(GroupFileExtra).encode({ const transElemVal = new NapProtoMsg(GroupFileExtra).encode({
@@ -464,7 +464,7 @@ export class PacketMsgFileElement extends IPacketMsgElement<SendFileElement> {
}]; }];
} }
toPreview(): string { override toPreview(): string {
return `[文件]${this.fileName}`; return `[文件]${this.fileName}`;
} }
} }
@@ -477,7 +477,7 @@ export class PacketMsgLightAppElement extends IPacketMsgElement<SendArkElement>
this.payload = element.arkElement.bytesData; this.payload = element.arkElement.bytesData;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return [{ return [{
lightAppElem: { lightAppElem: {
data: Buffer.concat([ data: Buffer.concat([
@@ -488,7 +488,7 @@ export class PacketMsgLightAppElement extends IPacketMsgElement<SendArkElement>
}]; }];
} }
toPreview(): string { override toPreview(): string {
return '[卡片消息]'; return '[卡片消息]';
} }
} }
@@ -501,7 +501,7 @@ export class PacketMsgMarkDownElement extends IPacketMsgElement<SendMarkdownElem
this.content = element.markdownElement.content; this.content = element.markdownElement.content;
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return [{ return [{
commonElem: { commonElem: {
serviceType: 45, serviceType: 45,
@@ -513,7 +513,7 @@ export class PacketMsgMarkDownElement extends IPacketMsgElement<SendMarkdownElem
}]; }];
} }
toPreview(): string { override toPreview(): string {
return `[Markdown消息 ${this.content}]`; return `[Markdown消息 ${this.content}]`;
} }
} }
@@ -528,7 +528,7 @@ export class PacketMultiMsgElement extends IPacketMsgElement<SendStructLongMsgEl
this.message = message ?? []; this.message = message ?? [];
} }
buildElement(): NapProtoEncodeStructType<typeof Elem>[] { override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
return [{ return [{
lightAppElem: { lightAppElem: {
data: Buffer.concat([ data: Buffer.concat([
@@ -539,7 +539,7 @@ export class PacketMultiMsgElement extends IPacketMsgElement<SendStructLongMsgEl
}]; }];
} }
toPreview(): string { override toPreview(): string {
return '[聊天记录]'; return '[聊天记录]';
} }
} }

View File

@@ -1,3 +1,5 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
export class Sha1Stream { export class Sha1Stream {
readonly Sha1BlockSize = 64; readonly Sha1BlockSize = 64;
readonly Sha1DigestSize = 20; readonly Sha1DigestSize = 20;

View File

@@ -16,7 +16,8 @@ export class CalculateStreamBytesTransform extends stream.Transform {
this.byteArrayList = []; this.byteArrayList = [];
} }
_transform(chunk: Buffer, _: BufferEncoding, callback: stream.TransformCallback): void { // eslint-disable-next-line no-undef
override _transform(chunk: Buffer, _: BufferEncoding, callback: stream.TransformCallback): void {
try { try {
this.buffer = Buffer.concat([this.buffer, chunk]); this.buffer = Buffer.concat([this.buffer, chunk]);
let offset = 0; let offset = 0;
@@ -37,7 +38,7 @@ export class CalculateStreamBytesTransform extends stream.Transform {
} }
} }
_flush(callback: stream.TransformCallback): void { override _flush(callback: stream.TransformCallback): void {
try { try {
if (this.buffer.length > 0) this.sha1.update(this.buffer); if (this.buffer.length > 0) this.sha1.update(this.buffer);
const finalDigest = this.sha1.final(); const finalDigest = this.sha1.final();

View File

@@ -1,4 +1,6 @@
// love from https://github.com/LagrangeDev/lagrangejs/blob/main/src/core/tea.ts & https://github.com/takayama-lily/oicq/blob/main/lib/core/tea.ts // love from https://github.com/LagrangeDev/lagrangejs/blob/main/src/core/tea.ts & https://github.com/takayama-lily/oicq/blob/main/lib/core/tea.ts
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
const BUF7 = Buffer.alloc(7); const BUF7 = Buffer.alloc(7);
const deltas = [ const deltas = [
0x9e3779b9, 0x3c6ef372, 0xdaa66d2b, 0x78dde6e4, 0x1715609d, 0xb54cda56, 0x5384540f, 0xf1bbcdc8, 0x8ff34781, 0x9e3779b9, 0x3c6ef372, 0xdaa66d2b, 0x78dde6e4, 0x1715609d, 0xb54cda56, 0x5384540f, 0xf1bbcdc8, 0x8ff34781,

View File

@@ -1,47 +1,47 @@
export interface NodeIKernelAlbumService { export interface NodeIKernelAlbumService {
setAlbumServiceInfo(...args: any[]): unknown;// needs 3 arguments setAlbumServiceInfo(...args: unknown[]): unknown;// needs 3 arguments
getMainPage(...args: any[]): unknown;// needs 2 arguments getMainPage(...args: unknown[]): unknown;// needs 2 arguments
getAlbumList(...args: any[]): unknown;// needs 1 arguments getAlbumList(...args: unknown[]): unknown;// needs 1 arguments
getAlbumInfo(...args: any[]): unknown;// needs 1 arguments getAlbumInfo(...args: unknown[]): unknown;// needs 1 arguments
deleteAlbum(...args: any[]): unknown;// needs 3 arguments deleteAlbum(...args: unknown[]): unknown;// needs 3 arguments
addAlbum(...args: any[]): unknown;// needs 2 arguments addAlbum(...args: unknown[]): unknown;// needs 2 arguments
deleteMedias(...args: any[]): unknown;// needs 4 arguments deleteMedias(...args: unknown[]): unknown;// needs 4 arguments
modifyAlbum(...args: any[]): unknown;// needs 3 arguments modifyAlbum(...args: unknown[]): unknown;// needs 3 arguments
getMediaList(...args: any[]): unknown;// needs 1 arguments getMediaList(...args: unknown[]): unknown;// needs 1 arguments
quoteToQzone(...args: any[]): unknown;// needs 1 arguments quoteToQzone(...args: unknown[]): unknown;// needs 1 arguments
quoteToQunAlbum(...args: any[]): unknown;// needs 1 arguments quoteToQunAlbum(...args: unknown[]): unknown;// needs 1 arguments
queryQuoteToQunAlbumStatus(...args: any[]): unknown;// needs 1 arguments queryQuoteToQunAlbumStatus(...args: unknown[]): unknown;// needs 1 arguments
getQunFeeds(...args: any[]): unknown;//needs 1 arguments getQunFeeds(...args: unknown[]): unknown;//needs 1 arguments
getQunFeedDetail(...args: any[]): unknown;// needs 1 arguments getQunFeedDetail(...args: unknown[]): unknown;// needs 1 arguments
getQunNoticeList(...args: any[]): unknown;// needs 4 arguments getQunNoticeList(...args: unknown[]): unknown;// needs 4 arguments
getQunComment(...args: any[]): unknown;// needs 1 arguments getQunComment(...args: unknown[]): unknown;// needs 1 arguments
getQunLikes(...args: any[]): unknown;// needs 4 arguments getQunLikes(...args: unknown[]): unknown;// needs 4 arguments
deleteQunFeed(...args: any[]): unknown;// needs 1 arguments deleteQunFeed(...args: unknown[]): unknown;// needs 1 arguments
doQunComment(...args: any[]): unknown;// needs 6 arguments doQunComment(...args: unknown[]): unknown;// needs 6 arguments
doQunReply(...args: any[]): unknown;// needs 7 arguments doQunReply(...args: unknown[]): unknown;// needs 7 arguments
doQunLike(...args: any[]): unknown;// needs 5 arguments doQunLike(...args: unknown[]): unknown;// needs 5 arguments
getRedPoints(...args: any[]): unknown;// needs 3 arguments getRedPoints(...args: unknown[]): unknown;// needs 3 arguments
} }

View File

@@ -1,7 +1,7 @@
import { GeneralCallResult } from './common'; import { GeneralCallResult } from './common';
export interface NodeIKernelCollectionService { export interface NodeIKernelCollectionService {
addKernelCollectionListener(...args: any[]): void;//needs 1 arguments addKernelCollectionListener(...args: unknown[]): void;//needs 1 arguments
removeKernelCollectionListener(listenerId: number): void; removeKernelCollectionListener(listenerId: number): void;
@@ -55,37 +55,37 @@ export interface NodeIKernelCollectionService {
} }
>; >;
getCollectionContent(...args: any[]): unknown;//needs 5 arguments getCollectionContent(...args: unknown[]): unknown;//needs 5 arguments
getCollectionCustomGroupList(...args: any[]): unknown;//needs 0 arguments getCollectionCustomGroupList(...args: unknown[]): unknown;//needs 0 arguments
getCollectionUserInfo(...args: any[]): unknown;//needs 0 arguments getCollectionUserInfo(...args: unknown[]): unknown;//needs 0 arguments
searchCollectionItemList(...args: any[]): unknown;//needs 2 arguments searchCollectionItemList(...args: unknown[]): unknown;//needs 2 arguments
addMsgToCollection(...args: any[]): unknown;//needs 2 arguments addMsgToCollection(...args: unknown[]): unknown;//needs 2 arguments
collectionArkShare(...args: any[]): unknown;//needs 1 arguments collectionArkShare(...args: unknown[]): unknown;//needs 1 arguments
collectionFileForward(...args: any[]): unknown;//needs 3 arguments collectionFileForward(...args: unknown[]): unknown;//needs 3 arguments
downloadCollectionFile(...args: any[]): unknown;//needs 4 arguments downloadCollectionFile(...args: unknown[]): unknown;//needs 4 arguments
downloadCollectionFileThumbPic(...args: any[]): unknown;//needs 4 arguments downloadCollectionFileThumbPic(...args: unknown[]): unknown;//needs 4 arguments
downloadCollectionPic(...args: any[]): unknown;//needs 3 arguments downloadCollectionPic(...args: unknown[]): unknown;//needs 3 arguments
cancelDownloadCollectionFile(...args: any[]): unknown;//needs 1 arguments cancelDownloadCollectionFile(...args: unknown[]): unknown;//needs 1 arguments
deleteCollectionItemList(...args: any[]): unknown;//needs 1 arguments deleteCollectionItemList(...args: unknown[]): unknown;//needs 1 arguments
editCollectionItem(...args: any[]): unknown;//needs 2 arguments editCollectionItem(...args: unknown[]): unknown;//needs 2 arguments
getEditPicInfoByPath(...args: any[]): unknown;//needs 1 arguments getEditPicInfoByPath(...args: unknown[]): unknown;//needs 1 arguments
collectionFastUpload(...args: any[]): unknown;//needs 1 arguments collectionFastUpload(...args: unknown[]): unknown;//needs 1 arguments
editCollectionItemAfterFastUpload(...args: any[]): unknown;//needs 2 arguments editCollectionItemAfterFastUpload(...args: unknown[]): unknown;//needs 2 arguments
createNewCollectionItem(...args: any[]): unknown;//needs 1 arguments createNewCollectionItem(...args: unknown[]): unknown;//needs 1 arguments
} }

View File

@@ -20,7 +20,7 @@ export interface NodeIKernelGroupService {
getAllGroupPrivilegeFlag(troopUinList: string[], serviceType: number): Promise<unknown>; getAllGroupPrivilegeFlag(troopUinList: string[], serviceType: number): Promise<unknown>;
// <--- // <---
getGroupExt0xEF0Info(enableGroupCodes: string[], bannedGroupCodes: string[], filter: GroupExt0xEF0InfoFilter, forceFetch: boolean): getGroupExt0xEF0Info(enableGroupCodes: string[], bannedGroupCodes: string[], filter: GroupExt0xEF0InfoFilter, forceFetch: boolean):
Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, any> } }>; Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, unknown> } }>;
kickMemberV2(param: KickMemberV2Req): Promise<GeneralCallResult>; kickMemberV2(param: KickMemberV2Req): Promise<GeneralCallResult>;
@@ -153,7 +153,7 @@ export interface NodeIKernelGroupService {
getMemberExtInfo(param: GroupExtParam): Promise<unknown>;//req getMemberExtInfo(param: GroupExtParam): Promise<unknown>;//req
getGroupAllInfo(groupId: string, sourceId: number): Promise<any>; getGroupAllInfo(groupId: string, sourceId: number): Promise<unknown>;
getDiscussExistInfo(): unknown; getDiscussExistInfo(): unknown;
@@ -213,7 +213,7 @@ export interface NodeIKernelGroupService {
deleteGroupBulletin(groupCode: string, seq: string, noticeId: string): void; deleteGroupBulletin(groupCode: string, seq: string, noticeId: string): void;
publishGroupBulletin(groupCode: string, pskey: string, data: any): Promise<GeneralCallResult>; publishGroupBulletin(groupCode: string, pskey: string, data: unknown): Promise<GeneralCallResult>;
publishInstructionForNewcomers(groupCode: string, arg: unknown): void; publishInstructionForNewcomers(groupCode: string, arg: unknown): void;

View File

@@ -82,7 +82,7 @@ export interface NodeIKernelLoginService {
quickLoginWithUin(uin: string): Promise<QuickLoginResult>; quickLoginWithUin(uin: string): Promise<QuickLoginResult>;
passwordLogin(param: PasswordLoginArgType): Promise<any>; passwordLogin(param: PasswordLoginArgType): Promise<unknown>;
getQRCodePicture(): boolean; getQRCodePicture(): boolean;
} }

View File

@@ -3,25 +3,25 @@ export interface NodeIKernelMsgBackupService {
removeKernelMsgBackupListener(listenerId: number): void; removeKernelMsgBackupListener(listenerId: number): void;
getMsgBackupLocation(...args: any[]): unknown;// needs 0 arguments getMsgBackupLocation(...args: unknown[]): unknown;// needs 0 arguments
setMsgBackupLocation(...args: any[]): unknown;// needs 1 arguments setMsgBackupLocation(...args: unknown[]): unknown;// needs 1 arguments
requestMsgBackup(...args: any[]): unknown;// needs 0 arguments requestMsgBackup(...args: unknown[]): unknown;// needs 0 arguments
requestMsgRestore(...args: any[]): unknown;// needs 1 arguments requestMsgRestore(...args: unknown[]): unknown;// needs 1 arguments
requestMsgMigrate(...args: any[]): unknown;// needs 1 arguments requestMsgMigrate(...args: unknown[]): unknown;// needs 1 arguments
getLocalStorageBackup(...args: any[]): unknown;// needs 0 arguments getLocalStorageBackup(...args: unknown[]): unknown;// needs 0 arguments
deleteLocalBackup(...args: any[]): unknown;// needs 1 arguments deleteLocalBackup(...args: unknown[]): unknown;// needs 1 arguments
clearCache(...args: any[]): unknown;// needs 0 arguments clearCache(...args: unknown[]): unknown;// needs 0 arguments
start(...args: any[]): unknown;// needs 1 arguments start(...args: unknown[]): unknown;// needs 1 arguments
stop(...args: any[]): unknown;// needs 1 arguments stop(...args: unknown[]): unknown;// needs 1 arguments
pause(...args: any[]): unknown;// needs 2 arguments pause(...args: unknown[]): unknown;// needs 2 arguments
} }

View File

@@ -10,7 +10,7 @@ export interface NodeIKernelMsgService {
addKernelMsgListener(nodeIKernelMsgListener: NodeIKernelMsgListener): number; addKernelMsgListener(nodeIKernelMsgListener: NodeIKernelMsgListener): number;
sendMsg(msgId: string, peer: Peer, msgElements: SendMessageElement[], map: Map<any, any>): Promise<GeneralCallResult>; sendMsg(msgId: string, peer: Peer, msgElements: SendMessageElement[], map: Map<unknown, unknown>): Promise<GeneralCallResult>;
recallMsg(peer: Peer, msgIds: string[]): Promise<GeneralCallResult>; recallMsg(peer: Peer, msgIds: string[]): Promise<GeneralCallResult>;
@@ -114,9 +114,9 @@ export interface NodeIKernelMsgService {
addLocalTofuRecordMsg(...args: unknown[]): unknown; addLocalTofuRecordMsg(...args: unknown[]): unknown;
addLocalRecordMsg(Peer: Peer, msgId: string, ele: MessageElement, attr: Array<any> | number, front: boolean): Promise<unknown>; addLocalRecordMsg(Peer: Peer, msgId: string, ele: MessageElement, attr: Array<unknown> | number, front: boolean): Promise<unknown>;
deleteMsg(Peer: Peer, msgIds: Array<string>): Promise<any>; deleteMsg(Peer: Peer, msgIds: Array<string>): Promise<unknown>;
updateElementExtBufForUI(...args: unknown[]): unknown; updateElementExtBufForUI(...args: unknown[]): unknown;

View File

@@ -30,7 +30,7 @@ export interface NodeIKernelOnlineStatusService {
checkLikeStatus(param: { checkLikeStatus(param: {
businessType: number, businessType: number,
uins: string[] uins: string[]
}): Promise<any>; }): Promise<unknown>;
isNull(): boolean; isNull(): boolean;
} }

View File

@@ -3,11 +3,11 @@ import { BizKey, ModifyProfileParams, NodeIKernelProfileListener, ProfileBizType
import { GeneralCallResult } from '@/core/services/common'; import { GeneralCallResult } from '@/core/services/common';
export interface NodeIKernelProfileService { export interface NodeIKernelProfileService {
getOtherFlag(callfrom: string, uids: string[]): Promise<Map<string, any>>; getOtherFlag(callfrom: string, uids: string[]): Promise<Map<string, unknown>>;
getVasInfo(callfrom: string, uids: string[]): Promise<Map<string, any>>; getVasInfo(callfrom: string, uids: string[]): Promise<Map<string, unknown>>;
getRelationFlag(callfrom: string, uids: string[]): Promise<Map<string, any>>; getRelationFlag(callfrom: string, uids: string[]): Promise<Map<string, unknown>>;
getUidByUin(callfrom: string, uin: Array<string>): Map<string, string>; getUidByUin(callfrom: string, uin: Array<string>): Map<string, string>;
@@ -70,7 +70,7 @@ export interface NodeIKernelProfileService {
getProfileQzonePicInfo(uid: string, type: number, force: boolean): Promise<unknown>; getProfileQzonePicInfo(uid: string, type: number, force: boolean): Promise<unknown>;
// UserRemarkServiceImpl::getStrangerRemarkByUid [] // UserRemarkServiceImpl::getStrangerRemarkByUid []
getCoreInfo(sceneId: string, arg: any[]): unknown; getCoreInfo(sceneId: string, arg: unknown[]): unknown;
isNull(): boolean; isNull(): boolean;
} }

View File

@@ -20,10 +20,10 @@ export interface NodeIKernelRecentContactService {
errMsg: string, errMsg: string,
sortedContactList: Array<number>, sortedContactList: Array<number>,
changedList: Array<{ changedList: Array<{
remark: any; remark: unknown;
peerName: any; peerName: unknown;
sendMemberName: any; sendMemberName: unknown;
sendNickName: any; sendNickName: unknown;
peerUid: string; peerUin: string, msgTime: string, chatType: ChatType, msgId: string peerUid: string; peerUin: string, msgTime: string, chatType: ChatType, msgId: string
}> }>
} }
@@ -59,7 +59,7 @@ export interface NodeIKernelRecentContactService {
deleteRecentContactsVer2(...args: unknown[]): unknown; // 1 arguments deleteRecentContactsVer2(...args: unknown[]): unknown; // 1 arguments
getRecentContactList(): Promise<any>; getRecentContactList(): Promise<unknown>;
getMsgUnreadCount(): unknown; getMsgUnreadCount(): unknown;

View File

@@ -158,7 +158,7 @@ export interface NodeIKernelRichMediaService {
downloadFileForFileInfo(fileInfo: CommonFileInfo[], savePath: string): unknown; downloadFileForFileInfo(fileInfo: CommonFileInfo[], savePath: string): unknown;
createGroupFolder(GroupCode: string, FolderName: string): Promise<GeneralCallResult & { createGroupFolder(GroupCode: string, FolderName: string): Promise<GeneralCallResult & {
resultWithGroupItem: { result: any, groupItem: Array<any> } resultWithGroupItem: { result: unknown, groupItem: Array<unknown> }
}>; }>;
downloadFile(commonFile: CommonFileInfo, arg2: unknown, arg3: unknown, savePath: string): unknown; downloadFile(commonFile: CommonFileInfo, arg2: unknown, arg3: unknown, savePath: string): unknown;
@@ -217,9 +217,9 @@ export interface NodeIKernelRichMediaService {
deleteGroupFile(GroupCode: string, params: Array<number>, Files: Array<string>): Promise<GeneralCallResult & { deleteGroupFile(GroupCode: string, params: Array<number>, Files: Array<string>): Promise<GeneralCallResult & {
transGroupFileResult: { transGroupFileResult: {
result: any result: unknown
successFileIdList: Array<any> successFileIdList: Array<unknown>
failFileIdList: Array<any> failFileIdList: Array<unknown>
} }
}>; }>;

View File

@@ -29,7 +29,7 @@ export interface NodeIKernelRobotService {
setRobotPickTts(arg1: unknown, arg2: unknown): unknown; setRobotPickTts(arg1: unknown, arg2: unknown): unknown;
getRobotUinRange(data: any): Promise<{ response: { robotUinRanges: any } }>; getRobotUinRange(data: unknown): Promise<{ response: { robotUinRanges: Array<unknown> } }>;
isNull(): boolean; isNull(): boolean;
} }

View File

@@ -18,65 +18,65 @@ export interface NodeIKernelSearchService {
searchLocalInfo(keywords: string, type: number/*4*/): unknown; searchLocalInfo(keywords: string, type: number/*4*/): unknown;
cancelSearchLocalInfo(...args: any[]): unknown;// needs 3 arguments cancelSearchLocalInfo(...args: unknown[]): unknown;// needs 3 arguments
searchBuddyChatInfo(...args: any[]): unknown;// needs 2 arguments searchBuddyChatInfo(...args: unknown[]): unknown;// needs 2 arguments
searchMoreBuddyChatInfo(...args: any[]): unknown;// needs 1 arguments searchMoreBuddyChatInfo(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchBuddyChatInfo(...args: any[]): unknown;// needs 3 arguments cancelSearchBuddyChatInfo(...args: unknown[]): unknown;// needs 3 arguments
searchContact(...args: any[]): unknown;// needs 2 arguments searchContact(...args: unknown[]): unknown;// needs 2 arguments
searchMoreContact(...args: any[]): unknown;// needs 1 arguments searchMoreContact(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchContact(...args: any[]): unknown;// needs 3 arguments cancelSearchContact(...args: unknown[]): unknown;// needs 3 arguments
searchGroupChatInfo(...args: any[]): unknown;// needs 3 arguments searchGroupChatInfo(...args: unknown[]): unknown;// needs 3 arguments
resetSearchGroupChatInfoSortType(...args: any[]): unknown;// needs 3 arguments resetSearchGroupChatInfoSortType(...args: unknown[]): unknown;// needs 3 arguments
resetSearchGroupChatInfoFilterMembers(...args: any[]): unknown;// needs 3 arguments resetSearchGroupChatInfoFilterMembers(...args: unknown[]): unknown;// needs 3 arguments
searchMoreGroupChatInfo(...args: any[]): unknown;// needs 1 arguments searchMoreGroupChatInfo(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchGroupChatInfo(...args: any[]): unknown;// needs 3 arguments cancelSearchGroupChatInfo(...args: unknown[]): unknown;// needs 3 arguments
searchChatsWithKeywords(...args: any[]): unknown;// needs 3 arguments searchChatsWithKeywords(...args: unknown[]): unknown;// needs 3 arguments
searchMoreChatsWithKeywords(...args: any[]): unknown;// needs 1 arguments searchMoreChatsWithKeywords(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchChatsWithKeywords(...args: any[]): unknown;// needs 3 arguments cancelSearchChatsWithKeywords(...args: unknown[]): unknown;// needs 3 arguments
searchChatMsgs(...args: any[]): unknown;// needs 2 arguments searchChatMsgs(...args: unknown[]): unknown;// needs 2 arguments
searchMoreChatMsgs(...args: any[]): unknown;// needs 1 arguments searchMoreChatMsgs(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchChatMsgs(...args: any[]): unknown;// needs 3 arguments cancelSearchChatMsgs(...args: unknown[]): unknown;// needs 3 arguments
searchMsgWithKeywords(...args: any[]): unknown;// needs 2 arguments searchMsgWithKeywords(...args: unknown[]): unknown;// needs 2 arguments
searchMoreMsgWithKeywords(...args: any[]): unknown;// needs 1 arguments searchMoreMsgWithKeywords(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchMsgWithKeywords(...args: any[]): unknown;// needs 3 arguments cancelSearchMsgWithKeywords(...args: unknown[]): unknown;// needs 3 arguments
searchFileWithKeywords(keywords: string[], source: number): Promise<string>;// needs 2 arguments searchFileWithKeywords(keywords: string[], source: number): Promise<string>;// needs 2 arguments
searchMoreFileWithKeywords(...args: any[]): unknown;// needs 1 arguments searchMoreFileWithKeywords(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchFileWithKeywords(...args: any[]): unknown;// needs 3 arguments cancelSearchFileWithKeywords(...args: unknown[]): unknown;// needs 3 arguments
searchAtMeChats(...args: any[]): unknown;// needs 3 arguments searchAtMeChats(...args: unknown[]): unknown;// needs 3 arguments
searchMoreAtMeChats(...args: any[]): unknown;// needs 1 arguments searchMoreAtMeChats(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchAtMeChats(...args: any[]): unknown;// needs 3 arguments cancelSearchAtMeChats(...args: unknown[]): unknown;// needs 3 arguments
searchChatAtMeMsgs(...args: any[]): unknown;// needs 1 arguments searchChatAtMeMsgs(...args: unknown[]): unknown;// needs 1 arguments
searchMoreChatAtMeMsgs(...args: any[]): unknown;// needs 1 arguments searchMoreChatAtMeMsgs(...args: unknown[]): unknown;// needs 1 arguments
cancelSearchChatAtMeMsgs(...args: any[]): unknown;// needs 3 arguments cancelSearchChatAtMeMsgs(...args: unknown[]): unknown;// needs 3 arguments
addSearchHistory(param: { addSearchHistory(param: {
type: number,//4 type: number,//4
@@ -127,10 +127,10 @@ export interface NodeIKernelSearchService {
id?: number id?: number
}>; }>;
removeSearchHistory(...args: any[]): unknown;// needs 1 arguments removeSearchHistory(...args: unknown[]): unknown;// needs 1 arguments
searchCache(...args: any[]): unknown;// needs 3 arguments searchCache(...args: unknown[]): unknown;// needs 3 arguments
clearSearchCache(...args: any[]): unknown;// needs 1 arguments clearSearchCache(...args: unknown[]): unknown;// needs 1 arguments
} }

View File

@@ -3,6 +3,6 @@ export interface NodeIKernelTianShuService {
removeKernelTianShuListener(listenerId:number): void; removeKernelTianShuListener(listenerId:number): void;
reportTianShuNumeralRed(...args: any[]): unknown;// needs 1 arguments reportTianShuNumeralRed(...args: unknown[]): unknown;// needs 1 arguments
} }

View File

@@ -4,11 +4,11 @@ export interface NodeIKernelUnitedConfigService {
removeKernelUnitedConfigListener(listenerId:number): void; removeKernelUnitedConfigListener(listenerId:number): void;
fetchUnitedSwitchConfig(...args: any[]): unknown;// needs 1 arguments fetchUnitedSwitchConfig(...args: unknown[]): unknown;// needs 1 arguments
isUnitedConfigSwitchOn(...args: any[]): unknown;// needs 1 arguments isUnitedConfigSwitchOn(...args: unknown[]): unknown;// needs 1 arguments
registerUnitedConfigPushGroupList(...args: any[]): unknown;// needs 1 arguments registerUnitedConfigPushGroupList(...args: unknown[]): unknown;// needs 1 arguments
fetchUnitedCommendConfig(ids: `${string}`[]): void fetchUnitedCommendConfig(ids: `${string}`[]): void

View File

@@ -94,7 +94,7 @@ export interface VideoElement {
thumbHeight?: number; thumbHeight?: number;
busiType?: 0; // busiType?: 0; //
subBusiType?: 0; // 未知 subBusiType?: 0; // 未知
thumbPath?: Map<number, any>; thumbPath?: Map<number, unknown>;
transferStatus?: 0; // 未知 transferStatus?: 0; // 未知
progress?: 0; // 下载进度? progress?: 0; // 下载进度?
invalidState?: 0; // 未知 invalidState?: 0; // 未知

5
src/core/types/file.ts Normal file
View File

@@ -0,0 +1,5 @@
export interface rkeyDataType {
private_rkey: string;
group_rkey: string;
online_rkey: boolean;
};

View File

@@ -33,7 +33,7 @@ export interface GroupDetailInfo {
groupQuestion: string; groupQuestion: string;
certType: number; certType: number;
richFingerMemo: string; richFingerMemo: string;
tagRecord: any[]; tagRecord: unknown[];
shutUpAllTimestamp: number; shutUpAllTimestamp: number;
shutUpMeTimestamp: number; shutUpMeTimestamp: number;
groupTypeFlag: number; groupTypeFlag: number;
@@ -73,7 +73,7 @@ export interface GroupDetailInfo {
cmdUinFlagExt3Grocery: number; cmdUinFlagExt3Grocery: number;
groupCardPrefix: { groupCardPrefix: {
introduction: string; introduction: string;
rptPrefix: any[]; rptPrefix: unknown[];
}; };
groupExt: { groupExt: {
groupInfoExtSeq: number; groupInfoExtSeq: number;
@@ -102,13 +102,13 @@ export interface GroupDetailInfo {
showPlayTogetherSwitch: number; showPlayTogetherSwitch: number;
groupFlagPro1: string; groupFlagPro1: string;
groupBindGuildIds: { groupBindGuildIds: {
guildIds: any[]; guildIds: unknown[];
}; };
viewedMsgDisappearTime: string; viewedMsgDisappearTime: string;
groupExtFlameData: { groupExtFlameData: {
switchState: number; switchState: number;
state: number; state: number;
dayNums: any[]; dayNums: unknown[];
version: number; version: number;
updateTime: string; updateTime: string;
isDisplayDayNum: boolean; isDisplayDayNum: boolean;
@@ -116,7 +116,7 @@ export interface GroupDetailInfo {
groupBindGuildSwitch: number; groupBindGuildSwitch: number;
groupAioBindGuildId: string; groupAioBindGuildId: string;
groupExcludeGuildIds: { groupExcludeGuildIds: {
guildIds: any[]; guildIds: unknown[];
}; };
fullGroupExpansionSwitch: number; fullGroupExpansionSwitch: number;
fullGroupExpansionSeq: string; fullGroupExpansionSeq: string;
@@ -157,10 +157,10 @@ export interface GroupDetailInfo {
headPortraitSeq: number; headPortraitSeq: number;
groupHeadPortrait: { groupHeadPortrait: {
portraitCnt: number; portraitCnt: number;
portraitInfo: any[]; portraitInfo: unknown[];
defaultId: number; defaultId: number;
verifyingPortraitCnt: number; verifyingPortraitCnt: number;
verifyingPortraitInfo: any[]; verifyingPortraitInfo: unknown[];
}; };
cmdUinJoinMsgSeq: number; cmdUinJoinMsgSeq: number;
cmdUinJoinRealMsgSeq: number; cmdUinJoinRealMsgSeq: number;

View File

@@ -77,7 +77,7 @@ interface VideoInfo {
// 扩展在线业务信息 // 扩展在线业务信息
interface ExtOnlineBusinessInfo { interface ExtOnlineBusinessInfo {
buf: string; buf: string;
customStatus: any; customStatus: unknown;
videoBizInfo: VideoBizInfo; videoBizInfo: VideoBizInfo;
videoInfo: VideoInfo; videoInfo: VideoInfo;
} }
@@ -97,7 +97,7 @@ interface UserStatus {
termType: number; termType: number;
netType: number; netType: number;
iconType: number; iconType: number;
customStatus: any; customStatus: unknown;
setTime: string; setTime: string;
specialFlag: number; specialFlag: number;
abiFlag: number; abiFlag: number;
@@ -112,8 +112,8 @@ interface UserStatus {
// 特权图标 // 特权图标
interface PrivilegeIcon { interface PrivilegeIcon {
jumpUrl: string; jumpUrl: string;
openIconList: any[]; openIconList: unknown[];
closeIconList: any[]; closeIconList: unknown[];
} }
// 增值服务信息 // 增值服务信息
@@ -137,7 +137,7 @@ interface VasInfo {
fontEffect: number; fontEffect: number;
newLoverDiamondFlag: number; newLoverDiamondFlag: number;
extendNameplateId: number; extendNameplateId: number;
diyNameplateIDs: any[]; diyNameplateIDs: unknown[];
vipStartFlag: number; vipStartFlag: number;
vipDataFlag: number; vipDataFlag: number;
gameNameplateId: string; gameNameplateId: string;
@@ -183,7 +183,7 @@ interface CommonExt {
address: string; address: string;
regTime: number; regTime: number;
interest: string; interest: string;
labels: any[]; labels: string[];
qqLevel: QQLevel; qqLevel: QQLevel;
} }
@@ -214,8 +214,8 @@ export interface SimpleInfo {
status: UserStatus | null; status: UserStatus | null;
vasInfo: VasInfo | null; vasInfo: VasInfo | null;
relationFlags: RelationFlags | null; relationFlags: RelationFlags | null;
otherFlags: any; otherFlags: unknown;
intimate: any; intimate: unknown;
} }
// 好友类型 // 好友类型
@@ -229,7 +229,7 @@ export interface SelfStatusInfo {
termType: number; termType: number;
netType: number; netType: number;
iconType: number; iconType: number;
customStatus: any; customStatus: unknown;
setTime: string; setTime: string;
} }
@@ -248,7 +248,7 @@ export interface ModifyProfileParams {
longNick: string; longNick: string;
sex: NTSex; sex: NTSex;
birthday: { birthday_year: string, birthday_month: string, birthday_day: string }; birthday: { birthday_year: string, birthday_month: string, birthday_day: string };
location: any; location: unknown;
} }
// 好友资料点赞请求 // 好友资料点赞请求

View File

@@ -46,7 +46,7 @@ export interface WebApiGroupMemberRet {
em: string; em: string;
cache: number; cache: number;
adm_num: number; adm_num: number;
levelname: any; levelname: string;
mems: WebApiGroupMember[]; mems: WebApiGroupMember[];
count: number; count: number;
svr_time: number; svr_time: number;
@@ -99,7 +99,7 @@ export interface WebApiGroupNoticeRet {
sta: number, sta: number,
gln: number gln: number
tst: number, tst: number,
ui: any ui: unknown
server_time: number server_time: number
svrt: number svrt: number
ad: number ad: number
@@ -115,7 +115,7 @@ export interface GroupEssenceMsg {
add_digest_uin: string; add_digest_uin: string;
add_digest_nick: string; add_digest_nick: string;
add_digest_time: number; add_digest_time: number;
msg_content: any[]; msg_content: unknown[];
can_be_removed: true; can_be_removed: true;
} }

View File

@@ -71,7 +71,7 @@ export interface NodeQQNTWrapperUtil {
getPinyin(arg0: string, arg1: boolean): unknown; getPinyin(arg0: string, arg1: boolean): unknown;
matchInPinyin(arg0: any[], arg1: string): unknown; //参数特复杂 arg0是个复杂数据类型 matchInPinyin(arg0: unknown[], arg1: string): unknown; //参数特复杂 arg0是个复杂数据类型
makeDirByPath(arg0: string): unknown; makeDirByPath(arg0: string): unknown;
@@ -91,7 +91,7 @@ export interface NodeQQNTWrapperUtil {
resetUserDataSavePathToDocument(): unknown; resetUserDataSavePathToDocument(): unknown;
getSoBuildInfo(): any; //例如 0[0]_d491dc01e0a_0 getSoBuildInfo(): unknown; //例如 0[0]_d491dc01e0a_0
registerCountInstruments(arg0: string, arg1: string[], arg2: number, arg3: number): unknown; registerCountInstruments(arg0: string, arg1: string[], arg2: number, arg3: number): unknown;
@@ -123,9 +123,9 @@ export interface NodeQQNTWrapperUtil {
checkNewUserDataSaveDirAvailable(arg0: string): unknown; checkNewUserDataSaveDirAvailable(arg0: string): unknown;
copyUserData(arg0: string, arg1: string): Promise<any>; copyUserData(arg0: string, arg1: string): Promise<unknown>;
setUserDataSaveDirectory(arg0: string): Promise<any>; setUserDataSaveDirectory(arg0: string): Promise<unknown>;
hasOtherRunningQQProcess(): boolean; hasOtherRunningQQProcess(): boolean;

View File

@@ -2,7 +2,7 @@
const { ipcMain, BrowserWindow } = require('electron'); const { ipcMain, BrowserWindow } = require('electron');
const napcat = require('./napcat.cjs'); const napcat = require('./napcat.cjs');
const { shell } = require('electron'); const { shell } = require('electron');
ipcMain.handle('napcat_get_webui', async (event, arg) => { ipcMain.handle('napcat_get_webui', async () => {
return napcat.NCgetWebUiUrl(); return napcat.NCgetWebUiUrl();
}); });
ipcMain.on('open_external_url', (event, url) => { ipcMain.on('open_external_url', (event, url) => {

View File

@@ -28,7 +28,7 @@ export async function NCoreInitFramework(
console.log('[NapCat] [Error] Unhandled Exception:', err.message); console.log('[NapCat] [Error] Unhandled Exception:', err.message);
}); });
process.on('unhandledRejection', (reason, promise) => { process.on('unhandledRejection', (reason) => {
console.log('[NapCat] [Error] unhandledRejection:', reason); console.log('[NapCat] [Error] unhandledRejection:', reason);
}); });

View File

@@ -5,7 +5,7 @@ import { NapCatOneBot11Adapter, OB11Return } from '@/onebot';
import { NetworkAdapterConfig } from '../config/config'; import { NetworkAdapterConfig } from '../config/config';
export class OB11Response { export class OB11Response {
private static createResponse<T>(data: T, status: string, retcode: number, message: string = '', echo: any = null): OB11Return<T> { private static createResponse<T>(data: T, status: string, retcode: number, message: string = '', echo: unknown = null): OB11Return<T> {
return { return {
status, status,
retcode, retcode,
@@ -20,11 +20,11 @@ export class OB11Response {
return this.createResponse(data, status, retcode, message); return this.createResponse(data, status, retcode, message);
} }
static ok<T>(data: T, echo: any = null): OB11Return<T> { static ok<T>(data: T, echo: unknown = null): OB11Return<T> {
return this.createResponse(data, 'ok', 0, '', echo); return this.createResponse(data, 'ok', 0, '', echo);
} }
static error(err: string, retcode: number, echo: any = null): OB11Return<null> { static error(err: string, retcode: number, echo: unknown = null): OB11Return<null> {
return this.createResponse(null, 'failed', retcode, err, echo); return this.createResponse(null, 'failed', retcode, err, echo);
} }
} }
@@ -32,8 +32,8 @@ export class OB11Response {
export abstract class OneBotAction<PayloadType, ReturnDataType> { export abstract class OneBotAction<PayloadType, ReturnDataType> {
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown; actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
core: NapCatCore; core: NapCatCore;
private validate: ValidateFunction<any> | undefined = undefined; private validate?: ValidateFunction<unknown> = undefined;
payloadSchema: any = undefined; payloadSchema?: unknown = undefined;
obContext: NapCatOneBot11Adapter; obContext: NapCatOneBot11Adapter;
constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) { constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
@@ -64,13 +64,13 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
try { try {
const resData = await this._handle(payload, adaptername, config); const resData = await this._handle(payload, adaptername, config);
return OB11Response.ok(resData); return OB11Response.ok(resData);
} catch (e: any) { } catch (e: unknown) {
this.core.context.logger.logError('发生错误', e); this.core.context.logger.logError('发生错误', e);
return OB11Response.error((e as Error).message.toString() || e?.stack?.toString() || '未知错误,可能操作超时', 200); return OB11Response.error((e as Error).message.toString() || (e as Error)?.stack?.toString() || '未知错误,可能操作超时', 200);
} }
} }
public async websocketHandle(payload: PayloadType, echo: any, adaptername: string, config: NetworkAdapterConfig): Promise<OB11Return<ReturnDataType | null>> { public async websocketHandle(payload: PayloadType, echo: unknown, adaptername: string, config: NetworkAdapterConfig): Promise<OB11Return<ReturnDataType | null>> {
const result = await this.check(payload); const result = await this.check(payload);
if (!result.valid) { if (!result.valid) {
return OB11Response.error(result.message, 1400, echo); return OB11Response.error(result.message, 1400, echo);
@@ -78,9 +78,9 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
try { try {
const resData = await this._handle(payload, adaptername, config); const resData = await this._handle(payload, adaptername, config);
return OB11Response.ok(resData, echo); return OB11Response.ok(resData, echo);
} catch (e: any) { } catch (e: unknown) {
this.core.context.logger.logError('发生错误', e); this.core.context.logger.logError('发生错误', e);
return OB11Response.error((e as Error).message.toString() || e.stack?.toString(), 1200, echo); return OB11Response.error(((e as Error).message.toString() || (e as Error).stack?.toString()) ?? 'Error', 1200, echo);
} }
} }

View File

@@ -9,9 +9,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class CreateCollection extends OneBotAction<Payload, any> { export class CreateCollection extends OneBotAction<Payload, unknown> {
actionName = ActionName.CreateCollection; override actionName = ActionName.CreateCollection;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return await this.core.apis.CollectionApi.createCollection( return await this.core.apis.CollectionApi.createCollection(

View File

@@ -9,8 +9,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class FetchCustomFace extends OneBotAction<Payload, string[]> { export class FetchCustomFace extends OneBotAction<Payload, string[]> {
actionName = ActionName.FetchCustomFace; override actionName = ActionName.FetchCustomFace;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count); const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count);

View File

@@ -2,6 +2,7 @@ import { Type, Static } from '@sinclair/typebox';
import { OneBotAction } from '@/onebot/action/OneBotAction'; import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { MessageUnique } from '@/common/message-unique'; import { MessageUnique } from '@/common/message-unique';
import { type NTQQMsgApi } from '@/core/apis';
const SchemaData = Type.Object({ const SchemaData = Type.Object({
message_id: Type.Union([Type.Number(), Type.String()]), message_id: Type.Union([Type.Number(), Type.String()]),
@@ -12,14 +13,15 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class FetchEmojiLike extends OneBotAction<Payload, any> { export class FetchEmojiLike extends OneBotAction<Payload, Awaited<ReturnType<NTQQMsgApi['getMsgEmojiLikesList']>>> {
actionName = ActionName.FetchEmojiLike; override actionName = ActionName.FetchEmojiLike;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id); const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
if (!msgIdPeer) throw new Error('消息不存在'); if (!msgIdPeer) throw new Error('消息不存在');
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0]; const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0];
if (!msg) throw new Error('消息不存在');
return await this.core.apis.MsgApi.getMsgEmojiLikesList( return await this.core.apis.MsgApi.getMsgEmojiLikesList(
msgIdPeer.Peer, msg.msgSeq, payload.emojiId.toString(), payload.emojiType.toString(), +payload.count msgIdPeer.Peer, msg.msgSeq, payload.emojiId.toString(), payload.emojiType.toString(), +payload.count
); );

View File

@@ -20,8 +20,8 @@ interface GetAiCharactersResponse {
} }
export class GetAiCharacters extends GetPacketStatusDepends<Payload, GetAiCharactersResponse[]> { export class GetAiCharacters extends GetPacketStatusDepends<Payload, GetAiCharactersResponse[]> {
actionName = ActionName.GetAiCharacters; override actionName = ActionName.GetAiCharacters;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const rawList = await this.core.apis.PacketApi.pkt.operation.FetchAiVoiceList(+payload.group_id, +payload.chat_type as AIVoiceChatType); const rawList = await this.core.apis.PacketApi.pkt.operation.FetchAiVoiceList(+payload.group_id, +payload.chat_type as AIVoiceChatType);

View File

@@ -6,7 +6,7 @@ interface GetClientkeyResponse {
} }
export class GetClientkey extends OneBotAction<void, GetClientkeyResponse> { export class GetClientkey extends OneBotAction<void, GetClientkeyResponse> {
actionName = ActionName.GetClientkey; override actionName = ActionName.GetClientkey;
async _handle() { async _handle() {
return { clientkey: (await this.core.apis.UserApi.forceFetchClientKey()).clientKey }; return { clientkey: (await this.core.apis.UserApi.forceFetchClientKey()).clientKey };

View File

@@ -1,3 +1,4 @@
import { type NTQQCollectionApi } from '@/core/apis/collection';
import { OneBotAction } from '@/onebot/action/OneBotAction'; import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { Type, Static } from '@sinclair/typebox'; import { Type, Static } from '@sinclair/typebox';
@@ -9,9 +10,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class GetCollectionList extends OneBotAction<Payload, any> { export class GetCollectionList extends OneBotAction<Payload, Awaited<ReturnType<NTQQCollectionApi['getAllCollection']>>> {
actionName = ActionName.GetCollectionList; override actionName = ActionName.GetCollectionList;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return await this.core.apis.CollectionApi.getAllCollection(+payload.category, +payload.count); return await this.core.apis.CollectionApi.getAllCollection(+payload.category, +payload.count);

View File

@@ -2,10 +2,10 @@ import { OB11Construct } from '@/onebot/helper/data';
import { OneBotAction } from '@/onebot/action/OneBotAction'; import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
export class GetFriendWithCategory extends OneBotAction<void, any> { export class GetFriendWithCategory extends OneBotAction<void, unknown> {
actionName = ActionName.GetFriendsWithCategory; override actionName = ActionName.GetFriendsWithCategory;
async _handle(payload: void) { async _handle() {
return (await this.core.apis.FriendApi.getBuddyV2ExWithCate()).map(category => ({ return (await this.core.apis.FriendApi.getBuddyV2ExWithCate()).map(category => ({
...category, ...category,
buddyList: OB11Construct.friends(category.buddyList), buddyList: OB11Construct.friends(category.buddyList),

View File

@@ -4,9 +4,9 @@ import { ActionName } from '@/onebot/action/router';
import { Notify } from '@/onebot/types'; import { Notify } from '@/onebot/types';
export default class GetGroupAddRequest extends OneBotAction<null, Notify[] | null> { export default class GetGroupAddRequest extends OneBotAction<null, Notify[] | null> {
actionName = ActionName.GetGroupIgnoreAddRequest; override actionName = ActionName.GetGroupIgnoreAddRequest;
async _handle(payload: null): Promise<Notify[] | null> { async _handle(): Promise<Notify[] | null> {
const NTQQUserApi = this.core.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQGroupApi = this.core.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const ignoredNotifies = await NTQQGroupApi.getSingleScreenNotifies(true, 10); const ignoredNotifies = await NTQQGroupApi.getSingleScreenNotifies(true, 10);

View File

@@ -7,9 +7,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class GetGroupInfoEx extends OneBotAction<Payload, any> { export class GetGroupInfoEx extends OneBotAction<Payload, unknown> {
actionName = ActionName.GetGroupInfoEx; override actionName = ActionName.GetGroupInfoEx;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return (await this.core.apis.GroupApi.getGroupExtFE0Info([payload.group_id.toString()])).result.groupExtInfos.get(payload.group_id.toString()); return (await this.core.apis.GroupApi.getGroupExtFE0Info([payload.group_id.toString()])).result.groupExtInfos.get(payload.group_id.toString());

View File

@@ -38,8 +38,8 @@ type Payload = Static<typeof SchemaData>;
export class GetMiniAppArk extends GetPacketStatusDepends<Payload, { export class GetMiniAppArk extends GetPacketStatusDepends<Payload, {
data: MiniAppData | MiniAppRawData data: MiniAppData | MiniAppRawData
}> { }> {
actionName = ActionName.GetMiniAppArk; override actionName = ActionName.GetMiniAppArk;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
let reqParam: MiniAppReqParams; let reqParam: MiniAppReqParams;

View File

@@ -1,3 +1,4 @@
import { NTVoteInfo } from '@/core';
import { OneBotAction } from '@/onebot/action/OneBotAction'; import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { Type, Static } from '@sinclair/typebox'; import { Type, Static } from '@sinclair/typebox';
@@ -10,9 +11,25 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class GetProfileLike extends OneBotAction<Payload, any> { export class GetProfileLike extends OneBotAction<Payload, {
actionName = ActionName.GetProfileLike; uid: string;
payloadSchema = SchemaData; time: string;
favoriteInfo: {
userInfos: Array<NTVoteInfo>;
total_count: number;
last_time: number;
today_count: number;
};
voteInfo: {
total_count: number;
new_count: number;
new_nearby_count: number;
last_visit_time: number;
userInfos: Array<NTVoteInfo>;
};
}> {
override actionName = ActionName.GetProfileLike;
override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const isSelf = this.core.selfInfo.uin === payload.user_id || !payload.user_id; const isSelf = this.core.selfInfo.uin === payload.user_id || !payload.user_id;
const userUid = isSelf || !payload.user_id ? this.core.selfInfo.uid : await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString()); const userUid = isSelf || !payload.user_id ? this.core.selfInfo.uid : await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());

View File

@@ -1,8 +1,8 @@
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus'; import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
export class GetRkey extends GetPacketStatusDepends<void, Array<any>> { export class GetRkey extends GetPacketStatusDepends<void, Array<unknown>> {
actionName = ActionName.GetRkey; override actionName = ActionName.GetRkey;
async _handle() { async _handle() {
return await this.core.apis.PacketApi.pkt.operation.FetchRkey(); return await this.core.apis.PacketApi.pkt.operation.FetchRkey();

View File

@@ -1,8 +1,8 @@
import { OneBotAction } from '@/onebot/action/OneBotAction'; import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
export class GetRobotUinRange extends OneBotAction<void, Array<any>> { export class GetRobotUinRange extends OneBotAction<void, Array<unknown>> {
actionName = ActionName.GetRobotUinRange; override actionName = ActionName.GetRobotUinRange;
async _handle() { async _handle() {
return await this.core.apis.UserApi.getRobotUinRange(); return await this.core.apis.UserApi.getRobotUinRange();

View File

@@ -9,8 +9,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class GetUserStatus extends GetPacketStatusDepends<Payload, { status: number; ext_status: number; } | undefined> { export class GetUserStatus extends GetPacketStatusDepends<Payload, { status: number; ext_status: number; } | undefined> {
actionName = ActionName.GetUserStatus; override actionName = ActionName.GetUserStatus;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return await this.core.apis.PacketApi.pkt.operation.GetStrangerStatus(+payload.user_id); return await this.core.apis.PacketApi.pkt.operation.GetStrangerStatus(+payload.user_id);

View File

@@ -3,6 +3,7 @@ import { ActionName } from '@/onebot/action/router';
import { checkFileExist, uriToLocalFile } from '@/common/file'; import { checkFileExist, uriToLocalFile } from '@/common/file';
import fs from 'fs'; import fs from 'fs';
import { Static, Type } from '@sinclair/typebox'; import { Static, Type } from '@sinclair/typebox';
import { GeneralCallResultStatus } from '@/core';
const SchemaData = Type.Object({ const SchemaData = Type.Object({
image: Type.String(), image: Type.String(),
@@ -10,8 +11,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
class OCRImageBase extends OneBotAction<Payload, any> { class OCRImageBase extends OneBotAction<Payload, GeneralCallResultStatus> {
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image); const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
@@ -35,9 +36,9 @@ class OCRImageBase extends OneBotAction<Payload, any> {
} }
export class OCRImage extends OCRImageBase { export class OCRImage extends OCRImageBase {
actionName = ActionName.OCRImage; override actionName = ActionName.OCRImage;
} }
export class IOCRImage extends OCRImageBase { export class IOCRImage extends OCRImageBase {
actionName = ActionName.IOCRImage; override actionName = ActionName.IOCRImage;
} }

View File

@@ -1,3 +1,4 @@
import { PacketHexStr } from '@/core/packet/transformer/base';
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus'; import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { Static, Type } from '@sinclair/typebox'; import { Static, Type } from '@sinclair/typebox';
@@ -10,12 +11,12 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class SendPacket extends GetPacketStatusDepends<Payload, any> { export class SendPacket extends GetPacketStatusDepends<Payload, string | undefined> {
payloadSchema = SchemaData; override payloadSchema = SchemaData;
actionName = ActionName.SendPacket; override actionName = ActionName.SendPacket;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const rsp = typeof payload.rsp === 'boolean' ? payload.rsp : payload.rsp === 'true'; const rsp = typeof payload.rsp === 'boolean' ? payload.rsp : payload.rsp === 'true';
const data = await this.core.apis.PacketApi.pkt.operation.sendPacket({ cmd: payload.cmd, data: payload.data as any }, rsp); const data = await this.core.apis.PacketApi.pkt.operation.sendPacket({ cmd: payload.cmd, data: payload.data as PacketHexStr }, rsp);
return typeof data === 'object' ? data.toString('hex') : undefined; return typeof data === 'object' ? data.toString('hex') : undefined;
} }
} }

View File

@@ -8,8 +8,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
class SetGroupSignBase extends GetPacketStatusDepends<Payload, any> { class SetGroupSignBase extends GetPacketStatusDepends<Payload, void> {
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return await this.core.apis.PacketApi.pkt.operation.GroupSign(+payload.group_id); return await this.core.apis.PacketApi.pkt.operation.GroupSign(+payload.group_id);
@@ -17,9 +17,9 @@ class SetGroupSignBase extends GetPacketStatusDepends<Payload, any> {
} }
export class SetGroupSign extends SetGroupSignBase { export class SetGroupSign extends SetGroupSignBase {
actionName = ActionName.SetGroupSign; override actionName = ActionName.SetGroupSign;
} }
export class SendGroupSign extends SetGroupSignBase { export class SendGroupSign extends SetGroupSignBase {
actionName = ActionName.SendGroupSign; override actionName = ActionName.SendGroupSign;
} }

View File

@@ -10,9 +10,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class SetInputStatus extends OneBotAction<Payload, any> { export class SetInputStatus extends OneBotAction<Payload, unknown> {
actionName = ActionName.SetInputStatus; override actionName = ActionName.SetInputStatus;
override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString()); const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('uid is empty'); if (!uid) throw new Error('uid is empty');

View File

@@ -8,9 +8,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class SetLongNick extends OneBotAction<Payload, any> { export class SetLongNick extends OneBotAction<Payload, unknown> {
actionName = ActionName.SetLongNick; override actionName = ActionName.SetLongNick;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return await this.core.apis.UserApi.setLongNick(payload.longNick); return await this.core.apis.UserApi.setLongNick(payload.longNick);

View File

@@ -11,8 +11,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class SetOnlineStatus extends OneBotAction<Payload, null> { export class SetOnlineStatus extends OneBotAction<Payload, null> {
actionName = ActionName.SetOnlineStatus; override actionName = ActionName.SetOnlineStatus;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const ret = await this.core.apis.UserApi.setSelfOnlineStatus( const ret = await this.core.apis.UserApi.setSelfOnlineStatus(

View File

@@ -11,8 +11,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export default class SetAvatar extends OneBotAction<Payload, null> { export default class SetAvatar extends OneBotAction<Payload, null> {
actionName = ActionName.SetQQAvatar; override actionName = ActionName.SetQQAvatar;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const { path, success } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file)); const { path, success } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
if (!success) { if (!success) {

View File

@@ -10,9 +10,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class SetSpecialTittle extends GetPacketStatusDepends<Payload, any> { export class SetSpecialTittle extends GetPacketStatusDepends<Payload, void> {
actionName = ActionName.SetSpecialTittle; override actionName = ActionName.SetSpecialTittle;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString()); const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());

View File

@@ -1,3 +1,4 @@
import { GeneralCallResult } from '@/core';
import { OneBotAction } from '@/onebot/action/OneBotAction'; import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { Static, Type } from '@sinclair/typebox'; import { Static, Type } from '@sinclair/typebox';
@@ -10,9 +11,12 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class SharePeer extends OneBotAction<Payload, any> { export class SharePeer extends OneBotAction<Payload, GeneralCallResult & {
actionName = ActionName.SharePeer; arkMsg?: string;
payloadSchema = SchemaData; arkJson?: string;
}> {
override actionName = ActionName.SharePeer;
override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
if (payload.group_id) { if (payload.group_id) {
@@ -20,6 +24,7 @@ export class SharePeer extends OneBotAction<Payload, any> {
} else if (payload.user_id) { } else if (payload.user_id) {
return await this.core.apis.UserApi.getBuddyRecommendContactArkJson(payload.user_id.toString(), payload.phoneNumber); return await this.core.apis.UserApi.getBuddyRecommendContactArkJson(payload.user_id.toString(), payload.phoneNumber);
} }
throw new Error('group_id or user_id is required');
} }
} }
@@ -29,9 +34,9 @@ const SchemaDataGroupEx = Type.Object({
type PayloadGroupEx = Static<typeof SchemaDataGroupEx>; type PayloadGroupEx = Static<typeof SchemaDataGroupEx>;
export class ShareGroupEx extends OneBotAction<PayloadGroupEx, any> { export class ShareGroupEx extends OneBotAction<PayloadGroupEx, string> {
actionName = ActionName.ShareGroupEx; override actionName = ActionName.ShareGroupEx;
payloadSchema = SchemaDataGroupEx; override payloadSchema = SchemaDataGroupEx;
async _handle(payload: PayloadGroupEx) { async _handle(payload: PayloadGroupEx) {
return await this.core.apis.GroupApi.getArkJsonGroupShare(payload.group_id.toString()); return await this.core.apis.GroupApi.getArkJsonGroupShare(payload.group_id.toString());

View File

@@ -8,9 +8,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class TranslateEnWordToZn extends OneBotAction<Payload, Array<any> | null> { export class TranslateEnWordToZn extends OneBotAction<Payload, Array<unknown> | null> {
actionName = ActionName.TranslateEnWordToZn; override actionName = ActionName.TranslateEnWordToZn;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const ret = await this.core.apis.SystemApi.translateEnWordToZn(payload.words); const ret = await this.core.apis.SystemApi.translateEnWordToZn(payload.words);

View File

@@ -22,7 +22,7 @@ const GetFileBase_PayloadSchema = Type.Object({
export type GetFilePayload = Static<typeof GetFileBase_PayloadSchema>; export type GetFilePayload = Static<typeof GetFileBase_PayloadSchema>;
export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> { export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
payloadSchema = GetFileBase_PayloadSchema; override payloadSchema = GetFileBase_PayloadSchema;
async _handle(payload: GetFilePayload): Promise<GetFileResponse> { async _handle(payload: GetFilePayload): Promise<GetFileResponse> {
payload.file ||= payload.file_id || ''; payload.file ||= payload.file_id || '';
@@ -113,5 +113,5 @@ export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
} }
export default class GetFile extends GetFileBase { export default class GetFile extends GetFileBase {
actionName = ActionName.GetFile; override actionName = ActionName.GetFile;
} }

View File

@@ -15,8 +15,8 @@ interface GetGroupFileUrlResponse {
} }
export class GetGroupFileUrl extends GetPacketStatusDepends<Payload, GetGroupFileUrlResponse> { export class GetGroupFileUrl extends GetPacketStatusDepends<Payload, GetGroupFileUrlResponse> {
actionName = ActionName.GOCQHTTP_GetGroupFileUrl; override actionName = ActionName.GOCQHTTP_GetGroupFileUrl;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id); const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);

View File

@@ -3,5 +3,5 @@ import { ActionName } from '@/onebot/action/router';
export default class GetImage extends GetFileBase { export default class GetImage extends GetFileBase {
actionName = ActionName.GetImage; override actionName = ActionName.GetImage;
} }

View File

@@ -4,16 +4,16 @@ import { promises as fs } from 'fs';
import { decode } from 'silk-wasm'; import { decode } from 'silk-wasm';
import { FFmpegService } from '@/common/ffmpeg'; import { FFmpegService } from '@/common/ffmpeg';
const out_format = ['mp3' , 'amr' , 'wma' , 'm4a' , 'spx' , 'ogg' , 'wav' , 'flac']; const out_format = ['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac'];
type Payload = { type Payload = {
out_format : string out_format: string
} & GetFilePayload } & GetFilePayload
export default class GetRecord extends GetFileBase { export default class GetRecord extends GetFileBase {
actionName = ActionName.GetRecord; override actionName = ActionName.GetRecord;
async _handle(payload: Payload): Promise<GetFileResponse> { override async _handle(payload: Payload): Promise<GetFileResponse> {
const res = await super._handle(payload); const res = await super._handle(payload);
if (payload.out_format && typeof payload.out_format === 'string') { if (payload.out_format && typeof payload.out_format === 'string') {
const inputFile = res.file; const inputFile = res.file;
@@ -27,7 +27,7 @@ export default class GetRecord extends GetFileBase {
await fs.access(inputFile); await fs.access(inputFile);
try { try {
await fs.access(outputFile); await fs.access(outputFile);
} catch (error) { } catch {
await this.decodeFile(inputFile, pcmFile); await this.decodeFile(inputFile, pcmFile);
await FFmpegService.convertFile(pcmFile, outputFile, payload.out_format); await FFmpegService.convertFile(pcmFile, outputFile, payload.out_format);
} }

View File

@@ -8,10 +8,13 @@ const SchemaData = Type.Object({
}); });
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
interface ResponseType{
export class CreateGroupFileFolder extends OneBotAction<Payload, any> { result:unknown;
actionName = ActionName.GoCQHTTP_CreateGroupFileFolder; groupItem:unknown;
payloadSchema = SchemaData; }
export class CreateGroupFileFolder extends OneBotAction<Payload, ResponseType> {
override actionName = ActionName.GoCQHTTP_CreateGroupFileFolder;
override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return (await this.core.apis.GroupApi.creatGroupFileFolder(payload.group_id.toString(), payload.folder_name)).resultWithGroupItem; return (await this.core.apis.GroupApi.creatGroupFileFolder(payload.group_id.toString(), payload.folder_name)).resultWithGroupItem;
} }

View File

@@ -3,6 +3,7 @@ import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { FileNapCatOneBotUUID } from '@/common/file-uuid'; import { FileNapCatOneBotUUID } from '@/common/file-uuid';
import { Static, Type } from '@sinclair/typebox'; import { Static, Type } from '@sinclair/typebox';
import { NTQQGroupApi } from '@/core/apis';
const SchemaData = Type.Object({ const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]), group_id: Type.Union([Type.Number(), Type.String()]),
@@ -11,9 +12,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class DeleteGroupFile extends OneBotAction<Payload, any> { export class DeleteGroupFile extends OneBotAction<Payload, Awaited<ReturnType<NTQQGroupApi['delGroupFile']>>> {
actionName = ActionName.GOCQHTTP_DeleteGroupFile; override actionName = ActionName.GOCQHTTP_DeleteGroupFile;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const data = FileNapCatOneBotUUID.decodeModelId(payload.file_id); const data = FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (!data || !data.fileId) throw new Error('Invalid file_id'); if (!data || !data.fileId) throw new Error('Invalid file_id');

View File

@@ -1,6 +1,7 @@
import { ActionName } from '@/onebot/action/router'; import { ActionName } from '@/onebot/action/router';
import { OneBotAction } from '@/onebot/action/OneBotAction'; import { OneBotAction } from '@/onebot/action/OneBotAction';
import { Static, Type } from '@sinclair/typebox'; import { Static, Type } from '@sinclair/typebox';
import { NTQQGroupApi } from '@/core/apis';
const SchemaData = Type.Object({ const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]), group_id: Type.Union([Type.Number(), Type.String()]),
@@ -10,9 +11,9 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class DeleteGroupFileFolder extends OneBotAction<Payload, any> { export class DeleteGroupFileFolder extends OneBotAction<Payload, Awaited<ReturnType<NTQQGroupApi['delGroupFileFolder']>>['groupFileCommonResult']> {
actionName = ActionName.GoCQHTTP_DeleteGroupFileFolder; override actionName = ActionName.GoCQHTTP_DeleteGroupFileFolder;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return (await this.core.apis.GroupApi.delGroupFileFolder( return (await this.core.apis.GroupApi.delGroupFileFolder(
payload.group_id.toString(), payload.folder ?? payload.folder_id ?? '')).groupFileCommonResult; payload.group_id.toString(), payload.folder ?? payload.folder_id ?? '')).groupFileCommonResult;

View File

@@ -20,8 +20,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export default class GoCQHTTPDownloadFile extends OneBotAction<Payload, FileResponse> { export default class GoCQHTTPDownloadFile extends OneBotAction<Payload, FileResponse> {
actionName = ActionName.GoCQHTTP_DownloadFile; override actionName = ActionName.GoCQHTTP_DownloadFile;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<FileResponse> { async _handle(payload: Payload): Promise<FileResponse> {
const isRandomName = !payload.name; const isRandomName = !payload.name;

View File

@@ -11,9 +11,11 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, any> { export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
actionName = ActionName.GoCQHTTP_GetForwardMsg; messages: OB11Message[] | undefined;
payloadSchema = SchemaData; }> {
override actionName = ActionName.GoCQHTTP_GetForwardMsg;
override payloadSchema = SchemaData;
private createTemplateNode(message: OB11Message): OB11MessageNode { private createTemplateNode(message: OB11Message): OB11MessageNode {
return { return {
@@ -49,7 +51,7 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, any> {
return retMsg; return retMsg;
} }
async _handle(payload: Payload): Promise<any> { async _handle(payload: Payload) {
const msgId = payload.message_id || payload.id; const msgId = payload.message_id || payload.id;
if (!msgId) { if (!msgId) {
throw new Error('message_id is required'); throw new Error('message_id is required');
@@ -67,6 +69,9 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, any> {
} }
const singleMsg = data.msgList[0]; const singleMsg = data.msgList[0];
if (!singleMsg) {
throw new Error('找不到相关的聊天记录');
}
const resMsg = (await this.obContext.apis.MsgApi.parseMessageV2(singleMsg))?.arrayMsg;//强制array 以便处理 const resMsg = (await this.obContext.apis.MsgApi.parseMessageV2(singleMsg))?.arrayMsg;//强制array 以便处理
if (!(resMsg?.message?.[0] as OB11MessageForward)?.data?.content) { if (!(resMsg?.message?.[0] as OB11MessageForward)?.data?.content) {
throw new Error('找不到相关的聊天记录'); throw new Error('找不到相关的聊天记录');

View File

@@ -21,10 +21,10 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>; type Payload = Static<typeof SchemaData>;
export default class GetFriendMsgHistory extends OneBotAction<Payload, Response> { export default class GetFriendMsgHistory extends OneBotAction<Payload, Response> {
actionName = ActionName.GetFriendMsgHistory; override actionName = ActionName.GetFriendMsgHistory;
payloadSchema = SchemaData; override payloadSchema = SchemaData;
async _handle(payload: Payload, adapter: string, config: NetworkAdapterConfig): Promise<Response> { async _handle(payload: Payload, _adapter: string, config: NetworkAdapterConfig): Promise<Response> {
//处理参数 //处理参数
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString()); const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());

Some files were not shown because too many files have changed in this diff Show More