Skip to content

Commit

Permalink
fix: 多次调用登录
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-cn committed Apr 12, 2024
1 parent b27dff9 commit 855845b
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 57 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"scripts": {
"start": "node .",
"build": "vite build && tsc --project tsconfig.json && tsc-alias -p tsconfig.json && cp -r src/config.sample.yaml lib/config.sample.yaml",
"dev": "ts-node -r tsconfig-paths/register ./src/bin.ts -c config.yaml -r qq -r icqq -r dingtalk -r wechat",
"dev": "ts-node-dev -r tsconfig-paths/register ./src/bin.ts -c config.yaml -r qq -r icqq -r dingtalk -r wechat",
"pub": "npm publish --access public",
"lint": "prettier --check ./**/*.{ts,js}",
"lint:fix": "prettier --write ./**/*.{ts,js,md}",
Expand Down
1 change: 0 additions & 1 deletion src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ export abstract class Adapter<T extends string = string, Sendable = any> extends
return uin ? oneBot.uin === uin : true;
});
for (const oneBot of startOneBots) {
await this.setOnline(oneBot.uin);
await oneBot.start();
}
this.app.emit("adapter.start", this.platform);
Expand Down
10 changes: 5 additions & 5 deletions src/server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ export class App extends Koa {
init() {
this.logger = getLogger("[OneBots]");
this.logger.level = this.config.log_level;
this.router = new Router({ prefix: this.config.path });
this.httpServer = createServer(this.callback());
this.router = new Router(this.httpServer, { prefix: this.config.path });
this.use(KoaBodyParser())
.use(this.router.routes())
.use(this.router.allowedMethods())
Expand All @@ -95,8 +96,7 @@ export class App extends Koa {
})(ctx, next);
})
.use(koaStatic(path.resolve(__dirname, "../../dist")));
this.httpServer = createServer(this.callback());
this.ws = this.router.ws("/", this.httpServer);
this.ws = this.router.ws("/");

this.createOneBots();
}
Expand Down Expand Up @@ -187,10 +187,10 @@ export class App extends Koa {
});
};
fs.watch(App.logFile, fileListener);
this.on("close", () => {
this.once("close", () => {
fs.unwatchFile(App.logFile, fileListener);
});
process.on("disconnect", () => {
process.once("disconnect", () => {
fs.unwatchFile(App.logFile, fileListener);
});
this.ws.on("connection", async client => {
Expand Down
77 changes: 29 additions & 48 deletions src/server/router.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,40 @@
import KoaRouter from "@koa/router";
import { WebSocketServer, RawData } from "ws";
import http from "http";
import { parse } from "url";
import { Dict } from "@zhinjs/shared";
import { WebSocketServer, WebSocket, ServerOptions } from "ws";
import { IncomingMessage, Server } from "http";

export class WsServer extends WebSocketServer {
waiting_timeout: number = 1000 * 60 * 5;
async waitResult<T>(event: string, ...args: any[]) {
return new Promise<T>(resolve => {
const resolver = (result: T) => {
this.clients.forEach(client => client.off("message", listener));
clearTimeout(timer);
resolve(result);
};
const echo = Date.now().toString(36).slice(2);
let timer = setTimeout(() => {
resolver(null);
}, this.waiting_timeout);
const listener = (raw: RawData) => {
let data: Dict = null;
try {
data = JSON.parse(raw.toString());
} catch {}
if (!data) return;
if (data.echo === echo) resolver(data.result);
};
this.clients.forEach(client => {
client.on("message", listener);
client.send(
JSON.stringify({
event,
echo,
args,
}),
);
});
});
export class WsServer<
T extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket,
U extends typeof IncomingMessage = typeof IncomingMessage,
> extends WebSocketServer<T, U> {
constructor(options?: WsServer.Options<T, U>) {
super(options);
this.path = options.path;
}
}
export namespace WsServer {
export interface Options<
T extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket,
U extends typeof IncomingMessage = typeof IncomingMessage,
> extends ServerOptions<T, U> {
path: string;
}
}
export class Router extends KoaRouter {
wsStack: WsServer[] = [];

ws(path: string, server: http.Server) {
const wsServer = new WsServer({ noServer: true, path });
this.wsStack.push(wsServer);
constructor(server: Server, options?: KoaRouter.RouterOptions) {
super(options);
server.on("upgrade", (request, socket, head) => {
const { pathname } = parse(request.url);
if (this.wsStack.findIndex(wss => wss.options.path === path) === -1) {
socket.destroy();
} else if (pathname === path) {
wsServer.handleUpgrade(request, socket, head, function done(ws) {
wsServer.emit("connection", ws, request);
});
}
const { pathname } = new URL(request.url, `wss://localhost`);
const wsServer = this.wsStack.find(wss => wss.path === pathname);
if (!wsServer) socket.destroy();
wsServer.handleUpgrade(request, socket, head, function done(ws) {
wsServer.emit("connection", ws, request);
});
});
}
ws(path: string) {
const wsServer = new WsServer({ noServer: true, path });
this.wsStack.push(wsServer);
return wsServer;
}
}
2 changes: 1 addition & 1 deletion src/service/V11/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ export class V11 extends Service<"V11"> implements OneBot.Base {
}

private startWs() {
this.wss = this.oneBot.app.router.ws(this.path, this.oneBot.app.httpServer);
this.wss = this.oneBot.app.router.ws(this.path);
this.logger.mark(
`开启ws服务器成功,监听:ws://127.0.0.1:${this.oneBot.app.config.port}${this.path}`,
);
Expand Down
2 changes: 1 addition & 1 deletion src/service/V12/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ export class V12 extends Service<"V12"> implements OneBot.Base {
}

private startWs(config: V12.WsConfig) {
this.wss = this.oneBot.app.router.ws(this.path, this.oneBot.app.httpServer);
this.wss = this.oneBot.app.router.ws(this.path);
this.logger.mark(
`开启ws服务器成功,监听:ws://127.0.0.1:${this.oneBot.app.config.port}${this.path}`,
);
Expand Down
4 changes: 4 additions & 0 deletions vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
server:{
strictPort:false,
port:6728
},
plugins:[
vue(),
AutoImport({
Expand Down

0 comments on commit 855845b

Please sign in to comment.