mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2024-11-21 09:36:35 +00:00
style: lint
This commit is contained in:
parent
b29f533a3b
commit
ac5506a43b
@ -1,9 +1,10 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
'env': {
|
'env': {
|
||||||
|
'browser': true,
|
||||||
'es2021': true,
|
'es2021': true,
|
||||||
'node': true
|
'node': true
|
||||||
},
|
},
|
||||||
'ignorePatterns': ['src/core/', 'src/core.lib/'],
|
'ignorePatterns': ['src/core/', 'src/core.lib/','src/proto/'],
|
||||||
'extends': [
|
'extends': [
|
||||||
'eslint:recommended',
|
'eslint:recommended',
|
||||||
'plugin:@typescript-eslint/recommended'
|
'plugin:@typescript-eslint/recommended'
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import { log, logDebug, logError } from '@/common/utils/log';
|
import { log, logDebug, logError } from '@/common/utils/log';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import * as os from 'os';
|
import * as os from 'os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
@ -19,6 +19,6 @@ export function cpModule(moduleName: string) {
|
|||||||
try {
|
try {
|
||||||
fs.copyFileSync(path.join(currentDir, fileName), path.join(currentDir, `${moduleName}.node`));
|
fs.copyFileSync(path.join(currentDir, fileName), path.join(currentDir, `${moduleName}.node`));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,8 +2,8 @@ import crypto from 'node:crypto';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import fs from 'fs/promises';
|
import fs from 'fs/promises';
|
||||||
import { log, logDebug } from './log';
|
import { log, logDebug } from './log';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
@ -153,12 +153,27 @@ export async function UpdateConfig() {
|
|||||||
const configFiles = await fs.readdir(path.join(__dirname, 'config'));
|
const configFiles = await fs.readdir(path.join(__dirname, 'config'));
|
||||||
for (const file of configFiles) {
|
for (const file of configFiles) {
|
||||||
if (file.match(/^onebot11_\d+.json$/)) {
|
if (file.match(/^onebot11_\d+.json$/)) {
|
||||||
let CurrentConfig = JSON.parse(await fs.readFile(path.join(__dirname, 'config', file), 'utf8'));
|
const CurrentConfig = JSON.parse(await fs.readFile(path.join(__dirname, 'config', file), 'utf8'));
|
||||||
if (isValidOldConfig(CurrentConfig)) {
|
if (isValidOldConfig(CurrentConfig)) {
|
||||||
log("正在迁移旧配置到新配置 File:", file);
|
log('正在迁移旧配置到新配置 File:', file);
|
||||||
let NewConfig = migrateConfig(CurrentConfig);
|
const NewConfig = migrateConfig(CurrentConfig);
|
||||||
await fs.writeFile(path.join(__dirname, 'config', file), JSON.stringify(NewConfig, null, 2));
|
await fs.writeFile(path.join(__dirname, 'config', file), JSON.stringify(NewConfig, null, 2));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export function isEqual(obj1: any, obj2: any) {
|
||||||
|
if (obj1 === obj2) return true;
|
||||||
|
if (obj1 == null || obj2 == null) return false;
|
||||||
|
if (typeof obj1 !== 'object' || typeof obj2 !== 'object') return obj1 === obj2;
|
||||||
|
|
||||||
|
const keys1 = Object.keys(obj1);
|
||||||
|
const keys2 = Object.keys(obj2);
|
||||||
|
|
||||||
|
if (keys1.length !== keys2.length) return false;
|
||||||
|
|
||||||
|
for (const key of keys1) {
|
||||||
|
if (!isEqual(obj1[key], obj2[key])) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
@ -2,8 +2,8 @@ import log4js, { Configuration } from 'log4js';
|
|||||||
import { truncateString } from '@/common/utils/helper';
|
import { truncateString } from '@/common/utils/helper';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { SelfInfo } from '@/core';
|
import { SelfInfo } from '@/core';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
@ -1,17 +1,17 @@
|
|||||||
import { resolve } from "node:path";
|
import { resolve } from 'node:path';
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from 'node:child_process';
|
||||||
import { pid, ppid, exit } from 'node:process';
|
import { pid, ppid, exit } from 'node:process';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
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 async function rebootWithQuickLogin(uin: string) {
|
export async function rebootWithQuickLogin(uin: string) {
|
||||||
let batScript = resolve(__dirname, './napcat.bat');
|
const batScript = resolve(__dirname, './napcat.bat');
|
||||||
let batUtf8Script = resolve(__dirname, './napcat-utf8.bat');
|
const batUtf8Script = resolve(__dirname, './napcat-utf8.bat');
|
||||||
let bashScript = resolve(__dirname, './napcat.sh');
|
const bashScript = resolve(__dirname, './napcat.sh');
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
const subProcess = spawn(`start ${batUtf8Script} -q ${uin}`, { detached: true, windowsHide: false, env: process.env, shell: true, stdio: 'ignore' });
|
const subProcess = spawn(`start ${batUtf8Script} -q ${uin}`, { detached: true, windowsHide: false, env: process.env, shell: true, stdio: 'ignore' });
|
||||||
subProcess.unref();
|
subProcess.unref();
|
||||||
@ -27,9 +27,9 @@ export async function rebootWithQuickLogin(uin: string) {
|
|||||||
//exit(0);
|
//exit(0);
|
||||||
}
|
}
|
||||||
export async function rebootWithNormolLogin() {
|
export async function rebootWithNormolLogin() {
|
||||||
let batScript = resolve(__dirname, './napcat.bat');
|
const batScript = resolve(__dirname, './napcat.bat');
|
||||||
let batUtf8Script = resolve(__dirname, './napcat-utf8.bat');
|
const batUtf8Script = resolve(__dirname, './napcat-utf8.bat');
|
||||||
let bashScript = resolve(__dirname, './napcat.sh');
|
const bashScript = resolve(__dirname, './napcat.sh');
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
const subProcess = spawn(`start ${batUtf8Script} `, { detached: true, windowsHide: false, env: process.env, shell: true, stdio: 'ignore' });
|
const subProcess = spawn(`start ${batUtf8Script} `, { detached: true, windowsHide: false, env: process.env, shell: true, stdio: 'ignore' });
|
||||||
subProcess.unref();
|
subProcess.unref();
|
||||||
|
@ -31,7 +31,7 @@ export class RequestUtil {
|
|||||||
|
|
||||||
// 请求和回复都是JSON data传原始内容 自动编码json
|
// 请求和回复都是JSON data传原始内容 自动编码json
|
||||||
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: Record<string, string> = {}, isJsonRet: boolean = true, isArgJson: boolean = true): Promise<T> {
|
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: Record<string, string> = {}, isJsonRet: boolean = true, isArgJson: boolean = true): Promise<T> {
|
||||||
let option = new URL(url);
|
const option = new URL(url);
|
||||||
const protocol = url.startsWith('https://') ? https : http;
|
const protocol = url.startsWith('https://') ? https : http;
|
||||||
const options = {
|
const options = {
|
||||||
hostname: option.hostname,
|
hostname: option.hostname,
|
||||||
|
@ -1,39 +0,0 @@
|
|||||||
import * as frida from 'frida';
|
|
||||||
import { promises as fs } from 'fs';
|
|
||||||
import path from 'node:path';
|
|
||||||
|
|
||||||
async function loadFridaScript(scriptPath: string): Promise<void> {
|
|
||||||
try {
|
|
||||||
// Attach to the process
|
|
||||||
const currentPid = process.pid;
|
|
||||||
console.log('Attaching to process:', currentPid);
|
|
||||||
const targetProcess = await frida.attach(currentPid);
|
|
||||||
|
|
||||||
// Read the script file
|
|
||||||
const scriptCode = await fs.readFile(scriptPath, { encoding: 'utf8' });
|
|
||||||
|
|
||||||
// Create the script in the target process
|
|
||||||
const script = await targetProcess.createScript(scriptCode);
|
|
||||||
|
|
||||||
// Connect to script messages
|
|
||||||
script.message.connect((message, data) => {
|
|
||||||
if (message.type === 'send') {
|
|
||||||
console.log('[Script]:', message.payload);
|
|
||||||
} else if (message.type === 'error') {
|
|
||||||
console.error('[Script Error]:', message.stack);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Load the script into the target process
|
|
||||||
await script.load();
|
|
||||||
|
|
||||||
console.log('Script loaded successfully and is now running.');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to load script:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function hookInit() {
|
|
||||||
// Assuming the process name and script file path are correct
|
|
||||||
loadFridaScript(path.join(path.resolve(__dirname), 'frida_script.js')).catch(console.error);
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
const moduleName = 'wrapper.node';
|
|
||||||
const offset = 0x18152AFE0; // 静态地址偏移
|
|
||||||
|
|
||||||
// 查找模块基地址
|
|
||||||
const baseAddress = Module.findBaseAddress(moduleName);
|
|
||||||
if (!baseAddress) {
|
|
||||||
throw new Error('Module not found.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 计算绝对地址
|
|
||||||
const absoluteAddress = baseAddress.add(offset);
|
|
||||||
|
|
||||||
// 设置拦截器
|
|
||||||
Interceptor.attach(absoluteAddress, {
|
|
||||||
onEnter: function(args) {
|
|
||||||
console.log(`[+] Function at offset ${offset} in wrapper.node was called`);
|
|
||||||
console.log('Argument 0:', args[0].toInt32());
|
|
||||||
},
|
|
||||||
onLeave: function(retval) {
|
|
||||||
console.log('Return value:', retval.toInt32());
|
|
||||||
// 可以在这里修改返回值
|
|
||||||
retval.replace(42);
|
|
||||||
}
|
|
||||||
});
|
|
@ -1,23 +0,0 @@
|
|||||||
const frida = require('frida');
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
// 获取当前 Node.js 进程的 ID
|
|
||||||
const pid = process.pid;
|
|
||||||
const session = await frida.attach(pid); // 附加到当前进程
|
|
||||||
|
|
||||||
const scriptCode = fs.readFileSync(path.join(path.resolve(__dirname), 'frida_script.js'), 'utf-8');
|
|
||||||
const script = await session.createScript(scriptCode);
|
|
||||||
|
|
||||||
script.message.connect(message => {
|
|
||||||
console.log('Message from Frida:', message);
|
|
||||||
});
|
|
||||||
|
|
||||||
await script.load();
|
|
||||||
console.log('Frida script has been loaded successfully.');
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch(err => {
|
|
||||||
console.error(err);
|
|
||||||
});
|
|
@ -10,8 +10,8 @@ import { NapCatOnebot11 } from '@/onebot11/main';
|
|||||||
import { InitWebUi } from './webui/index';
|
import { InitWebUi } from './webui/index';
|
||||||
import { WebUiDataRuntime } from './webui/src/helper/Data';
|
import { WebUiDataRuntime } from './webui/src/helper/Data';
|
||||||
import { UpdateConfig } from './common/utils/helper';
|
import { UpdateConfig } from './common/utils/helper';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
@ -46,7 +46,7 @@ checkVersion().then(async (remoteVersion: string) => {
|
|||||||
logError('[NapCat] 检测更新失败', e);
|
logError('[NapCat] 检测更新失败', e);
|
||||||
});
|
});
|
||||||
// 不是很好待优化
|
// 不是很好待优化
|
||||||
let NapCat_OneBot11 = new NapCatOnebot11();
|
const NapCat_OneBot11 = new NapCatOnebot11();
|
||||||
|
|
||||||
WebUiDataRuntime.setOB11ConfigCall(NapCat_OneBot11.SetConfig);
|
WebUiDataRuntime.setOB11ConfigCall(NapCat_OneBot11.SetConfig);
|
||||||
|
|
||||||
|
@ -20,11 +20,11 @@ class BaseAction<PayloadType, ReturnDataType> {
|
|||||||
return {
|
return {
|
||||||
valid: false,
|
valid: false,
|
||||||
message: errorMessages.join('\n') as string || '未知错误'
|
message: errorMessages.join('\n') as string || '未知错误'
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
valid: true
|
valid: true
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
|
public async handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
|
||||||
|
@ -5,7 +5,7 @@ import BaseAction from '../BaseAction';
|
|||||||
import { ActionName, BaseCheckResult } from '../types';
|
import { ActionName, BaseCheckResult } from '../types';
|
||||||
import { NTQQUserApi } from '@/core/apis';
|
import { NTQQUserApi } from '@/core/apis';
|
||||||
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
|
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
|
||||||
import Ajv from "ajv"
|
import Ajv from 'ajv';
|
||||||
// 设置在线状态
|
// 设置在线状态
|
||||||
|
|
||||||
const SchemaData = {
|
const SchemaData = {
|
||||||
|
@ -13,7 +13,7 @@ export default class SetAvatar extends BaseAction<Payload, null> {
|
|||||||
actionName = ActionName.SetQQAvatar;
|
actionName = ActionName.SetQQAvatar;
|
||||||
// 用不着复杂检测
|
// 用不着复杂检测
|
||||||
protected async check(payload: Payload): Promise<BaseCheckResult> {
|
protected async check(payload: Payload): Promise<BaseCheckResult> {
|
||||||
if (!payload.file || typeof payload.file != "string") {
|
if (!payload.file || typeof payload.file != 'string') {
|
||||||
return {
|
return {
|
||||||
valid: false,
|
valid: false,
|
||||||
message: 'file字段不能为空或者类型错误',
|
message: 'file字段不能为空或者类型错误',
|
||||||
|
@ -17,9 +17,9 @@ const SchemaData = {
|
|||||||
base64: { type: 'string' },
|
base64: { type: 'string' },
|
||||||
name: { type: 'string' },
|
name: { type: 'string' },
|
||||||
headers: {
|
headers: {
|
||||||
type: ["string", "array"],
|
type: ['string', 'array'],
|
||||||
items: {
|
items: {
|
||||||
type: "string"
|
type: 'string'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { log } from '@/common/utils/log';
|
import { log } from '@/common/utils/log';
|
||||||
import BaseAction from '../BaseAction'
|
import BaseAction from '../BaseAction';
|
||||||
import { ActionName } from '../types'
|
import { ActionName } from '../types';
|
||||||
import { QuickAction, QuickActionEvent, handleQuickOperation } from '@/onebot11/server/postOB11Event';
|
import { QuickAction, QuickActionEvent, handleQuickOperation } from '@/onebot11/server/postOB11Event';
|
||||||
|
|
||||||
interface Payload{
|
interface Payload{
|
||||||
@ -9,9 +9,9 @@ interface Payload{
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class GoCQHTTHandleQuickAction extends BaseAction<Payload, null>{
|
export class GoCQHTTHandleQuickAction extends BaseAction<Payload, null>{
|
||||||
actionName = ActionName.GoCQHTTP_HandleQuickAction
|
actionName = ActionName.GoCQHTTP_HandleQuickAction;
|
||||||
protected async _handle(payload: Payload): Promise<null> {
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
handleQuickOperation(payload.context, payload.operation).then().catch(log);
|
handleQuickOperation(payload.context, payload.operation).then().catch(log);
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -24,24 +24,20 @@ export class SendGroupNotice extends BaseAction<Payload, null> {
|
|||||||
let UploadImage: { id: string, width: number, height: number } | undefined = undefined;
|
let UploadImage: { id: string, width: number, height: number } | undefined = undefined;
|
||||||
if (payload.image) {
|
if (payload.image) {
|
||||||
//公告图逻辑
|
//公告图逻辑
|
||||||
let Image_path, Image_errMsg, Image_IsLocal = false;
|
const { errMsg, path, isLocal } = (await uri2local(payload.image));
|
||||||
let Uri2LocalRet = (await uri2local(payload.image));
|
if (errMsg) {
|
||||||
Image_errMsg = Uri2LocalRet.errMsg;
|
|
||||||
Image_path = Uri2LocalRet.path;
|
|
||||||
Image_IsLocal = Uri2LocalRet.isLocal;
|
|
||||||
if (Image_errMsg) {
|
|
||||||
throw `群公告${payload.image}设置失败,image字段可能格式不正确`;
|
throw `群公告${payload.image}设置失败,image字段可能格式不正确`;
|
||||||
}
|
}
|
||||||
if (!Image_path) {
|
if (!path) {
|
||||||
throw `群公告${payload.image}设置失败,获取资源失败`;
|
throw `群公告${payload.image}设置失败,获取资源失败`;
|
||||||
}
|
}
|
||||||
await checkFileReceived(Image_path, 5000); // 文件不存在QQ会崩溃,需要提前判断
|
await checkFileReceived(path, 5000); // 文件不存在QQ会崩溃,需要提前判断
|
||||||
let ImageUploadResult = await NTQQGroupApi.uploadGroupBulletinPic(payload.group_id.toString(), Image_path);
|
const ImageUploadResult = await NTQQGroupApi.uploadGroupBulletinPic(payload.group_id.toString(), path);
|
||||||
if (ImageUploadResult.errCode != 0) {
|
if (ImageUploadResult.errCode != 0) {
|
||||||
throw `群公告${payload.image}设置失败,图片上传失败`;
|
throw `群公告${payload.image}设置失败,图片上传失败`;
|
||||||
}
|
}
|
||||||
if (!Image_IsLocal) {
|
if (!isLocal) {
|
||||||
unlink(Image_path, () => { });
|
unlink(path, () => { });
|
||||||
}
|
}
|
||||||
UploadImage = ImageUploadResult.picInfo;
|
UploadImage = ImageUploadResult.picInfo;
|
||||||
}
|
}
|
||||||
@ -53,7 +49,7 @@ export class SendGroupNotice extends BaseAction<Payload, null> {
|
|||||||
if (!payload.confirmRequired) {
|
if (!payload.confirmRequired) {
|
||||||
Notice_confirmRequired = 0;
|
Notice_confirmRequired = 0;
|
||||||
}
|
}
|
||||||
let PublishGroupBulletinResult = await NTQQGroupApi.publishGroupBulletin(payload.group_id.toString(), payload.content, UploadImage, Notice_Pinned, Notice_confirmRequired);
|
const PublishGroupBulletinResult = await NTQQGroupApi.publishGroupBulletin(payload.group_id.toString(), payload.content, UploadImage, Notice_Pinned, Notice_confirmRequired);
|
||||||
|
|
||||||
if (PublishGroupBulletinResult.result != 0) {
|
if (PublishGroupBulletinResult.result != 0) {
|
||||||
throw `设置群公告失败,错误信息:${PublishGroupBulletinResult.errMsg}`;
|
throw `设置群公告失败,错误信息:${PublishGroupBulletinResult.errMsg}`;
|
||||||
|
@ -18,8 +18,8 @@ export class GetGroupSystemMsg extends BaseAction<void, any> {
|
|||||||
actionName = ActionName.GetGroupSystemMsg;
|
actionName = ActionName.GetGroupSystemMsg;
|
||||||
protected async _handle(payload: void) {
|
protected async _handle(payload: void) {
|
||||||
// 默认10条 该api未完整实现 包括响应数据规范化 类型规范化
|
// 默认10条 该api未完整实现 包括响应数据规范化 类型规范化
|
||||||
let SingleScreenNotifies = await NTQQGroupApi.getSingleScreenNotifies(10);
|
const SingleScreenNotifies = await NTQQGroupApi.getSingleScreenNotifies(10);
|
||||||
let retData: any = { InvitedRequest: [], join_requests: [] };
|
const retData: any = { InvitedRequest: [], join_requests: [] };
|
||||||
for (const SSNotify of SingleScreenNotifies) {
|
for (const SSNotify of SingleScreenNotifies) {
|
||||||
if (SSNotify.type == 1) {
|
if (SSNotify.type == 1) {
|
||||||
retData.InvitedRequest.push({
|
retData.InvitedRequest.push({
|
||||||
|
@ -104,7 +104,7 @@ const _handlers: {
|
|||||||
// File service
|
// File service
|
||||||
|
|
||||||
[OB11MessageDataType.image]: async (sendMsg, context) => {
|
[OB11MessageDataType.image]: async (sendMsg, context) => {
|
||||||
let PicEle = await SendMsgElementConstructor.pic(
|
const PicEle = await SendMsgElementConstructor.pic(
|
||||||
(await handleOb11FileLikeMessage(sendMsg, context)).path,
|
(await handleOb11FileLikeMessage(sendMsg, context)).path,
|
||||||
sendMsg.data.summary || '',
|
sendMsg.data.summary || '',
|
||||||
sendMsg.data.subType || 0
|
sendMsg.data.subType || 0
|
||||||
|
@ -51,16 +51,16 @@ export async function sendMsg(peer: Peer, sendElements: SendMessageElement[], de
|
|||||||
totalSize += fs.statSync(fileElement.videoElement.filePath).size;
|
totalSize += fs.statSync(fileElement.videoElement.filePath).size;
|
||||||
}
|
}
|
||||||
if (fileElement.elementType === ElementType.PIC) {
|
if (fileElement.elementType === ElementType.PIC) {
|
||||||
totalSize += fs.statSync(fileElement.picElement.sourcePath).size
|
totalSize += fs.statSync(fileElement.picElement.sourcePath).size;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//且 PredictTime ((totalSize / 1024 / 512) * 1000)不等于Nan
|
//且 PredictTime ((totalSize / 1024 / 512) * 1000)不等于Nan
|
||||||
let PredictTime = totalSize / 1024 / 512 * 1000;
|
const PredictTime = totalSize / 1024 / 512 * 1000;
|
||||||
if (!Number.isNaN(PredictTime)) {
|
if (!Number.isNaN(PredictTime)) {
|
||||||
timeout += PredictTime// 5S Basic Timeout + PredictTime( For File 512kb/s )
|
timeout += PredictTime;// 5S Basic Timeout + PredictTime( For File 512kb/s )
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logError("发送消息计算预计时间异常", e);
|
logError('发送消息计算预计时间异常', e);
|
||||||
}
|
}
|
||||||
const returnMsg = await NTQQMsgApi.sendMsg(peer, sendElements, waitComplete, timeout);
|
const returnMsg = await NTQQMsgApi.sendMsg(peer, sendElements, waitComplete, timeout);
|
||||||
try {
|
try {
|
||||||
|
@ -60,7 +60,7 @@ export enum ActionName {
|
|||||||
CleanCache = 'clean_cache',
|
CleanCache = 'clean_cache',
|
||||||
GetCookies = 'get_cookies',
|
GetCookies = 'get_cookies',
|
||||||
// 以下为go-cqhttp api
|
// 以下为go-cqhttp api
|
||||||
GoCQHTTP_HandleQuickAction = ".handle_quick_operation",
|
GoCQHTTP_HandleQuickAction = '.handle_quick_operation',
|
||||||
GetGroupHonorInfo = 'get_group_honor_info',
|
GetGroupHonorInfo = 'get_group_honor_info',
|
||||||
GoCQHTTP_GetEssenceMsg = 'get_essence_msg_list',
|
GoCQHTTP_GetEssenceMsg = 'get_essence_msg_list',
|
||||||
GoCQHTTP_SendGroupNotice = '_send_group_notice',
|
GoCQHTTP_SendGroupNotice = '_send_group_notice',
|
||||||
@ -78,5 +78,5 @@ export enum ActionName {
|
|||||||
GoCQHTTP_GetGroupMsgHistory = 'get_group_msg_history',
|
GoCQHTTP_GetGroupMsgHistory = 'get_group_msg_history',
|
||||||
GoCQHTTP_GetForwardMsg = 'get_forward_msg',
|
GoCQHTTP_GetForwardMsg = 'get_forward_msg',
|
||||||
GetFriendMsgHistory = 'get_friend_msg_history',
|
GetFriendMsgHistory = 'get_friend_msg_history',
|
||||||
GetGroupSystemMsg = "get_group_system_msg"
|
GetGroupSystemMsg = 'get_group_system_msg'
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
import fs from "node:fs";
|
import fs from 'node:fs';
|
||||||
import path from "node:path";
|
import path from 'node:path';
|
||||||
import { selfInfo } from "@/core/data";
|
import { selfInfo } from '@/core/data';
|
||||||
import { logDebug, logError } from "@/common/utils/log";
|
import { logDebug, logError } from '@/common/utils/log';
|
||||||
import { ConfigBase } from "@/common/utils/ConfigBase";
|
import { ConfigBase } from '@/common/utils/ConfigBase';
|
||||||
import { json } from "stream/consumers";
|
import { json } from 'stream/consumers';
|
||||||
|
|
||||||
export interface OB11Config {
|
export interface OB11Config {
|
||||||
http: {
|
http: {
|
||||||
@ -27,7 +27,7 @@ export interface OB11Config {
|
|||||||
|
|
||||||
debug: boolean;
|
debug: boolean;
|
||||||
heartInterval: number;
|
heartInterval: number;
|
||||||
messagePostFormat: "array" | "string";
|
messagePostFormat: 'array' | 'string';
|
||||||
enableLocalFile2Url: boolean;
|
enableLocalFile2Url: boolean;
|
||||||
musicSignUrl: string;
|
musicSignUrl: string;
|
||||||
reportSelfMessage: boolean;
|
reportSelfMessage: boolean;
|
||||||
@ -41,16 +41,16 @@ export interface OB11Config {
|
|||||||
class Config extends ConfigBase<OB11Config> implements OB11Config {
|
class Config extends ConfigBase<OB11Config> implements OB11Config {
|
||||||
http = {
|
http = {
|
||||||
enable: false,
|
enable: false,
|
||||||
host: "",
|
host: '',
|
||||||
port: 3000,
|
port: 3000,
|
||||||
secret: "",
|
secret: '',
|
||||||
enableHeart: false,
|
enableHeart: false,
|
||||||
enablePost: false,
|
enablePost: false,
|
||||||
postUrls: [],
|
postUrls: [],
|
||||||
};
|
};
|
||||||
ws = {
|
ws = {
|
||||||
enable: false,
|
enable: false,
|
||||||
host: "",
|
host: '',
|
||||||
port: 3001,
|
port: 3001,
|
||||||
};
|
};
|
||||||
reverseWs = {
|
reverseWs = {
|
||||||
@ -59,11 +59,11 @@ class Config extends ConfigBase<OB11Config> implements OB11Config {
|
|||||||
};
|
};
|
||||||
debug = false;
|
debug = false;
|
||||||
heartInterval = 30000;
|
heartInterval = 30000;
|
||||||
messagePostFormat: "array" | "string" = "array";
|
messagePostFormat: 'array' | 'string' = 'array';
|
||||||
enableLocalFile2Url = true;
|
enableLocalFile2Url = true;
|
||||||
musicSignUrl = "";
|
musicSignUrl = '';
|
||||||
reportSelfMessage = false;
|
reportSelfMessage = false;
|
||||||
token = "";
|
token = '';
|
||||||
|
|
||||||
getConfigPath() {
|
getConfigPath() {
|
||||||
return path.join(this.getConfigDir(), `onebot11_${selfInfo.uin}.json`);
|
return path.join(this.getConfigDir(), `onebot11_${selfInfo.uin}.json`);
|
||||||
|
@ -31,10 +31,11 @@ import { OB11GroupRecallNoticeEvent } from '@/onebot11/event/notice/OB11GroupRec
|
|||||||
import { logMessage, logNotice, logRequest } from '@/onebot11/log';
|
import { logMessage, logNotice, logRequest } from '@/onebot11/log';
|
||||||
import { OB11Message } from '@/onebot11/types';
|
import { OB11Message } from '@/onebot11/types';
|
||||||
import { OB11LifeCycleEvent } from './event/meta/OB11LifeCycleEvent';
|
import { OB11LifeCycleEvent } from './event/meta/OB11LifeCycleEvent';
|
||||||
import { Data as SysData } from '@/proto/SysMessage'
|
import { Data as SysData } from '@/proto/SysMessage';
|
||||||
import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent';
|
import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent';
|
||||||
|
import { isEqual } from '@/common/utils/helper';
|
||||||
//peer->cached(boolen)
|
//peer->cached(boolen)
|
||||||
let PokeCache = new Map<string, boolean>();
|
const PokeCache = new Map<string, boolean>();
|
||||||
export class NapCatOnebot11 {
|
export class NapCatOnebot11 {
|
||||||
private bootTime: number = Date.now() / 1000; // 秒
|
private bootTime: number = Date.now() / 1000; // 秒
|
||||||
|
|
||||||
@ -92,12 +93,12 @@ export class NapCatOnebot11 {
|
|||||||
// }
|
// }
|
||||||
// };
|
// };
|
||||||
try {
|
try {
|
||||||
let sysMsg = SysData.fromBinary(Buffer.from(protobufData));
|
const sysMsg = SysData.fromBinary(Buffer.from(protobufData));
|
||||||
let peeruin = sysMsg.header[0].groupNumber;
|
const peeruin = sysMsg.header[0].groupNumber;
|
||||||
let peeruid = sysMsg.header[0].groupString;
|
const peeruid = sysMsg.header[0].groupString;
|
||||||
let MsgType = sysMsg.body[0].msgType;
|
const MsgType = sysMsg.body[0].msgType;
|
||||||
let subType0 = sysMsg.body[0].subType0;
|
const subType0 = sysMsg.body[0].subType0;
|
||||||
let subType1 = sysMsg.body[0].subType1;
|
const subType1 = sysMsg.body[0].subType1;
|
||||||
let pokeEvent: OB11FriendPokeEvent | OB11GroupPokeEvent;
|
let pokeEvent: OB11FriendPokeEvent | OB11GroupPokeEvent;
|
||||||
//console.log(peeruid);
|
//console.log(peeruid);
|
||||||
if (MsgType == 528 && subType0 == 290) {
|
if (MsgType == 528 && subType0 == 290) {
|
||||||
@ -106,7 +107,7 @@ export class NapCatOnebot11 {
|
|||||||
PokeCache.delete(peeruid);
|
PokeCache.delete(peeruid);
|
||||||
} else {
|
} else {
|
||||||
PokeCache.set(peeruid, false);
|
PokeCache.set(peeruid, false);
|
||||||
log("[私聊] 用户 ", peeruin, " 对你戳一戳");
|
log('[私聊] 用户 ', peeruin, ' 对你戳一戳');
|
||||||
pokeEvent = new OB11FriendPokeEvent(peeruin);
|
pokeEvent = new OB11FriendPokeEvent(peeruin);
|
||||||
postOB11Event(pokeEvent);
|
postOB11Event(pokeEvent);
|
||||||
}
|
}
|
||||||
@ -117,13 +118,13 @@ export class NapCatOnebot11 {
|
|||||||
PokeCache.delete(peeruid);
|
PokeCache.delete(peeruid);
|
||||||
} else {
|
} else {
|
||||||
PokeCache.set(peeruid, false);
|
PokeCache.set(peeruid, false);
|
||||||
log("[群聊] 群组 ", peeruin, " 戳一戳");
|
log('[群聊] 群组 ', peeruin, ' 戳一戳');
|
||||||
pokeEvent = new OB11GroupPokeEvent(peeruin);
|
pokeEvent = new OB11GroupPokeEvent(peeruin);
|
||||||
postOB11Event(pokeEvent);
|
postOB11Event(pokeEvent);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("解析SysMsg异常", e);
|
log('解析SysMsg异常', e);
|
||||||
// console.log(e);
|
// console.log(e);
|
||||||
//
|
//
|
||||||
}
|
}
|
||||||
@ -184,15 +185,15 @@ export class NapCatOnebot11 {
|
|||||||
};
|
};
|
||||||
groupListener.onMemberInfoChange = async (groupCode: string, changeType: number, members: Map<string, GroupMember>) => {
|
groupListener.onMemberInfoChange = async (groupCode: string, changeType: number, members: Map<string, GroupMember>) => {
|
||||||
// 如果自身是非管理员也许要从这里获取Delete 成员变动 待测试与验证
|
// 如果自身是非管理员也许要从这里获取Delete 成员变动 待测试与验证
|
||||||
let role = (await getGroupMember(groupCode, selfInfo.uin))?.role;
|
const role = (await getGroupMember(groupCode, selfInfo.uin))?.role;
|
||||||
let isPrivilege = role === 3 || role === 4;
|
const isPrivilege = role === 3 || role === 4;
|
||||||
for (const member of members.values()) {
|
for (const member of members.values()) {
|
||||||
if (member?.isDelete && !isPrivilege) {
|
if (member?.isDelete && !isPrivilege) {
|
||||||
const groupDecreaseEvent = new OB11GroupDecreaseEvent(parseInt(groupCode), parseInt(member.uin), 0, 'leave');// 不知道怎么出去的
|
const groupDecreaseEvent = new OB11GroupDecreaseEvent(parseInt(groupCode), parseInt(member.uin), 0, 'leave');// 不知道怎么出去的
|
||||||
postOB11Event(groupDecreaseEvent, true);
|
postOB11Event(groupDecreaseEvent, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
groupListener.onJoinGroupNotify = (...notify) => {
|
groupListener.onJoinGroupNotify = (...notify) => {
|
||||||
// console.log('ob11 onJoinGroupNotify', notify);
|
// console.log('ob11 onJoinGroupNotify', notify);
|
||||||
};
|
};
|
||||||
@ -253,21 +254,6 @@ export class NapCatOnebot11 {
|
|||||||
}
|
}
|
||||||
async SetConfig(NewOb11: OB11Config) {
|
async SetConfig(NewOb11: OB11Config) {
|
||||||
try {
|
try {
|
||||||
function isEqual(obj1: any, obj2: any) {
|
|
||||||
if (obj1 === obj2) return true;
|
|
||||||
if (obj1 == null || obj2 == null) return false;
|
|
||||||
if (typeof obj1 !== 'object' || typeof obj2 !== 'object') return obj1 === obj2;
|
|
||||||
|
|
||||||
const keys1 = Object.keys(obj1);
|
|
||||||
const keys2 = Object.keys(obj2);
|
|
||||||
|
|
||||||
if (keys1.length !== keys2.length) return false;
|
|
||||||
|
|
||||||
for (let key of keys1) {
|
|
||||||
if (!isEqual(obj1[key], obj2[key])) return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
// if (!NewOb11 || typeof NewOb11 !== 'object') {
|
// if (!NewOb11 || typeof NewOb11 !== 'object') {
|
||||||
// throw new Error('Invalid configuration object');
|
// throw new Error('Invalid configuration object');
|
||||||
// }
|
// }
|
||||||
|
@ -170,26 +170,26 @@ async function handleGroupRequest(request: OB11GroupRequestEvent, quickAction: Q
|
|||||||
groupNotifies[request.flag],
|
groupNotifies[request.flag],
|
||||||
quickAction.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
|
quickAction.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
|
||||||
quickAction.reason,
|
quickAction.reason,
|
||||||
).then().catch(logError)
|
).then().catch(logError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function handleFriendRequest(request: OB11FriendRequestEvent, quickAction: QuickActionFriendRequest) {
|
async function handleFriendRequest(request: OB11FriendRequestEvent, quickAction: QuickActionFriendRequest) {
|
||||||
if (!isNull(quickAction.approve)) {
|
if (!isNull(quickAction.approve)) {
|
||||||
NTQQFriendApi.handleFriendRequest(friendRequests[request.flag], !!quickAction.approve).then().catch(logError)
|
NTQQFriendApi.handleFriendRequest(friendRequests[request.flag], !!quickAction.approve).then().catch(logError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export async function handleQuickOperation(context: QuickActionEvent, quickAction: QuickAction) {
|
export async function handleQuickOperation(context: QuickActionEvent, quickAction: QuickAction) {
|
||||||
if (context.post_type === 'message') {
|
if (context.post_type === 'message') {
|
||||||
handleMsg(context as OB11Message, quickAction).then().catch(logError)
|
handleMsg(context as OB11Message, quickAction).then().catch(logError);
|
||||||
}
|
}
|
||||||
if (context.post_type === 'request') {
|
if (context.post_type === 'request') {
|
||||||
const friendRequest = context as OB11FriendRequestEvent;
|
const friendRequest = context as OB11FriendRequestEvent;
|
||||||
const groupRequest = context as OB11GroupRequestEvent;
|
const groupRequest = context as OB11GroupRequestEvent;
|
||||||
if ((friendRequest).request_type === 'friend') {
|
if ((friendRequest).request_type === 'friend') {
|
||||||
handleFriendRequest(friendRequest, quickAction).then().catch(logError)
|
handleFriendRequest(friendRequest, quickAction).then().catch(logError);
|
||||||
}
|
}
|
||||||
else if (groupRequest.request_type === 'group') {
|
else if (groupRequest.request_type === 'group') {
|
||||||
handleGroupRequest(groupRequest, quickAction).then().catch(logError)
|
handleGroupRequest(groupRequest, quickAction).then().catch(logError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,15 +1,15 @@
|
|||||||
// @generated by protobuf-ts 2.9.4
|
// @generated by protobuf-ts 2.9.4
|
||||||
// @generated from protobuf file "SysMessage.proto" (package "SysMessage", syntax proto3)
|
// @generated from protobuf file "SysMessage.proto" (package "SysMessage", syntax proto3)
|
||||||
// tslint:disable
|
// tslint:disable
|
||||||
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
|
import type { BinaryWriteOptions } from '@protobuf-ts/runtime';
|
||||||
import type { IBinaryWriter } from "@protobuf-ts/runtime";
|
import type { IBinaryWriter } from '@protobuf-ts/runtime';
|
||||||
import { WireType } from "@protobuf-ts/runtime";
|
import { WireType } from '@protobuf-ts/runtime';
|
||||||
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
|
import type { BinaryReadOptions } from '@protobuf-ts/runtime';
|
||||||
import type { IBinaryReader } from "@protobuf-ts/runtime";
|
import type { IBinaryReader } from '@protobuf-ts/runtime';
|
||||||
import { UnknownFieldHandler } from "@protobuf-ts/runtime";
|
import { UnknownFieldHandler } from '@protobuf-ts/runtime';
|
||||||
import type { PartialMessage } from "@protobuf-ts/runtime";
|
import type { PartialMessage } from '@protobuf-ts/runtime';
|
||||||
import { reflectionMergePartial } from "@protobuf-ts/runtime";
|
import { reflectionMergePartial } from '@protobuf-ts/runtime';
|
||||||
import { MessageType } from "@protobuf-ts/runtime";
|
import { MessageType } from '@protobuf-ts/runtime';
|
||||||
/**
|
/**
|
||||||
* @generated from protobuf message SysMessage.Data
|
* @generated from protobuf message SysMessage.Data
|
||||||
*/
|
*/
|
||||||
@ -80,9 +80,9 @@ export interface Body {
|
|||||||
// @generated message type with reflection information, may provide speed optimized methods
|
// @generated message type with reflection information, may provide speed optimized methods
|
||||||
class Data$Type extends MessageType<Data> {
|
class Data$Type extends MessageType<Data> {
|
||||||
constructor() {
|
constructor() {
|
||||||
super("SysMessage.Data", [
|
super('SysMessage.Data', [
|
||||||
{ no: 1, name: "header", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => Header },
|
{ no: 1, name: 'header', kind: 'message', repeat: 1 /*RepeatType.PACKED*/, T: () => Header },
|
||||||
{ no: 2, name: "body", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => Body }
|
{ no: 2, name: 'body', kind: 'message', repeat: 1 /*RepeatType.PACKED*/, T: () => Body }
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
create(value?: PartialMessage<Data>): Data {
|
create(value?: PartialMessage<Data>): Data {
|
||||||
@ -94,9 +94,9 @@ class Data$Type extends MessageType<Data> {
|
|||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Data): Data {
|
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Data): Data {
|
||||||
let message = target ?? this.create(), end = reader.pos + length;
|
const message = target ?? this.create(), end = reader.pos + length;
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
let [fieldNo, wireType] = reader.tag();
|
const [fieldNo, wireType] = reader.tag();
|
||||||
switch (fieldNo) {
|
switch (fieldNo) {
|
||||||
case /* repeated SysMessage.Header header */ 1:
|
case /* repeated SysMessage.Header header */ 1:
|
||||||
message.header.push(Header.internalBinaryRead(reader, reader.uint32(), options));
|
message.header.push(Header.internalBinaryRead(reader, reader.uint32(), options));
|
||||||
@ -105,10 +105,10 @@ class Data$Type extends MessageType<Data> {
|
|||||||
message.body.push(Body.internalBinaryRead(reader, reader.uint32(), options));
|
message.body.push(Body.internalBinaryRead(reader, reader.uint32(), options));
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
let u = options.readUnknownField;
|
const u = options.readUnknownField;
|
||||||
if (u === "throw")
|
if (u === 'throw')
|
||||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||||
let d = reader.skip(wireType);
|
const d = reader.skip(wireType);
|
||||||
if (u !== false)
|
if (u !== false)
|
||||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||||
}
|
}
|
||||||
@ -122,7 +122,7 @@ class Data$Type extends MessageType<Data> {
|
|||||||
/* repeated SysMessage.Body body = 2; */
|
/* repeated SysMessage.Body body = 2; */
|
||||||
for (let i = 0; i < message.body.length; i++)
|
for (let i = 0; i < message.body.length; i++)
|
||||||
Body.internalBinaryWrite(message.body[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join();
|
Body.internalBinaryWrite(message.body[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join();
|
||||||
let u = options.writeUnknownFields;
|
const u = options.writeUnknownFields;
|
||||||
if (u !== false)
|
if (u !== false)
|
||||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||||
return writer;
|
return writer;
|
||||||
@ -135,26 +135,26 @@ export const Data = new Data$Type();
|
|||||||
// @generated message type with reflection information, may provide speed optimized methods
|
// @generated message type with reflection information, may provide speed optimized methods
|
||||||
class Header$Type extends MessageType<Header> {
|
class Header$Type extends MessageType<Header> {
|
||||||
constructor() {
|
constructor() {
|
||||||
super("SysMessage.Header", [
|
super('SysMessage.Header', [
|
||||||
{ no: 1, name: "GroupNumber", kind: "scalar", jsonName: "GroupNumber", T: 13 /*ScalarType.UINT32*/ },
|
{ no: 1, name: 'GroupNumber', kind: 'scalar', jsonName: 'GroupNumber', T: 13 /*ScalarType.UINT32*/ },
|
||||||
{ no: 2, name: "GroupString", kind: "scalar", jsonName: "GroupString", T: 9 /*ScalarType.STRING*/ },
|
{ no: 2, name: 'GroupString', kind: 'scalar', jsonName: 'GroupString', T: 9 /*ScalarType.STRING*/ },
|
||||||
{ no: 5, name: "QQ", kind: "scalar", jsonName: "QQ", T: 13 /*ScalarType.UINT32*/ },
|
{ no: 5, name: 'QQ', kind: 'scalar', jsonName: 'QQ', T: 13 /*ScalarType.UINT32*/ },
|
||||||
{ no: 6, name: "Uid", kind: "scalar", jsonName: "Uid", opt: true, T: 9 /*ScalarType.STRING*/ }
|
{ no: 6, name: 'Uid', kind: 'scalar', jsonName: 'Uid', opt: true, T: 9 /*ScalarType.STRING*/ }
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
create(value?: PartialMessage<Header>): Header {
|
create(value?: PartialMessage<Header>): Header {
|
||||||
const message = globalThis.Object.create((this.messagePrototype!));
|
const message = globalThis.Object.create((this.messagePrototype!));
|
||||||
message.groupNumber = 0;
|
message.groupNumber = 0;
|
||||||
message.groupString = "";
|
message.groupString = '';
|
||||||
message.qQ = 0;
|
message.qQ = 0;
|
||||||
if (value !== undefined)
|
if (value !== undefined)
|
||||||
reflectionMergePartial<Header>(this, message, value);
|
reflectionMergePartial<Header>(this, message, value);
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Header): Header {
|
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Header): Header {
|
||||||
let message = target ?? this.create(), end = reader.pos + length;
|
const message = target ?? this.create(), end = reader.pos + length;
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
let [fieldNo, wireType] = reader.tag();
|
const [fieldNo, wireType] = reader.tag();
|
||||||
switch (fieldNo) {
|
switch (fieldNo) {
|
||||||
case /* uint32 GroupNumber = 1 [json_name = "GroupNumber"];*/ 1:
|
case /* uint32 GroupNumber = 1 [json_name = "GroupNumber"];*/ 1:
|
||||||
message.groupNumber = reader.uint32();
|
message.groupNumber = reader.uint32();
|
||||||
@ -169,10 +169,10 @@ class Header$Type extends MessageType<Header> {
|
|||||||
message.uid = reader.string();
|
message.uid = reader.string();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
let u = options.readUnknownField;
|
const u = options.readUnknownField;
|
||||||
if (u === "throw")
|
if (u === 'throw')
|
||||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||||
let d = reader.skip(wireType);
|
const d = reader.skip(wireType);
|
||||||
if (u !== false)
|
if (u !== false)
|
||||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||||
}
|
}
|
||||||
@ -184,7 +184,7 @@ class Header$Type extends MessageType<Header> {
|
|||||||
if (message.groupNumber !== 0)
|
if (message.groupNumber !== 0)
|
||||||
writer.tag(1, WireType.Varint).uint32(message.groupNumber);
|
writer.tag(1, WireType.Varint).uint32(message.groupNumber);
|
||||||
/* string GroupString = 2 [json_name = "GroupString"]; */
|
/* string GroupString = 2 [json_name = "GroupString"]; */
|
||||||
if (message.groupString !== "")
|
if (message.groupString !== '')
|
||||||
writer.tag(2, WireType.LengthDelimited).string(message.groupString);
|
writer.tag(2, WireType.LengthDelimited).string(message.groupString);
|
||||||
/* uint32 QQ = 5 [json_name = "QQ"]; */
|
/* uint32 QQ = 5 [json_name = "QQ"]; */
|
||||||
if (message.qQ !== 0)
|
if (message.qQ !== 0)
|
||||||
@ -192,7 +192,7 @@ class Header$Type extends MessageType<Header> {
|
|||||||
/* optional string Uid = 6 [json_name = "Uid"]; */
|
/* optional string Uid = 6 [json_name = "Uid"]; */
|
||||||
if (message.uid !== undefined)
|
if (message.uid !== undefined)
|
||||||
writer.tag(6, WireType.LengthDelimited).string(message.uid);
|
writer.tag(6, WireType.LengthDelimited).string(message.uid);
|
||||||
let u = options.writeUnknownFields;
|
const u = options.writeUnknownFields;
|
||||||
if (u !== false)
|
if (u !== false)
|
||||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||||
return writer;
|
return writer;
|
||||||
@ -205,14 +205,14 @@ export const Header = new Header$Type();
|
|||||||
// @generated message type with reflection information, may provide speed optimized methods
|
// @generated message type with reflection information, may provide speed optimized methods
|
||||||
class Body$Type extends MessageType<Body> {
|
class Body$Type extends MessageType<Body> {
|
||||||
constructor() {
|
constructor() {
|
||||||
super("SysMessage.Body", [
|
super('SysMessage.Body', [
|
||||||
{ no: 1, name: "MsgType", kind: "scalar", jsonName: "MsgType", T: 13 /*ScalarType.UINT32*/ },
|
{ no: 1, name: 'MsgType', kind: 'scalar', jsonName: 'MsgType', T: 13 /*ScalarType.UINT32*/ },
|
||||||
{ no: 2, name: "SubType_0", kind: "scalar", jsonName: "SubType0", T: 13 /*ScalarType.UINT32*/ },
|
{ no: 2, name: 'SubType_0', kind: 'scalar', jsonName: 'SubType0', T: 13 /*ScalarType.UINT32*/ },
|
||||||
{ no: 3, name: "SubType_1", kind: "scalar", jsonName: "SubType1", T: 13 /*ScalarType.UINT32*/ },
|
{ no: 3, name: 'SubType_1', kind: 'scalar', jsonName: 'SubType1', T: 13 /*ScalarType.UINT32*/ },
|
||||||
{ no: 5, name: "MsgSeq", kind: "scalar", jsonName: "MsgSeq", T: 13 /*ScalarType.UINT32*/ },
|
{ no: 5, name: 'MsgSeq', kind: 'scalar', jsonName: 'MsgSeq', T: 13 /*ScalarType.UINT32*/ },
|
||||||
{ no: 6, name: "Time", kind: "scalar", jsonName: "Time", T: 13 /*ScalarType.UINT32*/ },
|
{ no: 6, name: 'Time', kind: 'scalar', jsonName: 'Time', T: 13 /*ScalarType.UINT32*/ },
|
||||||
{ no: 12, name: "MsgID", kind: "scalar", jsonName: "MsgID", T: 4 /*ScalarType.UINT64*/, L: 0 /*LongType.BIGINT*/ },
|
{ no: 12, name: 'MsgID', kind: 'scalar', jsonName: 'MsgID', T: 4 /*ScalarType.UINT64*/, L: 0 /*LongType.BIGINT*/ },
|
||||||
{ no: 13, name: "Other", kind: "scalar", jsonName: "Other", T: 13 /*ScalarType.UINT32*/ }
|
{ no: 13, name: 'Other', kind: 'scalar', jsonName: 'Other', T: 13 /*ScalarType.UINT32*/ }
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
create(value?: PartialMessage<Body>): Body {
|
create(value?: PartialMessage<Body>): Body {
|
||||||
@ -229,9 +229,9 @@ class Body$Type extends MessageType<Body> {
|
|||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Body): Body {
|
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Body): Body {
|
||||||
let message = target ?? this.create(), end = reader.pos + length;
|
const message = target ?? this.create(), end = reader.pos + length;
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
let [fieldNo, wireType] = reader.tag();
|
const [fieldNo, wireType] = reader.tag();
|
||||||
switch (fieldNo) {
|
switch (fieldNo) {
|
||||||
case /* uint32 MsgType = 1 [json_name = "MsgType"];*/ 1:
|
case /* uint32 MsgType = 1 [json_name = "MsgType"];*/ 1:
|
||||||
message.msgType = reader.uint32();
|
message.msgType = reader.uint32();
|
||||||
@ -255,10 +255,10 @@ class Body$Type extends MessageType<Body> {
|
|||||||
message.other = reader.uint32();
|
message.other = reader.uint32();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
let u = options.readUnknownField;
|
const u = options.readUnknownField;
|
||||||
if (u === "throw")
|
if (u === 'throw')
|
||||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||||
let d = reader.skip(wireType);
|
const d = reader.skip(wireType);
|
||||||
if (u !== false)
|
if (u !== false)
|
||||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||||
}
|
}
|
||||||
@ -287,7 +287,7 @@ class Body$Type extends MessageType<Body> {
|
|||||||
/* uint32 Other = 13 [json_name = "Other"]; */
|
/* uint32 Other = 13 [json_name = "Other"]; */
|
||||||
if (message.other !== 0)
|
if (message.other !== 0)
|
||||||
writer.tag(13, WireType.Varint).uint32(message.other);
|
writer.tag(13, WireType.Varint).uint32(message.other);
|
||||||
let u = options.writeUnknownFields;
|
const u = options.writeUnknownFields;
|
||||||
if (u !== false)
|
if (u !== false)
|
||||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||||
return writer;
|
return writer;
|
||||||
|
@ -5,8 +5,8 @@ import { resolve } from 'node:path';
|
|||||||
import { ALLRouter } from './src/router';
|
import { ALLRouter } from './src/router';
|
||||||
import { WebUiConfig } from './src/helper/config';
|
import { WebUiConfig } from './src/helper/config';
|
||||||
const app = express();
|
const app = express();
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
@ -19,7 +19,7 @@ const __dirname = dirname(__filename);
|
|||||||
* @returns {Promise<void>} 无返回值。
|
* @returns {Promise<void>} 无返回值。
|
||||||
*/
|
*/
|
||||||
export async function InitWebUi() {
|
export async function InitWebUi() {
|
||||||
let config = await WebUiConfig.GetWebUIConfig();
|
const config = await WebUiConfig.GetWebUIConfig();
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
// 初始服务
|
// 初始服务
|
||||||
app.all('/', (_req, res) => {
|
app.all('/', (_req, res) => {
|
||||||
@ -34,6 +34,6 @@ export async function InitWebUi() {
|
|||||||
app.listen(config.port, async () => {
|
app.listen(config.port, async () => {
|
||||||
console.log(`[NapCat] [WebUi] Current WebUi is running at IP:${config.port}`);
|
console.log(`[NapCat] [WebUi] Current WebUi is running at IP:${config.port}`);
|
||||||
console.log(`[NapCat] [WebUi] Login Token is ${config.token}`);
|
console.log(`[NapCat] [WebUi] Login Token is ${config.token}`);
|
||||||
})
|
});
|
||||||
|
|
||||||
}
|
}
|
@ -1,10 +1,10 @@
|
|||||||
import { RequestHandler } from "express";
|
import { RequestHandler } from 'express';
|
||||||
import { AuthHelper } from "../helper/SignToken";
|
import { AuthHelper } from '../helper/SignToken';
|
||||||
import { WebUiConfig } from "../helper/config";
|
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) => {
|
||||||
let 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({
|
||||||
@ -28,12 +28,12 @@ export const LoginHandler: RequestHandler = async (req, res) => {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let signCredential = Buffer.from(JSON.stringify(await AuthHelper.signCredential(WebUiConfigData.token))).toString('base64');
|
const signCredential = Buffer.from(JSON.stringify(await AuthHelper.signCredential(WebUiConfigData.token))).toString('base64');
|
||||||
res.json({
|
res.json({
|
||||||
code: 0,
|
code: 0,
|
||||||
message: 'success',
|
message: 'success',
|
||||||
data: {
|
data: {
|
||||||
"Credential": signCredential
|
'Credential': signCredential
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@ -47,12 +47,12 @@ export const LogoutHandler: RequestHandler = (req, res) => {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
export const checkHandler: RequestHandler = async (req, res) => {
|
export const checkHandler: RequestHandler = async (req, res) => {
|
||||||
let WebUiConfigData = await WebUiConfig.GetWebUIConfig();
|
const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
|
||||||
const authorization = req.headers.authorization;
|
const authorization = req.headers.authorization;
|
||||||
try {
|
try {
|
||||||
let CredentialBase64:string = authorization?.split(' ')[1] as string;
|
const CredentialBase64:string = authorization?.split(' ')[1] as string;
|
||||||
let Credential = JSON.parse(Buffer.from(CredentialBase64, 'base64').toString());
|
const Credential = JSON.parse(Buffer.from(CredentialBase64, 'base64').toString());
|
||||||
await AuthHelper.validateCredentialWithinOneHour(WebUiConfigData.token,Credential)
|
await AuthHelper.validateCredentialWithinOneHour(WebUiConfigData.token,Credential);
|
||||||
res.json({
|
res.json({
|
||||||
code: 0,
|
code: 0,
|
||||||
message: 'success'
|
message: 'success'
|
||||||
|
@ -1,54 +1,54 @@
|
|||||||
import { RequestHandler } from "express";
|
import { RequestHandler } from 'express';
|
||||||
import { resolve } from "path";
|
import { resolve } from 'path';
|
||||||
import { readdir, stat } from "fs/promises";
|
import { readdir, stat } from 'fs/promises';
|
||||||
import { existsSync } from "fs";
|
import { existsSync } from 'fs';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
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 {
|
||||||
let LogsPath = resolve(__dirname, "./logs/");
|
const LogsPath = resolve(__dirname, './logs/');
|
||||||
let 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) => {
|
||||||
let LogsPath = resolve(__dirname, "./logs/");
|
const LogsPath = resolve(__dirname, './logs/');
|
||||||
let 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;
|
||||||
}
|
// }
|
||||||
|
|
||||||
let 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 {
|
try {
|
||||||
let fileStats = await stat(filePath);
|
const fileStats = await stat(filePath);
|
||||||
if (!fileStats.isFile()) {
|
if (!fileStats.isFile()) {
|
||||||
res.json({ code: -1, msg: "LogFile must be a file" });
|
res.json({ code: -1, msg: 'LogFile must be a file' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.sendFile(filePath);
|
res.sendFile(filePath);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.json({ code: -1, msg: "Failed to send log file." });
|
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 = /[\.\:\*\?\"\<\>\|\/\\]/;
|
||||||
return !invalidChars.test(fileName);
|
// return !invalidChars.test(fileName);
|
||||||
}
|
// }
|
@ -1,64 +1,64 @@
|
|||||||
import { RequestHandler } from "express";
|
import { RequestHandler } from 'express';
|
||||||
import { WebUiDataRuntime } from "../helper/Data";
|
import { WebUiDataRuntime } from '../helper/Data';
|
||||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { resolve } from "node:path";
|
import { resolve } from 'node:path';
|
||||||
import { OB11Config } from "@/webui/ui/components/WebUiApiOB11Config";
|
import { OB11Config } from '@/webui/ui/components/WebUiApiOB11Config';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
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);
|
||||||
|
|
||||||
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) => {
|
||||||
let 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;
|
||||||
}
|
}
|
||||||
const uin = await WebUiDataRuntime.getQQLoginUin();
|
const uin = await WebUiDataRuntime.getQQLoginUin();
|
||||||
let configFilePath = resolve(__dirname, `./config/onebot11_${uin}.json`);
|
const configFilePath = resolve(__dirname, `./config/onebot11_${uin}.json`);
|
||||||
//console.log(configFilePath);
|
//console.log(configFilePath);
|
||||||
let data: OB11Config;
|
let data: OB11Config;
|
||||||
try {
|
try {
|
||||||
data = JSON.parse(
|
data = JSON.parse(
|
||||||
existsSync(configFilePath)
|
existsSync(configFilePath)
|
||||||
? readFileSync(configFilePath).toString()
|
? readFileSync(configFilePath).toString()
|
||||||
: readFileSync(resolve(__dirname, `./config/onebot11.json`)).toString()
|
: readFileSync(resolve(__dirname, './config/onebot11.json')).toString()
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
data = {} as OB11Config;
|
data = {} as OB11Config;
|
||||||
res.send({
|
res.send({
|
||||||
code: -1,
|
code: -1,
|
||||||
message: "Config Get Error",
|
message: 'Config Get Error',
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
res.send({
|
res.send({
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "success",
|
message: 'success',
|
||||||
data: data,
|
data: data,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
export const OB11SetConfigHandler: RequestHandler = async (req, res) => {
|
export const OB11SetConfigHandler: RequestHandler = async (req, res) => {
|
||||||
let 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;
|
||||||
}
|
}
|
||||||
@ -84,12 +84,12 @@ export const OB11SetConfigHandler: RequestHandler = async (req, res) => {
|
|||||||
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',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { RequestHandler } from "express";
|
import { RequestHandler } from 'express';
|
||||||
import { WebUiDataRuntime } from "../helper/Data";
|
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()) {
|
||||||
@ -10,7 +10,7 @@ export const QQGetQRcodeHandler: RequestHandler = async (req, res) => {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let qrcodeUrl = await WebUiDataRuntime.getQQLoginQrcodeURL();
|
const qrcodeUrl = await WebUiDataRuntime.getQQLoginQrcodeURL();
|
||||||
if (isEmpty(qrcodeUrl)) {
|
if (isEmpty(qrcodeUrl)) {
|
||||||
res.send({
|
res.send({
|
||||||
code: -1,
|
code: -1,
|
||||||
@ -37,8 +37,8 @@ export const QQCheckLoginStatusHandler: RequestHandler = async (req, res) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
export const QQSetQuickLoginHandler: RequestHandler = async (req, res) => {
|
export const QQSetQuickLoginHandler: RequestHandler = async (req, res) => {
|
||||||
let { uin } = req.body;
|
const { uin } = req.body;
|
||||||
let isLogin = await WebUiDataRuntime.getQQLoginStatus();
|
const isLogin = await WebUiDataRuntime.getQQLoginStatus();
|
||||||
if (isLogin) {
|
if (isLogin) {
|
||||||
res.send({
|
res.send({
|
||||||
code: -1,
|
code: -1,
|
||||||
@ -67,11 +67,11 @@ export const QQSetQuickLoginHandler: RequestHandler = async (req, res) => {
|
|||||||
code: 0,
|
code: 0,
|
||||||
message: 'success'
|
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
|
||||||
});
|
});
|
||||||
}
|
};
|
@ -1,4 +1,4 @@
|
|||||||
import { OB11Config } from "@/onebot11/config";
|
import { OB11Config } from '@/onebot11/config';
|
||||||
|
|
||||||
interface LoginRuntimeType {
|
interface LoginRuntimeType {
|
||||||
LoginCurrentTime: number;
|
LoginCurrentTime: number;
|
||||||
@ -12,18 +12,18 @@ interface LoginRuntimeType {
|
|||||||
QQLoginList: string[]
|
QQLoginList: string[]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let 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++;
|
||||||
@ -80,4 +80,4 @@ export const WebUiDataRuntime = {
|
|||||||
setOB11Config: async function (ob11: OB11Config): Promise<void> {
|
setOB11Config: async function (ob11: OB11Config): Promise<void> {
|
||||||
await LoginRuntime.NapCatHelper.SetOb11ConfigCall(ob11);
|
await LoginRuntime.NapCatHelper.SetOb11ConfigCall(ob11);
|
||||||
}
|
}
|
||||||
}
|
};
|
@ -1,8 +1,8 @@
|
|||||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { resolve } from "node:path";
|
import { resolve } from 'node:path';
|
||||||
import * as net from "node:net";
|
import * as net from 'node:net';
|
||||||
import { dirname } from "node:path"
|
import { dirname } from 'node:path';
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
@ -14,7 +14,7 @@ const MAX_PORT_TRY = 100;
|
|||||||
async function tryUsePort(port: number, tryCount: number = 0): Promise<number> {
|
async function tryUsePort(port: number, tryCount: number = 0): Promise<number> {
|
||||||
return new Promise(async (resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
try {
|
try {
|
||||||
let server = net.createServer();
|
const server = net.createServer();
|
||||||
server.on('listening', () => {
|
server.on('listening', () => {
|
||||||
server.close();
|
server.close();
|
||||||
resolve(port);
|
resolve(port);
|
||||||
@ -55,8 +55,8 @@ class WebUiConfigWrapper {
|
|||||||
return this.WebUiConfigData;
|
return this.WebUiConfigData;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
let configPath = resolve(__dirname, "./config/webui.json");
|
const configPath = resolve(__dirname, './config/webui.json');
|
||||||
let config: WebUiConfigType = {
|
const config: WebUiConfigType = {
|
||||||
port: 6099,
|
port: 6099,
|
||||||
token: Math.random().toString(36).slice(2),//生成随机密码
|
token: Math.random().toString(36).slice(2),//生成随机密码
|
||||||
loginRate: 3
|
loginRate: 3
|
||||||
@ -66,8 +66,8 @@ class WebUiConfigWrapper {
|
|||||||
writeFileSync(configPath, JSON.stringify(config, null, 4));
|
writeFileSync(configPath, JSON.stringify(config, null, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
let fileContent = readFileSync(configPath, "utf-8");
|
const fileContent = readFileSync(configPath, 'utf-8');
|
||||||
let parsedConfig = JSON.parse(fileContent) as WebUiConfigType;
|
const parsedConfig = JSON.parse(fileContent) as WebUiConfigType;
|
||||||
|
|
||||||
// 修正端口占用情况
|
// 修正端口占用情况
|
||||||
const [err, data] = await tryUsePort(parsedConfig.port).then(data => [null, data as number]).catch(err => [err, null]);
|
const [err, data] = await tryUsePort(parsedConfig.port).then(data => [null, data as number]).catch(err => [err, null]);
|
||||||
@ -78,7 +78,7 @@ class WebUiConfigWrapper {
|
|||||||
this.WebUiConfigData = parsedConfig;
|
this.WebUiConfigData = parsedConfig;
|
||||||
return this.WebUiConfigData;
|
return this.WebUiConfigData;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("读取配置文件失败", e);
|
console.error('读取配置文件失败', e);
|
||||||
}
|
}
|
||||||
return {} as WebUiConfigType; // 理论上这行代码到不了,为了保持函数完整性而保留
|
return {} as WebUiConfigType; // 理论上这行代码到不了,为了保持函数完整性而保留
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { Router } from 'express';
|
import { Router } from 'express';
|
||||||
import { OB11GetConfigHandler,OB11SetConfigHandler } from '../api/OB11Config';
|
import { OB11GetConfigHandler,OB11SetConfigHandler } from '../api/OB11Config';
|
||||||
const router = Router();
|
const router = Router();
|
||||||
router.post('/GetConfig', OB11GetConfigHandler)
|
router.post('/GetConfig', OB11GetConfigHandler);
|
||||||
router.post('/SetConfig', OB11SetConfigHandler);
|
router.post('/SetConfig', OB11SetConfigHandler);
|
||||||
export { router as OB11ConfigRouter };
|
export { router as OB11ConfigRouter };
|
@ -1,7 +1,7 @@
|
|||||||
import { Router } from 'express';
|
import { Router } from 'express';
|
||||||
import { QQCheckLoginStatusHandler, QQGetQRcodeHandler, QQGetQuickLoginListHandler, QQSetQuickLoginHandler } from '../api/QQLogin';
|
import { QQCheckLoginStatusHandler, QQGetQRcodeHandler, QQGetQuickLoginListHandler, QQSetQuickLoginHandler } from '../api/QQLogin';
|
||||||
const router = Router();
|
const router = Router();
|
||||||
router.all('/GetQuickLoginList', QQGetQuickLoginListHandler)
|
router.all('/GetQuickLoginList', QQGetQuickLoginListHandler);
|
||||||
router.post('/CheckLoginStatus', QQCheckLoginStatusHandler);
|
router.post('/CheckLoginStatus', QQCheckLoginStatusHandler);
|
||||||
router.post('/GetQQLoginQrcode', QQGetQRcodeHandler);
|
router.post('/GetQQLoginQrcode', QQGetQRcodeHandler);
|
||||||
router.post('/SetQuickLogin', QQSetQuickLoginHandler);
|
router.post('/SetQuickLogin', QQSetQuickLoginHandler);
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { Router } from "express";
|
import { Router } from 'express';
|
||||||
import { AuthHelper } from '../../src/helper/SignToken';
|
import { AuthHelper } from '../../src/helper/SignToken';
|
||||||
import { NextFunction, Request, Response } from 'express';
|
import { NextFunction, Request, Response } from 'express';
|
||||||
import { QQLoginRouter } from "./QQLogin";
|
import { QQLoginRouter } from './QQLogin';
|
||||||
import { AuthRouter } from "./auth";
|
import { AuthRouter } from './auth';
|
||||||
import { OB11ConfigRouter } from "./OB11Config";
|
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 如果是跳过鉴权
|
||||||
@ -13,7 +13,7 @@ export async function AuthApi(req: Request, res: Response, next: NextFunction) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (req.headers?.authorization) {
|
if (req.headers?.authorization) {
|
||||||
let authorization = req.headers.authorization.split(' ');
|
const authorization = req.headers.authorization.split(' ');
|
||||||
if (authorization.length < 2) {
|
if (authorization.length < 2) {
|
||||||
res.json({
|
res.json({
|
||||||
code: -1,
|
code: -1,
|
||||||
@ -21,7 +21,7 @@ export async function AuthApi(req: Request, res: Response, next: NextFunction) {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let token = authorization[1];
|
const token = authorization[1];
|
||||||
let Credential: any;
|
let Credential: any;
|
||||||
try {
|
try {
|
||||||
Credential = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
|
Credential = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
|
||||||
@ -32,8 +32,8 @@ export async function AuthApi(req: Request, res: Response, next: NextFunction) {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let config = await WebUiConfig.GetWebUIConfig();
|
const config = await WebUiConfig.GetWebUIConfig();
|
||||||
let credentialJson = await AuthHelper.validateCredentialWithinOneHour(config.token, Credential);
|
const credentialJson = await AuthHelper.validateCredentialWithinOneHour(config.token, Credential);
|
||||||
if (credentialJson) {
|
if (credentialJson) {
|
||||||
//通过验证
|
//通过验证
|
||||||
next();
|
next();
|
||||||
@ -53,7 +53,7 @@ export async function AuthApi(req: Request, res: Response, next: NextFunction) {
|
|||||||
return;
|
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',
|
||||||
@ -62,4 +62,4 @@ router.all("/test", (req, res) => {
|
|||||||
router.use('/auth', AuthRouter);
|
router.use('/auth', AuthRouter);
|
||||||
router.use('/QQLogin', QQLoginRouter);
|
router.use('/QQLogin', QQLoginRouter);
|
||||||
router.use('/OB11Config', OB11ConfigRouter);
|
router.use('/OB11Config', OB11ConfigRouter);
|
||||||
export { router as ALLRouter }
|
export { router as ALLRouter };
|
@ -1,15 +1,15 @@
|
|||||||
import { SettingList } from "./components/SettingList";
|
import { SettingList } from './components/SettingList';
|
||||||
import { SettingItem } from "./components/SettingItem";
|
import { SettingItem } from './components/SettingItem';
|
||||||
import { SettingButton } from "./components/SettingButton";
|
import { SettingButton } from './components/SettingButton';
|
||||||
import { SettingSwitch } from "./components/SettingSwitch";
|
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);
|
||||||
let 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) {
|
||||||
@ -21,7 +21,7 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
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>`,
|
||||||
@ -29,39 +29,39 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
SettingItem(
|
SettingItem(
|
||||||
'<span id="napcat-update-title">Napcat</span>',
|
'<span id="napcat-update-title">Napcat</span>',
|
||||||
undefined,
|
undefined,
|
||||||
SettingButton("V1.4.0", "napcat-update-button", "secondary")
|
SettingButton('V1.4.0', '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>
|
||||||
@ -81,27 +81,27 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
<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>
|
||||||
@ -112,81 +112,81 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
<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,
|
||||||
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://napneko.github.io/", "_blank");
|
window.open('https://napneko.github.io/', '_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://github.com/NapNeko/NapCatQQ");
|
window.open('https://github.com/NapNeko/NapCatQQ');
|
||||||
});
|
});
|
||||||
// 生成反向地址列表
|
// 生成反向地址列表
|
||||||
const buildHostListItem = (
|
const buildHostListItem = (
|
||||||
@ -196,29 +196,29 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
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);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -245,7 +245,7 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
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`
|
||||||
@ -253,22 +253,22 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
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);
|
||||||
@ -276,51 +276,51 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
initReverseHost("http.postUrls", doc);
|
initReverseHost('http.postUrls', doc);
|
||||||
initReverseHost("reverseWs.urls", doc);
|
initReverseHost('reverseWs.urls', doc);
|
||||||
|
|
||||||
doc
|
doc
|
||||||
.querySelector("#config-ob11-http-postUrls-add")
|
.querySelector('#config-ob11-http-postUrls-add')
|
||||||
?.addEventListener("click", () =>
|
?.addEventListener('click', () =>
|
||||||
addReverseHost("http.postUrls", document, {
|
addReverseHost('http.postUrls', document, {
|
||||||
placeholder: "如:http://127.0.0.1:5140/onebot",
|
placeholder: '如:http://127.0.0.1:5140/onebot',
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
doc
|
doc
|
||||||
.querySelector("#config-ob11-reverseWs-urls-add")
|
.querySelector('#config-ob11-reverseWs-urls-add')
|
||||||
?.addEventListener("click", () =>
|
?.addEventListener('click', () =>
|
||||||
addReverseHost("reverseWs.urls", document, {
|
addReverseHost('reverseWs.urls', document, {
|
||||||
placeholder: "如:ws://127.0.0.1:5140/onebot",
|
placeholder: '如:ws://127.0.0.1:5140/onebot',
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
doc.querySelector("#config-ffmpeg-select")?.addEventListener("click", () => {
|
doc.querySelector('#config-ffmpeg-select')?.addEventListener('click', () => {
|
||||||
//选择ffmpeg
|
//选择ffmpeg
|
||||||
});
|
});
|
||||||
|
|
||||||
doc.querySelector("#config-open-log-path")?.addEventListener("click", () => {
|
doc.querySelector('#config-open-log-path')?.addEventListener('click', () => {
|
||||||
//打开日志
|
//打开日志
|
||||||
});
|
});
|
||||||
|
|
||||||
// 开关
|
// 开关
|
||||||
doc
|
doc
|
||||||
.querySelectorAll("setting-switch[data-config-key]")
|
.querySelectorAll('setting-switch[data-config-key]')
|
||||||
.forEach((dom: Element) => {
|
.forEach((dom: Element) => {
|
||||||
dom.addEventListener("click", () => {
|
dom.addEventListener('click', () => {
|
||||||
const active = dom.getAttribute("is-active") == undefined;
|
const active = dom.getAttribute('is-active') == undefined;
|
||||||
//@ts-ignore 扩展
|
//@ts-expect-error 等待修复
|
||||||
setOB11Config(dom.dataset.configKey, active);
|
setOB11Config(dom.dataset.configKey, active);
|
||||||
if (active) dom.setAttribute("is-active", "");
|
if (active) dom.setAttribute('is-active', '');
|
||||||
else dom.removeAttribute("is-active");
|
else dom.removeAttribute('is-active');
|
||||||
//@ts-ignore 等待修复
|
//@ts-expect-error 等待修复
|
||||||
if (!isEmpty(dom.dataset.controlDisplayId)) {
|
if (!isEmpty(dom.dataset.controlDisplayId)) {
|
||||||
const displayDom = document.querySelector(
|
const displayDom = document.querySelector(
|
||||||
//@ts-ignore 等待修复
|
//@ts-expect-error 等待修复
|
||||||
`#${dom.dataset.controlDisplayId}`
|
`#${dom.dataset.controlDisplayId}`
|
||||||
);
|
);
|
||||||
if (active) displayDom?.removeAttribute("is-hidden");
|
if (active) displayDom?.removeAttribute('is-hidden');
|
||||||
else displayDom?.setAttribute("is-hidden", "");
|
else displayDom?.setAttribute('is-hidden', '');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -328,15 +328,15 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
// 输入框
|
// 输入框
|
||||||
doc
|
doc
|
||||||
.querySelectorAll(
|
.querySelectorAll(
|
||||||
"setting-item .q-input input.q-input__inner[data-config-key]"
|
'setting-item .q-input input.q-input__inner[data-config-key]'
|
||||||
)
|
)
|
||||||
.forEach((dom: Element) => {
|
.forEach((dom: Element) => {
|
||||||
dom.addEventListener("input", () => {
|
dom.addEventListener('input', () => {
|
||||||
const Type = dom.getAttribute("type");
|
const Type = dom.getAttribute('type');
|
||||||
//@ts-ignore 等待修复
|
//@ts-expect-error等待修复
|
||||||
const configKey = dom.dataset.configKey;
|
const configKey = dom.dataset.configKey;
|
||||||
const configValue =
|
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
|
||||||
@ -348,11 +348,11 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
|
|
||||||
// 下拉框
|
// 下拉框
|
||||||
doc
|
doc
|
||||||
.querySelectorAll("ob-setting-select[data-config-key]")
|
.querySelectorAll('ob-setting-select[data-config-key]')
|
||||||
.forEach((dom: Element) => {
|
.forEach((dom: Element) => {
|
||||||
//@ts-ignore 等待修复
|
//@ts-expect-error等待修复
|
||||||
dom?.addEventListener("selected", (e: CustomEvent) => {
|
dom?.addEventListener('selected', (e: CustomEvent) => {
|
||||||
//@ts-ignore 等待修复
|
//@ts-expect-error等待修复
|
||||||
const configKey = dom.dataset.configKey;
|
const configKey = dom.dataset.configKey;
|
||||||
const configValue = e.detail.value;
|
const configValue = e.detail.value;
|
||||||
setOB11Config(configKey, configValue);
|
setOB11Config(configKey, configValue);
|
||||||
@ -360,9 +360,9 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 保存按钮
|
// 保存按钮
|
||||||
doc.querySelector("#config-ob11-save")?.addEventListener("click", () => {
|
doc.querySelector('#config-ob11-save')?.addEventListener('click', () => {
|
||||||
OB11ConfigWrapper.SetOB11Config(ob11Config);
|
OB11ConfigWrapper.SetOB11Config(ob11Config);
|
||||||
alert("保存成功");
|
alert('保存成功');
|
||||||
});
|
});
|
||||||
doc.body.childNodes.forEach((node) => {
|
doc.body.childNodes.forEach((node) => {
|
||||||
view.appendChild(node);
|
view.appendChild(node);
|
||||||
|
@ -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>`;
|
||||||
}
|
};
|
@ -11,5 +11,5 @@ export const SettingItem = (
|
|||||||
${subtitle ? `<setting-text data-type="secondary">${subtitle}</setting-text>` : ''}
|
${subtitle ? `<setting-text data-type="secondary">${subtitle}</setting-text>` : ''}
|
||||||
</div>
|
</div>
|
||||||
${action ? `<div>${action}</div>` : ''}
|
${action ? `<div>${action}</div>` : ''}
|
||||||
</setting-item>`
|
</setting-item>`;
|
||||||
}
|
};
|
@ -10,5 +10,5 @@ export const SettingList = (
|
|||||||
${items.join('')}
|
${items.join('')}
|
||||||
</setting-list>
|
</setting-list>
|
||||||
</setting-panel>
|
</setting-panel>
|
||||||
</setting-section>`
|
</setting-section>`;
|
||||||
}
|
};
|
@ -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>`;
|
||||||
}
|
};
|
@ -1,11 +1,11 @@
|
|||||||
import { SettingOption } from './SettingOption'
|
import { SettingOption } from './SettingOption';
|
||||||
|
|
||||||
interface MouseEventExtend extends MouseEvent {
|
interface MouseEventExtend extends MouseEvent {
|
||||||
target: HTMLElement
|
target: HTMLElement
|
||||||
}
|
}
|
||||||
|
|
||||||
// <ob-setting-select>
|
// <ob-setting-select>
|
||||||
const SelectTemplate = document.createElement('template')
|
const SelectTemplate = document.createElement('template');
|
||||||
SelectTemplate.innerHTML = `<style>
|
SelectTemplate.innerHTML = `<style>
|
||||||
.hidden { display: none !important; }
|
.hidden { display: none !important; }
|
||||||
</style>
|
</style>
|
||||||
@ -17,19 +17,19 @@ SelectTemplate.innerHTML = `<style>
|
|||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<ul class="hidden" part="option-list"><slot></slot></ul>
|
<ul class="hidden" part="option-list"><slot></slot></ul>
|
||||||
</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"]');
|
||||||
@ -39,21 +39,21 @@ window.customElements.define(
|
|||||||
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(
|
||||||
@ -65,20 +65,20 @@ window.customElements.define(
|
|||||||
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>`;
|
||||||
}
|
};
|
@ -4,5 +4,5 @@ export const SettingSwitch = (configKey?: string, isActive: boolean = false, ext
|
|||||||
${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]}"`) : ''}
|
||||||
>
|
>
|
||||||
</setting-switch>`
|
</setting-switch>`;
|
||||||
}
|
};
|
@ -2,16 +2,16 @@ export interface OB11Config {
|
|||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
http: {
|
http: {
|
||||||
enable: boolean;
|
enable: boolean;
|
||||||
host: "";
|
host: '';
|
||||||
port: number;
|
port: number;
|
||||||
secret: "";
|
secret: '';
|
||||||
enableHeart: boolean;
|
enableHeart: boolean;
|
||||||
enablePost: boolean;
|
enablePost: boolean;
|
||||||
postUrls: string[];
|
postUrls: string[];
|
||||||
};
|
};
|
||||||
ws: {
|
ws: {
|
||||||
enable: boolean;
|
enable: boolean;
|
||||||
host: "";
|
host: '';
|
||||||
port: number;
|
port: number;
|
||||||
};
|
};
|
||||||
reverseWs: {
|
reverseWs: {
|
||||||
@ -21,45 +21,45 @@ export interface OB11Config {
|
|||||||
|
|
||||||
debug: boolean;
|
debug: boolean;
|
||||||
heartInterval: number;
|
heartInterval: number;
|
||||||
messagePostFormat: "array" | "string";
|
messagePostFormat: 'array' | 'string';
|
||||||
enableLocalFile2Url: boolean;
|
enableLocalFile2Url: boolean;
|
||||||
musicSignUrl: "";
|
musicSignUrl: '';
|
||||||
reportSelfMessage: boolean;
|
reportSelfMessage: boolean;
|
||||||
token: "";
|
token: '';
|
||||||
}
|
}
|
||||||
|
|
||||||
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> {
|
async GetOB11Config(): Promise<OB11Config> {
|
||||||
let ConfigResponse = await fetch("/api/OB11Config/GetConfig", {
|
const ConfigResponse = await fetch('/api/OB11Config/GetConfig', {
|
||||||
method: "POST",
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: "Bearer " + this.retCredential,
|
Authorization: 'Bearer ' + this.retCredential,
|
||||||
"Content-Type": "application/json",
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (ConfigResponse.status == 200) {
|
if (ConfigResponse.status == 200) {
|
||||||
let ConfigResponseJson = await ConfigResponse.json();
|
const ConfigResponseJson = await ConfigResponse.json();
|
||||||
if (ConfigResponseJson.code == 0) {
|
if (ConfigResponseJson.code == 0) {
|
||||||
return ConfigResponseJson?.data;
|
return ConfigResponseJson?.data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {} as OB11Config;
|
return {} as OB11Config;
|
||||||
}
|
}
|
||||||
async SetOB11Config(config: OB11Config): Promise<Boolean> {
|
async SetOB11Config(config: OB11Config): Promise<boolean> {
|
||||||
let ConfigResponse = await fetch("/api/OB11Config/SetConfig", {
|
const ConfigResponse = await fetch('/api/OB11Config/SetConfig', {
|
||||||
method: "POST",
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: "Bearer " + this.retCredential,
|
Authorization: 'Bearer ' + this.retCredential,
|
||||||
"Content-Type": "application/json",
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ config: JSON.stringify(config) }),
|
body: JSON.stringify({ config: JSON.stringify(config) }),
|
||||||
});
|
});
|
||||||
if (ConfigResponse.status == 200) {
|
if (ConfigResponse.status == 200) {
|
||||||
let ConfigResponseJson = await ConfigResponse.json();
|
const ConfigResponseJson = await ConfigResponse.json();
|
||||||
if (ConfigResponseJson.code == 0) {
|
if (ConfigResponseJson.code == 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { defineConfig } from 'vite'
|
import { defineConfig } from 'vite';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
build:{
|
build:{
|
||||||
|
@ -9,7 +9,7 @@ import { builtinModules } from 'module';
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
|
|
||||||
const external = ['silk-wasm', 'ws', 'express', 'uuid', 'fluent-ffmpeg', 'sqlite3', 'log4js',
|
const external = ['silk-wasm', 'ws', 'express', 'uuid', 'fluent-ffmpeg', 'sqlite3', 'log4js',
|
||||||
'qrcode-terminal', 'MoeHoo', 'frida'];
|
'qrcode-terminal'];
|
||||||
|
|
||||||
const nodeModules = [...builtinModules, builtinModules.map(m => `node:${m}`)].flat();
|
const nodeModules = [...builtinModules, builtinModules.map(m => `node:${m}`)].flat();
|
||||||
// let nodeModules = ["fs", "path", "events", "buffer", "url", "crypto", "fs/promise", "fsPromise", "os", "http", "net"]
|
// let nodeModules = ["fs", "path", "events", "buffer", "url", "crypto", "fs/promise", "fsPromise", "os", "http", "net"]
|
||||||
|
Loading…
x
Reference in New Issue
Block a user