Skip to content

Commit

Permalink
fix: wsserver connect and close
Browse files Browse the repository at this point in the history
  • Loading branch information
BIYUEHU committed Jun 7, 2024
1 parent 106ac48 commit 6817c70
Show file tree
Hide file tree
Showing 32 changed files with 388 additions and 384 deletions.
199 changes: 126 additions & 73 deletions CHANGELOG.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion modules/access/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kotori-bot/kotori-plugin-access",
"version": "1.0.0",
"version": "1.0.1",
"description": "access plugin",
"main": "lib/index.js",
"keywords": [
Expand Down
16 changes: 8 additions & 8 deletions modules/access/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ export const inject = ['file'];
type Data = Record<string, string[]>;

export function main(ctx: Context) {
const load = (platform: string) => ctx.file.load(`${platform}.json`, 'json', {}) as Data;
const save = (platform: string, data: Data) => ctx.file.save(`${platform}.json`, data);
const load = (bot: string) => ctx.file.load<Data>(`${bot}.json`, 'json', {});
const save = (bot: string, data: Data) => ctx.file.save(`${bot}.json`, data);

ctx.on('before_parse', (data) => {
const d = data;
if (d.session.type !== MessageScope.GROUP || !d.session.groupId) return;
const list = load(d.session.api.adapter.platform);
const list = load(d.session.api.adapter.identity);
if (!(String(d.session.groupId) in list)) return;
if (!list[String(d.session.groupId)].includes(String(d.session.userId))) return;
d.session.sender.role = 'admin';
Expand All @@ -22,7 +22,7 @@ export function main(ctx: Context) {
ctx
.command('access query - access.descr.access.query')
.action((_, session) => {
const list = (load(session.api.adapter.platform)[String(session.groupId)] ?? [])
const list = (load(session.api.adapter.identity)[String(session.groupId)] ?? [])
.map((el) => session.format('access.msg.access.list', [el]))
.join('');
return ['access.msg.access.query', [list]];
Expand All @@ -33,14 +33,14 @@ export function main(ctx: Context) {
ctx
.command('access add <userId> - access.descr.access.add')
.action((data, session) => {
const list = load(session.api.adapter.platform);
const list = load(session.api.adapter.identity);
const index = String(session.groupId);
list[index] = list[index] ?? [];
if (list[index].includes(data.args[0] as string)) {
return session.error('exists', { target: data.args[0] as string });
}
list[index].push(data.args[0] as string);
save(session.api.adapter.platform, list);
save(session.api.adapter.identity, list);
return ['access.msg.access.add', [data.args[0]]];
})
.scope(MessageScope.GROUP)
Expand All @@ -49,14 +49,14 @@ export function main(ctx: Context) {
ctx
.command('access del <userId> - access.descr.access.del')
.action((data, session) => {
const list = load(session.api.adapter.platform);
const list = load(session.api.adapter.identity);
const index = String(session.groupId);
list[index] = list[index] ?? [];
if (!list[index].includes(data.args[0] as string)) {
return session.error('no_exists', { target: data.args[0] as string });
}
list[index] = list[index].filter((el) => el !== data.args[0]);
save(session.api.adapter.platform, list);
save(session.api.adapter.identity, list);
return ['access.msg.access.del', [data.args[0]]];
})
.scope(MessageScope.GROUP)
Expand Down
8 changes: 6 additions & 2 deletions modules/adapter-minecraft/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "kotori-plugin-adapter-minecraft",
"version": "1.0.1",
"version": "2.0.0",
"description": "Adapter For Minecraft Bedrock Edition",
"main": "lib/index.js",
"keywords": [
Expand All @@ -24,6 +24,10 @@
"kotori-bot": "workspace:^"
},
"dependencies": {
"mcwss": "^2.1.2"
"mcwss": "^2.1.3",
"ws": "^8.14.2"
},
"devDependencies": {
"@types/ws": "^8.5.8"
}
}
69 changes: 25 additions & 44 deletions modules/adapter-minecraft/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,15 @@
* @Blog: https://hotaru.icu
* @Date: 2023-09-29 14:31:09
* @LastEditors: Hotaru [email protected]
* @LastEditTime: 2024-05-02 18:12:01
* @LastEditTime: 2024-06-07 20:14:31
*/
import { Adapter, AdapterConfig, Context, MessageScope, Tsu, stringTemp } from 'kotori-bot';
import { AdapterConfig, Adapters, Context, MessageScope, Tsu, stringTemp } from 'kotori-bot';
import Mcwss from 'mcwss';
import WebSocket from 'ws';
import McApi from './api';
import McElements from './elements';

export const config = Tsu.Object({
port: Tsu.Number().int().range(1, 65535),
address: Tsu.String()
.regexp(/^ws(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/)
.default('ws://127.0.0.1'),
nickname: Tsu.String().default('Romi'),
template: Tsu.Union([Tsu.Null(), Tsu.String()]).default('<%nickname%> %msg%')
});
Expand All @@ -30,9 +27,7 @@ type MessageData =
: never
: never;

export class McAdapter extends Adapter<McApi> {
private app?: Mcwss;

export class McAdapter extends Adapters.WebSocket<McApi, MessageData> {
private clients: Record<string, MessageData['client']> = {};

private messageId = 1;
Expand All @@ -44,7 +39,27 @@ export class McAdapter extends Adapter<McApi> {
this.config = config;
}

public handle(data: MessageData) {
public start() {
this.connection = (ws, req) => {
const fakeServer = new WebSocket.Server({ noServer: true });
const app = new Mcwss({ server: fakeServer });
app.on('error', (err) => this.ctx.logger.error(err));
app.on('connection', (data) => {
this.online();
this.clients[data.client.sessionId] = data.client;
});
app.on('player_message', (data) => this.onMessage(data));
app.start();
fakeServer.emit('connection', ws, req);
};
this.setup();
}

public handle() {
this.handle.toString();
}

public onMessage(data: MessageData) {
this.session('on_message', {
type: data.body.type === 'chat' ? MessageScope.GROUP : MessageScope.PRIVATE,
messageId: this.messageId,
Expand All @@ -60,29 +75,6 @@ export class McAdapter extends Adapter<McApi> {
this.messageId += 1;
}

public start() {
this.connect();
this.ctx.emit('connect', {
type: 'connect',
adapter: this,
normal: true,
mode: 'ws-reverse',
address: `${this.config.address}:${this.config.port}`
});
}

public stop() {
this.app?.stop();
this.ctx.emit('connect', {
type: 'disconnect',
adapter: this,
normal: true,
mode: 'other',
address: `${this.config.address}:${this.config.port}`
});
this.offline();
}

public send(action: string, params: { msg: string }) {
const [sessionId, playerName] = action.split('@');
const { msg } = params;
Expand All @@ -99,17 +91,6 @@ export class McAdapter extends Adapter<McApi> {
messageId: this.messageId
});
}

private connect() {
this.app = new Mcwss({ port: this.config.port, autoRegister: true, autoClearEvents: true });
this.app.on('error', (err) => this.ctx.logger.error(err));
this.app.on('connection', (data) => {
if (Object.keys(this.clients).length === 0) this.online();
this.clients[data.client.sessionId] = data.client;
});
this.app.on('player_message', (data) => this.handle(data));
this.app.start();
}
}

export default McAdapter;
2 changes: 1 addition & 1 deletion modules/adapter-onebot/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kotori-bot/kotori-plugin-adapter-onebot",
"version": "1.2.1",
"version": "2.0.0",
"description": "Adapter For Onebot (go-cqhttp)",
"main": "lib/index.js",
"keywords": [
Expand Down
103 changes: 41 additions & 62 deletions modules/adapter-onebot/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
* @Blog: https://hotaru.icu
* @Date: 2023-09-29 14:31:09
* @LastEditors: Hotaru [email protected]
* @LastEditTime: 2024-02-16 15:33:09
* @LastEditTime: 2024-06-07 19:53:00
*/
import { Adapter, AdapterConfig, Context, EventDataApiBase, EventDataTargetId, MessageScope, Tsu } from 'kotori-bot';
import { Adapters, AdapterConfig, Context, EventDataApiBase, EventDataTargetId, MessageScope, Tsu } from 'kotori-bot';
import WebSocket from 'ws';
import OnebotApi from './api';
import WsServer from './services/wsserver';
import { EventDataType } from './types';
import OnebotElements from './elements';

Expand All @@ -24,37 +23,40 @@ declare module 'kotori-bot' {
}
}

export const config = Tsu.Intersection([
export const config = Tsu.Union([
Tsu.Object({
mode: Tsu.Literal('ws'),
port: Tsu.Number().int().range(1, 65535),
address: Tsu.String()
.regexp(/^ws(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/)
.default('ws://127.0.0.1'),
retry: Tsu.Number().int().min(1).default(10)
}),
Tsu.Union([
Tsu.Object({
mode: Tsu.Literal('ws')
}),
Tsu.Object({
mode: Tsu.Literal('ws-reverse')
})
])
Tsu.Object({
mode: Tsu.Literal('ws-reverse')
})
]);

type OnebotConfig = Tsu.infer<typeof config> & AdapterConfig;

const handleMsg = (msg: string) => msg.replace(/\[CQ:at,qq=(.*?)\]/g, '$1');

export class OnebotAdapter extends Adapter {
export class OnebotAdapter extends Adapters.WebSocket<OnebotApi> {
private readonly address: string;

private readonly isReverse: boolean;

public readonly config: OnebotConfig;

public constructor(ctx: Context, config: OnebotConfig, identity: string) {
super(ctx, config, identity, OnebotApi, new OnebotElements());
this.config = config;
this.address = `${this.config.address ?? 'ws://127.0.0.1'}:${this.config.port}`;
this.address = this.config.mode === 'ws' ? `${this.config.address ?? 'ws://127.0.0.1'}:${this.config.port}` : '';
this.isReverse = !this.address;
if (!this.isReverse) return;
this.connection = (ws) => {
this.socket = ws;
};
}

public handle(data: EventDataType) {
Expand Down Expand Up @@ -168,32 +170,48 @@ export class OnebotAdapter extends Adapter {
groupId: data.group_id!
});
}
if (!this.onlineTimerId) this.onlineTimerId = setTimeout(() => this.offline, 50 * 1000);
if (!this.onlineTimerId) this.onlineTimerId = setTimeout(() => this.offline(), 50 * 1000);
}

public start() {
if (this.config.mode === 'ws-reverse') {
if (this.isReverse) {
this.setup();
return;
}
/* ws mode handle */
this.ctx.emit('connect', {
type: 'connect',
mode: 'ws',
adapter: this,
normal: true,
address: this.address
});
this.socket = new WebSocket(`${this.address}`);
this.socket.on('close', () => {
this.ctx.emit('connect', {
type: 'connect',
mode: 'ws-reverse',
type: 'disconnect',
adapter: this,
normal: true,
normal: false,
mode: 'ws',
address: this.address
});
}
this.connectWss();
});
this.socket.on('message', (raw) => this.handle(JSON.parse(raw.toString())));
}

public stop() {
if (this.isReverse) {
super.stop();
return;
}
this.ctx.emit('connect', {
type: 'disconnect',
adapter: this,
normal: true,
address: this.address,
mode: this.config.mode
mode: 'ws'
});
this.socket?.close();
this.offline();
}

public send(action: string, params?: object) {
Expand All @@ -202,45 +220,6 @@ export class OnebotAdapter extends Adapter {

private socket: WebSocket | null = null;

private async connectWss() {
if (this.config.mode === 'ws-reverse') {
const wss = await WsServer(this.config.port);
const [socket] = wss;
this.socket = socket;
} else {
this.ctx.emit('connect', {
type: 'connect',
mode: 'ws',
adapter: this,
normal: true,
address: this.address
});
this.socket = new WebSocket(`${this.address}`);
this.socket.on('close', () => {
this.ctx.emit('connect', {
type: 'disconnect',
adapter: this,
normal: false,
mode: 'ws',
address: this.address
});
setTimeout(() => {
if (!this.socket) return;
this.socket.close();
this.ctx.emit('connect', {
type: 'connect',
mode: 'ws-reverse',
adapter: this,
normal: false,
address: this.address
});
this.connectWss();
}, this.config.retry * 1000);
});
}
this.socket.on('message', (data) => this.handle(JSON.parse(data.toString())));
}

/* global NodeJS */
private onlineTimerId: NodeJS.Timeout | null = null;
}
22 changes: 0 additions & 22 deletions modules/adapter-onebot/src/services/wsserver.ts

This file was deleted.

Loading

0 comments on commit 6817c70

Please sign in to comment.