chore: fix indentation and semi in files

This commit is contained in:
Wesley F. Young 2024-08-09 10:37:09 +08:00
parent 024faa2561
commit db4c5bc3a3
27 changed files with 1326 additions and 1330 deletions

View File

@ -1,68 +1,64 @@
module.exports = { module.exports = {
'env': { 'env': {
'browser': true, 'browser': true,
'es2021': true, 'es2021': true,
'node': true
},
'ignorePatterns': ['src/core/', 'src/core.lib/','src/proto/'],
'extends': [
'eslint:recommended',
'plugin:@typescript-eslint/recommended'
],
'overrides': [
{
'env': {
'node': true 'node': true
},
'files': [
'.eslintrc.{js,cjs}'
],
'parserOptions': {
'sourceType': 'script'
}
}
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 'latest',
'sourceType': 'module'
},
'plugins': [
'@typescript-eslint',
'import'
],
'settings': {
'import/parsers': {
'@typescript-eslint/parser': ['.ts']
}, },
'import/resolver': { 'ignorePatterns': ['src/core/', 'src/core.lib/','src/proto/'],
'typescript': { 'extends': [
'alwaysTryTypes': true 'eslint:recommended',
} 'plugin:@typescript-eslint/recommended'
],
'overrides': [
{
'env': {
'node': true
},
'files': [
'.eslintrc.{js,cjs}'
],
'parserOptions': {
'sourceType': 'script'
}
}
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 'latest',
'sourceType': 'module'
},
'plugins': [
'@typescript-eslint',
'import'
],
'settings': {
'import/parsers': {
'@typescript-eslint/parser': ['.ts']
},
'import/resolver': {
'typescript': {
'alwaysTryTypes': true
}
}
},
'rules': {
'indent': [
'error',
4
],
'linebreak-style': [
'error',
'unix'
],
'semi': [
'error',
'always'
],
'no-unused-vars': 'off',
'no-async-promise-executor': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-var-requires': 'off',
'object-curly-spacing': ['error', 'always'],
} }
},
'rules': {
'indent': [
'error',
4
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
],
'no-unused-vars': 'off',
'no-async-promise-executor': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-var-requires': 'off',
'object-curly-spacing': ['error', 'always'],
}
}; };

View File

@ -58,21 +58,21 @@ export class NTEventChannel extends EventEmitter {
} }
async createEventWithListener<EventType extends (...args: any) => any, ListenerType extends (...args: any) => any> async createEventWithListener<EventType extends (...args: any) => any, ListenerType extends (...args: any) => any>
( (
eventName: string, eventName: string,
listenerName: string, listenerName: string,
waitTimes = 1, waitTimes = 1,
timeout: number = 3000, timeout: number = 3000,
checker: (...args: Parameters<ListenerType>) => boolean, checker: (...args: Parameters<ListenerType>) => boolean,
...eventArg: Parameters<EventType> ...eventArg: Parameters<EventType>
) { ) {
return new Promise<[EventRet: Awaited<ReturnType<EventType>>, ...Parameters<ListenerType>]>(async (resolve, reject) => { return new Promise<[EventRet: Awaited<ReturnType<EventType>>, ...Parameters<ListenerType>]>(async (resolve, reject) => {
const ListenerNameList = listenerName.split('/'); const ListenerNameList = listenerName.split('/');
const ListenerMainName = ListenerNameList[0]; const ListenerMainName = ListenerNameList[0];
//const ListenerSubName = ListenerNameList[1]; //const ListenerSubName = ListenerNameList[1];
this.getOrInitListener<ListenerType>(ListenerMainName); this.getOrInitListener<ListenerType>(ListenerMainName);
let complete = 0; let complete = 0;
let retData: Parameters<ListenerType> | undefined = undefined; const retData: Parameters<ListenerType> | undefined = undefined;
let retEvent: any = {}; let retEvent: any = {};
const databack = () => { const databack = () => {
if (complete == 0) { if (complete == 0) {
@ -82,7 +82,7 @@ export class NTEventChannel extends EventEmitter {
} }
}; };
const Timeouter = setTimeout(databack, timeout); const Timeouter = setTimeout(databack, timeout);
let callback = (...args: Parameters<ListenerType>) => { const callback = (...args: Parameters<ListenerType>) => {
if (checker(...args)) { if (checker(...args)) {
complete++; complete++;
if (complete >= waitTimes) { if (complete >= waitTimes) {
@ -109,9 +109,9 @@ export class NTEventChannel extends EventEmitter {
//getNodeIKernelGroupListener,GroupService //getNodeIKernelGroupListener,GroupService
//console.log('2', eventName); //console.log('2', eventName);
const services = (this.wrapperSession as unknown as eventType)[serviceName](); const services = (this.wrapperSession as unknown as eventType)[serviceName]();
let event = services[eventName] const event = services[eventName]
//重新绑定this //重新绑定this
.bind(services); .bind(services);
if (event) { if (event) {
return event as T; return event as T;
} }

View File

@ -29,7 +29,7 @@ export class QQBasicInfoWrapper {
? JSON.parse(fs.readFileSync(this.QQVersionConfigPath!).toString()) ? JSON.parse(fs.readFileSync(this.QQVersionConfigPath!).toString())
: getDefaultQQVersionConfigInfo(); : getDefaultQQVersionConfigInfo();
this.QQPackageInfo = JSON.parse(fs.readFileSync(this.QQPackageInfoPath).toString()); this.QQPackageInfo = JSON.parse(fs.readFileSync(this.QQPackageInfoPath).toString());
let { appid: IQQVersionAppid, qua: IQQVersionQua } = this.getAppidV2(); const { appid: IQQVersionAppid, qua: IQQVersionQua } = this.getAppidV2();
this.QQVersionAppid = IQQVersionAppid; this.QQVersionAppid = IQQVersionAppid;
this.QQVersionQua = IQQVersionQua; this.QQVersionQua = IQQVersionQua;
} }
@ -40,13 +40,13 @@ export class QQBasicInfoWrapper {
} }
getFullQQVesion() { getFullQQVesion() {
let version = this.isQuickUpdate ? this.QQVersionConfig?.curVersion : this.QQPackageInfo?.version; const version = this.isQuickUpdate ? this.QQVersionConfig?.curVersion : this.QQPackageInfo?.version;
if(!version) throw new Error("QQ版本获取失败"); if(!version) throw new Error("QQ版本获取失败");
return version; return version;
} }
requireMinNTQQBuild(buildStr: string) { requireMinNTQQBuild(buildStr: string) {
let currentBuild = parseInt(this.getQQBuildStr() || "0"); const currentBuild = parseInt(this.getQQBuildStr() || "0");
if (currentBuild == 0) throw new Error("QQBuildStr获取失败"); if (currentBuild == 0) throw new Error("QQBuildStr获取失败");
return currentBuild >= parseInt(buildStr); return currentBuild >= parseInt(buildStr);
} }
@ -59,7 +59,7 @@ export class QQBasicInfoWrapper {
getAppidV2(): { appid: string; qua: string } { getAppidV2(): { appid: string; qua: string } {
const appidTbale = AppidTable as unknown as QQAppidTableType; const appidTbale = AppidTable as unknown as QQAppidTableType;
try { try {
let fullVersion = this.getFullQQVesion(); const fullVersion = this.getFullQQVesion();
if (!fullVersion) throw new Error("QQ版本获取失败"); if (!fullVersion) throw new Error("QQ版本获取失败");
const data = appidTbale[fullVersion]; const data = appidTbale[fullVersion];
if (data) { if (data) {

View File

@ -10,126 +10,126 @@ export enum LogLevel {
FATAL = 'fatal', FATAL = 'fatal',
} }
function getFormattedTimestamp() { function getFormattedTimestamp() {
const now = new Date(); const now = new Date();
const year = now.getFullYear(); const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0'); const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0'); const day = now.getDate().toString().padStart(2, '0');
const hours = now.getHours().toString().padStart(2, '0'); const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0'); const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0'); const seconds = now.getSeconds().toString().padStart(2, '0');
const milliseconds = now.getMilliseconds().toString().padStart(3, '0'); const milliseconds = now.getMilliseconds().toString().padStart(3, '0');
return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}.${milliseconds}`; return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}.${milliseconds}`;
} }
export class LogWrapper { export class LogWrapper {
fileLogEnabled = true; fileLogEnabled = true;
consoleLogEnabled = true; consoleLogEnabled = true;
logConfig: Configuration; logConfig: Configuration;
loggerConsole: log4js.Logger; loggerConsole: log4js.Logger;
loggerFile: log4js.Logger; loggerFile: log4js.Logger;
loggerDefault: log4js.Logger; loggerDefault: log4js.Logger;
// eslint-disable-next-line no-control-regex // eslint-disable-next-line no-control-regex
colorEscape = /\x1B[@-_][0-?]*[ -/]*[@-~]/g; colorEscape = /\x1B[@-_][0-?]*[ -/]*[@-~]/g;
constructor(logDir: string) { constructor(logDir: string) {
// logDir = path.join(path.resolve(__dirname), 'logs'); // logDir = path.join(path.resolve(__dirname), 'logs');
const filename = `${getFormattedTimestamp()}.log`; const filename = `${getFormattedTimestamp()}.log`;
const logPath = path.join(logDir, filename); const logPath = path.join(logDir, filename);
this.logConfig = { this.logConfig = {
appenders: { appenders: {
FileAppender: { // 输出到文件的appender FileAppender: { // 输出到文件的appender
type: 'file', type: 'file',
filename: logPath, // 指定日志文件的位置和文件名 filename: logPath, // 指定日志文件的位置和文件名
maxLogSize: 10485760, // 日志文件的最大大小单位字节这里设置为10MB maxLogSize: 10485760, // 日志文件的最大大小单位字节这里设置为10MB
layout: { layout: {
type: 'pattern', type: 'pattern',
pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %X{userInfo} | %m' pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %X{userInfo} | %m'
} }
}, },
ConsoleAppender: { // 输出到控制台的appender ConsoleAppender: { // 输出到控制台的appender
type: 'console', type: 'console',
layout: { layout: {
type: 'pattern', type: 'pattern',
pattern: `%d{yyyy-MM-dd hh:mm:ss} [%[%p%]] ${chalk.magenta('%X{userInfo}')} | %m` pattern: `%d{yyyy-MM-dd hh:mm:ss} [%[%p%]] ${chalk.magenta('%X{userInfo}')} | %m`
} }
}
},
categories: {
default: { appenders: ['FileAppender', 'ConsoleAppender'], level: 'debug' }, // 默认情况下同时输出到文件和控制台
file: { appenders: ['FileAppender'], level: 'debug' },
console: { appenders: ['ConsoleAppender'], level: 'debug' }
}
};
log4js.configure(this.logConfig);
this.loggerConsole = log4js.getLogger('console');
this.loggerFile = log4js.getLogger('file');
this.loggerDefault = log4js.getLogger('default');
this.setLogSelfInfo({ nick: '', uin: '', uid: '' });
}
setLogLevel(fileLogLevel: LogLevel, consoleLogLevel: LogLevel) {
this.logConfig.categories.file.level = fileLogLevel;
this.logConfig.categories.console.level = consoleLogLevel;
log4js.configure(this.logConfig);
}
setLogSelfInfo(selfInfo: { nick: string, uin: string, uid: string }) {
const userInfo = `${selfInfo.nick}(${selfInfo.uin})`;
this.loggerConsole.addContext('userInfo', userInfo);
this.loggerFile.addContext('userInfo', userInfo);
this.loggerDefault.addContext('userInfo', userInfo);
}
enableFileLog(enable: boolean) {
this.fileLogEnabled = enable;
}
enableConsoleLog(enable: boolean) {
this.consoleLogEnabled = enable;
}
formatMsg(msg: any[]) {
let logMsg = '';
for (const msgItem of msg) {
if (msgItem instanceof Error) { // 判断是否是错误
logMsg += msgItem.stack + ' ';
continue;
} else if (typeof msgItem === 'object') { // 判断是否是对象
const obj = JSON.parse(JSON.stringify(msgItem, null, 2));
logMsg += JSON.stringify(truncateString(obj)) + ' ';
continue;
}
logMsg += msgItem + ' ';
} }
}, return logMsg;
categories: {
default: { appenders: ['FileAppender', 'ConsoleAppender'], level: 'debug' }, // 默认情况下同时输出到文件和控制台
file: { appenders: ['FileAppender'], level: 'debug' },
console: { appenders: ['ConsoleAppender'], level: 'debug' }
}
};
log4js.configure(this.logConfig);
this.loggerConsole = log4js.getLogger('console');
this.loggerFile = log4js.getLogger('file');
this.loggerDefault = log4js.getLogger('default');
this.setLogSelfInfo({ nick: '', uin: '', uid: '' });
}
setLogLevel(fileLogLevel: LogLevel, consoleLogLevel: LogLevel) {
this.logConfig.categories.file.level = fileLogLevel;
this.logConfig.categories.console.level = consoleLogLevel;
log4js.configure(this.logConfig);
}
setLogSelfInfo(selfInfo: { nick: string, uin: string, uid: string }) {
const userInfo = `${selfInfo.nick}(${selfInfo.uin})`;
this.loggerConsole.addContext('userInfo', userInfo);
this.loggerFile.addContext('userInfo', userInfo);
this.loggerDefault.addContext('userInfo', userInfo);
}
enableFileLog(enable: boolean) {
this.fileLogEnabled = enable;
}
enableConsoleLog(enable: boolean) {
this.consoleLogEnabled = enable;
}
formatMsg(msg: any[]) {
let logMsg = '';
for (const msgItem of msg) {
if (msgItem instanceof Error) { // 判断是否是错误
logMsg += msgItem.stack + ' ';
continue;
} else if (typeof msgItem === 'object') { // 判断是否是对象
const obj = JSON.parse(JSON.stringify(msgItem, null, 2));
logMsg += JSON.stringify(truncateString(obj)) + ' ';
continue;
}
logMsg += msgItem + ' ';
} }
return logMsg;
}
_log(level: LogLevel, ...args: any[]) { _log(level: LogLevel, ...args: any[]) {
if (this.consoleLogEnabled) { if (this.consoleLogEnabled) {
this.loggerConsole[level](this.formatMsg(args)); this.loggerConsole[level](this.formatMsg(args));
}
if (this.fileLogEnabled) {
this.loggerFile[level](this.formatMsg(args).replace(this.colorEscape, ''));
}
} }
if (this.fileLogEnabled) {
this.loggerFile[level](this.formatMsg(args).replace(this.colorEscape, ''));
}
}
log(...args: any[]) { log(...args: any[]) {
// info 等级 // info 等级
this._log(LogLevel.INFO, ...args); this._log(LogLevel.INFO, ...args);
} }
logDebug(...args: any[]) { logDebug(...args: any[]) {
this._log(LogLevel.DEBUG, ...args); this._log(LogLevel.DEBUG, ...args);
} }
logError(...args: any[]) { logError(...args: any[]) {
this._log(LogLevel.ERROR, ...args); this._log(LogLevel.ERROR, ...args);
} }
logWarn(...args: any[]) { logWarn(...args: any[]) {
this._log(LogLevel.WARN, ...args); this._log(LogLevel.WARN, ...args);
} }
logFatal(...args: any[]) { logFatal(...args: any[]) {
this._log(LogLevel.FATAL, ...args); this._log(LogLevel.FATAL, ...args);
} }
} }

View File

@ -17,5 +17,5 @@ export function proxyHandlerOf(logger: LogWrapper) {
} }
export function proxiedListenerOf<T extends object>(listener: T, logger: LogWrapper) { export function proxiedListenerOf<T extends object>(listener: T, logger: LogWrapper) {
return new Proxy<T>(listener, proxyHandlerOf(logger)) return new Proxy<T>(listener, proxyHandlerOf(logger));
} }

View File

@ -2,190 +2,190 @@ import https from 'node:https';
import http from 'node:http'; import http from 'node:http';
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
export class RequestUtil { export class RequestUtil {
// 适用于获取服务器下发cookies时获取仅GET // 适用于获取服务器下发cookies时获取仅GET
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string }> { static async HttpsGetCookies(url: string): Promise<{ [key: string]: string }> {
const client = url.startsWith('https') ? https : http; const client = url.startsWith('https') ? https : http;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const req = client.get(url, (res) => { const req = client.get(url, (res) => {
let cookies: { [key: string]: string } = {}; let cookies: { [key: string]: string } = {};
const handleRedirect = (res: http.IncomingMessage) => { const handleRedirect = (res: http.IncomingMessage) => {
//console.log(res.headers.location); //console.log(res.headers.location);
if (res.statusCode === 301 || res.statusCode === 302) { if (res.statusCode === 301 || res.statusCode === 302) {
if (res.headers.location) { if (res.headers.location) {
const redirectUrl = new URL(res.headers.location, url); const redirectUrl = new URL(res.headers.location, url);
RequestUtil.HttpsGetCookies(redirectUrl.href).then((redirectCookies) => { RequestUtil.HttpsGetCookies(redirectUrl.href).then((redirectCookies) => {
// 合并重定向过程中的cookies // 合并重定向过程中的cookies
cookies = { ...cookies, ...redirectCookies }; cookies = { ...cookies, ...redirectCookies };
resolve(cookies); resolve(cookies);
}).catch((err) => { }).catch((err) => {
reject(err); reject(err);
}); });
} else { } else {
resolve(cookies); resolve(cookies);
} }
} else { } else {
resolve(cookies); resolve(cookies);
} }
}; };
res.on('data', () => { }); // Necessary to consume the stream res.on('data', () => { }); // Necessary to consume the stream
res.on('end', () => { res.on('end', () => {
handleRedirect(res); handleRedirect(res);
});
if (res.headers['set-cookie']) {
//console.log(res.headers['set-cookie']);
res.headers['set-cookie'].forEach((cookie) => {
const parts = cookie.split(';')[0].split('=');
const key = parts[0];
const value = parts[1];
if (key && value && key.length > 0 && value.length > 0) {
cookies[key] = value;
}
});
}
});
req.on('error', (error: any) => {
reject(error);
});
}); });
if (res.headers['set-cookie']) {
//console.log(res.headers['set-cookie']);
res.headers['set-cookie'].forEach((cookie) => {
const parts = cookie.split(';')[0].split('=');
const key = parts[0];
const value = parts[1];
if (key && value && key.length > 0 && value.length > 0) {
cookies[key] = value;
}
});
}
});
req.on('error', (error: any) => {
reject(error);
});
});
}
// 请求和回复都是JSON data传原始内容 自动编码json
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string } = {}, isJsonRet: boolean = true, isArgJson: boolean = true): Promise<T> {
const option = new URL(url);
const protocol = url.startsWith('https://') ? https : http;
const options = {
hostname: option.hostname,
port: option.port,
path: option.href,
method: method,
headers: headers
};
// headers: {
// 'Content-Type': 'application/json',
// 'Content-Length': Buffer.byteLength(postData),
// },
return new Promise((resolve, reject) => {
const req = protocol.request(options, (res: any) => {
let responseBody = '';
res.on('data', (chunk: string | Buffer) => {
responseBody += chunk.toString();
});
res.on('end', () => {
try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
if (isJsonRet) {
const responseJson = JSON.parse(responseBody);
resolve(responseJson as T);
} else {
resolve(responseBody as T);
}
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
}
} catch (parseError) {
reject(parseError);
}
});
});
req.on('error', (error: any) => {
reject(error);
});
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
if (isArgJson) {
req.write(JSON.stringify(data));
} else {
req.write(data);
}
}
req.end();
});
}
// 请求返回都是原始内容
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string } = {}) {
return this.HttpGetJson<string>(url, method, data, headers, false, false);
}
static async createFormData(boundary: string, filePath: string): Promise<Buffer> {
let type = 'image/png';
if (filePath.endsWith('.jpg')) {
type = 'image/jpeg';
} }
const formDataParts = [
`------${boundary}\r\n`,
`Content-Disposition: form-data; name="share_image"; filename="${filePath}"\r\n`,
'Content-Type: ' + type + '\r\n\r\n'
];
const fileContent = readFileSync(filePath);
const footer = `\r\n------${boundary}--`;
return Buffer.concat([
Buffer.from(formDataParts.join(''), 'utf8'),
fileContent,
Buffer.from(footer, 'utf8')
]);
}
static async uploadImageForOpenPlatform(filePath: string,cookies:string): Promise<string> {
return new Promise(async (resolve, reject) => { // 请求和回复都是JSON data传原始内容 自动编码json
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string } = {}, isJsonRet: boolean = true, isArgJson: boolean = true): Promise<T> {
const option = new URL(url);
const protocol = url.startsWith('https://') ? https : http;
const options = {
hostname: option.hostname,
port: option.port,
path: option.href,
method: method,
headers: headers
};
// headers: {
// 'Content-Type': 'application/json',
// 'Content-Length': Buffer.byteLength(postData),
// },
return new Promise((resolve, reject) => {
const req = protocol.request(options, (res: any) => {
let responseBody = '';
res.on('data', (chunk: string | Buffer) => {
responseBody += chunk.toString();
});
res.on('end', () => {
try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
if (isJsonRet) {
const responseJson = JSON.parse(responseBody);
resolve(responseJson as T);
} else {
resolve(responseBody as T);
}
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
}
} catch (parseError) {
reject(parseError);
}
});
});
req.on('error', (error: any) => {
reject(error);
});
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
if (isArgJson) {
req.write(JSON.stringify(data));
} else {
req.write(data);
}
}
req.end();
});
}
// 请求返回都是原始内容
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string } = {}) {
return this.HttpGetJson<string>(url, method, data, headers, false, false);
}
static async createFormData(boundary: string, filePath: string): Promise<Buffer> {
let type = 'image/png';
if (filePath.endsWith('.jpg')) {
type = 'image/jpeg';
}
const formDataParts = [
`------${boundary}\r\n`,
`Content-Disposition: form-data; name="share_image"; filename="${filePath}"\r\n`,
'Content-Type: ' + type + '\r\n\r\n'
];
const fileContent = readFileSync(filePath);
const footer = `\r\n------${boundary}--`;
return Buffer.concat([
Buffer.from(formDataParts.join(''), 'utf8'),
fileContent,
Buffer.from(footer, 'utf8')
]);
}
static async uploadImageForOpenPlatform(filePath: string,cookies:string): Promise<string> {
return new Promise(async (resolve, reject) => {
type retType = { retcode: number, result?: { url: string } }; type retType = { retcode: number, result?: { url: string } };
try { try {
const options = { const options = {
hostname: 'cgi.connect.qq.com', hostname: 'cgi.connect.qq.com',
port: 443, port: 443,
path: '/qqconnectopen/upload_share_image', path: '/qqconnectopen/upload_share_image',
method: 'POST', method: 'POST',
headers: { headers: {
'Referer': 'https://cgi.connect.qq.com', 'Referer': 'https://cgi.connect.qq.com',
'Cookie': cookies, 'Cookie': cookies,
'Accept': '*/*', 'Accept': '*/*',
'Connection': 'keep-alive', 'Connection': 'keep-alive',
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
}
};
const req = https.request(options, async (res) => {
let responseBody = '';
res.on('data', (chunk: string | Buffer) => {
responseBody += chunk.toString();
});
res.on('end', () => {
try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
const responseJson = JSON.parse(responseBody) as retType;
resolve(responseJson.result!.url!);
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
} }
} catch (parseError) { };
reject(parseError); const req = https.request(options, async (res) => {
} let responseBody = '';
res.on('data', (chunk: string | Buffer) => {
responseBody += chunk.toString();
});
res.on('end', () => {
try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
const responseJson = JSON.parse(responseBody) as retType;
resolve(responseJson.result!.url!);
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
}
} catch (parseError) {
reject(parseError);
}
});
}); });
}); req.on('error', (error) => {
reject(error);
console.error('Error during upload:', error);
});
req.on('error', (error) => { const body = await RequestUtil.createFormData('WebKitFormBoundary7MA4YWxkTrZu0gW', filePath);
reject(error); // req.setHeader('Content-Length', Buffer.byteLength(body));
console.error('Error during upload:', error); // console.log(`Prepared data size: ${Buffer.byteLength(body)} bytes`);
}); req.write(body);
req.end();
const body = await RequestUtil.createFormData('WebKitFormBoundary7MA4YWxkTrZu0gW', filePath); return;
// req.setHeader('Content-Length', Buffer.byteLength(body));
// console.log(`Prepared data size: ${Buffer.byteLength(body)} bytes`);
req.write(body);
req.end();
return;
} catch (error) { } catch (error) {
reject(error); reject(error);
} }
return undefined; return undefined;
}); });
} }
} }

View File

@ -9,58 +9,58 @@ let osName: string;
let machineId: Promise<string>; let machineId: Promise<string>;
try { try {
osName = os.hostname(); osName = os.hostname();
} catch (e) { } catch (e) {
osName = 'NapCat'; // + crypto.randomUUID().substring(0, 4); osName = 'NapCat'; // + crypto.randomUUID().substring(0, 4);
} }
const invalidMacAddresses = new Set([ const invalidMacAddresses = new Set([
'00:00:00:00:00:00', '00:00:00:00:00:00',
'ff:ff:ff:ff:ff:ff', 'ff:ff:ff:ff:ff:ff',
'ac:de:48:00:11:22' 'ac:de:48:00:11:22'
]); ]);
function validateMacAddress(candidate: string): boolean { function validateMacAddress(candidate: string): boolean {
// eslint-disable-next-line no-useless-escape // eslint-disable-next-line no-useless-escape
const tempCandidate = candidate.replace(/\-/g, ':').toLowerCase(); const tempCandidate = candidate.replace(/\-/g, ':').toLowerCase();
return !invalidMacAddresses.has(tempCandidate); return !invalidMacAddresses.has(tempCandidate);
} }
export async function getMachineId(): Promise<string> { export async function getMachineId(): Promise<string> {
if (!machineId) { if (!machineId) {
machineId = (async () => { machineId = (async () => {
const id = await getMacMachineId(); const id = await getMacMachineId();
return id || randomUUID(); // fallback, generate a UUID return id || randomUUID(); // fallback, generate a UUID
})(); })();
} }
return machineId; return machineId;
} }
export function getMac(): string { export function getMac(): string {
const ifaces = networkInterfaces(); const ifaces = networkInterfaces();
for (const name in ifaces) { for (const name in ifaces) {
const networkInterface = ifaces[name]; const networkInterface = ifaces[name];
if (networkInterface) { if (networkInterface) {
for (const { mac } of networkInterface) { for (const { mac } of networkInterface) {
if (validateMacAddress(mac)) { if (validateMacAddress(mac)) {
return mac; return mac;
}
}
} }
}
} }
}
throw new Error('Unable to retrieve mac address (unexpected format)'); throw new Error('Unable to retrieve mac address (unexpected format)');
} }
async function getMacMachineId(): Promise<string | undefined> { async function getMacMachineId(): Promise<string | undefined> {
try { try {
const crypto = await import('crypto'); const crypto = await import('crypto');
const macAddress = getMac(); const macAddress = getMac();
return crypto.createHash('sha256').update(macAddress, 'utf8').digest('hex'); return crypto.createHash('sha256').update(macAddress, 'utf8').digest('hex');
} catch (err) { } catch (err) {
return undefined; return undefined;
} }
} }
const homeDir = os.homedir(); const homeDir = os.homedir();

View File

@ -4,7 +4,7 @@ const CurrentPath = path.dirname(__filename);
let Process = require('process'); let Process = require('process');
let os = require('os'); let os = require('os');
Process.dlopenOrig = Process.dlopen Process.dlopenOrig = Process.dlopen;
let proxyHandler = { let proxyHandler = {
get(target, prop, receiver) { get(target, prop, receiver) {
@ -22,22 +22,22 @@ let WrapperNodeApi = undefined;//NativeNpdeApi
let WrapperLoginService = undefined; let WrapperLoginService = undefined;
Process.dlopen = function (module, filename, flags = os.constants.dlopen.RTLD_LAZY) { Process.dlopen = function (module, filename, flags = os.constants.dlopen.RTLD_LAZY) {
let dlopenRet = this.dlopenOrig(module, filename, flags) let dlopenRet = this.dlopenOrig(module, filename, flags);
for (let export_name in module.exports) { for (let export_name in module.exports) {
module.exports[export_name] = new Proxy(module.exports[export_name], { module.exports[export_name] = new Proxy(module.exports[export_name], {
construct: (target, args, _newTarget) => { construct: (target, args, _newTarget) => {
let ret = new target(...args) let ret = new target(...args);
if (export_name === 'NodeIQQNTWrapperSession') WrapperSession = ret if (export_name === 'NodeIQQNTWrapperSession') WrapperSession = ret;
if (export_name === 'NodeIKernelLoginService') WrapperLoginService = ret if (export_name === 'NodeIKernelLoginService') WrapperLoginService = ret;
return ret return ret;
}, },
}) });
} }
if (filename.toLowerCase().indexOf('wrapper.node') != -1) { if (filename.toLowerCase().indexOf('wrapper.node') != -1) {
WrapperNodeApi = module.exports; WrapperNodeApi = module.exports;
} }
return dlopenRet; return dlopenRet;
} };
function getWrapperSession() { function getWrapperSession() {
return WrapperSession; return WrapperSession;
} }

View File

@ -16,13 +16,13 @@ import { sleep } from "@/common/utils/helper";
export async function NCoreInitLiteLoader(session: NodeIQQNTWrapperSession, loginService: NodeIKernelLoginService) { export async function NCoreInitLiteLoader(session: NodeIQQNTWrapperSession, loginService: NodeIKernelLoginService) {
//在进入本层前是否登录未进行判断 //在进入本层前是否登录未进行判断
console.log("NapCat LiteLoader App Loading..."); console.log("NapCat LiteLoader App Loading...");
let pathWrapper = new NapCatPathWrapper(); const pathWrapper = new NapCatPathWrapper();
let logger = new LogWrapper(pathWrapper.logsPath); const logger = new LogWrapper(pathWrapper.logsPath);
let basicInfoWrapper = new QQBasicInfoWrapper({ logger }); const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
let wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVesion()); const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVesion());
//直到登录成功后,执行下一步 //直到登录成功后,执行下一步
let selfInfo = await new Promise<SelfInfo>((resolve) => { const selfInfo = await new Promise<SelfInfo>((resolve) => {
let loginListener = new LoginListener(); const loginListener = new LoginListener();
loginListener.onQRCodeLoginSucceed = async (loginResult) => resolve({ loginListener.onQRCodeLoginSucceed = async (loginResult) => resolve({
uid: loginResult.uid, uid: loginResult.uid,
uin: loginResult.uin, uin: loginResult.uin,
@ -35,7 +35,7 @@ export async function NCoreInitLiteLoader(session: NodeIQQNTWrapperSession, logi
// 过早进入会导致addKernelMsgListener等Listener添加失败 // 过早进入会导致addKernelMsgListener等Listener添加失败
await sleep(2500); await sleep(2500);
// 初始化 NapCatLiteLoader // 初始化 NapCatLiteLoader
let loaderObject = new NapCatLiteLoader(wrapper, session, logger, loginService, selfInfo, basicInfoWrapper); const loaderObject = new NapCatLiteLoader(wrapper, session, logger, loginService, selfInfo, basicInfoWrapper);
//启动WebUi //启动WebUi

View File

@ -20,26 +20,26 @@ const __dirname = dirname(__filename);
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function InitWebUi() { export async function InitWebUi() {
const config = await WebUiConfig.GetWebUIConfig(); const config = await WebUiConfig.GetWebUIConfig();
if (config.port == 0) { if (config.port == 0) {
log('[NapCat] [WebUi] Current WebUi is not run.'); log('[NapCat] [WebUi] Current WebUi is not run.');
return; return;
} }
app.use(express.json()); app.use(express.json());
// 初始服务 // 初始服务
// WebUI只在config.prefix所示路径上提供服务可配合Nginx挂载到子目录中 // WebUI只在config.prefix所示路径上提供服务可配合Nginx挂载到子目录中
app.all(config.prefix + '/', (_req, res) => { app.all(config.prefix + '/', (_req, res) => {
res.json({ res.json({
msg: 'NapCat WebAPI is now running!', msg: 'NapCat WebAPI is now running!',
});
});
// 配置静态文件服务,提供./static目录下的文件服务访问路径为/webui
app.use(config.prefix + '/webui', express.static(resolve(__dirname, './static')));
//挂载API接口
app.use(config.prefix + '/api', ALLRouter);
app.listen(config.port, config.host, async () => {
log(`[NapCat] [WebUi] Current WebUi is running at http://${config.host}:${config.port}${config.prefix}`);
log(`[NapCat] [WebUi] Login URL is http://${config.host}:${config.port}${config.prefix}/webui`);
log(`[NapCat] [WebUi] Login Token is ${config.token}`);
}); });
});
// 配置静态文件服务,提供./static目录下的文件服务访问路径为/webui
app.use(config.prefix + '/webui', express.static(resolve(__dirname, './static')));
//挂载API接口
app.use(config.prefix + '/api', ALLRouter);
app.listen(config.port, config.host, async () => {
log(`[NapCat] [WebUi] Current WebUi is running at http://${config.host}:${config.port}${config.prefix}`);
log(`[NapCat] [WebUi] Login URL is http://${config.host}:${config.port}${config.prefix}/webui`);
log(`[NapCat] [WebUi] Login Token is ${config.token}`);
});
} }

View File

@ -4,65 +4,65 @@ import { WebUiConfig } from '../helper/config';
import { WebUiDataRuntime } from '../helper/Data'; import { WebUiDataRuntime } from '../helper/Data';
const isEmpty = (data: any) => data === undefined || data === null || data === ''; const isEmpty = (data: any) => data === undefined || data === null || data === '';
export const LoginHandler: RequestHandler = async (req, res) => { export const LoginHandler: RequestHandler = async (req, res) => {
const WebUiConfigData = await WebUiConfig.GetWebUIConfig(); const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
const { token } = req.body; const { token } = req.body;
if (isEmpty(token)) { if (isEmpty(token)) {
res.json({ res.json({
code: -1, code: -1,
message: 'token is empty' message: 'token is empty'
}); });
return; return;
} }
if (!await WebUiDataRuntime.checkLoginRate(WebUiConfigData.loginRate)) { if (!await WebUiDataRuntime.checkLoginRate(WebUiConfigData.loginRate)) {
res.json({ res.json({
code: -1, code: -1,
message: 'login rate limit' message: 'login rate limit'
}); });
return; return;
}
//验证config.token是否等于token
if (WebUiConfigData.token !== token) {
res.json({
code: -1,
message: 'token is invalid'
});
return;
}
const signCredential = Buffer.from(JSON.stringify(await AuthHelper.signCredential(WebUiConfigData.token))).toString('base64');
res.json({
code: 0,
message: 'success',
data: {
'Credential': signCredential
} }
}); //验证config.token是否等于token
return; if (WebUiConfigData.token !== token) {
res.json({
code: -1,
message: 'token is invalid'
});
return;
}
const signCredential = Buffer.from(JSON.stringify(await AuthHelper.signCredential(WebUiConfigData.token))).toString('base64');
res.json({
code: 0,
message: 'success',
data: {
'Credential': signCredential
}
});
return;
}; };
export const LogoutHandler: RequestHandler = (req, res) => { export const LogoutHandler: RequestHandler = (req, res) => {
// 这玩意无状态销毁个灯 得想想办法 // 这玩意无状态销毁个灯 得想想办法
res.json({
code: 0,
message: 'success'
});
return;
};
export const checkHandler: RequestHandler = async (req, res) => {
const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
const authorization = req.headers.authorization;
try {
const CredentialBase64:string = authorization?.split(' ')[1] as string;
const Credential = JSON.parse(Buffer.from(CredentialBase64, 'base64').toString());
await AuthHelper.validateCredentialWithinOneHour(WebUiConfigData.token,Credential);
res.json({ res.json({
code: 0, code: 0,
message: 'success' message: 'success'
}); });
return; return;
} catch (e) { };
res.json({ export const checkHandler: RequestHandler = async (req, res) => {
code: -1, const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
message: 'failed' const authorization = req.headers.authorization;
}); try {
} const CredentialBase64:string = authorization?.split(' ')[1] as string;
return; const Credential = JSON.parse(Buffer.from(CredentialBase64, 'base64').toString());
await AuthHelper.validateCredentialWithinOneHour(WebUiConfigData.token,Credential);
res.json({
code: 0,
message: 'success'
});
return;
} catch (e) {
res.json({
code: -1,
message: 'failed'
});
}
return;
}; };

View File

@ -9,44 +9,44 @@ import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename); const __dirname = dirname(__filename);
export const GetLogFileListHandler: RequestHandler = async (req, res) => { export const GetLogFileListHandler: RequestHandler = async (req, res) => {
try { try {
const LogsPath = resolve(__dirname, './logs/'); const LogsPath = resolve(__dirname, './logs/');
const LogFiles = await readdir(LogsPath); const LogFiles = await readdir(LogsPath);
res.json({ res.json({
code: 0, code: 0,
data: LogFiles data: LogFiles
}); });
} catch (error) { } catch (error) {
res.json({ code: -1, msg: 'Failed to retrieve log file list.' }); res.json({ code: -1, msg: 'Failed to retrieve log file list.' });
} }
}; };
export const GetLogFileHandler: RequestHandler = async (req, res) => { export const GetLogFileHandler: RequestHandler = async (req, res) => {
const LogsPath = resolve(__dirname, './logs/'); const LogsPath = resolve(__dirname, './logs/');
const LogFile = req.query.file as string; const LogFile = req.query.file as string;
// if (!isValidFileName(LogFile)) { // if (!isValidFileName(LogFile)) {
// res.json({ code: -1, msg: 'LogFile is not safe' }); // res.json({ code: -1, msg: 'LogFile is not safe' });
// return; // return;
// } // }
const filePath = `${LogsPath}/${LogFile}`; const filePath = `${LogsPath}/${LogFile}`;
if (!existsSync(filePath)) { if (!existsSync(filePath)) {
res.status(404).json({ code: -1, msg: 'LogFile does not exist' }); res.status(404).json({ code: -1, msg: 'LogFile does not exist' });
return; return;
}
try {
const fileStats = await stat(filePath);
if (!fileStats.isFile()) {
res.json({ code: -1, msg: 'LogFile must be a file' });
return;
} }
res.sendFile(filePath); try {
} catch (error) { const fileStats = await stat(filePath);
res.json({ code: -1, msg: 'Failed to send log file.' }); if (!fileStats.isFile()) {
} res.json({ code: -1, msg: 'LogFile must be a file' });
return;
}
res.sendFile(filePath);
} catch (error) {
res.json({ code: -1, msg: 'Failed to send log file.' });
}
}; };
// export function isValidFileName(fileName: string): boolean { // export function isValidFileName(fileName: string): boolean {
// const invalidChars = /[\.\:\*\?\"\<\>\|\/\\]/; // const invalidChars = /[\.\:\*\?\"\<\>\|\/\\]/;

View File

@ -11,87 +11,87 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename); const __dirname = dirname(__filename);
const isEmpty = (data: any) => const isEmpty = (data: any) =>
data === undefined || data === null || data === ''; data === undefined || data === null || data === '';
export const OB11GetConfigHandler: RequestHandler = async (req, res) => { export const OB11GetConfigHandler: RequestHandler = async (req, res) => {
const isLogin = await WebUiDataRuntime.getQQLoginStatus(); const isLogin = await WebUiDataRuntime.getQQLoginStatus();
if (!isLogin) { if (!isLogin) {
res.send({
code: -1,
message: 'Not Login',
});
return;
}
const uin = await WebUiDataRuntime.getQQLoginUin();
const configFilePath = resolve(__dirname, `./config/onebot11_${uin}.json`);
//console.log(configFilePath);
let data: OB11Config;
try {
data = JSON.parse(
existsSync(configFilePath)
? readFileSync(configFilePath).toString()
: readFileSync(resolve(__dirname, './config/onebot11.json')).toString()
);
} catch (e) {
data = {} as OB11Config;
res.send({
code: -1,
message: 'Config Get Error',
});
return;
}
res.send({ res.send({
code: -1, code: 0,
message: 'Not Login', message: 'success',
data: data,
}); });
return; return;
}
const uin = await WebUiDataRuntime.getQQLoginUin();
const configFilePath = resolve(__dirname, `./config/onebot11_${uin}.json`);
//console.log(configFilePath);
let data: OB11Config;
try {
data = JSON.parse(
existsSync(configFilePath)
? readFileSync(configFilePath).toString()
: readFileSync(resolve(__dirname, './config/onebot11.json')).toString()
);
} catch (e) {
data = {} as OB11Config;
res.send({
code: -1,
message: 'Config Get Error',
});
return;
}
res.send({
code: 0,
message: 'success',
data: data,
});
return;
}; };
export const OB11SetConfigHandler: RequestHandler = async (req, res) => { export const OB11SetConfigHandler: RequestHandler = async (req, res) => {
const isLogin = await WebUiDataRuntime.getQQLoginStatus(); const isLogin = await WebUiDataRuntime.getQQLoginStatus();
if (!isLogin) { if (!isLogin) {
res.send({ res.send({
code: -1, code: -1,
message: 'Not Login', message: 'Not Login',
}); });
return; return;
} }
if (isEmpty(req.body.config)) { if (isEmpty(req.body.config)) {
res.send({ res.send({
code: -1, code: -1,
message: 'config is empty', message: 'config is empty',
}); });
return; return;
} }
let SetResult; let SetResult;
try { try {
await WebUiDataRuntime.setOB11Config(JSON.parse(req.body.config)); await WebUiDataRuntime.setOB11Config(JSON.parse(req.body.config));
SetResult = true; SetResult = true;
} catch (e) { } catch (e) {
SetResult = false; SetResult = false;
} }
// let configFilePath = resolve(__dirname, `./config/onebot11_${await WebUiDataRuntime.getQQLoginUin()}.json`); // let configFilePath = resolve(__dirname, `./config/onebot11_${await WebUiDataRuntime.getQQLoginUin()}.json`);
// try { // try {
// JSON.parse(req.body.config) // JSON.parse(req.body.config)
// readFileSync(configFilePath); // readFileSync(configFilePath);
// } // }
// catch (e) { // catch (e) {
// //console.log(e); // //console.log(e);
// configFilePath = resolve(__dirname, `./config/onebot11.json`); // configFilePath = resolve(__dirname, `./config/onebot11.json`);
// } // }
// //console.log(configFilePath,JSON.parse(req.body.config)); // //console.log(configFilePath,JSON.parse(req.body.config));
// writeFileSync(configFilePath, JSON.stringify(JSON.parse(req.body.config), null, 4)); // writeFileSync(configFilePath, JSON.stringify(JSON.parse(req.body.config), null, 4));
if (SetResult) { if (SetResult) {
res.send({ res.send({
code: 0, code: 0,
message: 'success', message: 'success',
}); });
} else { } else {
res.send({ res.send({
code: -1, code: -1,
message: 'Config Set Error', message: 'Config Set Error',
}); });
} }
return; return;
}; };

View File

@ -3,75 +3,75 @@ import { WebUiDataRuntime } from '../helper/Data';
import { sleep } from '@/common/utils/helper'; import { sleep } from '@/common/utils/helper';
const isEmpty = (data: any) => data === undefined || data === null || data === ''; const isEmpty = (data: any) => data === undefined || data === null || data === '';
export const QQGetQRcodeHandler: RequestHandler = async (req, res) => { export const QQGetQRcodeHandler: RequestHandler = async (req, res) => {
if (await WebUiDataRuntime.getQQLoginStatus()) { if (await WebUiDataRuntime.getQQLoginStatus()) {
res.send({ res.send({
code: -1, code: -1,
message: 'QQ Is Logined' message: 'QQ Is Logined'
}); });
return; return;
}
const qrcodeUrl = await WebUiDataRuntime.getQQLoginQrcodeURL();
if (isEmpty(qrcodeUrl)) {
res.send({
code: -1,
message: 'QRCode Get Error'
});
return;
}
res.send({
code: 0,
message: 'success',
data: {
qrcode: qrcodeUrl
} }
}); const qrcodeUrl = await WebUiDataRuntime.getQQLoginQrcodeURL();
return; if (isEmpty(qrcodeUrl)) {
res.send({
code: -1,
message: 'QRCode Get Error'
});
return;
}
res.send({
code: 0,
message: 'success',
data: {
qrcode: qrcodeUrl
}
});
return;
}; };
export const QQCheckLoginStatusHandler: RequestHandler = async (req, res) => { export const QQCheckLoginStatusHandler: RequestHandler = async (req, res) => {
res.send({ res.send({
code: 0, code: 0,
message: 'success', message: 'success',
data: { data: {
isLogin: await WebUiDataRuntime.getQQLoginStatus() isLogin: await WebUiDataRuntime.getQQLoginStatus()
} }
}); });
}; };
export const QQSetQuickLoginHandler: RequestHandler = async (req, res) => { export const QQSetQuickLoginHandler: RequestHandler = async (req, res) => {
const { uin } = req.body; const { uin } = req.body;
const isLogin = await WebUiDataRuntime.getQQLoginStatus(); const isLogin = await WebUiDataRuntime.getQQLoginStatus();
if (isLogin) { if (isLogin) {
res.send({
code: -1,
message: 'QQ Is Logined'
});
return;
}
if (isEmpty(uin)) {
res.send({
code: -1,
message: 'uin is empty'
});
return;
}
const { result, message } = await WebUiDataRuntime.getQQQuickLogin(uin);
if (!result) {
res.send({
code: -1,
message: message
});
return;
}
//本来应该验证 但是http不宜这么搞 建议前端验证
//isLogin = await WebUiDataRuntime.getQQLoginStatus();
res.send({ res.send({
code: -1, code: 0,
message: 'QQ Is Logined' message: 'success'
}); });
return;
}
if (isEmpty(uin)) {
res.send({
code: -1,
message: 'uin is empty'
});
return;
}
const { result, message } = await WebUiDataRuntime.getQQQuickLogin(uin);
if (!result) {
res.send({
code: -1,
message: message
});
return;
}
//本来应该验证 但是http不宜这么搞 建议前端验证
//isLogin = await WebUiDataRuntime.getQQLoginStatus();
res.send({
code: 0,
message: 'success'
});
}; };
export const QQGetQuickLoginListHandler: RequestHandler = async (req, res) => { export const QQGetQuickLoginListHandler: RequestHandler = async (req, res) => {
const quickLoginList = await WebUiDataRuntime.getQQQuickLoginList(); const quickLoginList = await WebUiDataRuntime.getQQQuickLoginList();
res.send({ res.send({
code: 0, code: 0,
data: quickLoginList data: quickLoginList
}); });
}; };

View File

@ -13,71 +13,71 @@ interface LoginRuntimeType {
} }
} }
const LoginRuntime: LoginRuntimeType = { const LoginRuntime: LoginRuntimeType = {
LoginCurrentTime: Date.now(), LoginCurrentTime: Date.now(),
LoginCurrentRate: 0, LoginCurrentRate: 0,
QQLoginStatus: false, //已实现 但太傻了 得去那边注册个回调刷新 QQLoginStatus: false, //已实现 但太傻了 得去那边注册个回调刷新
QQQRCodeURL: '', QQQRCodeURL: '',
QQLoginUin: '', QQLoginUin: '',
NapCatHelper: { NapCatHelper: {
SetOb11ConfigCall: async (ob11: OB11Config) => { return; }, SetOb11ConfigCall: async (ob11: OB11Config) => { return; },
CoreQuickLoginCall: async (uin: string) => { return { result: false, message: '' }; }, CoreQuickLoginCall: async (uin: string) => { return { result: false, message: '' }; },
QQLoginList: [] QQLoginList: []
} }
}; };
export const WebUiDataRuntime = { export const WebUiDataRuntime = {
checkLoginRate: async function (RateLimit: number): Promise<boolean> { checkLoginRate: async function (RateLimit: number): Promise<boolean> {
LoginRuntime.LoginCurrentRate++; LoginRuntime.LoginCurrentRate++;
//console.log(RateLimit, LoginRuntime.LoginCurrentRate, Date.now() - LoginRuntime.LoginCurrentTime); //console.log(RateLimit, LoginRuntime.LoginCurrentRate, Date.now() - LoginRuntime.LoginCurrentTime);
if (Date.now() - LoginRuntime.LoginCurrentTime > 1000 * 60) { if (Date.now() - LoginRuntime.LoginCurrentTime > 1000 * 60) {
LoginRuntime.LoginCurrentRate = 0;//超出时间重置限速 LoginRuntime.LoginCurrentRate = 0;//超出时间重置限速
LoginRuntime.LoginCurrentTime = Date.now(); LoginRuntime.LoginCurrentTime = Date.now();
return true; return true;
}
if (LoginRuntime.LoginCurrentRate <= RateLimit) {
return true;
}
return false;
} }
if (LoginRuntime.LoginCurrentRate <= RateLimit) { ,
return true; getQQLoginStatus: async function (): Promise<boolean> {
return LoginRuntime.QQLoginStatus;
}
,
setQQLoginStatus: async function (status: boolean): Promise<void> {
LoginRuntime.QQLoginStatus = status;
}
,
setQQLoginQrcodeURL: async function (url: string): Promise<void> {
LoginRuntime.QQQRCodeURL = url;
}
,
getQQLoginQrcodeURL: async function (): Promise<string> {
return LoginRuntime.QQQRCodeURL;
}
,
setQQLoginUin: async function (uin: string): Promise<void> {
LoginRuntime.QQLoginUin = uin;
}
,
getQQLoginUin: async function (): Promise<string> {
return LoginRuntime.QQLoginUin;
},
getQQQuickLoginList: async function (): Promise<any[]> {
return LoginRuntime.NapCatHelper.QQLoginList;
},
setQQQuickLoginList: async function (list: string[]): Promise<void> {
LoginRuntime.NapCatHelper.QQLoginList = list;
},
setQQQuickLoginCall(func: (uin: string) => Promise<{ result: boolean, message: string }>): void {
LoginRuntime.NapCatHelper.CoreQuickLoginCall = func;
},
getQQQuickLogin: async function (uin: string): Promise<{ result: boolean, message: string }> {
return await LoginRuntime.NapCatHelper.CoreQuickLoginCall(uin);
},
setOB11ConfigCall: async function (func: (ob11: OB11Config) => Promise<void>): Promise<void> {
LoginRuntime.NapCatHelper.SetOb11ConfigCall = func;
},
setOB11Config: async function (ob11: OB11Config): Promise<void> {
await LoginRuntime.NapCatHelper.SetOb11ConfigCall(ob11);
} }
return false;
}
,
getQQLoginStatus: async function (): Promise<boolean> {
return LoginRuntime.QQLoginStatus;
}
,
setQQLoginStatus: async function (status: boolean): Promise<void> {
LoginRuntime.QQLoginStatus = status;
}
,
setQQLoginQrcodeURL: async function (url: string): Promise<void> {
LoginRuntime.QQQRCodeURL = url;
}
,
getQQLoginQrcodeURL: async function (): Promise<string> {
return LoginRuntime.QQQRCodeURL;
}
,
setQQLoginUin: async function (uin: string): Promise<void> {
LoginRuntime.QQLoginUin = uin;
}
,
getQQLoginUin: async function (): Promise<string> {
return LoginRuntime.QQLoginUin;
},
getQQQuickLoginList: async function (): Promise<any[]> {
return LoginRuntime.NapCatHelper.QQLoginList;
},
setQQQuickLoginList: async function (list: string[]): Promise<void> {
LoginRuntime.NapCatHelper.QQLoginList = list;
},
setQQQuickLoginCall(func: (uin: string) => Promise<{ result: boolean, message: string }>): void {
LoginRuntime.NapCatHelper.CoreQuickLoginCall = func;
},
getQQQuickLogin: async function (uin: string): Promise<{ result: boolean, message: string }> {
return await LoginRuntime.NapCatHelper.CoreQuickLoginCall(uin);
},
setOB11ConfigCall: async function (func: (ob11: OB11Config) => Promise<void>): Promise<void> {
LoginRuntime.NapCatHelper.SetOb11ConfigCall = func;
},
setOB11Config: async function (ob11: OB11Config): Promise<void> {
await LoginRuntime.NapCatHelper.SetOb11ConfigCall(ob11);
}
}; };

View File

@ -11,58 +11,58 @@ interface WebUiCredentialJson {
} }
export class AuthHelper { export class AuthHelper {
private static secretKey = Math.random().toString(36).slice(2); private static secretKey = Math.random().toString(36).slice(2);
/** /**
* *
* @param token * @param token
* @returns * @returns
*/ */
public static async signCredential(token: string): Promise<WebUiCredentialJson> { public static async signCredential(token: string): Promise<WebUiCredentialJson> {
const innerJson: WebUiCredentialInnerJson = { const innerJson: WebUiCredentialInnerJson = {
CreatedTime: Date.now(), CreatedTime: Date.now(),
TokenEncoded: token, TokenEncoded: token,
}; };
const jsonString = JSON.stringify(innerJson); const jsonString = JSON.stringify(innerJson);
const hmac = crypto.createHmac('sha256', AuthHelper.secretKey) const hmac = crypto.createHmac('sha256', AuthHelper.secretKey)
.update(jsonString, 'utf8') .update(jsonString, 'utf8')
.digest('hex'); .digest('hex');
return { Data: innerJson, Hmac: hmac }; return { Data: innerJson, Hmac: hmac };
} }
/** /**
* *
* @param credentialJson JSON对象 * @param credentialJson JSON对象
* @returns * @returns
*/ */
public static async checkCredential(credentialJson: WebUiCredentialJson): Promise<boolean> { public static async checkCredential(credentialJson: WebUiCredentialJson): Promise<boolean> {
try { try {
const jsonString = JSON.stringify(credentialJson.Data); const jsonString = JSON.stringify(credentialJson.Data);
const calculatedHmac = crypto.createHmac('sha256', AuthHelper.secretKey) const calculatedHmac = crypto.createHmac('sha256', AuthHelper.secretKey)
.update(jsonString, 'utf8') .update(jsonString, 'utf8')
.digest('hex'); .digest('hex');
return calculatedHmac === credentialJson.Hmac; return calculatedHmac === credentialJson.Hmac;
} catch (error) { } catch (error) {
return false; return false;
}
} }
}
/** /**
* 1token与原始token相同 * 1token与原始token相同
* @param token token * @param token token
* @param credentialJson JSON对象 * @param credentialJson JSON对象
* @returns token匹配 * @returns token匹配
*/ */
public static async validateCredentialWithinOneHour(token: string, credentialJson: WebUiCredentialJson): Promise<boolean> { public static async validateCredentialWithinOneHour(token: string, credentialJson: WebUiCredentialJson): Promise<boolean> {
const isValid = await AuthHelper.checkCredential(credentialJson); const isValid = await AuthHelper.checkCredential(credentialJson);
if (!isValid) { if (!isValid) {
return false; return false;
}
const currentTime = Date.now() / 1000;
const createdTime = credentialJson.Data.CreatedTime;
const timeDifference = currentTime - createdTime;
return timeDifference <= 3600 && credentialJson.Data.TokenEncoded === token;
} }
const currentTime = Date.now() / 1000;
const createdTime = credentialJson.Data.CreatedTime;
const timeDifference = currentTime - createdTime;
return timeDifference <= 3600 && credentialJson.Data.TokenEncoded === token;
}
} }

View File

@ -13,60 +13,60 @@ const __dirname = dirname(__filename);
const MAX_PORT_TRY = 100; const MAX_PORT_TRY = 100;
async function tryUseHost(host: string): Promise<string> { async function tryUseHost(host: string): Promise<string> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const server = net.createServer(); const server = net.createServer();
server.on('listening', () => { server.on('listening', () => {
server.close(); server.close();
resolve(host); resolve(host);
}); });
server.on('error', (err: any) => { server.on('error', (err: any) => {
if (err.code === 'EADDRNOTAVAIL') { if (err.code === 'EADDRNOTAVAIL') {
reject('主机地址验证失败,可能为非本机地址'); reject('主机地址验证失败,可能为非本机地址');
} else { } else {
reject(`遇到错误: ${err.code}`); reject(`遇到错误: ${err.code}`);
}
});
// 尝试监听 让系统随机分配一个端口
server.listen(0, host);
} catch (error) {
// 这里捕获到的错误应该是启动服务器时的同步错误
reject(`服务器启动时发生错误: ${error}`);
} }
}); });
// 尝试监听 让系统随机分配一个端口
server.listen(0, host);
} catch (error) {
// 这里捕获到的错误应该是启动服务器时的同步错误
reject(`服务器启动时发生错误: ${error}`);
}
});
} }
async function tryUsePort(port: number, host: string, tryCount: number = 0): Promise<number> { async function tryUsePort(port: number, host: string, tryCount: number = 0): Promise<number> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const server = net.createServer(); const server = net.createServer();
server.on('listening', () => { server.on('listening', () => {
server.close(); server.close();
resolve(port); resolve(port);
}); });
server.on('error', (err: any) => { server.on('error', (err: any) => {
if (err.code === 'EADDRINUSE') { if (err.code === 'EADDRINUSE') {
if (tryCount < MAX_PORT_TRY) { if (tryCount < MAX_PORT_TRY) {
// 使用循环代替递归 // 使用循环代替递归
resolve(tryUsePort(port + 1, host, tryCount + 1)); resolve(tryUsePort(port + 1, host, tryCount + 1));
} else { } else {
reject(`端口尝试失败,达到最大尝试次数: ${MAX_PORT_TRY}`); reject(`端口尝试失败,达到最大尝试次数: ${MAX_PORT_TRY}`);
} }
} else { } else {
reject(`遇到错误: ${err.code}`); reject(`遇到错误: ${err.code}`);
}
});
// 尝试监听端口
server.listen(port, host);
} catch (error) {
// 这里捕获到的错误应该是启动服务器时的同步错误
reject(`服务器启动时发生错误: ${error}`);
} }
}); });
// 尝试监听端口
server.listen(port, host);
} catch (error) {
// 这里捕获到的错误应该是启动服务器时的同步错误
reject(`服务器启动时发生错误: ${error}`);
}
});
} }
export interface WebUiConfigType { export interface WebUiConfigType {
@ -78,65 +78,65 @@ export interface WebUiConfigType {
} }
// 读取当前目录下名为 webui.json 的配置文件,如果不存在则创建初始化配置文件 // 读取当前目录下名为 webui.json 的配置文件,如果不存在则创建初始化配置文件
class WebUiConfigWrapper { class WebUiConfigWrapper {
WebUiConfigData: WebUiConfigType | undefined = undefined; WebUiConfigData: WebUiConfigType | undefined = undefined;
private applyDefaults<T>(obj: Partial<T>, defaults: T): T { private applyDefaults<T>(obj: Partial<T>, defaults: T): T {
return { ...defaults, ...obj }; return { ...defaults, ...obj };
}
async GetWebUIConfig(): Promise<WebUiConfigType> {
if (this.WebUiConfigData) {
return this.WebUiConfigData;
} }
const defaultconfig: WebUiConfigType = { async GetWebUIConfig(): Promise<WebUiConfigType> {
host: '0.0.0.0', if (this.WebUiConfigData) {
port: 6099, return this.WebUiConfigData;
prefix: '',
token: '', // 默认先填空,空密码无法登录
loginRate: 3
};
try {
defaultconfig.token = Math.random().toString(36).slice(2); //生成随机密码
} catch (e) {
logError('随机密码生成失败', e);
}
try {
const configPath = resolve(__dirname, './config/webui.json');
if (!existsSync(configPath)) {
writeFileSync(configPath, JSON.stringify(defaultconfig, null, 4));
}
const fileContent = readFileSync(configPath, 'utf-8');
// 更新配置字段后新增字段可能会缺失,同步一下
const parsedConfig = this.applyDefaults(JSON.parse(fileContent) as Partial<WebUiConfigType>, defaultconfig);
if (!parsedConfig.prefix.startsWith('/')) parsedConfig.prefix = '/' + parsedConfig.prefix;
if (parsedConfig.prefix.endsWith('/')) parsedConfig.prefix = parsedConfig.prefix.slice(0, -1);
// 配置已经被操作过了,还是回写一下吧,不然新配置不会出现在配置文件里
writeFileSync(configPath, JSON.stringify(parsedConfig, null, 4));
// 不希望回写的配置放后面
// 查询主机地址是否可用
const [host_err, host] = await tryUseHost(parsedConfig.host).then(data => [null, data as string]).catch(err => [err, null]);
if (host_err) {
logError('host不可用', host_err);
parsedConfig.port = 0; // 设置为0禁用WebUI
} else {
parsedConfig.host = host;
// 修正端口占用情况
const [port_err, port] = await tryUsePort(parsedConfig.port, parsedConfig.host).then(data => [null, data as number]).catch(err => [err, null]);
if (port_err) {
logError('port不可用', port_err);
parsedConfig.port = 0; // 设置为0禁用WebUI
} else {
parsedConfig.port = port;
} }
} const defaultconfig: WebUiConfigType = {
this.WebUiConfigData = parsedConfig; host: '0.0.0.0',
return this.WebUiConfigData; port: 6099,
} catch (e) { prefix: '',
logError('读取配置文件失败', e); token: '', // 默认先填空,空密码无法登录
loginRate: 3
};
try {
defaultconfig.token = Math.random().toString(36).slice(2); //生成随机密码
} catch (e) {
logError('随机密码生成失败', e);
}
try {
const configPath = resolve(__dirname, './config/webui.json');
if (!existsSync(configPath)) {
writeFileSync(configPath, JSON.stringify(defaultconfig, null, 4));
}
const fileContent = readFileSync(configPath, 'utf-8');
// 更新配置字段后新增字段可能会缺失,同步一下
const parsedConfig = this.applyDefaults(JSON.parse(fileContent) as Partial<WebUiConfigType>, defaultconfig);
if (!parsedConfig.prefix.startsWith('/')) parsedConfig.prefix = '/' + parsedConfig.prefix;
if (parsedConfig.prefix.endsWith('/')) parsedConfig.prefix = parsedConfig.prefix.slice(0, -1);
// 配置已经被操作过了,还是回写一下吧,不然新配置不会出现在配置文件里
writeFileSync(configPath, JSON.stringify(parsedConfig, null, 4));
// 不希望回写的配置放后面
// 查询主机地址是否可用
const [host_err, host] = await tryUseHost(parsedConfig.host).then(data => [null, data as string]).catch(err => [err, null]);
if (host_err) {
logError('host不可用', host_err);
parsedConfig.port = 0; // 设置为0禁用WebUI
} else {
parsedConfig.host = host;
// 修正端口占用情况
const [port_err, port] = await tryUsePort(parsedConfig.port, parsedConfig.host).then(data => [null, data as number]).catch(err => [err, null]);
if (port_err) {
logError('port不可用', port_err);
parsedConfig.port = 0; // 设置为0禁用WebUI
} else {
parsedConfig.port = port;
}
}
this.WebUiConfigData = parsedConfig;
return this.WebUiConfigData;
} catch (e) {
logError('读取配置文件失败', e);
}
return defaultconfig; // 理论上这行代码到不了,到了只能返回默认配置了
} }
return defaultconfig; // 理论上这行代码到不了,到了只能返回默认配置了
}
} }
export const WebUiConfig = new WebUiConfigWrapper(); export const WebUiConfig = new WebUiConfigWrapper();

View File

@ -7,57 +7,57 @@ import { OB11ConfigRouter } from './OB11Config';
import { WebUiConfig } from '../helper/config'; import { WebUiConfig } from '../helper/config';
const router = Router(); const router = Router();
export async function AuthApi(req: Request, res: Response, next: NextFunction) { export async function AuthApi(req: Request, res: Response, next: NextFunction) {
//判断当前url是否为/login 如果是跳过鉴权 //判断当前url是否为/login 如果是跳过鉴权
if (req.url == '/auth/login') { if (req.url == '/auth/login') {
next(); next();
return; return;
}
if (req.headers?.authorization) {
const authorization = req.headers.authorization.split(' ');
if (authorization.length < 2) {
res.json({
code: -1,
msg: 'Unauthorized',
});
return;
} }
const token = authorization[1]; if (req.headers?.authorization) {
let Credential: any; const authorization = req.headers.authorization.split(' ');
try { if (authorization.length < 2) {
Credential = JSON.parse(Buffer.from(token, 'base64').toString('utf-8')); res.json({
} catch (e) { code: -1,
res.json({ msg: 'Unauthorized',
code: -1, });
msg: 'Unauthorized', return;
}); }
return; const token = authorization[1];
} let Credential: any;
const config = await WebUiConfig.GetWebUIConfig(); try {
const credentialJson = await AuthHelper.validateCredentialWithinOneHour(config.token, Credential); Credential = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
if (credentialJson) { } catch (e) {
//通过验证 res.json({
next(); code: -1,
return; msg: 'Unauthorized',
});
return;
}
const config = await WebUiConfig.GetWebUIConfig();
const credentialJson = await AuthHelper.validateCredentialWithinOneHour(config.token, Credential);
if (credentialJson) {
//通过验证
next();
return;
}
res.json({
code: -1,
msg: 'Unauthorized',
});
return;
} }
res.json({ res.json({
code: -1, code: -1,
msg: 'Unauthorized', msg: 'Server Error',
}); });
return; return;
}
res.json({
code: -1,
msg: 'Server Error',
});
return;
} }
router.use(AuthApi); router.use(AuthApi);
router.all('/test', (req, res) => { router.all('/test', (req, res) => {
res.json({ res.json({
code: 0, code: 0,
msg: 'ok', msg: 'ok',
}); });
}); });
router.use('/auth', AuthRouter); router.use('/auth', AuthRouter);
router.use('/QQLogin', QQLoginRouter); router.use('/QQLogin', QQLoginRouter);

View File

@ -5,64 +5,64 @@ import { SettingSwitch } from './components/SettingSwitch';
import { SettingSelect } from './components/SettingSelect'; import { SettingSelect } from './components/SettingSelect';
import { OB11Config, OB11ConfigWrapper } from './components/WebUiApiOB11Config'; import { OB11Config, OB11ConfigWrapper } from './components/WebUiApiOB11Config';
async function onSettingWindowCreated(view: Element) { async function onSettingWindowCreated(view: Element) {
const isEmpty = (value: any) => value === undefined || value === undefined || value === ''; const isEmpty = (value: any) => value === undefined || value === undefined || value === '';
await OB11ConfigWrapper.Init(localStorage.getItem('auth') as string); await OB11ConfigWrapper.Init(localStorage.getItem('auth') as string);
const ob11Config: OB11Config = await OB11ConfigWrapper.GetOB11Config(); const ob11Config: OB11Config = await OB11ConfigWrapper.GetOB11Config();
const setOB11Config = (key: string, value: any) => { const setOB11Config = (key: string, value: any) => {
const configKey = key.split('.'); const configKey = key.split('.');
if (configKey.length === 2) { if (configKey.length === 2) {
ob11Config[configKey[1]] = value; ob11Config[configKey[1]] = value;
} else if (configKey.length === 3) { } else if (configKey.length === 3) {
ob11Config[configKey[1]][configKey[2]] = value; ob11Config[configKey[1]][configKey[2]] = value;
} }
// OB11ConfigWrapper.SetOB11Config(ob11Config); // 只有当点保存时才下发配置,而不是在修改值后立即下发 // OB11ConfigWrapper.SetOB11Config(ob11Config); // 只有当点保存时才下发配置,而不是在修改值后立即下发
}; };
const parser = new DOMParser(); const parser = new DOMParser();
const doc = parser.parseFromString( const doc = parser.parseFromString(
[ [
'<div>', '<div>',
`<setting-section id="napcat-error"> `<setting-section id="napcat-error">
<setting-panel><pre><code></code></pre></setting-panel> <setting-panel><pre><code></code></pre></setting-panel>
</setting-section>`, </setting-section>`,
SettingList([ SettingList([
SettingItem( SettingItem(
'<span id="napcat-update-title">Napcat</span>', '<span id="napcat-update-title">Napcat</span>',
undefined, undefined,
SettingButton('V1.8.3', 'napcat-update-button', 'secondary') SettingButton('V1.8.3', 'napcat-update-button', 'secondary')
), ),
]), ]),
SettingList([ SettingList([
SettingItem( SettingItem(
'启用 HTTP 服务', '启用 HTTP 服务',
undefined, undefined,
SettingSwitch('ob11.http.enable', ob11Config.http.enable, { SettingSwitch('ob11.http.enable', ob11Config.http.enable, {
'control-display-id': 'config-ob11-http-port', 'control-display-id': 'config-ob11-http-port',
}) })
), ),
SettingItem( SettingItem(
'HTTP 服务监听端口', 'HTTP 服务监听端口',
undefined, undefined,
`<div class="q-input"><input class="q-input__inner" data-config-key="ob11.http.port" type="number" min="1" max="65534" value="${ob11Config.http.port}" placeholder="${ob11Config.http.port}" /></div>`, `<div class="q-input"><input class="q-input__inner" data-config-key="ob11.http.port" type="number" min="1" max="65534" value="${ob11Config.http.port}" placeholder="${ob11Config.http.port}" /></div>`,
'config-ob11-http-port', 'config-ob11-http-port',
ob11Config.http.enable ob11Config.http.enable
), ),
SettingItem( SettingItem(
'启用 HTTP 心跳', '启用 HTTP 心跳',
undefined, undefined,
SettingSwitch('ob11.http.enableHeart', ob11Config.http.enableHeart, { SettingSwitch('ob11.http.enableHeart', ob11Config.http.enableHeart, {
'control-display-id': 'config-ob11-HTTP.enableHeart', 'control-display-id': 'config-ob11-HTTP.enableHeart',
}) })
), ),
SettingItem( SettingItem(
'启用 HTTP 事件上报', '启用 HTTP 事件上报',
undefined, undefined,
SettingSwitch('ob11.http.enablePost', ob11Config.http.enablePost, { SettingSwitch('ob11.http.enablePost', ob11Config.http.enablePost, {
'control-display-id': 'config-ob11-http-postUrls', 'control-display-id': 'config-ob11-http-postUrls',
}) })
), ),
`<div class="config-host-list" id="config-ob11-http-postUrls" ${ob11Config.http.enablePost ? '' : 'is-hidden' `<div class="config-host-list" id="config-ob11-http-postUrls" ${ob11Config.http.enablePost ? '' : 'is-hidden'
}> }>
<setting-item data-direction="row"> <setting-item data-direction="row">
<div> <div>
<setting-text>HTTP </setting-text> <setting-text>HTTP </setting-text>
@ -80,28 +80,28 @@ async function onSettingWindowCreated(view: Element) {
</setting-item> </setting-item>
<div id="config-ob11-http-postUrls-list"></div> <div id="config-ob11-http-postUrls-list"></div>
</div>`, </div>`,
SettingItem( SettingItem(
'启用正向 WebSocket 服务', '启用正向 WebSocket 服务',
undefined, undefined,
SettingSwitch('ob11.ws.enable', ob11Config.ws.enable, { SettingSwitch('ob11.ws.enable', ob11Config.ws.enable, {
'control-display-id': 'config-ob11-ws-port', 'control-display-id': 'config-ob11-ws-port',
}) })
), ),
SettingItem( SettingItem(
'正向 WebSocket 服务监听端口', '正向 WebSocket 服务监听端口',
undefined, undefined,
`<div class="q-input"><input class="q-input__inner" data-config-key="ob11.ws.port" type="number" min="1" max="65534" value="${ob11Config.ws.port}" placeholder="${ob11Config.ws.port}" /></div>`, `<div class="q-input"><input class="q-input__inner" data-config-key="ob11.ws.port" type="number" min="1" max="65534" value="${ob11Config.ws.port}" placeholder="${ob11Config.ws.port}" /></div>`,
'config-ob11-ws-port', 'config-ob11-ws-port',
ob11Config.ws.enable ob11Config.ws.enable
), ),
SettingItem( SettingItem(
'启用反向 WebSocket 服务', '启用反向 WebSocket 服务',
undefined, undefined,
SettingSwitch('ob11.reverseWs.enable', ob11Config.reverseWs.enable, { SettingSwitch('ob11.reverseWs.enable', ob11Config.reverseWs.enable, {
'control-display-id': 'config-ob11-reverseWs-urls', 'control-display-id': 'config-ob11-reverseWs-urls',
}) })
), ),
`<div class="config-host-list" id="config-ob11-reverseWs-urls" ${ob11Config.reverseWs.enable ? '' : 'is-hidden'}> `<div class="config-host-list" id="config-ob11-reverseWs-urls" ${ob11Config.reverseWs.enable ? '' : 'is-hidden'}>
<setting-item data-direction="row"> <setting-item data-direction="row">
<div> <div>
<setting-text> WebSocket </setting-text> <setting-text> WebSocket </setting-text>
@ -110,42 +110,42 @@ async function onSettingWindowCreated(view: Element) {
</setting-item> </setting-item>
<div id="config-ob11-reverseWs-urls-list"></div> <div id="config-ob11-reverseWs-urls-list"></div>
</div>`, </div>`,
SettingItem( SettingItem(
' WebSocket 服务心跳间隔', ' WebSocket 服务心跳间隔',
'控制每隔多久发送一个心跳包,单位为毫秒', '控制每隔多久发送一个心跳包,单位为毫秒',
`<div class="q-input"><input class="q-input__inner" data-config-key="ob11.heartInterval" type="number" min="1000" value="${ob11Config.heartInterval}" placeholder="${ob11Config.heartInterval}" /></div>` `<div class="q-input"><input class="q-input__inner" data-config-key="ob11.heartInterval" type="number" min="1000" value="${ob11Config.heartInterval}" placeholder="${ob11Config.heartInterval}" /></div>`
), ),
SettingItem( SettingItem(
'Access token', 'Access token',
undefined, undefined,
`<div class="q-input" style="width:210px;"><input class="q-input__inner" data-config-key="ob11.token" type="text" value="${ob11Config.token}" placeholder="未设置" /></div>` `<div class="q-input" style="width:210px;"><input class="q-input__inner" data-config-key="ob11.token" type="text" value="${ob11Config.token}" placeholder="未设置" /></div>`
), ),
SettingItem( SettingItem(
'新消息上报格式', '新消息上报格式',
'如客户端无特殊需求推荐保持默认设置,两者的详细差异可参考 <a href="javascript:LiteLoader.api.openExternal(\'https://github.com/botuniverse/onebot-11/tree/master/message#readme\');">OneBot v11 文档</a>', '如客户端无特殊需求推荐保持默认设置,两者的详细差异可参考 <a href="javascript:LiteLoader.api.openExternal(\'https://github.com/botuniverse/onebot-11/tree/master/message#readme\');">OneBot v11 文档</a>',
SettingSelect( SettingSelect(
[ [
{ text: '消息段', value: 'array' }, { text: '消息段', value: 'array' },
{ text: 'CQ码', value: 'string' }, { text: 'CQ码', value: 'string' },
], ],
'ob11.messagePostFormat', 'ob11.messagePostFormat',
ob11Config.messagePostFormat ob11Config.messagePostFormat
) )
), ),
SettingItem( SettingItem(
'音乐卡片签名地址', '音乐卡片签名地址',
undefined, undefined,
`<div class="q-input" style="width:210px;"><input class="q-input__inner" data-config-key="ob11.musicSignUrl" type="text" value="${ob11Config.musicSignUrl}" placeholder="未设置" /></div>`, `<div class="q-input" style="width:210px;"><input class="q-input__inner" data-config-key="ob11.musicSignUrl" type="text" value="${ob11Config.musicSignUrl}" placeholder="未设置" /></div>`,
'ob11.musicSignUrl' 'ob11.musicSignUrl'
), ),
SettingItem( SettingItem(
'启用本地进群时间与发言时间记录', '启用本地进群时间与发言时间记录',
undefined, undefined,
SettingSwitch('ob11.GroupLocalTime.Record', ob11Config.GroupLocalTime.Record, { SettingSwitch('ob11.GroupLocalTime.Record', ob11Config.GroupLocalTime.Record, {
'control-display-id': 'config-ob11-GroupLocalTime-RecordList', 'control-display-id': 'config-ob11-GroupLocalTime-RecordList',
}) })
), ),
`<div class="config-host-list" id="config-ob11-GroupLocalTime-RecordList" ${ob11Config.GroupLocalTime.Record ? '' : 'is-hidden'}> `<div class="config-host-list" id="config-ob11-GroupLocalTime-RecordList" ${ob11Config.GroupLocalTime.Record ? '' : 'is-hidden'}>
<setting-item data-direction="row"> <setting-item data-direction="row">
<div> <div>
<setting-text></setting-text> <setting-text></setting-text>
@ -154,239 +154,239 @@ async function onSettingWindowCreated(view: Element) {
</setting-item> </setting-item>
<div id="config-ob11-GroupLocalTime-RecordList-list"></div> <div id="config-ob11-GroupLocalTime-RecordList-list"></div>
</div>`, </div>`,
SettingItem( SettingItem(
'', '',
undefined, undefined,
SettingButton('保存', 'config-ob11-save', 'primary') SettingButton('保存', 'config-ob11-save', 'primary')
), ),
]), ]),
SettingList([ SettingList([
SettingItem( SettingItem(
'上报 Bot 自身发送的消息', '上报 Bot 自身发送的消息',
'上报 event 为 message_sent', '上报 event 为 message_sent',
SettingSwitch('ob11.reportSelfMessage', ob11Config.reportSelfMessage) SettingSwitch('ob11.reportSelfMessage', ob11Config.reportSelfMessage)
), ),
]), ]),
SettingList([ SettingList([
SettingItem( SettingItem(
'GitHub 仓库', 'GitHub 仓库',
'https://github.com/NapNeko/NapCatQQ', 'https://github.com/NapNeko/NapCatQQ',
SettingButton('点个星星', 'open-github') SettingButton('点个星星', 'open-github')
), ),
SettingItem('NapCat 文档', '', SettingButton('看看文档', 'open-docs')), SettingItem('NapCat 文档', '', SettingButton('看看文档', 'open-docs')),
SettingItem( SettingItem(
'Telegram 群', 'Telegram 群',
'https://t.me/+nLZEnpne-pQ1OWFl', 'https://t.me/+nLZEnpne-pQ1OWFl',
SettingButton('进去逛逛', 'open-telegram') SettingButton('进去逛逛', 'open-telegram')
), ),
SettingItem( SettingItem(
'QQ 群', 'QQ 群',
'545402644', '545402644',
SettingButton('我要进去', 'open-qq-group') SettingButton('我要进去', 'open-qq-group')
), ),
]), ]),
'</div>', '</div>',
].join(''), ].join(''),
'text/html' 'text/html'
); );
// 外链按钮 // 外链按钮
doc.querySelector('#open-github')?.addEventListener('click', () => { doc.querySelector('#open-github')?.addEventListener('click', () => {
window.open('https://github.com/NapNeko/NapCatQQ', '_blank'); window.open('https://github.com/NapNeko/NapCatQQ', '_blank');
}); });
doc.querySelector('#open-telegram')?.addEventListener('click', () => { doc.querySelector('#open-telegram')?.addEventListener('click', () => {
window.open('https://t.me/+nLZEnpne-pQ1OWFl'); window.open('https://t.me/+nLZEnpne-pQ1OWFl');
}); });
doc.querySelector('#open-qq-group')?.addEventListener('click', () => { doc.querySelector('#open-qq-group')?.addEventListener('click', () => {
window.open('https://qm.qq.com/q/bDnHRG38aI'); window.open('https://qm.qq.com/q/bDnHRG38aI');
}); });
doc.querySelector('#open-docs')?.addEventListener('click', () => { doc.querySelector('#open-docs')?.addEventListener('click', () => {
window.open('https://napneko.github.io/', '_blank'); window.open('https://napneko.github.io/', '_blank');
}); });
// 生成反向地址列表 // 生成反向地址列表
const buildHostListItem = ( const buildHostListItem = (
type: string, type: string,
host: string, host: string,
index: number, index: number,
inputAttrs: any = {} inputAttrs: any = {}
) => { ) => {
const dom = { const dom = {
container: document.createElement('setting-item'), container: document.createElement('setting-item'),
input: document.createElement('input'), input: document.createElement('input'),
inputContainer: document.createElement('div'), inputContainer: document.createElement('div'),
deleteBtn: document.createElement('setting-button'), deleteBtn: document.createElement('setting-button'),
}; };
dom.container.classList.add('setting-host-list-item'); dom.container.classList.add('setting-host-list-item');
dom.container.dataset.direction = 'row'; dom.container.dataset.direction = 'row';
Object.assign(dom.input, inputAttrs); Object.assign(dom.input, inputAttrs);
dom.input.classList.add('q-input__inner'); dom.input.classList.add('q-input__inner');
dom.input.type = 'url'; dom.input.type = 'url';
dom.input.value = host; dom.input.value = host;
dom.input.addEventListener('input', () => { dom.input.addEventListener('input', () => {
ob11Config[type.split('-')[0]][type.split('-')[1]][index] = ob11Config[type.split('-')[0]][type.split('-')[1]][index] =
dom.input.value; dom.input.value;
}); });
dom.inputContainer.classList.add('q-input'); dom.inputContainer.classList.add('q-input');
dom.inputContainer.appendChild(dom.input); dom.inputContainer.appendChild(dom.input);
dom.deleteBtn.innerHTML = '删除'; dom.deleteBtn.innerHTML = '删除';
dom.deleteBtn.dataset.type = 'secondary'; dom.deleteBtn.dataset.type = 'secondary';
dom.deleteBtn.addEventListener('click', () => { dom.deleteBtn.addEventListener('click', () => {
ob11Config[type.split('-')[0]][type.split('-')[1]].splice(index, 1); ob11Config[type.split('-')[0]][type.split('-')[1]].splice(index, 1);
initReverseHost(type); initReverseHost(type);
}); });
dom.container.appendChild(dom.inputContainer); dom.container.appendChild(dom.inputContainer);
dom.container.appendChild(dom.deleteBtn); dom.container.appendChild(dom.deleteBtn);
return dom.container; return dom.container;
}; };
const buildHostList = ( const buildHostList = (
hosts: string[], hosts: string[],
type: string, type: string,
inputAttr: any = {} inputAttr: any = {}
) => { ) => {
const result: HTMLElement[] = []; const result: HTMLElement[] = [];
hosts?.forEach((host, index) => { hosts?.forEach((host, index) => {
result.push(buildHostListItem(type, host, index, inputAttr)); result.push(buildHostListItem(type, host, index, inputAttr));
}); });
return result; return result;
}; };
const addReverseHost = ( const addReverseHost = (
type: string, type: string,
doc: Document = document, doc: Document = document,
inputAttr: any = {} inputAttr: any = {}
) => { ) => {
type = type.replace(/\./g, '-');//替换操作 type = type.replace(/\./g, '-');//替换操作
const hostContainerDom = doc.body.querySelector( const hostContainerDom = doc.body.querySelector(
`#config-ob11-${type}-list` `#config-ob11-${type}-list`
); );
hostContainerDom?.appendChild( hostContainerDom?.appendChild(
buildHostListItem( buildHostListItem(
type, type,
'', '',
ob11Config[type.split('-')[0]][type.split('-')[1]].length, ob11Config[type.split('-')[0]][type.split('-')[1]].length,
inputAttr inputAttr
) )
); );
ob11Config[type.split('-')[0]][type.split('-')[1]].push(''); ob11Config[type.split('-')[0]][type.split('-')[1]].push('');
}; };
const initReverseHost = (type: string, doc: Document = document) => { const initReverseHost = (type: string, doc: Document = document) => {
type = type.replace(/\./g, '-');//替换操作 type = type.replace(/\./g, '-');//替换操作
const hostContainerDom = doc.body?.querySelector( const hostContainerDom = doc.body?.querySelector(
`#config-ob11-${type}-list` `#config-ob11-${type}-list`
); );
if (hostContainerDom) { if (hostContainerDom) {
[...hostContainerDom.childNodes].forEach((dom) => dom.remove()); [...hostContainerDom.childNodes].forEach((dom) => dom.remove());
buildHostList( buildHostList(
ob11Config[type.split('-')[0]][type.split('-')[1]], ob11Config[type.split('-')[0]][type.split('-')[1]],
type type
).forEach((dom) => { ).forEach((dom) => {
hostContainerDom?.appendChild(dom); hostContainerDom?.appendChild(dom);
}); });
}
};
initReverseHost('http.postUrls', doc);
initReverseHost('reverseWs.urls', doc);
initReverseHost('GroupLocalTime.RecordList', doc);
doc
.querySelector('#config-ob11-http-postUrls-add')
?.addEventListener('click', () =>
addReverseHost('http.postUrls', document, {
placeholder: '如http://127.0.0.1:5140/onebot',
})
);
doc
.querySelector('#config-ob11-reverseWs-urls-add')
?.addEventListener('click', () =>
addReverseHost('reverseWs.urls', document, {
placeholder: '如ws://127.0.0.1:5140/onebot',
})
);
doc
.querySelector('#config-ob11-GroupLocalTime-RecordList-add')
?.addEventListener('click', () =>
addReverseHost('GroupLocalTime.RecordList', document, {
placeholder: '此处填写群号 -1为全部',
})
);
doc.querySelector('#config-ffmpeg-select')?.addEventListener('click', () => {
//选择ffmpeg
});
doc.querySelector('#config-open-log-path')?.addEventListener('click', () => {
//打开日志
});
// 开关
doc
.querySelectorAll('setting-switch[data-config-key]')
.forEach((dom: Element) => {
dom.addEventListener('click', () => {
const active = dom.getAttribute('is-active') == undefined;
//@ts-expect-error 等待修复
setOB11Config(dom.dataset.configKey, active);
if (active) dom.setAttribute('is-active', '');
else dom.removeAttribute('is-active');
//@ts-expect-error 等待修复
if (!isEmpty(dom.dataset.controlDisplayId)) {
const displayDom = document.querySelector(
//@ts-expect-error 等待修复
`#${dom.dataset.controlDisplayId}`
);
if (active) displayDom?.removeAttribute('is-hidden');
else displayDom?.setAttribute('is-hidden', '');
} }
}); };
initReverseHost('http.postUrls', doc);
initReverseHost('reverseWs.urls', doc);
initReverseHost('GroupLocalTime.RecordList', doc);
doc
.querySelector('#config-ob11-http-postUrls-add')
?.addEventListener('click', () =>
addReverseHost('http.postUrls', document, {
placeholder: '如http://127.0.0.1:5140/onebot',
})
);
doc
.querySelector('#config-ob11-reverseWs-urls-add')
?.addEventListener('click', () =>
addReverseHost('reverseWs.urls', document, {
placeholder: '如ws://127.0.0.1:5140/onebot',
})
);
doc
.querySelector('#config-ob11-GroupLocalTime-RecordList-add')
?.addEventListener('click', () =>
addReverseHost('GroupLocalTime.RecordList', document, {
placeholder: '此处填写群号 -1为全部',
})
);
doc.querySelector('#config-ffmpeg-select')?.addEventListener('click', () => {
//选择ffmpeg
}); });
// 输入框 doc.querySelector('#config-open-log-path')?.addEventListener('click', () => {
doc //打开日志
.querySelectorAll( });
'setting-item .q-input input.q-input__inner[data-config-key]'
) // 开关
.forEach((dom: Element) => { doc
dom.addEventListener('input', () => { .querySelectorAll('setting-switch[data-config-key]')
const Type = dom.getAttribute('type'); .forEach((dom: Element) => {
//@ts-expect-error等待修复 dom.addEventListener('click', () => {
const configKey = dom.dataset.configKey; const active = dom.getAttribute('is-active') == undefined;
const configValue = //@ts-expect-error 等待修复
setOB11Config(dom.dataset.configKey, active);
if (active) dom.setAttribute('is-active', '');
else dom.removeAttribute('is-active');
//@ts-expect-error 等待修复
if (!isEmpty(dom.dataset.controlDisplayId)) {
const displayDom = document.querySelector(
//@ts-expect-error 等待修复
`#${dom.dataset.controlDisplayId}`
);
if (active) displayDom?.removeAttribute('is-hidden');
else displayDom?.setAttribute('is-hidden', '');
}
});
});
// 输入框
doc
.querySelectorAll(
'setting-item .q-input input.q-input__inner[data-config-key]'
)
.forEach((dom: Element) => {
dom.addEventListener('input', () => {
const Type = dom.getAttribute('type');
//@ts-expect-error等待修复
const configKey = dom.dataset.configKey;
const configValue =
Type === 'number' Type === 'number'
? parseInt((dom as HTMLInputElement).value) >= 1 ? parseInt((dom as HTMLInputElement).value) >= 1
? parseInt((dom as HTMLInputElement).value) ? parseInt((dom as HTMLInputElement).value)
: 1 : 1
: (dom as HTMLInputElement).value; : (dom as HTMLInputElement).value;
setOB11Config(configKey, configValue); setOB11Config(configKey, configValue);
}); });
});
// 下拉框
doc
.querySelectorAll('ob-setting-select[data-config-key]')
.forEach((dom: Element) => {
//@ts-expect-error等待修复
dom?.addEventListener('selected', (e: CustomEvent) => {
//@ts-expect-error等待修复
const configKey = dom.dataset.configKey;
const configValue = e.detail.value;
setOB11Config(configKey, configValue);
});
});
// 保存按钮
doc.querySelector('#config-ob11-save')?.addEventListener('click', () => {
OB11ConfigWrapper.SetOB11Config(ob11Config);
alert('保存成功');
}); });
doc.body.childNodes.forEach((node) => {
// 下拉框 view.appendChild(node);
doc
.querySelectorAll('ob-setting-select[data-config-key]')
.forEach((dom: Element) => {
//@ts-expect-error等待修复
dom?.addEventListener('selected', (e: CustomEvent) => {
//@ts-expect-error等待修复
const configKey = dom.dataset.configKey;
const configValue = e.detail.value;
setOB11Config(configKey, configValue);
});
}); });
// 保存按钮
doc.querySelector('#config-ob11-save')?.addEventListener('click', () => {
OB11ConfigWrapper.SetOB11Config(ob11Config);
alert('保存成功');
});
doc.body.childNodes.forEach((node) => {
view.appendChild(node);
});
} }
export { onSettingWindowCreated }; export { onSettingWindowCreated };

View File

@ -1,3 +1,3 @@
export const SettingButton = (text: string, id?: string, type: string = 'secondary') => { export const SettingButton = (text: string, id?: string, type: string = 'secondary') => {
return `<setting-button ${type ? `data-type="${type}"` : ''} ${id ? `id="${id}"` : ''}>${text}</setting-button>`; return `<setting-button ${type ? `data-type="${type}"` : ''} ${id ? `id="${id}"` : ''}>${text}</setting-button>`;
}; };

View File

@ -1,11 +1,11 @@
export const SettingItem = ( export const SettingItem = (
title: string, title: string,
subtitle?: string, subtitle?: string,
action?: string, action?: string,
id?: string, id?: string,
visible: boolean = true, visible: boolean = true,
) => { ) => {
return `<setting-item ${id ? `id="${id}"` : ''} ${!visible ? 'is-hidden' : ''}> return `<setting-item ${id ? `id="${id}"` : ''} ${!visible ? 'is-hidden' : ''}>
<div> <div>
<setting-text>${title}</setting-text> <setting-text>${title}</setting-text>
${subtitle ? `<setting-text data-type="secondary">${subtitle}</setting-text>` : ''} ${subtitle ? `<setting-text data-type="secondary">${subtitle}</setting-text>` : ''}

View File

@ -1,10 +1,10 @@
export const SettingList = ( export const SettingList = (
items: string[], items: string[],
title?: string, title?: string,
isCollapsible: boolean = false, isCollapsible: boolean = false,
direction: string = 'column', direction: string = 'column',
) => { ) => {
return `<setting-section ${title && !isCollapsible ? `data-title="${title}"` : ''}> return `<setting-section ${title && !isCollapsible ? `data-title="${title}"` : ''}>
<setting-panel> <setting-panel>
<setting-list ${direction ? `data-direction="${direction}"` : ''} ${isCollapsible ? 'is-collapsible' : ''} ${title && isCollapsible ? `data-title="${title}"` : ''}> <setting-list ${direction ? `data-direction="${direction}"` : ''} ${isCollapsible ? 'is-collapsible' : ''} ${title && isCollapsible ? `data-title="${title}"` : ''}>
${items.join('')} ${items.join('')}

View File

@ -1,3 +1,3 @@
export const SettingOption = (text: string, value?: string, isSelected: boolean = false) => { export const SettingOption = (text: string, value?: string, isSelected: boolean = false) => {
return `<setting-option ${value ? `data-value="${value}"` : ''} ${isSelected ? 'is-selected' : ''}>${text}</setting-option>`; return `<setting-option ${value ? `data-value="${value}"` : ''} ${isSelected ? 'is-selected' : ''}>${text}</setting-option>`;
}; };

View File

@ -20,65 +20,65 @@ SelectTemplate.innerHTML = `<style>
</div>`; </div>`;
window.customElements.define( window.customElements.define(
'ob-setting-select', 'ob-setting-select',
class extends HTMLElement { class extends HTMLElement {
readonly _button: HTMLDivElement; readonly _button: HTMLDivElement;
readonly _text: HTMLInputElement; readonly _text: HTMLInputElement;
readonly _context: HTMLUListElement; readonly _context: HTMLUListElement;
constructor() { constructor() {
super(); super();
this.attachShadow({ mode: 'open' }); this.attachShadow({ mode: 'open' });
this.shadowRoot?.append(SelectTemplate.content.cloneNode(true)); this.shadowRoot?.append(SelectTemplate.content.cloneNode(true));
this._button = this.shadowRoot.querySelector('div[part="button"]'); this._button = this.shadowRoot.querySelector('div[part="button"]');
this._text = this.shadowRoot.querySelector('input[part="current-text"]'); this._text = this.shadowRoot.querySelector('input[part="current-text"]');
this._context = this.shadowRoot.querySelector('ul[part="option-list"]'); this._context = this.shadowRoot.querySelector('ul[part="option-list"]');
const buttonClick = () => { const buttonClick = () => {
const isHidden = this._context.classList.toggle('hidden'); const isHidden = this._context.classList.toggle('hidden');
window[`${isHidden ? 'remove' : 'add'}EventListener`]('pointerdown', windowPointerDown); window[`${isHidden ? 'remove' : 'add'}EventListener`]('pointerdown', windowPointerDown);
}; };
const windowPointerDown = ({ target }) => { const windowPointerDown = ({ target }) => {
if (!this.contains(target)) buttonClick(); if (!this.contains(target)) buttonClick();
}; };
this._button.addEventListener('click', buttonClick); this._button.addEventListener('click', buttonClick);
this._context.addEventListener('click', ({ target }: MouseEventExtend) => { this._context.addEventListener('click', ({ target }: MouseEventExtend) => {
if (target.tagName !== 'SETTING-OPTION') return; if (target.tagName !== 'SETTING-OPTION') return;
buttonClick(); buttonClick();
if (target.hasAttribute('is-selected')) return; if (target.hasAttribute('is-selected')) return;
this.querySelectorAll('setting-option[is-selected]').forEach((dom) => dom.toggleAttribute('is-selected')); this.querySelectorAll('setting-option[is-selected]').forEach((dom) => dom.toggleAttribute('is-selected'));
target.toggleAttribute('is-selected'); target.toggleAttribute('is-selected');
this._text.value = target.textContent as string; this._text.value = target.textContent as string;
this.dispatchEvent( this.dispatchEvent(
new CustomEvent('selected', { new CustomEvent('selected', {
bubbles: true, bubbles: true,
composed: true, composed: true,
detail: { detail: {
name: target.textContent, name: target.textContent,
value: target.dataset.value, value: target.dataset.value,
}, },
}), }),
); );
}); });
this._text.value = this.querySelector('setting-option[is-selected]')?.textContent as string; this._text.value = this.querySelector('setting-option[is-selected]')?.textContent as string;
} }
}, },
); );
export const SettingSelect = (items: Array<{ text: string; value: string }>, configKey?: string, configValue?: any) => { export const SettingSelect = (items: Array<{ text: string; value: string }>, configKey?: string, configValue?: any) => {
return `<ob-setting-select ${configKey ? `data-config-key="${configKey}"` : ''}> return `<ob-setting-select ${configKey ? `data-config-key="${configKey}"` : ''}>
${items ${items
.map((e, i) => { .map((e, i) => {
return SettingOption(e.text, e.value, configKey && configValue ? configValue === e.value : i === 0); return SettingOption(e.text, e.value, configKey && configValue ? configValue === e.value : i === 0);
}) })
.join('')} .join('')}
</ob-setting-select>`; </ob-setting-select>`;
}; };

View File

@ -1,5 +1,5 @@
export const SettingSwitch = (configKey?: string, isActive: boolean = false, extraData?: Record<string, string>) => { export const SettingSwitch = (configKey?: string, isActive: boolean = false, extraData?: Record<string, string>) => {
return `<setting-switch return `<setting-switch
${configKey ? `data-config-key="${configKey}"` : ''} ${configKey ? `data-config-key="${configKey}"` : ''}
${isActive ? 'is-active' : ''} ${isActive ? 'is-active' : ''}
${extraData ? Object.keys(extraData).map((key) => `data-${key}="${extraData[key]}"`) : ''} ${extraData ? Object.keys(extraData).map((key) => `data-${key}="${extraData[key]}"`) : ''}

View File

@ -33,42 +33,42 @@ export interface OB11Config {
} }
class WebUiApiOB11ConfigWrapper { class WebUiApiOB11ConfigWrapper {
private retCredential: string = ''; private retCredential: string = '';
async Init(Credential: string) { async Init(Credential: string) {
this.retCredential = Credential; this.retCredential = Credential;
}
async GetOB11Config(): Promise<OB11Config> {
const ConfigResponse = await fetch('../api/OB11Config/GetConfig', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + this.retCredential,
'Content-Type': 'application/json',
},
});
if (ConfigResponse.status == 200) {
const ConfigResponseJson = await ConfigResponse.json();
if (ConfigResponseJson.code == 0) {
return ConfigResponseJson?.data;
}
} }
return {} as OB11Config; async GetOB11Config(): Promise<OB11Config> {
} const ConfigResponse = await fetch('../api/OB11Config/GetConfig', {
async SetOB11Config(config: OB11Config): Promise<boolean> { method: 'POST',
const ConfigResponse = await fetch('../api/OB11Config/SetConfig', { headers: {
method: 'POST', Authorization: 'Bearer ' + this.retCredential,
headers: { 'Content-Type': 'application/json',
Authorization: 'Bearer ' + this.retCredential, },
'Content-Type': 'application/json', });
}, if (ConfigResponse.status == 200) {
body: JSON.stringify({ config: JSON.stringify(config) }), const ConfigResponseJson = await ConfigResponse.json();
}); if (ConfigResponseJson.code == 0) {
if (ConfigResponse.status == 200) { return ConfigResponseJson?.data;
const ConfigResponseJson = await ConfigResponse.json(); }
if (ConfigResponseJson.code == 0) { }
return true; return {} as OB11Config;
} }
async SetOB11Config(config: OB11Config): Promise<boolean> {
const ConfigResponse = await fetch('../api/OB11Config/SetConfig', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + this.retCredential,
'Content-Type': 'application/json',
},
body: JSON.stringify({ config: JSON.stringify(config) }),
});
if (ConfigResponse.status == 200) {
const ConfigResponseJson = await ConfigResponse.json();
if (ConfigResponseJson.code == 0) {
return true;
}
}
return false;
} }
return false;
}
} }
export const OB11ConfigWrapper = new WebUiApiOB11ConfigWrapper(); export const OB11ConfigWrapper = new WebUiApiOB11ConfigWrapper();

View File

@ -1,13 +1,13 @@
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
export default defineConfig({ export default defineConfig({
build:{ build:{
target: 'esnext', target: 'esnext',
minify: false, minify: false,
lib: { lib: {
entry: 'ui/NapCat.ts', entry: 'ui/NapCat.ts',
formats: ['es'], formats: ['es'],
fileName: () => 'renderer.js', fileName: () => 'renderer.js',
}
} }
}
}); });