feat: Websocket Server

feat: change port not need restart
This commit is contained in:
linyuchen 2024-02-16 00:47:04 +08:00
parent a7d75f84cb
commit ef4443d080
9 changed files with 195 additions and 98 deletions

View File

@ -4,7 +4,7 @@
"name": "LLOneBot", "name": "LLOneBot",
"slug": "LLOneBot", "slug": "LLOneBot",
"description": "LiteLoaderQQNT的OneBotApi", "description": "LiteLoaderQQNT的OneBotApi",
"version": "3.0.8", "version": "3.1.0",
"thumbnail": "./icon.png", "thumbnail": "./icon.png",
"authors": [{ "authors": [{
"name": "linyuchen", "name": "linyuchen",

34
package-lock.json generated
View File

@ -18,11 +18,13 @@
"@babel/preset-env": "^7.23.2", "@babel/preset-env": "^7.23.2",
"@types/express": "^4.17.20", "@types/express": "^4.17.20",
"@types/uuid": "^9.0.8", "@types/uuid": "^9.0.8",
"@types/ws": "^8.5.10",
"babel-loader": "^9.1.3", "babel-loader": "^9.1.3",
"ts-loader": "^9.5.0", "ts-loader": "^9.5.0",
"typescript": "^5.2.2", "typescript": "^5.2.2",
"webpack": "^5.89.0", "webpack": "^5.89.0",
"webpack-cli": "^5.1.4" "webpack-cli": "^5.1.4",
"ws": "^8.16.0"
} }
}, },
"node_modules/@ampproject/remapping": { "node_modules/@ampproject/remapping": {
@ -2199,6 +2201,15 @@
"integrity": "sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==", "integrity": "sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==",
"dev": true "dev": true
}, },
"node_modules/@types/ws": {
"version": "8.5.10",
"resolved": "https://mirrors.cloud.tencent.com/npm/@types/ws/-/ws-8.5.10.tgz",
"integrity": "sha512-vmQSUcfalpIq0R9q7uTo2lXs6eGIpt9wtnLdMv9LVpIjCA/+ufZRozlVoVelIYixx1ugCBKDhn89vnsEGOCx9A==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@webassemblyjs/ast": { "node_modules/@webassemblyjs/ast": {
"version": "1.11.6", "version": "1.11.6",
"resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz",
@ -4691,6 +4702,27 @@
"integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==", "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==",
"dev": true "dev": true
}, },
"node_modules/ws": {
"version": "8.16.0",
"resolved": "https://mirrors.cloud.tencent.com/npm/ws/-/ws-8.16.0.tgz",
"integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==",
"dev": true,
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/yallist": { "node_modules/yallist": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",

View File

@ -26,10 +26,12 @@
"@babel/preset-env": "^7.23.2", "@babel/preset-env": "^7.23.2",
"@types/express": "^4.17.20", "@types/express": "^4.17.20",
"@types/uuid": "^9.0.8", "@types/uuid": "^9.0.8",
"@types/ws": "^8.5.10",
"babel-loader": "^9.1.3", "babel-loader": "^9.1.3",
"ts-loader": "^9.5.0", "ts-loader": "^9.5.0",
"typescript": "^5.2.2", "typescript": "^5.2.2",
"webpack": "^5.89.0", "webpack": "^5.89.0",
"webpack-cli": "^5.1.4" "webpack-cli": "^5.1.4",
"ws": "^8.16.0"
} }
} }

View File

@ -11,13 +11,16 @@ export class ConfigUtil{
getConfig(): Config { getConfig(): Config {
if (!fs.existsSync(this.configPath)) { if (!fs.existsSync(this.configPath)) {
return {port:3000, hosts: ["http://192.168.1.2:5000/"]} return {port: 3000, hosts: ["http://192.168.1.2:5000/"], wsPort: 3001}
} else { } else {
const data = fs.readFileSync(this.configPath, "utf-8"); const data = fs.readFileSync(this.configPath, "utf-8");
let jsonData = JSON.parse(data); let jsonData = JSON.parse(data);
if (!jsonData.hosts) { if (!jsonData.hosts) {
jsonData.hosts = [] jsonData.hosts = []
} }
if (!jsonData.wsPort){
jsonData.wsPort = 3001
}
return jsonData; return jsonData;
} }
} }

View File

@ -1,5 +1,6 @@
export interface Config { export interface Config {
port: number port: number
wsPort: number
hosts: string[] hosts: string[]
enableBase64?: boolean enableBase64?: boolean
debug?: boolean debug?: boolean

View File

@ -10,7 +10,7 @@ import {
CHANNEL_LOG, CHANNEL_LOG,
CHANNEL_SET_CONFIG, CHANNEL_SET_CONFIG,
} from "../common/channels"; } from "../common/channels";
import { postMsg, startExpress } from "../onebot11/server"; import { postMsg, startHTTPServer, startWSServer } from "../onebot11/server";
import { CONFIG_DIR, getConfigUtil, log } from "../common/utils"; import { CONFIG_DIR, getConfigUtil, log } from "../common/utils";
import { addHistoryMsg, msgHistory, selfInfo } from "../common/data"; import { addHistoryMsg, msgHistory, selfInfo } from "../common/data";
import { hookNTQQApiReceive, ReceiveCmd, registerReceiveHook } from "../ntqqapi/hook"; import { hookNTQQApiReceive, ReceiveCmd, registerReceiveHook } from "../ntqqapi/hook";
@ -37,7 +37,14 @@ function onLoad() {
return getConfigUtil().getConfig() return getConfigUtil().getConfig()
}) })
ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => { ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => {
let oldConfig = getConfigUtil().getConfig();
getConfigUtil().setConfig(arg) getConfigUtil().setConfig(arg)
if (arg.port != oldConfig.port){
startHTTPServer(arg.port)
}
if (arg.wsPort != oldConfig.wsPort){
startWSServer(arg.wsPort)
}
}) })
ipcMain.on(CHANNEL_LOG, (event: any, arg: any) => { ipcMain.on(CHANNEL_LOG, (event: any, arg: any) => {
@ -67,7 +74,6 @@ function onLoad() {
function start() { function start() {
log("llonebot start")
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => { registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
try { try {
// log("received msg length", payload.msgList.length); // log("received msg length", payload.msgList.length);
@ -90,7 +96,10 @@ function onLoad() {
} }
}) })
NTQQApi.getGroups(true).then() NTQQApi.getGroups(true).then()
startExpress(getConfigUtil().getConfig().port) const config = getConfigUtil().getConfig()
startHTTPServer(config.port)
startWSServer(config.wsPort)
log("LLOneBot start")
} }
const init = async () => { const init = async () => {
@ -130,7 +139,7 @@ function onBrowserWindowCreated(window: BrowserWindow) {
try { try {
hookNTQQApiReceive(window); hookNTQQApiReceive(window);
} catch (e) { } catch (e) {
log("llonebot hook error: ", e.toString()) log("LLOneBot hook error: ", e.toString())
} }
} }

View File

@ -1,72 +1,21 @@
import { getConfigUtil, log } from "../common/utils"; import * as http from "http";
import * as websocket from "ws";
const express = require("express"); import express from "express";
import { Request } from 'express'; import { Request } from 'express';
import { Response } from 'express'; import { Response } from 'express';
import { getConfigUtil, log } from "../common/utils";
const JSONbig = require('json-bigint')({ storeAsString: true });
import { selfInfo } from "../common/data"; import { selfInfo } from "../common/data";
import { OB11Message, OB11Return, OB11MessageData } from './types'; import { OB11Message, OB11Return, OB11MessageData } from './types';
import { actionHandlers } from "./actions"; import { actionHandlers } from "./actions";
import { OB11Response } from "./actions/utils";
import { ActionName } from "./actions/types";
import BaseAction from "./actions/BaseAction";
let wsServer: websocket.Server = null;
// @SiberianHusky 2021-08-15 const JSONbig = require('json-bigint')({storeAsString: true});
function checkSendMessage(sendMsgList: OB11MessageData[]) {
function checkUri(uri: string): boolean {
const pattern = /^(file:\/\/|http:\/\/|https:\/\/|base64:\/\/)/;
return pattern.test(uri);
}
for (let msg of sendMsgList) {
if (msg["type"] && msg["data"]) {
let type = msg["type"];
let data = msg["data"];
if (type === "text" && !data["text"]) {
return 400;
} else if (["image", "voice", "record"].includes(type)) {
if (!data["file"]) {
return 400;
} else {
if (checkUri(data["file"])) {
return 200;
} else {
return 400;
}
}
} else if (type === "at" && !data["qq"]) {
return 400;
} else if (type === "reply" && !data["id"]) {
return 400;
}
} else {
return 400
}
}
return 200;
}
// ==end==
class OB11Response {
static res<T>(data: T, status: number = 0, message: string = ""): OB11Return<T> {
return {
status: status,
retcode: status,
data: data,
message: message
}
}
static ok<T>(data: T) {
return OB11Response.res<T>(data)
}
static error(err: string) {
return OB11Response.res(null, -1, err)
}
}
const expressAPP = express(); const expressAPP = express();
let httpServer: http.Server = null;
expressAPP.use(express.urlencoded({extended: true, limit: "500mb"})); expressAPP.use(express.urlencoded({extended: true, limit: "500mb"}));
expressAPP.use((req, res, next) => { expressAPP.use((req, res, next) => {
@ -86,24 +35,76 @@ expressAPP.use((req, res, next) => {
next(); next();
}); });
}); });
// expressAPP.use(express.json({
// limit: '500mb',
// verify: (req: any, res: any, buf: any, encoding: any) => {
// req.rawBody = buf;
// }
// }));
export function startExpress(port: number) {
export function startHTTPServer(port: number) {
if (httpServer) {
httpServer.close();
}
expressAPP.get('/', (req: Request, res: Response) => { expressAPP.get('/', (req: Request, res: Response) => {
res.send('llonebot已启动'); res.send('LLOneBot已启动');
}) })
expressAPP.listen(port, "0.0.0.0", () => { httpServer = expressAPP.listen(port, "0.0.0.0", () => {
console.log(`llonebot started 0.0.0.0:${port}`); console.log(`LLOneBot http server started 0.0.0.0:${port}`);
}); });
} }
let wsEventClients: websocket.WebSocket[] = [];
type RouterHandler = (payload: any) => Promise<OB11Return<any>>
let routers: Record<string, RouterHandler> = {};
function wsReply(wsClient: websocket.WebSocket, data: OB11Return<any> | OB11Message) {
try {
wsClient.send(JSON.stringify(data))
} catch (e) {
log("websocket 回复失败", e)
}
}
export function startWSServer(port: number) {
if (wsServer) {
wsServer.close((err)=>{
log("ws server close failed!", err)
})
}
wsServer = new websocket.Server({port})
wsServer.on("connection", (ws, req) => {
const url = req.url;
ws.send('Welcome to the LLOneBot WebSocket server! url:' + url);
if (url == "/api" || url == "/api/") {
ws.on("message", async (msg) => {
let receiveData: { action: ActionName, params: any } = {action: null, params: {}}
log("收到ws消息", msg.toString())
try {
receiveData = JSON.parse(msg.toString())
} catch (e) {
return wsReply(ws, OB11Response.error("json解析失败请检查数据格式"))
}
const handle: RouterHandler | undefined = routers[receiveData.action]
if (!handle) {
return wsReply(ws, OB11Response.error("不支持的api " + receiveData.action))
}
try {
const handleResult = await handle(receiveData.params)
wsReply(ws, handleResult)
} catch (e) {
wsReply(ws, OB11Response.error(`api处理出错:${e}`))
}
})
} else if (url == "/event" || url == "/event/") {
log("event上报ws客户端已连接")
wsEventClients.push(ws)
ws.on("close", () => {
log("event上报ws客户端已断开")
wsEventClients = wsEventClients.filter((c) => c != ws)
})
}
})
}
export function postMsg(msg: OB11Message) { export function postMsg(msg: OB11Message) {
const {reportSelfMessage} = getConfigUtil().getConfig() const {reportSelfMessage} = getConfigUtil().getConfig()
@ -121,27 +122,32 @@ export function postMsg(msg: OB11Message) {
}, },
body: JSON.stringify(msg) body: JSON.stringify(msg)
}).then((res: any) => { }).then((res: any) => {
log(`新消息事件上报成功: ${host} ` + JSON.stringify(msg)); log(`新消息事件HTTP上报成功: ${host} ` + JSON.stringify(msg));
}, (err: any) => { }, (err: any) => {
log(`新消息事件上报失败: ${host} ` + err + JSON.stringify(msg)); log(`新消息事件HTTP上报失败: ${host} ` + err + JSON.stringify(msg));
}); });
} }
for (const wsClient of wsEventClients) {
log("新消息事件ws上报", msg)
new Promise((resolve, reject) => {
wsReply(wsClient, msg);
}).then();
}
} }
let routers: Record<string, (payload: any) => Promise<OB11Return<any>>> = {};
function registerRouter(action: string, handle: (payload: any) => Promise<any>) { function registerRouter(action: string, handle: (payload: any) => Promise<any>) {
let url = action.toString() let url = action.toString()
if (!action.startsWith("/")) { if (!action.startsWith("/")) {
url = "/" + action url = "/" + action
} }
async function _handle(res: Response, payload: any) { async function _handle(res: Response, payload: any) {
log("receive post data", url, payload) log("receive post data", url, payload)
try { try {
const result = await handle(payload) const result = await handle(payload)
res.send(result) res.send(result)
} } catch (e) {
catch (e) {
log(e.stack); log(e.stack);
res.send(OB11Response.error(e.stack.toString())) res.send(OB11Response.error(e.stack.toString()))
} }
@ -153,7 +159,7 @@ function registerRouter(action: string, handle: (payload: any) => Promise<any>)
expressAPP.get(url, (req: Request, res: Response) => { expressAPP.get(url, (req: Request, res: Response) => {
_handle(res, req.query as any).then() _handle(res, req.query as any).then()
}); });
routers[url] = handle routers[action] = handle
} }
for (const action of actionHandlers) { for (const action of actionHandlers) {

View File

@ -1,6 +1,7 @@
import { CONFIG_DIR, isGIF } from "../common/utils"; import { CONFIG_DIR, isGIF } from "../common/utils";
import * as path from 'path'; import * as path from 'path';
import { NTQQApi } from '../ntqqapi/ntcall'; import { NTQQApi } from '../ntqqapi/ntcall';
import { OB11MessageData } from "./types";
const fs = require("fs").promises; const fs = require("fs").promises;
export async function uri2local(fileName: string, uri: string){ export async function uri2local(fileName: string, uri: string){
@ -60,3 +61,39 @@ export async function uri2local(fileName: string, uri: string){
res.path = filePath res.path = filePath
return res return res
} }
function checkSendMessage(sendMsgList: OB11MessageData[]) {
function checkUri(uri: string): boolean {
const pattern = /^(file:\/\/|http:\/\/|https:\/\/|base64:\/\/)/;
return pattern.test(uri);
}
for (let msg of sendMsgList) {
if (msg["type"] && msg["data"]) {
let type = msg["type"];
let data = msg["data"];
if (type === "text" && !data["text"]) {
return 400;
} else if (["image", "voice", "record"].includes(type)) {
if (!data["file"]) {
return 400;
} else {
if (checkUri(data["file"])) {
return 200;
} else {
return 400;
}
}
} else if (type === "at" && !data["qq"]) {
return 400;
} else if (type === "reply" && !data["id"]) {
return 400;
}
} else {
return 400
}
}
return 200;
}

View File

@ -29,16 +29,20 @@ async function onSettingWindowCreated(view: Element) {
<setting-panel> <setting-panel>
<setting-list class="wrap"> <setting-list class="wrap">
<setting-item class="vertical-list-item" data-direction="row"> <setting-item class="vertical-list-item" data-direction="row">
<setting-text></setting-text> <setting-text>HTTP监听端</setting-text>
<input id="port" type="number" value="${config.port}"/> <input id="port" type="number" value="${config.port}"/>
</setting-item> </setting-item>
<setting-item class="vertical-list-item" data-direction="row">
<setting-text>ws监听端口</setting-text>
<input id="wsPort" type="number" value="${config.wsPort}"/>
</setting-item>
<div> <div>
<button id="addHost" class="q-button"></button> <button id="addHost" class="q-button">HTTP上报地</button>
</div> </div>
<div id="hostItems"> <div id="hostItems">
${hostsEleStr} ${hostsEleStr}
</div> </div>
<button id="save" class="q-button">(QQ后生效)</button> <button id="save" class="q-button"></button>
</setting-list> </setting-list>
</setting-panel> </setting-panel>
<setting-panel> <setting-panel>
@ -124,11 +128,13 @@ async function onSettingWindowCreated(view: Element) {
doc.getElementById("save")?.addEventListener("click", doc.getElementById("save")?.addEventListener("click",
() => { () => {
const portEle: HTMLInputElement = document.getElementById("port") as HTMLInputElement const portEle: HTMLInputElement = document.getElementById("port") as HTMLInputElement
const wsPortEle: HTMLInputElement = document.getElementById("wsPort") as HTMLInputElement
const hostEles: HTMLCollectionOf<HTMLInputElement> = document.getElementsByClassName("host") as HTMLCollectionOf<HTMLInputElement>; const hostEles: HTMLCollectionOf<HTMLInputElement> = document.getElementsByClassName("host") as HTMLCollectionOf<HTMLInputElement>;
// const port = doc.querySelector("input[type=number]")?.value // const port = doc.querySelector("input[type=number]")?.value
// const host = doc.querySelector("input[type=text]")?.value // const host = doc.querySelector("input[type=text]")?.value
// 获取端口和host // 获取端口和host
const port = portEle.value const port = portEle.value
const wsPort = wsPortEle.value
let hosts: string[] = []; let hosts: string[] = [];
for (const hostEle of hostEles) { for (const hostEle of hostEles) {
if (hostEle.value) { if (hostEle.value) {
@ -136,6 +142,7 @@ async function onSettingWindowCreated(view: Element) {
} }
} }
config.port = parseInt(port); config.port = parseInt(port);
config.wsPort = parseInt(wsPort);
config.hosts = hosts; config.hosts = hosts;
window.llonebot.setConfig(config); window.llonebot.setConfig(config);
alert("保存成功"); alert("保存成功");