package eu.mikroskeem.utils.bukkit; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import lombok.Getter; import lombok.experimental.Delegate; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; /** * PluginMessage class * * Checks if plugin message channel is registered and sends message if try-resource block ends. * You can use this like you would write normal plugin messages. */ public class PluginMessage implements AutoCloseable,ByteArrayDataOutput { @Getter @Delegate private ByteArrayDataOutput pluginMessage = ByteStreams.newDataOutput(); private String channel; private Player player; private Plugin plugin; private boolean wasChannelRegistered = false; public PluginMessage(Plugin plugin, Player player, String channel){ this.channel = channel; this.player = player; this.plugin = plugin; /* Check if channel is registered */ if(plugin.getServer().getMessenger().isOutgoingChannelRegistered(plugin, channel)){ wasChannelRegistered = true; } else { plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, channel); } } @Override public void close() { player.sendPluginMessage(plugin, channel, pluginMessage.toByteArray()); if(!wasChannelRegistered){ plugin.getServer().getMessenger().unregisterOutgoingPluginChannel(plugin, channel); } } }