2020-05-02 16:14:47 +00:00
|
|
|
import { channel, plugin } from '@ccms/api'
|
|
|
|
import { inject, provideSingleton } from '@ccms/container'
|
2020-02-24 10:36:08 +00:00
|
|
|
|
|
|
|
const Bukkit = org.bukkit.Bukkit
|
|
|
|
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
|
|
|
const Messenger = Bukkit.getMessenger()
|
|
|
|
|
2020-02-26 02:15:33 +00:00
|
|
|
@provideSingleton(channel.Channel)
|
2020-02-24 10:36:08 +00:00
|
|
|
export class BukkitChannel extends channel.Channel {
|
|
|
|
@inject(plugin.PluginInstance)
|
2020-07-23 05:44:39 +00:00
|
|
|
private pluginInstance: any
|
2020-09-17 09:44:48 +00:00
|
|
|
private cacheChannel = new Map<string, any[]>()
|
2020-07-23 05:44:39 +00:00
|
|
|
/**
|
|
|
|
* 给玩家发送通道消息
|
|
|
|
* @param player 接受消息的玩家
|
|
|
|
* @param channel 通道
|
|
|
|
* @param data 数据
|
|
|
|
*/
|
|
|
|
send(player: any, channel: string, data: number[]) {
|
|
|
|
player.sendPluginMessage(this.pluginInstance, channel, data)
|
2020-02-24 10:36:08 +00:00
|
|
|
}
|
2020-07-23 05:44:39 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 注册通道监听器
|
|
|
|
* @param channel 通道
|
|
|
|
* @param listener 监听器
|
|
|
|
*/
|
2020-02-24 10:36:08 +00:00
|
|
|
register(channel: string, listener: channel.ChannelListener) {
|
2020-09-17 09:44:48 +00:00
|
|
|
if (!this.cacheChannel.has(channel)) this.cacheChannel.set(channel, [])
|
|
|
|
this.cacheChannel.get(channel).push(listener)
|
|
|
|
let pluginMessageListener = new PluginMessageListener({
|
2020-02-27 10:14:17 +00:00
|
|
|
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
2020-09-17 09:44:48 +00:00
|
|
|
try {
|
|
|
|
listener(data, { channel, player, data })
|
|
|
|
} catch (error) {
|
|
|
|
console.ex(error)
|
|
|
|
}
|
2020-02-24 10:36:08 +00:00
|
|
|
}
|
2020-09-17 09:44:48 +00:00
|
|
|
})
|
|
|
|
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, pluginMessageListener)
|
2020-07-23 05:44:39 +00:00
|
|
|
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel)
|
2020-09-17 09:44:48 +00:00
|
|
|
return pluginMessageListener
|
2020-02-24 10:36:08 +00:00
|
|
|
}
|
|
|
|
unregister(channel: string, listener: any) {
|
2020-09-17 09:44:48 +00:00
|
|
|
if (!this.cacheChannel.has(channel)) return
|
|
|
|
let cacheListener = this.cacheChannel.get(channel)
|
|
|
|
cacheListener = cacheListener.filter(l => l != listener)
|
|
|
|
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel, listener)
|
|
|
|
if (cacheListener.length == 0) {
|
|
|
|
this.cacheChannel.delete(channel)
|
|
|
|
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
|
|
|
|
}
|
2020-02-24 10:36:08 +00:00
|
|
|
}
|
|
|
|
}
|