ms/packages/bukkit/src/channel.ts

55 lines
2.1 KiB
TypeScript
Raw Normal View History

import { channel, plugin } from '@ccms/api'
import { inject, provideSingleton } from '@ccms/container'
const Bukkit = org.bukkit.Bukkit
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
const Messenger = Bukkit.getMessenger()
@provideSingleton(channel.Channel)
export class BukkitChannel extends channel.Channel {
@inject(plugin.PluginInstance)
private pluginInstance: any
2020-09-17 09:44:48 +00:00
private cacheChannel = new Map<string, any[]>()
/**
*
* @param player
* @param channel
* @param data
*/
send(player: any, channel: string, data: number[]) {
player.sendPluginMessage(this.pluginInstance, channel, data)
}
/**
*
* @param channel
* @param listener
*/
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({
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-09-17 09:44:48 +00:00
})
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, pluginMessageListener)
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel)
2020-09-17 09:44:48 +00:00
return pluginMessageListener
}
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)
}
}
}