Skip to content

Commit

Permalink
fix: kritor 适配
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-cn committed Jul 11, 2024
1 parent 9a0182f commit 8d34ff8
Show file tree
Hide file tree
Showing 13 changed files with 133 additions and 111 deletions.
15 changes: 12 additions & 3 deletions core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Middleware } from './middleware';
import { Plugin, PluginMap } from './plugin';
import { Bot, LogLevel } from './types';
import { loadModule } from './utils';
import { remove } from '@zhinjs/shared';
import { remove, sleep } from '@zhinjs/shared';
import { APP_KEY, CONFIG_DIR, REQUIRED_KEY, WORK_DIR } from './constans';
import path from 'path';
import { Adapter, AdapterBot, AdapterReceive } from './adapter';
Expand Down Expand Up @@ -348,8 +348,16 @@ export class App extends EventEmitter {
if (!loaded) this.logger.warn(`load plugin "${name}" failed`, error);
return this;
}

stop() {}
async stop() {
for (const [name, adapter] of this.adapters) {
adapter.emit('stop');
this.logger.mark(`adapter: ${name} stopped`);
}
this.emit('stop');
this.logger.info(`process exit after 3 seconds...`);
await sleep(3000);
process.exit();
}
}

export interface App extends App.Services {
Expand Down Expand Up @@ -430,6 +438,7 @@ export namespace App {
}

export interface Config {
has_init?: boolean;
log_level: LogLevel | string;
disable_adapters: string[];
disable_bots: string[];
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/zhinjs/zhin"
},
"scripts": {
"start": "pnpm start -C test start",
"start": "pnpm -C test start",
"dev": "pnpm -C test dev",
"init": "pnpm -C test run init",
"lint": "eslint packages --ext .ts",
Expand Down
132 changes: 67 additions & 65 deletions packages/adapters/kritor/src/client.ts

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion packages/adapters/kritor/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ adapter.schema({
});
adapter.define('sendMsg', async (bot_id, target_id, target_type, message, source) => {
const bot = adapter.pick(bot_id);
let template: string = await adapter.app!.renderMessage(message as string, source);
const contact = bot.createContact(target_id, target_type as any);
await bot.sendMessage(contact, Client.createElementsFromTemplate(message));
await bot.sendMessage(contact, Client.createElementsFromTemplate(template));
bot.logger.info(`send [${target_type} ${target_id}]:${decodeURIComponent(message)}`);
});
const messageHandler = (bot: Adapter.Bot<Client>, event: kritor.common.IPushMessageBody) => {
Expand Down
3 changes: 2 additions & 1 deletion packages/adapters/mock/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"directory": "packages/adapters/mock"
},
"peerDependencies": {
"zhin": "workspace:^"
"zhin": "workspace:^",
"@zhinjs/web": "workspace:^"
},
"devDependencies": {
"@types/node": "latest",
Expand Down
7 changes: 7 additions & 0 deletions packages/adapters/mock/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { Adapter } from 'zhin';
import type {} from '@zhinjs/web';

const adapter = new Adapter('console');
const startBots = () => {
adapter.app!.web.ws.on('message', e => {});
};
const stopBots = () => {};
adapter.on('start', startBots);
adapter.on('stop', stopBots);
export default adapter;
2 changes: 1 addition & 1 deletion packages/plugins/qa/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const getAnswer = async (message: Message): Promise<undefined | QAInfo> => {
const qaPlugin = new Plugin('问答管理');
qaPlugin.required('database');
const qaCommand = qaPlugin
.command('问答 <question:string> <answer:string>')
.command('问答 <question:string> <answer:any>')
.desc('添加问答')
.option('-a <adapter:string> 可用适配器,默认*', '*')
.option('-b <bot:string> 可用机器人,默认*', '*')
Expand Down
53 changes: 27 additions & 26 deletions packages/services/web/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ import * as path from 'path';
declare module 'zhin' {
namespace App {
interface Services {
viteServer: import('vite').ViteDevServer;

addEntry(entry: string): () => void;

wsServer: WebSocket.Server;
entries: Record<string, string>;
web: WebServer;
}
}
}
export type WebServer = {
vite: import('vite').ViteDevServer;
addEntry(entry: string): () => void;
ws: WebSocket.Server;
entries: Record<string, string>;
};
export const name = 'Web端';
const plugin = new Plugin('Web端');
const createSyncMsg = (key: string, value: any) => {
Expand Down Expand Up @@ -82,8 +83,8 @@ plugin.mounted(async () => {
if (filename.endsWith('.ts')) ctx.type = 'text/javascript';
return (ctx.body = fs.createReadStream(filename));
};
if (Object.keys(plugin.entries).includes(name)) {
return sendFile(path.resolve(process.env.PWD!, plugin.entries[name]));
if (Object.keys(plugin.web.entries).includes(name)) {
return sendFile(path.resolve(process.env.PWD!, plugin.web.entries[name]));
}
const filename = path.resolve(root, name);
if (!filename.startsWith(root) && !filename.includes('node_modules')) {
Expand All @@ -104,26 +105,26 @@ plugin.mounted(async () => {
viteServer.middlewares(ctx.req, ctx.res, resolve);
}),
);
plugin.service('viteServer', viteServer);

plugin.service('entries', {});
plugin.service('addEntry', entry => {
const hash = Date.now().toString(16);
plugin.entries[hash] = `/vite/@fs/${entry}`;
for (const ws of plugin.wsServer?.clients || []) {
ws.send(JSON.stringify(createAddMsg('entries', plugin.entries[hash])));
}
return () => {
for (const ws of plugin.wsServer?.clients || []) {
ws.send(JSON.stringify(createDeleteMsg('entries', plugin.entries[hash])));
plugin.service('web', {
vite: viteServer,
entries: {},
addEntry(entry) {
const hash = Date.now().toString(16);
this.entries[hash] = `/vite/@fs/${entry}`;
for (const ws of this.ws.clients || []) {
ws.send(JSON.stringify(createAddMsg('entries', this.entries[hash])));
}
delete plugin.entries[hash];
};
return () => {
for (const ws of this.ws.clients || []) {
ws.send(JSON.stringify(createDeleteMsg('entries', this.entries[hash])));
}
delete this.entries[hash];
};
},
ws: plugin.router.ws('/server'),
});
const wss: WebSocket.Server = plugin.router.ws('/server');
plugin.service('wsServer', wss);
wss.on('connection', (ws: WebSocket) => {
ws.send(JSON.stringify(createSyncMsg('entries', Object.values(plugin.entries))));
plugin.web.ws.on('connection', (ws: WebSocket) => {
ws.send(JSON.stringify(createSyncMsg('entries', Object.values(plugin.web.entries))));
});
});
plugin.required('koa', 'router', 'server');
Expand Down
5 changes: 0 additions & 5 deletions shared/tsconfig.dtsc.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,5 @@
"declaration": true,
"rootDir": "src",
"outFile": "lib/index.d.ts"
},
"dtsc": {
"inline": [
"@zhinjs/core"
],
}
}
2 changes: 1 addition & 1 deletion test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"private": true,
"version": "2.0.35",
"scripts": {
"start": "zhin",
"start": "zhin init && zhin -m dev",
"init": "zhin init",
"dev": "zhin -m dev"
},
Expand Down
6 changes: 0 additions & 6 deletions zhin/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@ const getValue = (list: string[], key: string, defaultValue: string) => {
list.splice(list.indexOf(key) + 1, 1);
return value;
};
const paddingToLength = (str: string | Buffer, length: number) => {
if (str.length === length) return str.toString();
if (typeof str === str) str = Buffer.from(str);
if (str.length > length) return str.slice(0, length).toString();
return str.toString().padEnd(length, '0');
};
const defaultArgv = {
mode: 'prod',
key: '',
Expand Down
1 change: 1 addition & 0 deletions zhin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export async function initialApp(this: App) {
const userPluginDir = path.join(WORK_DIR, 'plugins');
if (!fs.existsSync(userAdapterDir)) fs.mkdirSync(userAdapterDir);
if (!fs.existsSync(userPluginDir)) fs.mkdirSync(userPluginDir);
this.config.has_init = true;
this.config.adapters.push('processAdapter');
this.config.db_driver = 'level';
this.config.db_init_args = [
Expand Down
13 changes: 12 additions & 1 deletion zhin/src/start.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { createApp } from '@zhinjs/core';
import { CONFIG_DIR, createApp } from '@zhinjs/core';
import { initialApp } from '.';
import { sleep } from '@zhinjs/shared';
import process from 'process';
const errorHandler = (e: unknown) => console.error(e);

(async () => {
Expand All @@ -8,7 +10,16 @@ const errorHandler = (e: unknown) => console.error(e);
process.on('uncaughtException', errorHandler);
const app = createApp();
if (init === '1') {
if (app.config.has_init) {
app.logger.info('zhin app has already initialized, skipping initialization');
return process.exit();
}
app.logger.info('initializing');
await initialApp.apply(app);
app.logger.info('initialized,process will exit after 3 seconds');
app.logger.info(`please run 'npm start' to start zhin app`);
await sleep(3000);
return process.exit();
}
app.start(process.env.mode || 'prod');
})();

0 comments on commit 8d34ff8

Please sign in to comment.