2020-09-24 02:31:20 +00:00
|
|
|
import { injectable } from "@ccms/container"
|
2020-02-24 10:36:08 +00:00
|
|
|
|
|
|
|
export namespace channel {
|
|
|
|
/**
|
|
|
|
* handle plugin message
|
|
|
|
* @param data byte[]
|
|
|
|
*/
|
2020-02-27 10:14:17 +00:00
|
|
|
export type ChannelListener = (data: any, exts?: any) => void
|
2020-02-24 10:36:08 +00:00
|
|
|
|
|
|
|
@injectable()
|
|
|
|
export abstract class Channel {
|
|
|
|
private listenerMap = [];
|
2020-03-24 09:59:18 +00:00
|
|
|
/**
|
|
|
|
* 注册通道
|
|
|
|
* @param plugin 插件
|
|
|
|
* @param channel 通道
|
|
|
|
* @param exec 执行器
|
|
|
|
*/
|
2020-02-24 10:36:08 +00:00
|
|
|
listen(plugin: any, channel: string, exec: ChannelListener) {
|
2020-09-17 09:44:48 +00:00
|
|
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!')
|
|
|
|
let name = plugin.description.name
|
2020-02-24 10:36:08 +00:00
|
|
|
let listener = this.register(channel, exec)
|
2020-09-17 09:44:48 +00:00
|
|
|
if (!this.listenerMap[name]) this.listenerMap[name] = []
|
2020-02-24 10:36:08 +00:00
|
|
|
let offExec = () => {
|
2020-09-17 09:44:48 +00:00
|
|
|
this.unregister(channel, listener)
|
|
|
|
console.debug(`[${name}] unregister channel ${channel}`)
|
|
|
|
}
|
2020-02-24 10:36:08 +00:00
|
|
|
var off = {
|
|
|
|
channel,
|
|
|
|
listener,
|
|
|
|
off: offExec
|
2020-09-17 09:44:48 +00:00
|
|
|
}
|
|
|
|
this.listenerMap[name].push(off)
|
|
|
|
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`)
|
|
|
|
return off
|
2020-02-24 10:36:08 +00:00
|
|
|
}
|
2020-03-24 09:59:18 +00:00
|
|
|
/**
|
|
|
|
* 关闭插件注册的通道
|
|
|
|
* @param plugin 插件
|
|
|
|
*/
|
2020-02-24 10:36:08 +00:00
|
|
|
disable(plugin: any) {
|
2020-09-17 09:44:48 +00:00
|
|
|
var channelCache = this.listenerMap[plugin.description.name]
|
2020-02-24 10:36:08 +00:00
|
|
|
if (channelCache) {
|
2020-09-17 09:44:48 +00:00
|
|
|
channelCache.forEach(t => t.off())
|
|
|
|
delete this.listenerMap[plugin.description.name]
|
2020-02-24 10:36:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Send Channel Message
|
|
|
|
* @param player recover target
|
|
|
|
* @param channel ChannelName
|
|
|
|
* @param data byte[]
|
|
|
|
*/
|
|
|
|
abstract send(player: any, channel: string, data: any)
|
|
|
|
/**
|
|
|
|
* register channel
|
|
|
|
* @param channel ChannelName
|
|
|
|
*/
|
|
|
|
abstract register(channel: string, listener: ChannelListener): any
|
|
|
|
/**
|
|
|
|
* unregister channel
|
|
|
|
* @param channel ChannelName
|
|
|
|
*/
|
|
|
|
abstract unregister(channel: string, listener?: any): void
|
|
|
|
}
|
|
|
|
}
|