Plugin Message channal and global chat check

This commit is contained in:
len 2021-05-13 20:27:20 +02:00
parent d087d47d5c
commit 35fda21ed1
15 changed files with 231 additions and 81 deletions

View File

@ -21,6 +21,9 @@ public class ChatImplementation implements ChatAPI{
public ChatImplementation() {
instance = this;
Config.init();
luckPerms = getLuckPerms();
//databaseConnection = getDataBase();
// init database
// init depends//or set them the first time they are called?
}

View File

@ -184,4 +184,9 @@ public final class Config {
GACFORMAT = getString("commands.globaladminchat.format", GACFORMAT);
}
public static String MESSAGECHANNEL = "altitude:chatplugin";
private static void messageChannels() {
MESSAGECHANNEL = getString("settings.message-channel", MESSAGECHANNEL);
}
}

View File

@ -6,6 +6,8 @@ public class ChatPlayer {
// todo merge partyuser here, or make party user extend this?
// todo gctoggle?
// todo cache prefixes?
private UUID uuid;
private UUID replyTarget;
private boolean globalChatEnabled; // this vs permission?

View File

@ -1,8 +1,10 @@
package com.alttd.chat;
import com.alttd.chat.commands.GlobalChat;
import com.alttd.chat.config.Config;
import com.alttd.chat.handler.ChatHandler;
import com.alttd.chat.listeners.PlayerListener;
import com.alttd.chat.listeners.PluginMessage;
import org.bukkit.command.CommandExecutor;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
@ -14,6 +16,8 @@ public class ChatPlugin extends JavaPlugin {
private ChatAPI chatAPI;
private ChatHandler chatHandler;
private String messageChannel;
@Override
public void onEnable() {
instance = this;
@ -21,6 +25,11 @@ public class ChatPlugin extends JavaPlugin {
chatHandler = new ChatHandler();
registerListener(new PlayerListener());
registerCommand("globalchat", new GlobalChat());
messageChannel = Config.MESSAGECHANNEL;
getServer().getMessenger().registerOutgoingPluginChannel(this, messageChannel);
getServer().getMessenger().registerIncomingPluginChannel(this, messageChannel, new PluginMessage());
}
@Override

View File

@ -5,11 +5,15 @@ import org.apache.commons.lang.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class GlobalChat implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(!(sender instanceof Player)) {
return true;
}
String message = StringUtils.join(args, " ", 0, args.length);
ChatPlugin.getInstance().getChatHandler().globalChat(sender, message);
return false;

View File

@ -2,13 +2,20 @@ package com.alttd.chat.handler;
import com.alttd.chat.ChatPlugin;
import com.alttd.chat.config.Config;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.Template;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChatHandler {
@ -21,29 +28,71 @@ public class ChatHandler {
public void globalChat(CommandSender source, String message) {
String senderName, prefix = "";
Map<String, String> map = new HashMap<>();
if (source instanceof Player) {
Player sender = (Player) source;
senderName = sender.getDisplayName();
prefix = plugin.getChatAPI().getPrefix(sender.getUniqueId());
} else {
senderName = Config.CONSOLENAME;
}
Player sender = (Player) source;
senderName = sender.getDisplayName(); // TODO this can be a component
prefix = plugin.getChatAPI().getPrefix(sender.getUniqueId());
MiniMessage miniMessage = MiniMessage.get();
if(!source.hasPermission("chat.format"))
message = miniMessage.stripTokens(message);
if(message.contains("[i]"))
message = message.replace("[i]", "<[i]>");
map.put("sender", senderName);
map.put("message", message);
map.put("server", Bukkit.getServerName());
map.put("prefix", prefix);
List<Template> templates = new ArrayList<>(List.of(
Template.of("sender", senderName),
Template.of("prefix", prefix),
Template.of("message", message),
Template.of("server", Bukkit.getServerName()),
Template.of("[i]", itemComponent(sender.getInventory().getItemInMainHand()))));
Component component = miniMessage.parse(Config.GCFORMAT, map);
Component component = miniMessage.parse(Config.GCFORMAT, templates);
Bukkit.broadcast(component, Config.GCPERMISSION);
// TODO this should be a plugin message, so proxy can handle the forwarding, we only do this on server level for [i] support
Bukkit.broadcast(miniMessage.serialize(component), Config.GCPERMISSION);
//todo make a method for this, it'll be used more then onc
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("globalchat");
out.writeUTF(miniMessage.serialize(component));
sender.sendPluginMessage(plugin, Config.MESSAGECHANNEL, out.toByteArray());
}
public Component itemComponent(ItemStack item) {
Component component = Component.text("[i]"); // todo config stuff
if(item.getType().equals(Material.AIR))
return component;
boolean dname = item.hasItemMeta() && item.getItemMeta().hasDisplayName();
if(dname) {
component = component.append(item.getItemMeta().displayName());
} else {
component = Component.text(materialToName(item.getType()));
}
component = component.hoverEvent(item.asHoverEvent());
return component;
}
private static String materialToName(Material m) {
if (m.equals(Material.TNT)) {
return "TNT";
}
String orig = m.toString().toLowerCase();
String[] splits = orig.split("_");
StringBuilder sb = new StringBuilder(orig.length());
int pos = 0;
for (String split : splits) {
sb.append(split);
int loc = sb.lastIndexOf(split);
char charLoc = sb.charAt(loc);
if (!(split.equalsIgnoreCase("of") || split.equalsIgnoreCase("and") ||
split.equalsIgnoreCase("with") || split.equalsIgnoreCase("on")))
sb.setCharAt(loc, Character.toUpperCase(charLoc));
if (pos != splits.length - 1)
sb.append(' ');
++pos;
}
return sb.toString();
}
}

View File

@ -0,0 +1,25 @@
package com.alttd.chat.listeners;
import com.alttd.chat.config.Config;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
public class PluginMessage implements PluginMessageListener {
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] bytes) {
if(!channel.equals(Config.MESSAGECHANNEL)) {
return;
}
ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
String subChannel = in.readUTF();
switch(subChannel) {
case "globalchat":
break;
default:
break;
}
}
}

View File

@ -37,11 +37,17 @@
<includes>
<include>net.kyori:adventure-text-minimessage</include>
<include>com.alttd.chat:chat-api</include>
<include>mysql:mysql-connector-java</include>
</includes>
<excludes>
<exclude>META-INF/*.MF</exclude>
</excludes>
</artifactSet>
<transformers>
<transformer>
<resource>META-INF/services/java.sql.Driver</resource>
</transformer>
</transformers>
</configuration>
</plugin>
</plugins>
@ -65,12 +71,6 @@
<version>4.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>11</maven.compiler.target>

View File

@ -37,11 +37,17 @@
<includes>
<include>net.kyori:adventure-text-minimessage</include>
<include>com.alttd.chat:chat-api</include>
<include>mysql:mysql-connector-java</include>
</includes>
<excludes>
<exclude>META-INF/*.MF</exclude>
</excludes>
</artifactSet>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/services/java.sql.Driver</resource>
</transformer>
</transformers>
</configuration>
<executions>
<execution>

View File

@ -1,10 +1,10 @@
package com.alttd.chat;
import com.alttd.chat.commands.GlobalAdminChat;
import com.alttd.chat.commands.GlobalChat;
import com.alttd.chat.commands.GlobalChatToggle;
import com.alttd.chat.database.DatabaseConnection;
import com.alttd.chat.config.Config;
import com.alttd.chat.handlers.ChatHandler;
import com.alttd.chat.handlers.ServerHandler;
import com.alttd.chat.listeners.ChatListener;
import com.alttd.chat.listeners.PluginMessageListener;
import com.google.inject.Inject;
@ -34,11 +34,10 @@ public class VelocityChat {
private final Path dataDirectory;
private ChatAPI chatAPI;
private DatabaseConnection databaseConnection;
private ChatHandler chatHandler;
private ServerHandler serverHandler;
private final ChannelIdentifier channelIdentifier =
MinecraftChannelIdentifier.from("customplugin:mychannel");
private ChannelIdentifier channelIdentifier;
@Inject
public VelocityChat(ProxyServer proxyServer, Logger proxyLogger, @DataDirectory Path proxydataDirectory) {
@ -50,16 +49,14 @@ public class VelocityChat {
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
//Config.init(getDataDirectory());
chatAPI = new ChatImplementation();
databaseConnection = chatAPI.getDataBase();
if (!databaseConnection.initialize()) {
// todo should we do this in the API or in the implementation?
return;
}
serverHandler = new ServerHandler();
chatHandler = new ChatHandler();
server.getEventManager().register(this, new ChatListener());
String[] channels = Config.MESSAGECHANNEL.split(":");// todo add a check for this?
channelIdentifier = MinecraftChannelIdentifier.create(channels[0], channels[1]);
server.getChannelRegistrar().register(channelIdentifier);
server.getEventManager().register(this, new PluginMessageListener(channelIdentifier));
loadCommands();
@ -73,10 +70,6 @@ public class VelocityChat {
return plugin;
}
public DatabaseConnection getDatabaseConnection() {
return databaseConnection;
}
public Logger getLogger() {
return logger;
}
@ -88,17 +81,18 @@ public class VelocityChat {
public void loadCommands() {
new GlobalAdminChat(server);
new GlobalChatToggle(server);
new GlobalChat(server);
// all commands go here
// all (proxy)commands go here
}
public ChatAPI API() {
return chatAPI;
}
public ChatHandler getChatHandler() {
return chatHandler;
}
public ServerHandler getServerHandler() {
return serverHandler;
}
}

View File

@ -1,37 +0,0 @@
package com.alttd.chat.commands;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.tree.LiteralCommandNode;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.command.CommandMeta;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.ProxyServer;
public class GlobalChat {
// todo move to server implementation and send plugin event to allowed servers, this means we can implement [i] in here
public GlobalChat(ProxyServer proxyServer) {
LiteralCommandNode<CommandSource> command = LiteralArgumentBuilder
.<CommandSource>literal("globalchat")
.requires(ctx -> ctx.hasPermission("command.proxy.globalchat"))// TODO permission system? load permissions from config?
.then(RequiredArgumentBuilder
.<CommandSource, String>argument("message", StringArgumentType.greedyString())
.executes(context -> {
//ChatPlugin.getPlugin().getChatHandler().globalChat(context.getSource(), context.getArgument("message", String.class));
return 1;
})
)
.executes(context -> 0)
.build();
BrigadierCommand brigadierCommand = new BrigadierCommand(command);
CommandMeta.Builder metaBuilder = proxyServer.getCommandManager().metaBuilder(brigadierCommand);
CommandMeta meta = metaBuilder.build();
proxyServer.getCommandManager().register(meta, brigadierCommand);
}
}

View File

@ -68,4 +68,8 @@ public final class ServerConfig {
/** DO NOT EDIT ANYTHING ABOVE **/
public boolean GLOBALCHAT = true; // TODO change to false on release
private void ServerSettings() {
GLOBALCHAT = getBoolean("global-chat-enabled", GLOBALCHAT);
}
}

View File

@ -0,0 +1,29 @@
package com.alttd.chat.data;
import com.alttd.chat.config.ServerConfig;
import com.velocitypowered.api.proxy.server.RegisteredServer;
public class ServerWrapper
{
private RegisteredServer registeredServer;
private final boolean globalChat;
public ServerWrapper(RegisteredServer registeredServer, ServerConfig serverConfig)
{
this.registeredServer = registeredServer;
this.globalChat = serverConfig.GLOBALCHAT;
}
public RegisteredServer getRegisteredServer() {
return registeredServer;
}
public boolean globalChat()
{
return globalChat;
}
}

View File

@ -0,0 +1,47 @@
package com.alttd.chat.handlers;
import com.alttd.chat.VelocityChat;
import com.alttd.chat.config.ServerConfig;
import com.alttd.chat.data.ServerWrapper;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import net.kyori.adventure.text.minimessage.MiniMessage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ServerHandler {
private VelocityChat plugin;
private static List<ServerWrapper> servers;
public ServerHandler() {
plugin = VelocityChat.getPlugin();
initialize();
}
public void cleanup() { // for use on /reload?
servers.clear();
initialize();
}
public void initialize() {
servers = new ArrayList<>();
for (RegisteredServer registeredServer : plugin.getProxy().getAllServers()) {
servers.add(new ServerWrapper(registeredServer, new ServerConfig(registeredServer.getServerInfo().getName())));
}
}
public void sendGlobalChat(String message) {
servers.stream()
.filter(serverWrapper -> serverWrapper.globalChat())
.forEach(serverWrapper -> serverWrapper.getRegisteredServer().sendMessage(MiniMessage.get().parse(message)));
}
public List<ServerWrapper> getServers()
{
return Collections.unmodifiableList(servers);
}
}

View File

@ -1,5 +1,6 @@
package com.alttd.chat.listeners;
import com.alttd.chat.VelocityChat;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import com.velocitypowered.api.event.Subscribe;
@ -10,6 +11,7 @@ import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
public class PluginMessageListener {
//todo add an extra listener for nicknames?
private final ChannelIdentifier identifier;
public PluginMessageListener(ChannelIdentifier identifier){
@ -22,13 +24,21 @@ public class PluginMessageListener {
event.setResult(PluginMessageEvent.ForwardResult.handled());
if(event.getSource() instanceof Player){
// if this happens there's an oopsie
}
if(event.getSource() instanceof ServerConnection){
// Read the data written to the message
ByteArrayDataInput in = ByteStreams.newDataInput(event.getData());
String message = in.readUTF();
String channel = in.readUTF();
VelocityChat.getPlugin().getLogger().info("server " + event.getSource());
switch (channel) {
case "globalchat":
VelocityChat.getPlugin().getServerHandler().sendGlobalChat(in.readUTF());
break;
default:
VelocityChat.getPlugin().getLogger().info("server " + event.getSource());
break;
}
}
}
}