Skip to content

Commit

Permalink
fix: close #73 #120
Browse files Browse the repository at this point in the history
  • Loading branch information
sj817 committed Aug 16, 2024
1 parent 35facaf commit 282ae6e
Show file tree
Hide file tree
Showing 14 changed files with 182 additions and 80 deletions.
2 changes: 1 addition & 1 deletion src/adapter/input/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export class AdapterInput implements KarinAdapter {
return { message_id: e.message_id, message_time: Date.now(), raw_data: elements }
}

listener.emit('message', e)
listener.emit('adapter.message', e)
}

async #MsgToFile (type: 'image' | 'record', file: Buffer | string): Promise<string> {
Expand Down
8 changes: 4 additions & 4 deletions src/adapter/onebot/11/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export class OB11Event {
*/
e.replyCallback = async elements => await this.adapter.SendMessage(e.contact, elements)

listener.emit('message', e)
listener.emit('adapter.message', e)
}

/**
Expand Down Expand Up @@ -381,7 +381,7 @@ export class OB11Event {
*/
notice.replyCallback = async elements => await this.adapter.SendMessage(notice.contact, elements)

listener.emit('notice', notice)
listener.emit('adapter.notice', notice)
}

/** 请求事件 */
Expand Down Expand Up @@ -419,7 +419,7 @@ export class OB11Event {
*/
request.replyCallback = async elements => await this.adapter.SendMessage(request.contact, elements)

listener.emit('request', request)
listener.emit('adapter.request', request)
return
}
case 'group': {
Expand Down Expand Up @@ -457,7 +457,7 @@ export class OB11Event {
*/
request.replyCallback = async elements => await this.adapter.SendMessage(request.contact, elements)

listener.emit('request', request)
listener.emit('adapter.request', request)
return
}
default: {
Expand Down
6 changes: 3 additions & 3 deletions src/adapter/onebot/11/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import WebSocket from 'ws'
import { randomUUID } from 'crypto'
import { IncomingMessage } from 'http'
import { listener } from 'karin/core/listener/listener'
import { karin } from 'karin/core/karin/karin'
import { common, config, logger, segment } from 'karin/utils'
import { GroupHonorInfo, KarinAdapter, LoggerLevel, MessageType, OB11Api, OB11ApiParams, OB11ApiResponse, OB11Segment, OB11SegmentType, Role } from 'karin/types'

Expand Down Expand Up @@ -104,7 +104,7 @@ export class AdapterOneBot11 implements KarinAdapter {
this.socket.removeAllListeners()

/** 注销bot */
this.adapter.index && listener.delBot(this.adapter.index)
this.adapter.index && karin.delBot(this.adapter.index)

/** 正向ws需要重连 */
if (this.adapter.sub_type === 'client') {
Expand Down Expand Up @@ -149,7 +149,7 @@ export class AdapterOneBot11 implements KarinAdapter {
this.account.name = data.account_name
this.logger('info', `[加载完成][app_name:${this.version.name}][version:${this.version.version}] ` + logger.green(this.adapter.connect as string))
/** 注册bot */
const index = listener.addBot({ type: this.adapter.type, bot: this })
const index = karin.addBot({ type: this.adapter.type, bot: this })
if (index) this.adapter.index = index
}

Expand Down
2 changes: 1 addition & 1 deletion src/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export * from './karin/karin'
export * from './init/dir'
export * from './init/init'
export * from './karin/karin'
export * from './listener/listener'
export * from './plugin/base'
export * from '../types/plugin/app'
Expand Down
48 changes: 33 additions & 15 deletions src/core/karin/karin.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { server } from '../server/server'
import { stateArr } from '../plugin/base'
import { common } from 'karin/utils'
import { listener } from '../listener/listener'
import onebot11 from 'karin/adapter/onebot/11'
import { render, RenderServer } from 'karin/render'
import { render } from 'karin/render/app'
import { RenderServer } from 'karin/render/server'

import {
Scene,
Contact,
Expand All @@ -25,6 +24,11 @@ import {
AllRequestSubType,
} from 'karin/types'

import { pluginLoader } from '../plugin/loader'
import { common } from 'karin/utils/common/common'
import { logger } from 'karin/utils/core/logger'
import { Listeners } from '../listener/listener'

type FncFunction = (e: KarinMessage) => Promise<boolean>
type FncElement = string | KarinElement | Array<KarinElement>
type UseReceive = (e: KarinMessageType, next: Function, exit: Function) => Promise<void>
Expand Down Expand Up @@ -102,10 +106,13 @@ export interface OptionsElement extends OptionsCommand {
stop?: boolean
}

export class Karin {
start: boolean
export class Karin extends Listeners {
/** 是否启动 */
#start: boolean
constructor () {
this.start = false
super()

this.#start = false
this.run()
}

Expand Down Expand Up @@ -294,7 +301,7 @@ export class Karin {
const userId = options?.userId || e.user_id
const key = e.group_id ? `${e.group_id}.${userId}` : userId
stateArr[key] = { type: 'ctx' }
// 返回promise 设置超时时间

return new Promise((resolve, reject) => {
setTimeout(() => {
if (stateArr[key]) {
Expand All @@ -305,7 +312,7 @@ export class Karin {
}
}, time * 1000)

listener.once(`ctx:${key}`, (e: KarinMessage) => resolve(e))
this.once(`ctx:${key}`, (e: KarinMessage) => resolve(e))
})
}

Expand Down Expand Up @@ -354,15 +361,26 @@ export class Karin {
/**
* - 启动
*/
run () {
if (this.start) return
this.start = true
async run () {
if (this.#start) return
this.#start = true
const { server } = await import('../server/server')
server.init()
listener.emit('load.plugin')
listener.emit('adapter', RenderServer)
listener.emit('adapter', onebot11)
pluginLoader.load()
this.emit('adapter', RenderServer)
this.emit('adapter', onebot11)
}
}

export const karin = new Karin()
/**
* 即将废弃 请使用karin
* @deprecated
*/
export const listener = karin
/**
* 即将废弃 请使用karin
* @deprecated
*/
export const Bot = karin
export default karin
131 changes: 96 additions & 35 deletions src/core/listener/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,111 @@ import { level } from 'karin/db'
import { EventEmitter } from 'events'
import { pluginLoader } from '../plugin/loader'
import { common, logger, config, segment } from 'karin/utils'
import { KarinAdapter, Contact, KarinElement } from 'karin/types'
import { MessageHandler, NoticeHandler, RequestHandler } from 'karin/event'
import {
Contact,
KarinElement,
KarinAdapter,
KarinMessage,
KarinNoticeType,
KarinRequestType,
KarinMessageType,
} from 'karin/types'

type AdapterType = KarinAdapter['adapter']['type']
type onAdapter = { type: AdapterType; adapter: new () => KarinAdapter; path?: string }

/**
* 监听器管理
* 产生事件映射
*/
export class Listeners extends EventEmitter {
/**
* Bot索引
* @type - Bot索引
*/
index: number
export interface EmittEventMap {
'karin:count:send': number
'karin:count:fnc': string
error: any
adapter: onAdapter
'adapter.message': KarinMessageType
'adapter.notice': KarinNoticeType
'adapter.request': KarinRequestType
message: KarinMessageType
notice: KarinNoticeType
request: KarinRequestType
'plugin.watch': undefined
'restart.grpc': undefined
'restart.http': undefined
}

/**
* 框架名称
*/
/** 上下文 */
type ContextEvents = {
[K in `ctx:${string}`]: (e: KarinMessage) => void
}

/**
* 监听事件映射
*/
export interface OnEventMap extends ContextEvents {
'karin:count:send': (count: number) => void
'karin:count:fnc': (fnc: string) => void
error: (error: any) => void
adapter: (data: onAdapter) => void
'adapter.message': (data: KarinMessageType) => void
'adapter.notice': (data: KarinNoticeType) => void
'adapter.request': (data: KarinRequestType) => void
message: (data: KarinMessageType) => void
notice: (data: KarinNoticeType) => void
request: (data: KarinRequestType) => void
'plugin.watch': undefined
'restart.grpc': undefined
'restart.http': undefined
}

/**
* 监听器实例
*/
export class Listeners extends EventEmitter {
/** 框架名称 */
name: string
list: Array<{ index: number; type: KarinAdapter['adapter']['type']; bot: KarinAdapter }>
adapter: Array<{ type: KarinAdapter['adapter']['type']; adapter: new () => KarinAdapter; path: string }>
/** Bot列表 */
list: Array<{ index: number; type: AdapterType; bot: KarinAdapter }>
/** 适配器列表 */
adapter: Array<{ type: AdapterType; adapter: new () => KarinAdapter; path: string }>
/** Bot自增索引 */
#index: number
/** 是否启动 */
#start: boolean

constructor () {
super()
this.index = 0
this.#index = 0
this.name = 'Karin'
this.list = []
this.adapter = []
this.on('error', data => logger.error(data))
this.on('load.plugin', () => pluginLoader.load())
this.on('adapter', data => {
let path = data.path || '无'
if (path && data.type !== 'grpc') path = `ws://127.0.0.1:${config.Server.http.port}${data.path}`
path = logger.green(path)
logger.info(`[适配器][注册][${data.type}]: ` + path)
this.addAdapter(data)
})

this.on('message', data => new MessageHandler(data))
this.on('notice', data => new NoticeHandler(data))
this.on('request', data => new RequestHandler(data))
this.on('adapter', data => this.addAdapter(data))
this.on('adapter.message', data => new MessageHandler(data))
this.on('adapter.notice', data => new NoticeHandler(data))
this.on('adapter.request', data => new RequestHandler(data))

this.#start = false
}

on<K extends keyof OnEventMap> (event: K, listener: OnEventMap[K]): this
on (event: string, listener: (...args: any[]) => void): this
on (event: string | symbol, listener: (...args: any[]) => void): this {
return super.on(event, listener)
}

emit<K extends keyof EmittEventMap> (event: K, ...args: Parameters<EmittEventMap[K]>): boolean
emit (event: string | symbol, ...args: any[]): boolean
emit (event: string | symbol, ...args: any[]): boolean {
return super.emit(event, ...args)
}

/**
* 注册Bot 返回索引id
*/
addBot (data: { bot: KarinAdapter; type: KarinAdapter['adapter']['type'] }): number | false {
this.index++
const index = this.index
addBot (data: { bot: KarinAdapter; type: AdapterType }): number | false {
this.#index++
const index = this.#index
if (!data.bot) {
logger.error('[Bot管理][注册] 注册失败: Bot实例不能为空', JSON.stringify(data))
return false
Expand All @@ -61,8 +120,8 @@ export class Listeners extends EventEmitter {
}

/**
* 发送上线通知
*/
* 发送上线通知
*/
async #online (uid: string) {
/** 重启 */
const key = `karin:restart:${uid}`
Expand Down Expand Up @@ -151,7 +210,12 @@ export class Listeners extends EventEmitter {
* @param data.adapter - 适配器实例
* @param data.path - 适配器路径
*/
addAdapter (data: { type: KarinAdapter['adapter']['type']; adapter: new () => KarinAdapter; path?: string }) {
addAdapter (data: onAdapter) {
let path = data.path || '无'
if (path && data.type !== 'grpc') path = `ws://127.0.0.1:${config.Server.http.port}${data.path}`
path = logger.green(path)
logger.info(`[适配器][注册][${data.type}]: ` + path)

const adapter = { type: data.type, adapter: data.adapter, path: '' }
if (data.path) adapter.path = data.path
this.adapter.push(adapter)
Expand Down Expand Up @@ -249,6 +313,3 @@ export class Listeners extends EventEmitter {
return result
}
}

export const listener = new Listeners()
export const Bot = listener
8 changes: 4 additions & 4 deletions src/core/plugin/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import path from 'path'
import lodash from 'lodash'
import chokidar from 'chokidar'
import schedule from 'node-schedule'
import { listener } from '../listener/listener'
import { render } from 'karin/render'
import { karin } from '../karin/karin'
import { common, logger } from 'karin/utils'
import {
UseInfo,
Expand Down Expand Up @@ -115,7 +115,7 @@ class PluginLoader {
* 插件初始化
*/
async load () {
listener.once('plugin.watch', () => {
karin.once('plugin.watch', () => {
this.watchList.forEach(async ({ plugin, path }) => {
await this.watchDir(plugin, path)
logger.debug(`[热更新][${plugin}][${path}] 监听中...`)
Expand All @@ -136,7 +136,7 @@ class PluginLoader {

/** 优先级排序并打印插件信息 */
this.orderBy(true)
listener.emit('plugin.watch')
karin.emit('plugin.watch')
return this
}

Expand Down Expand Up @@ -371,7 +371,7 @@ class PluginLoader {

if (!isPrint) return

logger.info(`[插件][${Object.keys(this.plugin).length}个] 加载完成`)
logger.info(`[插件][${this.plugin.size}个] 加载完成`)
logger.info(`[渲染器][${render.Apps.length}个] 加载完成`)
logger.info(`[command][${this.command.length}个] 加载完成`)
logger.info(`[button][${this.button.length}个] 加载完成`)
Expand Down
Loading

0 comments on commit 282ae6e

Please sign in to comment.