diff --git a/multichat/dependency-reduced-pom.xml b/multichat/dependency-reduced-pom.xml index b6a4f28d..b7444e32 100644 --- a/multichat/dependency-reduced-pom.xml +++ b/multichat/dependency-reduced-pom.xml @@ -3,7 +3,7 @@ 4.0.0 xyz.olivermartin.multichat multichat - 1.9.5 + 1.10 @@ -261,8 +261,14 @@ me.clip placeholderapi - 2.9.2 + 2.10.9 provided + + + annotations + org.jetbrains + + com.github.rojo8399 @@ -293,5 +299,9 @@ + + 1.8 + UTF-8 + diff --git a/multichat/pom.xml b/multichat/pom.xml index aa6ee45a..3ae1d0bb 100644 --- a/multichat/pom.xml +++ b/multichat/pom.xml @@ -5,7 +5,12 @@ xyz.olivermartin.multichat multichat - 1.9.5 + 1.10 + + + 1.8 + UTF-8 + @@ -147,7 +152,7 @@ me.clip placeholderapi - 2.9.2 + 2.10.9 provided diff --git a/multichat/releases/1.10/multichat-1.10-beta.1.jar b/multichat/releases/1.10/multichat-1.10-beta.1.jar new file mode 100644 index 00000000..3a51c949 Binary files /dev/null and b/multichat/releases/1.10/multichat-1.10-beta.1.jar differ diff --git a/multichat/releases/1.10/multichat-1.10-beta.2.jar b/multichat/releases/1.10/multichat-1.10-beta.2.jar new file mode 100644 index 00000000..0b8910b6 Binary files /dev/null and b/multichat/releases/1.10/multichat-1.10-beta.2.jar differ diff --git a/multichat/releases/1.10/multichat-1.10-beta.3.jar b/multichat/releases/1.10/multichat-1.10-beta.3.jar new file mode 100644 index 00000000..c3cd97da Binary files /dev/null and b/multichat/releases/1.10/multichat-1.10-beta.3.jar differ diff --git a/multichat/releases/1.10/multichat-1.10-beta.4.jar b/multichat/releases/1.10/multichat-1.10-beta.4.jar new file mode 100644 index 00000000..9e7970b2 Binary files /dev/null and b/multichat/releases/1.10/multichat-1.10-beta.4.jar differ diff --git a/multichat/releases/1.10/multichat-1.10-beta.5.jar b/multichat/releases/1.10/multichat-1.10-beta.5.jar new file mode 100644 index 00000000..7dfcc0d7 Binary files /dev/null and b/multichat/releases/1.10/multichat-1.10-beta.5.jar differ diff --git a/multichat/releases/1.10/multichat-1.10-beta.6.jar b/multichat/releases/1.10/multichat-1.10-beta.6.jar new file mode 100644 index 00000000..edf8f88b Binary files /dev/null and b/multichat/releases/1.10/multichat-1.10-beta.6.jar differ diff --git a/multichat/releases/1.10/multichat-1.10-beta.7.jar b/multichat/releases/1.10/multichat-1.10-beta.7.jar new file mode 100644 index 00000000..41204bef Binary files /dev/null and b/multichat/releases/1.10/multichat-1.10-beta.7.jar differ diff --git a/multichat/src/main/java/com/olivermartin410/plugins/TGroupChatInfo.java b/multichat/src/main/java/com/olivermartin410/plugins/TGroupChatInfo.java index 07493223..32a15daf 100644 --- a/multichat/src/main/java/com/olivermartin410/plugins/TGroupChatInfo.java +++ b/multichat/src/main/java/com/olivermartin410/plugins/TGroupChatInfo.java @@ -1,8 +1,8 @@ package com.olivermartin410.plugins; import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; +import java.util.Set; import java.util.UUID; /** @@ -16,22 +16,22 @@ public class TGroupChatInfo extends TChatInfo implements Serializable { private static final long serialVersionUID = 1L; - private List Members = new ArrayList(); - private List Viewers = new ArrayList(); - private List Admins = new ArrayList(); - private List BannedPlayers = new ArrayList(); + private final Set members = new HashSet<>(); + private final Set viewers = new HashSet<>(); + private final Set admins = new HashSet<>(); + private final Set bannedPlayers = new HashSet<>(); private String PartyName; private boolean secret; private String password; private boolean formal; - public void setPassword(String newpassword) { - this.password = newpassword; + public void setPassword(String password) { + this.password = password; } - public void setFormal(boolean trueorfalse) { - this.formal = trueorfalse; + public void setFormal(boolean formal) { + this.formal = formal; } public boolean getFormal() { @@ -42,8 +42,8 @@ public String getPassword() { return this.password; } - public void setSecret(boolean trueorfalse) { - this.secret = trueorfalse; + public void setSecret(boolean secret) { + this.secret = secret; } public boolean getSecret() { @@ -58,91 +58,67 @@ public void setName(String Name) { this.PartyName = Name; } - public List getMembers() { - return this.Members; + public Set getMembers() { + return this.members; } - public void addMember(UUID memberuuid) { - this.Members.add(memberuuid); + public void addMember(UUID playerUID) { + this.members.add(playerUID); } - public void delMember(UUID memberuuid) { - this.Members.remove(memberuuid); + public void delMember(UUID playerUID) { + this.members.remove(playerUID); } - public List getAdmins() { - return this.Admins; + public Set getAdmins() { + return this.admins; } - public void addAdmin(UUID adminuuid) { - this.Admins.add(adminuuid); + public void addAdmin(UUID playerUID) { + this.admins.add(playerUID); } - public void delAdmin(UUID adminuuid) { - this.Admins.remove(adminuuid); + public void delAdmin(UUID playerUID) { + this.admins.remove(playerUID); } - public boolean existsAdmin(UUID adminuuid) { - - if (this.Admins.contains(adminuuid)) { - return true; - } - - return false; - + public boolean isAdmin(UUID playerUID) { + return this.admins.contains(playerUID); } - public List getBanned() { - return this.BannedPlayers; + public Set getBanned() { + return this.bannedPlayers; } - public void addBanned(UUID banuuid) { - this.BannedPlayers.add(banuuid); + public void addBanned(UUID playerUID) { + this.bannedPlayers.add(playerUID); } - public void delBanned(UUID banuuid) { - this.BannedPlayers.remove(banuuid); + public void delBanned(UUID playerUID) { + this.bannedPlayers.remove(playerUID); } - public boolean existsBanned(UUID banuuid) { - - if (this.BannedPlayers.contains(banuuid)) { - return true; - } - - return false; - + public boolean isBanned(UUID playerUID) { + return this.bannedPlayers.contains(playerUID); } - public boolean existsMember(UUID memberuuid) { - - if (this.Members.contains(memberuuid)) { - return true; - } - - return false; - + public boolean isMember(UUID playerUID) { + return this.members.contains(playerUID); } - public List getViewers() { - return this.Viewers; + public Set getViewers() { + return this.viewers; } - public void addViewer(UUID memberuuid) { - this.Viewers.add(memberuuid); + public void addViewer(UUID playerUID) { + this.viewers.add(playerUID); } - public void delViewer(UUID memberuuid) { - this.Viewers.remove(memberuuid); + public void delViewer(UUID playerUID) { + this.viewers.remove(playerUID); } - public boolean existsViewer(UUID memberuuid) { - - if (this.Viewers.contains(memberuuid)) { - return true; - } - - return false; - + public boolean isViewer(UUID playerUID) { + return this.viewers.contains(playerUID); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Announcements.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Announcements.java index 355f00e5..f09e9074 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Announcements.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Announcements.java @@ -1,15 +1,18 @@ package xyz.olivermartin.multichat.bungee; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.scheduler.ScheduledTask; import xyz.olivermartin.multichat.bungee.events.PostBroadcastEvent; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; /** * Announcements Management @@ -29,19 +32,21 @@ public static boolean startAnnouncement(final String name, Integer minutes) { Integer ID; - ScheduledTask task = ProxyServer.getInstance().getScheduler().schedule(MultiChat.getInstance(), new Runnable() { + ScheduledTask task = ProxyServer.getInstance().getScheduler().schedule(MultiChatProxy.getInstance().getPlugin(), new Runnable() { @Override public void run() { String message = announcements.get(name.toLowerCase()); - message = ChatControl.applyChatRules(message, "announcements", "").get(); + message = ChatControl.applyChatRules(null, message, MessageType.ANNOUNCEMENTS).get(); + + message = MultiChatUtil.translateColorCodes(message); for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&',message)))); + if (ProxyConfigs.CONFIG.isLegacyServer(onlineplayer.getServer().getInfo().getName())) { + onlineplayer.sendMessage(ProxyJsonUtils.parseMessage(MultiChatUtil.approximateRGBColorCodes(message))); } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&',message))); + onlineplayer.sendMessage(ProxyJsonUtils.parseMessage(message)); } } @@ -92,7 +97,7 @@ public static boolean addAnnouncement(String name, String message) { if (!announcements.containsKey(name.toLowerCase())) { - announcements.put(name.toLowerCase(), MultiChatUtil.reformatRGB(message)); + announcements.put(name.toLowerCase(), message); return true; } else { @@ -133,13 +138,15 @@ public static void playAnnouncement(String name) { String message = announcements.get(name.toLowerCase()); - message = ChatControl.applyChatRules(message, "announcements", "").get(); + message = ChatControl.applyChatRules(null, message, MessageType.ANNOUNCEMENTS).get(); + + message = MultiChatUtil.translateColorCodes(message); for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&',message)))); + if (ProxyConfigs.CONFIG.isLegacyServer(onlineplayer.getServer().getInfo().getName())) { + onlineplayer.sendMessage(ProxyJsonUtils.parseMessage(MultiChatUtil.approximateRGBColorCodes(message))); } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&',message))); + onlineplayer.sendMessage(ProxyJsonUtils.parseMessage(message)); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Bulletins.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Bulletins.java index f08f7ff3..4daf3ee4 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Bulletins.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Bulletins.java @@ -1,15 +1,18 @@ package xyz.olivermartin.multichat.bungee; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.concurrent.TimeUnit; - -import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.scheduler.ScheduledTask; import xyz.olivermartin.multichat.bungee.events.PostBroadcastEvent; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.concurrent.TimeUnit; /** * Bulletins Management @@ -72,7 +75,7 @@ public static void stopBulletins() { public static void addBulletin(String message) { synchronized (bulletin) { - bulletin.add(MultiChatUtil.reformatRGB(message)); + bulletin.add(message); } } @@ -95,7 +98,7 @@ public static void removeBulletin(int index) { } private static void scheduleNextBulletin(final int minutes) { - ScheduledTask task = ProxyServer.getInstance().getScheduler().schedule(MultiChat.getInstance(), new Runnable() { + ScheduledTask task = ProxyServer.getInstance().getScheduler().schedule(MultiChatProxy.getInstance().getPlugin(), new Runnable() { @Override public void run() { @@ -108,16 +111,18 @@ public void run() { message = bulletin.get(nextBulletin); - message = ChatControl.applyChatRules(message, "bulletins", "").get(); + message = ChatControl.applyChatRules(null, message, MessageType.BULLETINS).get(); + + message = MultiChatUtil.translateColorCodes(message); for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&',message)))); + if (ProxyConfigs.CONFIG.isLegacyServer(onlineplayer.getServer().getInfo().getName())) { + onlineplayer.sendMessage(ProxyJsonUtils.parseMessage(MultiChatUtil.approximateRGBColorCodes(message))); } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&',message))); + onlineplayer.sendMessage(ProxyJsonUtils.parseMessage(message)); } } - + // Trigger PostBroadcastEvent ProxyServer.getInstance().getPluginManager().callEvent(new PostBroadcastEvent("bulletin", message)); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/BungeeComm.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/BungeeComm.java deleted file mode 100644 index 7800dfc4..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/BungeeComm.java +++ /dev/null @@ -1,513 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.util.Optional; -import java.util.UUID; -import java.util.regex.PatternSyntaxException; - -import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.config.ServerInfo; -import net.md_5.bungee.api.connection.ProxiedPlayer; -import net.md_5.bungee.api.connection.Server; -import net.md_5.bungee.api.event.PluginMessageEvent; -import net.md_5.bungee.api.plugin.Listener; -import net.md_5.bungee.config.Configuration; -import net.md_5.bungee.event.EventHandler; - -/** - * Bungee Communication Manager - *

Manages all plug-in messaging channels on the BungeeCord side

- * - * @author Oliver Martin (Revilo410) - * - */ -public class BungeeComm implements Listener { - - public static void sendMessage(String message, ServerInfo server) { - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(stream); - - try { - // Players name - out.writeUTF(message); - - // Should display name be set? - Configuration configYML = ConfigManager.getInstance().getHandler("config.yml").getConfig(); - if (configYML.contains("set_display_name")) { - if (configYML.getBoolean("set_display_name")) { - out.writeUTF("T"); - } else { - out.writeUTF("F"); - } - } else { - out.writeUTF("T"); - } - - // Display name format - if (configYML.contains("display_name_format")) { - out.writeUTF(configYML.getString("display_name_format")); - } else { - out.writeUTF("%PREFIX%%NICK%%SUFFIX%"); - } - - // Is this server a global chat server? - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("global") == true - && !ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_global").contains(server.getName())) { - out.writeUTF("T"); - } else { - out.writeUTF("F"); - } - - // Send the global format - out.writeUTF(Channel.getGlobalChannel().getFormat()); - - } catch (IOException e) { - e.printStackTrace(); - } - - server.sendData("multichat:comm", stream.toByteArray()); - - } - - public static void sendCommandMessage(String command, ServerInfo server) { - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(stream); - - try { - - // Command - out.writeUTF(command); - - } catch (IOException e) { - e.printStackTrace(); - } - - server.sendData("multichat:act", stream.toByteArray()); - - } - - public static void sendPlayerCommandMessage(String command, String playerRegex, ServerInfo server) { - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(stream); - - try { - - // Command - out.writeUTF(playerRegex); - out.writeUTF(command); - - } catch (IOException e) { - e.printStackTrace(); - } - - server.sendData("multichat:pact", stream.toByteArray()); - - } - - public static void sendChatMessage(String message, ServerInfo server) { - - // This has been repurposed to send casts to local chat streams! - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(stream); - - - try { - // message part - out.writeUTF(message); - - - } catch (IOException e) { - e.printStackTrace(); - } - - server.sendData("multichat:chat", stream.toByteArray()); - - } - - public static void sendIgnoreMap(ServerInfo server) { - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - //DataOutputStream out = new DataOutputStream(stream); - try { - ObjectOutputStream oout = new ObjectOutputStream(stream); - - oout.writeObject(ChatControl.getIgnoreMap()); - - } catch (IOException e) { - e.printStackTrace(); - } - - server.sendData("multichat:ignore", stream.toByteArray()); - - } - - public static void sendPlayerChannelMessage(String playerName, String channel, Channel channelObject, ServerInfo server, boolean colour, boolean rgb) { - - sendIgnoreMap(server); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - //DataOutputStream out = new DataOutputStream(stream); - try { - ObjectOutputStream oout = new ObjectOutputStream(stream); - - // Players name - oout.writeUTF(playerName); - // Channel part - oout.writeUTF(channel); - oout.writeBoolean(colour); - oout.writeBoolean(rgb); - oout.writeBoolean(channelObject.isWhitelistMembers()); - oout.writeObject(channelObject.getMembers()); - - } catch (IOException e) { - e.printStackTrace(); - } - - server.sendData("multichat:ch", stream.toByteArray()); - - DebugManager.log("Sent message on multichat:ch channel!"); - - } - - @EventHandler - public static void onPluginMessage(PluginMessageEvent ev) { - - if (! (ev.getTag().equals("multichat:comm") || ev.getTag().equals("multichat:chat") || ev.getTag().equals("multichat:prefix") || ev.getTag().equals("multichat:suffix") || ev.getTag().equals("multichat:dn") || ev.getTag().equals("multichat:world") || ev.getTag().equals("multichat:nick") || ev.getTag().equals("multichat:pxe") || ev.getTag().equals("multichat:ppxe")) ) { - return; - } - - if (!(ev.getSender() instanceof Server)) { - return; - } - - if (ev.getTag().equals("multichat:comm")) { - - // TODO Remove - legacy - return; - - } - - if (ev.getTag().equals("multichat:chat")) { - - ev.setCancelled(true); - - DebugManager.log("{multichat:chat} Got a plugin message"); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - try { - - UUID uuid = UUID.fromString(in.readUTF()); - DebugManager.log("{multichat:chat} UUID = " + uuid); - String message = in.readUTF(); - DebugManager.log("{multichat:chat} Message = " + message); - String format = in.readUTF(); - - DebugManager.log("{multichat:chat} Format (before removal of double chars) = " + format); - - format = format.replace("%%","%"); - - DebugManager.log("{multichat:chat} Format = " + format); - - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (player == null) { - DebugManager.log("{multichat:chat} Could not get player! Abandoning chat message... (Is IP-Forwarding on?)"); - return; - } - - DebugManager.log("{multichat:chat} Got player successfully! Name = " + player.getName()); - - //synchronized (player) { - - DebugManager.log("{multichat:chat} Global Channel Available? = " + (Channel.getGlobalChannel() != null)); - Channel.getGlobalChannel().sendMessage(player, message, format); - - //} - - } catch (IOException e) { - DebugManager.log("{multichat:chat} ERROR READING PLUGIN MESSAGE"); - e.printStackTrace(); - } - - - return; - - } - - if (ev.getTag().equals("multichat:nick")) { - - ev.setCancelled(true); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - try { - - UUID uuid = UUID.fromString(in.readUTF()); - String nick = in.readUTF(); - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (player == null) return; - - synchronized (player) { - - /* - * Update the nickname stored somewhere and call for an update of the player - * display name in that location. (Pending the "true" value of fetch display names) - * and a new config option to decide if the display name should be set. - */ - - Optional opm = PlayerMetaManager.getInstance().getPlayer(uuid); - - if (opm.isPresent()) { - - opm.get().nick = nick; - PlayerMetaManager.getInstance().updateDisplayName(uuid); - - } - - } - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - if (ev.getTag().equals("multichat:prefix")) { - - ev.setCancelled(true); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - try { - - UUID uuid = UUID.fromString(in.readUTF()); - String prefix = in.readUTF(); - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (player == null) return; - - synchronized (player) { - - /* - * Update the prefix stored somewhere and call for an update of the player - * display name in that location. (Pending the "true" value of fetch display names) - * and a new config option to decide if the display name should be set. - */ - - Optional opm = PlayerMetaManager.getInstance().getPlayer(uuid); - - if (opm.isPresent()) { - - opm.get().prefix = prefix; - PlayerMetaManager.getInstance().updateDisplayName(uuid); - - } - - } - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - if (ev.getTag().equals("multichat:suffix")) { - - ev.setCancelled(true); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - try { - - UUID uuid = UUID.fromString(in.readUTF()); - String suffix = in.readUTF(); - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (player == null) return; - - synchronized (player) { - - /* - * Update the suffix stored somewhere and call for an update of the player - * display name in that location. (Pending the "true" value of fetch display names) - * and a new config option to decide if the display name should be set. - */ - - Optional opm = PlayerMetaManager.getInstance().getPlayer(uuid); - - if (opm.isPresent()) { - - opm.get().suffix = suffix; - PlayerMetaManager.getInstance().updateDisplayName(uuid); - - } - - } - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - if (ev.getTag().equals("multichat:dn")) { - - ev.setCancelled(true); - - DebugManager.log("[multichat:dn] Got an incoming channel message!"); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - try { - - UUID uuid = UUID.fromString(in.readUTF()); - String spigotDisplayName = in.readUTF(); - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (player == null) return; - - synchronized (player) { - - DebugManager.log("[multichat:dn] Player exists!"); - - Optional opm = PlayerMetaManager.getInstance().getPlayer(uuid); - - if (opm.isPresent()) { - - DebugManager.log("[multichat:dn] Player meta exists!"); - - DebugManager.log("[multichat:dn] The displayname received is: " + spigotDisplayName); - - opm.get().spigotDisplayName = spigotDisplayName; - PlayerMetaManager.getInstance().updateDisplayName(uuid); - - } - - } - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - if (ev.getTag().equals("multichat:world")) { - - ev.setCancelled(true); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - DebugManager.log("[multichat:world] Got an incoming channel message!"); - - try { - - UUID uuid = UUID.fromString(in.readUTF()); - String world = in.readUTF(); - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (player == null) return; - - DebugManager.log("[multichat:world] Player is online!"); - - synchronized (player) { - - /* - * Update the world stored somewhere - */ - - Optional opm = PlayerMetaManager.getInstance().getPlayer(uuid); - - if (opm.isPresent()) { - - DebugManager.log("[multichat:world] Got their meta data correctly"); - - opm.get().world = world; - - DebugManager.log("[multichat:world] Set their world to: " + world); - - } - - } - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - if (ev.getTag().equals("multichat:pxe")) { - - ev.setCancelled(true); - - DebugManager.log("[multichat:pxe] Got an incoming pexecute message!"); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - try { - - String command = in.readUTF(); - DebugManager.log("[multichat:pxe] Command is: " + command); - ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), command); - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - if (ev.getTag().equals("multichat:ppxe")) { - - ev.setCancelled(true); - - DebugManager.log("[multichat:ppxe] Got an incoming pexecute message (for a player)!"); - - ByteArrayInputStream stream = new ByteArrayInputStream(ev.getData()); - DataInputStream in = new DataInputStream(stream); - - try { - - String command = in.readUTF(); - String playerRegex = in.readUTF(); - - DebugManager.log("[multichat:ppxe] Command is: " + command); - DebugManager.log("[multichat:ppxe] Player regex is: " + playerRegex); - - for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { - - if (p.getName().matches(playerRegex)) { - - ProxyServer.getInstance().getPluginManager().dispatchCommand(p, command); - - } - - } - - } catch (IOException e) { - e.printStackTrace(); - } catch (PatternSyntaxException e2) { - MessageManager.sendMessage(ProxyServer.getInstance().getConsole(), "command_execute_regex"); - } - - } - - } -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CastControl.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CastControl.java index 5a6229d9..deb97507 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CastControl.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CastControl.java @@ -4,6 +4,9 @@ import java.util.Map; import net.md_5.bungee.api.CommandSender; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.proxy.common.channels.local.LocalChannel; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.ProxyChannel; /** * Cast Control @@ -16,13 +19,18 @@ public class CastControl { public static Map castList = new HashMap(); - public static void sendCast(String castName, String castMessage, Channel chatStream, CommandSender sender) { - castMessage = ChatControl.applyChatRules(castMessage, "casts", "").get(); - chatStream.sendMessage(castList.get(castName.toLowerCase()) + " " + castMessage, sender); + public static void sendCast(String castName, String castMessage, ProxyChannel channel, CommandSender sender) { + castMessage = ChatControl.applyChatRules(sender, castMessage, MessageType.CASTS).get(); + channel.broadcastRawMessage(sender, castList.get(castName.toLowerCase()) + " " + castMessage); + } + + public static void sendCast(String castName, String castMessage, LocalChannel channel, String server, CommandSender sender) { + castMessage = ChatControl.applyChatRules(sender, castMessage, MessageType.CASTS).get(); + channel.broadcastRawMessage(sender, server, castList.get(castName.toLowerCase()) + " " + castMessage); } public static void addCast(String castName, String castFormat) { - castList.put(castName.toLowerCase(), MultiChatUtil.reformatRGB(castFormat)); + castList.put(castName.toLowerCase(), castFormat); } public static void removeCast(String castName) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Channel.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Channel.java deleted file mode 100644 index 953a453d..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Channel.java +++ /dev/null @@ -1,418 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; - -import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.CommandSender; -import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.api.connection.ProxiedPlayer; -import xyz.olivermartin.multichat.bungee.events.PostBroadcastEvent; -import xyz.olivermartin.multichat.bungee.events.PostGlobalChatEvent; - -/** - * Channel - *

A class to represent a chat channel and control the messages sent etc.

- * - * @author Oliver Martin (Revilo410) - * - */ -public class Channel { - - private static GlobalChannel global; - private static LocalChannel local; - - static { - - global = new GlobalChannel("&f%DISPLAYNAME%&f: "); - local = new LocalChannel(); - - } - - public static GlobalChannel getGlobalChannel() { - return global; - } - - public static LocalChannel getLocalChannel() { - return local; - } - - public static Map playerChannels = new HashMap(); - - public static void setChannel (UUID uuid, Channel channel) { - Channel.playerChannels.put(uuid, channel); - } - - public static Channel getChannel (UUID uuid) { - return Channel.playerChannels.get(uuid); - } - - public static void removePlayer (UUID uuid) { - Channel.playerChannels.remove(uuid); - } - - /* END STATIC */ - - boolean whitelistMembers; - protected List members; - - boolean whitelistServers; - protected List servers; - - protected String name; - protected String format; - - public Channel(String name, String format, boolean whitelistServers, boolean whitelistMembers) { - - this.name = name; - this.whitelistServers = whitelistServers; - this.format = format; - this.servers = new ArrayList(); - this.members = new ArrayList(); - this.whitelistMembers = whitelistMembers; - - } - - public boolean isMember(UUID player) { - if (this.whitelistMembers) { - return this.members.contains(player); - } else { - return !this.members.contains(player); - } - } - - public void removeMember(UUID player) { - this.members.remove(player); - } - - public List getMembers() { - return this.members; - } - - public boolean isWhitelistMembers() { - return this.whitelistMembers; - } - - public void addServer(String server) { - if (!servers.contains(server)) servers.add(server); - } - - public void setServers(List servers) { - this.servers = servers; - } - - public void clearServers() { - this.servers = new ArrayList(); - } - - public void addMember(UUID member) { - if (!members.contains(member)) members.add(member); - } - - public void setMembers(List members) { - this.members = members; - } - - public String getName() { - return this.name; - } - - public String getFormat() { - return this.format; - } - - public void setFormat(String format) { - this.format = format; - } - - public void sendMessage(ProxiedPlayer sender, String message, String format) { - - DebugManager.log("CHANNEL #" + getName() + ": Got a message for the channel"); - DebugManager.log("CHANNEL #" + getName() + ": SENDER = " + sender.getName()); - DebugManager.log("CHANNEL #" + getName() + ": MESSAGE = " + message); - DebugManager.log("CHANNEL #" + getName() + ": FORMAT = " + format); - - for (ProxiedPlayer receiver : ProxyServer.getInstance().getPlayers()) { - - if (receiver != null && sender != null) { - - synchronized (receiver) { - - if (sender.getServer() != null && receiver.getServer() != null) { - - if ( (whitelistMembers && members.contains(receiver.getUniqueId())) || (!whitelistMembers && !members.contains(receiver.getUniqueId()))) { - if ( (whitelistServers && servers.contains(receiver.getServer().getInfo().getName())) || (!whitelistServers && !servers.contains(receiver.getServer().getInfo().getName()))) { - - if (!ChatControl.ignores(sender.getUniqueId(), receiver.getUniqueId(), "global_chat")) { - if (!receiver.getServer().getInfo().getName().equals(sender.getServer().getInfo().getName())) { - receiver.sendMessage(buildFormat(sender,receiver,format,message)); - } else { - // If they are on the same server, this message will already have been displayed locally. - } - } else { - ChatControl.sendIgnoreNotifications(receiver, sender, "global_chat"); - } - - } - - } - - } - - } - - } - - } - - // Trigger PostGlobalChatEvent - ProxyServer.getInstance().getPluginManager().callEvent(new PostGlobalChatEvent(sender, format, message)); - - sendToConsole(sender,format,message); - - } - - public void sendMessage(String message, CommandSender sender) { - - for (ProxiedPlayer receiver : ProxyServer.getInstance().getPlayers()) { - if (receiver != null && sender != null) { - if (receiver.getServer() != null) { - if ( (whitelistMembers && members.contains(receiver.getUniqueId())) || (!whitelistMembers && !members.contains(receiver.getUniqueId()))) { - if ( (whitelistServers && servers.contains(receiver.getServer().getInfo().getName())) || (!whitelistServers && !servers.contains(receiver.getServer().getInfo().getName()))) { - //TODO hiding & showing streams - - if (MultiChat.legacyServers.contains(receiver.getServer().getInfo().getName())) { - receiver.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', message)))); - } else { - receiver.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', message))); - } - - } - } - } - } - } - - // Trigger PostBroadcastEvent - ProxyServer.getInstance().getPluginManager().callEvent(new PostBroadcastEvent("cast", message)); - - ConsoleManager.logDisplayMessage(message); - - } - - /*public String buildSpigotFormat(ProxiedPlayer sender, String format, String message) { - - String newFormat = format; - - /*newFormat = newFormat.replace("%DISPLAYNAME%", sender.getDisplayName()); - newFormat = newFormat.replace("%NAME%", sender.getName()); - - Optional opm = PlayerMetaManager.getInstance().getPlayer(sender.getUniqueId()); - if (opm.isPresent()) { - newFormat = newFormat.replace("%PREFIX%", opm.get().prefix); - newFormat = newFormat.replace("%SUFFIX%", opm.get().suffix); - newFormat = newFormat.replace("%NICK%", opm.get().nick); - newFormat = newFormat.replace("%WORLD%", opm.get().world); - } - - newFormat = newFormat.replace("%SERVER%", sender.getServer().getInfo().getName()); - - - if (!ChatModeManager.getInstance().isGlobal(sender.getUniqueId())) { - newFormat = newFormat.replace("%MODE%", "Local"); - newFormat = newFormat.replace("%M%", "L"); - } - - if (ChatModeManager.getInstance().isGlobal(sender.getUniqueId())) { - newFormat = newFormat.replace("%MODE%", "Global"); - newFormat = newFormat.replace("%M%", "G"); - } - - newFormat = newFormat + "%MESSAGE%"; - - return newFormat; - - }*/ - - public BaseComponent[] buildFormat(ProxiedPlayer sender, ProxiedPlayer receiver, String format, String message) { - - String newFormat = format; - - /*newFormat = newFormat.replace("%DISPLAYNAME%", sender.getDisplayName()); - newFormat = newFormat.replace("%NAME%", sender.getName()); - - Optional opm = PlayerMetaManager.getInstance().getPlayer(sender.getUniqueId()); - if (opm.isPresent()) { - newFormat = newFormat.replace("%PREFIX%", opm.get().prefix); - newFormat = newFormat.replace("%SUFFIX%", opm.get().suffix); - newFormat = newFormat.replace("%NICK%", opm.get().nick); - newFormat = newFormat.replace("%WORLD%", opm.get().world); - } - - newFormat = newFormat.replace("%DISPLAYNAMET%", receiver.getDisplayName()); - newFormat = newFormat.replace("%NAMET%", receiver.getName()); - - Optional opmt = PlayerMetaManager.getInstance().getPlayer(receiver.getUniqueId()); - if (opmt.isPresent()) { - newFormat = newFormat.replace("%PREFIXT%", opmt.get().prefix); - newFormat = newFormat.replace("%SUFFIXT%", opmt.get().suffix); - newFormat = newFormat.replace("%NICKT%", opmt.get().nick); - newFormat = newFormat.replace("%WORLDT%", opmt.get().world); - } - - newFormat = newFormat.replace("%SERVER%", sender.getServer().getInfo().getName()); - newFormat = newFormat.replace("%SERVERT%", receiver.getServer().getInfo().getName()); - - - if (!ChatModeManager.getInstance().isGlobal(sender.getUniqueId())) { - newFormat = newFormat.replace("%MODE%", "Local"); - newFormat = newFormat.replace("%M%", "L"); - } - - if (ChatModeManager.getInstance().isGlobal(sender.getUniqueId())) { - newFormat = newFormat.replace("%MODE%", "Global"); - newFormat = newFormat.replace("%M%", "G"); - }*/ - - newFormat = newFormat + "%MESSAGE%"; - - BaseComponent[] toSend; - - if (sender.hasPermission("multichat.chat.colour") || sender.hasPermission("multichat.chat.color")) { - - newFormat = newFormat.replace("%MESSAGE%", message); - if (MultiChat.legacyServers.contains(receiver.getServer().getInfo().getName())) { - newFormat = MultiChatUtil.approximateHexCodes(newFormat); - } - toSend = TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', newFormat)); - - } else { - - newFormat = newFormat.replace("%MESSAGE%", ""); - if (MultiChat.legacyServers.contains(receiver.getServer().getInfo().getName())) { - newFormat = MultiChatUtil.approximateHexCodes(newFormat); - } - toSend = TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', newFormat) + message); - } - - return toSend; - - } - - public BaseComponent[] buildFormat(String name, String displayName, String server, String world, ProxiedPlayer receiver, String format, String message) { - - String newFormat = format; - - newFormat = newFormat.replace("%DISPLAYNAME%", displayName); - newFormat = newFormat.replace("%NAME%", name); - newFormat = newFormat.replace("%DISPLAYNAMET%", receiver.getDisplayName()); - newFormat = newFormat.replace("%NAMET%", receiver.getName()); - - Optional opmt = PlayerMetaManager.getInstance().getPlayer(receiver.getUniqueId()); - if (opmt.isPresent()) { - newFormat = newFormat.replace("%PREFIXT%", opmt.get().prefix); - newFormat = newFormat.replace("%SUFFIXT%", opmt.get().suffix); - newFormat = newFormat.replace("%NICKT%", opmt.get().nick); - newFormat = newFormat.replace("%WORLDT%", opmt.get().world); - } - - newFormat = newFormat.replace("%SERVER%", server); - newFormat = newFormat.replace("%SERVERT%", receiver.getServer().getInfo().getName()); - - newFormat = newFormat.replace("%WORLD%", world); - - - /*newFormat = newFormat.replace("%MODE%", "Global"); - newFormat = newFormat.replace("%M%", "G");*/ - - newFormat = newFormat + "%MESSAGE%"; - - BaseComponent[] toSend; - - newFormat = newFormat.replace("%MESSAGE%", message); - if (MultiChat.legacyServers.contains(receiver.getServer().getInfo().getName())) { - newFormat = MultiChatUtil.approximateHexCodes(newFormat); - } - toSend = TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', newFormat)); - - return toSend; - - } - - public void sendToConsole(ProxiedPlayer sender, String format, String message) { - - String newFormat = format; - - newFormat = newFormat.replace("%DISPLAYNAME%", sender.getDisplayName()); - newFormat = newFormat.replace("%NAME%", sender.getName()); - - Optional opm = PlayerMetaManager.getInstance().getPlayer(sender.getUniqueId()); - if (opm.isPresent()) { - newFormat = newFormat.replace("%PREFIX%", opm.get().prefix); - newFormat = newFormat.replace("%SUFFIX%", opm.get().suffix); - newFormat = newFormat.replace("%NICK%", opm.get().nick); - newFormat = newFormat.replace("%WORLD%", opm.get().world); - } - - newFormat = newFormat.replace("%DISPLAYNAMET%", "CONSOLE"); - newFormat = newFormat.replace("%NAMET%", "CONSOLE"); - newFormat = newFormat.replace("%SERVER%", sender.getServer().getInfo().getName()); - newFormat = newFormat.replace("%SERVERT%", "CONSOLE"); - newFormat = newFormat.replace("%WORLDT%", "CONSOLE"); - - /*if (!ChatModeManager.getInstance().isGlobal(sender.getUniqueId())) { - newFormat = newFormat.replace("%MODE%", "Local"); - newFormat = newFormat.replace("%M%", "L"); - } - - if (ChatModeManager.getInstance().isGlobal(sender.getUniqueId())) { - newFormat = newFormat.replace("%MODE%", "Global"); - newFormat = newFormat.replace("%M%", "G"); - }*/ - - newFormat = newFormat + "%MESSAGE%"; - - if (sender.hasPermission("multichat.chat.colour") || sender.hasPermission("multichat.chat.color")) { - - newFormat = newFormat.replace("%MESSAGE%", message); - ConsoleManager.logChat(newFormat); - - } else { - - newFormat = newFormat.replace("%MESSAGE%", ""); - ConsoleManager.logBasicChat(newFormat, message); - - } - - } - - public void sendToConsole(String name, String displayName, String server, String world, String format, String message) { - - String newFormat = format; - - newFormat = newFormat.replace("%DISPLAYNAME%", displayName); - newFormat = newFormat.replace("%NAME%", name); - newFormat = newFormat.replace("%DISPLAYNAMET%", "CONSOLE"); - newFormat = newFormat.replace("%NAMET%", "CONSOLE"); - newFormat = newFormat.replace("%SERVER%", server); - newFormat = newFormat.replace("%SERVERT%", "CONSOLE"); - newFormat = newFormat.replace("%WORLD%", world); - newFormat = newFormat.replace("%WORLDT%", "CONSOLE"); - - /*newFormat = newFormat.replace("%MODE%", "Global"); - newFormat = newFormat.replace("%M%", "G");*/ - - newFormat = newFormat + "%MESSAGE%"; - - newFormat = newFormat.replace("%MESSAGE%", message); - - ConsoleManager.logChat(newFormat); - - } -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatControl.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatControl.java index 443e3e4d..cf8ae1d6 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatControl.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatControl.java @@ -2,7 +2,6 @@ import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -12,24 +11,24 @@ import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; -import net.md_5.bungee.config.Configuration; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyChatControl; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +// TODO: Refactor ChatControl some more at some point public class ChatControl { static { - mutedPlayers = new HashSet(); - ignoreMap = new HashMap>(); - spamMap = new HashMap(); + mutedPlayers = new HashSet<>(); + ignoreMap = new HashMap<>(); + spamMap = new HashMap<>(); } private static Set mutedPlayers; private static Map> ignoreMap; private static Map spamMap; - public static boolean controlLinks = false; - public static String linkRegex = "((https|http):\\/\\/)?(www\\.)?([-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.)+[a-zA-Z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)"; - public static String linkMessage = "[LINK REMOVED]"; - public static Set getMutedPlayers() { return mutedPlayers; } @@ -47,125 +46,26 @@ public static void setIgnoreMap(Map> ignoreMap) { } /** - * + * @param commandSender the sender that rules should be applied for or null * @param input The input message - * @param chatType The type of chat the message was sent in + * @param messageType the type of message to be checked against * @return The message to send with rules applied, or empty if the chat message should be cancelled */ - @SuppressWarnings("rawtypes") - public static OptionalapplyChatRules(String input, String chatType, String playerName) { - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - boolean cancel = false; - - ProxiedPlayer pp = ProxyServer.getInstance().getPlayer(playerName); - - if (config.contains("apply_rules_to." + chatType)) { - if (config.getBoolean("apply_rules_to." + chatType)) { - - List rules = config.getList("regex_rules"); - - if (rules != null) { - for (Object rule : rules) { - Map dictionary = (Map) rule; - - if (pp != null) { - if (dictionary.containsKey("permission")) { - String permission = String.valueOf(dictionary.get("permission")); - if (permission.startsWith("!")) { - permission = permission.substring(1); - if (pp.hasPermission(permission)) continue; - } else { - if (!pp.hasPermission(permission)) continue; - } - } - } - - input = input.replaceAll(String.valueOf( dictionary.get("look_for")), String.valueOf(dictionary.get("replace_with") )); - } - } - - } - } - - if (config.contains("apply_actions_to." + chatType)) { - if (config.getBoolean("apply_actions_to." + chatType)) { - - List actions = config.getList("regex_actions"); - - if (actions != null) { - for (Object action : actions) { - Map dictionary = (Map) action; - - if (input.matches(String.valueOf(dictionary.get("look_for")))) { - - if (pp != null) { - if (dictionary.containsKey("permission")) { - String permission = String.valueOf(dictionary.get("permission")); - if (permission.startsWith("!")) { - permission = permission.substring(1); - if (pp.hasPermission(permission)) continue; - } else { - if (!pp.hasPermission(permission)) continue; - } - } - } - - if ((Boolean) dictionary.get("cancel")) { - cancel = true; - } - - if ((Boolean) dictionary.get("spigot")) { - - ServerInfo server = ProxyServer.getInstance().getPlayer(playerName).getServer().getInfo(); - BungeeComm.sendCommandMessage(String.valueOf(dictionary.get("command")).replaceAll("%PLAYER%", playerName), server); - - } else { - ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), String.valueOf(dictionary.get("command")).replaceAll("%PLAYER%", playerName)); - } - - } - - } - } - - } - } - - if (cancel) { + public static Optional applyChatRules(CommandSender commandSender, String input, MessageType messageType) { + input = ProxyConfigs.CHAT_CONTROL.applyRegexRules(commandSender, input, messageType); + if (commandSender != null && ProxyConfigs.CHAT_CONTROL.regexActionsCancel(commandSender, input, messageType)) return Optional.empty(); - } else { - return Optional.of(input); - } - + return Optional.of(input); } - public static boolean isMuted(UUID uuid, String chatType) { - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (!config.getBoolean("mute")) return false; - - if (!mutedPlayers.contains(uuid)) return false; - - if (!config.contains("apply_mute_to." + chatType)) return false; - - if (!config.getBoolean("apply_mute_to." + chatType)) return false; - - return true; - + public static boolean isMuted(UUID uuid, MessageType messageType) { + return ProxyConfigs.CHAT_CONTROL.isMute() + && mutedPlayers.contains(uuid) + && ProxyConfigs.CHAT_CONTROL.applyMuteTo(messageType); } public static boolean isMutedAnywhere(UUID uuid) { - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (!config.getBoolean("mute")) return false; - - if (!mutedPlayers.contains(uuid)) return false; - - return true; - + return ProxyConfigs.CHAT_CONTROL.isMute() && mutedPlayers.contains(uuid); } public static void mute(UUID uuid) { @@ -186,25 +86,8 @@ public static void unmute(UUID uuid) { * @param target The player who will see the message * @return TRUE if the target ignores the sender and the message should not be sent, FALSE otherwise */ - public static boolean ignores(UUID sender, UUID target, String chatType) { - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (!ignoreMap.containsKey(target)) return false; - - Set ignoredPlayers = ignoreMap.get(target); - - if (ignoredPlayers == null) return false; - - if (!ignoredPlayers.contains(sender)) return false; - - if (!config.contains("apply_ignore_to." + chatType)) return false; - - if (!config.getBoolean("apply_ignore_to." + chatType)) return false; - - - return true; - + public static boolean ignores(UUID sender, UUID target, MessageType messageType) { + return ignoresAnywhere(sender, target) && ProxyConfigs.CHAT_CONTROL.applyIgnoreTo(messageType); } /** @@ -214,17 +97,8 @@ public static boolean ignores(UUID sender, UUID target, String chatType) { * @return TRUE if the target ignores the sender and the message should not be sent, FALSE otherwise */ public static boolean ignoresAnywhere(UUID sender, UUID target) { - - if (!ignoreMap.containsKey(target)) return false; - Set ignoredPlayers = ignoreMap.get(target); - - if (ignoredPlayers == null) return false; - - if (!ignoredPlayers.contains(sender)) return false; - - return true; - + return ignoredPlayers != null && ignoredPlayers.contains(sender); } public static void ignore(UUID ignorer, UUID ignoree) { @@ -237,7 +111,7 @@ public static void ignore(UUID ignorer, UUID ignoree) { } else { - ignoredPlayers = new HashSet(); + ignoredPlayers = new HashSet<>(); } @@ -277,16 +151,13 @@ public static void unignoreAll(UUID ignorer) { } public static void sendIgnoreNotifications(CommandSender ignorer, CommandSender ignoree, String chatType) { - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (config.getBoolean("notify_ignore")) { - MessageManager.sendSpecialMessage(ignorer, "ignore_target", ignoree.getName()); + if (ProxyConfigs.CHAT_CONTROL.isNotifyIgnore()) { + ProxyConfigs.MESSAGES.sendMessage(ignorer, "ignore_target", ignoree.getName()); } if (!chatType.equals("private_messages")) return; - MessageManager.sendMessage(ignoree, "ignore_sender"); + ProxyConfigs.MESSAGES.sendMessage(ignoree, "ignore_sender"); } @@ -294,27 +165,10 @@ public static void sendIgnoreNotifications(CommandSender ignorer, CommandSender * If sessional ignore is enabled, removes any offline players from the ignore map */ public static void reload() { + if (!ProxyConfigs.CHAT_CONTROL.isSessionIgnore()) + return; - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (config.getBoolean("session_ignore")) { - - for (UUID uuid : ignoreMap.keySet()) { - - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (player == null) ignoreMap.remove(uuid); - - } - - } - - } - - public static String replaceLinks(String message) { - if (!controlLinks) return message; - return message.replaceAll(linkRegex, linkMessage); - //return message.replaceAll("((https|http):\\/\\/)?(www\\.)?([-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.)+[a-zA-Z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)", linkMessage); + ignoreMap.keySet().removeIf(uuid -> ProxyServer.getInstance().getPlayer(uuid) == null); } public static void spamPardonPlayer(UUID uuid) { @@ -325,25 +179,23 @@ public static void spamPardonPlayer(UUID uuid) { * * @return true if the player is spamming and the message should be blocked */ - public static boolean handleSpam(ProxiedPlayer player, String message, String chatType) { + public static boolean handleSpam(ProxiedPlayer player, String message, MessageType messageType) { DebugManager.log(player.getName() + " - checking for spam..."); - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); + ProxyChatControl config = ProxyConfigs.CHAT_CONTROL; if (player.hasPermission("multichat.spam.bypass")) return false; DebugManager.log(player.getName() + " - does not have bypass perm..."); - if (!config.getBoolean("anti_spam")) return false; + if (!config.isAntiSpam()) return false; DebugManager.log(player.getName() + " - anti spam IS enabled..."); - if (!config.contains("apply_anti_spam_to." + chatType)) return false; - - if (!config.getBoolean("apply_anti_spam_to." + chatType)) return false; + if (!config.applyAntiSpamTo(messageType)) return false; - DebugManager.log(player.getName() + " - anti spam IS enabled for " + chatType + "..."); + DebugManager.log(player.getName() + " - anti spam IS enabled for " + messageType.toString() + "..."); if (!spamMap.containsKey(player.getUniqueId())) spamMap.put(player.getUniqueId(), new PlayerSpamInfo()); @@ -355,25 +207,25 @@ public static boolean handleSpam(ProxiedPlayer player, String message, String ch DebugManager.log(player.getName() + " - PLAYER IS SPAMMING!"); - MessageManager.sendSpecialMessage(player, "anti_spam_cooldown", String.valueOf(spamInfo.getCooldownSeconds())); + ProxyConfigs.MESSAGES.sendMessage(player, "anti_spam_cooldown", String.valueOf(spamInfo.getCooldownSeconds())); DebugManager.log(player.getName() + " - sent cooldown message to player..."); - if (spamInfo.getSpamTriggerCount() >= config.getInt("anti_spam_trigger")) { + if (spamInfo.getSpamTriggerCount() >= config.getAntiSpamTrigger()) { DebugManager.log(player.getName() + " - they have set off the trigger..."); spamInfo.resetSpamTriggerCount(); - if (config.getBoolean("anti_spam_action")) { + if (config.isAntiSpamAction()) { DebugManager.log(player.getName() + " - trigger IS enabled..."); - if (config.getBoolean("anti_spam_spigot")) { + if (config.isAntiSpamSpigot()) { ServerInfo server = player.getServer().getInfo(); - BungeeComm.sendCommandMessage(config.getString("anti_spam_command").replaceAll("%PLAYER%", player.getName()), server); + ProxyLocalCommunicationManager.sendCommandMessage(config.getAntiSpamCommand().replaceAll("%PLAYER%", player.getName()), server); } else { - ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), config.getString("anti_spam_command").replaceAll("%PLAYER%", player.getName())); + ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), config.getAntiSpamCommand().replaceAll("%PLAYER%", player.getName())); } } @@ -392,7 +244,7 @@ public static class PlayerSpamInfo { int spamTriggerCount = 0; long lastSpamTime = 0L; - long messageTimeBuffer[] = {0L, 0L, 0L}; + long[] messageTimeBuffer = {0L, 0L, 0L}; int sameMessageCounter = 0; String lastMessage = ""; @@ -404,10 +256,10 @@ public boolean checkSpam(String message) { boolean spam = false; long currentTime = System.currentTimeMillis(); - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); + int antiSpamTime = ProxyConfigs.CHAT_CONTROL.getAntiSpamTime(); // If the user triggered anti-spam, check if they are still on cooldown - if (currentTime - lastSpamTime < (1000 * config.getInt("anti_spam_cooldown"))) return true; + if (currentTime - lastSpamTime < (1000 * ProxyConfigs.CHAT_CONTROL.getAntiSpamCoolDown())) return true; long deltaTime = currentTime - messageTimeBuffer[2]; @@ -415,7 +267,7 @@ public boolean checkSpam(String message) { // This is a hard coded test. If the same message is sent 4 times in a row, it is spam... // However; this extra bit states that if it has been longer than 10 times the usual spam time // then this should not be considered spam. And hence the counter is reset. - if ((currentTime - messageTimeBuffer[0]) < (1000 * config.getInt("anti_spam_time")*10)) { + if ((currentTime - messageTimeBuffer[0]) < (1000 * antiSpamTime*10)) { sameMessageCounter++; } else { sameMessageCounter = 0; @@ -428,8 +280,8 @@ public boolean checkSpam(String message) { rotateMessages(currentTime); // Max messages in time limit or same message in row check - if (deltaTime < (1000 * config.getInt("anti_spam_time")) - || !(sameMessageCounter + 1 < config.getInt("spam_same_message"))) { + if (deltaTime < (1000 * antiSpamTime) + || !(sameMessageCounter + 1 < ProxyConfigs.CHAT_CONTROL.getSpamSameMessage())) { spam = true; lastSpamTime = currentTime; spamTriggerCount++; @@ -453,8 +305,7 @@ public void resetSpamTriggerCount() { } public long getCooldownSeconds() { - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - return config.getInt("anti_spam_cooldown") - ((System.currentTimeMillis() - lastSpamTime)/1000); + return ProxyConfigs.CHAT_CONTROL.getAntiSpamCoolDown() - ((System.currentTimeMillis() - lastSpamTime)/1000); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatManipulation.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatManipulation.java index 17540d89..106b8c3a 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatManipulation.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatManipulation.java @@ -6,6 +6,8 @@ import com.olivermartin410.plugins.TGroupChatInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * LEGACY ** TO BE REMOVED ** Chat Manipulation Class @@ -20,7 +22,7 @@ public class ChatManipulation { public String replaceMsgVars(String messageFormat, String message, ProxiedPlayer sender, ProxiedPlayer target) { - messageFormat = messageFormat.replace("%MESSAGE%", message); + //messageFormat = messageFormat.replace("%MESSAGE%", message); messageFormat = messageFormat.replace("%DISPLAYNAME%", sender.getDisplayName()); messageFormat = messageFormat.replace("%NAME%", sender.getName()); @@ -43,17 +45,17 @@ public String replaceMsgVars(String messageFormat, String message, ProxiedPlayer messageFormat = messageFormat.replace("%SERVER%", sender.getServer().getInfo().getName()); messageFormat = messageFormat.replace("%SERVERT%", target.getServer().getInfo().getName()); - + messageFormat = messageFormat.replace("%WORLD%", opm.get().world); messageFormat = messageFormat.replace("%WORLDT%", opmt.get().world); - + return messageFormat; } public String replaceMsgConsoleTargetVars(String messageFormat, String message, ProxiedPlayer sender) { - messageFormat = messageFormat.replace("%MESSAGE%", message); + //messageFormat = messageFormat.replace("%MESSAGE%", message); messageFormat = messageFormat.replace("%DISPLAYNAME%", sender.getDisplayName()); messageFormat = messageFormat.replace("%NAME%", sender.getName()); @@ -73,17 +75,17 @@ public String replaceMsgConsoleTargetVars(String messageFormat, String message, messageFormat = messageFormat.replace("%SERVER%", sender.getServer().getInfo().getName()); messageFormat = messageFormat.replace("%SERVERT%", "CONSOLE"); - + messageFormat = messageFormat.replace("%WORLD%", opm.get().world); messageFormat = messageFormat.replace("%WORLDT%", "CONSOLE"); - + return messageFormat; } public String replaceMsgConsoleSenderVars(String messageFormat, String message, ProxiedPlayer target) { - messageFormat = messageFormat.replace("%MESSAGE%", message); + //messageFormat = messageFormat.replace("%MESSAGE%", message); messageFormat = messageFormat.replace("%DISPLAYNAME%", "CONSOLE"); messageFormat = messageFormat.replace("%NAME%", "CONSOLE"); @@ -103,53 +105,60 @@ public String replaceMsgConsoleSenderVars(String messageFormat, String message, messageFormat = messageFormat.replace("%SERVER%", "CONSOLE"); messageFormat = messageFormat.replace("%SERVERT%", target.getServer().getInfo().getName()); - + messageFormat = messageFormat.replace("%WORLD%", "CONSOLE"); messageFormat = messageFormat.replace("%WORLDT%", opmt.get().world); - + return messageFormat; } public String replaceModChatVars(String messageFormat, String playername, String displayname, String server, String message, ProxiedPlayer target) { + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + messageFormat = messageFormat.replace("%DISPLAYNAME%", displayname); messageFormat = messageFormat.replace("%NAME%", playername); messageFormat = messageFormat.replace("%SERVER%", server); - messageFormat = messageFormat.replace("%MESSAGE%", message); - messageFormat = messageFormat.replace("%CC%", "&" + ((TChatInfo)MultiChat.modchatpreferences.get(target.getUniqueId())).getChatColor()); - messageFormat = messageFormat.replace("%NC%", "&" + ((TChatInfo)MultiChat.modchatpreferences.get(target.getUniqueId())).getNameColor()); + //messageFormat = messageFormat.replace("%MESSAGE%", message); + messageFormat = messageFormat.replace("%CC%", "&" + ((TChatInfo)ds.getModChatPreferences().get(target.getUniqueId())).getChatColor()); + messageFormat = messageFormat.replace("%NC%", "&" + ((TChatInfo)ds.getModChatPreferences().get(target.getUniqueId())).getNameColor()); return messageFormat; } public String replaceAdminChatVars(String messageFormat, String playername, String displayname, String server, String message, ProxiedPlayer target) { + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + messageFormat = messageFormat.replace("%DISPLAYNAME%",displayname); messageFormat = messageFormat.replace("%NAME%", playername); messageFormat = messageFormat.replace("%SERVER%", server); - messageFormat = messageFormat.replace("%MESSAGE%", message); - messageFormat = messageFormat.replace("%CC%", "&" + ((TChatInfo)MultiChat.adminchatpreferences.get(target.getUniqueId())).getChatColor()); - messageFormat = messageFormat.replace("%NC%", "&" + ((TChatInfo)MultiChat.adminchatpreferences.get(target.getUniqueId())).getNameColor()); + //messageFormat = messageFormat.replace("%MESSAGE%", message); + messageFormat = messageFormat.replace("%CC%", "&" + ((TChatInfo)ds.getAdminChatPreferences().get(target.getUniqueId())).getChatColor()); + messageFormat = messageFormat.replace("%NC%", "&" + ((TChatInfo)ds.getAdminChatPreferences().get(target.getUniqueId())).getNameColor()); return messageFormat; } public String replaceGroupChatVars(String messageFormat, String sendername, String message, String groupName) { + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + messageFormat = messageFormat.replace("%NAME%", sendername); - messageFormat = messageFormat.replace("%MESSAGE%", message); - messageFormat = messageFormat.replace("%CC%", "&" + ((TGroupChatInfo)MultiChat.groupchats.get(groupName)).getChatColor()); - messageFormat = messageFormat.replace("%NC%", "&" + ((TGroupChatInfo)MultiChat.groupchats.get(groupName)).getNameColor()); + //messageFormat = messageFormat.replace("%MESSAGE%", message); + messageFormat = messageFormat.replace("%CC%", "&" + ((TGroupChatInfo)ds.getGroupChats().get(groupName)).getChatColor()); + messageFormat = messageFormat.replace("%NC%", "&" + ((TGroupChatInfo)ds.getGroupChats().get(groupName)).getNameColor()); messageFormat = messageFormat.replace("%GROUPNAME%", groupName.toUpperCase()); return messageFormat; } - public String replaceJoinMsgVars(String MessageFormat, String sendername) { + public String replaceJoinMsgVars(String messageFormat, String senderName, String serverName) { - MessageFormat = MessageFormat.replace("%NAME%", sendername); - return MessageFormat; + messageFormat = messageFormat.replace("%NAME%", senderName); + messageFormat = messageFormat.replace("%SERVER%", serverName); + return messageFormat; } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatModeManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatModeManager.java index 90ab8072..c9b584e0 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatModeManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ChatModeManager.java @@ -6,6 +6,10 @@ import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; public class ChatModeManager { @@ -29,43 +33,61 @@ private ChatModeManager() { public void setLocal(UUID uuid) { + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + globalPlayers.put(uuid, false); // TODO - Channel.setChannel(uuid, Channel.getLocalChannel()); + //LegacyChannel.setChannel(uuid, LegacyChannel.getLocalChannel()); + channelManager.select(uuid, "local"); // TODO ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); if (player == null) return; - Channel local = Channel.getLocalChannel(); + /*LegacyChannel local = LegacyChannel.getLocalChannel(); if (!local.isMember(uuid)) { local.removeMember(uuid); MessageManager.sendSpecialMessage(player, "command_channel_show", "LOCAL"); + }*/ + + if (channelManager.isHidden(uuid, "local")) { + channelManager.show(uuid, "local"); + ProxyConfigs.MESSAGES.sendMessage(player, "command_channel_show", "LOCAL"); } - BungeeComm.sendPlayerChannelMessage(player.getName(), Channel.getChannel(uuid).getName(), Channel.getChannel(uuid), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); + // TODO + //ProxyLocalCommunicationManager.sendPlayerDataMessage(player.getName(), LegacyChannel.getChannel(uuid).getName(), LegacyChannel.getChannel(uuid), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); + ProxyLocalCommunicationManager.sendPlayerDataMessage(player.getName(), "local", channelManager.getLocalChannel().getFormat(), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); } public void setGlobal(UUID uuid) { + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + globalPlayers.put(uuid, true); // TODO - Channel.setChannel(uuid, Channel.getGlobalChannel()); + channelManager.select(uuid, "global"); + //LegacyChannel.setChannel(uuid, LegacyChannel.getGlobalChannel()); // TODO ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); if (player == null) return; - Channel global = Channel.getGlobalChannel(); + /*LegacyChannel global = LegacyChannel.getGlobalChannel(); if (!global.isMember(uuid)) { global.removeMember(uuid); MessageManager.sendSpecialMessage(player, "command_channel_show", "GLOBAL"); + }*/ + + if (channelManager.isHidden(uuid, "global")) { + channelManager.show(uuid, "global"); + ProxyConfigs.MESSAGES.sendMessage(player, "command_channel_show", "GLOBAL"); } - BungeeComm.sendPlayerChannelMessage(player.getName(), Channel.getChannel(uuid).getName(), Channel.getChannel(uuid), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); + ProxyLocalCommunicationManager.sendPlayerDataMessage(player.getName(), "global", channelManager.getGlobalChannel().getInfo().getFormat(), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CommandManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CommandManager.java index 0383c000..0bc159e8 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CommandManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/CommandManager.java @@ -17,6 +17,7 @@ import xyz.olivermartin.multichat.bungee.commands.HelpMeCommand; import xyz.olivermartin.multichat.bungee.commands.IgnoreCommand; import xyz.olivermartin.multichat.bungee.commands.LocalCommand; +import xyz.olivermartin.multichat.bungee.commands.LocalSpyCommand; import xyz.olivermartin.multichat.bungee.commands.MCCCommand; import xyz.olivermartin.multichat.bungee.commands.MCCommand; import xyz.olivermartin.multichat.bungee.commands.MsgCommand; @@ -29,6 +30,7 @@ import xyz.olivermartin.multichat.bungee.commands.StaffListCommand; import xyz.olivermartin.multichat.bungee.commands.UseCastCommand; +// TODO: [2.0] Definitely needs refactor public class CommandManager { static { @@ -49,6 +51,7 @@ public class CommandManager { helpme = new HelpMeCommand(); ignore = new IgnoreCommand(); local = new LocalCommand(); + localspy = new LocalSpyCommand(); mcc = new MCCCommand(); mc = new MCCommand(); msg = new MsgCommand(); @@ -79,6 +82,7 @@ public class CommandManager { private static Command helpme; private static Command ignore; private static Command local; + private static Command localspy; private static Command mcc; private static Command mc; private static Command msg; @@ -418,6 +422,18 @@ public static Command getUsecast() { public static void setUsecast(Command usecast) { CommandManager.usecast = usecast; } + /** + * @return the localspy + */ + public static Command getLocalspy() { + return localspy; + } + /** + * @param localspy the localspy to set + */ + public static void setLocalspy(Command localspy) { + CommandManager.localspy = localspy; + } /** * Generates new instances of all commands @@ -439,6 +455,7 @@ public static void reload() { helpme = new HelpMeCommand(); ignore = new IgnoreCommand(); local = new LocalCommand(); + localspy = new LocalSpyCommand(); mcc = new MCCCommand(); mc = new MCCommand(); msg = new MsgCommand(); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConfigHandler.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConfigHandler.java deleted file mode 100644 index 913ec557..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConfigHandler.java +++ /dev/null @@ -1,105 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.CopyOption; -import java.nio.file.Files; - -import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.config.Configuration; -import net.md_5.bungee.config.ConfigurationProvider; -import net.md_5.bungee.config.YamlConfiguration; - -/** - * Configuration Handler Class - *

Manages loading / creation of an individual configuration file

- * - * @author Oliver Martin (Revilo410) - * - */ -public class ConfigHandler { - - // The config file - private Configuration config; - // Path of config file - private File configPath; - // Name of config file - private String fileName; - - public ConfigHandler(File configPath, String fileName) { - - this.configPath = configPath; - this.config = null; - this.fileName = fileName; - this.startupConfig(); - - } - - public Configuration getConfig() { - if (config == null) startupConfig(); - return config; - } - - public void startupConfig() { - - try { - - File file = new File(configPath, fileName); - - if (!file.exists()) { - - ProxyServer.getInstance().getLogger().info("Config file " + fileName + " not found... Creating new one."); - saveDefaultConfig(); - - loadConfig(); - - } else { - - ProxyServer.getInstance().getLogger().info("Loading " + fileName + "..."); - loadConfig(); - - } - - } catch (Exception e) { - ProxyServer.getInstance().getLogger().info("[ERROR] Could not load " + fileName); - e.printStackTrace(); - } - } - - private void saveDefaultConfig() { - - // Load default file into input stream - InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); - - // Copy to desired location - try { - Files.copy(inputStream, new File(configPath, fileName).toPath(), new CopyOption[0]); - } catch (IOException e) { - ProxyServer.getInstance().getLogger().info("[ERROR] Could not create new " + fileName + " file..."); - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - private void loadConfig() { - - try { - - this.config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(new File(configPath, fileName)); - - } catch (IOException e) { - - ProxyServer.getInstance().getLogger().info("[ERROR] Could not load " + fileName + " file..."); - e.printStackTrace(); - - } - } -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConfigManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConfigManager.java deleted file mode 100644 index 7582a4e0..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConfigManager.java +++ /dev/null @@ -1,71 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Configuration Manager Class - *

Manages all access and creation of the config.yml file

- * - * @author Oliver Martin (Revilo410) - * - */ -public class ConfigManager { - - private static ConfigManager instance; - - static { - - instance = new ConfigManager(); - - } - - public static ConfigManager getInstance() { - return instance; - } - - // END OF STATIC - - private Map handlerMap; - - private ConfigManager() { - - handlerMap = new HashMap(); - - } - - /** - * Create a new configHandler for a given filename and path - * @param fileName filename i.e. config.yml - * @param configPath THE PATH WITHOUT THE FILE NAME - */ - public void registerHandler(String fileName, File configPath) { - - handlerMap.put(fileName, new ConfigHandler(configPath, fileName)); - - } - - public Optional getSafeHandler(String fileName) { - - if (handlerMap.containsKey(fileName)) { - return Optional.of(handlerMap.get(fileName)); - } - - return Optional.empty(); - - } - - public ConfigHandler getHandler(String fileName) { - - if (handlerMap.containsKey(fileName)) { - return handlerMap.get(fileName); - } - - return null; - - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConsoleManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConsoleManager.java index a974d60f..bdc080a3 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConsoleManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConsoleManager.java @@ -1,12 +1,13 @@ package xyz.olivermartin.multichat.bungee; -import java.util.Arrays; -import java.util.stream.Stream; - -import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.Arrays; +import java.util.stream.Stream; public class ConsoleManager { @@ -15,71 +16,73 @@ public static void log(String message) { } public static void logDisplayMessage(String message) { - logToConsole(MessageManager.getMessage("console_display_prefix") + message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_display_prefix") + message); } public static void logChat(String message) { - logToConsole(MessageManager.getMessage("console_chat_prefix") + message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_chat_prefix") + message); } public static void logModChat(String message) { - if (!MultiChat.logStaffChat) { + if (!ProxyConfigs.CONFIG.isLogStaffChat()) { return; } - logToConsole(MessageManager.getMessage("console_modchat_prefix") + message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_modchat_prefix") + message); } public static void logGroupChat(String message) { - if (!MultiChat.logGroupChat) { + if (!ProxyConfigs.CONFIG.isLogGroupChat()) { return; } - logToConsole(MessageManager.getMessage("console_groupchat_prefix") + message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_groupchat_prefix") + message); } public static void logAdminChat(String message) { - if (!MultiChat.logStaffChat) { + if (!ProxyConfigs.CONFIG.isLogStaffChat()) { return; } - logToConsole(MessageManager.getMessage("console_adminchat_prefix") + message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_adminchat_prefix") + message); } public static void logHelpMe(String message) { - logToConsole(MessageManager.getMessage("console_helpme_prefix") + message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_helpme_prefix") + message); } public static void logBasicChat(String prefix, String message) { - logToConsole(MessageManager.getMessage("console_chat_prefix") + prefix, message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_chat_prefix") + prefix, message); } public static void logSocialSpy(String p1, String p2, String message) { - if (!MultiChat.logPMs) { + if (!ProxyConfigs.CONFIG.isLogPms()) { return; } - logToConsole(MessageManager.getMessage("console_socialspy_prefix") + "(" + p1 + " -> " + p2 + ") " + message); + logToConsole(ProxyConfigs.MESSAGES.getMessage("console_socialspy_prefix") + "(" + p1 + " -> " + p2 + ") " + message); } private static void logToConsole(String message, String unformattedMessage) { BaseComponent[] first = TextComponent.fromLegacyText( - ChatColor.translateAlternateColorCodes('&', MessageManager.getMessage("console_main_prefix") + MultiChatUtil.approximateHexCodes(MultiChatUtil.reformatRGB(message)))); + MultiChatUtil.approximateRGBColorCodes( + MultiChatUtil.translateColorCodes( + ProxyConfigs.MESSAGES.getMessage("console_main_prefix") + message))); BaseComponent[] second = TextComponent.fromLegacyText(unformattedMessage); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Events.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Events.java index f88aa543..3ff2f3ae 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Events.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Events.java @@ -2,32 +2,29 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.UUID; -import java.util.concurrent.TimeUnit; -import com.olivermartin410.plugins.TChatInfo; import com.olivermartin410.plugins.TGroupChatInfo; -import de.myzelyam.api.vanish.BungeeVanishAPI; -import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.ComponentBuilder; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.ChatEvent; -import net.md_5.bungee.api.event.PlayerDisconnectEvent; -import net.md_5.bungee.api.event.PostLoginEvent; -import net.md_5.bungee.api.event.ServerSwitchEvent; import net.md_5.bungee.api.plugin.Listener; -import net.md_5.bungee.config.Configuration; import net.md_5.bungee.event.EventHandler; -import net.md_5.bungee.event.EventPriority; import xyz.olivermartin.multichat.bungee.commands.GCCommand; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyChatManager; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelMode; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.ProxyChannel; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * Events Manager @@ -40,13 +37,11 @@ public class Events implements Listener { public static List mcbPlayers = new ArrayList(); - private static List MCToggle = new ArrayList(); - private static List ACToggle = new ArrayList(); - private static List GCToggle = new ArrayList(); + public static List MCToggle = new ArrayList(); + public static List ACToggle = new ArrayList(); + public static List GCToggle = new ArrayList(); public static Map PMToggle = new HashMap(); - public static Set hiddenStaff = new HashSet(); - public static boolean toggleMC(UUID uuid) { if (MCToggle.contains(uuid)) { @@ -138,6 +133,9 @@ public static boolean togglePM(UUID uuid, UUID uuidt) { @EventHandler(priority=64) public void onChat(ChatEvent event) { + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + ProxyChatManager chatManager = MultiChatProxy.getInstance().getChatManager(); ProxiedPlayer player = (ProxiedPlayer) event.getSender(); // New null pointer checks @@ -157,9 +155,9 @@ public void onChat(ChatEvent event) { } /// - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { + if (ProxyConfigs.CONFIG.isFetchSpigotDisplayNames()) { if (player.getServer() != null) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(player.getName(), player.getServer().getInfo()); } } /// @@ -202,13 +200,13 @@ public void onChat(ChatEvent event) { event.setCancelled(true); - if (MultiChat.viewedchats.get(player.getUniqueId()) != null) { + if (ds.getViewedChats().get(player.getUniqueId()) != null) { - String chatName = ((String)MultiChat.viewedchats.get(player.getUniqueId())).toLowerCase(); + String chatName = ((String)ds.getViewedChats().get(player.getUniqueId())).toLowerCase(); - if (MultiChat.groupchats.containsKey(chatName)) { + if (ds.getGroupChats().containsKey(chatName)) { - TGroupChatInfo chatInfo = (TGroupChatInfo)MultiChat.groupchats.get(chatName); + TGroupChatInfo chatInfo = (TGroupChatInfo)ds.getGroupChats().get(chatName); String playerName = player.getName(); if ((chatInfo.getFormal() == true) @@ -221,13 +219,13 @@ public void onChat(ChatEvent event) { GCCommand.sendMessage(message, playerName, chatInfo); } else { - MessageManager.sendMessage(player, "groups_toggled_but_no_longer_exists_1"); - MessageManager.sendMessage(player, "groups_toggled_but_no_longer_exists_2"); + ProxyConfigs.MESSAGES.sendMessage(player, "groups_toggled_but_no_longer_exists_1"); + ProxyConfigs.MESSAGES.sendMessage(player, "groups_toggled_but_no_longer_exists_2"); } } else { - MessageManager.sendMessage(player, "groups_toggled_but_no_longer_exists_1"); - MessageManager.sendMessage(player, "groups_toggled_but_no_longer_exists_2"); + ProxyConfigs.MESSAGES.sendMessage(player, "groups_toggled_but_no_longer_exists_1"); + ProxyConfigs.MESSAGES.sendMessage(player, "groups_toggled_but_no_longer_exists_2"); } } } @@ -242,16 +240,16 @@ public void onChat(ChatEvent event) { event.setCancelled(true); - if (ChatControl.isMuted(player.getUniqueId(), "private_messages")) { - MessageManager.sendMessage(player, "mute_cannot_send_message"); + if (ChatControl.isMuted(player.getUniqueId(), MessageType.PRIVATE_MESSAGES)) { + ProxyConfigs.MESSAGES.sendMessage(player, "mute_cannot_send_message"); return; } - if (ChatControl.handleSpam(player, message, "private_messages")) { + if (ChatControl.handleSpam(player, message, MessageType.PRIVATE_MESSAGES)) { return; } - crm = ChatControl.applyChatRules(message, "private_messages", player.getName()); + crm = ChatControl.applyChatRules(player, message, MessageType.PRIVATE_MESSAGES); if (crm.isPresent()) { message = crm.get(); @@ -263,14 +261,14 @@ public void onChat(ChatEvent event) { ProxiedPlayer target = ProxyServer.getInstance().getPlayer((UUID)PMToggle.get(player.getUniqueId())); - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - BungeeComm.sendMessage(target.getName(), target.getServer().getInfo()); + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(player.getName(), player.getServer().getInfo()); + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(target.getName(), target.getServer().getInfo()); - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(player.getServer().getInfo().getName())) { + if (!ProxyConfigs.CONFIG.isNoPmServer(player.getServer().getInfo().getName())) { - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(target.getServer().getInfo().getName())) { + if (!ProxyConfigs.CONFIG.isNoPmServer(target.getServer().getInfo().getName())) { - if (ChatControl.ignores(player.getUniqueId(), target.getUniqueId(), "private_messages")) { + if (ChatControl.ignores(player.getUniqueId(), target.getUniqueId(), MessageType.PRIVATE_MESSAGES)) { ChatControl.sendIgnoreNotifications(target, player, "private_messages"); return; } @@ -278,15 +276,15 @@ public void onChat(ChatEvent event) { PrivateMessageManager.getInstance().sendMessage(message, player, target); } else { - MessageManager.sendMessage(player, "command_msg_disabled_target"); + ProxyConfigs.MESSAGES.sendMessage(player, "command_msg_disabled_target"); } } else { - MessageManager.sendMessage(player, "command_msg_disabled_sender"); + ProxyConfigs.MESSAGES.sendMessage(player, "command_msg_disabled_sender"); } } else { - MessageManager.sendMessage(player, "command_msg_not_online"); + ProxyConfigs.MESSAGES.sendMessage(player, "command_msg_not_online"); } } @@ -320,7 +318,16 @@ public void onChat(ChatEvent event) { String message = MultiChatUtil.getMessageFromArgs(parts, 1); - CastControl.sendCast(parts[0].substring(1),message,Channel.getChannel(playerSender.getUniqueId()), playerSender); + if (channelManager.getChannelMode(player.getUniqueId()) == ChannelMode.LOCAL) { + + CastControl.sendCast(parts[0].substring(1),message,channelManager.getLocalChannel(), player.getServer().getInfo().getName(), playerSender); + + } else { + + ProxyChannel pc = channelManager.getProxyChannel(channelManager.getChannel(player)).get(); // TODO unsafe + CastControl.sendCast(parts[0].substring(1),message,pc, playerSender); + + } event.setCancelled(true); @@ -330,7 +337,7 @@ public void onChat(ChatEvent event) { String message = MultiChatUtil.getMessageFromArgs(parts, 1); - CastControl.sendCast(parts[0].substring(1), message, Channel.getGlobalChannel(), ProxyServer.getInstance().getConsole()); + CastControl.sendCast(parts[0].substring(1), message, channelManager.getGlobalChannel(), ProxyServer.getInstance().getConsole()); event.setCancelled(true); @@ -340,320 +347,59 @@ public void onChat(ChatEvent event) { if ((!event.isCancelled()) && (!event.isCommand())) { - //TODO? I removed these checks... I think thats good... if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("global") == true) { - - //TODO ? if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_global").contains(player.getServer().getInfo().getName())) { - - /*if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - if (player.getServer() != null) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - }*/ - - if ((!MultiChat.frozen) || (player.hasPermission("multichat.chat.always"))) { - - String message = event.getMessage(); - - if (ChatControl.isMuted(player.getUniqueId(), "global_chat")) { - MessageManager.sendMessage(player, "mute_cannot_send_message"); - event.setCancelled(true); - return; - } - - DebugManager.log(player.getName() + "- about to check for spam"); - - if (ChatControl.handleSpam(player, message, "global_chat")) { - DebugManager.log(player.getName() + " - chat message being cancelled due to spam"); - event.setCancelled(true); - return; - } - - Optional crm; - - crm = ChatControl.applyChatRules(message, "global_chat", player.getName()); - - if (crm.isPresent()) { - message = crm.get(); - event.setMessage(message); - } else { - event.setCancelled(true); - return; - } - - if (!player.hasPermission("multichat.chat.link")) { - message = ChatControl.replaceLinks(message); - event.setMessage(message); - } - - DebugManager.log("Does player have ALL colour permission? " + (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color"))); - - DebugManager.log("Does player have simple colour permission? " + (player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple"))); - - DebugManager.log("Does player have rgb colour permission? " + (player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); - - // Let server know players channel preference - BungeeComm.sendPlayerChannelMessage(player.getName(), Channel.getChannel(player.getUniqueId()).getName(), Channel.getChannel(player.getUniqueId()), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); - - // Message passes through to spigot here - - if (hiddenStaff.contains(player.getUniqueId())) { - hiddenStaff.remove(player.getUniqueId()); - } + String message = event.getMessage(); // Current message + + Optional optionalMessage = chatManager.handleChatMessage(player, message); // Processed message - } else { - MessageManager.sendMessage(player, "freezechat_frozen"); + if (!optionalMessage.isPresent()) { + // Player not permitted to send this message, so cancel it event.setCancelled(true); - } - - } - //TODO ?} - //TODO? } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onLogin(PostLoginEvent event) { - - ProxiedPlayer player = event.getPlayer(); - UUID uuid = player.getUniqueId(); - boolean firstJoin = false; - - if (player.hasPermission("multichat.staff.mod")) { - - if (!MultiChat.modchatpreferences.containsKey(uuid)) { - - TChatInfo chatinfo = new TChatInfo(); - chatinfo.setChatColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("modchat.ccdefault").toCharArray()[0]); - chatinfo.setNameColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("modchat.ncdefault").toCharArray()[0]); - MultiChat.modchatpreferences.put(uuid, chatinfo); - - } - } - - if (player.hasPermission("multichat.staff.admin")) { - - if (!MultiChat.adminchatpreferences.containsKey(uuid)) { - - TChatInfo chatinfo = new TChatInfo(); - chatinfo.setChatColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("adminchat.ccdefault").toCharArray()[0]); - chatinfo.setNameColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("adminchat.ncdefault").toCharArray()[0]); - MultiChat.adminchatpreferences.put(uuid, chatinfo); - - } - } - - PlayerMetaManager.getInstance().registerPlayer(uuid, event.getPlayer().getName()); - - if (!MultiChat.viewedchats.containsKey(uuid)) { - - MultiChat.viewedchats.put(uuid, null); - ConsoleManager.log("Registered player " + player.getName()); - - } - - if (!ChatModeManager.getInstance().existsPlayer(uuid)) { - - boolean globalMode; - if (!MultiChat.defaultChannel.equalsIgnoreCase("local")) { - globalMode = true; - } else { - globalMode = false; - } - ChatModeManager.getInstance().registerPlayer(uuid, globalMode); - firstJoin = true; - //ConsoleManager.log("Created new global chat entry for " + player.getName()); - - } - - if (MultiChat.forceChannelOnJoin) { - - boolean globalMode; - if (!MultiChat.defaultChannel.equalsIgnoreCase("local")) { - globalMode = true; - } else { - globalMode = false; - } - ChatModeManager.getInstance().registerPlayer(uuid, globalMode); - - } - - // Set player to appropriate channels - if (ChatModeManager.getInstance().isGlobal(uuid)) { - Channel.setChannel(player.getUniqueId(), Channel.getGlobalChannel()); - } else { - Channel.setChannel(player.getUniqueId(), Channel.getLocalChannel()); - } - - //BungeeComm.sendPlayerChannelMessage(player.getName(), Channel.getChannel(player.getUniqueId()).getName(), Channel.getChannel(player.getUniqueId()), player.getServer().getInfo()); - - if (UUIDNameManager.existsUUID(uuid)) { - UUIDNameManager.removeUUID(uuid); - } - - UUIDNameManager.addNew(uuid, player.getName()); - - ConsoleManager.log("Refreshed UUID-Name lookup: " + uuid.toString()); - - if ( ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getBoolean("showjoin") == true ) { - - // PremiumVanish support, return as early as possible to avoid loading unnecessary resources - if (MultiChat.premiumVanish && MultiChat.hideVanishedStaffInJoin && BungeeVanishAPI.isInvisible(player)) { return; } - - String joinformat = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getString("serverjoin"); - String silentformat = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getString("silentjoin"); - String welcomeMessage = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getString("welcome_message"); - String privateWelcomeMessage = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getString("private_welcome_message"); - - ChatManipulation chatman = new ChatManipulation(); - - joinformat = chatman.replaceJoinMsgVars(joinformat, player.getName()); - silentformat = chatman.replaceJoinMsgVars(silentformat, player.getName()); - welcomeMessage = chatman.replaceJoinMsgVars(welcomeMessage, player.getName()); - privateWelcomeMessage = chatman.replaceJoinMsgVars(privateWelcomeMessage, player.getName()); - - boolean broadcastWelcome = true; - if (ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().contains("welcome")) { - broadcastWelcome = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getBoolean("welcome"); - } - - boolean privateWelcome = false; - if (ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().contains("private_welcome")) { - privateWelcome = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getBoolean("private_welcome"); - } - - boolean broadcastJoin = !player.hasPermission("multichat.staff.silentjoin"); - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - - if (broadcastJoin) { - - if (firstJoin && broadcastWelcome) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', welcomeMessage))); - } - - if (firstJoin && privateWelcome && onlineplayer.getName().equals(player.getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', privateWelcomeMessage))); - } - - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', joinformat))); - - } else { - - hiddenStaff.add(player.getUniqueId()); - - if (onlineplayer.hasPermission("multichat.staff.silentjoin") ) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', silentformat))); - } - - } - } - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onLogout(PlayerDisconnectEvent event) { - - ProxiedPlayer player = event.getPlayer(); - UUID uuid = event.getPlayer().getUniqueId(); - - if (hiddenStaff.contains(uuid)) { - hiddenStaff.remove(uuid); - } - - if (mcbPlayers.contains(uuid)) { - mcbPlayers.remove(uuid); - } - - if (MCToggle.contains(uuid)) { - MCToggle.remove(uuid); - } - if (ACToggle.contains(uuid)) { - ACToggle.remove(uuid); - } - if (GCToggle.contains(uuid)) { - GCToggle.remove(uuid); - } - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (config.getBoolean("session_ignore")) { - ChatControl.unignoreAll(uuid); - } - - // Reset their spam data on logout (nothing is stored persistantly) - ChatControl.spamPardonPlayer(uuid); - - /// - Channel.removePlayer(player.getUniqueId()); - /// - - if (MultiChat.viewedchats.containsKey(uuid)) { - MultiChat.viewedchats.remove(uuid); - } - - PlayerMetaManager.getInstance().unregisterPlayer(uuid); - ConsoleManager.log("Un-Registered player " + player.getName()); + message = optionalMessage.get(); + event.setMessage(message); - if (!Channel.getGlobalChannel().isMember(player.getUniqueId())) { - Channel.getGlobalChannel().removeMember(uuid); - } - - if (!Channel.getLocalChannel().isMember(player.getUniqueId())) { - Channel.getLocalChannel().removeMember(uuid); - } - - if ( ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getBoolean("showquit") == true ) { - - String joinformat = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getString("networkquit"); - String silentformat = ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getString("silentquit"); + DebugManager.log("Does player have ALL colour permission? " + chatManager.hasLegacyColourPermission(player)); + DebugManager.log("Does player have simple colour permission? " + chatManager.hasSimpleColourPermission(player)); + DebugManager.log("Does player have rgb colour permission? " + chatManager.hasRGBColourPermission(player)); - ChatManipulation chatman = new ChatManipulation(); + // Let server know players channel preference - joinformat = chatman.replaceJoinMsgVars(joinformat, player.getName()); - silentformat = chatman.replaceJoinMsgVars(silentformat, player.getName()); + String channelFormat; - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - - if (!player.hasPermission("multichat.staff.silentjoin")) { - - onlineplayer.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', joinformat)).create()); + switch (channelManager.getChannel(player)) { + case "global": + channelFormat = channelManager.getGlobalChannel().getInfo().getFormat(); + break; + case "local": + channelFormat = channelManager.getLocalChannel().getFormat(); + break; + default: + if (channelManager.existsProxyChannel(channelManager.getChannel(player))) { + channelFormat = channelManager.getProxyChannel(channelManager.getChannel(player)).get().getInfo().getFormat(); } else { - - if (onlineplayer.hasPermission("multichat.staff.silentjoin") ) { - onlineplayer.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', silentformat)).create()); - } + channelFormat = channelManager.getGlobalChannel().getInfo().getFormat(); } + break; } - } - } - - - @EventHandler(priority = EventPriority.LOWEST) - public void onServerSwitch(ServerSwitchEvent event) { - // Tell the new server the player's channel preference - ProxyServer.getInstance().getScheduler().schedule(MultiChat.getInstance(), new Runnable() { - public void run() { + ProxyLocalCommunicationManager.sendPlayerDataMessage( + player.getName(), + channelManager.getChannel(player), + channelFormat, + player.getServer().getInfo(), + chatManager.hasSimpleColourPermission(player), + chatManager.hasRGBColourPermission(player)); - try { - BungeeComm.sendPlayerChannelMessage(event.getPlayer().getName(), Channel.getChannel(event.getPlayer().getUniqueId()).getName(), Channel.getChannel(event.getPlayer().getUniqueId()), event.getPlayer().getServer().getInfo(), (event.getPlayer().hasPermission("multichat.chat.colour")||event.getPlayer().hasPermission("multichat.chat.color")||event.getPlayer().hasPermission("multichat.chat.colour.simple")||event.getPlayer().hasPermission("multichat.chat.color.simple")), (event.getPlayer().hasPermission("multichat.chat.colour")||event.getPlayer().hasPermission("multichat.chat.color")||event.getPlayer().hasPermission("multichat.chat.colour.rgb")||event.getPlayer().hasPermission("multichat.chat.color.rgb"))); + // Message passes through to spigot here - // LEGACY SERVER HACK - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("legacy_servers").contains(event.getPlayer().getServer().getInfo().getName())) { - DebugManager.log("Player: " + event.getPlayer().getName() + ", switching to server: " + event.getPlayer().getServer().getInfo().getName() + ", is a LEGACY server!"); - BungeeComm.sendCommandMessage("!!!LEGACYSERVER!!!", event.getPlayer().getServer().getInfo()); - } else { - BungeeComm.sendCommandMessage("!!!NOTLEGACYSERVER!!!", event.getPlayer().getServer().getInfo()); - } - - } - - catch (NullPointerException ex) { /* EMPTY */ } + if (ds.getHiddenStaff().contains(player.getUniqueId())) { + ds.getHiddenStaff().remove(player.getUniqueId()); } - }, 500L, TimeUnit.MILLISECONDS); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/GlobalChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/GlobalChannel.java deleted file mode 100644 index 5d84f61c..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/GlobalChannel.java +++ /dev/null @@ -1,9 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - -public class GlobalChannel extends Channel { - - public GlobalChannel(String format) { - super("global", format, false, false); - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/GroupManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/GroupManager.java index e15c5b08..c6686427 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/GroupManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/GroupManager.java @@ -7,226 +7,156 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import xyz.olivermartin.multichat.bungee.commands.GCCommand; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * Group Chat Management Class *

Handles Group Chat Operations

- * + * * @author Oliver Martin (Revilo410) - * */ public class GroupManager { - /** - * Creates a new informal group chat based on the specified parameters - * Also adds the creator to the group as the owner - */ - public void createGroup(String groupname, UUID owneruuid, boolean secret, String password) { - - TGroupChatInfo newgroup = new TGroupChatInfo(); - - newgroup.addMember(owneruuid); - newgroup.addViewer(owneruuid); - newgroup.addAdmin(owneruuid); - newgroup.setName(groupname.toLowerCase()); - newgroup.setChatColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("groupchat.ccdefault").toCharArray()[0]); - newgroup.setNameColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("groupchat.ncdefault").toCharArray()[0]); - newgroup.setSecret(secret); - newgroup.setPassword(password); - newgroup.setFormal(false); - - MultiChat.groupchats.put(groupname.toLowerCase(), newgroup); - - } - - /** - * Adds a player to a group chat while removing them from the spy list if they were spying on it before - * This will also check if they are banned and stop them being added - * It will also check if they are already a member - * Passwords for the group are also checked - */ - public boolean joinGroup(String groupname, ProxiedPlayer player, String password) { - - boolean success = false; - - TGroupChatInfo groupchat = new TGroupChatInfo(); - groupchat = (TGroupChatInfo)MultiChat.groupchats.get(groupname.toLowerCase()); - - if (!groupchat.existsBanned(player.getUniqueId())) { - - if (!groupchat.existsMember(player.getUniqueId())) { - - if (!groupchat.getSecret()) { - - if (groupchat.existsViewer(player.getUniqueId())) { - - if (player.hasPermission("multichat.staff.spy")) { - - MessageManager.sendSpecialMessage(player, "command_group_spy_off", groupname.toUpperCase()); - groupchat.delViewer(player.getUniqueId()); - - } else { - - groupchat.delViewer(player.getUniqueId()); - - } - - } - - groupchat.addMember(player.getUniqueId()); - groupchat.addViewer(player.getUniqueId()); - - MultiChat.groupchats.remove(groupname.toLowerCase()); - MultiChat.groupchats.put(groupname.toLowerCase(), groupchat); - - success = true; - - } else { - - if (password.equals("")) { - - MessageManager.sendSpecialMessage(player, "groups_password_protected", groupname.toUpperCase()); - - } else { - - if (password.equals(groupchat.getPassword())) { - - if (groupchat.existsViewer(player.getUniqueId())) { - - if (player.hasPermission("multichat.staff.spy")) { - - MessageManager.sendSpecialMessage(player, "command_group_spy_off", groupname.toUpperCase()); - groupchat.delViewer(player.getUniqueId()); - - } else { - groupchat.delViewer(player.getUniqueId()); - } - - } - - groupchat.addMember(player.getUniqueId()); - groupchat.addViewer(player.getUniqueId()); - - MultiChat.groupchats.remove(groupname.toLowerCase()); - MultiChat.groupchats.put(groupname.toLowerCase(), groupchat); - - success = true; - - } else { - - MessageManager.sendSpecialMessage(player, "groups_password_incorrect", groupname.toUpperCase()); - - } - - } - } - - } else { - MessageManager.sendSpecialMessage(player, "groups_already_joined", groupname.toUpperCase()); - } - - } else { - MessageManager.sendSpecialMessage(player, "groups_banned", groupname.toUpperCase()); - } - - groupchat = null; - return success; - - } - - /** - * Sets the selected group of a player to the specified group - */ - public void setViewedChat(UUID playeruuid, String groupname) { - - String viewedchat = (String)MultiChat.viewedchats.get(playeruuid); - - viewedchat = groupname.toLowerCase(); - MultiChat.viewedchats.remove(playeruuid); - MultiChat.viewedchats.put(playeruuid, viewedchat); - - } - - /** - * The INFO announce in a group that a player has joined - */ - public void announceJoinGroup(String playername, String groupname) { - - GCCommand.sendMessage(playername + MessageManager.getMessage("groups_info_joined"), "&lINFO", MultiChat.groupchats.get(groupname.toLowerCase())); - - } - - /** - * The INFO announce in a group that a player has left - */ - public void announceQuitGroup(String playername, String groupname) { - - GCCommand.sendMessage(playername + MessageManager.getMessage("groups_info_quit"), "&lINFO", MultiChat.groupchats.get(groupname.toLowerCase())); - - } - - /** - * Quits a group, announces in the group chat and notifies the player quitting - */ - public void quitGroup(String groupname, UUID player, ProxiedPlayer pinstance) { - - TGroupChatInfo groupchatinfo = new TGroupChatInfo(); - String viewedchat = (String)MultiChat.viewedchats.get(player); - - groupchatinfo = (TGroupChatInfo)MultiChat.groupchats.get(groupname.toLowerCase()); - - if (groupchatinfo.existsMember(player)) { - - if ((!groupchatinfo.existsAdmin(player)) || (groupchatinfo.getAdmins().size() > 1)) { - - groupchatinfo.delMember(player); - groupchatinfo.delViewer(player); - - if (groupchatinfo.existsAdmin(player)) { - groupchatinfo.delAdmin(player); - } - - viewedchat = null; - - MultiChat.viewedchats.remove(player); - MultiChat.viewedchats.put(player, viewedchat); - MultiChat.groupchats.remove(groupname.toLowerCase()); - MultiChat.groupchats.put(groupname.toLowerCase(), groupchatinfo); - - MessageManager.sendSpecialMessage(pinstance, "groups_quit", groupname.toUpperCase()); - announceQuitGroup(pinstance.getName(), groupname); - - } else if (!groupchatinfo.getFormal()) { - - MessageManager.sendSpecialMessage(pinstance, "groups_cannot_quit_owner_1", groupname.toUpperCase()); - MessageManager.sendSpecialMessage(pinstance, "groups_cannot_quit_owner_2", groupname.toUpperCase()); - - } else { - - MessageManager.sendSpecialMessage(pinstance, "groups_cannot_quit_admin_1", groupname.toUpperCase()); - MessageManager.sendSpecialMessage(pinstance, "groups_cannot_quit_admin_2", groupname.toUpperCase()); - } - - } else { - - MessageManager.sendSpecialMessage(pinstance, "command_group_not_a_member", groupname.toUpperCase()); - - } - - groupchatinfo = null; - - } - - public void displayHelp(int page, CommandSender sender) { - - if (page == 1) { - - MessageManager.sendMessage(sender, "groups_help_1"); - - } else { - - MessageManager.sendMessage(sender, "groups_help_2"); - - } - } + /** + * Creates a new informal group chat based on the specified parameters + * Also adds the creator to the group as the owner + */ + public void createGroup(String groupname, UUID owneruuid, boolean secret, String password) { + + TGroupChatInfo newgroup = new TGroupChatInfo(); + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + newgroup.addMember(owneruuid); + newgroup.addViewer(owneruuid); + newgroup.addAdmin(owneruuid); + newgroup.setName(groupname.toLowerCase()); + newgroup.setChatColor(ProxyConfigs.CONFIG.getGroupChatColor()); + newgroup.setNameColor(ProxyConfigs.CONFIG.getGroupNameColor()); + newgroup.setSecret(secret); + newgroup.setPassword(password); + newgroup.setFormal(false); + + ds.getGroupChats().put(groupname.toLowerCase(), newgroup); + + } + + /** + * Adds a player to a group chat while removing them from the spy list if they were spying on it before + * This will also check if they are banned and stop them being added + * It will also check if they are already a member + * Passwords for the group are also checked + */ + public boolean joinGroup(String groupname, ProxiedPlayer player, String password) { + ProxyDataStore dataStore = MultiChatProxy.getInstance().getDataStore(); + TGroupChatInfo groupChatInfo = dataStore.getGroupChats().get(groupname.toLowerCase()); + + UUID playerUID = player.getUniqueId(); + if (groupChatInfo.isBanned(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(player, "groups_banned", groupname.toUpperCase()); + return false; + } + + if (groupChatInfo.isMember(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(player, "groups_already_joined", groupname.toUpperCase()); + return false; + } + + if (groupChatInfo.getSecret()) { + if (password.isEmpty()) { + ProxyConfigs.MESSAGES.sendMessage(player, "groups_password_protected", groupname.toUpperCase()); + return false; + } + + if (!password.equals(groupChatInfo.getPassword())) { + ProxyConfigs.MESSAGES.sendMessage(player, "groups_password_incorrect", groupname.toUpperCase()); + return false; + } + } + + if (groupChatInfo.isViewer(player.getUniqueId())) { + if (player.hasPermission("multichat.staff.spy")) + ProxyConfigs.MESSAGES.sendMessage(player, "command_group_spy_off", groupname.toUpperCase()); + + groupChatInfo.delViewer(player.getUniqueId()); + } + + groupChatInfo.addMember(player.getUniqueId()); + groupChatInfo.addViewer(player.getUniqueId()); + + dataStore.getGroupChats().remove(groupname.toLowerCase()); + dataStore.getGroupChats().put(groupname.toLowerCase(), groupChatInfo); + + return true; + } + + /** + * Sets the selected group of a player to the specified group + */ + public void setViewedChat(UUID playeruuid, String groupname) { + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + ds.getViewedChats().get(playeruuid); + String viewedchat = groupname.toLowerCase(); + ds.getViewedChats().remove(playeruuid); + ds.getViewedChats().put(playeruuid, viewedchat); + } + + /** + * The INFO announce in a group that a player has joined + */ + public void announceJoinGroup(String playername, String groupname) { + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + GCCommand.sendMessage(playername + ProxyConfigs.MESSAGES.getMessage("groups_info_joined"), "&lINFO", ds.getGroupChats().get(groupname.toLowerCase())); + } + + /** + * The INFO announce in a group that a player has left + */ + public void announceQuitGroup(String playername, String groupname) { + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + GCCommand.sendMessage(playername + ProxyConfigs.MESSAGES.getMessage("groups_info_quit"), "&lINFO", ds.getGroupChats().get(groupname.toLowerCase())); + } + + /** + * Quits a group, announces in the group chat and notifies the player quitting + */ + public void quitGroup(String groupname, UUID player, ProxiedPlayer pinstance) { + ProxyDataStore dataStore = MultiChatProxy.getInstance().getDataStore(); + TGroupChatInfo groupChatInfo = dataStore.getGroupChats().get(groupname.toLowerCase()); + + if (!groupChatInfo.isMember(player)) { + ProxyConfigs.MESSAGES.sendMessage(pinstance, "command_group_not_a_member", groupname.toUpperCase()); + return; + } + + if ((!groupChatInfo.isAdmin(player)) || (groupChatInfo.getAdmins().size() > 1)) { + groupChatInfo.delMember(player); + groupChatInfo.delViewer(player); + + if (groupChatInfo.isAdmin(player)) { + groupChatInfo.delAdmin(player); + } + + dataStore.getViewedChats().remove(player); + dataStore.getViewedChats().put(player, null); + dataStore.getGroupChats().remove(groupname.toLowerCase()); + dataStore.getGroupChats().put(groupname.toLowerCase(), groupChatInfo); + + ProxyConfigs.MESSAGES.sendMessage(pinstance, "groups_quit", groupname.toUpperCase()); + announceQuitGroup(pinstance.getName(), groupname); + } else if (!groupChatInfo.getFormal()) { + ProxyConfigs.MESSAGES.sendMessage(pinstance, "groups_cannot_quit_owner_1", groupname.toUpperCase()); + ProxyConfigs.MESSAGES.sendMessage(pinstance, "groups_cannot_quit_owner_2", groupname.toUpperCase()); + } else { + ProxyConfigs.MESSAGES.sendMessage(pinstance, "groups_cannot_quit_admin_1", groupname.toUpperCase()); + ProxyConfigs.MESSAGES.sendMessage(pinstance, "groups_cannot_quit_admin_2", groupname.toUpperCase()); + } + } + + public void displayHelp(int page, CommandSender sender) { + ProxyConfigs.MESSAGES.sendMessage(sender, "groups_help_" + (page == 1 ? "1" : "2")); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/LocalChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/LocalChannel.java deleted file mode 100644 index 512b948e..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/LocalChannel.java +++ /dev/null @@ -1,32 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - -import net.md_5.bungee.api.CommandSender; -import net.md_5.bungee.api.connection.ProxiedPlayer; - -public class LocalChannel extends Channel { - - public LocalChannel() { - super("local", "", false, false); - } - - /** - * This has no purpose as local chat for players is handled by the local servers - */ - @Override - public void sendMessage(ProxiedPlayer sender, String message, String format) { - /* EMPTY */ - } - - @Override - public void sendMessage(String message, CommandSender sender) { - - DebugManager.log("LocalChannel wants to send a cast message!"); - - // Use this to relay CASTS to local chat! - if (sender instanceof ProxiedPlayer) { - BungeeComm.sendChatMessage(message, ((ProxiedPlayer)sender).getServer().getInfo()); - } - - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MessageManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MessageManager.java deleted file mode 100644 index 9cfad8cd..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MessageManager.java +++ /dev/null @@ -1,438 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - -import java.util.HashMap; -import java.util.Map; - -import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.CommandSender; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.config.Configuration; - -/** - * Message Manager - *

Used to display all plugin messages to players

- * - * @author Oliver Martin (Revilo410) - */ -public class MessageManager { - - private static Map defaultMessages; - - private static String prefix; - - static { - - defaultMessages = new HashMap(); - - // *** CONSOLE LOGS *** // - - defaultMessages.put("console_main_prefix", "&8[&2M&aC&8]&f "); - defaultMessages.put("console_chat_prefix", "&fCHAT &f> "); - defaultMessages.put("console_modchat_prefix", "&3STAFFCHAT &f> &3"); - defaultMessages.put("console_adminchat_prefix", "&5STAFFCHAT &f> &5"); - defaultMessages.put("console_groupchat_prefix", "&2GROUPCHAT &f> &2"); - defaultMessages.put("console_display_prefix", "&fDISPLAY &f> "); - defaultMessages.put("console_socialspy_prefix", "&cSOCIALSPY &f> &c"); - defaultMessages.put("console_helpme_prefix", "&4HELPME &f> &4"); - - - // *** PREFIX *** // - - defaultMessages.put("prefix", "&8&l[&2&lM&a&lC&8&l]&f "); - - // *** COMMANDS *** // - - defaultMessages.put("command_acc_usage", "&aUsage: /acc "); - defaultMessages.put("command_acc_only_players", "&cOnly players can change chat colours!"); - defaultMessages.put("command_acc_updated", "&aAdmin-Chat colours updated!"); - defaultMessages.put("command_acc_invalid", "&cInvalid color codes specified: Must be letters a-f or numbers 0-9"); - defaultMessages.put("command_acc_invalid_usage", "&cUsage: /acc "); - - defaultMessages.put("command_ac_toggle_on", "&dAdmin chat toggled on!"); - defaultMessages.put("command_ac_toggle_off", "&cAdmin chat toggled off!"); - defaultMessages.put("command_ac_only_players", "&cOnly players can toggle the chat!"); - - defaultMessages.put("command_announcement_list", "&aList of avaliable announcements:"); - defaultMessages.put("command_announcement_list_item", "&b -> %SPECIAL%"); - defaultMessages.put("command_announcement_does_not_exist", "&cSorry, no such announcement found: %SPECIAL%"); - defaultMessages.put("command_announcement_removed", "&aRemoved announcement: %SPECIAL%"); - defaultMessages.put("command_announcement_stopped", "&aStopped announcement: %SPECIAL%"); - defaultMessages.put("command_announcement_stopped_error", "&cSorry, unable to stop announcement: %SPECIAL%"); - defaultMessages.put("command_announcement_started", "&aStarted announcement: %SPECIAL%"); - defaultMessages.put("command_announcement_started_error", "&cSorry, unable to start announcement: %SPECIAL%"); - defaultMessages.put("command_announcement_added", "&aAdded announcement: %SPECIAL%"); - defaultMessages.put("command_announcement_added_error", "&cSorry, announcement already exists: %SPECIAL%"); - defaultMessages.put("command_announcement_usage", "&aUsage:"); - - defaultMessages.put("command_bulletin_stopped", "&bBulletins stopped"); - defaultMessages.put("command_bulletin_list", "&aList of bulletin messages with index:"); - defaultMessages.put("command_bulletin_list_item", "&b -> %SPECIAL%"); - defaultMessages.put("command_bulletin_removed", "&bRemoved bulletin"); - defaultMessages.put("command_bulletin_started", "&bStarted bulletin"); - defaultMessages.put("command_bulletin_added", "&bAdded to bulletin"); - defaultMessages.put("command_bulletin_invalid_usage", "&cInvalid command usage!"); - defaultMessages.put("command_bulletin_usage", "&aUsage:"); - - defaultMessages.put("command_cast_usage", "&aUsage:"); - defaultMessages.put("command_cast_list", "&aList of avaliable casts:"); - defaultMessages.put("command_cast_list_item", "&b -> %SPECIAL%"); - defaultMessages.put("command_cast_removed", "&aRemoved cast: %SPECIAL%"); - defaultMessages.put("command_cast_does_not_exist", "&cSorry, no such cast found: %SPECIAL%"); - defaultMessages.put("command_cast_added", "&aAdded cast: %SPECIAL%"); - defaultMessages.put("command_cast_added_error", "&cSorry, cast already exists: %SPECIAL%"); - - defaultMessages.put("command_channel_help", - "&3&lChannel Command Help\n" - + "&bSwitch channel\n" - + "&f&o/channel switch \n" - + "&bShow/Hide channel\n" - + "&f&o/channel show/hide "); - defaultMessages.put("command_channel_switch", "&bSwitched to channel: &f&o%SPECIAL%"); - defaultMessages.put("command_channel_hide", "&bYou have hidden channel: &f&o%SPECIAL%"); - defaultMessages.put("command_channel_show", "&bYou have un-hidden channel: &f&o%SPECIAL%"); - defaultMessages.put("command_channel_already_hide", "&bYou have already hidden channel: &f&o%SPECIAL%"); - defaultMessages.put("command_channel_already_show", "&bYou have already un-hidden channel: &f&o%SPECIAL%"); - defaultMessages.put("command_channel_does_not_exist", "&cSorry, that channel does not exist"); - defaultMessages.put("command_channel_only_players", "&cSorry, only players can use chat channel commands"); - defaultMessages.put("command_channel_switch_no_permission", "&cYou are unable to switch channels"); - defaultMessages.put("command_channel_hide_no_permission", "&cYou are unable to hide channels"); - defaultMessages.put("command_channel_show_no_permission", "&cYou are unable to show channels"); - defaultMessages.put("command_channel_cannot_hide", "&cYou cannot hide your currently selected channel"); - - defaultMessages.put("command_clearchat_self", "&bYour chat has been cleared"); - defaultMessages.put("command_clearchat_server", "&bServer chat has been cleared"); - defaultMessages.put("command_clearchat_global", "&bGlobal chat has been cleared"); - defaultMessages.put("command_clearchat_all", "&bAll chat has been cleared"); - defaultMessages.put("command_clearchat_no_permission", "&cYou do not have permission to clear %SPECIAL% chat"); - defaultMessages.put("command_clearchat_usage", "&cUsage: /clearchat [self/server/global/all]"); - - defaultMessages.put("command_display_desc", "&3Display a message to the entire network"); - defaultMessages.put("command_display_usage", "&bUsage /display "); - - defaultMessages.put("command_freezechat_thawed", "&b&lChat was &3&lTHAWED &b&lby &a&l%SPECIAL%"); - defaultMessages.put("command_freezechat_frozen", "&b&lChat was &3&lFROZEN &b&lby &a&l%SPECIAL%"); - - defaultMessages.put("command_gc_toggle_on", "&aGroup chat toggled on!"); - defaultMessages.put("command_gc_toggle_off", "&cGroup chat toggled off!"); - defaultMessages.put("command_gc_only_players_toggle", "&cOnly players can toggle the chat!"); - defaultMessages.put("command_gc_no_longer_exists", "&cSorry your selected chat no longer exists, please select a chat with /group "); - defaultMessages.put("command_gc_no_chat_selected", "&cPlease select the chat you wish to message using /group "); - defaultMessages.put("command_gc_only_players_speak", "&cOnly players can speak in group chats"); - - defaultMessages.put("command_global_enabled_1", "&3GLOBAL CHAT ENABLED"); - defaultMessages.put("command_global_enabled_2", "&bYour messages will go to all servers!"); - defaultMessages.put("command_global_only_players", "&cOnly players can change their chat state"); - - defaultMessages.put("command_group_selected", "&aYour /gc messages will now go to group: %SPECIAL%"); - defaultMessages.put("command_group_not_a_member", "&cSorry you aren't a member of group: %SPECIAL%"); - defaultMessages.put("command_group_does_not_exist", "&cSorry the following group chat does not exist: %SPECIAL%"); - defaultMessages.put("command_group_only_players_select", "&cOnly players can select a group chat"); - defaultMessages.put("command_group_incorrect_usage", "&cIncorrect command usage, use /group to see a list of commands!"); - defaultMessages.put("command_group_member_list", "&a&lShowing members of group: %SPECIAL%"); - defaultMessages.put("command_group_member_list_item", "&b- %SPECIAL%"); - defaultMessages.put("command_group_member_list_item_admin", "&b- &b&o%SPECIAL%"); - defaultMessages.put("command_group_spy_all_disabled_1", "&cGlobal group spy disabled"); - defaultMessages.put("command_group_spy_all_disabled_2", "&cAny groups you previously activated spy for will still be spied on!"); - defaultMessages.put("command_group_spy_all_disabled_3", "&cDisable spy for individual groups with /group spy "); - defaultMessages.put("command_group_spy_all_enabled", "&aGlobal group spy enabled for all group chats!"); - defaultMessages.put("command_group_spy_no_permission", "&cSorry this command does not exist, use /group"); - defaultMessages.put("command_group_spy_off", "&cYou are no longer spying on: %SPECIAL%"); - defaultMessages.put("command_group_spy_on", "&aYou are now spying on: %SPECIAL%"); - defaultMessages.put("command_group_spy_already_a_member", "&cYou are already a member of this chat so can't spy on it!"); - defaultMessages.put("command_group_spy_does_not_exist", "&cSorry this group chat does not exist!"); - defaultMessages.put("command_group_created", "&aYou successfully created, joined, and selected the group: %SPECIAL%"); - defaultMessages.put("command_group_already_exists", "&cSorry the following group chat already exists: %SPECIAL%"); - defaultMessages.put("command_group_max_length", "&cSorry group name cannot exceed 20 characters!"); - defaultMessages.put("command_group_create_no_permission", "&cSorry you do not have permission to create new group chats"); - defaultMessages.put("command_group_joined", "&aYou successfully joined and selected the group: %SPECIAL%"); - defaultMessages.put("command_group_formal_not_owner", "&cSorry this command can only be used by the group chat owner"); - defaultMessages.put("command_group_formal_already_formal", "&cSorry this chat is already a formal group chat: %SPECIAL%"); - defaultMessages.put("command_group_formal_not_admin", "&cSorry this command can only be used by group admins/owners"); - defaultMessages.put("command_group_max_length_password", "&cSorry neither group name or password must exceed 20 characters"); - defaultMessages.put("command_group_transfer_not_member", "&cThis player is not already a member of the group!"); - defaultMessages.put("command_group_transfer_not_owner", "&cSorry you are not the owner of this chat!"); - defaultMessages.put("command_group_transfer_not_informal", "&cThis command can only be used on informal chats!"); - defaultMessages.put("command_group_player_not_online", "&cThis player is not online!"); - defaultMessages.put("command_group_formal_only_admin", "&cYou can't step down as a group admin because you are the only one!"); - defaultMessages.put("command_group_formal_cannot_demote", "&cYou can't demote another group admin!"); - defaultMessages.put("command_group_not_formal", "&cThis command can only be used on formal chats!"); - defaultMessages.put("command_group_banned", "&cYou were banned from group: %SPECIAL%"); - defaultMessages.put("command_group_unbanned", "&aYou were unbanned from group: %SPECIAL%"); - defaultMessages.put("command_group_cannot_ban_admin", "&cYou can't ban a group admin!"); - defaultMessages.put("command_group_color_invalid", "&cInvalid color codes specified: Must be letters a-f or numbers 0-9"); - defaultMessages.put("command_group_color_usage", "&cUsage: /group color/colour "); - defaultMessages.put("command_group_only_players", "&cOnly players can use group chats"); - - defaultMessages.put("command_grouplist_list", "&a&lGroup List:"); - defaultMessages.put("command_grouplist_list_item", "&b- %SPECIAL%"); - - defaultMessages.put("command_helpme_desc", "&4Request help from a staff member!"); - defaultMessages.put("command_helpme_usage", "&cUsage: /HelpMe "); - defaultMessages.put("command_helpme_sent", "&cYour request for help has been sent to all online staff :)"); - defaultMessages.put("command_helpme_only_players", "&4Only players can request help!"); - defaultMessages.put("command_helpme_format", "&c&l<< &4HELPME &c&l>> &f&o%SPECIAL%"); - - defaultMessages.put("command_local_enabled_1", "&3LOCAL CHAT ENABLED"); - defaultMessages.put("command_local_enabled_2", "&bYour messages will only go to this server!"); - defaultMessages.put("command_local_only_players", "&cOnly players can change their chat state"); - - defaultMessages.put("command_mcc_usage", "&aUsage: /mcc "); - defaultMessages.put("command_mcc_only_players", "&cOnly players can change chat colours!"); - defaultMessages.put("command_mcc_updated", "&aMod-Chat colours updated!"); - defaultMessages.put("command_mcc_invalid", "&cInvalid color codes specified: Must be letters a-f or numbers 0-9"); - defaultMessages.put("command_mcc_invalid_usage", "&cUsage: /mcc "); - - defaultMessages.put("command_mc_toggle_on", "&bMod chat toggled on!"); - defaultMessages.put("command_mc_toggle_off", "&cMod chat toggled off!"); - defaultMessages.put("command_mc_only_players", "&cOnly players can toggle the chat!"); - - defaultMessages.put("command_msg_usage", "&bUsage: /msg [message]"); - defaultMessages.put("command_msg_usage_toggle", "&bUsing /msg with no message will toggle chat to go to that player"); - defaultMessages.put("command_msg_toggle_on", "&ePrivate chat toggled on! [You -> %SPECIAL%] (Type the same command to disable the toggle)"); - defaultMessages.put("command_msg_toggle_off", "&cPrivate chat toggled off!"); - defaultMessages.put("command_msg_only_players", "&cOnly players can toggle the chat!"); - defaultMessages.put("command_msg_not_online", "&cSorry this person is not online!"); - defaultMessages.put("command_msg_disabled_target", "&cSorry private messages are disabled on the target player's server!"); - defaultMessages.put("command_msg_disabled_sender", "&cSorry private messages are disabled on this server!"); - defaultMessages.put("command_msg_no_toggle", "&cSorry, message toggles are not allowed on this server!"); - - // TODO Somehow combine all these into one message but provide a special method like "displayMessagePage()" in this - // message manager which automatically decides how many lines to show for the page specified to the message manager. - defaultMessages.put("command_multichat_help_1", - "&2&lMulti&a&lChat &b&lHelp\n" - + "&3Display plugin version info\n" - + "&b/multichat\n" - + "&3Reload the plugin config\n" - + "&b/multichat reload\n" - + "&3Save ALL plugin data\n" - + "&b/multichat save\n" - + "&3Display a message to all players\n" - + "&b/display \n" - + "&3View group chat help\n" - + "&b/group\n" - + "&3Send mod chat message &o(Send admin chat message)\n" - + "&b/mc &o(/ac )\n" - + "&3Change mod/&oadmin &3chat colours\n" - + "&b/mcc \n" - + "&b&o/acc \n" - + "&3Toggle mod chat &o(Toggle admin chat)\n" - + "&b/mc &o(/ac)\n" - + "&3&lType &b&l/multichat help &3<o view more commands"); - - defaultMessages.put("command_multichat_help_2", - "&2&lMulti&a&lChat &b&lHelp [Page 2]\n" - + "&3View all global chat (Enabled by default)\n" - + "&b/global\n" - + "&3Only view chat from your current server\n" - + "&b/local\n" - + "&3See a list of online staff members\n" - + "&b/staff\n" - + "&3See a list of all group chats\n" - + "&b/groups\n" - + "&3Send a player a private message\n" - + "&b/msg [message]\n" - + "&3Reply to your last message\n" - + "&b/r \n" - + "&3Toggle socialspy to view private messages\n" - + "&b/socialspy\n" - + "&3Freeze the chat to stop messages being sent\n" - + "&b/freezechat\n" - + "&3Clear the chat stream for yourself or a group of people\n" - + "&b/clearchat [self,server,global,all]"); - - defaultMessages.put("command_multichat_help_3", - "&2&lMulti&a&lChat &b&lHelp [Page 3]\n" - + "&3View announcement commands\n" - + "&b/announcement\n" - + "&3View bulletin commands\n" - + "&b/bulletin\n" - + "&3View cast commands\n" - + "&b/cast\n" - + "&3Use a specified cast from the console\n" - + "&b/usecast \n" - + "&3Alert staff members of a problem\n" - + "&b/helpme \n" - + "&3Nickname a player (Only works if MultiChat installed on Spigot / Sponge)\n" - + "&b/nick [player] \n" - + "&3Get players real name from their nickname (Only works on Spigot)\n" - + "&b/realname \n" - + "&3Mute players to prevent them sending messages\n" - + "&b/mute \n" - + "&3Ignore players to stop seeing their messages\n" - + "&b/ignore "); - - defaultMessages.put("command_multichat_save_prepare", "&3Preparing to save multichat files!"); - defaultMessages.put("command_multichat_save_completed", "&bSave completed!"); - defaultMessages.put("command_multichat_reload_prepare", "&3Preparing to reload multichat files!"); - defaultMessages.put("command_multichat_reload_completed", "&bReload completed!"); - - defaultMessages.put("command_multichatbypass_usage", "&4Usage: /mcb\n" - + "&c&oThis command causes your chat messages to bypass MultiChat and be handled directly by spigot."); - defaultMessages.put("command_multichatbypass_enabled", "&aMultiChat BYPASS Enabled"); - defaultMessages.put("command_multichatbypass_disabled", "&bMultiChat BYPASS Disabled"); - - defaultMessages.put("command_execute_usage", "&2Usage: /mce [-s ] [-p ] \n" - + "&a&oThis command allows you to execute a command over all your spigot servers (&lwhich have at least 1 player online!&a&o)\n" - + "By default the command will be executed by console, you can instead make players execute the command using the -p flag\n" - + "By default the command will be executed on all servers, you can limit which servers using the -s flag."); - defaultMessages.put("command_execute_sent", "&2The command has been sent"); - defaultMessages.put("command_execute_regex", "&cThe regex specified was invalid"); - - defaultMessages.put("command_reply_usage", "&bUsage: /r "); - defaultMessages.put("command_reply_desc", "&bReply to the person who you private messaged most recently"); - defaultMessages.put("command_reply_no_one_to_reply_to", "&cYou have no one to reply to!"); - defaultMessages.put("command_reply_only_players", "&cOnly players can reply to private messages"); - - defaultMessages.put("command_socialspy_disabled", "&cSocial Spy Disabled"); - defaultMessages.put("command_socialspy_enabled", "&bSocial Spy Enabled"); - defaultMessages.put("command_socialspy_usage", "&bUsage: /socialspy"); - defaultMessages.put("command_socialspy_desc", "&bToggles if the user has social spy enabled or disabled"); - defaultMessages.put("command_socialspy_only_players", "&cOnly players can toggle socialspy"); - - defaultMessages.put("command_stafflist_list", "&a&lOnline Staff"); - defaultMessages.put("command_stafflist_list_item", "&b- %SPECIAL%"); - defaultMessages.put("command_stafflist_list_server", "&a%SPECIAL%"); - defaultMessages.put("command_stafflist_no_staff", "&b&oThere are currently no staff online"); - - defaultMessages.put("command_usecast_usage", "&aUsage:"); - defaultMessages.put("command_usecast_does_not_exist", "&cSorry, no such cast found: %SPECIAL%"); - - // *** GROUPS *** // - - defaultMessages.put("groups_toggled_but_no_longer_exists_1", "&cYou have toggled group chat but selected group doesn't exist!"); - defaultMessages.put("groups_toggled_but_no_longer_exists_2", "&cPlease select the chat you wish to message using /group or disable the toggle with /gc"); - defaultMessages.put("groups_password_protected", "&cSorry this group chat is password protected: %SPECIAL%"); - defaultMessages.put("groups_password_incorrect", "&cSorry incorrect password for: %SPECIAL%"); - defaultMessages.put("groups_already_joined", "&cSorry you are already a member of the group: %SPECIAL%"); - defaultMessages.put("groups_banned", "&cSorry you are banned from the group: %SPECIAL%"); - defaultMessages.put("groups_quit", "&aYou successfully left the group: %SPECIAL%"); - defaultMessages.put("groups_cannot_quit_owner_1", "&cSorry you cannot leave as you created the group!: %SPECIAL%"); - defaultMessages.put("groups_cannot_quit_owner_2", "&cPlease transfer group ownership first! Use /group transfer %SPECIAL% "); - defaultMessages.put("groups_cannot_quit_admin_1", "&cSorry you cannot leave as you are the only group admin!: %SPECIAL%"); - defaultMessages.put("groups_cannot_quit_admin_2", "&cPlease appoint a new admin using /group admin %SPECIAL% "); - - defaultMessages.put("groups_info_joined", " has joined the group chat!"); - defaultMessages.put("groups_info_quit", " has left the group chat!"); - defaultMessages.put("groups_info_formal", " has converted this group to a FORMAL group chat!"); - defaultMessages.put("groups_info_deleted", " has deleted this group chat!"); - defaultMessages.put("groups_info_goodbye", "Goodbye! If you want to see group chat commands do /group"); - defaultMessages.put("groups_info_transfer", " has transferred ownership to "); - defaultMessages.put("groups_info_promoted", " has promoted the following member to group admin: "); - defaultMessages.put("groups_info_step_down", " has stepped down as a group admin"); - defaultMessages.put("groups_info_kick", " kicked the following player from the group chat: "); - defaultMessages.put("groups_info_ban", " has banned the following player from the group chat: "); - defaultMessages.put("groups_info_unban", " has unbanned the following player from the group chat: "); - defaultMessages.put("groups_info_colors", "Group chat colours changed by "); - - defaultMessages.put("groups_help_1", - "&cGroup Chat Command Usage [Page 1] - INFORMAL GROUPS\n" - + "&2MAKE A NEW GROUP CHAT\n" - + "&a/group create/make [password]\n" - + "&2JOIN AN EXISTING GROUP CHAT\n" - + "&a/group join [password]\n" - + "&2LEAVE A GROUP CHAT\n" - + "&a/group leave/quit \n" - + "&2SELECT THE GROUP CHAT YOU WISH FOR YOUR MESSAGES TO GO TO\n" - + "&a/group \n" - + "&2SET THE COLOURS OF YOUR GROUP CHAT\n" - + "&a/group color/colour \n" - + "&2TRANSFER OWNERSHIP OF YOUR INFORMAL GROUP CHAT\n" - + "&a/group transfer \n" - + "&2DELETE A GROUP CHAT\n" - + "&a/group delete \n" - + "&2LIST GROUP CHAT MEMBERS\n" - + "&a/group list/members \n" - + "&2SEND A MESSAGE TO THE SELECTED GROUP CHAT\n" - + "&a/gc \n" - + "&cTo see FORMAL group chat commands do /group help 2"); - - defaultMessages.put("groups_help_2", - "&cGroup Chat Command Usage [Page 2] - FORMAL GROUPS\n" - + "&3All group chats default to informal group chats\n" - + "&3If you are a group owner you can convert your group to a formal group chat\n" - + "&3Formal group chats restrict changing colours to appointed group admins only\n" - + "&3Appointed group admins will also be able to ban people from the chat\n" - + "&3CONVERSION TO A FORMAL GROUP CHAT IS IRREVERSIBLE\n" - + "&2CONVERT YOUR GROUP CHAT TO A FORMAL GROUP CHAT (IRREVERSIBLE)\n" - + "&a/group formal \n" - + "&2ADD OR REMOVE AN ADMIN FROM A FORMAL GROUP CHAT\n" - + "&a/group admin \n" - + "&2BAN/UNBAN A PLAYER FROM YOUR FORMAL GROUP CHAT\n" - + "&a/group ban \n" - + "&cTo see INFORMAL group chat commands do /group help 1"); - - // *** FREEZECHAT *** // - - defaultMessages.put("freezechat_frozen", "&bSorry chat has been &3&lFROZEN"); - - // *** MUTE ***// - - defaultMessages.put("mute_muted", "&cYou have been muted by staff! You can no longer send chat messages."); - defaultMessages.put("mute_unmuted", "&aYou have been unmuted by staff, you can now send messages."); - defaultMessages.put("mute_muted_staff", "&cPlayer has been muted!"); - defaultMessages.put("mute_unmuted_staff", "&aPlayer has been unmuted!"); - defaultMessages.put("mute_cannot_send_message", "&cYou are currently muted so cannot send messages!"); - defaultMessages.put("mute_usage", "&cUsage: /mute (Also used to unmute players)"); - defaultMessages.put("mute_player_not_found", "&cPlayer cannot be muted as they are not online"); - defaultMessages.put("mute_bypass", "&cYou cannot mute this player"); - - // *** IGNORE *** // - - defaultMessages.put("ignore_sender", "&cYou cannot message this person"); - defaultMessages.put("ignore_target", "&c[%SPECIAL% sent a message, but you ignore them]"); - defaultMessages.put("ignore_ignored", "&bYou will no longer see chat messages from %SPECIAL%"); - defaultMessages.put("ignore_unignored", "&bYou have un-ignored %SPECIAL%"); - defaultMessages.put("ignore_player_not_found", "&cPlayer cannot be ignored as they are not online"); - defaultMessages.put("ignore_usage", "&cUsage: /ignore (Also used to un-ignore players)"); - defaultMessages.put("ignore_bypass", "&cYou cannot ignore this player"); - defaultMessages.put("ignore_only_players", "&cOnly players can use this command"); - defaultMessages.put("ignore_cannot_ignore_yourself", "&cYou cannot ignore yourself!"); - - // *** ANTI-SPAM *** // - - defaultMessages.put("anti_spam_cooldown", "&cANTI-SPAM: Your messages have been blocked. You cannot chat for another %SPECIAL% seconds."); - - } - - public static String getPrefix() { - return prefix; - } - - public static String getMessage(String id) { - - Configuration config = ConfigManager.getInstance().getHandler("messages.yml").getConfig(); - - if (config.contains(id)) return config.getString(id); - if (!defaultMessages.containsKey(id)) return "&cERROR - Please report to plugin developer - No message defined for: " + id; - return defaultMessages.get(id.toLowerCase()); - - } - - public static void sendMessage(CommandSender sender, String id) { - updatePrefix(); - sender.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', prefix + MultiChatUtil.reformatRGB(getMessage(id))))); - } - - public static void sendSpecialMessage(CommandSender sender, String id, String special) { - updatePrefix(); - sender.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', prefix + MultiChatUtil.reformatRGB(getMessage(id)).replaceAll("%SPECIAL%", special)))); - } - - public static void sendSpecialMessageWithoutPrefix(CommandSender sender, String id, String special) { - updatePrefix(); - sender.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', MultiChatUtil.reformatRGB(getMessage(id)).replaceAll("%SPECIAL%", special)))); - } - - private static void updatePrefix() { - - Configuration config = ConfigManager.getInstance().getHandler("messages.yml").getConfig(); - - if (config.contains("prefix")) { - prefix = config.getString("prefix"); - } else { - prefix = defaultMessages.get("prefix"); - } - - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChat.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChat.java index b360ca77..48409291 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChat.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChat.java @@ -1,1084 +1,328 @@ package xyz.olivermartin.multichat.bungee; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.plugin.Plugin; +import xyz.olivermartin.multichat.common.communication.CommChannels; +import xyz.olivermartin.multichat.proxy.common.*; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.channels.TagManager; +import xyz.olivermartin.multichat.proxy.common.channels.local.LocalChannel; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.GlobalStaticProxyChannel; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.ProxyChannelInfo; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.StaticProxyChannel; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.contexts.ContextManager; +import xyz.olivermartin.multichat.proxy.common.contexts.GlobalContext; +import xyz.olivermartin.multichat.proxy.common.listeners.ProxyLoginListener; +import xyz.olivermartin.multichat.proxy.common.listeners.ProxyLogoutListener; +import xyz.olivermartin.multichat.proxy.common.listeners.ProxyServerConnectedListener; +import xyz.olivermartin.multichat.proxy.common.listeners.ProxyServerSwitchListener; +import xyz.olivermartin.multichat.proxy.common.listeners.communication.ProxyPlayerActionListener; +import xyz.olivermartin.multichat.proxy.common.listeners.communication.ProxyPlayerChatListener; +import xyz.olivermartin.multichat.proxy.common.listeners.communication.ProxyPlayerMetaListener; +import xyz.olivermartin.multichat.proxy.common.listeners.communication.ProxyServerActionListener; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyFileStoreManager; +import xyz.olivermartin.multichat.proxy.common.storage.files.*; + import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.HashSet; import java.util.Set; -import java.util.UUID; import java.util.concurrent.TimeUnit; -import com.olivermartin410.plugins.TChatInfo; -import com.olivermartin410.plugins.TGroupChatInfo; - -import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.connection.ProxiedPlayer; -import net.md_5.bungee.api.event.PostLoginEvent; -import net.md_5.bungee.api.event.ServerSwitchEvent; -import net.md_5.bungee.api.plugin.Listener; -import net.md_5.bungee.api.plugin.Plugin; -import net.md_5.bungee.config.Configuration; -import net.md_5.bungee.event.EventHandler; - /** * The MAIN MultiChat Class *

This class is the main plugin. All plugin enable and disable control happens here.

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ -public class MultiChat extends Plugin implements Listener { - - public static final String LATEST_VERSION = "1.9.5"; - - public static final String[] ALLOWED_VERSIONS = new String[] { - - LATEST_VERSION, - "1.9.4", - "1.9.3", - "1.9.2", - "1.9.1", - "1.9", - "1.8.2", - "1.8.1", - "1.8", - "1.7.5", - "1.7.4", - "1.7.3", - "1.7.2", - "1.7.1", - "1.7", - "1.6.2", - "1.6.1", - "1.6", - "1.5.2", - "1.5.1", - "1.5", - "1.4.2", - "1.4.1", - "1.4", - "1.3.4", - "1.3.3", - "1.3.2", - "1.3.1", - "1.3" - - }; - - public static Map modchatpreferences = new HashMap(); - public static Map adminchatpreferences = new HashMap(); - public static Map groupchats = new HashMap(); - - public static Map viewedchats = new HashMap(); - public static Map lastmsg = new HashMap(); - public static List allspy = new ArrayList(); - public static List socialspy = new ArrayList(); - - public static File configDir; - public static String configversion; - - public static boolean frozen; - - public static String defaultChannel = ""; - public static boolean forceChannelOnJoin = false; - - public static boolean logPMs = true; - public static boolean logStaffChat = true; - public static boolean logGroupChat = true; - - private static MultiChat instance; - - public static boolean premiumVanish = false; - public static boolean hideVanishedStaffInMsg = true; - public static boolean hideVanishedStaffInStaffList = true; - public static boolean hideVanishedStaffInJoin = true; - - public static List legacyServers = new ArrayList(); - - public static MultiChat getInstance() { - return instance; - } - - public void backup() { - - getProxy().getScheduler().schedule(this, new Runnable() { - - public void run() { - - getLogger().info("Commencing backup!"); - - saveChatInfo(); - saveGroupChatInfo(); - saveGroupSpyInfo(); - saveGlobalChatInfo(); - saveSocialSpyInfo(); - saveAnnouncements(); - saveBulletins(); - saveCasts(); - saveMute(); - saveIgnore(); - UUIDNameManager.saveUUIDS(); - - getLogger().info("Backup complete. Any errors reported above."); - - } - - }, 1L, 60L, TimeUnit.MINUTES); - - } - - public void fetchDisplayNames() { - - getProxy().getScheduler().schedule(this, new Runnable() { - - public void run() { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - - for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) { - if (player.getServer() != null) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - } - - } - - } - - }, 1L, 5L, TimeUnit.MINUTES); - - } - - @EventHandler - public void onLogin(PostLoginEvent event) { - - fetchDisplayNameOnce(event.getPlayer().getName()); - - } - - @EventHandler - public void onServerSwitch(ServerSwitchEvent event) { - - fetchDisplayNameOnce(event.getPlayer().getName()); - - } - - public void fetchDisplayNameOnce(final String playername) { - - getProxy().getScheduler().schedule(this, new Runnable() { - - public void run() { - - try { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - - ProxiedPlayer player = getProxy().getPlayer(playername); - if (player.getServer() != null) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - - } - } catch (NullPointerException ex) { /* EMPTY */ } - - } - - }, 0L, TimeUnit.SECONDS); - - getProxy().getScheduler().schedule(this, new Runnable() { - - public void run() { - - try { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - - ProxiedPlayer player = getProxy().getPlayer(playername); - if (player.getServer() != null) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - - } - } - - catch (NullPointerException ex) { /* EMPTY */ } - } - - }, 1L, TimeUnit.SECONDS); - - getProxy().getScheduler().schedule(this, new Runnable() { - - public void run() { - - try { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - - ProxiedPlayer player = getProxy().getPlayer(playername); - if (player.getServer() != null) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - - } - - } catch (NullPointerException ex) { /* EMPTY */ } - - } - - }, 2L, TimeUnit.SECONDS); - - getProxy().getScheduler().schedule(this, new Runnable() { - - public void run() { - - try { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - - ProxiedPlayer player = getProxy().getPlayer(playername); - if (player.getServer() != null) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - - } - - } catch (NullPointerException ex) { /* EMPTY */ } - - } - - }, 4L, TimeUnit.SECONDS); - - } - - public void onEnable() { - - instance = this; - - @SuppressWarnings("unused") - Metrics metrics = new Metrics(this); - - configDir = getDataFolder(); - if (!getDataFolder().exists()) { - System.out.println("[MultiChat] Creating plugin directory!"); - getDataFolder().mkdirs(); - } - - String translationsDir = configDir.toString() + File.separator + "translations"; - if (!new File(translationsDir).exists()) { - System.out.println("[MultiChat] Creating translations directory!"); - new File(translationsDir).mkdirs(); - } - - ConfigManager.getInstance().registerHandler("config.yml", configDir); - ConfigManager.getInstance().registerHandler("joinmessages.yml", configDir); - ConfigManager.getInstance().registerHandler("messages.yml", configDir); - ConfigManager.getInstance().registerHandler("chatcontrol.yml", configDir); - - ConfigManager.getInstance().registerHandler("messages_fr.yml", new File(translationsDir)); - ConfigManager.getInstance().registerHandler("joinmessages_fr.yml", new File(translationsDir)); - ConfigManager.getInstance().registerHandler("config_fr.yml", new File(translationsDir)); - ConfigManager.getInstance().registerHandler("chatcontrol_fr.yml", new File(translationsDir)); - - Configuration configYML = ConfigManager.getInstance().getHandler("config.yml").getConfig(); - Configuration chatcontrolYML = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - configversion = configYML.getString("version"); - - if (Arrays.asList(ALLOWED_VERSIONS).contains(configversion)) { - - // TODO - Remove for future versions! - if (!configversion.equals(LATEST_VERSION)) { - - getLogger().info("[!!!] [WARNING] YOUR CONFIG FILES ARE NOT THE LATEST VERSION"); - getLogger().info("[!!!] [WARNING] MULTICHAT 1.8 INTRODUCES SEVERAL NEW FEATURES WHICH ARE NOT IN YOUR OLD FILE"); - getLogger().info("[!!!] [WARNING] THE PLUGIN SHOULD WORK WITH THE OLDER FILE, BUT IS NOT SUPPORTED!"); - getLogger().info("[!!!] [WARNING] PLEASE BACKUP YOUR OLD CONFIG FILES AND DELETE THEM FROM THE MULTICHAT FOLDER SO NEW ONES CAN BE GENERATED!"); - getLogger().info("[!!!] [WARNING] THANK YOU"); - - } - - // Register listeners - getProxy().getPluginManager().registerListener(this, new Events()); - getProxy().getPluginManager().registerListener(this, this); - - // Register communication channels and appropriate listeners - getProxy().registerChannel("multichat:comm"); - getProxy().registerChannel("multichat:prefix"); - getProxy().registerChannel("multichat:suffix"); - getProxy().registerChannel("multichat:dn"); - getProxy().registerChannel("multichat:nick"); - getProxy().registerChannel("multichat:world"); - getProxy().registerChannel("multichat:act"); - getProxy().registerChannel("multichat:pact"); - getProxy().registerChannel("multichat:chat"); - getProxy().registerChannel("multichat:ch"); - getProxy().registerChannel("multichat:ignore"); - getProxy().registerChannel("multichat:pxe"); - getProxy().registerChannel("multichat:ppxe"); - getProxy().getPluginManager().registerListener(this, new BungeeComm()); - - // Register commands - registerCommands(configYML, chatcontrolYML); - - System.out.println("[MultiChat] Config Version: " + configversion); - - // Run start-up routines - Startup(); - UUIDNameManager.Startup(); - - // Set up chat control stuff - if (chatcontrolYML.contains("link_control")) { - ChatControl.controlLinks = chatcontrolYML.getBoolean("link_control"); - ChatControl.linkMessage = chatcontrolYML.getString("link_removal_message"); - if (chatcontrolYML.contains("link_regex")) { - ChatControl.linkRegex = chatcontrolYML.getString("link_regex"); - } - } - - if (configYML.contains("privacy_settings")) { - logPMs = configYML.getSection("privacy_settings").getBoolean("log_pms"); - logStaffChat = configYML.getSection("privacy_settings").getBoolean("log_staffchat"); - logGroupChat = configYML.getSection("privacy_settings").getBoolean("log_groupchat"); - } - - // Legacy servers for RGB approximation - if (configYML.contains("legacy_servers")) { - legacyServers = configYML.getStringList("legacy_servers"); - } - - // Set default channel - defaultChannel = configYML.getString("default_channel"); - forceChannelOnJoin = configYML.getBoolean("force_channel_on_join"); - - // Set up global chat - GlobalChannel channel = Channel.getGlobalChannel(); - channel.setFormat(configYML.getString("globalformat")); - - // Add all appropriate servers to this hardcoded global chat stream - for (String server : configYML.getStringList("no_global")) { - channel.addServer(server); - } - - // Initiate backup routine - backup(); - - // Fetch display names of all players - fetchDisplayNames(); - - // Manage premiumVanish dependency - if (ProxyServer.getInstance().getPluginManager().getPlugin("PremiumVanish") != null) { - premiumVanish = true; - System.out.println("[MultiChat] Hooked with PremiumVanish!"); - - if (configYML.contains("premium_vanish")) { - hideVanishedStaffInMsg = configYML.getBoolean("premium_vanish.prevent_message"); - hideVanishedStaffInStaffList = configYML.getBoolean("premium_vanish.prevent_staff_list"); - hideVanishedStaffInJoin = configYML.getBoolean("premium_vanish.silence_join"); - } - - } - - } else { - getLogger().info("Config incorrect version! Please repair or delete it!"); - } - } - - public void onDisable() { - - getLogger().info("Thankyou for using MultiChat. Disabling..."); - - saveChatInfo(); - saveGroupChatInfo(); - saveGroupSpyInfo(); - saveGlobalChatInfo(); - saveSocialSpyInfo(); - saveAnnouncements(); - saveBulletins(); - saveCasts(); - saveMute(); - saveIgnore(); - UUIDNameManager.saveUUIDS(); - - } - - public void registerCommands(Configuration configYML, Configuration chatcontrolYML) { - - // Register main commands - getProxy().getPluginManager().registerCommand(this, CommandManager.getAcc()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getAc()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getMcc()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getMc()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getGc()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getGroup()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getGrouplist()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getMultichat()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getMultichatBypass()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getMultiChatExecute()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getDisplay()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getFreezechat()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getHelpme()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getClearchat()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getAnnouncement()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getBulletin()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getCast()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getUsecast()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getIgnore()); - - // Register PM commands - if (configYML.getBoolean("pm")) { - getProxy().getPluginManager().registerCommand(this, CommandManager.getMsg()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getReply()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getSocialspy()); - } - - // Register global chat commands - if (configYML.getBoolean("global")) { - getProxy().getPluginManager().registerCommand(this, CommandManager.getLocal()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getGlobal()); - getProxy().getPluginManager().registerCommand(this, CommandManager.getChannel()); - } - - // Register staff list command /staff - if (configYML.contains("staff_list")) { - if (configYML.getBoolean("staff_list")) { - getProxy().getPluginManager().registerCommand(this, CommandManager.getStafflist()); - } - } else { - getProxy().getPluginManager().registerCommand(this, CommandManager.getStafflist()); - } - - // Register mute command - if (chatcontrolYML.getBoolean("mute")) { - getProxy().getPluginManager().registerCommand(this, CommandManager.getMute()); - } - - } - - public void unregisterCommands(Configuration configYML, Configuration chatcontrolYML) { - - // Unregister main commands - getProxy().getPluginManager().unregisterCommand(CommandManager.getAcc()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getAc()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getMcc()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getMc()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getGc()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getGroup()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getGrouplist()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getMultichat()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getMultichatBypass()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getMultiChatExecute()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getDisplay()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getFreezechat()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getHelpme()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getClearchat()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getAnnouncement()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getBulletin()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getCast()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getUsecast()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getIgnore()); - - // Unregister PM commands - if (configYML.getBoolean("pm")) { - getProxy().getPluginManager().unregisterCommand(CommandManager.getMsg()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getReply()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getSocialspy()); - } - - // Unregister global chat commands - if (configYML.getBoolean("global")) { - getProxy().getPluginManager().unregisterCommand(CommandManager.getLocal()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getGlobal()); - getProxy().getPluginManager().unregisterCommand(CommandManager.getChannel()); - } - - // Unregister staff list command /staff - if (configYML.contains("staff_list")) { - if (configYML.getBoolean("staff_list")) { - getProxy().getPluginManager().unregisterCommand(CommandManager.getStafflist()); - } - } else { - getProxy().getPluginManager().unregisterCommand(CommandManager.getStafflist()); - } - - // UnRegister mute command - if (chatcontrolYML.getBoolean("mute")) { - getProxy().getPluginManager().unregisterCommand(CommandManager.getMute()); - } - - } - - public static void saveAnnouncements() { - - try { - File file = new File(configDir, "Announcements.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(Announcements.getAnnouncementList()); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the announcements file!"); - e.printStackTrace(); - } - - } - - public static void saveBulletins() { - - try { - File file = new File(configDir, "Bulletins.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeBoolean(Bulletins.isEnabled()); - out.writeInt(Bulletins.getTimeBetween()); - out.writeObject(Bulletins.getArrayList()); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the bulletins file!"); - e.printStackTrace(); - } - - } - - public static void saveChatInfo() { - - try { - File file = new File(configDir, "StaffChatInfo.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(modchatpreferences); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the mod chat info file!"); - e.printStackTrace(); - } - - try { - File file = new File(configDir, "AdminChatInfo.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(adminchatpreferences); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the admin chat info file!"); - e.printStackTrace(); - } - - } - - public static void saveGroupChatInfo() { - - try { - File file = new File(configDir, "GroupChatInfo.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(groupchats); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the group chat info file!"); - e.printStackTrace(); - } - - } - - public static void saveCasts() { - - try { - File file = new File(configDir, "Casts.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(CastControl.castList); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the casts file!"); - e.printStackTrace(); - } - - } - - public static void saveGroupSpyInfo() { - - try { - File file = new File(configDir, "GroupSpyInfo.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(allspy); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the group spy info file!"); - e.printStackTrace(); - } - - } - - public static void saveSocialSpyInfo() { - - try { - File file = new File(configDir, "SocialSpyInfo.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(socialspy); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the social spy info file!"); - e.printStackTrace(); - } - - } - - public static void saveGlobalChatInfo() { - - try { - File file = new File(configDir, "GlobalChatInfo.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(ChatModeManager.getInstance().getData()); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the global chat info file!"); - e.printStackTrace(); - } - - } - - public static void saveMute() { - - try { - File file = new File(configDir, "Mute.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(ChatControl.getMutedPlayers()); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the mute file!"); - e.printStackTrace(); - } - - } - - public static void saveIgnore() { - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (config.getBoolean("session_ignore")) return; - - try { - File file = new File(configDir, "Ignore.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(ChatControl.getIgnoreMap()); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the ignore file!"); - e.printStackTrace(); - } - - } - - @SuppressWarnings("unchecked") - public static HashMap loadModChatInfo() { - - HashMap result = null; - - try { - File file = new File(configDir, "StaffChatInfo.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (HashMap)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the mod chat info file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static void loadBulletins() { - - ArrayList result = null; - boolean enabled = false; - int timeBetween = 0; - - try { - File file = new File(configDir, "Bulletins.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - enabled = in.readBoolean(); - timeBetween = in.readInt(); - result = (ArrayList)in.readObject(); - in.close(); - Bulletins.setArrayList(result); - if (enabled) { - Bulletins.startBulletins(timeBetween); - } - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the bulletins file!"); - e.printStackTrace(); - } - - } - - @SuppressWarnings("unchecked") - public static HashMap loadAnnouncements() { - - HashMap result = null; - - try { - File file = new File(configDir, "Announcements.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (HashMap)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the announcements file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static HashMap loadAdminChatInfo() { - - HashMap result = null; - - try { - File file = new File(configDir, "AdminChatInfo.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (HashMap)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the admin chat info file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static HashMap loadCasts() { - - HashMap result = null; - - try { - File file = new File(configDir, "Casts.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (HashMap)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the casts file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static HashMap loadGroupChatInfo() { - - HashMap result = null; - - try { - File file = new File(configDir, "GroupChatInfo.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (HashMap)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the group chat info file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static List loadGroupSpyInfo() { - - List result = null; - - try { - File file = new File(configDir, "GroupSpyInfo.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (List)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the group spy info file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static List loadSocialSpyInfo() { - - List result = null; - - try { - File file = new File(configDir, "SocialSpyInfo.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (List)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the social spy info file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static Map loadGlobalChatInfo() { - - Map result = null; - - try { - File file = new File(configDir, "GlobalChatInfo.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (Map)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the global chat info file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static Set loadMute() { - - Set result = null; - - try { - File file = new File(configDir, "Mute.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (Set)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the mute file!"); - e.printStackTrace(); - } - - return result; - - } - - @SuppressWarnings("unchecked") - public static Map> loadIgnore() { - - Configuration config = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig(); - - if (config.getBoolean("session_ignore")) return new HashMap>(); - - Map> result = null; - - try { - File file = new File(configDir, "Ignore.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (Map>)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[MultiChat] [Load Error] An error has occured reading the ignore file!"); - e.printStackTrace(); - } - - return result; - - } - - public static void Startup() { - - System.out.println("[MultiChat] Starting load routine for data files"); - - File f = new File(configDir, "StaffChatInfo.dat"); - File f2 = new File(configDir, "AdminChatInfo.dat"); - - if ((f.exists()) && (!f.isDirectory()) && (f2.exists()) && (!f2.isDirectory())) { - - modchatpreferences.putAll(loadModChatInfo()); - adminchatpreferences.putAll(loadAdminChatInfo()); - - } else { - - System.out.println("[MultiChat] Some staff chat files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Welcome to MultiChat! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveChatInfo(); - System.out.println("[MultiChat] The files were created!"); - - } - - File f3 = new File(configDir, "GroupChatInfo.dat"); - - if ((f3.exists()) && (!f3.isDirectory())) { - - groupchats.putAll(loadGroupChatInfo()); - - } else { - - System.out.println("[MultiChat] Some group chat files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Enabling Group Chats! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveGroupChatInfo(); - System.out.println("[MultiChat] The files were created!"); - - } - - File f4 = new File(configDir, "GroupSpyInfo.dat"); - - if ((f4.exists()) && (!f4.isDirectory())) { - - allspy = loadGroupSpyInfo(); - - } else { - - System.out.println("[MultiChat] Some group spy files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Enabling Group-Spy! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveGroupSpyInfo(); - System.out.println("[MultiChat] The files were created!"); - - } - - File f5 = new File(configDir, "GlobalChatInfo.dat"); - - if ((f5.exists()) && (!f5.isDirectory())) { - - ChatModeManager.getInstance().loadData(loadGlobalChatInfo()); - - } else { - - System.out.println("[MultiChat] Some global chat files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Enabling Global Chat! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveGlobalChatInfo(); - System.out.println("[MultiChat] The files were created!"); - - } - - File f6 = new File(configDir, "SocialSpyInfo.dat"); - - if ((f6.exists()) && (!f6.isDirectory())) { - - socialspy = loadSocialSpyInfo(); - - } else { - - System.out.println("[MultiChat] Some social spy files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Enabling Social Spy! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveGroupSpyInfo(); - System.out.println("[MultiChat] The files were created!"); - - } - - File f7 = new File(configDir, "Announcements.dat"); - - if ((f7.exists()) && (!f7.isDirectory())) { - - Announcements.loadAnnouncementList((loadAnnouncements())); - - } else { - - System.out.println("[MultiChat] Some announcements files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Welcome to MultiChat! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveAnnouncements(); - System.out.println("[MultiChat] The files were created!"); - - } - - File f8 = new File(configDir, "Bulletins.dat"); - - if ((f8.exists()) && (!f8.isDirectory())) { - - loadBulletins(); - - } else { - - System.out.println("[MultiChat] Some bulletins files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Welcome to MultiChat! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveBulletins(); - System.out.println("[MultiChat] The files were created!"); - - } - - File f9 = new File(configDir, "Casts.dat"); - - if ((f9.exists()) && (!f9.isDirectory())) { - - CastControl.castList = loadCasts(); - - } else { +public class MultiChat extends Plugin { + + public static final String LATEST_VERSION = "1.10"; + + public static final Set ALLOWED_VERSIONS = new HashSet<>(Arrays.asList( + LATEST_VERSION, + "1.9.5", + "1.9.4", + "1.9.3", + "1.9.2", + "1.9.1", + "1.9", + "1.8.2", + "1.8.1", + "1.8", + "1.7.5", + "1.7.4", + "1.7.3", + "1.7.2", + "1.7.1", + "1.7", + "1.6.2", + "1.6.1", + "1.6", + "1.5.2", + "1.5.1", + "1.5", + "1.4.2", + "1.4.1", + "1.4", + "1.3.4", + "1.3.3", + "1.3.2", + "1.3.1", + "1.3" + )); + + // Config values + public static boolean premiumVanish = false; + + public void fetchDisplayNames() { + + getProxy().getScheduler().schedule(this, () -> { + + if (ProxyConfigs.CONFIG.isFetchSpigotDisplayNames()) { + + for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) { + if (player.getServer() != null) { + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(player.getName(), player.getServer().getInfo()); + } + } + + } + + }, 1L, 5L, TimeUnit.MINUTES); + + } + + public void onEnable() { + + MultiChatProxy.getInstance().registerPlugin(this); + + @SuppressWarnings("unused") + Metrics metrics = new Metrics(this); + + MultiChatProxyPlatform platform = MultiChatProxyPlatform.BUNGEE; + MultiChatProxy.getInstance().registerPlatform(platform); + + ProxyDataStore dataStore = new ProxyDataStore(); + MultiChatProxy.getInstance().registerDataStore(dataStore); + + File configDirectory = getDataFolder(); + if (!getDataFolder().exists()) { + getLogger().info("Creating plugin directory"); + if (!getDataFolder().mkdirs()) { + getLogger().severe("Could not create plugin directory. Check write access to the plugins folder!"); + return; + } + } + MultiChatProxy.getInstance().registerConfigDirectory(configDirectory); + + File translationsDir = new File(configDirectory.toString() + File.separator + "translations"); + if (!translationsDir.exists()) { + getLogger().info("Creating translations directory"); + if (!translationsDir.mkdirs()) { + getLogger().severe("Could not create translations directory. Check write access to the plugins folder!"); + return; + } + } + + ProxyConfigs.ALL.forEach(proxyConfig -> { + proxyConfig.setPlugin(this); + proxyConfig.reloadConfig(); + ProxyConfigs.loadRawConfig(this, proxyConfig.getFileName().replace(".yml", "_fr.yml"), translationsDir); + }); + + + if (!ALLOWED_VERSIONS.contains(ProxyConfigs.CONFIG.getVersion())) { + getLogger().info("Config incorrect version! Please repair or delete it!"); + return; + } + + if (!ProxyConfigs.CONFIG.getVersion().equals(LATEST_VERSION)) { + getLogger().warning("YOUR CONFIG FILES ARE NOT THE LATEST VERSION"); + getLogger().warning("SOME FEATURES OF MULTICHAT ARE ONLY PRESENT IN THE LATEST VERSION OF THE CONFIG"); + } + + // Register listeners + getProxy().getPluginManager().registerListener(this, new Events()); + + // New listeners (1.10+) + getProxy().getPluginManager().registerListener(this, new ProxyLoginListener()); + getProxy().getPluginManager().registerListener(this, new ProxyServerConnectedListener()); + getProxy().getPluginManager().registerListener(this, new ProxyLogoutListener()); + getProxy().getPluginManager().registerListener(this, new ProxyServerSwitchListener()); + + // Communication Channels + getProxy().registerChannel(CommChannels.PLAYER_META); // pmeta + getProxy().registerChannel(CommChannels.PLAYER_CHAT); // pchat + getProxy().registerChannel(CommChannels.SERVER_CHAT); // schat + getProxy().registerChannel(CommChannels.PLAYER_ACTION); // pact + getProxy().registerChannel(CommChannels.SERVER_ACTION); // sact + getProxy().registerChannel(CommChannels.PLAYER_DATA); // pdata + getProxy().registerChannel(CommChannels.SERVER_DATA); // sdata + getProxy().getPluginManager().registerListener(this, new ProxyPlayerMetaListener()); // list - pmeta + getProxy().getPluginManager().registerListener(this, new ProxyPlayerChatListener()); // list - pchat + getProxy().getPluginManager().registerListener(this, new ProxyPlayerActionListener()); // list - pact + getProxy().getPluginManager().registerListener(this, new ProxyServerActionListener()); // list - sact - System.out.println("[MultiChat] Some casts files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Welcome to MultiChat! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveCasts(); - System.out.println("[MultiChat] The files were created!"); + // Register commands + registerCommands(); - } + getLogger().info("Config Version: " + ProxyConfigs.CONFIG.getVersion()); - File f10 = new File(configDir, "Mute.dat"); + // Run start-up routines + ProxyFileStoreManager fileStoreManager = new ProxyFileStoreManager(); - if ((f10.exists()) && (!f10.isDirectory())) { + fileStoreManager.registerFileStore("announcements.dat", + new ProxyAnnouncementsFileStore("Announcements.dat", configDirectory)); - ChatControl.setMutedPlayers(loadMute()); + fileStoreManager.registerFileStore("bulletins.dat", + new ProxyBulletinsFileStore("Bulletins.dat", configDirectory)); - } else { + fileStoreManager.registerFileStore("staffchatinfo.dat", + new ProxyStaffChatFileStore("StaffChatInfo.dat", configDirectory)); - System.out.println("[MultiChat] Some mute files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Welcome to MultiChat! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveMute(); - System.out.println("[MultiChat] The files were created!"); + fileStoreManager.registerFileStore("adminchatinfo.dat", + new ProxyAdminChatFileStore("AdminChatInfo.dat", configDirectory)); - } + fileStoreManager.registerFileStore("groupchatinfo.dat", + new ProxyGroupChatFileStore("GroupChatInfo.dat", configDirectory)); - File f11 = new File(configDir, "Ignore.dat"); + fileStoreManager.registerFileStore("groupspyinfo.dat", + new ProxyGroupSpyFileStore("GroupSpyInfo.dat", configDirectory)); + + fileStoreManager.registerFileStore("casts.dat", + new ProxyCastsFileStore("Casts.dat", configDirectory)); + + fileStoreManager.registerFileStore("socialspyinfo.dat", + new ProxySocialSpyFileStore("SocialSpyInfo.dat", configDirectory)); + + fileStoreManager.registerFileStore("globalchatinfo.dat", + new ProxyGlobalChatFileStore("GlobalChatInfo.dat", configDirectory)); + + fileStoreManager.registerFileStore("mute.dat", + new ProxyMuteFileStore("Mute.dat", configDirectory)); + + fileStoreManager.registerFileStore("ignore.dat", + new ProxyIgnoreFileStore("Ignore.dat", configDirectory)); + + fileStoreManager.registerFileStore("multichatuuidname.dat", + new ProxyUUIDNameFileStore("MultiChatUUIDName.dat", configDirectory)); + + fileStoreManager.registerFileStore("localspyinfo.dat", + new ProxyLocalSpyFileStore("LocalSpyInfo.dat", configDirectory)); + + MultiChatProxy.getInstance().registerFileStoreManager(fileStoreManager); + + // Set default channel + String defaultChannel = ProxyConfigs.CONFIG.getDefaultChannel(); + boolean forceChannelOnJoin = ProxyConfigs.CONFIG.isForceChannelOnJoin(); + + // New context manager and channels + GlobalContext globalContext = new GlobalContext(defaultChannel, forceChannelOnJoin, true); + ContextManager contextManager = new ContextManager(globalContext); + MultiChatProxy.getInstance().registerContextManager(contextManager); + + ChannelManager channelManager = new ChannelManager(); + channelManager.setGlobalChannel(new GlobalStaticProxyChannel("Global Channel", + ProxyConfigs.CONFIG.getGlobalFormat(), + channelManager) + ); + channelManager.setLocalChannel(new LocalChannel("Local Channel", + ProxyConfigs.CONFIG.getGlobalFormat(), + channelManager) + ); + MultiChatProxy.getInstance().registerChannelManager(channelManager); + + // TODO This is just a test channel + channelManager.registerProxyChannel(new StaticProxyChannel("test", new ProxyChannelInfo("A test channel", "&8[&7TEST&8] &f%DISPLAYNAME%&f: ", false, globalContext, "multichat.chat.channel.test", "multichat.chat.channel.test.view"), channelManager)); + + ProxyChatManager chatManager = new ProxyChatManager(); + MultiChatProxy.getInstance().registerChatManager(chatManager); + + MultiChatProxy.getInstance().registerTagManager(new TagManager()); + + /// + + // Initiate backup routine + ProxyBackupManager backupManager = new ProxyBackupManager(); + MultiChatProxy.getInstance().registerBackupManager(backupManager); + backupManager.registerBackupTask(() -> MultiChatProxy.getInstance().getFileStoreManager().save()); + backupManager.startBackup(1L, 60L, TimeUnit.MINUTES); + + // Fetch display names of all players + fetchDisplayNames(); + + // Manage premiumVanish dependency + if (ProxyServer.getInstance().getPluginManager().getPlugin("PremiumVanish") != null) { + premiumVanish = true; + getLogger().info("Hooked with PremiumVanish!"); + } + } - if ((f11.exists()) && (!f11.isDirectory())) { + public void onDisable() { - ChatControl.setIgnoreMap(loadIgnore()); + getLogger().info("Thank you for using MultiChat. Disabling..."); - } else { + MultiChatProxy.getInstance().getFileStoreManager().save(); - System.out.println("[MultiChat] Some ignore files do not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Welcome to MultiChat! :D"); - System.out.println("[MultiChat] Attempting to create hash files!"); - saveMute(); - System.out.println("[MultiChat] The files were created!"); + } - } + public void registerCommands() { - System.out.println("[MultiChat] [COMPLETE] Load sequence finished! (Any errors reported above)"); + // Register main commands + getProxy().getPluginManager().registerCommand(this, CommandManager.getAcc()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getAc()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getMcc()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getMc()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getGc()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getGroup()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getGrouplist()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getMultichat()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getMultichatBypass()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getMultiChatExecute()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getDisplay()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getFreezechat()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getHelpme()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getClearchat()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getAnnouncement()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getBulletin()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getCast()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getUsecast()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getIgnore()); + + // Register PM commands + if (ProxyConfigs.CONFIG.isPm()) { + getProxy().getPluginManager().registerCommand(this, CommandManager.getMsg()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getReply()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getSocialspy()); + } + + // Register global chat commands + if (ProxyConfigs.CONFIG.isGlobal()) { + getProxy().getPluginManager().registerCommand(this, CommandManager.getLocal()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getGlobal()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getChannel()); + getProxy().getPluginManager().registerCommand(this, CommandManager.getLocalspy()); + } + + // Register staff list command /staff + if (ProxyConfigs.CONFIG.isStaffList()) { + getProxy().getPluginManager().registerCommand(this, CommandManager.getStafflist()); + } + + // Register mute command + if (ProxyConfigs.CHAT_CONTROL.isMute()) { + getProxy().getPluginManager().registerCommand(this, CommandManager.getMute()); + } + + } + + public void unregisterCommands() { + getProxy().getPluginManager().unregisterCommands(this); + } - } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChatUtil.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChatUtil.java deleted file mode 100644 index 7e81e72f..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChatUtil.java +++ /dev/null @@ -1,151 +0,0 @@ -package xyz.olivermartin.multichat.bungee; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class MultiChatUtil { - - /** - * Reformat the RGB codes into Spigot Native version - * - * @param message - * @return message reformatted - */ - public static String reformatRGB(String message) { - // Translate RGB codes - return message.replaceAll("(?i)\\&(x|#)([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])", "&x&$2&$3&$4&$5&$6&$7"); - } - - public static String approximateHexCodes(String message) { - - message = message.replaceAll("(?i)(\\&|§)x(\\&|§)([0-9A-F])(\\&|§)([0-9A-F])(\\&|§)([0-9A-F])(\\&|§)([0-9A-F])(\\&|§)([0-9A-F])(\\&|§)([0-9A-F])", "&#$3$5$7$9$11$13"); - - List allMatches = new ArrayList(); - Matcher m = Pattern.compile("(?i)\\&(x|#)([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])") - .matcher(message); - while (m.find()) { - allMatches.add(m.group()); - } - - for (String match : allMatches) { - String hexonly = match.split("#")[1]; - String minecraftCode = hexToMinecraft(hexonly); - message = message.replace(match,"§"+minecraftCode); - } - - return message; - - } - - public static String hexToMinecraft(String hex) { - - String rcode = hex.substring(0,2); - String gcode = hex.substring(2,4); - String bcode = hex.substring(4,6); - - int rint = Integer.parseInt(rcode,16); - int gint = Integer.parseInt(gcode,16); - int bint = Integer.parseInt(bcode,16); - - String[] cga = {"000000","0000aa","00aa00","00aaaa","aa0000","aa00aa","ffaa00","aaaaaa","555555","5555ff","55ff55","55ffff","ff5555","ff55ff","ffff55","ffffff"}; - - int diff = 999999999; - int best = -1; - - for (int i = 0; i < 16; i++) { - - String current = cga[i]; - - String rcode2 = current.substring(0,2); - String gcode2 = current.substring(2,4); - String bcode2 = current.substring(4,6); - - int rint2 = Integer.parseInt(rcode2,16); - int gint2 = Integer.parseInt(gcode2,16); - int bint2 = Integer.parseInt(bcode2,16); - - int val = Math.abs(rint-rint2) + Math.abs(gint-gint2) + Math.abs(bint-bint2); - - if (val < diff) { - best = i; - diff = val; - } - - } - - return Integer.toHexString(best); - - } - - /** - * Concatenate the arguments together to get the message as a string - * - * @param args The arguments of the command - * @param start The (zero-indexed) starting index of the message (inclusive) - * @param end The (zero-indexed) finishing index of the message (inclusive) - * @return The concatenated message - */ - public static String getMessageFromArgs(String[] args, int start, int end) { - - int counter = 0; - String message = ""; - for (String arg : args) { - if (counter >= start && counter <= end) { - if (counter != end) { - message = message + arg + " "; - } else { - message = message + arg; - } - } - counter++; - } - - return message; - - } - - /** - * Concatenate the arguments together to get the message as a string - * - * @param args The arguments of the command - * @param start The (zero-indexed) starting index of the message (inclusive) - * @return The concatenated message - */ - public static String getMessageFromArgs(String[] args, int start) { - - return getMessageFromArgs(args, start, args.length - 1); - - } - - /** - * Concatenate the arguments together to get the message as a string - * - * @param args The arguments of the command - * @return The concatenated message - */ - public static String getMessageFromArgs(String[] args) { - - return getMessageFromArgs(args, 0, args.length - 1); - - } - - public static String getStringFromCollection(Collection collection) { - - String result = ""; - - for (String item : collection) { - if (result.equals("")) { - result = result + item; - } else { - result = result + " " + item; - } - } - - return result; - - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMeta.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMeta.java index 5b013937..7e01c695 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMeta.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMeta.java @@ -7,7 +7,7 @@ public class PlayerMeta { public UUID uuid; public String name; public String nick; - public String spigotDisplayName; + public String localDisplayName; public String prefix; public String suffix; public String world; @@ -16,14 +16,14 @@ public PlayerMeta(UUID uuid, String name) { this.uuid = uuid; this.name = name; nick = name; - spigotDisplayName = nick; + localDisplayName = nick; prefix = ""; suffix = ""; world = ""; } public String getSpigotDisplayname() { - return this.spigotDisplayName; + return this.localDisplayName; } /*public String getDisplayName(String format) { @@ -36,7 +36,7 @@ public String getSpigotDisplayname() { displayName = displayName.replaceAll("%NICK%", nick); displayName = displayName.replaceAll("%UUID%", uuid.toString()); - displayName = displayName.replaceAll("&(?=[a-f,0-9,k-o,r])", "§"); + displayName = displayName.replaceAll("&(?=[a-f,0-9,k-o,r])", "§"); return displayName; diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMetaManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMetaManager.java index d21ca316..cf022dc9 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMetaManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PlayerMetaManager.java @@ -7,105 +7,58 @@ import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; public class PlayerMetaManager { - static { - instance = new PlayerMetaManager(); - } + static { + instance = new PlayerMetaManager(); + } - private static PlayerMetaManager instance; + private static PlayerMetaManager instance; - public static PlayerMetaManager getInstance() { - return instance; - } + public static PlayerMetaManager getInstance() { + return instance; + } - // END OF STATIC + // END OF STATIC - private Map metaMap; + private Map metaMap; - public PlayerMetaManager() { - this.metaMap = new HashMap(); - } + public PlayerMetaManager() { + this.metaMap = new HashMap<>(); + } - public void registerPlayer(UUID uuid, String name) { - this.metaMap.put(uuid, new PlayerMeta(uuid, name)); - } + public void registerPlayer(UUID uuid, String name) { + this.metaMap.put(uuid, new PlayerMeta(uuid, name)); + } - public void unregisterPlayer(UUID uuid) { - metaMap.remove(uuid); - } + public void unregisterPlayer(UUID uuid) { + metaMap.remove(uuid); + } - public Optional getPlayer(UUID uuid) { - if (!metaMap.containsKey(uuid)) return Optional.empty(); - return Optional.of(metaMap.get(uuid)); - } + public Optional getPlayer(UUID uuid) { + if (!metaMap.containsKey(uuid)) return Optional.empty(); + return Optional.of(metaMap.get(uuid)); + } - public void updateDisplayName(UUID uuid) { + public void updateDisplayName(UUID uuid) { - DebugManager.log("[PlayerMetaManager] Updating display name..."); + DebugManager.log("[PlayerMetaManager] Updating display name..."); - Optional opm = getPlayer(uuid); + Optional opm = getPlayer(uuid); - if (!opm.isPresent()) return; + if (!opm.isPresent()) return; - DebugManager.log("[PlayerMetaManager] Player is present!"); + DebugManager.log("[PlayerMetaManager] Player is present!"); - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true && player != null) { - - DebugManager.log("[PlayerMetaManager] Fetch Spigot Display Names is true"); - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("set_display_name")) { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("set_display_name")) { - - DebugManager.log("[PlayerMetaManager] MultiChat is in charge of display names"); - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("display_name_format")) { - //player.setDisplayName(opm.get().getDisplayName(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("display_name_format"))); - - DebugManager.log("[PlayerMetaManager] Set as: " + opm.get().getSpigotDisplayname()); - - player.setDisplayName(opm.get().getSpigotDisplayname()); - } else { - //player.setDisplayName(opm.get().getDisplayName("%PREFIX%%NICK%%SUFFIX%")); - - DebugManager.log("[PlayerMetaManager] Set as: " + opm.get().getSpigotDisplayname()); - - player.setDisplayName(opm.get().getSpigotDisplayname()); - } - } else { - - DebugManager.log("[PlayerMetaManager] MultiChat is NOT in charge of display names!"); - - DebugManager.log("[PlayerMetaManager] Set as: " + opm.get().getSpigotDisplayname()); - - player.setDisplayName(opm.get().getSpigotDisplayname()); - - } - - } else { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("display_name_format")) { - //player.setDisplayName(opm.get().getDisplayName(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("display_name_format"))); - // TODO Maybe new option for "fetch_spigot_displayname"? - - DebugManager.log("[PlayerMetaManager] Set as: " + opm.get().getSpigotDisplayname()); - - player.setDisplayName(opm.get().getSpigotDisplayname()); - } else { - //player.setDisplayName(opm.get().getDisplayName("%PREFIX%%NICK%%SUFFIX%")); - - DebugManager.log("[PlayerMetaManager] Set as: " + opm.get().getSpigotDisplayname()); - - player.setDisplayName(opm.get().getSpigotDisplayname()); - } - } - - } - - } + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + // TODO: [ConfigRefactor] Decide whatever the hell this was supposed to be + if (ProxyConfigs.CONFIG.isFetchSpigotDisplayNames() && player != null) { + DebugManager.log("[PlayerMetaManager] Fetch Spigot Display Names is true"); + DebugManager.log("[PlayerMetaManager] Set as: " + opm.get().getSpigotDisplayname()); + player.setDisplayName(opm.get().getSpigotDisplayname()); + } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PrivateMessageManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PrivateMessageManager.java index 94fdf011..73417cc2 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PrivateMessageManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/PrivateMessageManager.java @@ -1,12 +1,16 @@ package xyz.olivermartin.multichat.bungee; -import java.util.UUID; - -import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.Collection; +import java.util.Optional; +import java.util.UUID; public class PrivateMessageManager { @@ -28,59 +32,70 @@ private PrivateMessageManager() { chatfix = new ChatManipulation(); } + private void displayMessage(ProxiedPlayer player, String rawMessage, String replacement) { + + rawMessage = MultiChatUtil.translateColorCodes(rawMessage); + replacement = MultiChatUtil.translateColorCodes(replacement); + + if (ProxyConfigs.CONFIG.isLegacyServer(player.getServer().getInfo().getName())) { + rawMessage = MultiChatUtil.approximateRGBColorCodes(rawMessage); + replacement = MultiChatUtil.approximateRGBColorCodes(replacement); + } + + player.sendMessage(ProxyJsonUtils.parseMessage(rawMessage, "%MESSAGE%", replacement)); + + } + + private void displayConsoleMessage(String rawMessage, String replacement) { + + rawMessage = MultiChatUtil.approximateRGBColorCodes(MultiChatUtil.translateColorCodes(rawMessage)); + replacement = MultiChatUtil.approximateRGBColorCodes(MultiChatUtil.translateColorCodes(replacement)); + ProxyServer.getInstance().getConsole().sendMessage(ProxyJsonUtils.parseMessage(rawMessage, "%MESSAGE%", replacement)); + + } + + private void updateLastMessage(UUID sender, UUID target) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + ds.getLastMsg().put(sender, target); + ds.getLastMsg().put(target, sender); + + } + public void sendMessage(String message, ProxiedPlayer sender, ProxiedPlayer target) { - message = MultiChatUtil.reformatRGB(message); + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); - String messageoutformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmout"); - String messageinformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmin"); - String messagespyformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmspy"); + // Replace placeholders (SENDER) + String finalmessage = chatfix.replaceMsgVars(ProxyConfigs.CONFIG.getPmOutFormat(), message, sender, target); - String finalmessage = chatfix.replaceMsgVars(messageoutformat, message, sender, target); - if (MultiChat.legacyServers.contains(sender.getServer().getInfo().getName())) { - sender.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', finalmessage)))); - } else { - sender.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); - } + displayMessage(sender, finalmessage, message); - finalmessage = chatfix.replaceMsgVars(messageinformat, message, sender, target); - if (MultiChat.legacyServers.contains(target.getServer().getInfo().getName())) { - target.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', finalmessage)))); - } else { - target.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); - } + // Replace placeholders (TARGET) + finalmessage = chatfix.replaceMsgVars(ProxyConfigs.CONFIG.getPmInFormat(), message, sender, target); + + displayMessage(target, finalmessage, message); + + // Replace placeholders (SPY) + finalmessage = chatfix.replaceMsgVars(ProxyConfigs.CONFIG.getPmSpyFormat(), message, sender, target); - finalmessage = chatfix.replaceMsgVars(messagespyformat, message, sender, target); for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { if ((onlineplayer.hasPermission("multichat.staff.spy")) - && (MultiChat.socialspy.contains(onlineplayer.getUniqueId())) + && (ds.getSocialSpy().contains(onlineplayer.getUniqueId())) && (onlineplayer.getUniqueId() != sender.getUniqueId()) && (onlineplayer.getUniqueId() != target.getUniqueId()) && (!(sender.hasPermission("multichat.staff.spy.bypass") || target.hasPermission("multichat.staff.spy.bypass")))) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', finalmessage)))); - } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); - } + displayMessage(onlineplayer, finalmessage, message); } } - if (MultiChat.lastmsg.containsKey(sender.getUniqueId())) { - MultiChat.lastmsg.remove(sender.getUniqueId()); - } - - MultiChat.lastmsg.put(sender.getUniqueId(), target.getUniqueId()); - - if (MultiChat.lastmsg.containsKey(target.getUniqueId())) { - MultiChat.lastmsg.remove(target.getUniqueId()); - } - - MultiChat.lastmsg.put(target.getUniqueId(), sender.getUniqueId()); + // Update the last message map to be used for /r + updateLastMessage(sender.getUniqueId(), target.getUniqueId()); ConsoleManager.logSocialSpy(sender.getName(), target.getName(), message); @@ -88,101 +103,96 @@ public void sendMessage(String message, ProxiedPlayer sender, ProxiedPlayer targ public void sendMessageConsoleTarget(String message, ProxiedPlayer sender) { - message = MultiChatUtil.reformatRGB(message); + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); - String messageoutformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmout"); - String messageinformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmin"); - String messagespyformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmspy"); + // Replace placeholders (SENDER) + String finalmessage = chatfix.replaceMsgConsoleTargetVars(ProxyConfigs.CONFIG.getPmOutFormat(), message, sender); - String finalmessage = chatfix.replaceMsgConsoleTargetVars(messageoutformat, message, (ProxiedPlayer)sender); - if (MultiChat.legacyServers.contains(sender.getServer().getInfo().getName())) { - sender.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', finalmessage)))); - } else { - sender.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); - } + displayMessage(sender, finalmessage, message); + + // Replace placeholders (TARGET) (CONSOLE) + finalmessage = chatfix.replaceMsgConsoleTargetVars(ProxyConfigs.CONFIG.getPmInFormat(), message, sender); - finalmessage = chatfix.replaceMsgConsoleTargetVars(messageinformat, message, (ProxiedPlayer)sender); - ProxyServer.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); + displayConsoleMessage(finalmessage, message); + + // Replace placeholders (SPY) + finalmessage = chatfix.replaceMsgConsoleTargetVars(ProxyConfigs.CONFIG.getPmSpyFormat(), message, sender); - finalmessage = chatfix.replaceMsgConsoleTargetVars(messagespyformat, message, (ProxiedPlayer)sender); for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { if ((onlineplayer.hasPermission("multichat.staff.spy")) - && (MultiChat.socialspy.contains(onlineplayer.getUniqueId())) - && (onlineplayer.getUniqueId() != ((ProxiedPlayer)sender).getUniqueId()) + && (ds.getSocialSpy().contains(onlineplayer.getUniqueId())) + && (onlineplayer.getUniqueId() != sender.getUniqueId()) && (!(sender.hasPermission("multichat.staff.spy.bypass")))) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', finalmessage)))); - } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); - } + displayMessage(onlineplayer, finalmessage, message); } } - if (MultiChat.lastmsg.containsKey(((ProxiedPlayer)sender).getUniqueId())) { - MultiChat.lastmsg.remove(((ProxiedPlayer)sender).getUniqueId()); - } - - MultiChat.lastmsg.put(((ProxiedPlayer)sender).getUniqueId(), new UUID(0L, 0L)); - - if (MultiChat.lastmsg.containsKey(new UUID(0L, 0L))) { - MultiChat.lastmsg.remove(new UUID(0L, 0L)); - } - - MultiChat.lastmsg.put(new UUID(0L, 0L), ((ProxiedPlayer)sender).getUniqueId()); + // Update the last message map to be used for /r + updateLastMessage(sender.getUniqueId(), new UUID(0L, 0L)); } public void sendMessageConsoleSender(String message, ProxiedPlayer target) { - message = MultiChatUtil.reformatRGB(message); + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); - CommandSender sender = ProxyServer.getInstance().getConsole(); + // Replace placeholders (SENDER) (CONSOLE) + String finalmessage = chatfix.replaceMsgConsoleSenderVars(ProxyConfigs.CONFIG.getPmOutFormat(), message, target); - String messageoutformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmout"); - String messageinformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmin"); - String messagespyformat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("pmspy"); + displayConsoleMessage(finalmessage, message); - String finalmessage = chatfix.replaceMsgConsoleSenderVars(messageoutformat, message, target); - sender.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); + // Replace placeholders (TARGET) + finalmessage = chatfix.replaceMsgConsoleSenderVars(ProxyConfigs.CONFIG.getPmInFormat(), message, target); - finalmessage = chatfix.replaceMsgConsoleSenderVars(messageinformat, message, target); - if (MultiChat.legacyServers.contains(target.getServer().getInfo().getName())) { - target.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', finalmessage)))); - } else { - target.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); - } + displayMessage(target, finalmessage, message); + + // Replace placeholders (SPY) + finalmessage = chatfix.replaceMsgConsoleSenderVars(ProxyConfigs.CONFIG.getPmSpyFormat(), message, target); - finalmessage = chatfix.replaceMsgConsoleSenderVars(messagespyformat, message, target); for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { if ((onlineplayer.hasPermission("multichat.staff.spy")) - && (MultiChat.socialspy.contains(onlineplayer.getUniqueId())) + && (ds.getSocialSpy().contains(onlineplayer.getUniqueId())) && (onlineplayer.getUniqueId() != target.getUniqueId()) && (!(target.hasPermission("multichat.staff.spy.bypass")))) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', finalmessage)))); - } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', finalmessage))); - } + displayMessage(onlineplayer, finalmessage, message); } } - if (MultiChat.lastmsg.containsKey(new UUID(0L, 0L))) { - MultiChat.lastmsg.remove(new UUID(0L, 0L)); + // Update the last message map to be used for /r + updateLastMessage(new UUID(0L, 0L), target.getUniqueId()); + + } + + public Optional getPartialPlayerMatch(String search) { + + // Spigot's own partial match algorithm + Collection spigotMatches = ProxyServer.getInstance().matchPlayer(search); + + if (spigotMatches != null && spigotMatches.size() > 0) { + return Optional.of(spigotMatches.iterator().next()); } - MultiChat.lastmsg.put(new UUID(0L, 0L), target.getUniqueId()); + // Check for names to contain the search + for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { + if (p.getName().toLowerCase().contains(search.toLowerCase())) { + return Optional.of(p); + } + } - if (MultiChat.lastmsg.containsKey(target.getUniqueId())) { - MultiChat.lastmsg.remove(target.getUniqueId()); + // Check for display names to contain the search + for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { + if (p.getDisplayName().toLowerCase().contains(search.toLowerCase())) { + return Optional.of(p); + } } - MultiChat.lastmsg.put(target.getUniqueId(), new UUID(0L, 0L)); + return Optional.empty(); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/StaffChatManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/StaffChatManager.java index 30bdf710..14e8d0f8 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/StaffChatManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/StaffChatManager.java @@ -1,14 +1,17 @@ package xyz.olivermartin.multichat.bungee; -import java.util.Optional; - import com.olivermartin410.plugins.TChatInfo; - -import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import xyz.olivermartin.multichat.bungee.events.PostStaffChatEvent; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.Optional; /** * Staff Chat Manager @@ -19,16 +22,27 @@ public class StaffChatManager { public void sendModMessage(String username, String displayname, String server, String message) { + sendStaffChatMessage("mod", username, displayname, server, message); + } + + public void sendAdminMessage(String username, String displayname, String server, String message) { + sendStaffChatMessage("admin", username, displayname, server, message); + } - message = MultiChatUtil.reformatRGB(message); + private void sendStaffChatMessage(String id, String username, String displayname, String server, String message) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); ChatManipulation chatfix = new ChatManipulation(); - String messageFormat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("modchat.format"); + String messageFormat = id.equals("mod") + ? ProxyConfigs.CONFIG.getModChatFormat() + : ProxyConfigs.CONFIG.getAdminChatFormat(); String original = message; Optional crm; - crm = ChatControl.applyChatRules(original, "staff_chats", username); + ProxiedPlayer proxiedPlayer = username.equals("console") ? null : ProxyServer.getInstance().getPlayer(username); + crm = ChatControl.applyChatRules(proxiedPlayer, original, MessageType.STAFF_CHATS); if (crm.isPresent()) { original = crm.get(); @@ -38,93 +52,60 @@ public void sendModMessage(String username, String displayname, String server, S for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (onlineplayer.hasPermission("multichat.staff.mod")) { + if (onlineplayer.hasPermission("multichat.staff." + id)) { - if (!MultiChat.modchatpreferences.containsKey(onlineplayer.getUniqueId())) { + if (id.equals("mod") && !ds.getModChatPreferences().containsKey(onlineplayer.getUniqueId())) { TChatInfo chatinfo = new TChatInfo(); - chatinfo.setChatColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("modchat.ccdefault").toCharArray()[0]); - chatinfo.setNameColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("modchat.ncdefault").toCharArray()[0]); + chatinfo.setChatColor(ProxyConfigs.CONFIG.getModChatColor()); + chatinfo.setNameColor(ProxyConfigs.CONFIG.getModNameColor()); - MultiChat.modchatpreferences.put(onlineplayer.getUniqueId(), chatinfo); + ds.getModChatPreferences().put(onlineplayer.getUniqueId(), chatinfo); - } - - message = chatfix.replaceModChatVars(messageFormat, username, displayname, server, original, onlineplayer); - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', message)))); - } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', message))); - } - - } - } - - // Trigger PostStaffChatEvent - if (username.equalsIgnoreCase("console")) { - ProxyServer.getInstance().getPluginManager().callEvent(new PostStaffChatEvent("mod", ProxyServer.getInstance().getConsole() , original)); - } else { - if (ProxyServer.getInstance().getPlayer(username) != null) { - ProxyServer.getInstance().getPluginManager().callEvent(new PostStaffChatEvent("mod", ProxyServer.getInstance().getPlayer(username) , original)); - } - } - - ConsoleManager.logModChat("(" + username + ") " + original); - - } - - public void sendAdminMessage(String username, String displayname, String server, String message) { - - message = MultiChatUtil.reformatRGB(message); - - String original = message; - ChatManipulation chatfix = new ChatManipulation(); - String messageFormat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("adminchat.format"); - - Optional crm; - - crm = ChatControl.applyChatRules(original, "staff_chats", username); - - if (crm.isPresent()) { - original = crm.get(); - } else { - return; - } - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - - if (onlineplayer.hasPermission("multichat.staff.admin")) { - - if (!MultiChat.adminchatpreferences.containsKey(onlineplayer.getUniqueId())) { + } else if (id.equals("admin") && !ds.getAdminChatPreferences().containsKey(onlineplayer.getUniqueId())) { TChatInfo chatinfo = new TChatInfo(); - chatinfo.setChatColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("adminchat.ccdefault").toCharArray()[0]); - chatinfo.setNameColor(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("adminchat.ncdefault").toCharArray()[0]); + chatinfo.setChatColor(ProxyConfigs.CONFIG.getAdminChatColor()); + chatinfo.setNameColor(ProxyConfigs.CONFIG.getAdminNameColor()); - MultiChat.adminchatpreferences.put(onlineplayer.getUniqueId(), chatinfo); + ds.getAdminChatPreferences().put(onlineplayer.getUniqueId(), chatinfo); } - message = chatfix.replaceAdminChatVars(messageFormat, username, displayname, server, original, onlineplayer); - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', message)))); + if (id.equals("mod")) { + message = chatfix.replaceModChatVars(messageFormat, username, displayname, server, original, onlineplayer); } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', message))); + message = chatfix.replaceAdminChatVars(messageFormat, username, displayname, server, original, onlineplayer); } + message = MultiChatUtil.translateColorCodes(message); + String originalTranslated = MultiChatUtil.translateColorCodes(original); + + if (ProxyConfigs.CONFIG.isLegacyServer(onlineplayer.getServer().getInfo().getName())) { + message = MultiChatUtil.approximateRGBColorCodes(message); + originalTranslated = MultiChatUtil.approximateRGBColorCodes(originalTranslated); + } + + onlineplayer.sendMessage(ProxyJsonUtils.parseMessage(message, "%MESSAGE%", originalTranslated)); + } } // Trigger PostStaffChatEvent if (username.equalsIgnoreCase("console")) { - ProxyServer.getInstance().getPluginManager().callEvent(new PostStaffChatEvent("admin", ProxyServer.getInstance().getConsole() , original)); + ProxyServer.getInstance().getPluginManager().callEvent(new PostStaffChatEvent(id, ProxyServer.getInstance().getConsole() , original)); } else { if (ProxyServer.getInstance().getPlayer(username) != null) { - ProxyServer.getInstance().getPluginManager().callEvent(new PostStaffChatEvent("admin", ProxyServer.getInstance().getPlayer(username) , original)); + ProxyServer.getInstance().getPluginManager().callEvent(new PostStaffChatEvent(id, ProxyServer.getInstance().getPlayer(username) , original)); } } - ConsoleManager.logAdminChat("(" + username + ") " + original); + if (id.equals("mod")) { + ConsoleManager.logModChat("(" + username + ") " + original); + } else { + ConsoleManager.logAdminChat("(" + username + ") " + original); + } } + } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/UUIDNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/UUIDNameManager.java index 97283381..9383a780 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/UUIDNameManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/UUIDNameManager.java @@ -1,11 +1,5 @@ package xyz.olivermartin.multichat.bungee; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -19,7 +13,7 @@ */ public class UUIDNameManager { - private static Map uuidname = new HashMap(); + public static Map uuidname = new HashMap(); public static void addNew(UUID uuid, String name) { uuidname.put(uuid, name); @@ -33,56 +27,6 @@ public static String getName(UUID uuid) { return (String)uuidname.get(uuid); } - public static void saveUUIDS() { - - try { - File file = new File(MultiChat.configDir, "MultiChatUUIDName.dat"); - FileOutputStream saveFile = new FileOutputStream(file); - ObjectOutputStream out = new ObjectOutputStream(saveFile); - out.writeObject(uuidname); - out.close(); - } catch (IOException e) { - System.out.println("[MultiChat] [Save Error] An error has occured writing the uuid-name file!"); - e.printStackTrace(); - } - - } - - @SuppressWarnings("unchecked") - public static HashMap loadUUIDS() { - - HashMap result = null; - - try { - File file = new File(MultiChat.configDir, "MultiChatUUIDName.dat"); - FileInputStream saveFile = new FileInputStream(file); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (HashMap)in.readObject(); - in.close(); - } catch (IOException|ClassNotFoundException e) { - System.out.println("[ActivityMonitor] [Load Error] An error has occured reading the uuid-name file!"); - e.printStackTrace(); - } - - return result; - - } - - public static void Startup() { - - File f = new File(MultiChat.configDir, "MultiChatUUIDName.dat"); - - if ((f.exists()) && (!f.isDirectory())) { - uuidname.putAll(loadUUIDS()); - } else { - System.out.println("[MultiChat] File for uuid-name conversion does not exist to load. Must be first startup!"); - System.out.println("[MultiChat] Attempting to create hash file!"); - saveUUIDS(); - System.out.println("[MultiChat] The uuid-name file was created!"); - } - - } - public static boolean existsUUID(UUID uuid) { if (uuidname.containsKey(uuid)) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCCommand.java index fdae1eb9..be48e935 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCCommand.java @@ -6,8 +6,10 @@ import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.DebugManager; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; +import xyz.olivermartin.multichat.common.RegexUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * Admin-Chat colour command @@ -18,75 +20,44 @@ */ public class ACCCommand extends Command { - // Command aliases - private static String[] aliases = new String[] {}; - public ACCCommand() { - super("acc", "multichat.staff.mod", aliases); + super("mcacc", "multichat.staff.admin", ProxyConfigs.ALIASES.getAliases("mcacc")); } public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_acc_only_players"); + return; + } + DebugManager.log("[ACCCommand] Command sender is a player"); - // Check correct arguments if (args.length != 2) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_acc_usage"); + return; + } + args[0] = args[0].toLowerCase(); + args[1] = args[1].toLowerCase(); - if ((sender instanceof ProxiedPlayer)) { - MessageManager.sendMessage(sender, "command_acc_usage"); - } else { - MessageManager.sendMessage(sender, "command_acc_only_players"); - } - - } else if ((sender instanceof ProxiedPlayer)) { - - DebugManager.log("[ACCCommand] Command sender is a player"); - - TChatInfo chatinfo = new TChatInfo(); - ProxiedPlayer player = (ProxiedPlayer)sender; - - // Convert args to lowercase - args[0] = args[0].toLowerCase(); - args[1] = args[1].toLowerCase(); - - if ((args[0].equals("a")) || (args[0].equals("b")) || (args[0].equals("c")) || (args[0].equals("d")) - || (args[0].equals("e")) || (args[0].equals("f")) || (args[0].equals("0")) || (args[0].equals("1")) - || (args[0].equals("2")) || (args[0].equals("3")) || (args[0].equals("4")) || (args[0].equals("5")) - || (args[0].equals("6")) || (args[0].equals("7")) || (args[0].equals("8")) || (args[0].equals("9"))) { - - if ((args[1].equals("a")) || (args[1].equals("b")) || (args[1].equals("c")) || (args[1].equals("d")) - || (args[1].equals("e")) || (args[1].equals("f")) || (args[1].equals("0")) || (args[1].equals("1")) - || (args[1].equals("2")) || (args[1].equals("3")) || (args[1].equals("4")) || (args[1].equals("5")) - || (args[1].equals("6")) || (args[1].equals("7")) || (args[1].equals("8")) || (args[1].equals("9"))) { - - DebugManager.log("[ACCCommand] Colour codes are valid"); - - chatinfo.setChatColor(args[0].charAt(0)); - chatinfo.setNameColor(args[1].charAt(0)); - - MultiChat.adminchatpreferences.remove(player.getUniqueId()); - MultiChat.adminchatpreferences.put(player.getUniqueId(), chatinfo); - - DebugManager.log("[ACCCommand] Preferences updated"); - - MessageManager.sendMessage(sender, "command_acc_updated"); - - } else { - - MessageManager.sendMessage(sender, "command_acc_invalid"); - MessageManager.sendMessage(sender, "command_acc_invalid_usage"); - - } + if (!RegexUtil.LEGACY_COLOR.matches(args[0]) || !RegexUtil.LEGACY_COLOR.matches(args[1])) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_acc_invalid"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_acc_invalid_usage"); + return; + } - } else { + DebugManager.log("[ACCCommand] Colour codes are valid"); - MessageManager.sendMessage(sender, "command_acc_invalid"); - MessageManager.sendMessage(sender, "command_acc_invalid_usage"); + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + TChatInfo chatinfo = new TChatInfo(); + ProxiedPlayer player = (ProxiedPlayer)sender; - } + chatinfo.setChatColor(args[0].charAt(0)); + chatinfo.setNameColor(args[1].charAt(0)); - } else { + ds.getAdminChatPreferences().remove(player.getUniqueId()); + ds.getAdminChatPreferences().put(player.getUniqueId(), chatinfo); - MessageManager.sendMessage(sender, "command_acc_only_players"); + DebugManager.log("[ACCCommand] Preferences updated"); - } + ProxyConfigs.MESSAGES.sendMessage(sender, "command_acc_updated"); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCommand.java index c7b1f49d..92065902 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ACCommand.java @@ -3,81 +3,48 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.DebugManager; import xyz.olivermartin.multichat.bungee.Events; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.bungee.StaffChatManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.UUID; /** * Admin-Chat command *

Allows the user to toggle / send a message to admin-chat

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class ACCommand extends Command { - private static String[] aliases = new String[] {}; - - public ACCommand() { - super("ac", "multichat.staff.admin", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - boolean toggleresult; - - if (args.length < 1) { - - if ((sender instanceof ProxiedPlayer)) { - - DebugManager.log("[ACCommand] Command sender is a player"); - - ProxiedPlayer player = (ProxiedPlayer)sender; - toggleresult = Events.toggleAC(player.getUniqueId()); - - DebugManager.log("[ACCommand] AC new toggle state: " + toggleresult); - - if (toggleresult == true) { - MessageManager.sendMessage(sender, "command_ac_toggle_on"); - } else { - MessageManager.sendMessage(sender, "command_ac_toggle_off"); - } - - } else { - - MessageManager.sendMessage(sender, "command_ac_only_players"); - - } - - } else if ((sender instanceof ProxiedPlayer)) { - - DebugManager.log("[ACCommand] Command sender is a player"); - - String message = MultiChatUtil.getMessageFromArgs(args); - - ProxiedPlayer player = (ProxiedPlayer)sender; - StaffChatManager chatman = new StaffChatManager(); - - DebugManager.log("[ACCommand] Next line of code will send the message, if no errors, then it worked!"); - - chatman.sendAdminMessage(player.getName(), player.getDisplayName(), player.getServer().getInfo().getName(), message); - chatman = null; - - } else { - - DebugManager.log("[ACCommand] Command sender is the console"); - - String message = MultiChatUtil.getMessageFromArgs(args); - - StaffChatManager chatman = new StaffChatManager(); - - DebugManager.log("[ACCommand] Next line of code will send the message, if no errors, then it worked!"); - - chatman.sendAdminMessage("CONSOLE", "CONSOLE", "#", message); - chatman = null; - - } - } + public ACCommand() { + super("mcac", "multichat.staff.admin", ProxyConfigs.ALIASES.getAliases("mcac")); + } + + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_ac_only_players"); + return; + } + + UUID playerUID = ((ProxiedPlayer) sender).getUniqueId(); + boolean toggleResult = Events.toggleAC(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_ac_toggle_" + (toggleResult ? "on" : "off")); + return; + } + + String name = "CONSOLE"; + String displayName = "CONSOLE"; + String serverName = "#"; + + if (sender instanceof ProxiedPlayer) { + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + name = proxiedPlayer.getName(); + displayName = proxiedPlayer.getDisplayName(); + serverName = proxiedPlayer.getServer().getInfo().getName(); + } + + new StaffChatManager().sendAdminMessage(name, displayName, serverName, String.join(" ", args)); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/AnnouncementCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/AnnouncementCommand.java index 83b087e7..db017df0 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/AnnouncementCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/AnnouncementCommand.java @@ -1,167 +1,123 @@ package xyz.olivermartin.multichat.bungee.commands; -import java.util.Iterator; -import java.util.Map; +import java.util.Arrays; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.Announcements; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; /** * Announcement Command *

Allows the user to create, remove or use announcements

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class AnnouncementCommand extends Command { - private static String[] aliases = new String[] {"announce"}; - - public AnnouncementCommand() { - super("announcement", "multichat.announce", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - showCommandUsage(sender); - - } else if (args.length == 1) { - - if (args[0].toLowerCase().equals("list")) { - - Map announcementList = Announcements.getAnnouncementList(); - Iterator it = announcementList.keySet().iterator(); - - MessageManager.sendMessage(sender, "command_announcement_list"); - - String currentItem; - while (it.hasNext()) { - currentItem = it.next(); - MessageManager.sendSpecialMessage(sender, "command_announcement_list_item", currentItem + ": " + announcementList.get(currentItem)); - } - - } else if (Announcements.existsAnnouncemnt(args[0].toLowerCase())) { - - Announcements.playAnnouncement(args[0].toLowerCase()); - - } else { - - MessageManager.sendSpecialMessage(sender, "command_announcement_does_not_exist", args[0].toUpperCase()); - - } - - } else if (args.length == 2) { - - if (args[0].toLowerCase().equals("remove")) { - - if (Announcements.removeAnnouncement(args[1].toLowerCase()) == true) { - MessageManager.sendSpecialMessage(sender, "command_announcement_removed", args[1].toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_announcement_does_not_exist", args[1].toUpperCase()); - } - - } else if (args[0].toLowerCase().equals("stop") ) { - - if (Announcements.stopAnnouncement(args[1].toLowerCase()) == true) { - MessageManager.sendSpecialMessage(sender, "command_announcement_stopped", args[1].toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_announcement_stopped_error", args[1].toUpperCase()); - } - - } else { - - showCommandUsage(sender); - } - - } else if (args.length == 3) { - - if (isInteger(args[2])) { - - if (args[0].toLowerCase().equals("start")) { - - if (Announcements.startAnnouncement(args[1].toLowerCase(), Integer.parseInt(args[2])) == true) { - MessageManager.sendSpecialMessage(sender, "command_announcement_started", args[1].toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_announcement_started_error", args[1].toUpperCase()); - } - - } else { - - showCommandUsage(sender); - - } - - } else if (args[0].toLowerCase().equals("add")) { - - if (Announcements.addAnnouncement(args[1].toLowerCase(), args[2]) == true) { - MessageManager.sendSpecialMessage(sender, "command_announcement_added", args[1].toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_announcement_added_error", args[1].toUpperCase()); - } - - } else { - - showCommandUsage(sender); - - } - - } else if (args.length >= 3) { - - if (args[0].toLowerCase().equals("add")) { - - String message = MultiChatUtil.getMessageFromArgs(args, 2); - - if (Announcements.addAnnouncement(args[1].toLowerCase(), message) == true) { - MessageManager.sendSpecialMessage(sender, "command_announcement_added", args[1].toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_announcement_added_error", args[1].toUpperCase()); - } - - } else { - - showCommandUsage(sender); - - } - - } else { - - showCommandUsage(sender); - - } - - } - - public static boolean isInteger(String str) { - - try { - - @SuppressWarnings("unused") - int n = Integer.parseInt(str); - - } catch(NumberFormatException nfe) { - return false; - } - - return true; - } - - private void showCommandUsage(CommandSender sender) { - - MessageManager.sendMessage(sender, "command_announcement_usage"); - sender.sendMessage(new ComponentBuilder("/announcement add ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/announcement remove ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/announcement start ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/announcement stop ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/announcement list").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/announce ").color(ChatColor.AQUA).create()); - - } - + public AnnouncementCommand() { + super("mcannouncement", "multichat.announce", ProxyConfigs.ALIASES.getAliases("mcannouncement")); + } + + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + showCommandUsage(sender); + return; + } + + String arg = args[0].toLowerCase(); + switch (arg) { + case "list": { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_list"); + Announcements.getAnnouncementList().forEach((key, value) -> + ProxyConfigs.MESSAGES.sendMessage(sender, + "command_announcement_list_item", + key + ": +++" + value, + true + ) + ); + return; + } + case "add": { + if (args.length < 3) + break; + + String announcementKey = args[1].toLowerCase(); + String message = String.join(" ", Arrays.copyOfRange(args, 2, args.length)); + if (Announcements.addAnnouncement(announcementKey, message)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_added", announcementKey); + } else { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_added_error", announcementKey); + } + return; + } + case "remove": { + if (args.length < 2) + break; + + String announcementKey = args[1].toLowerCase(); + if (Announcements.removeAnnouncement(announcementKey)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_removed", announcementKey); + } else { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_does_not_exist", announcementKey); + } + return; + } + case "start": { + int timer; + if (args.length < 3 || (timer = parseInt(args[2])) == -1) + break; + + String announcementKey = args[1].toLowerCase(); + if (Announcements.startAnnouncement(announcementKey, timer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_started", announcementKey); + } else { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_started_error", announcementKey); + } + return; + } + case "stop": { + if (args.length < 2) + break; + + String announcementKey = args[1].toLowerCase(); + if (Announcements.stopAnnouncement(announcementKey)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_stopped", announcementKey); + } else { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_stopped_error", announcementKey); + } + return; + } + default: { + if (Announcements.existsAnnouncemnt(arg)) { + Announcements.playAnnouncement(arg); + } else { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_does_not_exist", arg); + } + return; + } + } + + showCommandUsage(sender); + } + + private int parseInt(String str) { + try { + return Integer.parseInt(str); + } catch (NumberFormatException nfe) { + return -1; + } + } + + private void showCommandUsage(CommandSender sender) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_announcement_usage"); + sender.sendMessage(new ComponentBuilder("/announcement add ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/announcement remove ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/announcement start ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/announcement stop ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/announcement list").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/announce ").color(ChatColor.AQUA).create()); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/BulletinCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/BulletinCommand.java index 59c0902a..75d124f5 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/BulletinCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/BulletinCommand.java @@ -1,5 +1,6 @@ package xyz.olivermartin.multichat.bungee.commands; +import java.util.Arrays; import java.util.Iterator; import net.md_5.bungee.api.ChatColor; @@ -7,114 +8,97 @@ import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.Bulletins; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; /** * Bulletin Command *

Allows the user to create, start and stop bulletins

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class BulletinCommand extends Command { - private static String[] aliases = new String[] {"bulletins"}; - - public BulletinCommand() { - super("bulletin", "multichat.bulletin", aliases); - } - - @Override - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - showCommandUsage(sender); - - } else if (args.length == 1) { - - if (args[0].toLowerCase().equals("stop")) { - - Bulletins.stopBulletins(); - MessageManager.sendMessage(sender, "command_bulletin_stopped"); - - } else if (args[0].toLowerCase().equals("list")) { - - int counter = 0; - Iterator it = Bulletins.getIterator(); - - MessageManager.sendMessage(sender, "command_bulletin_list"); - while (it.hasNext()) { - counter++; - MessageManager.sendSpecialMessage(sender, "command_bulletin_list_item", counter + ": " + it.next()); - } - - } else { - - showCommandUsage(sender); - - } - - } else if (args.length == 2) { - - if (args[0].toLowerCase().equals("remove")) { - - try { - - Bulletins.removeBulletin(Integer.parseInt(args[1]) - 1); - MessageManager.sendMessage(sender, "command_bulletin_removed"); - - } catch (Exception e) { - MessageManager.sendMessage(sender, "command_bulletin_invalid_usage"); - } - - } else if (args[0].toLowerCase().equals("start") ) { - - try { - Bulletins.startBulletins(Integer.parseInt(args[1])); - MessageManager.sendMessage(sender, "command_bulletin_started"); - } catch (Exception e) { - MessageManager.sendMessage(sender, "command_bulletin_invalid_usage"); - } - - } else if (args[0].toLowerCase().equals("add") ) { - - Bulletins.addBulletin(args[1]); - MessageManager.sendMessage(sender, "command_bulletin_added"); - - } else { - - showCommandUsage(sender); - - } - - } else if (args.length > 2) { - - if (args[0].toLowerCase().equals("add")) { - - String message = MultiChatUtil.getMessageFromArgs(args, 1); - - Bulletins.addBulletin(message); - MessageManager.sendMessage(sender, "command_bulletin_added"); - } - - } else { - - showCommandUsage(sender); - - } - - } - - private void showCommandUsage(CommandSender sender) { - - MessageManager.sendMessage(sender, "command_bulletin_usage"); - sender.sendMessage(new ComponentBuilder("/bulletin add ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/bulletin remove ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/bulletin start ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/bulletin stop").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/bulletin list").color(ChatColor.AQUA).create()); - - } + public BulletinCommand() { + super("mcbulletin", "multichat.bulletin", ProxyConfigs.ALIASES.getAliases("mcbulletin")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + showCommandUsage(sender); + return; + } + + String arg = args[0].toLowerCase(); + switch (arg) { + case "list": { + // TODO: Refactor Bulletins to change this part properly + int counter = 0; + Iterator it = Bulletins.getIterator(); + + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_list"); + while (it.hasNext()) { + counter++; + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_list_item", counter + ": +++" + it.next(), true); + } + return; + } + case "add": { + if (args.length < 2) + break; + + Bulletins.addBulletin(String.join(" ", Arrays.copyOfRange(args, 1, args.length))); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_added"); + return; + } + case "remove": { + if (args.length < 2) + break; + + int id; + try { + id = Integer.parseInt(args[1]); + } catch (NumberFormatException ignored) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_invalid_usage"); + break; + } + + Bulletins.removeBulletin(id - 1); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_removed"); + return; + } + case "start": { + if (args.length < 2) + break; + + int bulletinDelay; + try { + bulletinDelay = Integer.parseInt(args[1]); + } catch (NumberFormatException ignored) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_invalid_usage"); + break; + } + + Bulletins.startBulletins(bulletinDelay); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_started"); + return; + } + case "stop": { + Bulletins.stopBulletins(); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_stopped"); + return; + } + } + + showCommandUsage(sender); + } + + private void showCommandUsage(CommandSender sender) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_bulletin_usage"); + sender.sendMessage(new ComponentBuilder("/bulletin add ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/bulletin remove ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/bulletin start ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/bulletin stop").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/bulletin list").color(ChatColor.AQUA).create()); + } } \ No newline at end of file diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/CastCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/CastCommand.java index f6982a79..ad2f2e46 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/CastCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/CastCommand.java @@ -1,127 +1,80 @@ package xyz.olivermartin.multichat.bungee.commands; -import java.util.Iterator; - import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.CastControl; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.Arrays; /** * Cast Command *

The Custom broadcAST (CAST) command allows you to create your own customised broadcast formats

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class CastCommand extends Command { - private static String[] aliases = new String[] {}; - - public CastCommand() { - super("cast", "multichat.cast.admin", aliases); - } - - public void showCommandUsage(CommandSender sender) { - MessageManager.sendMessage(sender, "command_cast_usage"); - sender.sendMessage(new ComponentBuilder("/cast add ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/cast remove ").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/cast list").color(ChatColor.AQUA).create()); - sender.sendMessage(new ComponentBuilder("/ ").color(ChatColor.AQUA).create()); - } - - @Override - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - showCommandUsage(sender); - - } else if (args.length == 1) { - - if (args[0].toLowerCase().equals("list")) { - - Iterator it = CastControl.castList.keySet().iterator(); - String currentItem; - - MessageManager.sendMessage(sender, "command_cast_list"); - while (it.hasNext()) { - currentItem = it.next(); - MessageManager.sendSpecialMessage(sender, "command_cast_list_item", currentItem + ": " + CastControl.castList.get(currentItem)); - } - - } else { - showCommandUsage(sender); - } - - } else if (args.length == 2) { - - if (args[0].toLowerCase().equals("remove")) { - - if (CastControl.existsCast(args[1])) { - - CastControl.removeCast(args[1]); - MessageManager.sendSpecialMessage(sender, "command_cast_removed", args[1].toUpperCase()); - - } else { - - MessageManager.sendSpecialMessage(sender, "command_cast_does_not_exist", args[1].toUpperCase()); - } - - } else { - - showCommandUsage(sender); - - } - - } else if (args.length == 3) { - - if (args[0].toLowerCase().equals("add")) { - - if (!(CastControl.existsCast(args[1])) && !args[1].equalsIgnoreCase("cast")) { - - CastControl.addCast(args[1], args[2]); - MessageManager.sendSpecialMessage(sender, "command_cast_added", args[1].toUpperCase()); - - } else { - - MessageManager.sendSpecialMessage(sender, "command_cast_added_error", args[1].toUpperCase()); - } - - } else { - - showCommandUsage(sender); - - } - - } else if (args.length >= 3) { - - if (args[0].toLowerCase().equals("add")) { - - String message = MultiChatUtil.getMessageFromArgs(args, 2); - - if (!CastControl.existsCast(args[1])) { - - CastControl.addCast(args[1], message); - MessageManager.sendSpecialMessage(sender, "command_cast_added", args[1].toUpperCase()); - - } else { - - MessageManager.sendSpecialMessage(sender, "command_cast_added_error", args[1].toUpperCase()); - } - - } else { - - showCommandUsage(sender); - - } - - } else { - - showCommandUsage(sender); - } - } + public CastCommand() { + super("mccast", "multichat.cast.admin", ProxyConfigs.ALIASES.getAliases("mccast")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + showCommandUsage(sender); + return; + } + + String arg = args[0].toLowerCase(); + switch (arg) { + case "list": { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_cast_list"); + CastControl.castList.forEach((key, value) -> + ProxyConfigs.MESSAGES.sendMessage(sender, "command_cast_list_item", key + ": " + value) + ); + return; + } + case "add": { + if (args.length < 3) + break; + + String castName = args[1]; + if (CastControl.existsCast(castName) || castName.equalsIgnoreCase("cast")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_cast_added_error", castName); + return; + } + + CastControl.addCast(castName, String.join(" ", Arrays.copyOfRange(args, 2, args.length))); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_cast_added", castName); + return; + } + case "remove": { + if (args.length < 2) + break; + + String castName = args[1]; + if (!CastControl.existsCast(castName)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_cast_does_not_exist", castName); + return; + } + + CastControl.removeCast(castName); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_cast_removed", castName); + return; + } + } + + showCommandUsage(sender); + } + + public void showCommandUsage(CommandSender sender) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_cast_usage"); + sender.sendMessage(new ComponentBuilder("/cast add ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/cast remove ").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/cast list").color(ChatColor.AQUA).create()); + sender.sendMessage(new ComponentBuilder("/ ").color(ChatColor.AQUA).create()); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ChannelCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ChannelCommand.java index 772eb377..9a99d7ba 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ChannelCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ChannelCommand.java @@ -4,153 +4,138 @@ import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.BungeeComm; -import xyz.olivermartin.multichat.bungee.Channel; import xyz.olivermartin.multichat.bungee.ChatModeManager; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.MessageManager; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.ProxyChannel; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.Optional; +import java.util.UUID; /** * Chat Channel Command *

Players can use this command to switch channels, as well as show and hide specific channels

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class ChannelCommand extends Command { - public ChannelCommand() { - super("channel", "multichat.chat.channel", (String[]) ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("channelcommand").toArray(new String[0])); - } - - private void showHelp(CommandSender sender) { - - MessageManager.sendMessage(sender, "command_channel_help"); - - } - - @Override - public void execute(CommandSender sender, String[] args) { - - if ((sender instanceof ProxiedPlayer)) { - - if ((args.length < 1) || ((args.length == 1) && (args[0].toLowerCase().equals("help")))) { - - showHelp(sender); - - } else if (args.length == 1) { - - showHelp(sender); - - } else if (args.length == 2) { - - String subCommand = args[0].toLowerCase(); - String operand = args[1].toLowerCase(); - - switch (subCommand) { - - case "switch": - if (!sender.hasPermission("multichat.chat.channel.switch")) { - MessageManager.sendMessage(sender, "command_channel_switch_no_permission"); - return; - } - if (operand.equals("local")) { - ChatModeManager.getInstance().setLocal(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendSpecialMessage(sender, "command_channel_switch", operand.toUpperCase()); - } else if (operand.equals("global")) { - ChatModeManager.getInstance().setGlobal(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendSpecialMessage(sender, "command_channel_switch", operand.toUpperCase()); - } else { - MessageManager.sendMessage(sender, "command_channel_does_not_exist"); - } - break; - - case "hide": - if (!sender.hasPermission("multichat.chat.channel.hide")) { - MessageManager.sendMessage(sender, "command_channel_hide_no_permission"); - return; - } - if (operand.equals("local")) { - - if (!ChatModeManager.getInstance().isGlobal(((ProxiedPlayer)sender).getUniqueId())) { - MessageManager.sendMessage(sender, "command_channel_cannot_hide"); - return; - } - - Channel local = Channel.getLocalChannel(); - if (local.isMember(((ProxiedPlayer)sender).getUniqueId())) { - local.addMember(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendSpecialMessage(sender, "command_channel_hide", operand.toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_channel_already_hide", operand.toUpperCase()); - } - - } else if (operand.equals("global")) { - - if (ChatModeManager.getInstance().isGlobal(((ProxiedPlayer)sender).getUniqueId())) { - MessageManager.sendMessage(sender, "command_channel_cannot_hide"); - return; - } - - Channel global = Channel.getGlobalChannel(); - if (global.isMember(((ProxiedPlayer)sender).getUniqueId())) { - global.addMember(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendSpecialMessage(sender, "command_channel_hide", operand.toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_channel_already_hide", operand.toUpperCase()); - } - - } else { - MessageManager.sendMessage(sender, "command_channel_does_not_exist"); - } - break; - - case "show": - if (!sender.hasPermission("multichat.chat.channel.show")) { - MessageManager.sendMessage(sender, "command_channel_show_no_permission"); - return; - } - if (operand.equals("local")) { - - Channel local = Channel.getLocalChannel(); - if (!local.isMember(((ProxiedPlayer)sender).getUniqueId())) { - local.removeMember(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendSpecialMessage(sender, "command_channel_show", operand.toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_channel_already_show", operand.toUpperCase()); - } - - } else if (operand.equals("global")) { - - Channel global = Channel.getGlobalChannel(); - if (!global.isMember(((ProxiedPlayer)sender).getUniqueId())) { - global.removeMember(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendSpecialMessage(sender, "command_channel_show", operand.toUpperCase()); - } else { - MessageManager.sendSpecialMessage(sender, "command_channel_already_show", operand.toUpperCase()); - } - - } else { - MessageManager.sendMessage(sender, "command_channel_does_not_exist"); - } - break; - - default: - showHelp(sender); - break; - } - - // Update local channel info - for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { - BungeeComm.sendPlayerChannelMessage(p.getName(), Channel.getChannel(p.getUniqueId()).getName(), Channel.getChannel(p.getUniqueId()), p.getServer().getInfo(), (p.hasPermission("multichat.chat.colour")||p.hasPermission("multichat.chat.color")||p.hasPermission("multichat.chat.colour.simple")||p.hasPermission("multichat.chat.color.simple")), (p.hasPermission("multichat.chat.colour")||p.hasPermission("multichat.chat.color")||p.hasPermission("multichat.chat.colour.rgb")||p.hasPermission("multichat.chat.color.rgb"))); - } - - } - - } else { - MessageManager.sendMessage(sender, "command_channel_only_players"); - } - - } - + public ChannelCommand() { + super("mcchannel", "multichat.chat.channel", ProxyConfigs.ALIASES.getAliases("mcchannel")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_only_players"); + return; + } + + if (args.length < 2) { + showCommandUsage(sender); + return; + } + + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + String operand = args[1].toLowerCase(); + + // TODO: This check is horrible... + // Future implementation of channelManager.exists? + // Or implement a Channel interface that both Proxy and Local extend + if (!channelManager.existsProxyChannel(operand) && !operand.equals("local")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_does_not_exist"); + return; + } + + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + UUID proxiedPlayerUID = proxiedPlayer.getUniqueId(); + Optional optionalProxyChannel = channelManager.getProxyChannel(operand); + + String subCommand = args[0].toLowerCase(); + + switch (subCommand) { + case "switch": { + if (!sender.hasPermission("multichat.chat.channel.switch")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_switch_no_permission"); + return; + } + + if (optionalProxyChannel.isPresent()) { + ProxyChannel proxyChannel = optionalProxyChannel.get(); + + if (!proxyChannel.getInfo().hasSpeakPermission(sender)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_switch_no_permission"); + return; + } + } + + ChatModeManager.getInstance().setGlobal(proxiedPlayerUID); + channelManager.select(proxiedPlayerUID, operand); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_switch", operand.toUpperCase()); + break; + } + case "hide": { + if (!sender.hasPermission("multichat.chat.channel.hide")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_hide_no_permission"); + return; + } + + if (channelManager.getChannel(proxiedPlayer).equalsIgnoreCase(operand)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_cannot_hide"); + return; + } + + if (channelManager.isHidden(proxiedPlayerUID, operand)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_already_hide", operand.toUpperCase()); + return; + } + + channelManager.hide(proxiedPlayerUID, operand); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_hide", operand.toUpperCase()); + break; + } + case "show": { + if (!sender.hasPermission("multichat.chat.channel.show")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_show_no_permission"); + return; + } + + if (!channelManager.isHidden(proxiedPlayerUID, operand)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_already_show", operand.toUpperCase()); + return; + } + + channelManager.show(proxiedPlayerUID, operand); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_show", operand.toUpperCase()); + break; + } + default: { + showCommandUsage(sender); + return; + } + } + + String channelFormat = optionalProxyChannel.isPresent() + ? optionalProxyChannel.get().getInfo().getFormat() + : channelManager.getLocalChannel().getFormat(); + + // Update channel info + for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { + ProxyLocalCommunicationManager.sendPlayerDataMessage(p.getName(), + channelManager.getChannel(p), + channelFormat, + p.getServer().getInfo(), + // TODO: Change this permission check mess please for the love of god (Move inside sendPlayerDataMessage) + (p.hasPermission("multichat.chat.colour") || p.hasPermission("multichat.chat.color") || p.hasPermission("multichat.chat.colour.simple") || p.hasPermission("multichat.chat.color.simple")), + (p.hasPermission("multichat.chat.colour") || p.hasPermission("multichat.chat.color") || p.hasPermission("multichat.chat.colour.rgb") || p.hasPermission("multichat.chat.color.rgb")) + ); + } + + } + + private void showCommandUsage(CommandSender sender) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_channel_help"); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ClearChatCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ClearChatCommand.java index b2e14dc3..5f17b2d1 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ClearChatCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ClearChatCommand.java @@ -2,121 +2,104 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.MessageManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.function.Predicate; +import java.util.stream.Stream; /** * Clear Chat Command *

Allows the user to clear their personal chat, the server chat, the global chat, or all servers' chat

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class ClearChatCommand extends Command { - private static String[] aliases = new String[] {"chatclear","wipechat","killchat"}; - - public ClearChatCommand() { - super("clearchat", "multichat.chat.clear", aliases); - } - - private void clearChatSelf(CommandSender sender) { - - for (int i = 1 ; i<151 ; i++ ) { - sender.sendMessage(new ComponentBuilder("").create()); - } - MessageManager.sendMessage(sender, "command_clearchat_self"); - - } - - private void clearChatServer(CommandSender sender) { - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (onlineplayer.getServer().getInfo().getName().equals(((ProxiedPlayer) sender).getServer().getInfo().getName() )) { - for (int i = 1 ; i<151 ; i++ ) { - onlineplayer.sendMessage(new ComponentBuilder("").create()); - } - MessageManager.sendMessage(onlineplayer, "command_clearchat_server"); - } - } - - } - - private void clearChatGlobal() { - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_global").contains(onlineplayer.getServer().getInfo().getName()) ) { - for (int i = 1 ; i<151 ; i++ ) { - onlineplayer.sendMessage(new ComponentBuilder("").create()); - } - MessageManager.sendMessage(onlineplayer, "command_clearchat_global"); - } - } - - } - - private void clearChatAll() { - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - for (int i = 1 ; i<151 ; i++ ) { - onlineplayer.sendMessage(new ComponentBuilder("").create()); - } - MessageManager.sendMessage(onlineplayer, "command_clearchat_all"); - } - - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - clearChatSelf(sender); - - } else { - if (args.length == 1) { - - if (args[0].toLowerCase().equals("self")) { - - clearChatSelf(sender); - - } else if (args[0].toLowerCase().equals("all") ) { - - if (sender.hasPermission("multichat.chat.clear.all")) { - - clearChatAll(); - - } else { - MessageManager.sendSpecialMessage(sender, "command_clearchat_no_permission", "ALL"); - } - - } else if (args[0].toLowerCase().equals("server") ) { - - if (sender.hasPermission("multichat.chat.clear.server")) { - - clearChatServer(sender); - - } else { - MessageManager.sendSpecialMessage(sender, "command_clearchat_no_permission", "SERVER"); - } - - } else if (args[0].toLowerCase().equals("global") ) { - - if (sender.hasPermission("multichat.chat.clear.global")) { - - clearChatGlobal(); - - } else { - MessageManager.sendSpecialMessage(sender, "command_clearchat_no_permission", "GLOBAL"); - } - - } - - } else { - MessageManager.sendMessage(sender, "command_clearchat_usage"); - } - } - } + private final TextComponent EMPTY_LINES; + + public ClearChatCommand() { + super("mcclearchat", "multichat.chat.clear", ProxyConfigs.ALIASES.getAliases("mcclearchat")); + + // Join space and linebreak character 200 times (= 100 empty lines) + char space = ' '; + char lf = '\n'; + char[] output = new char[200]; + // Reverse fori to fill char array properly + for (int i = 198; i >= 0; i -= 2) { + output[i] = space; + output[i + 1] = lf; + } + EMPTY_LINES = new TextComponent(new String(output)); + } + + public void execute(CommandSender sender, String[] args) { + String arg = args.length > 0 ? args[0].toLowerCase() : "self"; + switch (arg) { + case "self": { + clearChatSelf(sender); + break; + } + case "all": { + if (!sender.hasPermission("multichat.chat.clear.all")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_clearchat_no_permission", "ALL"); + return; + } + + clearChatForEveryone(null, null); + break; + } + case "server": { + if (!(sender instanceof ProxiedPlayer)) { + // TODO: Implement message + return; + } + + if (!sender.hasPermission("multichat.chat.clear.server")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_clearchat_no_permission", "SERVER"); + return; + } + + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + clearChatForEveryone("command_clearchat_server", + target -> proxiedPlayer.getServer().getInfo().equals(target.getServer().getInfo()) + ); + break; + } + case "global": { + if (!sender.hasPermission("multichat.chat.clear.global")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_clearchat_no_permission", "GLOBAL"); + return; + } + + clearChatForEveryone("command_clearchat_global", + target -> target.getServer() != null + && ProxyConfigs.CONFIG.isGlobalServer(target.getServer().getInfo().getName()) + ); + break; + } + default: { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_clearchat_usage"); + break; + } + } + } + + private void clearChatSelf(CommandSender sender) { + sender.sendMessage(EMPTY_LINES); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_clearchat_self"); + } + + private void clearChatForEveryone(String configPath, Predicate predicate) { + Stream playerStream = ProxyServer.getInstance().getPlayers().stream(); + if (predicate != null) playerStream = playerStream.filter(predicate); + playerStream.forEach(target -> { + target.sendMessage(EMPTY_LINES); + if (configPath != null && !configPath.isEmpty()) + ProxyConfigs.MESSAGES.sendMessage(target, configPath); + }); + playerStream.close(); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/DisplayCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/DisplayCommand.java index fd6f6dc7..ae5f67cc 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/DisplayCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/DisplayCommand.java @@ -1,72 +1,57 @@ package xyz.olivermartin.multichat.bungee.commands; -import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import net.md_5.bungee.config.Configuration; import xyz.olivermartin.multichat.bungee.ChatControl; -import xyz.olivermartin.multichat.bungee.ConfigManager; import xyz.olivermartin.multichat.bungee.ConsoleManager; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.bungee.events.PostBroadcastEvent; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.Optional; /** * Display Command *

Displays a message to every player connected to the BungeeCord network

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class DisplayCommand extends Command { - - private static String[] aliases = new String[] {}; - - public DisplayCommand() { - super("display", "multichat.staff.display", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - MessageManager.sendMessage(sender, "command_display_desc"); - MessageManager.sendMessage(sender, "command_display_usage"); - - } else { - - String message = MultiChatUtil.getMessageFromArgs(args); - - displayMessage(message); - } - } - - public static void displayMessage(String message) { - - message = ChatControl.applyChatRules(message, "display_command", "").get(); - message = MultiChatUtil.reformatRGB(message); - Configuration config = ConfigManager.getInstance().getHandler("config.yml").getConfig(); - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (onlineplayer.getServer() != null) { - if (!config.getStringList("no_global").contains( - onlineplayer.getServer().getInfo().getName())) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', message)))); - } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', message))); - } - } - } - } - - // Trigger PostBroadcastEvent - ProxyServer.getInstance().getPluginManager().callEvent(new PostBroadcastEvent("display", message)); - - ConsoleManager.logDisplayMessage(message); - } + + public DisplayCommand() { + super("mcdisplay", "multichat.staff.display", ProxyConfigs.ALIASES.getAliases("mcdisplay")); + } + + public void execute(CommandSender sender, String[] args) { + if (args.length < 1) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_display_desc"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_display_usage"); + return; + } + + String message = String.join(" ", args); + Optional optionalMessage = ChatControl.applyChatRules(sender, message, MessageType.DISPLAY_COMMAND); + if (!optionalMessage.isPresent()) + return; + + String finalMessage = MultiChatUtil.translateColorCodes(optionalMessage.get()); + ProxyServer.getInstance().getPlayers().stream() + .filter(target -> target.getServer() != null + && ProxyConfigs.CONFIG.isGlobalServer(target.getServer().getInfo().getName()) + ) + .forEach(target -> + target.sendMessage(ProxyConfigs.CONFIG.isLegacyServer(target.getServer().getInfo().getName()) + ? ProxyJsonUtils.parseMessage(MultiChatUtil.approximateRGBColorCodes(finalMessage)) + : ProxyJsonUtils.parseMessage(finalMessage) + ) + ); + + // Trigger PostBroadcastEvent + ProxyServer.getInstance().getPluginManager().callEvent(new PostBroadcastEvent("display", message)); + + ConsoleManager.logDisplayMessage(message); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/FreezeChatCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/FreezeChatCommand.java index 357d1c8e..6709afb2 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/FreezeChatCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/FreezeChatCommand.java @@ -2,43 +2,32 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * Freeze Chat Command *

Allows staff members to block all chat messages being sent

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class FreezeChatCommand extends Command { - private static String[] aliases = new String[] {}; - - public FreezeChatCommand() { - super("freezechat", "multichat.chat.freeze", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - if (MultiChat.frozen == true) { - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - MessageManager.sendSpecialMessage(onlineplayer, "command_freezechat_thawed", sender.getName()); - } - - MultiChat.frozen = false; - - } else { - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - MessageManager.sendSpecialMessage(onlineplayer, "command_freezechat_frozen", sender.getName()); - } - - MultiChat.frozen = true; - } - } + public FreezeChatCommand() { + super("mcfreezechat", "multichat.chat.freeze", ProxyConfigs.ALIASES.getAliases("mcfreezechat")); + } + + public void execute(CommandSender sender, String[] args) { + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + boolean frozen = !proxyDataStore.isChatFrozen(); + proxyDataStore.setChatFrozen(frozen); + ProxyServer.getInstance().getPlayers().forEach(proxiedPlayer -> + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, + "command_freezechat_" + (frozen ? "frozen" : "thawed"), + proxiedPlayer.getName() + ) + ); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GCCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GCCommand.java index a221d090..87a87c1e 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GCCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GCCommand.java @@ -1,153 +1,140 @@ package xyz.olivermartin.multichat.bungee.commands; -import java.util.Optional; - import com.olivermartin410.plugins.TGroupChatInfo; - -import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.ChatControl; -import xyz.olivermartin.multichat.bungee.ChatManipulation; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.ConsoleManager; -import xyz.olivermartin.multichat.bungee.Events; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.bungee.*; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.Optional; /** * Group Chat Messaging Command *

Allows players to send a message direct to a group chat or toggle group chats

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class GCCommand extends Command { - private static String[] aliases = new String[] {}; - - public GCCommand() { - super("gc", "multichat.group", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - if ((sender instanceof ProxiedPlayer)) { - - ProxiedPlayer player = (ProxiedPlayer)sender; - boolean toggleresult = Events.toggleGC(player.getUniqueId()); - - if (toggleresult == true) { - MessageManager.sendMessage(sender, "command_gc_toggle_on"); - } else { - MessageManager.sendMessage(sender, "command_gc_toggle_off"); - } - - } else { - - MessageManager.sendMessage(sender, "command_gc_only_players_toggle"); - } - - } else if ((sender instanceof ProxiedPlayer)) { - - ProxiedPlayer player = (ProxiedPlayer)sender; - - if (MultiChat.viewedchats.get(player.getUniqueId()) != null) { - - String groupName = (String)MultiChat.viewedchats.get(player.getUniqueId()); - - if (MultiChat.groupchats.containsKey(groupName)) { - - TGroupChatInfo groupInfo = (TGroupChatInfo) MultiChat.groupchats.get(groupName); - - String message = MultiChatUtil.getMessageFromArgs(args); - - String playerName = sender.getName(); - - if ((groupInfo.getFormal() == true) - && (groupInfo.getAdmins().contains(player.getUniqueId()))) { - playerName = "&o" + playerName; - } - - sendMessage(message, playerName, groupInfo); - - } else { - - MessageManager.sendMessage(sender, "command_gc_no_longer_exists"); - } - - } else { - MessageManager.sendMessage(sender, "command_gc_no_chat_selected"); - } - - } else { - MessageManager.sendMessage(sender, "command_gc_only_players_speak"); - } - } - - public static void sendMessage(String message, String playerName, TGroupChatInfo groupInfo) { - - ChatManipulation chatfix = new ChatManipulation(); - - message = MultiChatUtil.reformatRGB(message); - - ProxiedPlayer potentialPlayer = ProxyServer.getInstance().getPlayer(playerName); - if (potentialPlayer != null) { - if (ChatControl.isMuted(potentialPlayer.getUniqueId(), "group_chats")) { - MessageManager.sendMessage(potentialPlayer, "mute_cannot_send_message"); - return; - } - - if (ChatControl.handleSpam(potentialPlayer, message, "group_chats")) { - return; - } - } - - Optional crm; - - crm = ChatControl.applyChatRules(message, "group_chats", playerName); - - if (crm.isPresent()) { - message = crm.get(); - } else { - return; - } - - String messageFormat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("groupchat.format"); - message = chatfix.replaceGroupChatVars(messageFormat, playerName, message, groupInfo.getName()); - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - - if (((groupInfo.existsViewer(onlineplayer.getUniqueId())) && (onlineplayer.hasPermission("multichat.group"))) || ((MultiChat.allspy.contains(onlineplayer.getUniqueId())) && (onlineplayer.hasPermission("multichat.staff.spy")))) { - - if (potentialPlayer != null) { - if (!ChatControl.ignores(potentialPlayer.getUniqueId(), onlineplayer.getUniqueId(), "group_chats")) { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', message)))); - } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', message))); - } - } else { - ChatControl.sendIgnoreNotifications(onlineplayer, potentialPlayer, "group_chats"); - } - } else { - if (MultiChat.legacyServers.contains(onlineplayer.getServer().getInfo().getName())) { - onlineplayer.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateHexCodes(ChatColor.translateAlternateColorCodes('&', message)))); - } else { - onlineplayer.sendMessage(TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', message))); - } - } - - } - - } - - ConsoleManager.logGroupChat(message); - } + public GCCommand() { + super("mcgc", "multichat.group", ProxyConfigs.ALIASES.getAliases("mcgc")); + } + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, args.length == 0 + ? "command_gc_only_players_toggle" + : "command_gc_only_players_speak" + ); + return; + } + + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + if (args.length == 0) { + boolean toggleResult = Events.toggleGC(proxiedPlayer.getUniqueId()); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_gc_toggle_" + (toggleResult ? "on" : "off")); + return; + } + + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + String viewedChat = proxyDataStore.getViewedChats().get(proxiedPlayer.getUniqueId()); + if (viewedChat == null) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_gc_no_chat_selected"); + return; + } + + TGroupChatInfo groupChatInfo = proxyDataStore.getGroupChats().get(viewedChat); + if (groupChatInfo == null) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_gc_no_longer_exists"); + return; + } + + String playerName = sender.getName(); + + if (groupChatInfo.getFormal() && groupChatInfo.getAdmins().contains(proxiedPlayer.getUniqueId())) { + playerName = "&o" + playerName; + } + + sendMessage(String.join(" ", args), playerName, groupChatInfo); + } + + public static void sendMessage(String originalMessage, String playerName, TGroupChatInfo groupInfo) { + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + ChatManipulation manipulation = new ChatManipulation(); + + ProxiedPlayer proxiedPlayer = ProxyServer.getInstance().getPlayer(playerName); + if (proxiedPlayer != null) { + if (ChatControl.isMuted(proxiedPlayer.getUniqueId(), MessageType.GROUP_CHATS)) { + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "mute_cannot_send_message"); + return; + } + + if (ChatControl.handleSpam(proxiedPlayer, originalMessage, MessageType.GROUP_CHATS)) + return; + } + + Optional optionalChatRules; + + optionalChatRules = ChatControl.applyChatRules(proxiedPlayer, originalMessage, MessageType.GROUP_CHATS); + + if (!optionalChatRules.isPresent()) + return; + originalMessage = optionalChatRules.get(); + + String messageFormat = ProxyConfigs.CONFIG.getGroupChatFormat(); + String translatedMessage = MultiChatUtil.translateColorCodes( + manipulation.replaceGroupChatVars(messageFormat, playerName, originalMessage, groupInfo.getName()) + ); + String translatedOriginalMessage = MultiChatUtil.translateColorCodes(originalMessage); + + BaseComponent[] modernMessage = ProxyJsonUtils.parseMessage(translatedMessage, + "%MESSAGE%", + translatedOriginalMessage + ); + + BaseComponent[] legacyMessage = ProxyJsonUtils.parseMessage( + MultiChatUtil.approximateRGBColorCodes(translatedMessage), + "%MESSAGE%", + MultiChatUtil.approximateRGBColorCodes(translatedOriginalMessage) + ); + + ProxyServer.getInstance().getPlayers().stream() + .filter(target -> target.getServer() != null + && (groupInfo.isViewer(target.getUniqueId()) && target.hasPermission("multichat.group")) + || proxyDataStore.getAllSpy().contains(target.getUniqueId()) + ) + .forEach(target -> { + if (proxyDataStore.getAllSpy().contains(target.getUniqueId()) + && !target.hasPermission("multichat.staff.spy")) { + proxyDataStore.getAllSpy().remove(target.getUniqueId()); + return; + } + + if (proxiedPlayer != null + && ChatControl.ignores(proxiedPlayer.getUniqueId(), target.getUniqueId(), MessageType.GROUP_CHATS)) { + ChatControl.sendIgnoreNotifications(target, proxiedPlayer, "group_chats"); + return; + } + + // TODO: Move legacy check inside parsing at some point + if (ProxyConfigs.CONFIG.isLegacyServer(target.getServer().getInfo().getName())) { + target.sendMessage(legacyMessage); + return; + } + target.sendMessage(modernMessage); + }); + + StringBuilder consoleMessage = new StringBuilder(); + for (BaseComponent bc : legacyMessage) + consoleMessage.append(bc.toLegacyText()); + ConsoleManager.logGroupChat(consoleMessage.toString()); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GlobalCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GlobalCommand.java index 274b3156..1e8942a0 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GlobalCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GlobalCommand.java @@ -3,115 +3,96 @@ import java.util.Optional; import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.BungeeComm; -import xyz.olivermartin.multichat.bungee.Channel; -import xyz.olivermartin.multichat.bungee.ChatControl; import xyz.olivermartin.multichat.bungee.ChatModeManager; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.DebugManager; -import xyz.olivermartin.multichat.bungee.Events; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyChatManager; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; /** * Global Command *

Causes players to see messages sent from all servers in the global chat

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class GlobalCommand extends Command { - public GlobalCommand() { - super("global", "multichat.chat.mode", (String[]) ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("globalcommand").toArray(new String[0])); - } - - public void execute(CommandSender sender, String[] args) { - - if ((sender instanceof ProxiedPlayer)) { - - if (args.length < 1) { - - ChatModeManager.getInstance().setGlobal(((ProxiedPlayer)sender).getUniqueId()); - - MessageManager.sendMessage(sender, "command_global_enabled_1"); - MessageManager.sendMessage(sender, "command_global_enabled_2"); - - } else { - - ProxiedPlayer player = (ProxiedPlayer)sender; - String message = MultiChatUtil.getMessageFromArgs(args); - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("global") == true) { - - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_global").contains(player.getServer().getInfo().getName())) { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - - if ((!MultiChat.frozen) || (player.hasPermission("multichat.chat.always"))) { - - if (ChatControl.isMuted(player.getUniqueId(), "global_chat")) { - MessageManager.sendMessage(player, "mute_cannot_send_message"); - return; - } - - DebugManager.log(player.getName() + "- about to check for spam"); - - if (ChatControl.handleSpam(player, message, "global_chat")) { - DebugManager.log(player.getName() + " - chat message being cancelled due to spam"); - return; - } - - Optional crm; - - crm = ChatControl.applyChatRules(message, "global_chat", player.getName()); - - if (crm.isPresent()) { - message = crm.get(); - } else { - return; - } - - if (!player.hasPermission("multichat.chat.link")) { - message = ChatControl.replaceLinks(message); - } - - // If they had this channel hidden, then unhide it... - Channel global = Channel.getGlobalChannel(); - if (!global.isMember(player.getUniqueId())) { - global.removeMember(player.getUniqueId()); - MessageManager.sendSpecialMessage(player, "command_channel_show", "GLOBAL"); - } - - // Let server know players channel preference - BungeeComm.sendPlayerChannelMessage(player.getName(), Channel.getChannel(player.getUniqueId()).getName(), Channel.getChannel(player.getUniqueId()), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); - - // Message passes through to spigot here - - // Send message directly to global chat... - - BungeeComm.sendPlayerCommandMessage("!SINGLE G MESSAGE!" + message, sender.getName(), ((ProxiedPlayer)sender).getServer().getInfo()); - - if (Events.hiddenStaff.contains(player.getUniqueId())) { - Events.hiddenStaff.remove(player.getUniqueId()); - } - - } else { - MessageManager.sendMessage(player, "freezechat_frozen"); - } - - } - } - - } - - } else { - MessageManager.sendMessage(sender, "command_global_only_players"); - } - } + public GlobalCommand() { + super("mcglobal", "multichat.chat.mode", ProxyConfigs.ALIASES.getAliases("mcglobal")); + } + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_global_only_players"); + return; + } + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + + if (args.length == 0) { + ChatModeManager.getInstance().setGlobal(proxiedPlayer.getUniqueId()); + + ProxyConfigs.MESSAGES.sendMessage(sender, "command_global_enabled_1"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_global_enabled_2"); + return; + } + + if (!ProxyConfigs.CONFIG.isGlobal()) { + // TODO: Maybe add a message here? + // Don't think anyone will disable global chat and expect /global to work but you never know... + return; + } + + ServerInfo serverInfo = proxiedPlayer.getServer().getInfo(); + if (!ProxyConfigs.CONFIG.isGlobalServer(serverInfo.getName())) { + // TODO: Same as above + return; + } + + if (ProxyConfigs.CONFIG.isFetchSpigotDisplayNames()) + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(proxiedPlayer.getName(), serverInfo); + + ProxyChatManager chatManager = MultiChatProxy.getInstance().getChatManager(); + Optional optionalMessage = chatManager.handleChatMessage(proxiedPlayer, String.join(" ", args)); + if (!optionalMessage.isPresent()) + return; + + String message = optionalMessage.get(); + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + + // If they had this channel hidden, then unhide it... + if (channelManager.isHidden(proxiedPlayer.getUniqueId(), "global")) { + channelManager.show(proxiedPlayer.getUniqueId(), "global"); + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "command_channel_show", "GLOBAL"); + } + + // Let server know players channel preference + String currentChannel = channelManager.getChannel(proxiedPlayer); + String channelFormat = currentChannel.equals("local") + ? channelManager.getLocalChannel().getFormat() + : channelManager.getProxyChannel(currentChannel) + .orElse(channelManager.getGlobalChannel()).getInfo().getFormat(); + + ProxyLocalCommunicationManager.sendPlayerDataMessage(proxiedPlayer.getName(), + currentChannel, + channelFormat, + serverInfo, + // TODO: Move this permissions check somewhere else or make it simpler + (proxiedPlayer.hasPermission("multichat.chat.color") || proxiedPlayer.hasPermission("multichat.chat.colour.simple") || proxiedPlayer.hasPermission("multichat.chat.color.simple")), + (proxiedPlayer.hasPermission("multichat.chat.color") || proxiedPlayer.hasPermission("multichat.chat.colour.rgb") || proxiedPlayer.hasPermission("multichat.chat.color.rgb")) + ); + + // Send message directly to global chat... + ProxyLocalCommunicationManager.sendPlayerDirectChatMessage("global", + proxiedPlayer.getName(), + message, + serverInfo + ); + + // TODO: Move this to actual message distribution + MultiChatProxy.getInstance().getDataStore().getHiddenStaff().remove(proxiedPlayer.getUniqueId()); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupCommand.java index 839ed41a..4419e671 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupCommand.java @@ -1,10 +1,6 @@ package xyz.olivermartin.multichat.bungee.commands; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.UUID; +import java.util.*; import com.olivermartin410.plugins.TGroupChatInfo; @@ -14,702 +10,411 @@ import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.TabExecutor; import xyz.olivermartin.multichat.bungee.GroupManager; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; import xyz.olivermartin.multichat.bungee.UUIDNameManager; +import xyz.olivermartin.multichat.common.RegexUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * The Group Command *

From here the player can manipulate group chats in every possible way

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class GroupCommand extends Command implements TabExecutor { - private static String[] aliases = new String[] {}; - - public GroupCommand() { - super("group", "multichat.group", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - if ((args.length < 1) || ((args.length == 1) && (args[0].toLowerCase().equals("help")))) { - - GroupManager groupman = new GroupManager(); - groupman.displayHelp(1, sender); - groupman = null; - - } else if ((sender instanceof ProxiedPlayer)) { - - switch (args.length) { - - case 1: - - if ((sender instanceof ProxiedPlayer)) { - - if (MultiChat.groupchats.containsKey(args[0].toLowerCase())) { - - TGroupChatInfo groupInfo = (TGroupChatInfo) MultiChat.groupchats.get(args[0].toLowerCase()); - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (groupInfo.existsMember(player.getUniqueId())) { - - String viewedchat = (String)MultiChat.viewedchats.get(player.getUniqueId()); - viewedchat = args[0].toLowerCase(); - MultiChat.viewedchats.remove(player.getUniqueId()); - MultiChat.viewedchats.put(player.getUniqueId(), viewedchat); - - MessageManager.sendSpecialMessage(sender, "command_group_selected", args[0].toUpperCase()); - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_not_a_member", args[0].toUpperCase()); - } - - groupInfo = null; - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[0].toUpperCase()); - } - - } else { - MessageManager.sendMessage(sender, "command_group_only_players_select"); - } - - break; - - case 2: - - if ((!args[0].toLowerCase().equals("members")) && (!args[0].toLowerCase().equals("list")) - && (!args[0].toLowerCase().equals("spyall")) && (!args[0].toLowerCase().equals("spy")) - && (!args[0].toLowerCase().equals("help")) && (!args[0].toLowerCase().equals("create")) - && (!args[0].toLowerCase().equals("make")) && (!args[0].toLowerCase().equals("join")) - && (!args[0].toLowerCase().equals("quit")) && (!args[0].toLowerCase().equals("leave")) - && (!args[0].toLowerCase().equals("formal")) && (!args[0].toLowerCase().equals("delete"))) { - - MessageManager.sendMessage(sender, "command_group_incorrect_usage"); - } - - if ((args[0].toLowerCase().equals("list")) || (args[0].toLowerCase().equals("members"))) { - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - TGroupChatInfo groupChatInfo = new TGroupChatInfo(); - ProxiedPlayer player = (ProxiedPlayer) sender; - - groupChatInfo = (TGroupChatInfo)MultiChat.groupchats.get(args[1].toLowerCase()); - - if ((groupChatInfo.existsMember(player.getUniqueId())) || (sender.hasPermission("multichat.staff.spy"))) { - - List memberlist = groupChatInfo.getMembers(); - - MessageManager.sendSpecialMessage(sender, "command_group_member_list", groupChatInfo.getName().toUpperCase()); - - for (UUID member : memberlist) { - - if (!groupChatInfo.existsAdmin(member)) { - MessageManager.sendSpecialMessage(sender, "command_group_member_list_item", UUIDNameManager.getName(member)); - } else { - MessageManager.sendSpecialMessage(sender, "command_group_member_list_item_admin", UUIDNameManager.getName(member)); - } - } - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_not_a_member", args[1].toUpperCase()); - } - - groupChatInfo = null; - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - - } - - if (args[0].toLowerCase().equals("spy")) { - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (args[1].toLowerCase().equals("all")) { - - if (player.hasPermission("multichat.staff.spy")) { - - if (MultiChat.allspy.contains(player.getUniqueId())) { - - MultiChat.allspy.remove(player.getUniqueId()); - MessageManager.sendMessage(sender, "command_group_spy_all_disabled_1"); - MessageManager.sendMessage(sender, "command_group_spy_all_disabled_2"); - MessageManager.sendMessage(sender, "command_group_spy_all_disabled_3"); - - } else { - - MultiChat.allspy.add(player.getUniqueId()); - MessageManager.sendMessage(sender, "command_group_spy_all_enabled"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_spy_no_permission"); - } - - } else if (player.hasPermission("multichat.staff.spy")) { - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - TGroupChatInfo groupChatInfo = (TGroupChatInfo)MultiChat.groupchats.get(args[1].toLowerCase()); - - if (!groupChatInfo.existsMember(player.getUniqueId())) { - - if (groupChatInfo.existsViewer(player.getUniqueId())) { - - groupChatInfo.delViewer(player.getUniqueId()); - MultiChat.groupchats.remove(groupChatInfo.getName().toLowerCase()); - MultiChat.groupchats.put(groupChatInfo.getName().toLowerCase(), groupChatInfo); - MessageManager.sendSpecialMessage(sender, "command_group_spy_off", groupChatInfo.getName().toUpperCase()); - - } else { - - groupChatInfo.addViewer(player.getUniqueId()); - MultiChat.groupchats.remove(groupChatInfo.getName().toLowerCase()); - MultiChat.groupchats.put(groupChatInfo.getName().toLowerCase(), groupChatInfo); - MessageManager.sendSpecialMessage(sender, "command_group_spy_on", groupChatInfo.getName().toUpperCase()); - - } - - } else { - MessageManager.sendMessage(sender, "command_group_spy_already_a_member"); - } - - groupChatInfo = null; - - } else { - MessageManager.sendMessage(sender, "command_group_spy_does_not_exist"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_spy_no_permission"); - } - - } - - if (args[0].toLowerCase().equals("help")) { - - if (args[1].equals("1")) { - GroupManager groupman = new GroupManager(); - groupman.displayHelp(1,sender); - groupman = null; - } else { - GroupManager groupman = new GroupManager(); - groupman.displayHelp(2,sender); - groupman = null; - } - - } - - if ((args[0].toLowerCase().equals("create")) || (args[0].toLowerCase().equals("make"))) { - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (player.hasPermission("multichat.group.create")) { - - if (args[1].length() <= 20) { - - if (!MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - GroupManager groupman = new GroupManager(); - - // Make the new group - groupman.createGroup(args[1], player.getUniqueId(), false, ""); - // Select the new group for the player - groupman.setViewedChat(player.getUniqueId(), args[1]); - // Announce join to group members - MessageManager.sendSpecialMessage(sender, "command_group_created", args[1].toUpperCase()); - - groupman.announceJoinGroup(sender.getName(), args[1]); - groupman = null; - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_already_exists", args[1].toUpperCase()); - } - - } else { - MessageManager.sendMessage(sender, "command_group_max_length"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_create_no_permission"); - } - } - - if (args[0].toLowerCase().equals("join")) { - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - GroupManager groupman = new GroupManager(); - ProxiedPlayer player = (ProxiedPlayer)sender; - - //Run the join group routine - if (groupman.joinGroup(args[1], player, "") == true ){ - - //If the join is successful, set their viewed chat - groupman.setViewedChat(player.getUniqueId(), args[1]); - MessageManager.sendSpecialMessage(sender, "command_group_joined", args[1].toUpperCase()); - //Announce their join - groupman.announceJoinGroup(player.getName(), args[1]); - } - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - } - - if ((args[0].toLowerCase().equals("quit")) || (args[0].toLowerCase().equals("leave"))) { - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - GroupManager groupman = new GroupManager(); - - ProxiedPlayer player = (ProxiedPlayer)sender; - - groupman.quitGroup(args[1].toLowerCase(), player.getUniqueId(), player); - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - } - - if (args[0].toLowerCase().equals("formal")) { - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - TGroupChatInfo groupChatInfo = (TGroupChatInfo)MultiChat.groupchats.get(args[1].toLowerCase()); - - if (!groupChatInfo.getFormal()) { - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (groupChatInfo.getAdmins().contains(player.getUniqueId())) { - - groupChatInfo.setFormal(true); - MultiChat.groupchats.remove(groupChatInfo.getName()); - MultiChat.groupchats.put(groupChatInfo.getName(), groupChatInfo); - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_formal"), "&lINFO", groupChatInfo); - - } else { - MessageManager.sendMessage(sender, "command_group_formal_not_owner"); - } - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_formal_already_formal", args[1].toUpperCase()); - } - - groupChatInfo = null; - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - } - - if (args[0].toLowerCase().equals("delete")) { - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - TGroupChatInfo groupChatInfo = (TGroupChatInfo) MultiChat.groupchats.get(args[1].toLowerCase()); - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (groupChatInfo.getAdmins().contains(player.getUniqueId())) { - - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - - if ((MultiChat.viewedchats.get(onlineplayer.getUniqueId()) != null) && - (((String)MultiChat.viewedchats.get(onlineplayer.getUniqueId())).toLowerCase().equals(groupChatInfo.getName().toLowerCase()))) { - - MultiChat.viewedchats.remove(onlineplayer.getUniqueId()); - MultiChat.viewedchats.put(onlineplayer.getUniqueId(), null); - - } - } - - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_deleted"), "&lINFO", groupChatInfo); - GCCommand.sendMessage(MessageManager.getMessage("groups_info_goodbye"), "&lINFO", groupChatInfo); - - MultiChat.groupchats.remove(groupChatInfo.getName().toLowerCase()); - - groupChatInfo = null; - - } else { - MessageManager.sendMessage(sender, "command_group_formal_not_admin"); - } - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - } - - break; - - case 3: - - if ((!args[0].toLowerCase().equals("create")) && (!args[0].toLowerCase().equals("make")) - && (!args[0].toLowerCase().equals("join")) && (!args[0].toLowerCase().equals("transfer")) - && (!args[0].toLowerCase().equals("admin")) && (!args[0].toLowerCase().equals("addadmin")) - && (!args[0].toLowerCase().equals("removeadmin")) && (!args[0].toLowerCase().equals("ban"))) { - - MessageManager.sendMessage(sender, "command_group_incorrect_usage"); - - } - - if ((args[0].toLowerCase().equals("create")) || (args[0].toLowerCase().equals("make"))) { - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (player.hasPermission("multichat.group.create")) { - - if ((args[1].length() <= 20) && (args[2].length() <= 20)) { - - if (!MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - GroupManager groupman = new GroupManager(); - - //Make the new group - groupman.createGroup(args[1], player.getUniqueId(), true, args[2]); - //Select the new group for the player - groupman.setViewedChat(player.getUniqueId(), args[1]); - //Announce join to group members - groupman.announceJoinGroup(sender.getName(), args[1]); - - MessageManager.sendSpecialMessage(sender, "command_group_created", args[1].toUpperCase()); - groupman = null; - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_already_exists", args[1].toUpperCase()); - } - - } else { - MessageManager.sendMessage(sender, "command_group_max_length_password"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_create_no_permission"); - } - } - - if (args[0].toLowerCase().equals("join")) { - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - GroupManager groupman = new GroupManager(); - ProxiedPlayer player = (ProxiedPlayer)sender; - - //Run the join group routine - if (groupman.joinGroup(args[1], player, args[2]) == true ){ - - //If the join is successful, set their viewed chat - groupman.setViewedChat(player.getUniqueId(), args[1]); - MessageManager.sendSpecialMessage(sender, "command_group_joined", args[1].toUpperCase()); - //Announce their join - groupman.announceJoinGroup(player.getName(), args[1]); - } - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - } - - if (args[0].toLowerCase().equals("transfer")) { - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - if (ProxyServer.getInstance().getPlayer(args[2].toLowerCase()) != null) { - - ProxiedPlayer newplayer = ProxyServer.getInstance().getPlayer(args[2].toLowerCase()); - TGroupChatInfo groupChatInfo = (TGroupChatInfo)MultiChat.groupchats.get(args[1].toLowerCase()); - - if (!groupChatInfo.getFormal()) { - - if (groupChatInfo.existsAdmin(player.getUniqueId())) { - - if (groupChatInfo.existsMember(newplayer.getUniqueId())) { - - groupChatInfo.addAdmin(newplayer.getUniqueId()); - groupChatInfo.delAdmin(player.getUniqueId()); - - MultiChat.groupchats.remove(groupChatInfo.getName()); - MultiChat.groupchats.put(groupChatInfo.getName(), groupChatInfo); - - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_transfer") + newplayer.getName(), "&lINFO", groupChatInfo); - - } else { - MessageManager.sendMessage(sender, "command_group_transfer_not_member"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_transfer_not_owner"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_transfer_not_informal"); - } - - groupChatInfo = null; - - } else { - MessageManager.sendMessage(sender, "command_group_player_not_online"); - } - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - } - - if ((args[0].toLowerCase().equals("admin")) || (args[0].toLowerCase().equals("addadmin")) || (args[0].toLowerCase().equals("removeadmin"))) { - - ProxiedPlayer player = (ProxiedPlayer)sender; - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - if (ProxyServer.getInstance().getPlayer(args[2].toLowerCase()) != null) { - - ProxiedPlayer newplayer = ProxyServer.getInstance().getPlayer(args[2].toLowerCase()); - - TGroupChatInfo groupChatInfo = (TGroupChatInfo)MultiChat.groupchats.get(args[1].toLowerCase()); - - if (groupChatInfo.getFormal() == true) { - - if (groupChatInfo.existsAdmin(player.getUniqueId())) { - - if (groupChatInfo.existsMember(newplayer.getUniqueId())) { - - if (!groupChatInfo.existsAdmin(newplayer.getUniqueId())) { - - groupChatInfo.addAdmin(newplayer.getUniqueId()); - - MultiChat.groupchats.remove(groupChatInfo.getName()); - MultiChat.groupchats.put(groupChatInfo.getName(), groupChatInfo); - - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_promoted") + newplayer.getName(), "&lINFO", groupChatInfo); - - } else if (newplayer.getUniqueId().equals(player.getUniqueId())) { - - if (groupChatInfo.getAdmins().size() > 1) { - - groupChatInfo.delAdmin(player.getUniqueId()); - - MultiChat.groupchats.remove(groupChatInfo.getName()); - MultiChat.groupchats.put(groupChatInfo.getName(), groupChatInfo); - - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_step_down"), "&lINFO", groupChatInfo); - - } else { - MessageManager.sendMessage(sender, "command_group_formal_only_admin"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_formal_cannot_demote"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_transfer_not_member"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_formal_not_admin"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_not_formal"); - } - - groupChatInfo = null; - - } else { - MessageManager.sendMessage(sender, "command_group_player_not_online"); - } - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - - } - - if (args[0].toLowerCase().equals("ban")) { - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - if (ProxyServer.getInstance().getPlayer(args[2].toLowerCase()) != null) { - - ProxiedPlayer newPlayer = ProxyServer.getInstance().getPlayer(args[2].toLowerCase()); - TGroupChatInfo groupChatInfo = (TGroupChatInfo)MultiChat.groupchats.get(args[1].toLowerCase()); - - if (groupChatInfo.getFormal() == true) { - - if (groupChatInfo.existsAdmin(player.getUniqueId())) { - - if (!groupChatInfo.existsAdmin(newPlayer.getUniqueId())) { - - if (!groupChatInfo.existsBanned(newPlayer.getUniqueId())) { - - groupChatInfo.addBanned(newPlayer.getUniqueId()); - - if (groupChatInfo.existsMember(newPlayer.getUniqueId())) { - - groupChatInfo.delMember(newPlayer.getUniqueId()); - groupChatInfo.delViewer(newPlayer.getUniqueId()); - - MultiChat.viewedchats.remove(newPlayer.getUniqueId()); - MultiChat.viewedchats.put(newPlayer.getUniqueId(), null); - - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_kick") + newPlayer.getName(), "&lINFO", groupChatInfo); - } - - MultiChat.groupchats.remove(groupChatInfo.getName()); - MultiChat.groupchats.put(groupChatInfo.getName(), groupChatInfo); - - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_ban") + newPlayer.getName(), "&lINFO", groupChatInfo); - - MessageManager.sendSpecialMessage(newPlayer, "command_group_banned", groupChatInfo.getName()); - - - } else { - - groupChatInfo.delBanned(newPlayer.getUniqueId()); - - MultiChat.groupchats.remove(groupChatInfo.getName()); - MultiChat.groupchats.put(groupChatInfo.getName(), groupChatInfo); - - GCCommand.sendMessage(sender.getName() + MessageManager.getMessage("groups_info_unban") + newPlayer.getName(), "&lINFO", groupChatInfo); - - MessageManager.sendSpecialMessage(newPlayer, "command_group_unbanned", groupChatInfo.getName()); - } - - } else { - MessageManager.sendMessage(sender, "command_group_cannot_ban_admin"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_ban_not_admin"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_not_formal"); - } - - groupChatInfo = null; - - } else { - MessageManager.sendMessage(sender, "command_group_player_not_online"); - } - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - } - - break; - - case 4: - - if ((args[0].toLowerCase().equals("color")) || (args[0].toLowerCase().equals("colour"))) { - - if (MultiChat.groupchats.containsKey(args[1].toLowerCase())) { - - TGroupChatInfo groupChatInfo = new TGroupChatInfo(); - ProxiedPlayer player = (ProxiedPlayer) sender; - - groupChatInfo = (TGroupChatInfo)MultiChat.groupchats.get(args[1].toLowerCase()); - - if (((groupChatInfo.existsMember(player.getUniqueId())) - && (!groupChatInfo.getFormal())) || (groupChatInfo.existsAdmin(player.getUniqueId()))) { - - args[2] = args[2].toLowerCase(); - args[3] = args[3].toLowerCase(); - - if ((args[2].equals("a")) || (args[2].equals("b")) || (args[2].equals("c")) || (args[2].equals("d")) - || (args[2].equals("e")) || (args[2].equals("f")) || (args[2].equals("0")) || (args[2].equals("1")) - || (args[2].equals("2")) || (args[2].equals("3")) || (args[2].equals("4")) || (args[2].equals("5")) - || (args[2].equals("6")) || (args[2].equals("7")) || (args[2].equals("8")) || (args[2].equals("9"))) { - - if ((args[3].equals("a")) || (args[3].equals("b")) || (args[3].equals("c")) || (args[3].equals("d")) - || (args[3].equals("e")) || (args[3].equals("f")) || (args[3].equals("0")) || (args[3].equals("1")) - || (args[3].equals("2")) || (args[3].equals("3")) || (args[3].equals("4")) || (args[3].equals("5")) - || (args[3].equals("6")) || (args[3].equals("7")) || (args[3].equals("8")) || (args[3].equals("9"))) { - - MultiChat.groupchats.remove(groupChatInfo.getName()); - - groupChatInfo.setChatColor(args[2].charAt(0)); - groupChatInfo.setNameColor(args[3].charAt(0)); - - MultiChat.groupchats.put(groupChatInfo.getName(), groupChatInfo); - - GCCommand.sendMessage(MessageManager.getMessage("groups_info_colors") + sender.getName(), "&lINFO", groupChatInfo); - - } else { - MessageManager.sendMessage(sender, "command_group_color_invalid"); - MessageManager.sendMessage(sender, "command_group_color_usage"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_color_invalid"); - MessageManager.sendMessage(sender, "command_group_color_usage"); - } - - } else { - MessageManager.sendMessage(sender, "command_group_formal_not_admin"); - } - - groupChatInfo = null; - - } else { - MessageManager.sendSpecialMessage(sender, "command_group_does_not_exist", args[1].toUpperCase()); - } - - } else { - MessageManager.sendMessage(sender, "command_group_incorrect_usage"); - } - - break; - - } - - } else { - MessageManager.sendMessage(sender, "command_group_only_players"); - } - } - - @Override - public Iterable onTabComplete(CommandSender sender, String[] args) { - - Set matches = new HashSet(); - - if ( args.length == 1 ) { - - String search = args[0].toLowerCase(); - - List subCommands = new ArrayList(); - - subCommands.add("create"); - subCommands.add("join"); - subCommands.add("leave"); - subCommands.add("quit"); - subCommands.add("color"); - subCommands.add("colour"); - subCommands.add("transfer"); - subCommands.add("delete"); - subCommands.add("list"); - subCommands.add("members"); - subCommands.add("formal"); - subCommands.add("admin"); - subCommands.add("ban"); - - for ( String sub : subCommands ) { - if ( sub.toLowerCase().startsWith( search ) ) { - matches.add( sub ); - } - } - } - - return matches; - - } + private final Set args_zero = new HashSet<>(Arrays.asList("help", "members", "list", "spy", + "create", "make", "join", "quit", "leave", "formal", "delete", "transfer", "admin", "addadmin", + "removeadmin", "ban", "color") + ); + + public GroupCommand() { + super("mcgroup", "multichat.group", ProxyConfigs.ALIASES.getAliases("mcgroup")); + } + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_only_players"); + return; + } + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + UUID playerUID = proxiedPlayer.getUniqueId(); + + // TODO: This class needs some work in the future, then we can clean up this command more + GroupManager groupManager = new GroupManager(); + + String subCommand = args.length > 0 ? args[0].toLowerCase() : "help"; + String subArgument = args.length > 1 ? args[1].toLowerCase() : subCommand; + + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + + switch (subCommand) { + case "help": { + int page = 1; + try { + page = Integer.parseInt(subArgument); + } catch (NumberFormatException ignored) { + } + + groupManager.displayHelp(page, sender); + return; + } + case "members": + case "list": { + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, false); + if (groupChatInfo == null) break; + + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_member_list", subArgument); + groupChatInfo.getMembers().forEach(member -> + ProxyConfigs.MESSAGES.sendMessage(sender, + "command_group_member_list_item" + (groupChatInfo.isAdmin(member) ? "_admin" : ""), + UUIDNameManager.getName(member) + ) + ); + return; + } + case "spy": { + if (!proxiedPlayer.hasPermission("multichat.staff.spy")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_no_permission"); + return; + } + + if (subArgument.equals("all")) { + if (!proxyDataStore.getAllSpy().contains(playerUID)) { + proxyDataStore.getAllSpy().add(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_all_enabled"); + return; + } + + proxyDataStore.getAllSpy().remove(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_all_disabled_1"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_all_disabled_2"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_all_disabled_3"); + return; + } + + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, false); + if (groupChatInfo == null) break; + + if (groupChatInfo.isMember(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_already_a_member"); + return; + } + + if (groupChatInfo.isViewer(playerUID)) { + groupChatInfo.delViewer(playerUID); + proxyDataStore.getGroupChats().put(subArgument, groupChatInfo); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_off", subArgument); + return; + } + + groupChatInfo.addViewer(playerUID); + proxyDataStore.getGroupChats().put(subArgument, groupChatInfo); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_spy_on", subArgument); + return; + } + case "create": + case "make": { + if (!proxiedPlayer.hasPermission("multichat.group.create")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_create_no_permission"); + return; + } + + // TODO: Should probably make this configurable + if (subArgument.length() > 20) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_max_length"); + return; + } + + String password = args.length > 2 ? args[2] : ""; + if (password.length() > 20) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_max_length_password"); + return; + } + + if (proxyDataStore.getGroupChats().containsKey(subArgument)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_already_exists", subArgument); + return; + } + + // Make the new group, select it and announce the join + groupManager.createGroup(subArgument, playerUID, false, ""); + // TODO: Should probably move this inside the createGroup (joinGroup for join below) + groupManager.setViewedChat(playerUID, subArgument); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_created", subArgument); + + groupManager.announceJoinGroup(sender.getName(), subArgument); + return; + } + case "join": { + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, false); + if (groupChatInfo == null) break; + + if (!groupManager.joinGroup(subArgument, proxiedPlayer, args.length > 2 ? args[2] : "")) + return; + + groupManager.setViewedChat(playerUID, subArgument); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_joined", subArgument); + groupManager.announceJoinGroup(sender.getName(), subArgument); + return; + } + case "quit": + case "leave": { + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + groupManager.quitGroup(subArgument, playerUID, proxiedPlayer); + return; + } + case "formal": { + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + if (groupChatInfo.getFormal()) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_formal_already_formal", subArgument); + return; + } + + if (!groupChatInfo.getAdmins().contains(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_formal_not_owner"); + return; + } + + groupChatInfo.setFormal(true); + proxyDataStore.getGroupChats().put(subArgument, groupChatInfo); + // TODO: Excuse me what even is this + // We need to generalize sending messages at some point (and how placeholders are handled) + GCCommand.sendMessage(sender.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_formal"), "&lINFO", groupChatInfo); + return; + } + case "delete": { + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + if (!groupChatInfo.getAdmins().contains(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_formal_not_admin"); + return; + } + + proxyDataStore.getViewedChats().entrySet().forEach(entry -> { + if (entry.getValue() != null && entry.getValue().equals(subArgument)) + entry.setValue(null); + }); + + GCCommand.sendMessage(sender.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_deleted"), + "&lINFO", + groupChatInfo + ); + GCCommand.sendMessage(ProxyConfigs.MESSAGES.getMessage("groups_info_goodbye"), "&lINFO", groupChatInfo); + proxyDataStore.getGroupChats().remove(subArgument); + return; + } + case "transfer": { + if (args.length < 3) + break; + + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + if (groupChatInfo.getFormal()) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_transfer_not_informal"); + return; + } + + if (!groupChatInfo.isAdmin(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_transfer_not_owner"); + return; + } + + ProxiedPlayer target = getProxiedTargetFromName(groupChatInfo, proxiedPlayer, args[2], true); + if (target == null) + return; + UUID targetUID = target.getUniqueId(); + + groupChatInfo.addAdmin(targetUID); + groupChatInfo.delAdmin(playerUID); + GCCommand.sendMessage(sender.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_transfer") + target.getName(), "&lINFO", groupChatInfo); + + proxyDataStore.getGroupChats().put(subArgument, groupChatInfo); + return; + } + case "admin": + case "addadmin": + case "removeadmin": { + if (args.length < 3) + break; + + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + if (!groupChatInfo.getFormal()) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_not_formal"); + return; + } + + if (!groupChatInfo.isAdmin(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_formal_not_admin"); + return; + } + + ProxiedPlayer target = getProxiedTargetFromName(groupChatInfo, proxiedPlayer, args[2], true); + if (target == null) + return; + UUID targetUID = target.getUniqueId(); + + if (playerUID.equals(targetUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_formal_cannot_demote"); + return; + } + + if (groupChatInfo.isAdmin(targetUID)) { + groupChatInfo.delAdmin(targetUID); + GCCommand.sendMessage(target.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_step_down"), "&lINFO", groupChatInfo); + return; + } + + groupChatInfo.addAdmin(targetUID); + GCCommand.sendMessage(sender.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_promoted") + target.getName(), "&lINFO", groupChatInfo); + return; + } + case "ban": { + if (args.length < 3) + break; + + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + if (!groupChatInfo.getFormal()) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_not_formal"); + return; + } + + if (!groupChatInfo.isAdmin(playerUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_ban_not_admin"); + return; + } + + ProxiedPlayer target = getProxiedTargetFromName(groupChatInfo, proxiedPlayer, args[2], false); + if (target == null) + return; + UUID targetUID = target.getUniqueId(); + + if (groupChatInfo.isAdmin(targetUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_cannot_ban_admin"); + return; + } + + if (groupChatInfo.isBanned(targetUID)) { + groupChatInfo.delBanned(targetUID); + proxyDataStore.getGroupChats().put(subArgument, groupChatInfo); + GCCommand.sendMessage(sender.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_unban") + target.getName(), "&lINFO", groupChatInfo); + ProxyConfigs.MESSAGES.sendMessage(target, "command_group_unbanned", subArgument); + return; + } + + groupChatInfo.addBanned(targetUID); + if (groupChatInfo.isMember(targetUID)) { + groupChatInfo.delMember(targetUID); + groupChatInfo.delViewer(targetUID); + proxyDataStore.getViewedChats().put(targetUID, null); + + // TODO: I don't think we need to notify the user of being kicked AND banned further down below + GCCommand.sendMessage(sender.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_kick") + target.getName(), "&lINFO", groupChatInfo); + } + + proxyDataStore.getGroupChats().put(subArgument, groupChatInfo); + GCCommand.sendMessage(sender.getName() + ProxyConfigs.MESSAGES.getMessage("groups_info_ban") + target.getName(), "&lINFO", groupChatInfo); + ProxyConfigs.MESSAGES.sendMessage(target, "command_group_banned", subArgument); + return; + } + // Saving Private Byte + case "color": { + if (args.length < 4) + break; + + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + if (!groupChatInfo.isMember(playerUID) + || (groupChatInfo.getFormal() && !groupChatInfo.isAdmin(playerUID))) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_formal_not_admin"); + return; + } + + String chatColor = args[2].toLowerCase(); + String nameColor = args[3].toLowerCase(); + + if (!RegexUtil.LEGACY_COLOR.matches(chatColor) || !RegexUtil.LEGACY_COLOR.matches(nameColor)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_color_invalid"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_color_usage"); + return; + } + + groupChatInfo.setChatColor(chatColor.charAt(0)); + groupChatInfo.setNameColor(nameColor.charAt(0)); + + proxyDataStore.getGroupChats().put(subArgument, groupChatInfo); + GCCommand.sendMessage(ProxyConfigs.MESSAGES.getMessage("groups_info_colors") + sender.getName(), "&lINFO", groupChatInfo); + return; + } + default: { + TGroupChatInfo groupChatInfo = getGroupChatFromName(proxyDataStore, proxiedPlayer, subArgument, true); + if (groupChatInfo == null) break; + + proxyDataStore.getViewedChats().put(playerUID, subArgument); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_selected", subArgument); + return; + } + } + + ProxyConfigs.MESSAGES.sendMessage(sender, "command_group_incorrect_usage"); + } + + private TGroupChatInfo getGroupChatFromName(ProxyDataStore proxyDataStore, ProxiedPlayer proxiedPlayer, String groupName, boolean checkMember) { + TGroupChatInfo groupChatInfo = proxyDataStore.getGroupChats().get(groupName); + if (groupChatInfo == null) { + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "command_group_does_not_exist", groupName); + return null; + } + + if (checkMember && !groupChatInfo.isMember(proxiedPlayer.getUniqueId())) { + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "command_group_not_a_member", groupName); + return null; + } + + return groupChatInfo; + } + + private ProxiedPlayer getProxiedTargetFromName(TGroupChatInfo groupChatInfo, ProxiedPlayer proxiedPlayer, String name, boolean checkMember) { + ProxiedPlayer target = ProxyServer.getInstance().getPlayer(name); + if (target == null) { + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "command_group_player_not_online"); + return null; + } + UUID targetUID = target.getUniqueId(); + + if (checkMember && !groupChatInfo.isMember(targetUID)) { + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "command_group_transfer_not_member"); + return null; + } + + return target; + } + + @Override + public Iterable onTabComplete(CommandSender sender, String[] args) { + Set matches = new HashSet<>(); + + if (args.length == 1) { + String search = args[0].toLowerCase(); + args_zero.forEach(subCommand -> { + if (subCommand.length() > search.length() + && subCommand.regionMatches(true, 0, search, 0, search.length())) + matches.add(subCommand); + }); + } + + return matches; + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupListCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupListCommand.java index ab8afc08..50ef87d4 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupListCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/GroupListCommand.java @@ -2,31 +2,28 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * Group List Command *

Displays a list of all current group chats on the server

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class GroupListCommand extends Command { - private static String[] aliases = new String[] {}; - - public GroupListCommand() { - super("groups", "multichat.staff.listgroups", aliases); - } - - public void execute(CommandSender sender, String[] args) { + public GroupListCommand() { + super("mcgroups", "multichat.staff.listgroups", ProxyConfigs.ALIASES.getAliases("mcgroups")); + } - MessageManager.sendMessage(sender, "command_grouplist_list"); + public void execute(CommandSender sender, String[] args) { + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); - for (String groupname : MultiChat.groupchats.keySet()) { - MessageManager.sendSpecialMessage(sender, "command_grouplist_list_item", groupname); - } + ProxyConfigs.MESSAGES.sendMessage(sender, "command_grouplist_list"); - } + for (String groupName : proxyDataStore.getGroupChats().keySet()) + ProxyConfigs.MESSAGES.sendMessage(sender, "command_grouplist_list_item", groupName); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/HelpMeCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/HelpMeCommand.java index 28b9cdd3..35946b04 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/HelpMeCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/HelpMeCommand.java @@ -8,81 +8,58 @@ import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.ChatControl; import xyz.olivermartin.multichat.bungee.ConsoleManager; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; /** * 'Help Me' Command *

Allows players to request help from all online staff members

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class HelpMeCommand extends Command { - private static String[] aliases = new String[] {}; - public HelpMeCommand() { - super("helpme", "multichat.chat.helpme", aliases); + super("mchelpme", "multichat.chat.helpme", ProxyConfigs.ALIASES.getAliases("mchelpme")); } public void execute(CommandSender sender, String[] args) { - - if ( sender instanceof ProxiedPlayer ) { - - if (args.length < 1) { - - MessageManager.sendMessage(sender, "command_helpme_desc"); - MessageManager.sendMessage(sender, "command_helpme_usage"); - - } else { - - String message = MultiChatUtil.getMessageFromArgs(args); - - if ( sendMessage(sender.getName() + ": " + message, sender.getName()) ) { - MessageManager.sendMessage(sender, "command_helpme_sent"); - } - - } - - } else { - MessageManager.sendMessage(sender, "command_helpme_only_players"); + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_helpme_only_players"); + return; } - } - - public static boolean sendMessage(String message, String username) { - Optional crm; + if (args.length < 1) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_helpme_desc"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_helpme_usage"); + return; + } - ProxiedPlayer potentialPlayer = ProxyServer.getInstance().getPlayer(username); - if (potentialPlayer != null) { - if (ChatControl.isMuted(potentialPlayer.getUniqueId(), "helpme")) { - MessageManager.sendMessage(potentialPlayer, "mute_cannot_send_message"); - return false; - } + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; - if (ChatControl.handleSpam(potentialPlayer, message, "helpme")) { - return false; - } + if (ChatControl.isMuted(proxiedPlayer.getUniqueId(), MessageType.HELPME)) { + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "mute_cannot_send_message"); + return; } - crm = ChatControl.applyChatRules(message, "helpme", username); + // TODO: Probably should do this differently + String message = proxiedPlayer.getName() + ": " + String.join(" ", args); - if (crm.isPresent()) { - message = crm.get(); - } else { - return false; + if (ChatControl.handleSpam(proxiedPlayer, message, MessageType.HELPME)) { + return; } - for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { - if (onlineplayer.hasPermission("multichat.staff")) { - MessageManager.sendSpecialMessage(onlineplayer, "command_helpme_format", message); - } - } + Optional crm = ChatControl.applyChatRules(proxiedPlayer, message, MessageType.HELPME); + if (!crm.isPresent()) + return; - ConsoleManager.logHelpMe(message); + String finalMessage = crm.get(); - return true; + ProxyServer.getInstance().getPlayers().stream() + .filter(target -> target.hasPermission("multichat.staff")) + .forEach(target -> ProxyConfigs.MESSAGES.sendMessage(target, "command_helpme_format", finalMessage)); + ConsoleManager.logHelpMe(message); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_helpme_sent"); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/IgnoreCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/IgnoreCommand.java index c4f88496..78506127 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/IgnoreCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/IgnoreCommand.java @@ -4,68 +4,57 @@ import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.BungeeComm; import xyz.olivermartin.multichat.bungee.ChatControl; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.MessageManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; -public class IgnoreCommand extends Command { - - public IgnoreCommand() { - super("ignore", "multichat.ignore", (String[])ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().getStringList("ignorecommand").toArray(new String[0])); - } - - @Override - public void execute(CommandSender sender, String[] args) { - - if (args.length != 1) { - - MessageManager.sendMessage(sender, "ignore_usage"); - - } else { - - if (sender instanceof ProxiedPlayer) { - - String username = args[0]; - - ProxiedPlayer target = ProxyServer.getInstance().getPlayer(username); - - if (target != null) { - - if (target.getName().equals(sender.getName())) { - MessageManager.sendMessage(sender, "ignore_cannot_ignore_yourself"); - return; - } +import java.util.UUID; - if (target.hasPermission("multichat.ignore.bypass")) { - MessageManager.sendMessage(sender, "ignore_bypass"); - return; - } - - if (!ChatControl.ignoresAnywhere(target.getUniqueId(), ((ProxiedPlayer) sender).getUniqueId())) { - ChatControl.ignore(((ProxiedPlayer) sender).getUniqueId(), target.getUniqueId()); - MessageManager.sendSpecialMessage(sender, "ignore_ignored", target.getName()); - } else { - ChatControl.unignore(((ProxiedPlayer) sender).getUniqueId(), target.getUniqueId()); - MessageManager.sendSpecialMessage(sender, "ignore_unignored", target.getName()); - } - - BungeeComm.sendIgnoreMap(((ProxiedPlayer) sender).getServer().getInfo()); - - } else { - - MessageManager.sendMessage(sender, "ignore_player_not_found"); - - } - - } else { - - MessageManager.sendMessage(sender, "ignore_only_players"); - - } - - } - - } +public class IgnoreCommand extends Command { + public IgnoreCommand() { + super("mcignore", "multichat.ignore", ProxyConfigs.ALIASES.getAliases("mcignore")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "ignore_only_players"); + return; + } + + if (args.length == 0) { + ProxyConfigs.MESSAGES.sendMessage(sender, "ignore_usage"); + return; + } + + ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]); + + if (target == null) { + ProxyConfigs.MESSAGES.sendMessage(sender, "ignore_player_not_found"); + return; + } + + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + if (proxiedPlayer.equals(target)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "ignore_cannot_ignore_yourself"); + return; + } + + if (target.hasPermission("multichat.ignore.bypass")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "ignore_bypass"); + return; + } + + UUID playerUID = proxiedPlayer.getUniqueId(); + UUID targetUID = target.getUniqueId(); + + // TODO: ChatControl.toggleIgnore + if (!ChatControl.ignoresAnywhere(targetUID, playerUID)) { + ChatControl.ignore(playerUID, targetUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "ignore_ignored", target.getName()); + } else { + ChatControl.unignore(playerUID, targetUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "ignore_unignored", target.getName()); + } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/LocalCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/LocalCommand.java index 62a2c9f7..bcf0fd52 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/LocalCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/LocalCommand.java @@ -1,109 +1,90 @@ package xyz.olivermartin.multichat.bungee.commands; import java.util.Optional; +import java.util.UUID; import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.BungeeComm; -import xyz.olivermartin.multichat.bungee.Channel; -import xyz.olivermartin.multichat.bungee.ChatControl; import xyz.olivermartin.multichat.bungee.ChatModeManager; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.DebugManager; -import xyz.olivermartin.multichat.bungee.Events; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyChatManager; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; /** * Local Chat Command *

Players can use this command to only see the chat sent from players on their current server

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class LocalCommand extends Command { - public LocalCommand() { - super("local", "multichat.chat.mode", (String[]) ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("localcommand").toArray(new String[0])); - } - - public void execute(CommandSender sender, String[] args) { - - if ((sender instanceof ProxiedPlayer)) { - - if (args.length < 1) { - - ChatModeManager.getInstance().setLocal(((ProxiedPlayer)sender).getUniqueId()); - - MessageManager.sendMessage(sender, "command_local_enabled_1"); - MessageManager.sendMessage(sender, "command_local_enabled_2"); - - } else { - - String message = MultiChatUtil.getMessageFromArgs(args); - ProxiedPlayer player = (ProxiedPlayer)sender; - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - - if ((!MultiChat.frozen) || (player.hasPermission("multichat.chat.always"))) { + public LocalCommand() { + super("mclocal", "multichat.chat.mode", ProxyConfigs.ALIASES.getAliases("mclocal")); + } - if (ChatControl.isMuted(player.getUniqueId(), "global_chat")) { - MessageManager.sendMessage(player, "mute_cannot_send_message"); - return; - } + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_local_only_players"); + return; + } + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + UUID playerUID = proxiedPlayer.getUniqueId(); - DebugManager.log(player.getName() + "- about to check for spam"); + if (args.length == 0) { + ChatModeManager.getInstance().setLocal(playerUID); - if (ChatControl.handleSpam(player, message, "global_chat")) { - DebugManager.log(player.getName() + " - chat message being cancelled due to spam"); - return; - } + ProxyConfigs.MESSAGES.sendMessage(sender, "command_local_enabled_1"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_local_enabled_2"); + return; + } - Optional crm; + ServerInfo serverInfo = proxiedPlayer.getServer().getInfo(); + if (ProxyConfigs.CONFIG.isFetchSpigotDisplayNames()) + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(proxiedPlayer.getName(), serverInfo); - crm = ChatControl.applyChatRules(message, "global_chat", player.getName()); + ProxyChatManager chatManager = MultiChatProxy.getInstance().getChatManager(); - if (crm.isPresent()) { - message = crm.get(); - } else { - return; - } + String message = String.join(" ", args); - if (!player.hasPermission("multichat.chat.link")) { - message = ChatControl.replaceLinks(message); - } + Optional optionalMessage = chatManager.handleChatMessage(proxiedPlayer, message); // Processed message - // If they had this channel hidden, then unhide it... - Channel local = Channel.getLocalChannel(); - if (!local.isMember(player.getUniqueId())) { - local.removeMember(player.getUniqueId()); - MessageManager.sendSpecialMessage(player, "command_channel_show", "LOCAL"); - } + if (!optionalMessage.isPresent()) + return; - // Let server know players channel preference - BungeeComm.sendPlayerChannelMessage(player.getName(), Channel.getChannel(player.getUniqueId()).getName(), Channel.getChannel(player.getUniqueId()), player.getServer().getInfo(), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.simple")||player.hasPermission("multichat.chat.color.simple")), (player.hasPermission("multichat.chat.colour")||player.hasPermission("multichat.chat.color")||player.hasPermission("multichat.chat.colour.rgb")||player.hasPermission("multichat.chat.color.rgb"))); + message = optionalMessage.get(); - // Message passes through to spigot here - // Send message directly to local chat... + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); - BungeeComm.sendPlayerCommandMessage("!SINGLE L MESSAGE!" + message, sender.getName(), ((ProxiedPlayer)sender).getServer().getInfo()); + // If they had this channel hidden, then unhide it... + if (channelManager.isHidden(playerUID, "local")) { + channelManager.show(playerUID, "local"); + ProxyConfigs.MESSAGES.sendMessage(proxiedPlayer, "command_channel_show", "LOCAL"); + } - if (Events.hiddenStaff.contains(player.getUniqueId())) { - Events.hiddenStaff.remove(player.getUniqueId()); - } + // Let server know players channel preference - } else { - MessageManager.sendMessage(player, "freezechat_frozen"); - } + String currentChannel = channelManager.getChannel(proxiedPlayer); + String channelFormat = currentChannel.equals("local") + ? channelManager.getLocalChannel().getFormat() + : channelManager.getProxyChannel(currentChannel).orElse(channelManager.getGlobalChannel()).getInfo() + .getFormat(); - } + ProxyLocalCommunicationManager.sendPlayerDataMessage(proxiedPlayer.getName(), + currentChannel, + channelFormat, + serverInfo, + (proxiedPlayer.hasPermission("multichat.chat.color") || proxiedPlayer.hasPermission("multichat.chat.colour.simple") || proxiedPlayer.hasPermission("multichat.chat.color.simple")), + (proxiedPlayer.hasPermission("multichat.chat.color") || proxiedPlayer.hasPermission("multichat.chat.colour.rgb") || proxiedPlayer.hasPermission("multichat.chat.color.rgb")) + ); - } else { - MessageManager.sendMessage(sender, "command_local_only_players"); - } - } + // Message passes through to spigot here + // Send message directly to local chat... + ProxyLocalCommunicationManager.sendPlayerDirectChatMessage("local", sender.getName(), message, serverInfo); + // TODO: Move this somewhere else in the future + MultiChatProxy.getInstance().getDataStore().getHiddenStaff().remove(playerUID); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/LocalSpyCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/LocalSpyCommand.java new file mode 100644 index 00000000..86069c33 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/LocalSpyCommand.java @@ -0,0 +1,51 @@ +package xyz.olivermartin.multichat.bungee.commands; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.plugin.Command; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.UUID; + +/** + * SocialSpy Command + *

Allows staff members to view private messages sent by players

+ * + * @author Oliver Martin (Revilo410) + */ +public class LocalSpyCommand extends Command { + + public LocalSpyCommand() { + super("mclocalspy", "multichat.staff.spy", ProxyConfigs.ALIASES.getAliases("mclocalspy")); + } + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_localspy_only_players"); + return; + } + + // TODO: Do we really need this? I don't think so... just toggle it, no matter how many arguments + if (args.length != 0) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_localspy_usage"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_localspy_desc"); + return; + } + + UUID playerUID = ((ProxiedPlayer) sender).getUniqueId(); + + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + + // TODO: Potentially proxyDataStore.toggleSpy(playerUID) + if (proxyDataStore.getLocalSpy().contains(playerUID)) { + proxyDataStore.getLocalSpy().remove(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_localspy_disabled"); + return; + } + + proxyDataStore.getLocalSpy().add(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_localspy_enabled"); + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCCommand.java index 0535cef9..17524257 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCCommand.java @@ -5,73 +5,53 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; +import xyz.olivermartin.multichat.common.RegexUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.UUID; /** * Mod-Chat Colour Command *

Allows staff members to individually set the colours that they see the mod-chat displayed in

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class MCCCommand extends Command { - private static String[] aliases = new String[] {}; - - public MCCCommand() { - super("mcc", "multichat.staff.mod", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length != 2) { - - if ((sender instanceof ProxiedPlayer)) { - MessageManager.sendMessage(sender, "command_mcc_usage"); - } else { - MessageManager.sendMessage(sender, "command_mcc_only_players"); - } - - } else if ((sender instanceof ProxiedPlayer)) { - - TChatInfo chatinfo = new TChatInfo(); - ProxiedPlayer player = (ProxiedPlayer) sender; - - args[0] = args[0].toLowerCase(); - args[1] = args[1].toLowerCase(); - - if ((args[0].equals("a")) || (args[0].equals("b")) || (args[0].equals("c")) || (args[0].equals("d")) - || (args[0].equals("e")) || (args[0].equals("f")) || (args[0].equals("0")) || (args[0].equals("1")) - || (args[0].equals("2")) || (args[0].equals("3")) || (args[0].equals("4")) || (args[0].equals("5")) - || (args[0].equals("6")) || (args[0].equals("7")) || (args[0].equals("8")) || (args[0].equals("9"))) { - - if ((args[1].equals("a")) || (args[1].equals("b")) || (args[1].equals("c")) || (args[1].equals("d")) - || (args[1].equals("e")) || (args[1].equals("f")) || (args[1].equals("0")) || (args[1].equals("1")) - || (args[1].equals("2")) || (args[1].equals("3")) || (args[1].equals("4")) || (args[1].equals("5")) - || (args[1].equals("6")) || (args[1].equals("7")) || (args[1].equals("8")) || (args[1].equals("9"))) { + public MCCCommand() { + super("mcmcc", "multichat.staff.mod", ProxyConfigs.ALIASES.getAliases("mcmcc")); + } - MultiChat.modchatpreferences.remove(player.getUniqueId()); + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_mcc_only_players"); + return; + } - chatinfo.setChatColor(args[0].charAt(0)); - chatinfo.setNameColor(args[1].charAt(0)); + if (args.length < 2) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_mcc_usage"); + return; + } - MultiChat.modchatpreferences.put(player.getUniqueId(), chatinfo); + String chatColor = args[0].toLowerCase(); + String nameColor = args[1].toLowerCase(); - MessageManager.sendMessage(sender, "command_mcc_updated"); + if (!RegexUtil.LEGACY_COLOR.matches(chatColor) || !RegexUtil.LEGACY_COLOR.matches(nameColor)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_mcc_invalid"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_mcc_invalid_usage"); + return; + } - } else { - MessageManager.sendMessage(sender, "command_mcc_invalid"); - MessageManager.sendMessage(sender, "command_mcc_invalid_usage"); - } + UUID playerUID = ((ProxiedPlayer) sender).getUniqueId(); + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + TChatInfo chatInfo = proxyDataStore.getModChatPreferences().getOrDefault(playerUID, new TChatInfo()); - } else { - MessageManager.sendMessage(sender, "command_mcc_invalid"); - MessageManager.sendMessage(sender, "command_mcc_invalid_usage"); - } + chatInfo.setChatColor(chatColor.charAt(0)); + chatInfo.setNameColor(nameColor.charAt(0)); + proxyDataStore.getModChatPreferences().put(playerUID, chatInfo); - } else { - MessageManager.sendMessage(sender, "command_mcc_only_players"); - } - } + ProxyConfigs.MESSAGES.sendMessage(sender, "command_mcc_updated"); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCommand.java index a578fa3e..c6b90324 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MCCommand.java @@ -4,63 +4,47 @@ import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.Events; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.bungee.StaffChatManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.UUID; /** * Mod-Chat Commands *

Allows staff members to send mod-chat messages or toggle the chat

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class MCCommand extends Command { - private static String[] aliases = new String[] {}; - - public MCCommand() { - super("mc", "multichat.staff.mod", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - boolean toggleresult; - - if (args.length < 1) { - - if ((sender instanceof ProxiedPlayer)) { - - ProxiedPlayer player = (ProxiedPlayer) sender; - toggleresult = Events.toggleMC(player.getUniqueId()); - - if (toggleresult == true) { - MessageManager.sendMessage(sender, "command_mc_toggle_on"); - } else { - MessageManager.sendMessage(sender, "command_mc_toggle_off"); - } - - } else { - MessageManager.sendMessage(sender, "command_mc_only_players"); - } - - } else if ((sender instanceof ProxiedPlayer)) { - - String message = MultiChatUtil.getMessageFromArgs(args); - - ProxiedPlayer player = (ProxiedPlayer) sender; - - StaffChatManager chatman = new StaffChatManager(); - chatman.sendModMessage(player.getName(), player.getDisplayName(), player.getServer().getInfo().getName(), message); - chatman = null; - - } else { - - String message = MultiChatUtil.getMessageFromArgs(args); - - StaffChatManager chatman = new StaffChatManager(); - chatman.sendModMessage("CONSOLE", "CONSOLE", "#", message); - chatman = null; - } - } + public MCCommand() { + super("mcmc", "multichat.staff.mod", ProxyConfigs.ALIASES.getAliases("mcmc")); + } + + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_mc_only_players"); + return; + } + + UUID playerUID = ((ProxiedPlayer) sender).getUniqueId(); + boolean toggleResult = Events.toggleMC(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_mc_toggle_" + (toggleResult ? "on" : "off")); + return; + } + + String name = "CONSOLE"; + String displayName = "CONSOLE"; + String serverName = "#"; + + if (sender instanceof ProxiedPlayer) { + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + name = proxiedPlayer.getName(); + displayName = proxiedPlayer.getDisplayName(); + serverName = proxiedPlayer.getServer().getInfo().getName(); + } + + new StaffChatManager().sendModMessage(name, displayName, serverName, String.join(" ", args)); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MsgCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MsgCommand.java index 22fc963c..06e0cdb8 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MsgCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MsgCommand.java @@ -1,265 +1,202 @@ package xyz.olivermartin.multichat.bungee.commands; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; - import de.myzelyam.api.vanish.BungeeVanishAPI; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.TabExecutor; -import net.md_5.bungee.config.Configuration; -import xyz.olivermartin.multichat.bungee.BungeeComm; -import xyz.olivermartin.multichat.bungee.ChatControl; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.Events; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; -import xyz.olivermartin.multichat.bungee.PrivateMessageManager; +import xyz.olivermartin.multichat.bungee.*; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.*; /** * Message Command *

Allows players to send private messages to each other

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class MsgCommand extends Command implements TabExecutor { public MsgCommand() { - super("msg", "multichat.chat.msg", (String[]) ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("msgcommand").toArray(new String[0])); + super("mcmsg", "multichat.chat.msg", ProxyConfigs.ALIASES.getAliases("mcmsg")); } public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_usage"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_usage_toggle"); + return; + } - if (args.length < 1) { - - // Show usage (not enough args) - - MessageManager.sendMessage(sender, "command_msg_usage"); - MessageManager.sendMessage(sender, "command_msg_usage_toggle"); - - } else { - - boolean toggleresult; - - if (args.length == 1) { - - // 1 arg --> toggle - - if (ProxyServer.getInstance().getPlayer(args[0]) != null) { - - ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]); - - if ((sender instanceof ProxiedPlayer)) { - - boolean permittedToMessage = true; - - if (MultiChat.premiumVanish && MultiChat.hideVanishedStaffInMsg) { - if (BungeeVanishAPI.isInvisible(target) && !sender.hasPermission("multichat.chat.msg.vanished")) { - permittedToMessage = false; - } - } - - if (permittedToMessage) { - - ProxiedPlayer player = (ProxiedPlayer)sender; - toggleresult = Events.togglePM(player.getUniqueId(), target.getUniqueId()); - - if (toggleresult == true) { - - Configuration config = ConfigManager.getInstance().getHandler("config.yml").getConfig(); - - if (config.contains("toggle_pm") ? config.getBoolean("toggle_pm") == false : false) { - - toggleresult = Events.togglePM(player.getUniqueId(), target.getUniqueId()); - MessageManager.sendMessage(sender, "command_msg_no_toggle"); - - } else { - MessageManager.sendSpecialMessage(sender, "command_msg_toggle_on", target.getName()); - } - - } else { - MessageManager.sendMessage(sender, "command_msg_toggle_off"); - } - - } else { - // Vanished staff member - MessageManager.sendMessage(sender, "command_msg_not_online"); - } - - } else { - MessageManager.sendMessage(sender, "command_msg_only_players"); - } - - } else { - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if ( Events.PMToggle.containsKey(player.getUniqueId())) { - Events.PMToggle.remove(player.getUniqueId()); - MessageManager.sendMessage(sender, "command_msg_toggle_off"); - } else { - MessageManager.sendMessage(sender, "command_msg_not_online"); - } - - } - - } else if ((sender instanceof ProxiedPlayer)) { - - // >1 arg and the sender is a PLAYER - - String message = MultiChatUtil.getMessageFromArgs(args, 1); - - Optional crm; + // Pre-Load target because we need it in both scenarios + Optional optionalTarget = PrivateMessageManager.getInstance().getPartialPlayerMatch(args[0]); - if (ChatControl.isMuted(((ProxiedPlayer)sender).getUniqueId(), "private_messages")) { - MessageManager.sendMessage(sender, "mute_cannot_send_message"); - return; - } + if (args.length == 1) { + // Console can not toggle PMs + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_only_players"); + return; + } - if (ChatControl.handleSpam(((ProxiedPlayer)sender), message, "private_messages")) { - return; - } + // Check if PMs are allowed to be toggled + if (!ProxyConfigs.CONFIG.isTogglePm()) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_no_toggle"); + return; + } - crm = ChatControl.applyChatRules(message, "private_messages", sender.getName()); + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + UUID playerUID = proxiedPlayer.getUniqueId(); - if (crm.isPresent()) { - message = crm.get(); + // If there is no target, quit current PM toggle or notify sender about it + if (!optionalTarget.isPresent()) { + if (Events.PMToggle.containsKey(playerUID)) { + Events.PMToggle.remove(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_toggle_off"); } else { - return; + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_not_online"); } + return; + } - if (ProxyServer.getInstance().getPlayer(args[0]) != null) { - - ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]); - - boolean permittedToMessage = true; - - if (MultiChat.premiumVanish && MultiChat.hideVanishedStaffInMsg) { - if (BungeeVanishAPI.isInvisible(target) && !sender.hasPermission("multichat.chat.msg.vanished")) { - permittedToMessage = false; - } - } - - if (permittedToMessage) { - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - - BungeeComm.sendMessage(sender.getName(), ((ProxiedPlayer)sender).getServer().getInfo()); - BungeeComm.sendMessage(target.getName(), target.getServer().getInfo()); - - } - - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(((ProxiedPlayer)sender).getServer().getInfo().getName())) { - - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(target.getServer().getInfo().getName())) { - - if (ChatControl.ignores(((ProxiedPlayer)sender).getUniqueId(), target.getUniqueId(), "private_messages")) { - ChatControl.sendIgnoreNotifications(target, sender, "private_messages"); - return; - } - - PrivateMessageManager.getInstance().sendMessage(message, (ProxiedPlayer)sender, target); - - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_target"); - } - - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_sender"); - } - - } else { - // Vanished staff member - MessageManager.sendMessage(sender, "command_msg_not_online"); - } + ProxiedPlayer target = optionalTarget.get(); - } else if (args[0].equalsIgnoreCase("console")) { + // TODO: Make this into a proper hook at some point so we can just call Somewhere.getVanishHook().applies(); or something + if (MultiChat.premiumVanish + && ProxyConfigs.CONFIG.isPvPreventMessage() + && BungeeVanishAPI.isInvisible(target) + && !sender.hasPermission("multichat.chat.msg.vanished")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_not_online"); + return; + } - // New console target stuff here! + // Toggle PM and send message + boolean toggleResult = Events.togglePM(playerUID, target.getUniqueId()); + ProxyConfigs.MESSAGES.sendMessage(sender, + "command_msg_toggle_" + (toggleResult ? "on" : "off"), + target.getName() + ); + return; + } - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { + // Cache message + String message = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); - BungeeComm.sendMessage(sender.getName(), ((ProxiedPlayer)sender).getServer().getInfo()); + // Cache config values + boolean fetchSpigotDisplayNames = ProxyConfigs.CONFIG.isFetchSpigotDisplayNames(); - } + // Target not online + if (!optionalTarget.isPresent()) { + if (!(sender instanceof ProxiedPlayer) || !args[0].equalsIgnoreCase("console")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_not_online"); + return; + } - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(((ProxiedPlayer)sender).getServer().getInfo().getName())) { + // Support to send private messages to console + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + ServerInfo serverInfo = proxiedPlayer.getServer().getInfo(); - PrivateMessageManager.getInstance().sendMessageConsoleTarget(message, (ProxiedPlayer)sender); + // Handle disabled servers for player + if (ProxyConfigs.CONFIG.isNoPmServer(serverInfo.getName())) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_disabled_sender"); + return; + } - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_sender"); - } + // Update player data on local server + if (fetchSpigotDisplayNames) + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(sender.getName(), serverInfo); - // End of console target stuff + // Send message to console + PrivateMessageManager.getInstance().sendMessageConsoleTarget(message, proxiedPlayer); + return; + } - } else { - MessageManager.sendMessage(sender, "command_msg_not_online"); - } + ProxiedPlayer target = optionalTarget.get(); + ServerInfo targetServerInfo = target.getServer().getInfo(); - } else { + // Handle disabled servers for target + if (ProxyConfigs.CONFIG.isNoPmServer(targetServerInfo.getName())) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_disabled_target"); + return; + } - // >1 arg and the sender is the CONSOLE + // Update target data on local server + if (fetchSpigotDisplayNames) + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(target.getName(), targetServerInfo); - String message = MultiChatUtil.getMessageFromArgs(args, 1); + // If the command sender is the console, send the message now + if (!(sender instanceof ProxiedPlayer)) { + PrivateMessageManager.getInstance().sendMessageConsoleSender(message, target); + return; + } - if (ProxyServer.getInstance().getPlayer(args[0]) != null) { + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + UUID playerUID = proxiedPlayer.getUniqueId(); + ServerInfo serverInfo = proxiedPlayer.getServer().getInfo(); - ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]); + // Handle disabled servers for player + if (ProxyConfigs.CONFIG.isNoPmServer(serverInfo.getName())) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_disabled_sender"); + return; + } - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { + // Check if player has been muted through MultiChat + if (ChatControl.isMuted(playerUID, MessageType.PRIVATE_MESSAGES)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "mute_cannot_send_message"); + return; + } - BungeeComm.sendMessage(target.getName(), target.getServer().getInfo()); + // Check if the target ignores the player + if (ChatControl.ignores(playerUID, target.getUniqueId(), MessageType.PRIVATE_MESSAGES)) { + ChatControl.sendIgnoreNotifications(target, sender, "private_messages"); + return; + } - } + // Check player for potential spam + if (ChatControl.handleSpam(proxiedPlayer, message, MessageType.PRIVATE_MESSAGES)) + return; - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(target.getServer().getInfo().getName())) { + // Apply chat rules, if any of them cancel the message, return + Optional optionalChatControl = ChatControl.applyChatRules(sender, message, MessageType.PRIVATE_MESSAGES); + if (!optionalChatControl.isPresent()) + return; - PrivateMessageManager.getInstance().sendMessageConsoleSender(message, target); + message = optionalChatControl.get(); - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_target"); - } + if (MultiChat.premiumVanish + && ProxyConfigs.CONFIG.isPvPreventMessage() + && BungeeVanishAPI.isInvisible(target) + && !sender.hasPermission("multichat.chat.msg.vanished")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_not_online"); + return; + } - } else { - MessageManager.sendMessage(sender, "command_msg_not_online"); - } + // Update player data on local server + if (fetchSpigotDisplayNames) + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(sender.getName(), serverInfo); - } - } + // Finally send the message + PrivateMessageManager.getInstance().sendMessage(message, proxiedPlayer, target); } @Override public Iterable onTabComplete(CommandSender sender, String[] args) { - Set matches = new HashSet<>(); - if ( args.length == 1 ) { - + if (args.length == 1) { String search = args[0].toLowerCase(); - - for ( ProxiedPlayer player : ProxyServer.getInstance().getPlayers() ) { - - if ( player.getName().toLowerCase().startsWith( search ) ) { - - if (!Events.hiddenStaff.contains(player.getUniqueId())) { - if (MultiChat.premiumVanish) { - if (!BungeeVanishAPI.isInvisible(player)) { - matches.add(player.getName()); - } - } else { - matches.add(player.getName()); - } - } - - } - - } + Set hiddenStaff = MultiChatProxy.getInstance().getDataStore().getHiddenStaff(); + ProxyServer.getInstance().getPlayers().stream() + .filter(target -> target.getName().toLowerCase().startsWith(search) + && !hiddenStaff.contains(target.getUniqueId()) + && !(MultiChat.premiumVanish && BungeeVanishAPI.isInvisible(target)) + ) + .forEach(target -> matches.add(target.getName())); } return matches; diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatBypassCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatBypassCommand.java index 10afc672..4eeb7ea3 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatBypassCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatBypassCommand.java @@ -3,45 +3,38 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.ConfigManager; import xyz.olivermartin.multichat.bungee.Events; -import xyz.olivermartin.multichat.bungee.MessageManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; -public class MultiChatBypassCommand extends Command { - - public MultiChatBypassCommand() { - super("multichatbypass", "multichat.bypass", ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("multichatbypasscommand") ? (String[]) ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("multichatbypasscommand").toArray(new String[0]) : new String[0]); - } - - @Override - public void execute(CommandSender sender, String[] args) { - - if (! (sender instanceof ProxiedPlayer)) { - return; - } - - ProxiedPlayer player = (ProxiedPlayer) sender; - - if (args.length >= 1) { - - MessageManager.sendMessage(sender, "command_multichatbypass_usage"); - - } else { +import java.util.UUID; - if (Events.mcbPlayers.contains(player.getUniqueId())) { - - Events.mcbPlayers.remove(player.getUniqueId()); - MessageManager.sendMessage(sender, "command_multichatbypass_disabled"); - - } else { - - Events.mcbPlayers.add(player.getUniqueId()); - MessageManager.sendMessage(sender, "command_multichatbypass_enabled"); - - } - - } - - } +public class MultiChatBypassCommand extends Command { + public MultiChatBypassCommand() { + super("mcbypass", "multichat.bypass", ProxyConfigs.ALIASES.getAliases("mcbypass")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + // TODO: Add a message here like in all other commands + return; + } + + if (args.length != 0) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichatbypass_usage"); + return; + } + + UUID playerUID = ((ProxiedPlayer) sender).getUniqueId(); + + // TODO: This should definitely be changed later + if (Events.mcbPlayers.contains(playerUID)) { + Events.mcbPlayers.remove(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichatbypass_disabled"); + } else { + Events.mcbPlayers.add(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichatbypass_enabled"); + } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatCommand.java index f60fe8f3..79bd665c 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatCommand.java @@ -2,185 +2,107 @@ import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; -import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.Channel; -import xyz.olivermartin.multichat.bungee.ChatControl; -import xyz.olivermartin.multichat.bungee.CommandManager; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.DebugManager; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; -import xyz.olivermartin.multichat.bungee.UUIDNameManager; +import xyz.olivermartin.multichat.bungee.*; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.channels.local.LocalChannel; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.GlobalStaticProxyChannel; +import xyz.olivermartin.multichat.proxy.common.config.AbstractProxyConfig; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.contexts.GlobalContext; /** * MultiChat (Admin) Command *

Used to view details about the plugin and display help information

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class MultiChatCommand extends Command { - private static String[] aliases = new String[] {}; - - public MultiChatCommand() { - super("multichat", "multichat.admin", aliases); - } - - private void displayHelp(CommandSender sender, int page) { - - switch (page) { - - case 1: - - MessageManager.sendMessage(sender, "command_multichat_help_1"); - break; - - case 2: - - MessageManager.sendMessage(sender, "command_multichat_help_2"); - break; - - default: - - MessageManager.sendMessage(sender, "command_multichat_help_3"); - break; - - } - - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&2Multi&aChat &bVersion " + MultiChat.LATEST_VERSION)).create()); - sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&bBy Revilo410")).create()); - sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&bOriginally created for &3Oasis-MC.US")).create()); - sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&bUse &3/multichat help &bfor all commands")).create()); - - } else { - - if (args.length == 1) { - - if (args[0].toLowerCase().equals("help")) { - - displayHelp(sender, 1); - - } else if (args[0].toLowerCase().equals("debug")) { - - DebugManager.toggle(); - DebugManager.log("Debug mode toggled"); - - } else if (args[0].toLowerCase().equals("save")) { - - MessageManager.sendMessage(sender, "command_multichat_save_prepare"); - - MultiChat.saveChatInfo(); - MultiChat.saveGroupChatInfo(); - MultiChat.saveGroupSpyInfo(); - MultiChat.saveGlobalChatInfo(); - MultiChat.saveSocialSpyInfo(); - MultiChat.saveAnnouncements(); - MultiChat.saveBulletins(); - MultiChat.saveCasts(); - MultiChat.saveMute(); - MultiChat.saveIgnore(); - UUIDNameManager.saveUUIDS(); - - MessageManager.sendMessage(sender, "command_multichat_save_completed"); - - } else if (args[0].toLowerCase().equals("reload")) { - - MessageManager.sendMessage(sender, "command_multichat_reload_prepare"); - - // Unregister commands - MultiChat.getInstance().unregisterCommands(ConfigManager.getInstance().getHandler("config.yml").getConfig(), ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig()); - - ConfigManager.getInstance().getHandler("config.yml").startupConfig(); - MultiChat.configversion = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("version"); - - ConfigManager.getInstance().getHandler("joinmessages.yml").startupConfig(); - ConfigManager.getInstance().getHandler("messages.yml").startupConfig(); - ConfigManager.getInstance().getHandler("chatcontrol.yml").startupConfig(); - - ConfigManager.getInstance().getHandler("messages_fr.yml").startupConfig(); - ConfigManager.getInstance().getHandler("joinmessages_fr.yml").startupConfig(); - ConfigManager.getInstance().getHandler("config_fr.yml").startupConfig(); - ConfigManager.getInstance().getHandler("chatcontrol_fr.yml").startupConfig(); - - // Reload, and re-register commands - CommandManager.reload(); - MultiChat.getInstance().registerCommands(ConfigManager.getInstance().getHandler("config.yml").getConfig(), ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig()); - - ChatControl.reload(); - - System.out.println("VERSION LOADED: " + MultiChat.configversion); - - // Set up chat control stuff - if (ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().contains("link_control")) { - ChatControl.controlLinks = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().getBoolean("link_control"); - ChatControl.linkMessage = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().getString("link_removal_message"); - if (ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().contains("link_regex")) { - ChatControl.linkRegex = ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().getString("link_regex"); - } - } - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("privacy_settings")) { - MultiChat.logPMs = ConfigManager.getInstance().getHandler("config.yml").getConfig().getSection("privacy_settings").getBoolean("log_pms"); - MultiChat.logStaffChat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getSection("privacy_settings").getBoolean("log_staffchat"); - MultiChat.logGroupChat = ConfigManager.getInstance().getHandler("config.yml").getConfig().getSection("privacy_settings").getBoolean("log_groupchat"); - } - - // Legacy servers for RGB approximation - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("legacy_servers")) { - MultiChat.legacyServers = ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("legacy_servers"); - } - - // Set default channel - MultiChat.defaultChannel = ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("default_channel"); - MultiChat.forceChannelOnJoin = ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("force_channel_on_join"); - - Channel.getGlobalChannel().setFormat(ConfigManager.getInstance().getHandler("config.yml").getConfig().getString("globalformat")); - Channel.getGlobalChannel().clearServers(); - - for (String server : ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_global")) { - Channel.getGlobalChannel().addServer(server); - } - - if (ProxyServer.getInstance().getPluginManager().getPlugin("PremiumVanish") != null) { - MultiChat.premiumVanish = true; - - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("premium_vanish")) { - MultiChat.hideVanishedStaffInMsg = ConfigManager.getInstance().getHandler("config.yml").getConfig().getSection("premium_vanish").getBoolean("prevent_message"); - MultiChat.hideVanishedStaffInStaffList = ConfigManager.getInstance().getHandler("config.yml").getConfig().getSection("premium_vanish").getBoolean("prevent_staff_list"); - MultiChat.hideVanishedStaffInJoin = ConfigManager.getInstance().getHandler("config.yml").getConfig().getSection("premium_vanish").getBoolean("silence_join"); - } - - } else { - MultiChat.premiumVanish = false; - } - - MessageManager.sendMessage(sender, "command_multichat_reload_completed"); - } - } - - if (args.length == 2) { - - if (args[0].toLowerCase().equals("help")) { - - if (args[1].toLowerCase().equals("1")) { - displayHelp(sender,1); - } else if (args[1].toLowerCase().equals("2")) { - displayHelp(sender,2); - } else { - displayHelp(sender,3); - } - - } - } - } - } + public MultiChatCommand() { + super("multichat", "multichat.admin", ProxyConfigs.ALIASES.getAliases("multichat")); + } + + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&2Multi&aChat &bVersion " + MultiChat.LATEST_VERSION)).create()); + sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&bBy Revilo410")).create()); + sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&bOriginally created for &3Oasis-MC.US")).create()); + sender.sendMessage(new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', "&bUse &3/multichat help &bfor all commands")).create()); + return; + } + + String subCommand = args[0].toLowerCase(); + String subArgument = args.length > 1 ? args[1].toLowerCase() : ""; + + switch (subCommand) { + case "help": { + int page = 1; + try { + page = Integer.parseInt(subArgument); + } catch (NumberFormatException ignored) { + } + + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichat_help_" + Math.max(1, Math.min(page, 3))); + break; + } + case "debug": { + DebugManager.toggle(); + DebugManager.log("Debug mode toggled"); + break; + } + case "save": { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichat_save_prepare"); + MultiChatProxy.getInstance().getFileStoreManager().save(); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichat_save_completed"); + break; + } + case "reload": { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichat_reload_prepare"); + + // TODO: [2.0] This REALLY needs to change + MultiChat multiChat = (MultiChat) MultiChatProxy.getInstance().getPlugin(); + + multiChat.unregisterCommands(); + + ProxyConfigs.ALL.forEach(AbstractProxyConfig::reloadConfig); + ProxyConfigs.RAW_CONFIGS.forEach(AbstractProxyConfig::reloadConfig); + + // Reload, and re-register commands + CommandManager.reload(); + multiChat.registerCommands(); + + ChatControl.reload(); + + multiChat.getLogger().info("VERSION LOADED: " + ProxyConfigs.CONFIG.getVersion()); + + // Set default channel + String defaultChannel = ProxyConfigs.CONFIG.getDefaultChannel(); + boolean forceChannelOnJoin = ProxyConfigs.CONFIG.isForceChannelOnJoin(); + + // New context manager and channels + GlobalContext globalContext = new GlobalContext(defaultChannel, forceChannelOnJoin, true); + MultiChatProxy.getInstance().getContextManager().setGlobalContext(globalContext); + + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + channelManager.setGlobalChannel( + new GlobalStaticProxyChannel("Global Channel", + ProxyConfigs.CONFIG.getGlobalFormat(), + channelManager + ) + ); + channelManager.setLocalChannel( + new LocalChannel("Local Channel", + ProxyConfigs.CONFIG.getGlobalFormat(), + channelManager + ) + ); + + ProxyConfigs.MESSAGES.sendMessage(sender, "command_multichat_reload_completed"); + break; + } + } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatExecuteCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatExecuteCommand.java index 7057521b..97a6d908 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatExecuteCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MultiChatExecuteCommand.java @@ -1,103 +1,83 @@ package xyz.olivermartin.multichat.bungee.commands; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.config.ServerInfo; -import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.BungeeComm; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.MessageManager; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; /** * Execute Command *

Used to execute commands remotely on Spigot servers

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class MultiChatExecuteCommand extends Command { - public MultiChatExecuteCommand() { - super("multichatexecute", "multichat.execute", ConfigManager.getInstance().getHandler("config.yml").getConfig().contains("multichatexecutecommand") ? (String[]) ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("multichatexecutecommand").toArray(new String[0]) : new String[] {"mcexecute", "mce" ,"gexecute","gexe","gcommand"}); - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - MessageManager.sendMessage(sender, "command_execute_usage"); - - } else { - - String server = ".*"; - boolean playerFlag = false; - String player = ".*"; - - // Handle flags - int index = 0; - - while (index < args.length) { - - if (args[index].equalsIgnoreCase("-s")) { - if (index+1 < args.length) { - server = args[index+1]; - } - } else if (args[index].equalsIgnoreCase("-p")) { - if (index+1 < args.length) { - playerFlag = true; - player = args[index+1]; - } - } else { - break; - } - - index = index+2; - - } - - - String message = ""; - for (String arg : args) { - if (index > 0) { - index--; - } else { - message = message + arg + " "; - } - } - - message = message.trim(); - - try { - - for (ServerInfo s : ProxyServer.getInstance().getServers().values()) { - - if (s.getName().matches(server)) { - - if (playerFlag) { - for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { - if (p.getName().matches(player)) { - BungeeComm.sendPlayerCommandMessage(message, p.getName(), s); - } - } - } else { - BungeeComm.sendCommandMessage(message, s); - } - } - - } - - MessageManager.sendMessage(sender, "command_execute_sent"); - - } catch (PatternSyntaxException e) { - - MessageManager.sendMessage(sender, "command_execute_regex"); - - } - - } - } - + public MultiChatExecuteCommand() { + super("mcexecute", "multichat.execute", ProxyConfigs.ALIASES.getAliases("mcexecute")); + } + + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_execute_usage"); + return; + } + + List arguments = new ArrayList<>(Arrays.asList(args)); + + String server = ".*"; + int serverArgIndex = arguments.indexOf("-s"); + if (serverArgIndex > -1) { + server = arguments.get(serverArgIndex + 1); + arguments.remove("-s"); + arguments.remove(server); + } + + String player = ".*"; + int playerArgIndex = arguments.indexOf("-p"); + boolean playerFlag = playerArgIndex > -1; + if (playerFlag) { + player = arguments.get(playerArgIndex + 1); + arguments.remove("-p"); + arguments.remove(player); + } + + String message = String.join(" ", arguments); + + Pattern serverPattern; + Pattern playerPattern; + + try { + serverPattern = Pattern.compile(server); + playerPattern = Pattern.compile(player); + } catch (PatternSyntaxException ex) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_execute_regex"); + return; + } + + ProxyServer.getInstance().getServers().values().stream() + .filter(serverInfo -> serverPattern.matcher(serverInfo.getName()).matches()) + .forEach(serverInfo -> { + if (!playerFlag) { + ProxyLocalCommunicationManager.sendCommandMessage(message, serverInfo); + return; + } + + serverInfo.getPlayers().stream() + .filter(target -> playerPattern.matcher(target.getName()).matches()) + .forEach(target -> + ProxyLocalCommunicationManager.sendPlayerCommandMessage(message, + target.getName(), + serverInfo + ) + ); + }); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MuteCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MuteCommand.java index 133e9600..f1e0329e 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MuteCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/MuteCommand.java @@ -5,55 +5,41 @@ import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.ChatControl; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.MessageManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; public class MuteCommand extends Command { - public MuteCommand() { - super("multichatmute", "multichat.mute", (String[])ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().getStringList("mutecommand").toArray(new String[0])); - } - - @Override - public void execute(CommandSender sender, String[] args) { - - if (!ConfigManager.getInstance().getHandler("chatcontrol.yml").getConfig().getBoolean("mute")) return; - - if (args.length != 1) { - - MessageManager.sendMessage(sender, "mute_usage"); - - } else { - - String username = args[0]; - - ProxiedPlayer target = ProxyServer.getInstance().getPlayer(username); - - if (target != null) { - - if (target.hasPermission("multichat.mute.bypass")) { - MessageManager.sendMessage(sender, "mute_bypass"); - return; - } - - if (!ChatControl.isMutedAnywhere(target.getUniqueId())) { - ChatControl.mute(target.getUniqueId()); - MessageManager.sendMessage(sender, "mute_muted_staff"); - MessageManager.sendMessage(target, "mute_muted"); - } else { - ChatControl.unmute(target.getUniqueId()); - MessageManager.sendMessage(sender, "mute_unmuted_staff"); - MessageManager.sendMessage(target, "mute_unmuted"); - } - - } else { - - MessageManager.sendMessage(sender, "mute_player_not_found"); - - } - - } - - } + public MuteCommand() { + super("mcmute", "multichat.mute", ProxyConfigs.ALIASES.getAliases("mcmute")); + } + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length < 1) { + ProxyConfigs.MESSAGES.sendMessage(sender, "mute_usage"); + return; + } + + ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]); + + if (target == null) { + ProxyConfigs.MESSAGES.sendMessage(sender, "mute_player_not_found"); + return; + } + + if (target.hasPermission("multichat.mute.bypass")) { + ProxyConfigs.MESSAGES.sendMessage(sender, "mute_bypass"); + return; + } + + if (!ChatControl.isMutedAnywhere(target.getUniqueId())) { + ChatControl.mute(target.getUniqueId()); + ProxyConfigs.MESSAGES.sendMessage(sender, "mute_muted_staff"); + ProxyConfigs.MESSAGES.sendMessage(target, "mute_muted"); + } else { + ChatControl.unmute(target.getUniqueId()); + ProxyConfigs.MESSAGES.sendMessage(sender, "mute_unmuted_staff"); + ProxyConfigs.MESSAGES.sendMessage(target, "mute_unmuted"); + } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ReplyCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ReplyCommand.java index 96f09581..042d461c 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ReplyCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/ReplyCommand.java @@ -8,132 +8,87 @@ import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.ChatControl; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.bungee.PrivateMessageManager; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; /** * Reply Command *

Used to quickly reply to your last private message

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class ReplyCommand extends Command { - public ReplyCommand() { - super("r", "multichat.chat.msg", (String[])ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("rcommand").toArray(new String[0])); - } - - public void execute(CommandSender sender, String[] args) { - - if (args.length < 1) { - - MessageManager.sendMessage(sender, "command_reply_usage"); - MessageManager.sendMessage(sender, "command_reply_desc"); - - } else if ((sender instanceof ProxiedPlayer)) { - - String message = MultiChatUtil.getMessageFromArgs(args); - - Optional crm; - - if (ChatControl.isMuted(((ProxiedPlayer)sender).getUniqueId(), "private_messages")) { - MessageManager.sendMessage(sender, "mute_cannot_send_message"); - return; - } - - if (ChatControl.handleSpam(((ProxiedPlayer)sender), message, "private_messages")) { - return; - } - - crm = ChatControl.applyChatRules(message, "private_messages", sender.getName()); - - if (crm.isPresent()) { - message = crm.get(); - } else { - return; - } - - if (MultiChat.lastmsg.containsKey(((ProxiedPlayer)sender).getUniqueId())) { - - if (ProxyServer.getInstance().getPlayer((UUID)MultiChat.lastmsg.get(((ProxiedPlayer)sender).getUniqueId())) != null) { - - ProxiedPlayer target = ProxyServer.getInstance().getPlayer((UUID)MultiChat.lastmsg.get(((ProxiedPlayer)sender).getUniqueId())); - - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(((ProxiedPlayer)sender).getServer().getInfo().getName())) { - - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(target.getServer().getInfo().getName())) { - - if (ChatControl.ignores(((ProxiedPlayer)sender).getUniqueId(), target.getUniqueId(), "private_messages")) { - ChatControl.sendIgnoreNotifications(target, sender, "private_messages"); - return; - } - - PrivateMessageManager.getInstance().sendMessage(message, (ProxiedPlayer)sender, target); - - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_target"); - } - - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_sender"); - } - - } else if ( MultiChat.lastmsg.get( ((ProxiedPlayer)sender ).getUniqueId()).equals(new UUID(0L, 0L)) ) { - - // Console target stuff - - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(((ProxiedPlayer)sender).getServer().getInfo().getName())) { - - PrivateMessageManager.getInstance().sendMessageConsoleTarget(message, (ProxiedPlayer)sender); - - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_sender"); - } - - // End console target stuff - - } else { - MessageManager.sendMessage(sender, "command_reply_no_one_to_reply_to"); - } - - } else { - MessageManager.sendMessage(sender, "command_reply_no_one_to_reply_to"); - } - - } else { - - // New console reply - - String message = MultiChatUtil.getMessageFromArgs(args); - - if (MultiChat.lastmsg.containsKey(new UUID(0L,0L))) { - - if (ProxyServer.getInstance().getPlayer((UUID)MultiChat.lastmsg.get((new UUID(0L,0L)))) != null) { - - ProxiedPlayer target = ProxyServer.getInstance().getPlayer((UUID)MultiChat.lastmsg.get((new UUID(0L,0L)))); - - if (!ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("no_pm").contains(target.getServer().getInfo().getName())) { - - PrivateMessageManager.getInstance().sendMessageConsoleSender(message, target); - - } else { - MessageManager.sendMessage(sender, "command_msg_disabled_target"); - } - - } else { - MessageManager.sendMessage(sender, "command_reply_no_one_to_reply_to"); - } - - } else { - MessageManager.sendMessage(sender, "command_reply_no_one_to_reply_to"); - } - - // End new console stuff - - } - } + public ReplyCommand() { + super("mcr", "multichat.chat.msg", ProxyConfigs.ALIASES.getAliases("mcr")); + } + + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_reply_usage"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_reply_desc"); + return; + } + + UUID consoleUID = new UUID(0L, 0L); + UUID senderUID = sender instanceof ProxiedPlayer ? ((ProxiedPlayer) sender).getUniqueId() : consoleUID; + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + + if (!proxyDataStore.getLastMsg().containsKey(senderUID)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_reply_no_one_to_reply_to"); + return; + } + + UUID targetUID = proxyDataStore.getLastMsg().get(senderUID); + String message = String.join(" ", args); + + if (targetUID.equals(consoleUID) && sender instanceof ProxiedPlayer) { + PrivateMessageManager.getInstance().sendMessageConsoleTarget(message, (ProxiedPlayer) sender); + return; + } + + ProxiedPlayer target = ProxyServer.getInstance().getPlayer(targetUID); + if (target == null) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_reply_no_one_to_reply_to"); + return; + } + + if (ProxyConfigs.CONFIG.isNoPmServer(target.getServer().getInfo().getName())) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_disabled_target"); + return; + } + + if (!(sender instanceof ProxiedPlayer)) { + PrivateMessageManager.getInstance().sendMessageConsoleSender(message, target); + return; + } + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + + if (ProxyConfigs.CONFIG.isNoPmServer(proxiedPlayer.getServer().getInfo().getName())) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_msg_disabled_sender"); + return; + } + + if (ChatControl.isMuted(proxiedPlayer.getUniqueId(), MessageType.PRIVATE_MESSAGES)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "mute_cannot_send_message"); + return; + } + + if (ChatControl.ignores(proxiedPlayer.getUniqueId(), target.getUniqueId(), MessageType.PRIVATE_MESSAGES)) { + ChatControl.sendIgnoreNotifications(target, sender, "private_messages"); + return; + } + + if (ChatControl.handleSpam(proxiedPlayer, message, MessageType.PRIVATE_MESSAGES)) + return; + + Optional crm = ChatControl.applyChatRules(proxiedPlayer, message, MessageType.PRIVATE_MESSAGES); + if (!crm.isPresent()) + return; + + PrivateMessageManager.getInstance().sendMessage(crm.get(), proxiedPlayer, target); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/SocialSpyCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/SocialSpyCommand.java index 0c8e4a55..fc5a6290 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/SocialSpyCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/SocialSpyCommand.java @@ -3,44 +3,46 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChat; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.UUID; /** * SocialSpy Command *

Allows staff members to view private messages sent by players

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class SocialSpyCommand extends Command { - public SocialSpyCommand() { - super("socialspy", "multichat.staff.spy", (String[])ConfigManager.getInstance().getHandler("config.yml").getConfig().getStringList("socialspycommand").toArray(new String[0])); - } - - public void execute(CommandSender sender, String[] args) { - - if ((sender instanceof ProxiedPlayer)) { - - if (args.length < 1) { - - if (MultiChat.socialspy.contains(((ProxiedPlayer)sender).getUniqueId())) { - MultiChat.socialspy.remove(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendMessage(sender, "command_socialspy_disabled"); - } else { - MultiChat.socialspy.add(((ProxiedPlayer)sender).getUniqueId()); - MessageManager.sendMessage(sender, "command_socialspy_enabled"); - } - - } else { - MessageManager.sendMessage(sender, "command_socialspy_usage"); - MessageManager.sendMessage(sender, "command_socialspy_desc"); - } - - } else { - MessageManager.sendMessage(sender, "command_socialspy_only_players"); - } - } + public SocialSpyCommand() { + super("mcsocialspy", "multichat.staff.spy", ProxyConfigs.ALIASES.getAliases("mcsocialspy")); + } + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof ProxiedPlayer)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_socialspy_only_players"); + return; + } + + // TODO: We don't really need this check + if (args.length != 0) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_socialspy_usage"); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_socialspy_desc"); + return; + } + + UUID playerUID = ((ProxiedPlayer) sender).getUniqueId(); + ProxyDataStore proxyDataStore = MultiChatProxy.getInstance().getDataStore(); + + if (proxyDataStore.getSocialSpy().contains(playerUID)) { + proxyDataStore.getSocialSpy().remove(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_socialspy_disabled"); + } else { + proxyDataStore.getSocialSpy().add(playerUID); + ProxyConfigs.MESSAGES.sendMessage(sender, "command_socialspy_enabled"); + } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/StaffListCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/StaffListCommand.java index 96e2bb7a..38b8eb3f 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/StaffListCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/StaffListCommand.java @@ -1,102 +1,62 @@ package xyz.olivermartin.multichat.bungee.commands; -import java.util.Iterator; - import de.myzelyam.api.vanish.BungeeVanishAPI; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import xyz.olivermartin.multichat.bungee.BungeeComm; -import xyz.olivermartin.multichat.bungee.ConfigManager; -import xyz.olivermartin.multichat.bungee.DebugManager; -import xyz.olivermartin.multichat.bungee.MessageManager; import xyz.olivermartin.multichat.bungee.MultiChat; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.concurrent.atomic.AtomicBoolean; /** * Staff List Command *

Allows the user to view a list of all online staff, sorted by their server

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class StaffListCommand extends Command { - private static String[] aliases = new String[] {}; - - public StaffListCommand() { - super("staff", "multichat.staff.list", aliases); - } - - public void execute(CommandSender sender, String[] args) { - - String server; - boolean staff = false; - boolean onServer = false; - - MessageManager.sendMessage(sender, "command_stafflist_list"); - - DebugManager.log("[StaffList] Player: " + sender.getName() + " is the command sender!"); - - for (Iterator localIterator1 = ProxyServer.getInstance().getServers().keySet().iterator(); localIterator1.hasNext();) { - - server = (String)localIterator1.next(); - - DebugManager.log("[StaffList] First Server: " + server); - - if (!ProxyServer.getInstance().getServerInfo(server).getPlayers().isEmpty()) { - - onServer = false; - - for (ProxiedPlayer onlineplayer2 : ProxyServer.getInstance().getPlayers()) { - - if ((onlineplayer2.hasPermission("multichat.staff"))) { - - DebugManager.log("[StaffList] Found a staff member: " + onlineplayer2.getName()); - - boolean showInList = true; - - DebugManager.log("[StaffList] Are we hooked to PremiumVanish: " + MultiChat.premiumVanish); - DebugManager.log("[StaffList] Are we hiding vanished players as set in config?: " + MultiChat.hideVanishedStaffInStaffList); - - if (MultiChat.premiumVanish && MultiChat.hideVanishedStaffInStaffList) { - - DebugManager.log("[StaffList] Is staff invisible: " + BungeeVanishAPI.isInvisible(onlineplayer2)); - DebugManager.log("[StaffList] Can player see vanished staff?: " + sender.hasPermission("multichat.staff.list.vanished")); - - if (BungeeVanishAPI.isInvisible(onlineplayer2) && !sender.hasPermission("multichat.staff.list.vanished")) { - DebugManager.log("[StaffList] This staff member will be hidden from list!"); - showInList = false; - } - } - - if (showInList) { - - if (onlineplayer2.getServer().getInfo().getName().equals(server)) { + public StaffListCommand() { + super("mcstaff", "multichat.staff.list", ProxyConfigs.ALIASES.getAliases("mcstaff")); + } - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { - BungeeComm.sendMessage(onlineplayer2.getName(), onlineplayer2.getServer().getInfo()); - } + public void execute(CommandSender sender, String[] args) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_stafflist_list"); - staff = true; + AtomicBoolean anyStaff = new AtomicBoolean(false); - if (!onServer) { - MessageManager.sendSpecialMessage(sender, "command_stafflist_list_server", server); - onServer = true; - } + ProxyServer.getInstance().getServers().values().stream() + .filter(serverInfo -> serverInfo.getPlayers().size() > 0) + .forEach(serverInfo -> { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_stafflist_list_server", serverInfo.getName()); - MessageManager.sendSpecialMessage(sender, "command_stafflist_list_item", onlineplayer2.getDisplayName()); + serverInfo.getPlayers().stream() + .filter(target -> target.hasPermission("multichat.staff") + && !(MultiChat.premiumVanish + && ProxyConfigs.CONFIG.isPvPreventStaffList() + && BungeeVanishAPI.isInvisible(target) + && !sender.hasPermission("multichat.staff.list.vanished")) + ) + .forEach(target -> { + if (!anyStaff.get()) + anyStaff.set(true); - } + if (ProxyConfigs.CONFIG.isFetchSpigotDisplayNames()) + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(target.getName(), serverInfo); - } - } - } + ProxyConfigs.MESSAGES.sendMessage(sender, "command_stafflist_list_item", target.getDisplayName()); + }); - } - } + // TODO: We should decide when or how "no staff is online" is shown + // If we want to keep it like this, we should replace the stream with a normal for + if (!anyStaff.get()) + ProxyConfigs.MESSAGES.sendMessage(sender, "command_stafflist_no_staff"); + else + anyStaff.set(false); + }); - if (!staff) MessageManager.sendMessage(sender, "command_stafflist_no_staff"); - } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/UseCastCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/UseCastCommand.java index 843dda6d..f0b2096b 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/UseCastCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/commands/UseCastCommand.java @@ -5,49 +5,39 @@ import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.plugin.Command; import xyz.olivermartin.multichat.bungee.CastControl; -import xyz.olivermartin.multichat.bungee.Channel; -import xyz.olivermartin.multichat.bungee.MessageManager; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.Arrays; /** * Use Cast Command *

A command designed to allow you to use a cast from the console

- * - * @author Oliver Martin (Revilo410) * + * @author Oliver Martin (Revilo410) */ public class UseCastCommand extends Command { - private static String[] aliases = new String[] {}; - - public UseCastCommand() { - super("usecast", "multichat.cast.admin", aliases); - } - - public void displayUsage(CommandSender sender) { - MessageManager.sendMessage(sender, "command_usecast_usage"); - sender.sendMessage(new ComponentBuilder("/usecast ").color(ChatColor.AQUA).create()); - } - - @Override - public void execute(CommandSender sender, String[] args) { - - if (args.length < 2) { - displayUsage(sender); - return; - } - - if (CastControl.existsCast(args[0])) { - - String message = MultiChatUtil.getMessageFromArgs(args, 1); - - CastControl.sendCast(args[0], message, Channel.getGlobalChannel(), sender); - - } else { - - MessageManager.sendSpecialMessage(sender, "command_usecast_does_not_exist", args[0].toUpperCase()); - return; - - } - } + public UseCastCommand() { + super("mcusecast", "multichat.cast.admin", ProxyConfigs.ALIASES.getAliases("mcusecast")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length < 2) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_usecast_usage"); + // TODO: This should probably be in the configurable usecast message + sender.sendMessage(new ComponentBuilder("/usecast ").color(ChatColor.AQUA).create()); + return; + } + + String castName = args[0]; + if (!CastControl.existsCast(castName)) { + ProxyConfigs.MESSAGES.sendMessage(sender, "command_usecast_does_not_exist", castName); + return; + } + + String message = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); + CastControl.sendCast(castName, message, MultiChatProxy.getInstance().getChannelManager().getGlobalChannel(), sender); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/common/MessageType.java b/multichat/src/main/java/xyz/olivermartin/multichat/common/MessageType.java new file mode 100644 index 00000000..8d62a8be --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/common/MessageType.java @@ -0,0 +1,19 @@ +package xyz.olivermartin.multichat.common; + +public enum MessageType { + LOCAL_CHAT, + GLOBAL_CHAT, + PRIVATE_MESSAGES, + GROUP_CHATS, + STAFF_CHATS, + DISPLAY_COMMAND, + ANNOUNCEMENTS, + BULLETINS, + CASTS, + HELPME; + + @Override + public String toString() { + return name().toLowerCase(); + } +} \ No newline at end of file diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/common/MultiChatUtil.java b/multichat/src/main/java/xyz/olivermartin/multichat/common/MultiChatUtil.java new file mode 100644 index 00000000..ab0b8384 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/common/MultiChatUtil.java @@ -0,0 +1,389 @@ +package xyz.olivermartin.multichat.common; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MultiChatUtil { + + private static final Pattern SHORT_UNTRANSLATED_RGB = Pattern.compile("(?i)\\&(x|#)([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])"); + private static final Pattern LONG_UNTRANSLATED_RGB = Pattern.compile("(?i)\\&x\\&([0-9A-F])\\&([0-9A-F])\\&([0-9A-F])\\&([0-9A-F])\\&([0-9A-F])\\&([0-9A-F])"); + private static final Pattern TRANSLATED_RGB = Pattern.compile("(?i)(§r)?§x§([0-9A-F])§([0-9A-F])§([0-9A-F])§([0-9A-F])§([0-9A-F])§([0-9A-F])"); + private static final Pattern ALL_FORMATTING_CHARS = Pattern.compile("(?i)([0-9A-FK-ORX])"); + private static final Pattern JSON_RGB = Pattern.compile("(?i)(\"color\":\")#([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])(\")"); + private static final Pattern APPROX_RGB_FORMAT = Pattern.compile("(?i)\\§(#)([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])"); + + + /** + *

Takes a raw string and translates any color codes using the & symbol

+ *

Any RGB codes in the format &#abcdef, &xabcdef or &x&a&b&c&d&e&f will also be translated

+ * @param rawMessage The raw message to translate + * @return the translated message + */ + public static String translateColorCodes(String rawMessage) { + return translateColorCodes(rawMessage, TranslateMode.ALL); + } + + /** + *

Takes a raw string and translates formatting codes according to the TranslateMode

+ * @param rawMessage The raw message to translate + * @param modes The TranslateModes to process + * @return the translated message + */ + public static String translateColorCodes(String rawMessage, TranslateMode... modes) { + + String translatedMessage = rawMessage; + + boolean rgb = Arrays.stream(modes).anyMatch(value -> TranslateMode.isRGB(value)); + + // If we are translating RGB codes, reformat these to the correct format + if (rgb) translatedMessage = MultiChatUtil.preProcessColorCodes(translatedMessage); + + // Process each of the translations + for (TranslateMode mode : modes) { + translatedMessage = mode.translate(translatedMessage); + } + + return translatedMessage; + + } + + /** + *

Takes a raw string and strips any color codes using the & symbol

+ *

If stripTranslatedCodes is true then it will also strip any codes using the § symbol

+ * @param rawMessage The raw message to strip + * @param stripTranslatedCodes If pre-translated codes (§) should also be stripped + * @return the stripped message + */ + public static String stripColorCodes(String rawMessage, boolean stripTranslatedCodes) { + return stripColorCodes(rawMessage, stripTranslatedCodes, TranslateMode.ALL); + } + + /** + *

Takes a raw string and strips formatting codes (&) according to the TranslateMode

+ *

If stripTranslatedCodes is true then it will also strip any codes using the § symbol

+ * @param rawMessage The raw message to strip + * @param stripTranslatedCodes If pre-translated codes (§) should also be stripped + * @param modes The TranslateModes to apply + * @return the stripped message + */ + public static String stripColorCodes(String rawMessage, boolean stripTranslatedCodes, TranslateMode... modes) { + + String strippedMessage = rawMessage; + + boolean rgb = Arrays.stream(modes).anyMatch(value -> TranslateMode.isRGB(value)); + + // If we are stripping RGB codes, reformat these to the correct format + if (rgb) strippedMessage = MultiChatUtil.preProcessColorCodes(strippedMessage); + + // Process each of the strips + for (TranslateMode mode : modes) { + if (stripTranslatedCodes) { + strippedMessage = mode.stripAll(strippedMessage); + } else { + strippedMessage = mode.stripOrigin(strippedMessage); + } + } + + return strippedMessage; + + } + + /** + *

Takes a raw string and checks if it contains any codes using the & symbol

+ *

Any RGB codes in the format &#abcdef, &xabcdef or &x&a&b&c&d&e&f will also be checked

+ * @param rawMessage The raw message to check + * @param checkTranslatedCodes If pre-translated codes (§) should also be checked + * @return true if it contains format codes + */ + public static boolean containsColorCodes(String rawMessage, boolean checkTranslatedCodes) { + return containsColorCodes(rawMessage, checkTranslatedCodes, TranslateMode.ALL); + } + + /** + *

Takes a raw string and checks if it contains any formatting codes (&) according to the TranslateMode

+ * @param rawMessage The raw message to check + * @param checkTranslatedCodes If pre-translated codes (§) should also be checked + * @param modes The TranslateModes to process + * @return true if it contains format codes + */ + public static boolean containsColorCodes(String rawMessage, boolean checkTranslatedCodes, TranslateMode... modes) { + + boolean rgb = Arrays.stream(modes).anyMatch(value -> TranslateMode.isRGB(value)); + + // If we are checking RGB codes, reformat these to the correct format + if (rgb) rawMessage = MultiChatUtil.preProcessColorCodes(rawMessage); + + // Process each of the checks + for (TranslateMode mode : modes) { + if (checkTranslatedCodes) { + if (mode.containsAny(rawMessage)) return true; + } else { + if (mode.containsOrigin(rawMessage)) return true; + } + } + + return false; + + } + + /** + * Reformat the RGB codes into Spigot Native version + * + * @param message + * @return message reformatted + */ + public static String preProcessColorCodes(String message) { + + Matcher longRgb = LONG_UNTRANSLATED_RGB.matcher(message); + message = longRgb.replaceAll("&r&x&$1&$2&$3&$4&$5&$6"); + + Matcher shortRgb = SHORT_UNTRANSLATED_RGB.matcher(message); + message = shortRgb.replaceAll("&r&x&$2&$3&$4&$5&$6&$7"); + + String transformedMessage = ""; + char lastChar = 'a'; + + // Transform codes to lowercase for better compatibility with Essentials etc. + for (char c : message.toCharArray()) { + + // If this could be a color code + if (lastChar == '&') { + + // If it is a color code, set to be lowercase + Matcher allFormattingChars = ALL_FORMATTING_CHARS.matcher(String.valueOf(c)); + if (allFormattingChars.matches()) { + c = Character.toLowerCase(c); + } + + } + + // Append to message + transformedMessage = transformedMessage + c; + lastChar = c; + + } + + return transformedMessage; + + } + + public static String approximateRGBColorCodes(String message) { + + Matcher rgbMatcher = TRANSLATED_RGB.matcher(message); + message = rgbMatcher.replaceAll("§#$2$3$4$5$6$7"); + + message = replaceRGBShortCodesWithApproximations(message, false); + + return approximateJsonRGBColorCodes(message); + + } + + private static String approximateJsonRGBColorCodes(String message) { + + Matcher jsonRgbMatcher = JSON_RGB.matcher(message); + message = jsonRgbMatcher.replaceAll("$1§#$2$3$4$5$6$7$8"); + return replaceRGBShortCodesWithApproximations(message, true); + + } + + private static String replaceRGBShortCodesWithApproximations(String message, boolean useNameInsteadOfCode) { + + List allMatches = new ArrayList(); + Matcher m = APPROX_RGB_FORMAT.matcher(message); + + while (m.find()) { + allMatches.add(m.group()); + } + + for (String match : allMatches) { + + String hexonly; + if (match.contains("#")) { + hexonly = match.split("#")[1]; + } else if (match.contains("x")) { + hexonly = match.split("x")[1]; + } else { + hexonly = match.split("X")[1]; + } + String minecraftCode = hexToMinecraft(hexonly); + + if (useNameInsteadOfCode) { + message = message.replace(match,getMinecraftCodeName(minecraftCode)); + } else { + message = message.replace(match,"§"+minecraftCode); + } + + } + + return message; + + } + + public static String getMinecraftCodeName(String code) { + + code = code.toLowerCase(); + + switch (code) { + case "0": + return "black"; + case "1": + return "dark_blue"; + case "2": + return "dark_green"; + case "3": + return "dark_aqua"; + case "4": + return "dark_red"; + case "5": + return "dark_purple"; + case "6": + return "gold"; + case "7": + return "gray"; + case "8": + return "dark_gray"; + case "9": + return "blue"; + case "a": + return "green"; + case "b": + return "aqua"; + case "c": + return "red"; + case "d": + return "light_purple"; + case "e": + return "yellow"; + case "f": + return "white"; + default: + return "white"; + } + + } + + public static String hexToMinecraft(String hex) { + + String rcode = hex.substring(0,2); + String gcode = hex.substring(2,4); + String bcode = hex.substring(4,6); + + int rint = Integer.parseInt(rcode,16); + int gint = Integer.parseInt(gcode,16); + int bint = Integer.parseInt(bcode,16); + + String[] cga = {"000000","0000aa","00aa00","00aaaa","aa0000","aa00aa","ffaa00","aaaaaa","555555","5555ff","55ff55","55ffff","ff5555","ff55ff","ffff55","ffffff"}; + + int diff = 999999999; + int best = -1; + + for (int i = 0; i < 16; i++) { + + String current = cga[i]; + + String rcode2 = current.substring(0,2); + String gcode2 = current.substring(2,4); + String bcode2 = current.substring(4,6); + + int rint2 = Integer.parseInt(rcode2,16); + int gint2 = Integer.parseInt(gcode2,16); + int bint2 = Integer.parseInt(bcode2,16); + + int val = Math.abs(rint-rint2) + Math.abs(gint-gint2) + Math.abs(bint-bint2); + + if (val < diff) { + best = i; + diff = val; + } + + } + + return Integer.toHexString(best); + + } + + /** + * Concatenate the arguments together to get the message as a string + * + * @param args The arguments of the command + * @param start The (zero-indexed) starting index of the message (inclusive) + * @param end The (zero-indexed) finishing index of the message (inclusive) + * @return The concatenated message + */ + public static String getMessageFromArgs(String[] args, int start, int end) { + + int counter = 0; + String message = ""; + for (String arg : args) { + if (counter >= start && counter <= end) { + if (counter != end) { + message = message + arg + " "; + } else { + message = message + arg; + } + } + counter++; + } + + return message; + + } + + /** + * Concatenate the arguments together to get the message as a string + * + * @param args The arguments of the command + * @param start The (zero-indexed) starting index of the message (inclusive) + * @return The concatenated message + */ + public static String getMessageFromArgs(String[] args, int start) { + + return getMessageFromArgs(args, start, args.length - 1); + + } + + /** + * Concatenate the arguments together to get the message as a string + * + * @param args The arguments of the command + * @return The concatenated message + */ + public static String getMessageFromArgs(String[] args) { + + return getMessageFromArgs(args, 0, args.length - 1); + + } + + public static String getStringFromCollection(Collection collection) { + + String result = ""; + + for (String item : collection) { + if (result.equals("")) { + result = result + item; + } else { + result = result + " " + item; + } + } + + return result; + + } + + public static String visualiseColorCodes(String message) { + + Matcher originMatcher = TranslateMode.ALL.getOriginPattern().matcher(message); + Matcher translatedMatcher = TranslateMode.ALL.getTranslatedPattern().matcher(message); + + message = originMatcher.replaceAll("{O$1}"); + message = translatedMatcher.replaceAll("{T$1}"); + + return message; + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/common/RegexUtil.java b/multichat/src/main/java/xyz/olivermartin/multichat/common/RegexUtil.java new file mode 100644 index 00000000..570394a1 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/common/RegexUtil.java @@ -0,0 +1,22 @@ +package xyz.olivermartin.multichat.common; + +import java.util.regex.Pattern; + +public enum RegexUtil { + LEGACY_COLOR("\b(?i)[a-f0-9]\b"), + LEGACY_COLORS("(?i)[a-f0-9]"), + FORMAT("\b(?i)[k-or]\b"), + FORMATS("(?i)[k-or]"), + LEGACY_COLOR_FORMAT("\b(?i)[a-fk-or0-9]\b"), + LEGACY_COLORS_FORMATS("(?i)[a-fk-or0-9]"); + + private final Pattern pattern; + + RegexUtil(String pattern) { + this.pattern = Pattern.compile(pattern); + } + + public boolean matches(String toMatch) { + return pattern.matcher(toMatch).matches(); + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/common/TranslateMode.java b/multichat/src/main/java/xyz/olivermartin/multichat/common/TranslateMode.java new file mode 100644 index 00000000..3571bced --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/common/TranslateMode.java @@ -0,0 +1,83 @@ +package xyz.olivermartin.multichat.common; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public enum TranslateMode { + + COLOR_SIMPLE ("(?i)%1$s([a-f,0-9])"), + COLOR_ALL ("(?i)%1$s([a-f,0-9,r,x])"), + FORMAT_UNDERLINE ("(?i)%1$s([n])"), + FORMAT_ITALIC ("(?i)%1$s([o])"), + FORMAT_BOLD ("(?i)%1$s([l])"), + FORMAT_STRIKE ("(?i)%1$s([m])"), + FORMAT_OBFUSCATED ("(?i)%1$s([k])"), + FORMAT_RESET ("(?i)%1$s([r])"), + FORMAT_ALL ("(?i)%1$s([k-o,r])"), + SIMPLE ("(?i)%1$s([a-f,0-9,k-o,r])"), + ALL ("(?i)%1$s([a-f,0-9,k-o,r,x])"), + X ("(?i)%1$s([x])"); + + private static final String ORIGIN_CHAR = "&"; + private static final String TRANSLATED_CHAR = "§"; + + private Pattern originPattern; + private Pattern translatedPattern; + + private TranslateMode(String regex) { + this.originPattern = Pattern.compile(String.format(regex, ORIGIN_CHAR)); + this.translatedPattern = Pattern.compile(String.format(regex, TRANSLATED_CHAR)); + } + + public static boolean isRGB(TranslateMode mode) { + return mode.equals(ALL) || mode.equals(X) || mode.equals(COLOR_ALL); + } + + public Pattern getOriginPattern() { + return this.originPattern; + } + + public Pattern getTranslatedPattern() { + return this.translatedPattern; + } + + public String translate(String rawMessage) { + Matcher matcher = getOriginPattern().matcher(rawMessage); + return matcher.replaceAll(TRANSLATED_CHAR + "$1"); + } + + public String revert(String rawMessage) { + Matcher matcher = getTranslatedPattern().matcher(rawMessage); + return matcher.replaceAll(ORIGIN_CHAR + "$1"); + } + + public boolean containsAny(String rawMessage) { + return !rawMessage.equals(stripAll(rawMessage)); + } + + public boolean containsOrigin(String rawMessage) { + return !rawMessage.equals(stripOrigin(rawMessage)); + } + + public boolean containsTranslated(String rawMessage) { + return !rawMessage.equals(stripTranslated(rawMessage)); + } + + public String stripAll(String rawMessage) { + return stripTranslated(stripOrigin(rawMessage)); + } + + public String stripTranslated(String rawMessage) { + return strip(rawMessage, getTranslatedPattern()); + } + + public String stripOrigin(String rawMessage) { + return strip(rawMessage, getOriginPattern()); + } + + private String strip(String rawMessage, Pattern pattern) { + Matcher matcher = pattern.matcher(rawMessage); + return matcher.replaceAll(""); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/common/communication/CommChannels.java b/multichat/src/main/java/xyz/olivermartin/multichat/common/communication/CommChannels.java new file mode 100644 index 00000000..f337d013 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/common/communication/CommChannels.java @@ -0,0 +1,174 @@ +package xyz.olivermartin.multichat.common.communication; + +public interface CommChannels { + + /* + * The prefix used for multichat communication channels + */ + String PREFIX = "multichat:"; + + /** + * Gets the channel id used for: + * PLAYER META + * + *

Description: + *

+ * This channel communicates the following from PROXY -> LOCAL: + *

    + *
  • Requests for player meta to be updated on proxy
  • + *
+ *

+ *

+ * This channel communicates the following from LOCAL -> PROXY: + *

    + *
  • Player prefix
  • + *
  • Player suffix
  • + *
  • Player world
  • + *
  • Player display name
  • + *
  • Player nickname
  • + *
+ *

+ *

+ * @return the channel id + */ + String PLAYER_META = PREFIX + "pmeta"; + + /** + * Gets the channel id used for: + * PLAYER CHAT + * + *

Description: + *

+ * This channel communicates the following from PROXY -> LOCAL: + *

    + *
  • Direct chat messages through /local mymessagehere etc.
  • + *
+ *

+ *

+ * This channel communicates the following from LOCAL -> PROXY: + *

    + *
  • Player chat messages for distribution
  • + *
+ *

+ *

+ * @return the channel id + */ + String PLAYER_CHAT = PREFIX + "pchat"; + + /** + * Gets the channel id used for: + * SERVER CHAT + * + *

Description: + *

+ * This channel communicates the following from PROXY -> LOCAL: + *

    + *
  • Cast messages
  • + *
+ *

+ *

+ * This channel communicates the following from LOCAL -> PROXY: + *

    + *
  • Nil.
  • + *
+ *

+ *

+ * @return the channel id + */ + String SERVER_CHAT = PREFIX + "schat"; + + /** + * Gets the channel id used for: + * PLAYER DATA + * + *

Description: + *

+ * This channel communicates the following from PROXY -> LOCAL: + *

    + *
  • Player colour permissions
  • + *
  • Player currently selected channels
  • + *
  • Lists of channel members
  • + *
+ *

+ *

+ * This channel communicates the following from LOCAL -> PROXY: + *

    + *
  • Nil.
  • + *
+ *

+ *

+ * @return the channel id + */ + String PLAYER_DATA = PREFIX + "pdata"; + + /** + * Gets the channel id used for: + * SERVER DATA + * + *

Description: + *

+ * This channel communicates the following from PROXY -> LOCAL: + *

    + *
  • Global chat format
  • + *
  • If this server is a 'global chat server'
  • + *
  • If this server is a legacy server
  • + *
  • If the server should set the display name
  • + *
  • What the display name format is
  • + *
+ *

+ *

+ * This channel communicates the following from LOCAL -> PROXY: + *

    + *
  • Nil.
  • + *
+ *

+ *

+ * @return the channel id + */ + String SERVER_DATA = PREFIX + "sdata"; + + /** + * Gets the channel id used for: + * SERVER ACTIONS + * + *

Description: + *

+ * This channel communicates the following from PROXY -> LOCAL: + *

    + *
  • MCE commands
  • + *
+ *

+ *

+ * This channel communicates the following from LOCAL -> PROXY: + *

    + *
  • PXE commands
  • + *
+ *

+ *

+ * @return the channel id + */ + String SERVER_ACTION = PREFIX + "sact"; + + /** + * Gets the channel id used for: + * PLAYER ACTIONS + * + *

Description: + *

+ * This channel communicates the following from PROXY -> LOCAL: + *

    + *
  • MCE player commands
  • + *
+ *

+ *

+ * This channel communicates the following from LOCAL -> PROXY: + *

    + *
  • PXE player commands
  • + *
+ *

+ *

+ * @return the channel id + */ + String PLAYER_ACTION = PREFIX + "pact"; + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalBungeeCommunicationManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalBungeeCommunicationManager.java index 567698a8..9a0fbbfc 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalBungeeCommunicationManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalBungeeCommunicationManager.java @@ -1,7 +1,9 @@ package xyz.olivermartin.multichat.local.common; +import java.util.Set; import java.util.UUID; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.proxy.common.MultiChatProxyPlatform; /** @@ -12,65 +14,40 @@ */ public abstract class LocalBungeeCommunicationManager extends LocalProxyCommunicationManager { - protected final String nicknameChannel = "multichat:nick"; - protected final String worldChannel = "multichat:world"; - protected final String prefixChannel = "multichat:prefix"; - protected final String suffixChannel = "multichat:suffix"; - protected final String displayNameChannel = "multichat:dn"; - protected final String pxeChannel = "multichat:pxe"; - protected final String ppxeChannel = "multichat:ppxe"; - protected final String chatChannel = "multichat:chat"; - protected LocalBungeeCommunicationManager(MultiChatLocalPlatform localPlatform) { super(localPlatform, MultiChatProxyPlatform.BUNGEE); } protected abstract boolean sendUUIDAndString(String channel, UUID uuid, String value); - + protected abstract boolean sendUUIDAndStringAndString(String channel, UUID uuid, String value1, String value2); - protected abstract boolean sendStringAndString(String channel, String string1, String string2); + protected abstract boolean sendUUIDAndStringAndStringAndString(String channel, UUID uuid, String value1, String value2, String value3); - protected abstract boolean sendString(String channel, String string); + protected abstract boolean sendPlatformChatMessage(String channel, UUID uuid, String chatChannel, String message, String format, Set otherRecipients); - @Override - protected void sendNicknameUpdate(UUID uuid, String nickname) { - sendUUIDAndString(nicknameChannel, uuid, nickname); - } - - @Override - public void sendWorldUpdate(UUID uuid, String world) { - sendUUIDAndString(worldChannel, uuid, world); - } - - @Override - protected void sendPrefixUpdate(UUID uuid, String prefix) { - sendUUIDAndString(prefixChannel, uuid, prefix); - } + protected abstract boolean sendStringAndString(String channel, String string1, String string2); - @Override - protected void sendSuffixUpdate(UUID uuid, String suffix) { - sendUUIDAndString(suffixChannel, uuid, suffix); - } + protected abstract boolean sendString(String channel, String string); @Override - protected void sendDisplayNameUpdate(UUID uuid, String displayName) { - sendUUIDAndString(displayNameChannel, uuid, displayName); + public void sendMetaUpdate(UUID uuid, String metaId, String metaValue) { + sendUUIDAndStringAndString(CommChannels.PLAYER_META, uuid, metaId, metaValue); } @Override public void sendProxyExecuteMessage(String command) { - sendString(pxeChannel, command); + sendString(CommChannels.SERVER_ACTION, command); } @Override public void sendProxyExecutePlayerMessage(String command, String player) { - sendStringAndString(ppxeChannel, command, player); + sendStringAndString(CommChannels.PLAYER_ACTION, command, player); } - + @Override - public void sendChatMessage(UUID uuid, String message, String format) { - sendUUIDAndStringAndString(chatChannel, uuid, message, format); + public void sendPlayerChatMessage(UUID uuid, String channel, String message, String format, Set otherRecipients) { + sendPlatformChatMessage(CommChannels.PLAYER_CHAT, uuid, channel, message, format, otherRecipients); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalChatManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalChatManager.java index 680c9466..41ddc74d 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalChatManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalChatManager.java @@ -5,8 +5,11 @@ import java.util.Map; import java.util.Optional; import java.util.Queue; +import java.util.Set; import java.util.UUID; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.common.TranslateMode; import xyz.olivermartin.multichat.local.common.config.LocalConfig; import xyz.olivermartin.multichat.local.common.config.RegexChannelForcer; import xyz.olivermartin.multichat.local.common.storage.LocalDataStore; @@ -46,7 +49,6 @@ public String getSelectedChatChannel(UUID uuid) { if (playerChannels.containsKey(uuid)) { channel = playerChannels.get(uuid); - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Got selected player channel as " + channel); } else { channel = "global"; MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Player was not in channel map, so using global..."); @@ -58,6 +60,29 @@ public String getSelectedChatChannel(UUID uuid) { } + public void queueRecipients(UUID uuid, Set recipients) { + + Map>> recipientQueues = MultiChatLocal.getInstance().getDataStore().getRecipientQueues(); + + synchronized (recipientQueues) { + + if (recipientQueues.containsKey(uuid)) { + + Queue> q = recipientQueues.get(uuid); + q.add(recipients); + + } else { + + Queue> q = new LinkedList>(); + q.add(recipients); + recipientQueues.put(uuid, q); + + } + + } + + } + public void queueChatChannel(String playerName, String channel) { Map> chatQueues = MultiChatLocal.getInstance().getDataStore().getChatQueues(); @@ -81,6 +106,28 @@ public void queueChatChannel(String playerName, String channel) { } + public Optional> getRecipientsFromRecipientQueue(UUID uuid) { + + LocalDataStore store = MultiChatLocal.getInstance().getDataStore(); + Map>> recipientQueues = store.getRecipientQueues(); + Set recipients; + + synchronized (recipientQueues) { + + if (!recipientQueues.containsKey(uuid)) return Optional.empty(); + + recipients = recipientQueues.get(uuid).poll(); + + if (recipientQueues.get(uuid).size() < 1) { + recipientQueues.remove(uuid); + } + + } + + return Optional.of(recipients); + + } + private String getChannelFromChatQueue(MultiChatLocalPlayer player, boolean pollQueue) { LocalDataStore store = MultiChatLocal.getInstance().getDataStore(); @@ -150,7 +197,7 @@ public String getChannelFormat(String channel) { break; - default: + case "global": // Global Chat @@ -168,6 +215,11 @@ public String getChannelFormat(String channel) { break; + default: + + format = MultiChatLocal.getInstance().getDataStore().getChannelFormats().getOrDefault(channel, MultiChatLocal.getInstance().getDataStore().getGlobalChatFormat()); + break; + } return format; @@ -183,13 +235,7 @@ public boolean canChatInSimpleColour(UUID uuid) { if (colourMap.containsKey(uuid)) { - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Player is in the simple colour map!"); - - boolean colour = colourMap.get(uuid); - - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Can they use simple colours? --> " + colour); - - return colour; + return colourMap.get(uuid); } else { @@ -212,13 +258,7 @@ public boolean canChatInRGBColour(UUID uuid) { if (colourMap.containsKey(uuid)) { - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Player is in the rgb colour map!"); - - boolean colour = colourMap.get(uuid); - - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Can they use rgb colours? --> " + colour); - - return colour; + return colourMap.get(uuid); } else { @@ -232,33 +272,22 @@ public boolean canChatInRGBColour(UUID uuid) { } - public String reformatRGB(String message) { - - // Translate RGB codes - message = message.replaceAll("(?i)\\&(x|#)([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])", "&x&$2&$3&$4&$5&$6&$7"); - - String transformedMessage = ""; - char lastChar = 'a'; - - // Transform codes to lowercase for better compatibility with Essentials etc. - for (char c : message.toCharArray()) { + public String translateColorCodes(String message, boolean rgb) { - if (lastChar == '&') { - if (String.valueOf(c).matches("(?i)([0-9A-FX])")) { - c = Character.toLowerCase(c); - } - } + if (rgb) { + message = MultiChatUtil.translateColorCodes(message); + } else { + message = MultiChatUtil.translateColorCodes(message, TranslateMode.SIMPLE); + } - transformedMessage = transformedMessage + c; - lastChar = c; + if (MultiChatLocal.getInstance().getDataStore().isLegacy()) { + message = MultiChatUtil.approximateRGBColorCodes(message); } - return transformedMessage; + return message; } - public abstract String translateColourCodes(String message, boolean rgb); - public abstract String processExternalPlaceholders(MultiChatLocalPlayer player, String message); public String processMultiChatConfigPlaceholders(MultiChatLocalPlayer player, String message) { @@ -269,22 +298,22 @@ public String processMultiChatConfigPlaceholders(MultiChatLocalPlayer player, St for (String key : config.getMultichatPlaceholders().keySet()) { - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] MultiChatPlaceholder Key = " + key); + //MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] MultiChatPlaceholder Key = " + key); String value = config.getMultichatPlaceholders().get(key); - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] MultiChatPlaceholder Value = " + value); + //MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] MultiChatPlaceholder Value = " + value); value = MultiChatLocal.getInstance().getPlaceholderManager().processMultiChatPlaceholders(player.getUniqueId(), value); - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Processed Value to get: " + value); + //MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Processed Value to get: " + value); // If we are hooked with PAPI then use their placeholders! value = processExternalPlaceholders(player, value); - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Processed with external placeholders to get: " + value); + //MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Processed with external placeholders to get: " + value); - value = translateColourCodes(value, true); - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Translated colour codes to get: " + value); + value = translateColorCodes(value, true); + //MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] Translated colour codes to get: " + value); - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] MESSAGE = : " + message); + //MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalChatManager] MESSAGE = : " + message); if (message.contains(key)) { message = message.replace(key, value); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalConsoleLogger.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalConsoleLogger.java index 8c46bd00..60e1dbef 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalConsoleLogger.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalConsoleLogger.java @@ -1,33 +1,25 @@ package xyz.olivermartin.multichat.local.common; +import xyz.olivermartin.multichat.common.MultiChatUtil; + public abstract class LocalConsoleLogger { private MultiChatLocalPlatform platform; - protected String prefix; - protected String debugPrefix; + protected static final String PREFIX = MultiChatUtil.translateColorCodes("&8[&2M&aC&3L&8]&7 "); + protected static final String DEBUG_PREFIX = PREFIX + MultiChatUtil.translateColorCodes("&8[&4DEBUG&8]&7 "); private boolean debug; protected LocalConsoleLogger(MultiChatLocalPlatform platform) { this.platform = platform; debug = false; - prefix = "&8[&2M&aC&3L&8]&7 "; - debugPrefix = "&8[&2M&aC&3L&8][&4DEBUG&8]&7 "; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public String getPrefix() { - return this.prefix; } public void setDebug(boolean debug) { this.debug = debug; } - + public boolean toggleDebug() { this.debug = !this.debug; return this.debug; @@ -39,14 +31,20 @@ public MultiChatLocalPlatform getPlatform() { protected abstract void displayMessageUsingLogger(String message); - protected abstract void sendColouredMessageToConsoleSender(String message); + protected abstract void sendConsoleMessage(String message); public void log(String message) { - sendColouredMessageToConsoleSender(prefix + message); + sendConsoleMessage(PREFIX + message); } public void debug(String message) { - if (debug) sendColouredMessageToConsoleSender(debugPrefix + message); + debug("", message); + } + + public void debug(String prefix, String message) { + if (debug) sendConsoleMessage(DEBUG_PREFIX + + MultiChatUtil.approximateRGBColorCodes(MultiChatUtil.translateColorCodes(prefix)) + + message); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalMetaManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalMetaManager.java index c7e525cb..a6829339 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalMetaManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalMetaManager.java @@ -5,37 +5,38 @@ public abstract class LocalMetaManager { public LocalMetaManager() { /* EMPTY */ } - + public String getNick(UUID uuid) { - return MultiChatLocal.getInstance().getNameManager().getCurrentName(uuid); + return MultiChatLocal.getInstance().getChatManager().translateColorCodes( + MultiChatLocal.getInstance().getNameManager().getCurrentName(uuid), true); } - + /** * Get the prefix of an online player * @param uuid * @return The prefix if they are online, or blank if they are not */ public abstract String getPrefix(UUID uuid); - + /** * Get the suffix of an online player * @param uuid * @return The suffix if they are online, or blank if they are not */ public abstract String getSuffix(UUID uuid); - + /** * Get the world of an online player * @param uuid * @return The world if they are online, or blank if they are not */ public abstract String getWorld(UUID uuid); - + /** * Get the display name of an online player * @param uuid * @return The display name if they are online, or blank if they are not */ public abstract String getDisplayName(UUID uuid); - + } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalPlaceholderManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalPlaceholderManager.java index 70c6c0eb..6c09b774 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalPlaceholderManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalPlaceholderManager.java @@ -34,35 +34,14 @@ public MultiChatLocalPlatform getPlatform() { */ public String processMultiChatPlaceholders(UUID uuid, String message) { - LocalConsoleLogger logger = MultiChatLocal.getInstance().getConsoleLogger(); - - logger.debug("---------------------------"); - - logger.debug("Processing placeholders..."); - - logger.debug("INPUT FORMAT = " + message); - logger.debug("INPUT FORMAT (visualised) = " + message.replace("&", "(#d)").replace("§", "(#e)")); - - //logger.debug("%NAME% = " + MultiChatLocal.getInstance().getNameManager().getName(uuid)); if (message.contains("%NAME%")) message = message.replace("%NAME%", MultiChatLocal.getInstance().getNameManager().getName(uuid)); - //logger.debug("%NICK% = " + MultiChatLocal.getInstance().getMetaManager().getNick(uuid)); if (message.contains("%NICK%")) message = message.replace("%NICK%", MultiChatLocal.getInstance().getMetaManager().getNick(uuid)); - //logger.debug("%DISPLAYNAME% = " + MultiChatLocal.getInstance().getMetaManager().getDisplayName(uuid)); if (message.contains("%DISPLAYNAME%")) message = message.replace("%DISPLAYNAME%", MultiChatLocal.getInstance().getMetaManager().getDisplayName(uuid)); - //logger.debug("%PREFIX% = " + MultiChatLocal.getInstance().getMetaManager().getPrefix(uuid)); if (message.contains("%PREFIX%")) message = message.replace("%PREFIX%", MultiChatLocal.getInstance().getMetaManager().getPrefix(uuid)); - //logger.debug("%SUFFIX% = " + MultiChatLocal.getInstance().getMetaManager().getSuffix(uuid)); if (message.contains("%SUFFIX%")) message = message.replace("%SUFFIX%", MultiChatLocal.getInstance().getMetaManager().getSuffix(uuid)); - //logger.debug("%WORLD% = " + MultiChatLocal.getInstance().getMetaManager().getWorld(uuid)); if (message.contains("%WORLD%")) message = message.replace("%WORLD%", MultiChatLocal.getInstance().getMetaManager().getWorld(uuid)); - //logger.debug("%SERVER% = " + MultiChatLocal.getInstance().getConfigManager().getLocalConfig().getServerName()); if (message.contains("%SERVER%")) message = message.replace("%SERVER%", MultiChatLocal.getInstance().getConfigManager().getLocalConfig().getServerName()); - logger.debug("Final Message = " + message); - logger.debug("Final Message (visualised) = " + message.replace("&", "(#d)").replace("§", "(#e)")); - - logger.debug("---------------------------"); - return message; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalProxyCommunicationManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalProxyCommunicationManager.java index 105d5877..e47bad34 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalProxyCommunicationManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/LocalProxyCommunicationManager.java @@ -1,5 +1,6 @@ package xyz.olivermartin.multichat.local.common; +import java.util.Set; import java.util.UUID; import xyz.olivermartin.multichat.proxy.common.MultiChatProxyPlatform; @@ -30,28 +31,20 @@ public MultiChatProxyPlatform getProxyPlatform() { public void updatePlayerMeta(UUID uuid) { - sendNicknameUpdate(uuid, MultiChatLocal.getInstance().getMetaManager().getNick(uuid)); - sendWorldUpdate(uuid, MultiChatLocal.getInstance().getMetaManager().getWorld(uuid)); - sendPrefixUpdate(uuid, MultiChatLocal.getInstance().getMetaManager().getPrefix(uuid)); - sendSuffixUpdate(uuid, MultiChatLocal.getInstance().getMetaManager().getSuffix(uuid)); - sendDisplayNameUpdate(uuid, MultiChatLocal.getInstance().getMetaManager().getDisplayName(uuid)); + sendMetaUpdate(uuid, "nick", MultiChatLocal.getInstance().getMetaManager().getNick(uuid)); + sendMetaUpdate(uuid, "world", MultiChatLocal.getInstance().getMetaManager().getWorld(uuid)); + sendMetaUpdate(uuid, "prefix", MultiChatLocal.getInstance().getMetaManager().getPrefix(uuid)); + sendMetaUpdate(uuid, "suffix", MultiChatLocal.getInstance().getMetaManager().getSuffix(uuid)); + sendMetaUpdate(uuid, "dn", MultiChatLocal.getInstance().getMetaManager().getDisplayName(uuid)); } - protected abstract void sendNicknameUpdate(UUID uuid, String nickname); - - public abstract void sendWorldUpdate(UUID uuid, String world); - - protected abstract void sendPrefixUpdate(UUID uuid, String prefix); - - protected abstract void sendSuffixUpdate(UUID uuid, String suffix); - - protected abstract void sendDisplayNameUpdate(UUID uuid, String displayName); + public abstract void sendMetaUpdate(UUID uuid, String metaId, String metaValue); public abstract void sendProxyExecuteMessage(String command); public abstract void sendProxyExecutePlayerMessage(String command, String player); - - public abstract void sendChatMessage(UUID uuid, String message, String format); + + public abstract void sendPlayerChatMessage(UUID uuid, String channel, String message, String format, Set otherRecipients); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/commands/NickCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/commands/NickCommand.java index b8494b6c..623c665c 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/commands/NickCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/commands/NickCommand.java @@ -3,6 +3,8 @@ import java.util.UUID; import java.util.regex.Pattern; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.common.TranslateMode; import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.config.LocalConfig; @@ -13,15 +15,13 @@ public abstract class NickCommand { //private static final Pattern simpleNickname = Pattern.compile("^[a-zA-Z0-9&_]+$"); private static final Pattern simpleNickname = Pattern.compile("^([a-zA-Z0-9_]|(?i)(\\&[0-9A-FL-ORX]))+$"); - public boolean executeNickCommand(MultiChatLocalPlayer targetPlayer, MultiChatLocalPlayer sender, String proposedNick) { + public boolean executeNickCommand(UUID targetUniqueId, MultiChatLocalPlayer sender, String proposedNick) { - proposedNick = MultiChatLocal.getInstance().getChatManager().reformatRGB(proposedNick); - - UUID targetUUID = targetPlayer.getUniqueId(); + proposedNick = MultiChatUtil.preProcessColorCodes(proposedNick); LocalNameManager lnm = MultiChatLocal.getInstance().getNameManager(); - if (targetPlayer.getUniqueId() != sender.getUniqueId()) { + if (targetUniqueId != sender.getUniqueId()) { if (!sender.hasPermission("multichatlocal.nick.others")) { sender.sendBadMessage("You do not have permission to nickname other players!"); return true; @@ -29,41 +29,66 @@ public boolean executeNickCommand(MultiChatLocalPlayer targetPlayer, MultiChatLo } if (proposedNick.equalsIgnoreCase("off")) { - lnm.removeNickname(targetUUID); - MultiChatLocal.getInstance().getProxyCommunicationManager().updatePlayerMeta(targetUUID); + lnm.removeNickname(targetUniqueId); sender.sendGoodMessage("The nickname has been removed!"); return true; } - if (!checkPermissions(targetPlayer, sender, proposedNick)) { + if (!checkPermissions(targetUniqueId, sender, proposedNick)) { + return true; + } + + if (!checkValidNickname(targetUniqueId, sender, proposedNick)) { return true; } - lnm.setNickname(targetUUID, proposedNick); - MultiChatLocal.getInstance().getProxyCommunicationManager().updatePlayerMeta(targetUUID); + lnm.setNickname(targetUniqueId, proposedNick); sender.sendGoodMessage("The nickname has been set!"); return true; } + public boolean executeConsoleNickCommand(UUID targetUniqueId, MultiChatLocalCommandSender console, String proposedNick) { + + proposedNick = MultiChatUtil.preProcessColorCodes(proposedNick); + + LocalNameManager lnm = MultiChatLocal.getInstance().getNameManager(); + + if (proposedNick.equalsIgnoreCase("off")) { + lnm.removeNickname(targetUniqueId); + console.sendGoodMessage("The nickname has been removed!"); + return true; + } + + if (!checkValidNickname(targetUniqueId, console, proposedNick)) { + return true; + } + + lnm.setNickname(targetUniqueId, proposedNick); + + console.sendGoodMessage("The nickname has been set!"); + return true; + + } + - private boolean checkPermissions(MultiChatLocalPlayer targetPlayer, MultiChatLocalPlayer sender, String proposedNick) { + private boolean checkPermissions(UUID targetUniqueId, MultiChatLocalPlayer sender, String proposedNick) { LocalNameManager lnm = MultiChatLocal.getInstance().getNameManager(); LocalConfig config = MultiChatLocal.getInstance().getConfigManager().getLocalConfig(); - if (lnm.containsRGBColorCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.color") || sender.hasPermission("multichatlocal.nick.colour")||sender.hasPermission("multichatlocal.nick.color.rgb") || sender.hasPermission("multichatlocal.nick.colour.rgb"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.X) && !(sender.hasPermission("multichatlocal.nick.color") || sender.hasPermission("multichatlocal.nick.colour")||sender.hasPermission("multichatlocal.nick.color.rgb") || sender.hasPermission("multichatlocal.nick.colour.rgb"))) { sender.sendBadMessage("You do not have permission to use nicknames with rgb color codes!"); return false; } - if (lnm.containsSimpleColorCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.color") || sender.hasPermission("multichatlocal.nick.colour")||sender.hasPermission("multichatlocal.nick.color.simple") || sender.hasPermission("multichatlocal.nick.colour.simple") ||sender.hasPermission("multichatlocal.nick.color.rgb") || sender.hasPermission("multichatlocal.nick.colour.rgb"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.COLOR_SIMPLE) && !(sender.hasPermission("multichatlocal.nick.color") || sender.hasPermission("multichatlocal.nick.colour")||sender.hasPermission("multichatlocal.nick.color.simple") || sender.hasPermission("multichatlocal.nick.colour.simple") ||sender.hasPermission("multichatlocal.nick.color.rgb") || sender.hasPermission("multichatlocal.nick.colour.rgb"))) { sender.sendBadMessage("You do not have permission to use nicknames with simple color codes!"); return false; } - if (lnm.containsFormatCodes(proposedNick)) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.FORMAT_ALL)) { // If the nickname has ANY format codes... @@ -71,32 +96,32 @@ private boolean checkPermissions(MultiChatLocalPlayer targetPlayer, MultiChatLoc // If they don't have the permission for ALL format codes, then we will check individually... - if (lnm.containsBoldFormatCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.format.bold"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.FORMAT_BOLD) && !(sender.hasPermission("multichatlocal.nick.format.bold"))) { sender.sendBadMessage("You do not have permission to use nicknames with bold format codes!"); return false; } - if (lnm.containsItalicFormatCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.format.italic"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.FORMAT_ITALIC) && !(sender.hasPermission("multichatlocal.nick.format.italic"))) { sender.sendBadMessage("You do not have permission to use nicknames with italic format codes!"); return false; } - if (lnm.containsUnderlineFormatCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.format.underline"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.FORMAT_UNDERLINE) && !(sender.hasPermission("multichatlocal.nick.format.underline"))) { sender.sendBadMessage("You do not have permission to use nicknames with underline format codes!"); return false; } - if (lnm.containsStrikethroughFormatCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.format.strikethrough"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.FORMAT_STRIKE) && !(sender.hasPermission("multichatlocal.nick.format.strikethrough"))) { sender.sendBadMessage("You do not have permission to use nicknames with strikethrough format codes!"); return false; } - if (lnm.containsObfuscatedFormatCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.format.obfuscated"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.FORMAT_OBFUSCATED) && !(sender.hasPermission("multichatlocal.nick.format.obfuscated"))) { sender.sendBadMessage("You do not have permission to use nicknames with obfuscated format codes!"); return false; } - if (lnm.containsResetFormatCodes(proposedNick) && !(sender.hasPermission("multichatlocal.nick.format.reset"))) { + if (MultiChatUtil.containsColorCodes(proposedNick, false, TranslateMode.FORMAT_RESET) && !((sender.hasPermission("multichatlocal.nick.format.reset")||sender.hasPermission("multichatlocal.nick.color")||sender.hasPermission("multichatlocal.nick.colour")||sender.hasPermission("multichatlocal.nick.color.rgb")||sender.hasPermission("multichatlocal.nick.colour.rgb")))) { sender.sendBadMessage("You do not have permission to use nicknames with reset format codes!"); return false; } @@ -119,7 +144,7 @@ private boolean checkPermissions(MultiChatLocalPlayer targetPlayer, MultiChatLoc length = proposedNick.length(); endOfMessage = "(Including format codes)"; } else { - length = lnm.stripAllFormattingCodes(proposedNick).length(); + length = MultiChatUtil.stripColorCodes(proposedNick, false).length(); endOfMessage = "(Excluding format codes)"; } @@ -135,20 +160,9 @@ private boolean checkPermissions(MultiChatLocalPlayer targetPlayer, MultiChatLoc } - if (lnm.stripAllFormattingCodes(proposedNick).length() < 1) { - sender.sendBadMessage("Sorry your nickname cannot be empty!"); - return false; - } - - String targetNickname = lnm.stripAllFormattingCodes(lnm.getCurrentName(targetPlayer.getUniqueId(), false)); - String targetName = lnm.getName(targetPlayer.getUniqueId()); - - if (lnm.existsNickname(proposedNick) && !targetNickname.equalsIgnoreCase(lnm.stripAllFormattingCodes(proposedNick)) ) { - sender.sendBadMessage("Sorry, this nickname is already in use!"); - return false; - } + String targetName = lnm.getName(targetUniqueId); - if (lnm.existsPlayer(proposedNick) && !targetName.equalsIgnoreCase(lnm.stripAllFormattingCodes(proposedNick)) && !sender.hasPermission("multichatlocal.nick.impersonate")) { + if (lnm.existsPlayer(proposedNick) && !targetName.equalsIgnoreCase(MultiChatUtil.stripColorCodes(proposedNick, false)) && !sender.hasPermission("multichatlocal.nick.impersonate")) { sender.sendBadMessage("Sorry, a player already exists with this name!"); return false; } @@ -158,7 +172,7 @@ private boolean checkPermissions(MultiChatLocalPlayer targetPlayer, MultiChatLoc boolean blacklisted = false; for (String bl : config.getNicknameBlacklist()) { - if (lnm.stripAllFormattingCodes(proposedNick).matches(bl)) { + if (MultiChatUtil.stripColorCodes(proposedNick, false).matches(bl)) { blacklisted = true; break; } @@ -175,4 +189,24 @@ private boolean checkPermissions(MultiChatLocalPlayer targetPlayer, MultiChatLoc } + private boolean checkValidNickname(UUID targetUniqueId, MultiChatLocalCommandSender sender, String proposedNick) { + + LocalNameManager lnm = MultiChatLocal.getInstance().getNameManager(); + + if (MultiChatUtil.stripColorCodes(proposedNick, false).length() < 1) { + sender.sendBadMessage("Sorry your nickname cannot be empty!"); + return false; + } + + String targetNickname = MultiChatUtil.stripColorCodes(lnm.getCurrentName(targetUniqueId, false), false); + + if (lnm.existsNickname(proposedNick) && !targetNickname.equalsIgnoreCase(MultiChatUtil.stripColorCodes(proposedNick, false)) ) { + sender.sendBadMessage("Sorry, this nickname is already in use!"); + return false; + } + + return true; + + } + } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/config/RegexChannelForcer.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/config/RegexChannelForcer.java index 640fd1b0..a768c912 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/config/RegexChannelForcer.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/config/RegexChannelForcer.java @@ -1,6 +1,6 @@ package xyz.olivermartin.multichat.local.common.config; -import xyz.olivermartin.multichat.local.common.MultiChatLocal; +import xyz.olivermartin.multichat.common.MultiChatUtil; public class RegexChannelForcer { @@ -25,24 +25,15 @@ public RegexChannelForcer(String regex, boolean ignoreFormatCodes, String channe public boolean matchesRegex(String messageFormat) { - MultiChatLocal.getInstance().getConsoleLogger().debug("[RegexChannelForcer] Testing format: " + messageFormat); - MultiChatLocal.getInstance().getConsoleLogger().debug("[RegexChannelForcer] Testing format (visualised): " + messageFormat.replace("&", "(#d)").replace("§", "(#e)")); - String testMessage = messageFormat; if (ignoreFormatCodes) { - testMessage = MultiChatLocal.getInstance().getNameManager().stripAllFormattingCodesAndPreformattedText(testMessage); + testMessage = MultiChatUtil.stripColorCodes(testMessage, true); } else { // This makes life easier when doing the config file as only have to use & style colour codes - testMessage = testMessage.replace('§', '&'); + testMessage = testMessage.replace('§', '&'); } - MultiChatLocal.getInstance().getConsoleLogger().debug("[RegexChannelForcer] Processed format codes: " + testMessage); - MultiChatLocal.getInstance().getConsoleLogger().debug("[RegexChannelForcer] Processed format codes (visualised): " + testMessage.replace("&", "(#d)").replace("§", "(#e)")); - - MultiChatLocal.getInstance().getConsoleLogger().debug("[RegexChannelForcer] Regex is: " + regex); - MultiChatLocal.getInstance().getConsoleLogger().debug("[RegexChannelForcer] Regex is (visualised): " + regex.replace("&", "(#d)").replace("§", "(#e)")); - return testMessage.matches(regex); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/LocalWorldChangeListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/LocalWorldChangeListener.java index ce791961..c9a0510d 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/LocalWorldChangeListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/LocalWorldChangeListener.java @@ -6,7 +6,7 @@ public abstract class LocalWorldChangeListener { protected void updatePlayerWorld(MultiChatLocalPlayer player, String world) { - MultiChatLocal.getInstance().getProxyCommunicationManager().sendWorldUpdate(player.getUniqueId(), world); + MultiChatLocal.getInstance().getProxyCommunicationManager().sendMetaUpdate(player.getUniqueId(), "world", world); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerHighest.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerHighest.java index 28d357a9..c458736e 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerHighest.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerHighest.java @@ -1,108 +1,97 @@ package xyz.olivermartin.multichat.local.common.listeners.chat; -import java.util.Optional; +import java.util.Set; +import java.util.UUID; import xyz.olivermartin.multichat.local.common.LocalChatManager; -import xyz.olivermartin.multichat.local.common.LocalPseudoChannel; +import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; import xyz.olivermartin.multichat.local.common.MultiChatLocal; -import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; public abstract class LocalChatListenerHighest { public void handleChat(MultiChatLocalPlayerChatEvent event) { - // IF ITS ALREADY CANCELLED WE CAN IGNORE IT - if (event.isCancelled()) return; + LocalConsoleLogger logger = MultiChatLocal.getInstance().getConsoleLogger(); + + logger.debug("&8[&9CHAT-L2&8]&7 ", "Processing a chat message..."); + logger.debug("&8[&9CHAT-L2&8]&7 ", "SENDER = '" + event.getPlayer().getName() + "'"); + logger.debug("&8[&9CHAT-L2&8]&7 ", "ORIGINAL MESSAGE = '" + event.getMessage() + "'"); + logger.debug("&8[&9CHAT-L2&8]&7 ", "ORIGINAL FORMAT = '" + event.getFormat() + "'"); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Now is where the fun starts... Welcome to the highest level!"); + // IF ITS ALREADY CANCELLED WE CAN IGNORE IT + if (event.isCancelled()) { + logger.debug("&8[&9CHAT-L2&8]&7 ", "Message is already cancelled - FINISH"); + return; + } LocalChatManager chatManager = MultiChatLocal.getInstance().getChatManager(); if (chatManager.canChatInRGBColour(event.getPlayer().getUniqueId())) { - event.setMessage(chatManager.translateColourCodes(event.getMessage(),true)); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Translated their message to include the colours (RGB) and set back in the event as: " + event.getMessage()); + event.setMessage(chatManager.translateColorCodes(event.getMessage(),true)); + logger.debug("&8[&9CHAT-L2&8]&7 ", "COLOR PERMISSIONS = RGB"); } else if (chatManager.canChatInSimpleColour(event.getPlayer().getUniqueId())) { - event.setMessage(chatManager.translateColourCodes(event.getMessage(),false)); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Translated their message to include the colours (SIMPLE ONLY) and set back in the event as: " + event.getMessage()); + event.setMessage(chatManager.translateColorCodes(event.getMessage(),false)); + logger.debug("&8[&9CHAT-L2&8]&7 ", "COLOR PERMISSIONS = SIMPLE"); + } else { + logger.debug("&8[&9CHAT-L2&8]&7 ", "COLOR PERMISSIONS = NONE"); } - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Now we will process MultiChat placeholders!"); + logger.debug("&8[&9CHAT-L2&8]&7 ", "MESSAGE (after color processing) = '" + event.getMessage() + "'"); event.setFormat(chatManager.processMultiChatConfigPlaceholders(event.getPlayer(), event.getFormat())); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - The resulting format was... " + event.getFormat()); + logger.debug("&8[&9CHAT-L2&8]&7 ", "FORMAT (after MultiChat placeholders) = '" + event.getFormat() + "'"); String channel = chatManager.peekAtChatChannel(event.getPlayer()); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Channel for this message before forcing is: " + channel); + logger.debug("&8[&9CHAT-L2&8]&7 ", "CHANNEL (before forcing) = '" + channel + "'"); // Deal with regex channel forcing... channel = chatManager.getRegexForcedChannel(channel, event.getFormat()); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Channel for this message after forcing is: " + channel); + logger.debug("&8[&9CHAT-L2&8]&7 ", "CHANNEL (after forcing) = '" + channel + "'"); // Deal with ignores and channel members - Optional opChannelObject = chatManager.getChannelObject(channel); - - if (opChannelObject.isPresent()) { - - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Do we have a channel object to match that name? Yes!"); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Now we are attempting to remove ignored players from the recipient list of the message, and making sure only people who are meant to see the channel (as specified in the channel object), can see it!"); + Set intendedRecipients = event.getOtherRecipients(); - event.removeIgnoredPlayersAndNonChannelMembersFromRecipients(opChannelObject.get()); + chatManager.queueRecipients(event.getPlayer().getUniqueId(), intendedRecipients); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - And BAM! That was handled by the local platform implementation!"); + event.removeOtherPlayers(); - } else { - - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - We didn't find a channel object to match that name... Probably not good!"); - - } + logger.debug("&8[&9CHAT-L2&8]&7 ", "Removed all recipients except for sender"); if (!chatManager.isGlobalChatServer() || channel.equalsIgnoreCase("local")) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - We are speaking into local chat, so at this point we are returning! Bye!"); + logger.debug("&8[&9CHAT-L2&8]&7 ", "This is a local chat message - FINISH"); return; } if (chatManager.isForceMultiChatFormat()) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - OKAYYY! We are forcing our format! All other plugins shall now crumble!"); - - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Currently it is starting out as... " + event.getFormat()); + logger.debug("&8[&9CHAT-L2&8]&7 ", "MultiChat force format is enabled, so we will now force our own format"); String format; format = chatManager.getChannelFormat(channel); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Got the format for this channel as:" + format); + + logger.debug("&8[&9CHAT-L2&8]&7 ", "CHANNEL FORMAT = '" + format + "'"); // Build chat format - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Rebuilding the chat format..."); format = MultiChatLocal.getInstance().getPlaceholderManager().buildChatFormat(event.getPlayer().getUniqueId(), format); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Now we have: " + format); + logger.debug("&8[&9CHAT-L2&8]&7 ", "CHANNEL FORMAT (built) = '" + format + "'"); - format = chatManager.processExternalPlaceholders(event.getPlayer(), format); + format = chatManager.processExternalPlaceholders(event.getPlayer(), format) + "%2$s"; - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Processed external placeholders to get: " + format); + logger.debug("&8[&9CHAT-L2&8]&7 ", "CHANNEL FORMAT (final with external placeholders) = '" + format + "'"); - if (MultiChatLocal.getInstance().getPlatform() == MultiChatLocalPlatform.SPIGOT) { - // Handle Spigot displayname formatting etc. - format = format.replace("%1$s", "!!!1!!!"); - format = format.replace("%2$s", "!!!2!!!"); - format = format.replace("%", "%%"); - format = format.replace("!!!1!!!", "%1$s"); - format = format.replace("!!!2!!!", "%2$s"); - } else { - format = format.replace("%", "%%"); - } + event.setFormat(format); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - Did some magic to get..." + format); - - event.setFormat(chatManager.translateColourCodes(format, true)); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@HIGHEST - FORMAT HAS BEEN SET AS: " + event.getFormat()); + logger.debug("&8[&9CHAT-L2&8]&7 ", "Format has been set"); } + logger.debug("&8[&9CHAT-L2&8]&7 ", "Processing completed - FINISH"); + } } \ No newline at end of file diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerLowest.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerLowest.java index ff5b8809..58295e29 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerLowest.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerLowest.java @@ -1,18 +1,26 @@ package xyz.olivermartin.multichat.local.common.listeners.chat; import xyz.olivermartin.multichat.local.common.LocalChatManager; +import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; import xyz.olivermartin.multichat.local.common.MultiChatLocal; -import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; public abstract class LocalChatListenerLowest { public void handleChat(MultiChatLocalPlayerChatEvent event) { - // IF ITS ALREADY CANCELLED THEN WE CAN IGNORE IT! - if (event.isCancelled()) return; + LocalConsoleLogger logger = MultiChatLocal.getInstance().getConsoleLogger(); + + logger.debug("&8[&1CHAT-L1&8]&7 ", "Processing a chat message..."); + logger.debug("&8[&1CHAT-L1&8]&7 ", "SENDER = '" + event.getPlayer().getName() + "'"); + logger.debug("&8[&1CHAT-L1&8]&7 ", "ORIGINAL MESSAGE = '" + event.getMessage() + "'"); + logger.debug("&8[&1CHAT-L1&8]&7 ", "ORIGINAL FORMAT = '" + event.getFormat() + "'"); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Handling chat message..."); + // IF ITS ALREADY CANCELLED THEN WE CAN IGNORE IT! + if (event.isCancelled()) { + logger.debug("&8[&1CHAT-L1&8]&7 ", "Message is already cancelled - FINISH"); + return; + } LocalChatManager chatManager = MultiChatLocal.getInstance().getChatManager(); @@ -20,56 +28,43 @@ public void handleChat(MultiChatLocalPlayerChatEvent event) { String channel = chatManager.peekAtChatChannel(player); String format = event.getFormat(); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Channel for this message before forcing is " + channel); + logger.debug("&8[&1CHAT-L1&8]&7 ", "CHANNEL (before forcing) = '" + channel + "'"); // Deal with regex channel forcing... channel = chatManager.getRegexForcedChannel(channel, format); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Channel for this message after forcing is " + channel); + logger.debug("&8[&1CHAT-L1&8]&7 ", "CHANNEL (after forcing) = '" + channel + "'"); if (!chatManager.isGlobalChatServer()) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Not a global chat server, so setting channel to local!"); channel = "local"; + logger.debug("&8[&1CHAT-L1&8]&7 ", "CHANNEL (override - no global) = '" + channel + "'"); } if (channel.equals("local") && !chatManager.isSetLocalFormat()) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Its local chat and we aren't setting the format for that, so return now!"); + logger.debug("&8[&1CHAT-L1&8]&7 ", "Local chat and MultiChat not setting format - FINISH"); return; } if (chatManager.isOverrideMultiChatFormat()) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - We are overriding MultiChat's formatting... So abandon here..."); + logger.debug("&8[&1CHAT-L1&8]&7 ", "MultiChat formatting is set to be overridden - FINISH"); return; } format = chatManager.getChannelFormat(channel); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Got the format for this channel as:" + format); + logger.debug("&8[&1CHAT-L1&8]&7 ", "CHANNEL FORMAT = '" + format + "'"); // Build chat format format = MultiChatLocal.getInstance().getPlaceholderManager().buildChatFormat(player.getUniqueId(), format); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Built to become: " + format); - - format = chatManager.processExternalPlaceholders(player, format); + logger.debug("&8[&1CHAT-L1&8]&7 ", "CHANNEL FORMAT (built) = '" + format + "'"); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Processing external placeholders to become: " + format); - - if (MultiChatLocal.getInstance().getPlatform() == MultiChatLocalPlatform.SPIGOT) { - // Handle Spigot displayname formatting etc. - format = format.replace("%1$s", "!!!1!!!"); - format = format.replace("%2$s", "!!!2!!!"); - format = format.replace("%", "%%"); - format = format.replace("!!!1!!!", "%1$s"); - format = format.replace("!!!2!!!", "%2$s"); - } else { - format = format.replace("%", "%%"); - } + format = chatManager.processExternalPlaceholders(player, format) + "%2$s"; - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Did some magic formatting to end up as: " + format); + logger.debug("&8[&1CHAT-L1&8]&7 ", "CHANNEL FORMAT (final with external placeholders) = '" + format + "'"); - event.setFormat(chatManager.translateColourCodes(format, true)); + event.setFormat(format); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@LOWEST - Set the format of the message. Finished processing at the lowest level!"); + logger.debug("&8[&1CHAT-L1&8]&7 ", "Format has been set - FINISH"); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerMonitor.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerMonitor.java index 355ad0d6..0f91a799 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerMonitor.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/LocalChatListenerMonitor.java @@ -1,6 +1,11 @@ package xyz.olivermartin.multichat.local.common.listeners.chat; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + import xyz.olivermartin.multichat.local.common.LocalChatManager; +import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; import xyz.olivermartin.multichat.local.common.config.LocalConfig; @@ -9,36 +14,44 @@ public abstract class LocalChatListenerMonitor { public void handleChat(MultiChatLocalPlayerChatEvent event) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - Okay less fun here, we are just the monitor..."); + LocalConsoleLogger logger = MultiChatLocal.getInstance().getConsoleLogger(); + + logger.debug("&8[&3CHAT-L3&8]&7 ", "Processing a chat message..."); + logger.debug("&8[&3CHAT-L3&8]&7 ", "SENDER = '" + event.getPlayer().getName() + "'"); + logger.debug("&8[&3CHAT-L3&8]&7 ", "ORIGINAL MESSAGE = '" + event.getMessage() + "'"); + logger.debug("&8[&3CHAT-L3&8]&7 ", "ORIGINAL FORMAT = '" + event.getFormat() + "'"); LocalConfig config = MultiChatLocal.getInstance().getConfigManager().getLocalConfig(); LocalChatManager chatManager = MultiChatLocal.getInstance().getChatManager(); + Optional> originalRecipients = chatManager.getRecipientsFromRecipientQueue(event.getPlayer().getUniqueId()); + + if (!originalRecipients.isPresent()) { + logger.debug("&8[&3CHAT-L3&8]&7 ", "No recipients for message, must have been cancelled earlier - FINISH"); + return; + } + String channel = chatManager.pollChatChannel(event.getPlayer()); + logger.debug("&8[&3CHAT-L3&8]&7 ", "CHANNEL (before forcing) = '" + channel + "'"); + // Deal with regex channel forcing... channel = chatManager.getRegexForcedChannel(channel, event.getFormat()); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - If the message is cancelled, then we will end here..."); + logger.debug("&8[&3CHAT-L3&8]&7 ", "CHANNEL (after forcing) = '" + channel + "'"); // IF ITS ALREADY CANCELLED WE CAN IGNORE IT - if (event.isCancelled()) return; - - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - The message isn't cancelled!"); - - // IF ITS LOCAL CHAT WE CAN IGNORE IT - if (!chatManager.isGlobalChatServer() || channel.equalsIgnoreCase("local")) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - We are speaking into local chat, so at this point we are returning! Bye!"); + if (event.isCancelled()) { + logger.debug("&8[&3CHAT-L3&8]&7 ", "Message is already cancelled - FINISH"); return; } // IF WE ARE MANAGING GLOBAL CHAT THEN WE NEED TO MANAGE IT! - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - We are in global chat... SO TIME TO FORWARD TO PROXY!"); - - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - First we are sending their meta data..."); MultiChatLocal.getInstance().getProxyCommunicationManager().updatePlayerMeta(event.getPlayer().getUniqueId()); + logger.debug("&8[&3CHAT-L3&8]&7 ", "Player meta data update has just been sent to proxy"); + String proxyFormat = event.getFormat(); String proxyMessage = event.getMessage(); @@ -48,38 +61,29 @@ public void handleChat(MultiChatLocalPlayerChatEvent event) { if (!config.isOverrideAllMultiChatFormatting()) { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - We were managing the format..."); - - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - Currently it is " + proxyFormat); - proxyFormat = proxyFormat.replace("%1$s", MultiChatLocal.getInstance().getMetaManager().getDisplayName(event.getPlayer().getUniqueId())); proxyFormat = proxyFormat.replace("%2$s", ""); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - We replaced the special bits to get: " + proxyFormat); - } else { - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - Oh dear... we need to send it to the proxy... but we weren't managing the chat..."); - - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - The format currently is: " + proxyFormat); + logger.debug("&8[&3CHAT-L3&8]&7 ", "MultiChat's format has been overridden, so proxy formatting is done on a best-effort basis..."); proxyFormat = proxyFormat.replace("%1$s", MultiChatLocal.getInstance().getMetaManager().getDisplayName(event.getPlayer().getUniqueId())); proxyFormat = proxyFormat.replace("%2$s", ""); proxyFormat = proxyFormat.replaceFirst("\\$s", MultiChatLocal.getInstance().getMetaManager().getDisplayName(event.getPlayer().getUniqueId())); proxyFormat = proxyFormat.replaceFirst("\\$s", ""); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - But we worked some magic to arrive at... " + proxyFormat); - } } - MultiChatLocal.getInstance().getProxyCommunicationManager().sendChatMessage(event.getPlayer().getUniqueId(), proxyMessage, proxyFormat); + logger.debug("&8[&3CHAT-L3&8]&7 ", "FORMAT (final for proxy) = '" + proxyFormat + "'"); + logger.debug("&8[&3CHAT-L3&8]&7 ", "MESSAGE (final for proxy) = '" + proxyMessage + "'"); + logger.debug("&8[&3CHAT-L3&8]&7 ", "PLAYER UUID = '" + event.getPlayer().getUniqueId() + "'"); + + MultiChatLocal.getInstance().getProxyCommunicationManager().sendPlayerChatMessage(event.getPlayer().getUniqueId(), channel, proxyMessage, proxyFormat, originalRecipients.get()); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - Aaaaand we sent it to the proxy! ALL DONE."); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - UUID: " + event.getPlayer().getUniqueId()); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - MESSAGE (please note this will be shown in colour here even if the player doesn't have colour permissions): " + proxyMessage); - MultiChatLocal.getInstance().getConsoleLogger().debug("#CHAT@MONITOR - FORMAT: " + proxyFormat); + logger.debug("&8[&3CHAT-L3&8]&7 ", "Info sent to proxy - FINISH"); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/MultiChatLocalPlayerChatEvent.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/MultiChatLocalPlayerChatEvent.java index 8ace0f64..fbf9dce7 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/MultiChatLocalPlayerChatEvent.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/chat/MultiChatLocalPlayerChatEvent.java @@ -1,6 +1,8 @@ package xyz.olivermartin.multichat.local.common.listeners.chat; -import xyz.olivermartin.multichat.local.common.LocalPseudoChannel; +import java.util.Set; +import java.util.UUID; + import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; public interface MultiChatLocalPlayerChatEvent { @@ -19,6 +21,10 @@ public interface MultiChatLocalPlayerChatEvent { public void setCancelled(boolean cancelled); - public void removeIgnoredPlayersAndNonChannelMembersFromRecipients(LocalPseudoChannel channel); + //public void removeIgnoredPlayersAndNonChansnelMembersFromRecipients(LocalPseudoChannel channel); + + public void removeOtherPlayers(); + + public Set getOtherRecipients(); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalIgnoreListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalIgnoreListener.java deleted file mode 100644 index f46dd36b..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalIgnoreListener.java +++ /dev/null @@ -1,36 +0,0 @@ -package xyz.olivermartin.multichat.local.common.listeners.communication; - -import java.io.IOException; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import xyz.olivermartin.multichat.local.common.MultiChatLocal; -import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeObjectMessage; - -public abstract class LocalIgnoreListener { - - @SuppressWarnings("unchecked") - protected boolean handleMessage(LocalBungeeObjectMessage message) { - - try { - - MultiChatLocal.getInstance().getConsoleLogger().debug("{multichat:ignore} Reading ignore map..."); - MultiChatLocal.getInstance().getDataStore().setIgnoreMap((Map>) message.readObject()); - MultiChatLocal.getInstance().getConsoleLogger().debug("{multichat:ignore} Successfully read ignore map!"); - return true; - - } catch (IOException e) { - - MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred trying to read local ignore message from Bungeecord, is the server lagging?"); - return false; - - } catch (ClassNotFoundException e) { - - MultiChatLocal.getInstance().getConsoleLogger().log("Could not read the ignore Map from local ignore message..."); - return false; - } - - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerActionListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerActionListener.java index 4ddf5a24..f89944cf 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerActionListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerActionListener.java @@ -9,8 +9,6 @@ public abstract class LocalPlayerActionListener { protected abstract void executeCommandForPlayersMatchingRegex(String playerRegex, String command); - protected abstract void sendChatAsPlayer(String playerName, String rawMessage); - protected boolean handleMessage(LocalBungeeMessage message) { try { @@ -18,12 +16,6 @@ protected boolean handleMessage(LocalBungeeMessage message) { String playerRegex = message.readUTF(); String command = message.readUTF(); - // Handle the local global direct message hack - if (isHackedMessage(command)) { - handleHackedMessage(command, playerRegex); - return true; - } - executeCommandForPlayersMatchingRegex(playerRegex, command); return true; @@ -37,22 +29,4 @@ protected boolean handleMessage(LocalBungeeMessage message) { } - private boolean isHackedMessage(String command) { - return (command.startsWith("!SINGLE L MESSAGE!") || command.startsWith("!SINGLE G MESSAGE!")); - } - - private void handleHackedMessage(String command, String player) { - - String message = command.substring("!SINGLE X MESSAGE!".length(), command.length()); - - if (command.startsWith("!SINGLE L MESSAGE!")) { - MultiChatLocal.getInstance().getChatManager().queueChatChannel(player, "local"); - } else { - MultiChatLocal.getInstance().getChatManager().queueChatChannel(player, "global"); - } - - sendChatAsPlayer(player, message); - - } - } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerChatListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerChatListener.java new file mode 100644 index 00000000..6a8872ce --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerChatListener.java @@ -0,0 +1,49 @@ +package xyz.olivermartin.multichat.local.common.listeners.communication; + +import java.io.IOException; + +import xyz.olivermartin.multichat.local.common.MultiChatLocal; +import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; + +public abstract class LocalPlayerChatListener { + + protected abstract void sendChatAsPlayer(String playerName, String rawMessage); + + protected boolean handleMessage(LocalBungeeMessage message) { + + try { + + // This is used to handle the direct /local and /global messages + // Previously used the old "direct hack" in action listeners + + String channel = message.readUTF(); // TODO THIS NEEDS WORK + String player = message.readUTF(); + String chatMessage = message.readUTF(); + + switch (channel) { + + case "local": + MultiChatLocal.getInstance().getChatManager().queueChatChannel(player, "local"); + break; + case "global": + MultiChatLocal.getInstance().getChatManager().queueChatChannel(player, "global"); + break; + default: + // TODO No other channels exist at this point + break; + } + + sendChatAsPlayer(player, chatMessage); + + return true; + + } catch (IOException e) { + + MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred trying to read local direct player chat message from Bungeecord, is the server lagging?"); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerChannelListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerDataListener.java similarity index 62% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerChannelListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerDataListener.java index a6cc3223..c0509657 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerChannelListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerDataListener.java @@ -1,21 +1,18 @@ package xyz.olivermartin.multichat.local.common.listeners.communication; import java.io.IOException; -import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; -import xyz.olivermartin.multichat.local.common.LocalPseudoChannel; import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeObjectMessage; -public abstract class LocalPlayerChannelListener { +public abstract class LocalPlayerDataListener { protected abstract Optional getPlayerFromName(String playername); - @SuppressWarnings("unchecked") protected boolean handleMessage(LocalBungeeObjectMessage message) { try { @@ -27,41 +24,35 @@ protected boolean handleMessage(LocalBungeeObjectMessage message) { MultiChatLocalPlayer player = opPlayer.get(); String channelName = message.readUTF(); + Map playerChannels = MultiChatLocal.getInstance().getDataStore().getPlayerChannels(); synchronized (playerChannels) { playerChannels.put(player.getUniqueId(), channelName); } + String channelFormat = message.readUTF(); + MultiChatLocal.getInstance().getDataStore().getChannelFormats().put(channelName, channelFormat); + boolean colour = message.readBoolean(); boolean rgb = message.readBoolean(); + Map simpleColourMap = MultiChatLocal.getInstance().getDataStore().getSimpleColourMap(); Map rgbColourMap = MultiChatLocal.getInstance().getDataStore().getRGBColourMap(); + synchronized (simpleColourMap) { simpleColourMap.put(player.getUniqueId(), colour); } + synchronized (rgbColourMap) { rgbColourMap.put(player.getUniqueId(), rgb); } - boolean whitelistMembers = message.readBoolean(); - List channelMembers = (List) message.readObject(); - - LocalPseudoChannel channelObject = new LocalPseudoChannel(channelName, channelMembers, whitelistMembers); - Map channelObjects = MultiChatLocal.getInstance().getDataStore().getChannelObjects(); - synchronized (channelObjects) { - channelObjects.put(channelName, channelObject); - } - return true; } catch (IOException e) { - MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred trying to read local channel message from Bungeecord, is the server lagging?"); - return false; - - } catch (ClassNotFoundException e) { - - MultiChatLocal.getInstance().getConsoleLogger().log("Could not read List of UUIDs from local channel message..."); + e.printStackTrace(); + MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred trying to read player data message from Bungeecord, is the server lagging?"); return false; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerMetaListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerMetaListener.java index 620ae4cf..e2bcb2a9 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerMetaListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalPlayerMetaListener.java @@ -15,35 +15,14 @@ protected boolean handleMessage(LocalBungeeMessage message) { try { - boolean setDisplayName = false; - boolean globalChat = false; - String displayNameFormat = ""; - Optional opPlayer = getPlayerFromName(message.readUTF()); if (!opPlayer.isPresent()) return true; MultiChatLocalPlayer player = opPlayer.get(); - if (message.readUTF().equals("T")) { - setDisplayName = true; - } - - displayNameFormat = message.readUTF(); - - MultiChatLocal.getInstance().getDataStore().setSetDisplayName(setDisplayName); - MultiChatLocal.getInstance().getDataStore().setDisplayNameFormatLastVal(displayNameFormat); - MultiChatLocal.getInstance().getProxyCommunicationManager().updatePlayerMeta(player.getUniqueId()); - if (message.readUTF().equals("T")) { - globalChat = true; - } - - MultiChatLocal.getInstance().getDataStore().setGlobalChatServer(globalChat); - - MultiChatLocal.getInstance().getDataStore().setGlobalChatFormat(message.readUTF()); - return true; } catch (IOException e) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalActionListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerActionListener.java similarity index 52% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalActionListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerActionListener.java index 9a7d3f08..297d4476 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalActionListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerActionListener.java @@ -5,7 +5,7 @@ import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; -public abstract class LocalActionListener { +public abstract class LocalServerActionListener { protected abstract void executeCommandAsConsole(String command); @@ -14,13 +14,6 @@ protected boolean handleMessage(LocalBungeeMessage message) { try { String command = message.readUTF(); - - // HANDLE LEGACY SERVER HACK - if (isHackedMessage(command)) { - handleHackedMessage(command); - return true; - } - executeCommandAsConsole(command); return true; @@ -33,18 +26,4 @@ protected boolean handleMessage(LocalBungeeMessage message) { } - private boolean isHackedMessage(String command) { - return (command.equals("!!!LEGACYSERVER!!!") || command.equals("!!!NOTLEGACYSERVER!!!")); - } - - private void handleHackedMessage(String command) { - - if (command.equals("!!!LEGACYSERVER!!!")) { - MultiChatLocal.getInstance().getDataStore().setLegacy(true); - } else { - MultiChatLocal.getInstance().getDataStore().setLegacy(false); - } - - } - } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalCastListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerChatListener.java similarity index 76% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalCastListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerChatListener.java index 2f6793db..79c61fe1 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalCastListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerChatListener.java @@ -5,12 +5,16 @@ import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; -public abstract class LocalCastListener { +public abstract class LocalServerChatListener { protected boolean handleMessage(LocalBungeeMessage message) { try { + // This is currently only used for casts + + @SuppressWarnings("unused") + String channel = message.readUTF(); // TODO THIS NEEDS WORK String castMessage = message.readUTF(); broadcastRawMessageToChat(castMessage); return true; diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerDataListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerDataListener.java new file mode 100644 index 00000000..d6844c11 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/listeners/communication/LocalServerDataListener.java @@ -0,0 +1,83 @@ +package xyz.olivermartin.multichat.local.common.listeners.communication; + +import java.io.IOException; + +import xyz.olivermartin.multichat.local.common.MultiChatLocal; +import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeObjectMessage; + +public abstract class LocalServerDataListener { + + protected boolean handleMessage(LocalBungeeObjectMessage message) { + + try { + + /* + * This is for the sdata channel + * + * The ids are: + * - global = Global chat info + * - dn = display name info + * - legacy = legacy server info + */ + + String id = message.readUTF(); + + switch (id) { + + case "global": + + boolean globalServer; + String globalChatFormat; + + globalServer = message.readBoolean(); + globalChatFormat = message.readUTF(); + + MultiChatLocal.getInstance().getDataStore().setGlobalChatServer(globalServer); + MultiChatLocal.getInstance().getDataStore().setGlobalChatFormat(globalChatFormat); + + break; + + case "dn": + + boolean setDisplayName; + String displayNameFormat; + + setDisplayName = message.readBoolean(); + displayNameFormat = message.readUTF(); + + MultiChatLocal.getInstance().getDataStore().setSetDisplayName(setDisplayName); + MultiChatLocal.getInstance().getDataStore().setDisplayNameFormatLastVal(displayNameFormat); + + break; + + case "legacy": + + boolean isLegacy; + + isLegacy = message.readBoolean(); + + MultiChatLocal.getInstance().getDataStore().setLegacy(isLegacy); + + break; + + default: + + // TODO No other ids exist at this point + + break; + + } + + return true; + + } catch (IOException e) { + + e.printStackTrace(); + MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred trying to read local server data message from Bungeecord, is the server lagging?"); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalDataStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalDataStore.java index 8c9bdd15..28811d8d 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalDataStore.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalDataStore.java @@ -38,11 +38,21 @@ public class LocalDataStore { */ private String globalChatFormat = "&f%DISPLAYNAME%&f: "; + /** + * Channel formats received from the proxy + */ + private Map channelFormats = new HashMap(); + /** * Chat Queues to handle the local global hack */ private Map> chatQueues = new HashMap>(); + /** + * Recipient Queues + */ + private Map>> recipientQueues = new HashMap>>(); + /** * What channel is each player speaking in? */ @@ -63,11 +73,6 @@ public class LocalDataStore { */ private Map channelObjects = new HashMap(); - /** - * Map of who players ignore - */ - private Map> ignoreMap = new HashMap>(); - /** * IS THIS A LEGACY SERVER THAT NEEDS RGB CODE APPROX.? */ @@ -108,6 +113,13 @@ public synchronized Map> getChatQueues() { return chatQueues; } + /** + * @return the recipientQueues + */ + public synchronized Map>> getRecipientQueues() { + return recipientQueues; + } + /** * @return the playerChannels */ @@ -136,13 +148,6 @@ public synchronized Map getChannelObjects() { return channelObjects; } - /** - * @return the ignoreMap - */ - public synchronized Map> getIgnoreMap() { - return ignoreMap; - } - /** * @return the legacy */ @@ -185,6 +190,13 @@ public synchronized void setChatQueues(Map> chatQueues) { this.chatQueues = chatQueues; } + /** + * @param recipientQueues the recipientQueues to set + */ + public synchronized void setRecipientQueues(Map>> recipientQueues) { + this.recipientQueues = recipientQueues; + } + /** * @param playerChannels the playerChannels to set */ @@ -214,17 +226,24 @@ public synchronized void setChannelObjects(Map chann } /** - * @param ignoreMap the ignoreMap to set + * @param legach the legacy to set */ - public synchronized void setIgnoreMap(Map> ignoreMap) { - this.ignoreMap = ignoreMap; + public synchronized void setLegacy(boolean legacy) { + this.legacy = legacy; } /** - * @param legach the legacy to set + * @return the channelFormats */ - public synchronized void setLegacy(boolean legacy) { - this.legacy = legacy; + public Map getChannelFormats() { + return channelFormats; + } + + /** + * @param channelFormats the channelFormats to set + */ + public void setChannelFormats(Map channelFormats) { + this.channelFormats = channelFormats; } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalFileNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalFileNameManager.java index 6641128f..841807a6 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalFileNameManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalFileNameManager.java @@ -8,6 +8,7 @@ import java.util.UUID; import java.util.regex.PatternSyntaxException; +import xyz.olivermartin.multichat.common.MultiChatUtil; import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; @@ -109,28 +110,28 @@ public void setMapNickFormatted(Map mapNickFormatted) { * @return The NICKNAME of the player if it is set, otherwise their username */ public String getCurrentName(UUID uuid, boolean withPrefix) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Getting CurrentName for " + uuid); synchronized (mapUUIDNick) { if (mapUUIDNick.containsKey(uuid)) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] UUID is in the UUIDNick map"); - + String currentName; - + if (MultiChatLocal.getInstance().getConfigManager().getLocalConfig().isShowNicknamePrefix() && withPrefix) { currentName = MultiChatLocal.getInstance().getConfigManager().getLocalConfig().getNicknamePrefix() + mapNickFormatted.get(mapUUIDNick.get(uuid)); } else { currentName = mapNickFormatted.get(mapUUIDNick.get(uuid)); } - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] CurrentName (withPrefix?=" + withPrefix + ") is " + currentName); - + return currentName; } } - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] They do not have a nickname..."); synchronized (mapUUIDName) { @@ -141,7 +142,7 @@ public String getCurrentName(UUID uuid, boolean withPrefix) { return result; } } - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] This player does not exist in any map... returning empty string"); return ""; @@ -212,7 +213,7 @@ public Optional getUUIDFromName(String username) { * @param player */ public void registerPlayer(UUID uuid, String username) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Registering player (" + username + ") with UUID = " + uuid); String oldUsername; @@ -220,13 +221,13 @@ public void registerPlayer(UUID uuid, String username) { synchronized (mapUUIDName) { if (mapUUIDName.containsKey(uuid)) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] The player has joined before..."); oldUsername = mapUUIDName.get(uuid); if (!oldUsername.equalsIgnoreCase(username)) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] They have a new username (" + username + "), previously was " + oldUsername); synchronized (mapNameUUID) { @@ -242,11 +243,11 @@ public void registerPlayer(UUID uuid, String username) { mapNameFormatted.remove(oldUsername); mapNameFormatted.put(username.toLowerCase(), username); - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Updated necessary maps!"); } else { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Player has not joined before..."); synchronized (mapNameUUID) { @@ -254,7 +255,7 @@ public void registerPlayer(UUID uuid, String username) { mapUUIDName.put(uuid, username.toLowerCase()); mapNameUUID.put(username.toLowerCase(), uuid); mapNameFormatted.put(username.toLowerCase(), username); - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Updated necessary maps!"); } @@ -264,7 +265,7 @@ public void registerPlayer(UUID uuid, String username) { } online.add(uuid); - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Added player to list of online players!"); } @@ -305,7 +306,7 @@ public void registerOfflinePlayerByUUID(UUID uuid, String username) { * @param player */ public void unregisterPlayer(UUID uuid) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Unregistering " + uuid); online.remove(uuid); @@ -318,7 +319,7 @@ public void unregisterPlayer(UUID uuid) { * @param nickname */ public void setNickname(UUID uuid, String nickname) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Setting nickname (" + nickname + ") for UUID " + uuid); if (!mapUUIDName.containsKey(uuid)) { @@ -332,8 +333,8 @@ public void setNickname(UUID uuid, String nickname) { MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Old nickname removed!"); } - String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); - + String unformattedNickname = MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false); + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Unformatted nickname = " + unformattedNickname); synchronized (mapNickUUID) { @@ -349,7 +350,7 @@ public void setNickname(UUID uuid, String nickname) { mapUUIDNick.put(uuid, unformattedNickname); mapNickUUID.put(unformattedNickname, uuid); mapNickFormatted.put(unformattedNickname, nickname); - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Maps updated with new info!"); } @@ -369,7 +370,7 @@ public boolean existsPlayer(String username) { * @return If this nickname is currently in use */ public boolean existsNickname(String nickname) { - return mapNickUUID.containsKey(stripAllFormattingCodes(nickname.toLowerCase())); + return mapNickUUID.containsKey(MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false)); } /** @@ -380,7 +381,7 @@ public boolean existsNickname(String nickname) { public Optional> getPartialNicknameMatches(String nickname) { Set nickSet = mapNickUUID.keySet(); - nickname = stripAllFormattingCodes(nickname.toLowerCase()); + nickname = MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false); Set uuidSet = new HashSet(); for (String nick : nickSet) { @@ -431,7 +432,7 @@ public Optional> getPartialNicknameMatches(String nickname) { public Optional> getPartialNameMatches(String name) { Set nameSet = mapNameUUID.keySet(); - name = stripAllFormattingCodes(name.toLowerCase()); + name = MultiChatUtil.stripColorCodes(name.toLowerCase(), false); Set uuidSet = new HashSet(); for (String n : nameSet) { @@ -487,7 +488,7 @@ public boolean isOnline(UUID uuid) { * @param uuid */ public void removeNickname(UUID uuid) { - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Removing nickname for " + uuid); synchronized (mapUUIDNick) { @@ -502,7 +503,7 @@ public void removeNickname(UUID uuid) { mapUUIDNick.remove(uuid); mapNickUUID.remove(nickname); mapNickFormatted.remove(nickname); - + MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalFileNameManager] Updated necessary maps! Completed process."); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalNameManager.java index 15b9bd7d..06f2b98c 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalNameManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalNameManager.java @@ -5,8 +5,8 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; -import java.util.regex.Pattern; +import xyz.olivermartin.multichat.common.MultiChatUtil; import xyz.olivermartin.multichat.local.common.MultiChatLocal; /** @@ -88,7 +88,7 @@ public String getCurrentName(UUID uuid) { public Optional getUUIDFromNickname(String nickname) { nickname = nickname.toLowerCase(); - nickname = stripAllFormattingCodes(nickname); + nickname = MultiChatUtil.stripColorCodes(nickname, false); Optional uuid = getUUIDFromUnformattedNickname(nickname); @@ -234,191 +234,4 @@ public boolean isOnline(UUID uuid) { */ public abstract void removeNickname(UUID uuid); - /* - * Remove all colour / format codes from a string (using the '&' char) - */ - public String stripAllFormattingCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-ORX]"); - - if (input == null) { - return null; - } - - return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); - - } - - /* - * Remove all colour / format codes from a string (using the special § char) - */ - public String stripAllFormattingCodesAndPreformattedText(String input) { - - input = stripAllFormattingCodes(input); - - char COLOR_CHAR = '§'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-ORX]"); - - if (input == null) { - return null; - } - - return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); - - } - - /** - * @param input - * @return True if the input contains colour codes (e.g. '&a') - */ - public boolean containsSimpleColorCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-F]"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains hex colour codes (e.g. '&x...') - */ - public boolean containsRGBColorCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[X]"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains format codes (e.g. '&l') - */ - public boolean containsFormatCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[K-OR]"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains bold format codes - */ - public boolean containsBoldFormatCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "L"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains italic format codes - */ - public boolean containsItalicFormatCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "O"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains underline format codes - */ - public boolean containsUnderlineFormatCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "N"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains strikethrough format codes - */ - public boolean containsStrikethroughFormatCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "M"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains obfuscated format codes - */ - public boolean containsObfuscatedFormatCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "K"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - - /** - * @param input - * @return True if the input contains reset format codes - */ - public boolean containsResetFormatCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "R"); - - if (input == null) { - return false; - } - - return !STRIP_COLOR_PATTERN.matcher(input).replaceAll("").equals(input); - - } - } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalSQLNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalSQLNameManager.java index 92e5377b..992a671a 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalSQLNameManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/common/storage/LocalSQLNameManager.java @@ -7,6 +7,7 @@ import java.util.Set; import java.util.UUID; +import xyz.olivermartin.multichat.common.MultiChatUtil; import xyz.olivermartin.multichat.common.database.DatabaseManager; import xyz.olivermartin.multichat.common.database.GenericPooledDatabase; import xyz.olivermartin.multichat.common.database.SimpleConnection; @@ -71,8 +72,6 @@ public String getCurrentName(UUID uuid, boolean withPrefix) { } } - MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalSQLNameManager] CurrentName = " + name); - } catch (SQLException e) { e.printStackTrace(); name = ""; @@ -458,7 +457,7 @@ public void setNickname(UUID uuid, String nickname) { return; } - String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); + String unformattedNickname = MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false); MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalSQLNameManager] Unformatted nickname = " + unformattedNickname); @@ -535,7 +534,7 @@ public boolean existsNickname(String nickname) { try { conn = localDatabase.getConnection(); - ResultSet results = conn.safeQuery("SELECT u_nick FROM nick_data WHERE u_nick = ?;", stripAllFormattingCodes(nickname.toLowerCase())); + ResultSet results = conn.safeQuery("SELECT u_nick FROM nick_data WHERE u_nick = ?;", MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false)); if (results.next()) { MultiChatLocal.getInstance().getConsoleLogger().debug("[LocalSQLNameManager] Nickname " + nickname + " exists"); @@ -567,7 +566,7 @@ public boolean otherPlayerHasNickname(String nickname, UUID uuid) { conn = localDatabase.getConnection(); ResultSet results = conn.safeQuery("SELECT id, u_nick FROM nick_data WHERE u_nick = ?;" - , stripAllFormattingCodes(nickname.toLowerCase())); + , MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false)); if (results.next()) { if (results.getString("id").equals(uuid.toString())) { @@ -602,7 +601,7 @@ public Optional> getPartialNicknameMatches(String nickname) { conn = localDatabase.getConnection(); ResultSet results = conn.safeQuery("SELECT id FROM nick_data WHERE (u_nick LIKE ?);" - , "%" + stripAllFormattingCodes(nickname.toLowerCase()) + "%"); + , "%" + MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false) + "%"); if (results.next()) { Set uuids = new HashSet(); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotChatManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotChatManager.java index 7e454209..1369e95f 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotChatManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotChatManager.java @@ -1,37 +1,14 @@ package xyz.olivermartin.multichat.local.spigot; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import me.clip.placeholderapi.PlaceholderAPI; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.local.common.LocalChatManager; -import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.spigot.hooks.LocalSpigotPAPIHook; public class LocalSpigotChatManager extends LocalChatManager { - @Override - public String translateColourCodes(String message, boolean rgb) { - - if (rgb) { - message = MultiChatLocal.getInstance().getChatManager().reformatRGB(message); - - // LEGACY HACK - if (MultiChatLocal.getInstance().getDataStore().isLegacy()) { - message = message.replaceAll("&(?=[a-f,0-9,k-o,r,x])", "§"); - message = MultiChatUtil.approximateHexCodes(message); - } - - return ChatColor.translateAlternateColorCodes('&', message); - } else { - message = message.replaceAll("&(?=[a-f,0-9,k-o,r])", "§"); - return message; - } - - } - @Override public String processExternalPlaceholders(MultiChatLocalPlayer player, String message) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotConsoleLogger.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotConsoleLogger.java index a46139f9..a2035b68 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotConsoleLogger.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotConsoleLogger.java @@ -3,7 +3,6 @@ import java.util.logging.Logger; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; @@ -22,8 +21,8 @@ protected void displayMessageUsingLogger(String message) { } @Override - protected void sendColouredMessageToConsoleSender(String message) { - Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', message)); + protected void sendConsoleMessage(String message) { + Bukkit.getConsoleSender().sendMessage(message); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotMetaManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotMetaManager.java index 9ceebfdf..0798ab29 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotMetaManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotMetaManager.java @@ -7,7 +7,6 @@ import org.bukkit.entity.Player; import net.milkbowl.vault.chat.Chat; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; import xyz.olivermartin.multichat.local.common.LocalMetaManager; import xyz.olivermartin.multichat.local.common.MultiChatLocal; @@ -24,12 +23,13 @@ public String getPrefix(UUID uuid) { Chat vaultChat = opVault.get(); - // LEGACY HACK - if (MultiChatLocal.getInstance().getDataStore().isLegacy()) { - return MultiChatUtil.approximateHexCodes(vaultChat.getPlayerPrefix(Bukkit.getServer().getPlayer(uuid))); - } + // Get prefix + String prefix = vaultChat.getPlayerPrefix(Bukkit.getServer().getPlayer(uuid)); - return MultiChatUtil.reformatRGB(vaultChat.getPlayerPrefix(Bukkit.getServer().getPlayer(uuid))); + // Translate prefix + prefix = MultiChatLocal.getInstance().getChatManager().translateColorCodes(prefix, true); + + return prefix; } @@ -46,12 +46,13 @@ public String getSuffix(UUID uuid) { Chat vaultChat = opVault.get(); - // LEGACY HACK - if (MultiChatLocal.getInstance().getDataStore().isLegacy()) { - return MultiChatUtil.approximateHexCodes(vaultChat.getPlayerSuffix(Bukkit.getServer().getPlayer(uuid))); - } + // Get suffix + String suffix = vaultChat.getPlayerSuffix(Bukkit.getServer().getPlayer(uuid)); + + // Translate suffix + suffix = MultiChatLocal.getInstance().getChatManager().translateColorCodes(suffix, true); - return MultiChatUtil.reformatRGB(vaultChat.getPlayerSuffix(Bukkit.getServer().getPlayer(uuid))); + return suffix; } @@ -86,32 +87,14 @@ public String getDisplayName(UUID uuid) { String displayNameFormat = MultiChatLocal.getInstance().getDataStore().getDisplayNameFormatLastVal(); - logger.debug("[LocalSpigotMetaManager] Format = " + displayNameFormat); - logger.debug("[LocalSpigotMetaManager] Format (using & only) = " + displayNameFormat.replaceAll("(?i)§(?=[a-f,0-9,k-o,r,x])", "&")); - // TODO This stuff could be refactored as it is duplicated between Spigot and Sponge displayNameFormat = displayNameFormat.replaceAll("%NICK%", getNick(uuid)); displayNameFormat = displayNameFormat.replaceAll("%NAME%", player.getName()); displayNameFormat = displayNameFormat.replaceAll("%PREFIX%", getPrefix(uuid)); displayNameFormat = displayNameFormat.replaceAll("%SUFFIX%", getSuffix(uuid)); - logger.debug("[LocalSpigotMetaManager] Format with placeholders = " + displayNameFormat); - logger.debug("[LocalSpigotMetaManager] Format with placeholders (using & only) = " + displayNameFormat.replaceAll("(?i)§(?=[a-f,0-9,k-o,r,x])", "&")); - - displayNameFormat = MultiChatUtil.reformatRGB(displayNameFormat); - - logger.debug("[LocalSpigotMetaManager] Format after reformatting RGB = " + displayNameFormat); - logger.debug("[LocalSpigotMetaManager] Format after reformatting RGB (using & only) = " + displayNameFormat.replaceAll("(?i)§(?=[a-f,0-9,k-o,r,x])", "&")); - - displayNameFormat = displayNameFormat.replaceAll("(?i)&(?=[a-f,0-9,k-o,r,x])", "§"); - - logger.debug("[LocalSpigotMetaManager] FINAL = " + displayNameFormat); - logger.debug("[LocalSpigotMetaManager] FINAL (using & only) = " + displayNameFormat.replaceAll("(?i)§(?=[a-f,0-9,k-o,r,x])", "&")); - - // LEGACY HACK - if (MultiChatLocal.getInstance().getDataStore().isLegacy()) { - displayNameFormat = MultiChatUtil.approximateHexCodes(displayNameFormat); - } + // Translate displayname + displayNameFormat = MultiChatLocal.getInstance().getChatManager().translateColorCodes(displayNameFormat, true); player.setDisplayName(displayNameFormat); player.setPlayerListName(displayNameFormat); @@ -119,6 +102,7 @@ public String getDisplayName(UUID uuid) { } return player.getDisplayName(); + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotPlaceholderManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotPlaceholderManager.java index cf9975ae..861359bd 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotPlaceholderManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/LocalSpigotPlaceholderManager.java @@ -2,8 +2,8 @@ import java.util.UUID; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.local.common.LocalPlaceholderManager; +import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; public class LocalSpigotPlaceholderManager extends LocalPlaceholderManager { @@ -15,17 +15,17 @@ public LocalSpigotPlaceholderManager() { @Override public String buildChatFormat(UUID uuid, String format) { - // Reformat any hex codes in the format - format = MultiChatUtil.reformatRGB(format); - // RESPECT OTHER PLUGIN'S DISPLAY NAMES FIRST! (Allows for factions etc.) format = format.replace("%DISPLAYNAME%", "%1$s"); // PROCESS REST ACCORDING TO MULTICHAT'S PLACEHOLDERS format = processMultiChatPlaceholders(uuid, format); + // Translate codes + format = MultiChatLocal.getInstance().getChatManager().translateColorCodes(format, true); + // Adds the message on the end, respecting any changes from other plugins. - return format + "%2$s"; // TODO This bit should not be added here, should be added in a different part (As sponge does not add here) + return format; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/MultiChatLocalSpigotPlugin.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/MultiChatLocalSpigotPlugin.java index 79899fa7..81ebdfba 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/MultiChatLocalSpigotPlugin.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/MultiChatLocalSpigotPlugin.java @@ -7,6 +7,7 @@ import org.bukkit.plugin.java.JavaPlugin; import net.milkbowl.vault.chat.Chat; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.common.database.DatabaseManager; import xyz.olivermartin.multichat.local.common.LocalChatManager; import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; @@ -35,12 +36,13 @@ import xyz.olivermartin.multichat.local.spigot.listeners.chat.LocalSpigotChatListenerHighest; import xyz.olivermartin.multichat.local.spigot.listeners.chat.LocalSpigotChatListenerLowest; import xyz.olivermartin.multichat.local.spigot.listeners.chat.LocalSpigotChatListenerMonitor; -import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotActionListener; -import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotCastListener; -import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotIgnoreListener; import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotPlayerActionListener; -import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotPlayerChannelListener; +import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotPlayerChatListener; +import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotPlayerDataListener; import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotPlayerMetaListener; +import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotServerActionListener; +import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotServerChatListener; +import xyz.olivermartin.multichat.local.spigot.listeners.communication.LocalSpigotServerDataListener; public class MultiChatLocalSpigotPlugin extends JavaPlugin { @@ -167,22 +169,17 @@ public void onEnable() { private void registerCommunicationChannels() { - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:comm"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:chat"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:prefix"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:suffix"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:dn"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:world"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:nick"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:pxe"); - getServer().getMessenger().registerOutgoingPluginChannel(this, "multichat:ppxe"); - - getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:comm", new LocalSpigotPlayerMetaListener()); - getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:chat", new LocalSpigotCastListener()); - getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:act", new LocalSpigotActionListener()); - getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:pact", new LocalSpigotPlayerActionListener()); - getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:ch", new LocalSpigotPlayerChannelListener()); - getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:ignore", new LocalSpigotIgnoreListener()); + getServer().getMessenger().registerOutgoingPluginChannel(this, CommChannels.PLAYER_META); + getServer().getMessenger().registerOutgoingPluginChannel(this, CommChannels.PLAYER_CHAT); + getServer().getMessenger().registerOutgoingPluginChannel(this, CommChannels.PLAYER_ACTION); + getServer().getMessenger().registerOutgoingPluginChannel(this, CommChannels.SERVER_ACTION); + getServer().getMessenger().registerIncomingPluginChannel(this, CommChannels.SERVER_CHAT, new LocalSpigotServerChatListener()); + getServer().getMessenger().registerIncomingPluginChannel(this, CommChannels.SERVER_ACTION, new LocalSpigotServerActionListener()); + getServer().getMessenger().registerIncomingPluginChannel(this, CommChannels.PLAYER_ACTION, new LocalSpigotPlayerActionListener()); + getServer().getMessenger().registerIncomingPluginChannel(this, CommChannels.PLAYER_CHAT, new LocalSpigotPlayerChatListener()); + getServer().getMessenger().registerIncomingPluginChannel(this, CommChannels.PLAYER_DATA, new LocalSpigotPlayerDataListener()); + getServer().getMessenger().registerIncomingPluginChannel(this, CommChannels.SERVER_DATA, new LocalSpigotServerDataListener()); + getServer().getMessenger().registerIncomingPluginChannel(this, CommChannels.PLAYER_META, new LocalSpigotPlayerMetaListener()); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/SpigotBungeeCommunicationManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/SpigotBungeeCommunicationManager.java index 0876fac6..d8cdd4bf 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/SpigotBungeeCommunicationManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/SpigotBungeeCommunicationManager.java @@ -3,6 +3,8 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; +import java.io.ObjectOutputStream; +import java.util.Set; import java.util.UUID; import org.bukkit.Bukkit; @@ -122,4 +124,63 @@ protected boolean sendUUIDAndStringAndString(String channel, UUID uuid, String v } + @Override + protected boolean sendUUIDAndStringAndStringAndString(String channel, UUID uuid, String value1, String value2, + String value3) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + try { + + out.writeUTF(uuid.toString()); + out.writeUTF(value1); + out.writeUTF(value2); + out.writeUTF(value3); + + } catch (IOException e) { + + return false; + + } + + if (Bukkit.getServer().getOnlinePlayers().size() < 1) return false; + + ((PluginMessageRecipient)Bukkit.getServer().getOnlinePlayers().toArray()[0]).sendPluginMessage(Bukkit.getPluginManager().getPlugin(MultiChatLocal.getInstance().getPluginName()), channel, stream.toByteArray()); + + return true; + + } + + @Override + protected boolean sendPlatformChatMessage(String channel, UUID uuid, String chatChannel, String message, String format, Set otherRecipients) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + try { + + ObjectOutputStream out = new ObjectOutputStream(stream); + + out.writeUTF(uuid.toString()); + out.writeUTF(chatChannel); + out.writeUTF(message); + out.writeUTF(format); + out.writeObject(otherRecipients); + out.flush(); + + } catch (IOException e) { + + return false; + + } + + if (Bukkit.getServer().getOnlinePlayers().size() < 1) return false; + + ((PluginMessageRecipient)Bukkit.getServer().getOnlinePlayers().toArray()[0]).sendPluginMessage(Bukkit.getPluginManager().getPlugin(MultiChatLocal.getInstance().getPluginName()), channel, stream.toByteArray()); + + return true; + + + } + } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/commands/SpigotNickCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/commands/SpigotNickCommand.java index 4543b332..a5a8a483 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/commands/SpigotNickCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/commands/SpigotNickCommand.java @@ -1,10 +1,14 @@ package xyz.olivermartin.multichat.local.spigot.commands; +import java.util.Optional; +import java.util.UUID; + import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.commands.MultiChatLocalCommandSender; import xyz.olivermartin.multichat.local.common.commands.NickCommand; @@ -17,40 +21,46 @@ public boolean onCommand(CommandSender sender, Command command, String label, St if (!command.getName().equalsIgnoreCase("nick")) return false; - MultiChatLocalCommandSender mccs = new MultiChatLocalSpigotCommandSender(sender); - - if (!mccs.isPlayer()) { - mccs.sendBadMessage("Only players can use this command!"); - return true; - } - - MultiChatLocalPlayer senderPlayer = new MultiChatLocalSpigotPlayer((Player)sender); - if (args.length < 1 || args.length > 2) { return false; } - MultiChatLocalPlayer targetPlayer; + MultiChatLocalCommandSender mccs = new MultiChatLocalSpigotCommandSender(sender); + UUID targetUniqueId; + String proposedNickname; + if (args.length == 1) { - targetPlayer = senderPlayer; - - return executeNickCommand(targetPlayer, senderPlayer, args[0]); + if (!mccs.isPlayer()) { + mccs.sendBadMessage("Only players can have nicknames!"); + return true; + } + + MultiChatLocalPlayer senderPlayer = new MultiChatLocalSpigotPlayer((Player)sender); + + targetUniqueId = senderPlayer.getUniqueId(); + proposedNickname = args[0]; } else { - Player target = sender.getServer().getPlayer(args[0]); + Optional opTargetUniqueId = MultiChatLocal.getInstance().getNameManager().getUUIDFromName(args[0]); - if (target == null) { - mccs.sendBadMessage(args[0] + " is not currently online so cannot be nicknamed!"); + if (!opTargetUniqueId.isPresent()) { + mccs.sendBadMessage(args[0] + " has never joined the server so cannot be nicknamed!"); return true; } + + targetUniqueId = opTargetUniqueId.get(); + proposedNickname = args[1]; - targetPlayer = new MultiChatLocalSpigotPlayer(target); - - return executeNickCommand(targetPlayer, senderPlayer, args[1]); - + } + + if (!mccs.isPlayer()) { + return executeConsoleNickCommand(targetUniqueId, mccs, proposedNickname); + } else { + MultiChatLocalPlayer senderPlayer = new MultiChatLocalSpigotPlayer((Player)sender); + return executeNickCommand(targetUniqueId, senderPlayer, proposedNickname); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/chat/MultiChatLocalSpigotPlayerChatEvent.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/chat/MultiChatLocalSpigotPlayerChatEvent.java index 551327cb..7824554a 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/chat/MultiChatLocalSpigotPlayerChatEvent.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/chat/MultiChatLocalSpigotPlayerChatEvent.java @@ -1,15 +1,13 @@ package xyz.olivermartin.multichat.local.spigot.listeners.chat; +import java.util.HashSet; import java.util.Iterator; -import java.util.Map; import java.util.Set; import java.util.UUID; import org.bukkit.entity.Player; import org.bukkit.event.player.AsyncPlayerChatEvent; -import xyz.olivermartin.multichat.local.common.LocalPseudoChannel; -import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.listeners.chat.MultiChatLocalPlayerChatEvent; import xyz.olivermartin.multichat.local.spigot.MultiChatLocalSpigotPlayer; @@ -62,6 +60,33 @@ public void setCancelled(boolean cancelled) { } @Override + public void removeOtherPlayers() { + + Iterator it = event.getRecipients().iterator(); + + while (it.hasNext()) { + Player p = it.next(); + if (!p.getUniqueId().equals(player.getUniqueId())) it.remove(); + } + + } + + @Override + public Set getOtherRecipients() { + + Set rSet = new HashSet(); + + for (Player p : event.getRecipients()) { + rSet.add(p.getUniqueId()); + } + + rSet.remove(player.getUniqueId()); + + return rSet; + + } + + /*@Override public void removeIgnoredPlayersAndNonChannelMembersFromRecipients(LocalPseudoChannel channel) { MultiChatLocal.getInstance().getConsoleLogger().debug("[MultiChatLocalSpigotChatEvent] Removing Ignored Players and Non Channel Members from recipients!"); @@ -105,6 +130,6 @@ public void removeIgnoredPlayersAndNonChannelMembersFromRecipients(LocalPseudoCh } } - } + }*/ } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerActionListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerActionListener.java index 36db3dc1..ad603ddd 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerActionListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerActionListener.java @@ -4,6 +4,7 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerActionListener; import xyz.olivermartin.multichat.local.spigot.listeners.SpigotBungeeMessage; @@ -13,7 +14,7 @@ public class LocalSpigotPlayerActionListener extends LocalPlayerActionListener i @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("multichat:pact")) return; + if (!channel.equals(CommChannels.PLAYER_ACTION)) return; LocalBungeeMessage lbm = new SpigotBungeeMessage(message); @@ -34,9 +35,4 @@ protected void executeCommandForPlayersMatchingRegex(String playerRegex, String } - @Override - protected void sendChatAsPlayer(String playerName, String rawMessage) { - Bukkit.getServer().getPlayer(playerName).chat(rawMessage); - } - } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerChatListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerChatListener.java new file mode 100644 index 00000000..114596cc --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerChatListener.java @@ -0,0 +1,30 @@ +package xyz.olivermartin.multichat.local.spigot.listeners.communication; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.messaging.PluginMessageListener; + +import xyz.olivermartin.multichat.common.communication.CommChannels; +import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerChatListener; +import xyz.olivermartin.multichat.local.spigot.listeners.SpigotBungeeMessage; + +public class LocalSpigotPlayerChatListener extends LocalPlayerChatListener implements PluginMessageListener { + + @Override + public void onPluginMessageReceived(String channel, Player player, byte[] message) { + + if (!channel.equals(CommChannels.PLAYER_CHAT)) return; + + LocalBungeeMessage lbm = new SpigotBungeeMessage(message); + + handleMessage(lbm); + + } + + @Override + protected void sendChatAsPlayer(String playerName, String rawMessage) { + Bukkit.getServer().getPlayer(playerName).chat(rawMessage); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerChannelListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerDataListener.java similarity index 76% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerChannelListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerDataListener.java index 0d42a705..0b0429f3 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerChannelListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerDataListener.java @@ -7,19 +7,20 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeObjectMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerChannelListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerDataListener; import xyz.olivermartin.multichat.local.spigot.MultiChatLocalSpigotPlayer; import xyz.olivermartin.multichat.local.spigot.listeners.SpigotBungeeObjectMessage; -public class LocalSpigotPlayerChannelListener extends LocalPlayerChannelListener implements PluginMessageListener { +public class LocalSpigotPlayerDataListener extends LocalPlayerDataListener implements PluginMessageListener { @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("multichat:ch")) return; + if (!channel.equals(CommChannels.PLAYER_DATA)) return; try { LocalBungeeObjectMessage lbm = new SpigotBungeeObjectMessage(message); @@ -27,7 +28,7 @@ public void onPluginMessageReceived(String channel, Player player, byte[] messag handleMessage(lbm); } catch (IOException e) { - MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local channel listener..."); + MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local player data listener..."); return; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerMetaListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerMetaListener.java index 37a8d934..ef388b83 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerMetaListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotPlayerMetaListener.java @@ -6,6 +6,7 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerMetaListener; @@ -17,7 +18,7 @@ public class LocalSpigotPlayerMetaListener extends LocalPlayerMetaListener imple @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("multichat:comm")) return; + if (!channel.equals(CommChannels.PLAYER_META)) return; LocalBungeeMessage lbm = new SpigotBungeeMessage(message); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotActionListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerActionListener.java similarity index 71% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotActionListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerActionListener.java index b2f7b0f7..282eddc4 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotActionListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerActionListener.java @@ -4,16 +4,17 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalActionListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalServerActionListener; import xyz.olivermartin.multichat.local.spigot.listeners.SpigotBungeeMessage; -public class LocalSpigotActionListener extends LocalActionListener implements PluginMessageListener { +public class LocalSpigotServerActionListener extends LocalServerActionListener implements PluginMessageListener { @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("multichat:act")) return; + if (!channel.equals(CommChannels.SERVER_ACTION)) return; LocalBungeeMessage lbm = new SpigotBungeeMessage(message); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotCastListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerChatListener.java similarity index 72% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotCastListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerChatListener.java index 072d2c79..27e5609a 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotCastListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerChatListener.java @@ -5,16 +5,17 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalCastListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalServerChatListener; import xyz.olivermartin.multichat.local.spigot.listeners.SpigotBungeeMessage; -public class LocalSpigotCastListener extends LocalCastListener implements PluginMessageListener { +public class LocalSpigotServerChatListener extends LocalServerChatListener implements PluginMessageListener { @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("multichat:chat")) return; + if (!channel.equals(CommChannels.SERVER_CHAT)) return; LocalBungeeMessage lbm = new SpigotBungeeMessage(message); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotIgnoreListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerDataListener.java similarity index 68% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotIgnoreListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerDataListener.java index 6c0de6fe..23e2a43d 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotIgnoreListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/spigot/listeners/communication/LocalSpigotServerDataListener.java @@ -5,25 +5,26 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeObjectMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalIgnoreListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalServerDataListener; import xyz.olivermartin.multichat.local.spigot.listeners.SpigotBungeeObjectMessage; -public class LocalSpigotIgnoreListener extends LocalIgnoreListener implements PluginMessageListener { +public class LocalSpigotServerDataListener extends LocalServerDataListener implements PluginMessageListener { @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("multichat:ignore")) return; + if (!channel.equals(CommChannels.SERVER_DATA)) return; try { - LocalBungeeObjectMessage lbm = new SpigotBungeeObjectMessage(message); + LocalBungeeObjectMessage lbm = new SpigotBungeeObjectMessage(message); handleMessage(lbm); } catch (IOException e) { - MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local ignore listener..."); + MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local server data listener..."); return; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeChatManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeChatManager.java index c2215dc9..657854fe 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeChatManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeChatManager.java @@ -7,28 +7,12 @@ import org.spongepowered.api.text.serializer.TextSerializers; import me.rojo8399.placeholderapi.PlaceholderService; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.local.common.LocalChatManager; -import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.sponge.hooks.LocalSpongePAPIHook; public class LocalSpongeChatManager extends LocalChatManager { - @Override - public String translateColourCodes(String message, boolean rgb) { - - if (rgb) { - message = MultiChatLocal.getInstance().getChatManager().reformatRGB(message); - message = message.replaceAll("&(?=[a-f,0-9,k-o,r,x])", "§"); - message = MultiChatUtil.approximateHexCodes(message); - return TextSerializers.formattingCode('§').serialize(TextSerializers.FORMATTING_CODE.deserialize(message)); - } else { - return TextSerializers.formattingCode('§').serialize(TextSerializers.FORMATTING_CODE.deserialize(message)); - } - - } - @Override public String processExternalPlaceholders(MultiChatLocalPlayer player, String message) { @@ -37,13 +21,13 @@ public String processExternalPlaceholders(MultiChatLocalPlayer player, String me PlaceholderService papi = LocalSpongePAPIHook.getInstance().getHook().get(); Optional opPlayer = Sponge.getServer().getPlayer(player.getUniqueId()); if (opPlayer.isPresent()) { - MultiChatLocal.getInstance().getConsoleLogger().debug("Going into PAPI we have: " + message); - MultiChatLocal.getInstance().getConsoleLogger().debug("Going into PAPI we have (visualised): " + message.replace("&", "(#d)").replace("§", "(#e)")); + //MultiChatLocal.getInstance().getConsoleLogger().debug("Going into PAPI we have: " + message); + //MultiChatLocal.getInstance().getConsoleLogger().debug("Going into PAPI we have (visualised): " + message.replace("&", "(#d)").replace("§", "(#e)")); message = TextSerializers.FORMATTING_CODE.serialize(papi.replaceSourcePlaceholders(message+"#", opPlayer.get())); - MultiChatLocal.getInstance().getConsoleLogger().debug("Serialised we have: " + message); - MultiChatLocal.getInstance().getConsoleLogger().debug("Serialised we have (visualised): " + message.replace("&", "(#d)").replace("§", "(#e)")); + //MultiChatLocal.getInstance().getConsoleLogger().debug("Serialised we have: " + message); + //MultiChatLocal.getInstance().getConsoleLogger().debug("Serialised we have (visualised): " + message.replace("&", "(#d)").replace("§", "(#e)")); // PAPI replaces unknown placeholders with {key}, so change them back to %key%!! message = message.substring(0,message.length()-1); @@ -56,8 +40,8 @@ public String processExternalPlaceholders(MultiChatLocalPlayer player, String me message = message.replace("{WORLD}", "%WORLD%"); message = message.replace("{MODE}", "%MODE%"); - MultiChatLocal.getInstance().getConsoleLogger().debug("After PAPI we have: " + message); - MultiChatLocal.getInstance().getConsoleLogger().debug("After PAPI we have (visualised): " + message.replace("&", "(#d)").replace("§", "(#e)")); + //MultiChatLocal.getInstance().getConsoleLogger().debug("After PAPI we have: " + message); + //MultiChatLocal.getInstance().getConsoleLogger().debug("After PAPI we have (visualised): " + message.replace("&", "(#d)").replace("§", "(#e)")); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeConsoleLogger.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeConsoleLogger.java index 39fb21c9..cc172ea1 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeConsoleLogger.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeConsoleLogger.java @@ -18,8 +18,8 @@ protected void displayMessageUsingLogger(String message) { } @Override - protected void sendColouredMessageToConsoleSender(String message) { - Sponge.getServer().getConsole().sendMessage(TextSerializers.FORMATTING_CODE.deserialize(message)); + protected void sendConsoleMessage(String message) { + Sponge.getServer().getConsole().sendMessage(TextSerializers.formattingCode('§').deserialize(message)); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeFileNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeFileNameManager.java index bf0d8e31..67eb7803 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeFileNameManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeFileNameManager.java @@ -11,6 +11,7 @@ import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.service.user.UserStorageService; +import xyz.olivermartin.multichat.common.MultiChatUtil; import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; import xyz.olivermartin.multichat.local.common.storage.LocalFileNameManager; @@ -136,7 +137,7 @@ public void setNickname(UUID uuid, String nickname) { removeNickname(uuid); } - String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); + String unformattedNickname = MultiChatUtil.stripColorCodes(nickname.toLowerCase(), false); synchronized (mapNickUUID) { @@ -180,7 +181,7 @@ public Optional> getPartialNameMatches(String name) { Collection profiles = uss.getAll(); //Set nameSet = mapNameUUID.keySet(); - name = stripAllFormattingCodes(name.toLowerCase()); + name = MultiChatUtil.stripColorCodes(name.toLowerCase(), false); Set uuidSet = new HashSet(); for (GameProfile gp : profiles) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeMetaManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeMetaManager.java index 18acdbcf..902023a4 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeMetaManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongeMetaManager.java @@ -8,7 +8,6 @@ import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.local.common.LocalMetaManager; import xyz.olivermartin.multichat.local.common.MultiChatLocal; @@ -24,7 +23,7 @@ public String getPrefix(UUID uuid) { Player player = opPlayer.get(); if (player.getOption("prefix").isPresent()) { - return MultiChatUtil.approximateHexCodes(MultiChatUtil.reformatRGB(player.getOption("prefix").get())); + return MultiChatLocal.getInstance().getChatManager().translateColorCodes(player.getOption("prefix").get(), true); } else { return ""; } @@ -45,7 +44,7 @@ public String getSuffix(UUID uuid) { Player player = opPlayer.get(); if (player.getOption("suffix").isPresent()) { - return MultiChatUtil.approximateHexCodes(MultiChatUtil.reformatRGB(player.getOption("suffix").get())); + return MultiChatLocal.getInstance().getChatManager().translateColorCodes(player.getOption("suffix").get(), true); } else { return ""; } @@ -92,10 +91,9 @@ public String getDisplayName(UUID uuid) { displayNameFormat = displayNameFormat.replaceAll("%NAME%", player.getName()); displayNameFormat = displayNameFormat.replaceAll("%PREFIX%", getPrefix(uuid)); displayNameFormat = displayNameFormat.replaceAll("%SUFFIX%", getSuffix(uuid)); - displayNameFormat = MultiChatUtil.reformatRGB(displayNameFormat); - displayNameFormat = displayNameFormat.replaceAll("(?i)&(?=[a-f,0-9,k-o,r,x])", "§"); - displayNameFormat = MultiChatUtil.approximateHexCodes(displayNameFormat); + // Translate codes + displayNameFormat = MultiChatLocal.getInstance().getChatManager().translateColorCodes(displayNameFormat, true); // TODO Sponge doesn't seem to like this... So we tend to work around it by sending back our original string player.offer(Keys.DISPLAY_NAME,Text.of(displayNameFormat)); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongePlaceholderManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongePlaceholderManager.java index ad5963e7..0c47874a 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongePlaceholderManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/LocalSpongePlaceholderManager.java @@ -2,8 +2,8 @@ import java.util.UUID; -import xyz.olivermartin.multichat.bungee.MultiChatUtil; import xyz.olivermartin.multichat.local.common.LocalPlaceholderManager; +import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlatform; public class LocalSpongePlaceholderManager extends LocalPlaceholderManager { @@ -14,10 +14,8 @@ public LocalSpongePlaceholderManager() { @Override public String buildChatFormat(UUID uuid, String format) { - // Reformat any hex codes in the format - format = MultiChatUtil.reformatRGB(format); - format = processMultiChatPlaceholders(uuid, format).replaceAll("(?i)&(?=[a-f,0-9,k-o,r,x])", "§"); - format = MultiChatUtil.approximateHexCodes(format); + format = processMultiChatPlaceholders(uuid, format); + format = MultiChatLocal.getInstance().getChatManager().translateColorCodes(format, true); return format; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/MultiChatLocalSpongePlugin.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/MultiChatLocalSpongePlugin.java index a0601441..51366b10 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/MultiChatLocalSpongePlugin.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/MultiChatLocalSpongePlugin.java @@ -22,6 +22,7 @@ import com.google.inject.Inject; import me.rojo8399.placeholderapi.PlaceholderService; +import xyz.olivermartin.multichat.common.communication.CommChannels; import xyz.olivermartin.multichat.common.database.DatabaseManager; import xyz.olivermartin.multichat.local.common.LocalChatManager; import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; @@ -49,14 +50,15 @@ import xyz.olivermartin.multichat.local.sponge.listeners.chat.LocalSpongeChatListenerHighest; import xyz.olivermartin.multichat.local.sponge.listeners.chat.LocalSpongeChatListenerLowest; import xyz.olivermartin.multichat.local.sponge.listeners.chat.LocalSpongeChatListenerMonitor; -import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongeActionListener; -import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongeCastListener; -import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongeIgnoreListener; import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongePlayerActionListener; -import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongePlayerChannelListener; +import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongePlayerChatListener; +import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongePlayerDataListener; import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongePlayerMetaListener; +import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongeServerActionListener; +import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongeServerChatListener; +import xyz.olivermartin.multichat.local.sponge.listeners.communication.LocalSpongeServerDataListener; -@Plugin(id = "multichat", name = "MultiChat", version = "1.9.5", dependencies = { @Dependency(id = "placeholderapi", optional = true) }) +@Plugin(id = "multichat", name = "MultiChat", version = "1.10", dependencies = { @Dependency(id = "placeholderapi", optional = true) }) public class MultiChatLocalSpongePlugin { @Inject @@ -175,7 +177,7 @@ public void onServerStart(GameStartedServerEvent event) { CommandSpec nicknameCommandSpec = CommandSpec.builder() .description(Text.of("Sponge Nickname Command")) .arguments( - GenericArguments.onlyOne(GenericArguments.player(Text.of("player"))), + GenericArguments.onlyOne(GenericArguments.string(Text.of("player"))), GenericArguments.remainingJoinedStrings(Text.of("message"))) .permission("multichatlocal.nick.self") .executor(new SpongeNickCommand()) @@ -230,43 +232,35 @@ private void registerCommunicationChannels(SpongeBungeeCommunicationManager comm ChannelRegistrar channelRegistrar = Sponge.getGame().getChannelRegistrar(); - ChannelBinding.RawDataChannel commChannel = channelRegistrar.createRawChannel(this, "multichat:comm"); - commManager.registerChannel("multichat:comm", commChannel); - ChannelBinding.RawDataChannel chatChannel = channelRegistrar.createRawChannel(this, "multichat:chat"); - commManager.registerChannel("multichat:chat", chatChannel); - - ChannelBinding.RawDataChannel actionChannel = channelRegistrar.createRawChannel(this, "multichat:act"); - commManager.registerChannel("multichat:act", actionChannel); - ChannelBinding.RawDataChannel playerActionChannel = channelRegistrar.createRawChannel(this, "multichat:pact"); - commManager.registerChannel("multichat:pact", playerActionChannel); - - ChannelBinding.RawDataChannel prefixChannel = channelRegistrar.createRawChannel(this, "multichat:prefix"); - commManager.registerChannel("multichat:prefix", prefixChannel); - ChannelBinding.RawDataChannel suffixChannel = channelRegistrar.createRawChannel(this, "multichat:suffix"); - commManager.registerChannel("multichat:suffix", suffixChannel); - ChannelBinding.RawDataChannel displayNameChannel = channelRegistrar.createRawChannel(this, "multichat:dn"); - commManager.registerChannel("multichat:dn", displayNameChannel); - ChannelBinding.RawDataChannel worldChannel = channelRegistrar.createRawChannel(this, "multichat:world"); - commManager.registerChannel("multichat:world", worldChannel); - ChannelBinding.RawDataChannel nickChannel = channelRegistrar.createRawChannel(this, "multichat:nick"); - commManager.registerChannel("multichat:nick", nickChannel); - ChannelBinding.RawDataChannel channelChannel = channelRegistrar.createRawChannel(this, "multichat:ch"); - commManager.registerChannel("multichat:ch", channelChannel); - ChannelBinding.RawDataChannel ignoreChannel = channelRegistrar.createRawChannel(this, "multichat:ignore"); - commManager.registerChannel("multichat:ignore", ignoreChannel); - - ChannelBinding.RawDataChannel pexecuteChannel = channelRegistrar.createRawChannel(this, "multichat:pxe"); - commManager.registerChannel("multichat:pxe", pexecuteChannel); - ChannelBinding.RawDataChannel ppexecuteChannel = channelRegistrar.createRawChannel(this, "multichat:ppxe"); - commManager.registerChannel("multichat:ppxe", ppexecuteChannel); - - commChannel.addListener(Platform.Type.SERVER, new LocalSpongePlayerMetaListener()); - chatChannel.addListener(Platform.Type.SERVER, new LocalSpongeCastListener()); - channelChannel.addListener(Platform.Type.SERVER, new LocalSpongePlayerChannelListener()); - ignoreChannel.addListener(Platform.Type.SERVER, new LocalSpongeIgnoreListener()); - - actionChannel.addListener(Platform.Type.SERVER, new LocalSpongeActionListener()); + // New channels + ChannelBinding.RawDataChannel playerMetaChannel = channelRegistrar.createRawChannel(this, CommChannels.PLAYER_META); + commManager.registerChannel(CommChannels.PLAYER_META, playerMetaChannel); + + ChannelBinding.RawDataChannel playerChatChannel = channelRegistrar.createRawChannel(this, CommChannels.PLAYER_CHAT); + commManager.registerChannel(CommChannels.PLAYER_CHAT, playerChatChannel); + + ChannelBinding.RawDataChannel serverChatChannel = channelRegistrar.createRawChannel(this, CommChannels.SERVER_CHAT); + commManager.registerChannel(CommChannels.SERVER_CHAT, serverChatChannel); + + ChannelBinding.RawDataChannel serverActionChannel = channelRegistrar.createRawChannel(this, CommChannels.SERVER_ACTION); + commManager.registerChannel(CommChannels.SERVER_ACTION, serverActionChannel); + + ChannelBinding.RawDataChannel playerActionChannel = channelRegistrar.createRawChannel(this, CommChannels.PLAYER_ACTION); + commManager.registerChannel(CommChannels.PLAYER_ACTION, playerActionChannel); + + ChannelBinding.RawDataChannel playerDataChannel = channelRegistrar.createRawChannel(this, CommChannels.PLAYER_DATA); + commManager.registerChannel(CommChannels.PLAYER_DATA, playerDataChannel); + + ChannelBinding.RawDataChannel serverDataChannel = channelRegistrar.createRawChannel(this, CommChannels.SERVER_DATA); + commManager.registerChannel(CommChannels.SERVER_DATA, serverDataChannel); + + serverChatChannel.addListener(Platform.Type.SERVER, new LocalSpongeServerChatListener()); + serverActionChannel.addListener(Platform.Type.SERVER, new LocalSpongeServerActionListener()); playerActionChannel.addListener(Platform.Type.SERVER, new LocalSpongePlayerActionListener()); + playerChatChannel.addListener(Platform.Type.SERVER, new LocalSpongePlayerChatListener()); + playerDataChannel.addListener(Platform.Type.SERVER, new LocalSpongePlayerDataListener()); + serverDataChannel.addListener(Platform.Type.SERVER, new LocalSpongeServerDataListener()); + playerMetaChannel.addListener(Platform.Type.SERVER, new LocalSpongePlayerMetaListener()); } @@ -275,32 +269,27 @@ public void onServerStop(GameStoppingServerEvent event) { SpongeBungeeCommunicationManager commManager = (SpongeBungeeCommunicationManager)MultiChatLocal.getInstance().getProxyCommunicationManager(); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:comm")); - commManager.unregisterChannel("multichat:comm"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:chat")); - commManager.unregisterChannel("multichat:chat"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:act")); - commManager.unregisterChannel("multichat:act"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:pact")); - commManager.unregisterChannel("multichat:pact"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:prefix")); - commManager.unregisterChannel("multichat:prefix"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:suffix")); - commManager.unregisterChannel("multichat:suffix"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:dn")); - commManager.unregisterChannel("multichat:dn"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:nick")); - commManager.unregisterChannel("multichat:nick"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:world")); - commManager.unregisterChannel("multichat:world"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:ch")); - commManager.unregisterChannel("multichat:ch"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:ignore")); - commManager.unregisterChannel("multichat:ignore"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:pxe")); - commManager.unregisterChannel("multichat:pxe"); - Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel("multichat:ppxe")); - commManager.unregisterChannel("multichat:ppxe"); + // New channels + Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel(CommChannels.PLAYER_META)); + commManager.unregisterChannel(CommChannels.PLAYER_META); + + Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel(CommChannels.PLAYER_CHAT)); + commManager.unregisterChannel(CommChannels.PLAYER_CHAT); + + Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel(CommChannels.SERVER_CHAT)); + commManager.unregisterChannel(CommChannels.SERVER_CHAT); + + Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel(CommChannels.PLAYER_ACTION)); + commManager.unregisterChannel(CommChannels.PLAYER_ACTION); + + Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel(CommChannels.SERVER_ACTION)); + commManager.unregisterChannel(CommChannels.SERVER_ACTION); + + Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel(CommChannels.PLAYER_DATA)); + commManager.unregisterChannel(CommChannels.PLAYER_DATA); + + Sponge.getChannelRegistrar().unbindChannel(commManager.getChannel(CommChannels.SERVER_DATA)); + commManager.unregisterChannel(CommChannels.SERVER_DATA); if (MultiChatLocal.getInstance().getNameManager().getMode() == LocalNameManagerMode.SQL) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/SpongeBungeeCommunicationManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/SpongeBungeeCommunicationManager.java index bd56151b..0b9f30a6 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/SpongeBungeeCommunicationManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/SpongeBungeeCommunicationManager.java @@ -1,7 +1,13 @@ package xyz.olivermartin.multichat.local.sponge; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; +import java.util.Set; import java.util.UUID; import org.spongepowered.api.Sponge; @@ -97,4 +103,62 @@ protected boolean sendUUIDAndStringAndString(String channel, UUID uuid, String v return true; } + @Override + protected boolean sendUUIDAndStringAndStringAndString(String channel, UUID uuid, String value1, String value2, + String value3) { + if (!this.channels.containsKey(channel)) throw new IllegalStateException("Sponge Raw Data Channels must first be registered with MultiChat's SpongeBungeeCommunicationManager!"); + + if (Sponge.getServer().getOnlinePlayers().size() < 1) return false; + + Player facilitatingPlayer = (Player) Sponge.getServer().getOnlinePlayers().toArray()[0]; + + this.channels.get(channel).sendTo(facilitatingPlayer, buffer -> buffer.writeUTF(uuid.toString()).writeUTF(value1).writeUTF(value2).writeUTF(value3)); + + return true; + } + + @Override + protected boolean sendPlatformChatMessage(String channel, UUID uuid, String chatChannel, String message, String format, Set otherRecipients) { + + if (!this.channels.containsKey(channel)) throw new IllegalStateException("Sponge Raw Data Channels must first be registered with MultiChat's SpongeBungeeCommunicationManager!"); + + if (Sponge.getServer().getOnlinePlayers().size() < 1) return false; + + Player facilitatingPlayer = (Player) Sponge.getServer().getOnlinePlayers().toArray()[0]; + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + ByteArrayInputStream inputStream; + byte[] byteArray; + + try { + + ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); + + objectOutputStream.writeUTF(uuid.toString()); + objectOutputStream.writeUTF(chatChannel); + objectOutputStream.writeUTF(message); + objectOutputStream.writeUTF(format); + objectOutputStream.writeObject(otherRecipients); + objectOutputStream.flush(); + + inputStream = new ByteArrayInputStream(outputStream.toByteArray()); + + DataInputStream dis = new DataInputStream(inputStream); + + byteArray = new byte[dis.available()]; + + dis.readFully(byteArray);; + + } catch (IOException e) { + e.printStackTrace(); + return false; + } + + this.channels.get(channel).sendTo(facilitatingPlayer, buffer -> buffer.writeBytes(byteArray)); + + return true; + + } + } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/commands/SpongeNickCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/commands/SpongeNickCommand.java index b1ba9baf..97ee2b3a 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/commands/SpongeNickCommand.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/commands/SpongeNickCommand.java @@ -1,6 +1,7 @@ package xyz.olivermartin.multichat.local.sponge.commands; import java.util.Optional; +import java.util.UUID; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; @@ -9,6 +10,7 @@ import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.entity.living.player.Player; +import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.commands.MultiChatLocalCommandSender; import xyz.olivermartin.multichat.local.common.commands.NickCommand; @@ -21,32 +23,30 @@ public CommandResult execute(CommandSource src, CommandContext args) throws Comm MultiChatLocalCommandSender mccs = new MultiChatLocalSpongeCommandSender(src); - if (!mccs.isPlayer()) { - mccs.sendBadMessage("Only players can use this command!"); - return CommandResult.success(); - } - - MultiChatLocalPlayer senderPlayer = new MultiChatLocalSpongePlayer((Player)src); + Optional opTargetName = args.getOne("player"); - Optional opTarget = args.getOne("player"); - - if (!opTarget.isPresent()) { + if (!opTargetName.isPresent()) { mccs.sendBadMessage("That player could not be found!"); return CommandResult.success(); } - Player target = opTarget.get(); + Optional targetUniqueId = MultiChatLocal.getInstance().getNameManager().getUUIDFromName(opTargetName.get()); - if (target == null) { + if (!targetUniqueId.isPresent()) { mccs.sendBadMessage("That player could not be found!"); return CommandResult.success(); } String nickname = args.getOne("message").get(); - MultiChatLocalPlayer targetPlayer = new MultiChatLocalSpongePlayer(target); + boolean status; - boolean status = executeNickCommand(targetPlayer, senderPlayer, nickname); + if (!mccs.isPlayer()) { + status = executeConsoleNickCommand(targetUniqueId.get(), mccs, nickname); + } else { + MultiChatLocalPlayer senderPlayer = new MultiChatLocalSpongePlayer((Player)src); + status = executeNickCommand(targetUniqueId.get(), senderPlayer, nickname); + } if (status) { return CommandResult.success(); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatLocalSpongePlayerChatEvent.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatLocalSpongePlayerChatEvent.java index b28032fe..14435f29 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatLocalSpongePlayerChatEvent.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatLocalSpongePlayerChatEvent.java @@ -3,14 +3,16 @@ import java.util.Collection; import java.util.HashSet; import java.util.Optional; +import java.util.Set; +import java.util.UUID; import org.spongepowered.api.Sponge; +import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.message.MessageChannelEvent; import org.spongepowered.api.text.channel.MessageChannel; import org.spongepowered.api.text.channel.MessageReceiver; import org.spongepowered.api.text.serializer.TextSerializers; -import xyz.olivermartin.multichat.local.common.LocalPseudoChannel; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.listeners.chat.MultiChatLocalPlayerChatEvent; @@ -31,22 +33,22 @@ public MultiChatLocalPlayer getPlayer() { @Override public String getMessage() { - return TextSerializers.formattingCode('§').serialize(event.getFormatter().getBody().toText()); + return TextSerializers.formattingCode('§').serialize(event.getFormatter().getBody().toText()); } @Override public String getFormat() { - return TextSerializers.formattingCode('§').serialize(event.getFormatter().getHeader().toText()); + return TextSerializers.formattingCode('§').serialize(event.getFormatter().getHeader().toText()); } @Override public void setMessage(String message) { - event.getFormatter().setBody(TextSerializers.formattingCode('§').deserialize(message)); + event.getFormatter().setBody(TextSerializers.formattingCode('§').deserialize(message)); } @Override public void setFormat(String format) { - event.getFormatter().setHeader(TextSerializers.formattingCode('§').deserialize(format)); + event.getFormatter().setHeader(TextSerializers.formattingCode('§').deserialize(format)); } @Override @@ -60,6 +62,46 @@ public void setCancelled(boolean cancelled) { } @Override + public void removeOtherPlayers() { + + Optional currentChannel = event.getChannel(); + Collection recipients; + if (currentChannel.isPresent()) { + recipients = currentChannel.get().getMembers(); + } else { + recipients = new HashSet(Sponge.getServer().getOnlinePlayers()); + } + MultiChatMessageChannel messageChannel = new MultiChatMessageChannel(player, recipients); + event.setChannel(messageChannel); + + } + + @Override + public Set getOtherRecipients() { + + Set rSet = new HashSet(); + Optional currentChannel = event.getChannel(); + Collection recipients; + + if (currentChannel.isPresent()) { + recipients = currentChannel.get().getMembers(); + } else { + recipients = new HashSet(Sponge.getServer().getOnlinePlayers()); + } + + for (MessageReceiver r : recipients) { + if (r instanceof Player) { + rSet.add(((Player)r).getUniqueId()); + } + } + + rSet.remove(player.getUniqueId()); + + return rSet; + + } + + /*@Override public void removeIgnoredPlayersAndNonChannelMembersFromRecipients(LocalPseudoChannel channel) { channel = null; // TODO Ignored for Sponge... Optional currentChannel = event.getChannel(); @@ -71,6 +113,6 @@ public void removeIgnoredPlayersAndNonChannelMembersFromRecipients(LocalPseudoCh } MultiChatMessageChannel messageChannel = new MultiChatMessageChannel(player, recipients); event.setChannel(messageChannel); - } + }*/ } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatMessageChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatMessageChannel.java index fe0d2f11..32585b34 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatMessageChannel.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/chat/MultiChatMessageChannel.java @@ -3,19 +3,13 @@ import java.util.Collection; import java.util.HashSet; import java.util.Iterator; -import java.util.Map; -import java.util.Optional; import java.util.Set; -import java.util.UUID; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.channel.MessageReceiver; import org.spongepowered.api.text.channel.impl.SimpleMutableMessageChannel; -import xyz.olivermartin.multichat.local.common.LocalConsoleLogger; -import xyz.olivermartin.multichat.local.common.LocalPseudoChannel; -import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; public class MultiChatMessageChannel extends SimpleMutableMessageChannel { @@ -30,7 +24,21 @@ public MultiChatMessageChannel(MultiChatLocalPlayer sender, Collection recipients = new HashSet(originalRecipients); - LocalConsoleLogger logger = MultiChatLocal.getInstance().getConsoleLogger(); + Iterator it = recipients.iterator(); + + while (it.hasNext()) { + + MessageReceiver p = it.next(); + + if (p instanceof Player) { + + if (!((Player) p).getUniqueId().equals(sender.getUniqueId())) it.remove(); + + } + + } + + /*LocalConsoleLogger logger = MultiChatLocal.getInstance().getConsoleLogger(); logger.debug("Creating new MultiChatMessageChannel for " + sender.getName()); @@ -93,12 +101,13 @@ public MultiChatMessageChannel(MultiChatLocalPlayer sender, Collection opPlayer = Sponge.getServer().getPlayer(playerName); - if (opPlayer.isPresent()) { - EventContext context = EventContext.builder() - .add(EventContextKeys.PLAYER_SIMULATED, opPlayer.get().getProfile()) - .add(EventContextKeys.PLUGIN, Sponge.getPluginManager().getPlugin(MultiChatLocal.getInstance().getPluginName()).get()) - .build(); - opPlayer.get().simulateChat(Text.of(rawMessage), Cause.builder().append(opPlayer.get()).append(Sponge.getPluginManager().getPlugin(MultiChatLocal.getInstance().getPluginName()).get()).build(context)); - } - - } - } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerChatListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerChatListener.java new file mode 100644 index 00000000..5a25488f --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerChatListener.java @@ -0,0 +1,46 @@ +package xyz.olivermartin.multichat.local.sponge.listeners.communication; + +import java.util.Optional; + +import org.spongepowered.api.Platform.Type; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.EventContext; +import org.spongepowered.api.event.cause.EventContextKeys; +import org.spongepowered.api.network.ChannelBuf; +import org.spongepowered.api.network.RawDataListener; +import org.spongepowered.api.network.RemoteConnection; +import org.spongepowered.api.text.Text; + +import xyz.olivermartin.multichat.local.common.MultiChatLocal; +import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerChatListener; +import xyz.olivermartin.multichat.local.sponge.listeners.SpongeBungeeMessage; + +public class LocalSpongePlayerChatListener extends LocalPlayerChatListener implements RawDataListener { + + @Override + public void handlePayload(ChannelBuf data, RemoteConnection connection, Type side) { + + LocalBungeeMessage lbm = new SpongeBungeeMessage(data); + + handleMessage(lbm); + + } + + @Override + protected void sendChatAsPlayer(String playerName, String rawMessage) { + + Optional opPlayer = Sponge.getServer().getPlayer(playerName); + if (opPlayer.isPresent()) { + EventContext context = EventContext.builder() + .add(EventContextKeys.PLAYER_SIMULATED, opPlayer.get().getProfile()) + .add(EventContextKeys.PLUGIN, Sponge.getPluginManager().getPlugin(MultiChatLocal.getInstance().getPluginName()).get()) + .build(); + opPlayer.get().simulateChat(Text.of(rawMessage), Cause.builder().append(opPlayer.get()).append(Sponge.getPluginManager().getPlugin(MultiChatLocal.getInstance().getPluginName()).get()).build(context)); + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerChannelListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerDataListener.java similarity index 84% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerChannelListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerDataListener.java index 7afed239..51a254c2 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerChannelListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongePlayerDataListener.java @@ -13,11 +13,11 @@ import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.MultiChatLocalPlayer; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeObjectMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerChannelListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalPlayerDataListener; import xyz.olivermartin.multichat.local.sponge.MultiChatLocalSpongePlayer; import xyz.olivermartin.multichat.local.sponge.listeners.SpongeBungeeObjectMessage; -public class LocalSpongePlayerChannelListener extends LocalPlayerChannelListener implements RawDataListener { +public class LocalSpongePlayerDataListener extends LocalPlayerDataListener implements RawDataListener { @Override public void handlePayload(ChannelBuf data, RemoteConnection connection, Type side) { @@ -28,7 +28,7 @@ public void handlePayload(ChannelBuf data, RemoteConnection connection, Type sid handleMessage(lbm); } catch (IOException e) { - MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local channel listener..."); + MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local player data listener..."); return; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeActionListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerActionListener.java similarity index 83% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeActionListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerActionListener.java index 01d1c7f3..bf292ceb 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeActionListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerActionListener.java @@ -7,10 +7,10 @@ import org.spongepowered.api.network.RemoteConnection; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalActionListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalServerActionListener; import xyz.olivermartin.multichat.local.sponge.listeners.SpongeBungeeMessage; -public class LocalSpongeActionListener extends LocalActionListener implements RawDataListener { +public class LocalSpongeServerActionListener extends LocalServerActionListener implements RawDataListener { @Override public void handlePayload(ChannelBuf data, RemoteConnection connection, Type side) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeCastListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerChatListener.java similarity index 85% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeCastListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerChatListener.java index 05be7543..0f62bb8e 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeCastListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerChatListener.java @@ -8,10 +8,10 @@ import org.spongepowered.api.text.serializer.TextSerializers; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalCastListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalServerChatListener; import xyz.olivermartin.multichat.local.sponge.listeners.SpongeBungeeMessage; -public class LocalSpongeCastListener extends LocalCastListener implements RawDataListener { +public class LocalSpongeServerChatListener extends LocalServerChatListener implements RawDataListener { @Override public void handlePayload(ChannelBuf data, RemoteConnection connection, Type side) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeIgnoreListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerDataListener.java similarity index 79% rename from multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeIgnoreListener.java rename to multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerDataListener.java index d8503044..f3a912ad 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeIgnoreListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/local/sponge/listeners/communication/LocalSpongeServerDataListener.java @@ -9,21 +9,21 @@ import xyz.olivermartin.multichat.local.common.MultiChatLocal; import xyz.olivermartin.multichat.local.common.listeners.LocalBungeeObjectMessage; -import xyz.olivermartin.multichat.local.common.listeners.communication.LocalIgnoreListener; +import xyz.olivermartin.multichat.local.common.listeners.communication.LocalServerDataListener; import xyz.olivermartin.multichat.local.sponge.listeners.SpongeBungeeObjectMessage; -public class LocalSpongeIgnoreListener extends LocalIgnoreListener implements RawDataListener { +public class LocalSpongeServerDataListener extends LocalServerDataListener implements RawDataListener { @Override public void handlePayload(ChannelBuf data, RemoteConnection connection, Type side) { try { - LocalBungeeObjectMessage lbm = new SpongeBungeeObjectMessage(data); + LocalBungeeObjectMessage lbm = new SpongeBungeeObjectMessage(data); handleMessage(lbm); } catch (IOException e) { - MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local ignore listener..."); + MultiChatLocal.getInstance().getConsoleLogger().log("An error occurred reading the object stream in the local server data listener..."); return; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/MultiChatProxy.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/MultiChatProxy.java index d8fc39f5..8fe35e58 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/MultiChatProxy.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/MultiChatProxy.java @@ -1,5 +1,14 @@ package xyz.olivermartin.multichat.proxy.common; +import java.io.File; + +import net.md_5.bungee.api.plugin.Plugin; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.channels.TagManager; +import xyz.olivermartin.multichat.proxy.common.contexts.ContextManager; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyFileStoreManager; + /** * This is MultiChat's API running on the network proxy server * @@ -20,10 +29,99 @@ public static MultiChatProxy getInstance() { /* END STATIC */ - // TODO Add attributes + private MultiChatProxyPlatform platform; + private Plugin plugin; + private File configDirectory; + private ProxyDataStore dataStore; + private ProxyFileStoreManager fileStoreManager; + private ProxyBackupManager backupManager; + private ContextManager contextManager; + private ChannelManager channelManager; + private ProxyChatManager chatManager; + private TagManager tagManager; /* END ATTRIBUTES */ private MultiChatProxy() { /* EMPTY */ } + public Plugin getPlugin() { + return this.plugin; + } + + public void registerPlugin(Plugin plugin) { + this.plugin = plugin; + } + + public MultiChatProxyPlatform getPlatform() { + return this.platform; + } + + public void registerPlatform(MultiChatProxyPlatform platform) { + this.platform = platform; + } + + public File getConfigDirectory() { + return this.configDirectory; + } + + public void registerConfigDirectory(File configDirectory) { + this.configDirectory = configDirectory; + } + + public ProxyDataStore getDataStore() { + return this.dataStore; + } + + public void registerDataStore(ProxyDataStore dataStore) { + this.dataStore = dataStore; + } + + public ProxyFileStoreManager getFileStoreManager() { + return this.fileStoreManager; + } + + public void registerFileStoreManager(ProxyFileStoreManager fileStoreManager) { + this.fileStoreManager = fileStoreManager; + } + + public ProxyBackupManager getBackupManager() { + return this.backupManager; + } + + public void registerBackupManager(ProxyBackupManager backupManager) { + this.backupManager = backupManager; + } + + public ContextManager getContextManager() { + return this.contextManager; + } + + public void registerContextManager(ContextManager contextManager) { + this.contextManager = contextManager; + } + + public ChannelManager getChannelManager() { + return this.channelManager; + } + + public void registerChannelManager(ChannelManager channelManager) { + this.channelManager = channelManager; + } + + public ProxyChatManager getChatManager() { + return this.chatManager; + } + + public void registerChatManager(ProxyChatManager chatManager) { + this.chatManager = chatManager; + } + + public TagManager getTagManager() { + return this.tagManager; + } + + public void registerTagManager(TagManager tagManager) { + this.tagManager = tagManager; + } + } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyBackupManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyBackupManager.java new file mode 100644 index 00000000..d237de5d --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyBackupManager.java @@ -0,0 +1,48 @@ +package xyz.olivermartin.multichat.proxy.common; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.scheduler.ScheduledTask; + +public class ProxyBackupManager { + + private List backupTasks; + private ScheduledTask scheduledTask; + + public ProxyBackupManager() { + backupTasks = new ArrayList(); + } + + public void registerBackupTask(Runnable task) { + backupTasks.add(task); + } + + public void startBackup(long delay, long period, TimeUnit unit) { + + scheduledTask = ProxyServer.getInstance().getScheduler().schedule(MultiChatProxy.getInstance().getPlugin(), new Runnable() { + + public void run() { + + MultiChatProxy.getInstance().getPlugin().getLogger().info("Commencing backup!"); + + for (Runnable r : backupTasks) { + r.run(); + } + + MultiChatProxy.getInstance().getPlugin().getLogger().info("Backup complete. Any errors reported above."); + + } + + }, delay, period, unit); + + } + + public void stopBackup() { + if (scheduledTask == null) return; + scheduledTask.cancel(); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyChatManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyChatManager.java new file mode 100644 index 00000000..ac1d1980 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyChatManager.java @@ -0,0 +1,193 @@ +package xyz.olivermartin.multichat.proxy.common; + +import java.util.Optional; + +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.bungee.ChatControl; +import xyz.olivermartin.multichat.bungee.DebugManager; +import xyz.olivermartin.multichat.bungee.PlayerMeta; +import xyz.olivermartin.multichat.bungee.PlayerMetaManager; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +public class ProxyChatManager { + + public ProxyChatManager() { + /* EMPTY */ + } + + /** + * Check if the player has permission to use simple colour codes in chat + * @param player The player to check + * @return true if they have permission + */ + public boolean hasSimpleColourPermission(ProxiedPlayer player) { + return player.hasPermission("multichat.chat.colour.simple") + || player.hasPermission("multichat.chat.color.simple") + || hasRGBColourPermission(player); + } + + /** + * Check if the player has permission to use RGB colour codes in chat + * @param player The player to check + * @return true if they have permission + */ + public boolean hasRGBColourPermission(ProxiedPlayer player) { + return player.hasPermission("multichat.chat.colour.rgb") + || player.hasPermission("multichat.chat.color.rgb") + || hasLegacyColourPermission(player); + } + + /** + * Check if the player has permission to use all colour codes in chat (legacy permission) + * @param player The player to check + * @return true if they have permission + */ + public boolean hasLegacyColourPermission(ProxiedPlayer player) { + return player.hasPermission("multichat.chat.colour") + || player.hasPermission("multichat.chat.color"); + } + + /** + *

Check if this player is allowed to send a chat message

+ *

Possible reasons for not being allowed are: + *

    + *
  • Chat is frozen
  • + *
  • Player is muted by MultiChat
  • + *
  • Player is spamming
  • + *
+ *

+ * @param player The player to check + * @param message The message they are trying to send + * @return true if they are allowed to send a message + */ + private boolean canPlayerSendChat(ProxiedPlayer player, String message) { + + // Check if chat is frozen + if (MultiChatProxy.getInstance().getDataStore().isChatFrozen() && !player.hasPermission("multichat.chat.always")) { + ProxyConfigs.MESSAGES.sendMessage(player, "freezechat_frozen"); + return false; + } + + // Check if they are muted by MultiChat + if (ChatControl.isMuted(player.getUniqueId(), MessageType.GLOBAL_CHAT)) { + ProxyConfigs.MESSAGES.sendMessage(player, "mute_cannot_send_message"); + return false; + } + + // Check if they are spamming + if (ChatControl.handleSpam(player, message, MessageType.GLOBAL_CHAT)) { + DebugManager.log(player.getName() + " - chat message being cancelled due to spam"); + return false; + } + + return true; + + } + + /** + *

Pre-processes a chat message before sending it

+ *

This includes the following: + *

    + *
  • Applying regex rules and actions
  • + *
  • Filtering links if they player does not have permission
  • + *
+ *

+ * @param player The player to check + * @param message The message they are trying to send + * @return the new processed string if they are allowed to send the message, or empty if the message should be cancelled + */ + private Optional preProcessMessage(ProxiedPlayer player, String message) { + + Optional crm; + + crm = ChatControl.applyChatRules(player, message, MessageType.GLOBAL_CHAT); + + if (crm.isPresent()) { + message = crm.get(); + } else { + return Optional.empty(); + } + + if (!player.hasPermission("multichat.chat.link")) { + message = ProxyConfigs.CHAT_CONTROL.replaceLinks(message); + } + + return Optional.of(message); + + } + + /** + *

Handles the process of getting a message ready to send from the proxy

+ *

This includes the following: + *

    + *
  • Makes sure chat is not frozen
  • + *
  • Makes sure the player is not muted by MultiChat
  • + *
  • Makes sure the player is not spamming
  • + *
  • Applies regex rules and actions to message
  • + *
  • Filters links if they player does not have permission
  • + *
+ *

+ * @param player The player to check + * @param message The message they are trying to send + * @return the new processed string if they are allowed to send the message, or empty if the message should be cancelled + */ + public Optional handleChatMessage(ProxiedPlayer player, String message) { + + if (!canPlayerSendChat(player, message)) { + return Optional.empty(); + } + + return preProcessMessage(player, message); + + } + + public String getLocalSpyMessage(ProxiedPlayer player, String format, String message) { + + String spyFormat = ProxyConfigs.CONFIG.getLocalSpyFormat(); + + spyFormat = spyFormat.replace("%FORMAT%", format); + spyFormat = spyFormat.replace("%DISPLAYNAME%", player.getDisplayName()); + spyFormat = spyFormat.replace("%NAME%", player.getName()); + + Optional opm = PlayerMetaManager.getInstance().getPlayer(player.getUniqueId()); + if (opm.isPresent()) { + spyFormat = spyFormat.replace("%PREFIX%", opm.get().prefix); + spyFormat = spyFormat.replace("%SUFFIX%", opm.get().suffix); + spyFormat = spyFormat.replace("%NICK%", opm.get().nick); + spyFormat = spyFormat.replace("%WORLD%", opm.get().world); + } + + spyFormat = spyFormat.replace("%SERVER%", player.getServer().getInfo().getName()); + spyFormat = ChatColor.translateAlternateColorCodes('&', spyFormat); + + // Append message + spyFormat = spyFormat + message; + + return spyFormat; + + } + + public String getLocalSpyMessage(CommandSender sender, String message) { + + String spyFormat = ProxyConfigs.CONFIG.getLocalSpyFormat(); + + spyFormat = spyFormat.replace("%FORMAT%", ""); + spyFormat = spyFormat.replace("%DISPLAYNAME%", sender.getName()); + spyFormat = spyFormat.replace("%NAME%", sender.getName()); + + spyFormat = spyFormat.replace("%PREFIX%", ""); + spyFormat = spyFormat.replace("%SUFFIX%", ""); + spyFormat = spyFormat.replace("%NICK%", sender.getName()); + spyFormat = spyFormat.replace("%WORLD%", ""); + + spyFormat = spyFormat.replace("%SERVER%", ""); + spyFormat = ChatColor.translateAlternateColorCodes('&', spyFormat); + + return spyFormat + message; + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyJsonUtils.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyJsonUtils.java new file mode 100644 index 00000000..8122986b --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyJsonUtils.java @@ -0,0 +1,225 @@ +package xyz.olivermartin.multichat.proxy.common; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.JsonParser; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.chat.ComponentSerializer; + +public class ProxyJsonUtils { + + public static final String WITH_DELIMITER = "((?<=(%1$s))|(?=(%1$s)))"; + + /** + *

Parses a single node of a MultiChat message as legacy text and returns the BaseComponent[]

+ * @param rawMessage The raw message node to parse + * @return the parsed BaseComponent[] ready for sending + */ + private static BaseComponent[] parseNodeAsLegacy(String rawMessage) { + return TextComponent.fromLegacyText(rawMessage); + } + + /** + *

Parses a single node of a MultiChat message (which might be Json) and returns the BaseComponent[]

+ *

If the string is not Json text, it is treated as legacy text

+ * @param rawMessage The raw message node (which might be Json) to parse + * @return the parsed BaseComponent[] ready for sending + */ + private static BaseComponent[] parseNode(String rawMessage) { + + if (isValidJson(rawMessage)) { + return ComponentSerializer.parse(rawMessage); + } else { + return TextComponent.fromLegacyText(rawMessage); + } + + } + + /** + *

Parses a single node of a MultiChat message (which might be Json) and returns the BaseComponent[]

+ *

If the string is not Json text, it is treated as legacy text

+ *

This method allows for a partially substituted message node

+ *

You can specify a placeholder and its replacement which will be parsed as legacy text within the rest of the node

+ *

This is useful for user %MESSAGE%s which you do not want to be parsed as JSON

+ * @param rawMessage The raw message node (which might be Json) to parse + * @param placeholder The placeholder to be substituted + * @param replacement The replacement value for the placeholder (substituted as legacy text) + * @return the parsed BaseComponent[] ready for sending + */ + private static BaseComponent[] parsePartialNode(String rawMessage, String placeholder, String replacement) { + + if (placeholder == null || replacement == null) return parseNode(rawMessage); + + String[] split = rawMessage.split(String.format(WITH_DELIMITER, placeholder), -1); + BaseComponent[][] result = new BaseComponent[split.length][]; + + int counter = 0; + for (String s : split) { + + if (s.equals(placeholder)) { + result[counter++] = parseNodeAsLegacy(replacement); + } else { + result[counter++] = parseNode(s); + } + + } + + return merge(true, result); + + } + + /** + *

Parses an entire MultiChat message (which might include Json) and returns the BaseComponent[]

+ *

If the string is not Json text, it is treated as legacy text

+ *

The concatenation operator +++, and injection operator >>>, will also be parsed

+ * @param rawMessage The raw message (which might include Json) to parse + * @return the parsed BaseComponent[] ready for sending + */ + public static BaseComponent[] parseMessage(String rawMessage) { + return parseConcatenations(rawMessage, null, null); + } + + /** + *

Parses an entire MultiChat message (which might include Json) and returns the BaseComponent[]

+ *

If the string is not Json text, it is treated as legacy text

+ *

The concatenation operator +++, and injection operator >>>, will also be parsed

+ *

This method allows for a partially substituted message node

+ *

You can specify a placeholder and its replacement which will be parsed as legacy text within the rest of the node

+ *

This is useful for user %MESSAGE%s which you do not want to be parsed as JSON

+ * @param rawMessage The raw message (which might include Json) to parse + * @param placeholder The placeholder to be substituted + * @param replacement The replacement value for the placeholder (substituted as legacy text) + * @return the parsed BaseComponent[] ready for sending + */ + public static BaseComponent[] parseMessage(String rawMessage, String placeholder, String replacement) { + return parseConcatenations(rawMessage, placeholder, replacement); + } + + /* + * Parses the concatenations in a MultiChat message + */ + private static BaseComponent[] parseConcatenations(String rawMessage, String placeholder, String replacement) { + + String[] split = rawMessage.split("\\+\\+\\+"); + + List parsed = new ArrayList(); + int size = 0; + + for (String s : split) { + BaseComponent[] next = parseInjections(s, placeholder, replacement); + parsed.add(next); + size += next.length; + } + + BaseComponent[][] bcaa = new BaseComponent[parsed.size()][]; + + return merge(false, size, parsed.toArray(bcaa)); + + } + + /* + * Parses the injections in a MultiChat message + */ + private static BaseComponent[] parseInjections(String rawMessage, String placeholder, String replacement) { + + String[] split = rawMessage.split(">>>"); + + List parsed = new ArrayList(); + int size = 0; + + for (String s : split) { + BaseComponent[] next = parsePartialNode(s, placeholder, replacement); + parsed.add(next); + size += next.length; + } + + BaseComponent[][] bcaa = new BaseComponent[parsed.size()][]; + + return merge(true, size, parsed.toArray(bcaa)); + + } + + /** + * Merge together multiple entirely separate base component arrays + * @param injectFormatting If the formatting from the previous base component should be injected into the next + * @param baseComponentArrays The base component arrays to merge + * @return the concatenated array + */ + public static BaseComponent[] merge(boolean injectFormatting, BaseComponent[]... baseComponentArrays) { + return merge( + injectFormatting, + Arrays.stream(baseComponentArrays).mapToInt(bca -> bca.length).sum(), + baseComponentArrays); + } + + /** + * Merge together multiple entirely separate base component arrays + * @param injectFormatting If the formatting from the previous base component should be injected into the next + * @param size The length of the new array + * @param baseComponentArrays The base component arrays to merge + * @return the concatenated array + */ + public static BaseComponent[] merge(boolean injectFormatting, int size, BaseComponent[]... baseComponentArrays) { + + BaseComponent[] merged = new BaseComponent[size]; + BaseComponent previous = null; + boolean first = true; + + int counter = 0; + for (BaseComponent[] bca : baseComponentArrays) { + + for (BaseComponent bc : bca) { + if (!first && injectFormatting && previous != null) bc.copyFormatting(previous, false); + merged[counter++] = bc; + } + + previous = bca[bca.length-1]; + first = false; + + } + + return merged; + + } + + /** + *

Checks if a string is a valid json message or not

+ * @param json The string to check + * @return true if is valid json + */ + public static boolean isValidJson(String json) { + + if (!isSafeMinecraftJson(json)) return false; + + try { + + return new JsonParser().parse(json).getAsJsonObject() != null; + + } catch (Throwable ignored) { + + try { + return new JsonParser().parse(json).getAsJsonArray() != null; + } catch (Throwable ignored2) { + return false; + } + + } + + } + + /* + * Checks if the json can be safely parsed by Minecraft + */ + private static boolean isSafeMinecraftJson(String json) { + try { + return ComponentSerializer.parse(json) != null; + } catch (Throwable ignored) { + return false; + } + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyLocalCommunicationManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyLocalCommunicationManager.java new file mode 100644 index 00000000..0470fee5 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/ProxyLocalCommunicationManager.java @@ -0,0 +1,262 @@ +package xyz.olivermartin.multichat.proxy.common; + +import net.md_5.bungee.api.config.ServerInfo; +import xyz.olivermartin.multichat.bungee.DebugManager; +import xyz.olivermartin.multichat.common.communication.CommChannels; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; + +/** + * Proxy -> Local communication manager + *

Manages all plugin messaging channels on the BungeeCord side

+ * + * @author Oliver Martin (Revilo410) + * + */ +public class ProxyLocalCommunicationManager { + + public static void sendGlobalServerData(ServerInfo server) { + + DebugManager.log("About to send to multichat:sdata on the global id"); + + /* + * This is for the sdata channel id: global + * + * Other ids are: + * - global = Global chat info + * - dn = display name info + * - legacy = legacy server info + */ + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + try { + + ObjectOutputStream out = new ObjectOutputStream(stream); + + boolean globalChatServer = ProxyConfigs.CONFIG.isGlobal() && ProxyConfigs.CONFIG.isGlobalServer(server.getName()); + String globalChatFormat = MultiChatProxy.getInstance().getChannelManager().getGlobalChannel().getInfo().getFormat(); + + out.writeUTF("global"); + out.writeBoolean(globalChatServer); + out.writeUTF(globalChatFormat); + out.flush(); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.SERVER_DATA, stream.toByteArray()); + + DebugManager.log("Completed send on multichat:sdata on the global id"); + + } + + public static void sendDisplayNameServerData(ServerInfo server) { + + DebugManager.log("About to send to multichat:sdata on the dn id"); + + /* + * This is for the sdata channel id: dn + * + * Other ids are: + * - global = Global chat info + * - dn = display name info + * - legacy = legacy server info + */ + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + try { + + ObjectOutputStream out = new ObjectOutputStream(stream); + + boolean setDisplayName = ProxyConfigs.CONFIG.isSetDisplayName(); + String displayNameFormat = ProxyConfigs.CONFIG.getDisplayNameFormat(); + + out.writeUTF("dn"); + out.writeBoolean(setDisplayName); + out.writeUTF(displayNameFormat); + out.flush(); + + DebugManager.log("setDisplayName = " + setDisplayName); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.SERVER_DATA, stream.toByteArray()); + + DebugManager.log("Completed send to multichat:sdata on the dn id"); + + } + + public static void sendLegacyServerData(ServerInfo server) { + + DebugManager.log("About to send to multichat:sdata on the legacy id"); + + /* + * This is for the sdata channel id: legacy + * + * Other ids are: + * - global = Global chat info + * - dn = display name info + * - legacy = legacy server info + */ + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + try { + + ObjectOutputStream out = new ObjectOutputStream(stream); + + boolean isLegacy = ProxyConfigs.CONFIG.isLegacyServer(server.getName()); + + DebugManager.log("isLegacy = " + isLegacy); + + out.writeUTF("legacy"); + out.writeBoolean(isLegacy); + out.flush(); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.SERVER_DATA, stream.toByteArray()); + + DebugManager.log("Completed send to multichat:sdata on the legacy id"); + + } + + public static void sendUpdatePlayerMetaRequestMessage(String playerName, ServerInfo server) { + + DebugManager.log("About to send update player meta request!"); + sendDisplayNameServerData(server); + sendGlobalServerData(server); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + try { + + // Command + out.writeUTF(playerName); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.PLAYER_META, stream.toByteArray()); + DebugManager.log("Request sent!"); + + } + + public static void sendCommandMessage(String command, ServerInfo server) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + try { + + // Command + out.writeUTF(command); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.SERVER_ACTION, stream.toByteArray()); + + } + + public static void sendPlayerCommandMessage(String command, String playerRegex, ServerInfo server) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + try { + + // Command + out.writeUTF(playerRegex); + out.writeUTF(command); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.PLAYER_ACTION, stream.toByteArray()); + + } + + public static void sendPlayerDirectChatMessage(String channel, String player, String chatMessage, ServerInfo server) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + try { + + out.writeUTF(channel); + out.writeUTF(player); + out.writeUTF(chatMessage); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.PLAYER_CHAT, stream.toByteArray()); + + } + + public static void sendServerChatMessage(String channel, String message, ServerInfo server) { + + // This has been repurposed to send casts to local chat streams! + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + + try { + // message part + out.writeUTF(channel); + out.writeUTF(message); + + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.SERVER_CHAT, stream.toByteArray()); + + } + + public static void sendPlayerDataMessage(String playerName, String channel, String channelFormat, ServerInfo server, boolean colour, boolean rgb) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + try { + ObjectOutputStream oout = new ObjectOutputStream(stream); + + // Players name + oout.writeUTF(playerName); + // Channel part + oout.writeUTF(channel); + oout.writeUTF(channelFormat); + oout.writeBoolean(colour); + oout.writeBoolean(rgb); + oout.flush(); + + } catch (IOException e) { + e.printStackTrace(); + } + + server.sendData(CommChannels.PLAYER_DATA, stream.toByteArray()); + + DebugManager.log("Sent message on multichat:pdata channel!"); + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/ChannelManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/ChannelManager.java new file mode 100644 index 00000000..bbbef73c --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/ChannelManager.java @@ -0,0 +1,133 @@ +package xyz.olivermartin.multichat.proxy.common.channels; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.bungee.DebugManager; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.channels.local.LocalChannel; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.GlobalStaticProxyChannel; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.ProxyChannel; +import xyz.olivermartin.multichat.proxy.common.contexts.ContextManager; + +public class ChannelManager { + + // Local Channel Management + private LocalChannel local; + + // Proxy Channel Management + private Map proxyChannels; + private GlobalStaticProxyChannel global; + + // Player preferences for channels + private Map selectedChannels; + private Map> hiddenChannels; + + public ChannelManager() { + proxyChannels = new HashMap(); + selectedChannels = new HashMap(); + hiddenChannels = new HashMap>(); + } + + public Optional getProxyChannel(String channelId) { + return Optional.ofNullable(proxyChannels.get(channelId)); + } + + public String getChannel(ProxiedPlayer player) { + + DebugManager.log("Getting channel for: " + player.getName()); + UUID uuid = player.getUniqueId(); + + if (selectedChannels.containsKey(uuid)) { + DebugManager.log("Their UUID has a selected channel..."); + String channel = selectedChannels.get(uuid); + DebugManager.log("Their channel=" + channel); + return channel; + } else { + DebugManager.log("They don't yet have a selected channel"); + ContextManager cm = MultiChatProxy.getInstance().getContextManager(); + String defaultChannel = cm.getContext(player).getDefaultChannel(); + DebugManager.log("Default channel for their context is..." + defaultChannel); + select(player.getUniqueId(), defaultChannel); + return defaultChannel; + } + } + + public ChannelMode getChannelMode(UUID uuid) { + + if (selectedChannels.containsKey(uuid)) { + if (selectedChannels.get(uuid).equals("local")) return ChannelMode.LOCAL; + } + + return ChannelMode.PROXY; + + } + + public GlobalStaticProxyChannel getGlobalChannel() { + return this.global; + } + + public LocalChannel getLocalChannel() { + return this.local; + } + + public void setGlobalChannel(GlobalStaticProxyChannel global) { + this.global = global; + proxyChannels.remove("global"); + proxyChannels.put("global", global); + } + + public void setLocalChannel(LocalChannel local) { + this.local = local; + } + + public void registerProxyChannel(ProxyChannel channel) { + proxyChannels.put(channel.getId(), channel); + } + + public void unregisterProxyChannel(String channelId) { + if (channelId.equals("global")) return; + proxyChannels.remove(channelId); + } + + public boolean existsProxyChannel(String channelId) { + return proxyChannels.containsKey(channelId); + } + + public void hide(UUID uuid, String channelId) { + Set hidden = hiddenChannels.getOrDefault(uuid, new HashSet()); + hidden.add(channelId); + } + + public void show(UUID uuid, String channelId) { + Set hidden = hiddenChannels.getOrDefault(uuid, new HashSet()); + hidden.remove(channelId); + if (hidden.size() == 0) hiddenChannels.remove(uuid); + } + + public boolean isHidden(UUID uuid, String channelId) { + if (!hiddenChannels.containsKey(uuid)) return false; + Set hidden = hiddenChannels.get(uuid); + return hidden.contains(channelId); + } + + public boolean select(UUID uuid, String channelId) { + if (existsProxyChannel(channelId) || channelId.equals("local")) { + selectedChannels.put(uuid, channelId); + return true; + } else { + return false; + } + } + + public boolean isLocalSpy(ProxiedPlayer player) { + return MultiChatProxy.getInstance().getDataStore().getLocalSpy().contains(player.getUniqueId()) + && player.hasPermission("multichat.chat.spy"); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/ChannelMode.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/ChannelMode.java new file mode 100644 index 00000000..6aa3fecc --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/ChannelMode.java @@ -0,0 +1,6 @@ +package xyz.olivermartin.multichat.proxy.common.channels; + +public enum ChannelMode { + PROXY, + LOCAL +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/TagManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/TagManager.java new file mode 100644 index 00000000..82796634 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/TagManager.java @@ -0,0 +1,64 @@ +package xyz.olivermartin.multichat.proxy.common.channels; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; + +public class TagManager { + + public static final String REGEX = "(?i)@([A-Z0-9_]{3,})"; + + private Pattern tagPattern; + + public TagManager() { + tagPattern = Pattern.compile(REGEX); + } + + public void handleTags(String message, String tagger) { + notifyTaggedPlayers(getTaggedPlayers(getPotentialTags(message)), tagger); + } + + private List getPotentialTags(String message) { + + List potentialTags = new ArrayList(); + Matcher tagMatcher = tagPattern.matcher(message); + + while (tagMatcher.find()) { + potentialTags.add(tagMatcher.group(1)); + } + + return potentialTags; + + } + + private List getTaggedPlayers(List potentialTags) { + + List taggedPlayers = new ArrayList(); + + for (String potentialTag : potentialTags) { + ProxiedPlayer potentialPlayer = ProxyServer.getInstance().getPlayer(potentialTag); + if (potentialPlayer != null) taggedPlayers.add(potentialPlayer); + } + + return taggedPlayers; + + } + + private void notifyTaggedPlayers(List taggedPlayers, String tagger) { + for (ProxiedPlayer taggedPlayer : taggedPlayers) { + notifyPlayer(taggedPlayer, tagger); + } + } + + private void notifyPlayer(ProxiedPlayer player, String tagger) { + player.sendMessage(ChatMessageType.ACTION_BAR, ProxyJsonUtils.parseMessage(MultiChatUtil.translateColorCodes("&6You were mentioned by %SPECIAL%"), "%SPECIAL%", MultiChatUtil.translateColorCodes(tagger))); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/local/LocalChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/local/LocalChannel.java new file mode 100644 index 00000000..5fd54b0a --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/local/LocalChannel.java @@ -0,0 +1,124 @@ +package xyz.olivermartin.multichat.proxy.common.channels.local; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.bungee.ChatControl; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.Set; +import java.util.UUID; + +public class LocalChannel { + + private String desc; + private String format; + + private ChannelManager manager; + + public LocalChannel(String desc, String format, ChannelManager manager) { + + this.desc = desc; + this.format = format; + + this.manager = manager; + + } + + public String getDescription() { + return this.desc; + } + + public String getFormat() { + return this.format; + } + + public ChannelManager getManager() { + return this.manager; + } + + public void distributeMessage(ProxiedPlayer sender, String message, String format, Set otherRecipients) { + + // If the sender can't speak, or is between servers, then return + if (sender.getServer() == null) return; + + String joined = format + message; + + for (ProxiedPlayer receiver : ProxyServer.getInstance().getPlayers()) { + + // Skip sending to this player if they shouldn't receive the message + if (receiver.getServer() == null // Receiver is between servers + || manager.isHidden(receiver.getUniqueId(), "local")) // Receiver has hidden this channel + continue; + + // If receiver is sender then ignore them + if (receiver.getUniqueId().equals(sender.getUniqueId())) continue; + + // If receiver is NOT in the other recipients list then leave processing (as this is local only) (unless they are spying) + if (!otherRecipients.contains(receiver.getUniqueId()) + && !manager.isLocalSpy(receiver)) continue; + + // If receiver ignores sender + if (ChatControl.ignores(sender.getUniqueId(), receiver.getUniqueId(), MessageType.GLOBAL_CHAT)) { + ChatControl.sendIgnoreNotifications(receiver, sender, "global_chat"); + continue; + } + + String finalMessage = joined; + + if (manager.isLocalSpy(receiver) + && !otherRecipients.contains(receiver.getUniqueId())) { + finalMessage = MultiChatProxy.getInstance().getChatManager().getLocalSpyMessage(sender, format, message); + } + + if (ProxyConfigs.CONFIG.isLegacyServer(receiver.getServer().getInfo().getName())) { + receiver.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateRGBColorCodes(finalMessage))); + } else { + receiver.sendMessage(TextComponent.fromLegacyText(finalMessage)); + } + + } + + } + + public void sendMessage(ProxiedPlayer sender, String message) { + ProxyLocalCommunicationManager.sendPlayerDirectChatMessage("local", sender.getName(), message, sender.getServer().getInfo()); + } + + public void broadcastRawMessage(CommandSender sender, String server, String message) { + + message = MultiChatUtil.translateColorCodes(message); + + for (ProxiedPlayer receiver : ProxyServer.getInstance().getPlayers()) { + + // Skip sending to this player if they shouldn't receive the message + if (receiver.getServer() == null // Receiver is between servers + || manager.isHidden(receiver.getUniqueId(), "local")) // Receiver has hidden this channel + continue; + + // If not on specified server then return (unless spying) + if (!receiver.getServer().getInfo().getName().equals(server) && !manager.isLocalSpy(receiver)) continue; + + String finalMessage = message; + + if (manager.isLocalSpy(receiver) && !receiver.getServer().getInfo().getName().equals(server)) { + finalMessage = MultiChatProxy.getInstance().getChatManager().getLocalSpyMessage(sender, message); + } + + if (ProxyConfigs.CONFIG.isLegacyServer(receiver.getServer().getInfo().getName())) { + receiver.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateRGBColorCodes(finalMessage))); + } else { + receiver.sendMessage(TextComponent.fromLegacyText(finalMessage)); + } + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/DynamicProxyChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/DynamicProxyChannel.java new file mode 100644 index 00000000..0b196d44 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/DynamicProxyChannel.java @@ -0,0 +1,76 @@ +package xyz.olivermartin.multichat.proxy.common.channels.proxy; + +import java.util.Set; +import java.util.UUID; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; + +public class DynamicProxyChannel extends GenericProxyChannel { + + private boolean blacklistMembers; // Should member list of the channel be a blacklist or whitelist + private Set members; // Member list of the channel + + public DynamicProxyChannel(String id, ProxyChannelInfo info, ChannelManager manager, boolean blacklistMembers, Set members) { + super(id, info, manager); + this.blacklistMembers = blacklistMembers; + this.members = members; + } + + /** + * Checks if the command sender is a member of this channel + * @param sender The command sender to check + * @return true if they are a member of the channel + */ + public boolean isMember(CommandSender sender) { + + // Console always member + if (!(sender instanceof ProxiedPlayer)) return true; + + ProxiedPlayer player = (ProxiedPlayer) sender; + + if (blacklistMembers) { + return !members.contains(player.getUniqueId()); + } else { + return members.contains(player.getUniqueId()); + } + + } + + /** + * Is the member list for this channel a blacklist or a whitelist? + * @return true if it is a blacklist + */ + public boolean isBlacklistMembers() { + return this.blacklistMembers; + } + + /** + * Controls if the member list for this channel is a blacklist or a whitelist + * @param blacklistMembers TRUE for blacklist, FALSE for whitelist + */ + public void setBlacklistMembers(boolean blacklistMembers) { + this.blacklistMembers = blacklistMembers; + } + + /** + *

Gets the blacklist/whitelist of members for this channel.

+ *

List is a blacklist if isBlacklistMembers() returns true, otherwise is a whitelist

+ * @return the blacklist/whitelist of members + */ + public Set getMembers() { + return this.members; + } + + @Override + public boolean canSpeak(CommandSender sender) { + return isMember(sender) && getInfo().inContext(sender) && getInfo().hasSpeakPermission(sender); + } + + @Override + public boolean canView(CommandSender sender) { + return isMember(sender) && getInfo().inContext(sender) && getInfo().hasViewPermission(sender); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/GenericProxyChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/GenericProxyChannel.java new file mode 100644 index 00000000..950910a4 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/GenericProxyChannel.java @@ -0,0 +1,152 @@ +package xyz.olivermartin.multichat.proxy.common.channels.proxy; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.bungee.ChatControl; +import xyz.olivermartin.multichat.bungee.ConsoleManager; +import xyz.olivermartin.multichat.bungee.events.PostBroadcastEvent; +import xyz.olivermartin.multichat.bungee.events.PostGlobalChatEvent; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.Set; +import java.util.UUID; + +public abstract class GenericProxyChannel implements ProxyChannel { + + private String id; + private ProxyChannelInfo info; + private ChannelManager manager; + + public GenericProxyChannel(String id, ProxyChannelInfo info, ChannelManager manager) { + this.id = id; + this.info = info; + this.manager = manager; + } + + @Override + public String getId() { + return this.id; + } + + @Override + public ProxyChannelInfo getInfo() { + return this.info; + } + + @Override + public ChannelManager getManager() { + return this.manager; + } + + /** + * Updates the ChannelInfo used for this channel + * @param info The new info for the channel + */ + public void updateInfo(ProxyChannelInfo info) { + this.info = info; + } + + @Override + public void distributeMessage(ProxiedPlayer sender, String message, String format, Set otherRecipients) { + + // If the sender can't speak, or is between servers, then return + if (!canSpeak(sender) || sender.getServer() == null) return; + + String senderServer = sender.getServer().getInfo().getName(); + String joined = format + message; + + // TODO This is just a test + if (sender.hasPermission("multichat.chat.tag")) MultiChatProxy.getInstance().getTagManager().handleTags(message, sender.getName()); + + for (ProxiedPlayer receiver : ProxyServer.getInstance().getPlayers()) { + + // Skip sending to this player if they shouldn't receive the message + if (receiver.getServer() == null // Receiver is between servers + || !canView(receiver) // Receiver is not permitted to view message + || manager.isHidden(receiver.getUniqueId(), id)) // Receiver has hidden this channel + continue; + + // If receiver is on the same server as the sender AND NOT in the other recipients list + if (receiver.getServer().getInfo().getName().equals(senderServer) + && !otherRecipients.contains(receiver.getUniqueId())) + continue; + + // If receiver ignores sender + if (ChatControl.ignores(sender.getUniqueId(), receiver.getUniqueId(), MessageType.GLOBAL_CHAT)) { + ChatControl.sendIgnoreNotifications(receiver, sender, "global_chat"); + continue; + } + + if (ProxyConfigs.CONFIG.isLegacyServer(receiver.getServer().getInfo().getName())) { + receiver.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateRGBColorCodes(joined))); + } else { + receiver.sendMessage(TextComponent.fromLegacyText(joined)); + } + + } + + // Trigger PostGlobalChatEvent + ProxyServer.getInstance().getPluginManager().callEvent(new PostGlobalChatEvent(sender, format, message)); + + ConsoleManager.logChat(MultiChatUtil.approximateRGBColorCodes(joined)); + + } + + @Override + public void sendMessage(ProxiedPlayer sender, String message) { + ProxyLocalCommunicationManager.sendPlayerDirectChatMessage(getId(), sender.getName(), message, sender.getServer().getInfo()); + } + + @Override + public void broadcastRawMessage(CommandSender sender, String message) { + + // If the sender can't speak then return + if (!canSpeak(sender)) return; + + message = MultiChatUtil.translateColorCodes(message); + + for (ProxiedPlayer receiver : ProxyServer.getInstance().getPlayers()) { + + // Skip sending to this player if they shouldn't receive the message + if (receiver.getServer() == null // Receiver is between servers + || !canView(receiver) // Receiver is not permitted to view message + || manager.isHidden(receiver.getUniqueId(), id)) // Receiver has hidden this channel + continue; + + if (ProxyConfigs.CONFIG.isLegacyServer(receiver.getServer().getInfo().getName())) { + receiver.sendMessage(TextComponent.fromLegacyText(MultiChatUtil.approximateRGBColorCodes(message))); + } else { + receiver.sendMessage(TextComponent.fromLegacyText(message)); + } + + } + + // Trigger PostBroadcastEvent + ProxyServer.getInstance().getPluginManager().callEvent(new PostBroadcastEvent("cast", message)); + + ConsoleManager.logDisplayMessage(message); + + } + + /** + * Checks if this command sender is allowed to speak in the channel + * @param sender The command sender + * @return true if they are allowed to speak + */ + public abstract boolean canSpeak(CommandSender sender); + + /** + * Checks if this command sender is allowed to view the channel + * @param sender The command sender + * @return true if they are allowed to view + */ + public abstract boolean canView(CommandSender sender); + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/GlobalStaticProxyChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/GlobalStaticProxyChannel.java new file mode 100644 index 00000000..f8f38bfe --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/GlobalStaticProxyChannel.java @@ -0,0 +1,12 @@ +package xyz.olivermartin.multichat.proxy.common.channels.proxy; + +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; + +public class GlobalStaticProxyChannel extends StaticProxyChannel { + + public GlobalStaticProxyChannel(String desc, String format, ChannelManager manager) { + super("global", new ProxyChannelInfo(desc, format, false, MultiChatProxy.getInstance().getContextManager().getGlobalContext()), manager); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannel.java new file mode 100644 index 00000000..41d556e5 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannel.java @@ -0,0 +1,58 @@ +package xyz.olivermartin.multichat.proxy.common.channels.proxy; + +import java.util.Set; +import java.util.UUID; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; + +public interface ProxyChannel { + + /** + * Gets the ID of this proxy channel + * @return the id + */ + public String getId(); + + /** + * Gets the info for this proxy channel + * @return the info + */ + public ProxyChannelInfo getInfo(); + + /** + * Gets the channel manager for this channel + * @return the manager + */ + public ChannelManager getManager(); + + /** + *

Distributes the chat message to all remaining players

+ *

MultiChat works by first handling the message formatting on each local server.

+ *

This message is ONLY sent to the sender locally... It is then forwarded to the proxy to distribute.

+ * @param sender The sender of the message + * @param message The message to send + * @param format The format before the message part + * @param otherRecipients The recipients the message was intended for on the local server (excluding the sender) + */ + public void distributeMessage(ProxiedPlayer sender, String message, String format, Set otherRecipients); + + /** + *

Sends a chat message from a player to the local server to be sent

+ *

MultiChat works by first handling the message formatting on each local server.

+ *

This message is ONLY sent to the sender locally... It is then forwarded to the proxy to distribute.

+ * @param sender The sender of the message + * @param message The message to send + */ + public void sendMessage(ProxiedPlayer sender, String message); + + /** + *

Broadcasts a raw message to this channel

+ *

This sends a message directly to all permitted viewers on the proxy only

+ * @param sender The sender of the message + * @param message The message to send + */ + public void broadcastRawMessage(CommandSender sender, String message); + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannelInfo.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannelInfo.java new file mode 100644 index 00000000..3dc3dddf --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannelInfo.java @@ -0,0 +1,122 @@ +package xyz.olivermartin.multichat.proxy.common.channels.proxy; + +import net.md_5.bungee.api.CommandSender; +import xyz.olivermartin.multichat.proxy.common.contexts.Context; + +import java.util.Optional; + +public class ProxyChannelInfo { + + private String desc; // A short description of the channel + private String format; // The format of this channel + private boolean unhideable; // If the channel is unhideable + private Context context; // The context for this channel + + private String permission; // Permission to view / speak + private String viewPermission; // Permission to view only + + public ProxyChannelInfo(String desc, String format, boolean unhideable, Context context, String permission, String viewPermission) { + + this.desc = desc; + this.format = format; + this.unhideable = unhideable; + this.context = context; + + this.permission = permission; + this.viewPermission = viewPermission; + + } + + public ProxyChannelInfo(String desc, String format, boolean unhideable, Context context, String permission) { + this(desc, format, unhideable, context, permission, permission); + } + + public ProxyChannelInfo(String desc, String format, boolean unhideable, Context context) { + this(desc, format, unhideable, context, null); + } + + /** + * Gets a short description of this channel + * @return the description + */ + public String getDescription() { + return this.desc; + } + + /** + * Gets the format used for chat in this channel + * @return the format + */ + public String getFormat() { + return this.format; + } + + /** + * Checks if this channel is not allowed to be hidden + * @return true if the channel can not be hidden + */ + public boolean isUnhideable() { + return this.unhideable; + } + + /** + * Gets the context of this channel + * @return the context + */ + public Context getContext() { + return this.context; + } + + /* + * Are any permissions set for this channel? + */ + private boolean isPermissionProtected() { + return this.permission != null; + } + + /** + * Gets the permission required to view / speak in the channel (if one exists) + * @return an optional of the permission + */ + public Optional getPermission() { + return Optional.ofNullable(permission); + } + + /** + * Gets the permission required to ONLY view the channel (if one exists) + * @return an optional of the permission + */ + public Optional getViewPermission() { + return Optional.ofNullable(viewPermission); + } + + /** + * Checks if the command sender has permission to view this channel + * @param sender The command sender to check + * @return true if they have permission to view the channel + */ + public boolean hasViewPermission(CommandSender sender) { + if (!isPermissionProtected()) return true; + return sender.hasPermission(permission) || sender.hasPermission(viewPermission); + } + + /** + * Checks if the command sender has permission to speak in channel + * @param sender The command sender to check + * @return true if they have permission to speak into the channel + */ + public boolean hasSpeakPermission(CommandSender sender) { + if (!isPermissionProtected()) return true; + return sender.hasPermission(permission); + } + + /** + * Checks if the command sender is in the context of the channel + * @param sender The command sender to check + * @return true if they are in the context + */ + public boolean inContext(CommandSender sender) { + return context.contains(sender); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannelType.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannelType.java new file mode 100644 index 00000000..bf71da50 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/ProxyChannelType.java @@ -0,0 +1,10 @@ +package xyz.olivermartin.multichat.proxy.common.channels.proxy; + +public enum ProxyChannelType { + + STATIC, + DYNAMIC, + STAFF, + GROUP + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/StaticProxyChannel.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/StaticProxyChannel.java new file mode 100644 index 00000000..8332e6bb --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/channels/proxy/StaticProxyChannel.java @@ -0,0 +1,105 @@ +package xyz.olivermartin.multichat.proxy.common.channels.proxy; + +import net.md_5.bungee.api.CommandSender; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; + +public class StaticProxyChannel extends GenericProxyChannel { + + /*public static class Builder { + + private String id; // The channel ID + private String desc; // A short description of the channel + private String format; // The format of this channel + private boolean unhideable; // If the channel is unhideable + private Context context; // The context for this channel + private List aliases; // The command aliases for this channel + + private String permission; // Permission to view / speak + private String viewPermission; // Permission to view only + + private boolean blacklistMembers; // Should member list of the channel be a blacklist or whitelist + private Set members; // Member list of the channel + + public Builder(String id) { + + this.id = id; + this.desc = id; + this.format = "[" + id + "] %DISPLAYNAME%&f: "; + this.unhideable = false; + this.context = MultiChatProxy.getInstance().getContextManager().getGlobalContext(); + this.aliases = new ArrayList(); + + this.permission = null; + this.viewPermission = null; + + this.blacklistMembers = true; + this.members = new HashSet(); + + } + + public Builder withDescription(String desc) { + this.desc = desc; + return this; + } + + public Builder withFormat(String format) { + this.format = format; + return this; + } + + public Builder isUnhideable(boolean unhideable) { + this.unhideable = unhideable; + return this; + } + + public Builder inContext(Context context) { + this.context = context; + return this; + } + + public Builder withAliases(List aliases) { + this.aliases = aliases; + return this; + } + + public Builder withPemission(String permission) { + this.permission = permission; + return this; + } + + public Builder withViewPemission(String viewPermission) { + this.viewPermission = viewPermission; + return this; + } + + public Builder isBlacklistMembers(boolean blacklistMembers) { + this.blacklistMembers = blacklistMembers; + return this; + } + + public Builder withMemberList(Set members) { + this.members = members; + return this; + } + + public StaticNetworkChannel build() { + return new StaticNetworkChannel(id, desc, format, unhideable, context, aliases, permission, viewPermission); + } + + }*/ + + public StaticProxyChannel(String id, ProxyChannelInfo info, ChannelManager manager) { + super(id, info, manager); + } + + @Override + public boolean canSpeak(CommandSender sender) { + return getInfo().inContext(sender) && getInfo().hasSpeakPermission(sender); + } + + @Override + public boolean canView(CommandSender sender) { + return getInfo().inContext(sender) && getInfo().hasViewPermission(sender); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/AbstractProxyConfig.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/AbstractProxyConfig.java new file mode 100644 index 00000000..2ce280a4 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/AbstractProxyConfig.java @@ -0,0 +1,162 @@ +package xyz.olivermartin.multichat.proxy.common.config; + + +import java.io.File; +import java.io.IOException; + +import net.md_5.bungee.api.plugin.Plugin; +import net.md_5.bungee.config.Configuration; +import net.md_5.bungee.config.ConfigurationProvider; +import net.md_5.bungee.config.YamlConfiguration; + +/** + * Class that represents the base of a config that can be handled by MultiChat + *

+ * Manages creation and reloads + * + * @author Oliver Martin (Revilo410) + */ +public abstract class AbstractProxyConfig { + + private final String fileName; + + /** + * Prepare an abstract config. + * You have to call {@link #setPlugin(Plugin)} to make {@link #reloadConfig()} work. + * You can call {@link #setDataFolder(File)} to change the folder under which the plugin will be saved. + * + * @param fileName The name of the file, needs + */ + AbstractProxyConfig(String fileName) { + if (!fileName.endsWith(".yml")) + throw new IllegalArgumentException("Filename did not end with .yml"); + + this.fileName = fileName; + } + + private Plugin plugin; + private File dataFolder, configFile; + private Configuration config; + + /** + * Set the plugin that owns the configuration file + * + * @param plugin the BungeeCord plugin + * @throws IllegalArgumentException if the plugin has already been set + */ + public final void setPlugin(Plugin plugin) throws IllegalArgumentException { + if (this.plugin != null) + throw new IllegalArgumentException("You can not change the plugin after setting it once."); + + this.plugin = plugin; + } + + /** + * Set the folder under which the file should be + * + * @param dataFolder the folder + * @throws IllegalArgumentException if the data folder has already been set + */ + public final void setDataFolder(File dataFolder) throws IllegalArgumentException { + if (this.dataFolder != null) + throw new IllegalArgumentException("You can not change the data folder after setting it once."); + + this.dataFolder = dataFolder; + } + + /** + * Reload the config. + *

+ * This method can only be called if {@link #setPlugin(Plugin)} has been called. + * Data folder will be the plugin folder unless first set with with {@link #setDataFolder(File)}. + * + * @throws IllegalStateException if the plugin has not been set yet. + */ + public final void reloadConfig() throws IllegalStateException { + if (plugin == null) + throw new IllegalStateException("You have not set the plugin yet."); + + if (this.configFile == null) + this.configFile = new File(getDataFolder(), fileName); + + plugin.getLogger().info("Loading " + fileName + " ..."); + ProxyConfigUpdater configUpdater = new ProxyConfigUpdater(this); + configUpdater.update(); + + try { + config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); + reloadValues(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Method that can be overridden to define what should happen after configuration has been reloaded. + */ + void reloadValues() { + } + + /** + * Convenience method to get the plugin. Same-Package only. + * + * @return the data folder. + * @throws IllegalStateException if the plugin has not been set + */ + Plugin getPlugin() { + if (plugin == null) + throw new IllegalStateException("Method has been called without defining the plugin first."); + + return plugin; + } + + /** + * Convenience method to get the file name. + * + * @return the file name. + */ + public final String getFileName() { + return fileName; + } + + /** + * Convenience method to get the data folder. + * + * @return the data folder. + * @throws IllegalStateException if the plugin has not been set + */ + public final File getDataFolder() throws IllegalStateException { + if (plugin == null) + throw new IllegalStateException("Method has been called without defining the plugin first."); + + if (dataFolder == null) + dataFolder = plugin.getDataFolder(); + + return dataFolder; + } + + /** + * Convenience method to get the config's file. + * + * @return the config's file. + * @throws IllegalStateException if the plugin has not been set + */ + public final File getConfigFile() throws IllegalStateException { + if (plugin == null) + throw new IllegalStateException("Method has been called without defining the plugin first."); + + return configFile; + } + + /** + * Convenience method to get the bungee configuration. + * + * @return the config. + */ + public final Configuration getConfig() { + if (config == null) + throw new IllegalStateException("Configuration has not been loaded yet. This should NOT happen! " + + "Check the server startup for errors."); + return config; + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyAliases.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyAliases.java new file mode 100644 index 00000000..76458e0e --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyAliases.java @@ -0,0 +1,35 @@ +package xyz.olivermartin.multichat.proxy.common.config; + +import java.util.HashMap; +import java.util.Map; + +/** + * Class to represent the proxy's aliases.yml. + */ +public class ProxyAliases extends AbstractProxyConfig { + + private final Map commandAliases = new HashMap<>(); + + ProxyAliases() { + super("aliases.yml"); + } + + @Override + void reloadValues() { + commandAliases.clear(); + + getConfig().getKeys().forEach(key -> + commandAliases.put(key, getConfig().getStringList(key).toArray(new String[0])) + ); + } + + /** + * Get all aliases to a certain command. + * + * @param command The base name of the command + * @return the array of defined aliases, empty if command does not exist + */ + public String[] getAliases(String command) { + return commandAliases.getOrDefault(command, new String[0]); + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyChatControl.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyChatControl.java new file mode 100644 index 00000000..7d93ba7c --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyChatControl.java @@ -0,0 +1,257 @@ +package xyz.olivermartin.multichat.proxy.common.config; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.common.MessageType; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; + +import java.util.*; +import java.util.regex.Pattern; + +/** + * Class to represent the proxy's chatcontrol.yml. + *

+ * All methods should be relatively straight forward and represent their respective entries in the config. + */ +public class ProxyChatControl extends AbstractProxyConfig { + + private String version, antiSpamCommand, linkRemovalMessage; + private final Set regexRules = new LinkedHashSet<>(); + private final Set regexActions = new LinkedHashSet<>(); + private final Map applyRulesTo = new HashMap<>(), applyActionsTo = new HashMap<>(), + applyAntiSpamTo = new HashMap<>(), applyMuteTo = new HashMap<>(), applyIgnoreTo = new HashMap<>(); + + private boolean antiSpam, antiSpamAction, antiSpamSpigot, mute, notifyIgnore, sessionIgnore, linkControl; + private int antiSpamTime, spamSameMessage, antiSpamCoolDown, antiSpamTrigger; + private Pattern linkPattern; + + ProxyChatControl() { + super("chatcontrol.yml"); + } + + @Override + void reloadValues() { + regexRules.clear(); + regexActions.clear(); + applyRulesTo.clear(); + applyActionsTo.clear(); + applyAntiSpamTo.clear(); + applyMuteTo.clear(); + applyIgnoreTo.clear(); + + version = getConfig().getString("version", "1.10"); + + // Load regex rules + getConfig().getList("regex_rules").forEach(listEntry -> { + if (!(listEntry instanceof Map)) + return; + Map regexRuleConfig = (Map) listEntry; + String pattern = String.valueOf(regexRuleConfig.get("look_for")); + if (pattern == null || pattern.isEmpty()) + return; + + regexRules.add(new RegexRule(pattern, + String.valueOf(regexRuleConfig.get("replace_with")), + String.valueOf(regexRuleConfig.get("permission"))) + ); + }); + for (MessageType messageType : MessageType.values()) + applyRulesTo.put(messageType, getConfig().getBoolean("apply_rules_to." + messageType.toString(), false)); + + // Load regex actions + getConfig().getList("regex_actions").forEach(listEntry -> { + if (!(listEntry instanceof Map)) + return; + Map regexActionConfig = (Map) listEntry; + + String pattern = String.valueOf(regexActionConfig.get("look_for")); + if (pattern == null || pattern.isEmpty()) + return; + + Object cancelObject = regexActionConfig.get("cancel"); + boolean cancel = cancelObject instanceof Boolean && (boolean) cancelObject; + + Object spigotObject = regexActionConfig.get("spigot"); + boolean spigot = spigotObject instanceof Boolean && (boolean) spigotObject; + + regexActions.add(new RegexAction(pattern, + String.valueOf(regexActionConfig.get("command")), + String.valueOf(regexActionConfig.get("permission")), + cancel, + spigot + ) + ); + }); + for (MessageType messageType : MessageType.values()) + applyActionsTo.put(messageType, getConfig().getBoolean("apply_actions_to." + messageType.toString(), false)); + + // Load spam settings + antiSpam = getConfig().getBoolean("anti_spam", true); + antiSpamTime = getConfig().getInt("anti_spam_time", 4); + spamSameMessage = getConfig().getInt("spam_same_message", 4); + antiSpamCoolDown = getConfig().getInt("anti_spam_cooldown", 60); + antiSpamAction = getConfig().getBoolean("anti_spam_action", true); + antiSpamSpigot = getConfig().getBoolean("anti_spam_spigot", true); + antiSpamTrigger = getConfig().getInt("anti_spam_trigger", 3); + antiSpamCommand = getConfig().getString("anti_spam_command"); + for (MessageType messageType : MessageType.values()) + applyAntiSpamTo.put(messageType, getConfig().getBoolean("apply_anti_spam_to." + messageType.toString(), false)); + + // Load mute settings + mute = getConfig().getBoolean("mute", false); + for (MessageType messageType : MessageType.values()) + applyMuteTo.put(messageType, getConfig().getBoolean("apply_mute_to." + messageType.toString(), false)); + + // Load ignore settings + notifyIgnore = getConfig().getBoolean("notify_ignore", false); + sessionIgnore = getConfig().getBoolean("session_ignore", false); + for (MessageType messageType : MessageType.values()) + applyIgnoreTo.put(messageType, getConfig().getBoolean("apply_ignore_to." + messageType.toString(), false)); + + // Load link control settings + linkControl = getConfig().getBoolean("link_control", false); + linkPattern = Pattern.compile(getConfig().getString("link_regex", + "((https|http):\\/\\/)?(www\\.)?([-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.)+[a-zA-Z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&\\/\\/=]*)") + ); + linkRemovalMessage = getConfig().getString("link_removal_message", "[LINK REMOVED]"); + } + + public String getVersion() { + return version; + } + + // TODO: [2.0] Some of these #apply / #replace / #handle methods could be moved into a refactored ChatControl.class + // I just added them to not lose the logic for now + // TODO: [2.0] Add events for regex rules and actions ? + public String applyRegexRules(CommandSender commandSender, String message, MessageType messageType) { + if (!applyRulesTo.get(messageType)) return message; + + for (RegexRule regexRule : regexRules) + message = regexRule.apply(commandSender, message); + return message; + } + + public boolean regexActionsCancel(CommandSender commandSender, String message, MessageType messageType) { + if (!applyActionsTo.get(messageType)) return false; + + // TODO: [ConfigRefactor] Personally I believe we should return after the first action cancels the message being sent + boolean cancel = false; + for (RegexAction regexAction : regexActions) { + if (regexAction.cancels(commandSender, message)) + cancel = true; + } + + return cancel; + } + + public String replaceLinks(String message) { + if (!linkControl) + return message; + + return linkPattern.matcher(message).replaceAll(linkRemovalMessage); + } + + public boolean applyMuteTo(MessageType messageType) { + return applyMuteTo.get(messageType); + } + + public boolean applyIgnoreTo(MessageType messageType) { + return applyIgnoreTo.get(messageType); + } + + public boolean applyAntiSpamTo(MessageType messageType) { + return applyAntiSpamTo.get(messageType); + } + + public boolean isAntiSpam() { + return antiSpam; + } + + public int getAntiSpamTime() { + return antiSpamTime; + } + + public int getSpamSameMessage() { + return spamSameMessage; + } + + public int getAntiSpamCoolDown() { + return antiSpamCoolDown; + } + + public boolean isAntiSpamAction() { + return antiSpamAction; + } + + public boolean isAntiSpamSpigot() { + return antiSpamSpigot; + } + + public int getAntiSpamTrigger() { + return antiSpamTrigger; + } + + public String getAntiSpamCommand() { + return antiSpamCommand; + } + + public boolean isMute() { + return mute; + } + + public boolean isNotifyIgnore() { + return notifyIgnore; + } + + public boolean isSessionIgnore() { + return sessionIgnore; + } + + // TODO: [ConfigRefactor] [2.0] Decide if we want to move these out of here. I don't think any other class needs access to these though. + private static class RegexRule { + private final Pattern pattern; + private final String replaceWith, permission; + + RegexRule(String pattern, String replaceWith, String permission) { + this.pattern = Pattern.compile(pattern); + this.replaceWith = replaceWith.equals("null") ? "" : replaceWith; + this.permission = permission.equals("null") ? "" : permission; + } + + public String apply(CommandSender commandSender, String message) { + if (commandSender != null && !permission.isEmpty() && !commandSender.hasPermission(permission)) + return message; + return pattern.matcher(message).replaceAll(replaceWith); + } + } + + private static class RegexAction { + private final Pattern pattern, playerPattern = Pattern.compile("%PLAYER%"); + private final String command, permission; + private final boolean cancel, spigot; + + RegexAction(String pattern, String command, String permission, boolean cancel, boolean spigot) { + this.pattern = Pattern.compile(pattern); + this.command = command.equals("null") ? "" : command; + this.permission = permission.equals("null") ? "" : permission; + this.cancel = cancel; + this.spigot = spigot; + } + + public boolean cancels(CommandSender commandSender, String message) { + if (!permission.isEmpty() && !commandSender.hasPermission(permission)) + return false; + if (!pattern.matcher(message).matches()) + return false; + if (!command.isEmpty()) { + String tempCommand = playerPattern.matcher(command).replaceAll(commandSender.getName()); + if (spigot && commandSender instanceof ProxiedPlayer) + ProxyLocalCommunicationManager.sendCommandMessage(tempCommand, ((ProxiedPlayer) commandSender).getServer().getInfo()); + else + ProxyServer.getInstance().getPluginManager().dispatchCommand(commandSender, tempCommand); + } + return cancel; + } + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfig.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfig.java new file mode 100644 index 00000000..fd4e5f48 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfig.java @@ -0,0 +1,225 @@ +package xyz.olivermartin.multichat.proxy.common.config; + +import xyz.olivermartin.multichat.common.RegexUtil; + +import java.util.HashSet; +import java.util.Set; + +/** + * Class to represent the proxy's config.yml. + *

+ * All methods should be relatively straight forward and represent their respective entries in the config. + */ +public class ProxyConfig extends AbstractProxyConfig { + + private String version, displayNameFormat, pmOutFormat, pmInFormat, pmSpyFormat, defaultChannel, globalFormat, + localSpyFormat, groupChatFormat, modChatFormat, adminChatFormat; + private char groupChatColor, groupNameColor, modChatColor, modNameColor, adminChatColor, adminNameColor; + private boolean fetchSpigotDisplayNames, setDisplayName, pm, togglePm, forceChannelOnJoin, global, staffList, + logPms, logStaffChat, logGroupChat, pvPreventMessage, pvPreventStaffList, pvSilenceJoin; + private final Set noPmServers = new HashSet<>(), localServers = new HashSet<>(), legacyServers = new HashSet<>(); + + ProxyConfig() { + super("config.yml"); + } + + @Override + void reloadValues() { + noPmServers.clear(); + localServers.clear(); + legacyServers.clear(); + + version = getConfig().getString("version", "1.10"); + + fetchSpigotDisplayNames = getConfig().getBoolean("fetch_spigot_display_names", true); + setDisplayName = getConfig().getBoolean("set_display_name", true); + displayNameFormat = getConfig().getString("display_name_format", "%PREFIX%%NICK%%SUFFIX%"); + + pm = getConfig().getBoolean("pm", true); + noPmServers.addAll(getConfig().getStringList("no_pm")); + togglePm = getConfig().getBoolean("toggle_pm", true); + + pmOutFormat = getConfig().getString("pmout", "&6[&cYou &6-> &c%DISPLAYNAMET%&6] &f%MESSAGE%"); + pmInFormat = getConfig().getString("pmin", "&6[&c%DISPLAYNAME% &6-> &cMe&6] &f%MESSAGE%"); + pmSpyFormat = getConfig().getString("pmSpyFormat", "&8&l<< &f%NAME% &7-> &f%NAMET%&8: &7%MESSAGE% &8&l>>"); + + defaultChannel = getConfig().getString("default_channel", "global"); + if (!defaultChannel.equals("global") && !defaultChannel.equals("local")) + defaultChannel = "global"; + forceChannelOnJoin = getConfig().getBoolean("force_channel_on_join", forceChannelOnJoin); + + global = getConfig().getBoolean("global", true); + localServers.addAll(getConfig().getStringList("no_global")); + + globalFormat = getConfig().getString("globalformat", "&2[&aG&2] &f%DISPLAYNAME%&f: "); + localSpyFormat = getConfig().getString("localspyformat", "&8[&7SPY&8] %FORMAT%"); + + groupChatFormat = getConfig().getString("groupchat.format", "%CC%(%NC%%GROUPNAME%%CC%)(%NC%%NAME%%CC%) %MESSAGE%"); + groupChatColor = getConfig().getString("groupchat.ccdefault", "a").charAt(0); + if (!RegexUtil.LEGACY_COLOR.matches(String.valueOf(groupChatColor))) + groupChatColor = 'a'; + groupNameColor = getConfig().getString("groupchat.ncdefault", "f").charAt(0); + if (!RegexUtil.LEGACY_COLOR.matches(String.valueOf(groupNameColor))) + groupNameColor = 'f'; + + modChatFormat = getConfig().getString("modchat.format", "%CC%{%NC%%NAME%%CC%} %MESSAGE%"); + modChatColor = getConfig().getString("modchat.ccdefault", "b").charAt(0); + if (!RegexUtil.LEGACY_COLOR.matches(String.valueOf(modChatColor))) + modChatColor = 'b'; + modNameColor = getConfig().getString("modchat.ncdefault", "d").charAt(0); + if (!RegexUtil.LEGACY_COLOR.matches(String.valueOf(modNameColor))) + modNameColor = 'd'; + + adminChatFormat = getConfig().getString("adminchat.format", "%CC%{%NC%%NAME%%CC%} %MESSAGE%"); + adminChatColor = getConfig().getString("adminchat.ccdefault", "d").charAt(0); + if (!RegexUtil.LEGACY_COLOR.matches(String.valueOf(adminChatColor))) + adminChatColor = 'd'; + adminNameColor = getConfig().getString("adminchat.ncdefault", "b").charAt(0); + if (!RegexUtil.LEGACY_COLOR.matches(String.valueOf(adminNameColor))) + adminNameColor = 'b'; + + staffList = getConfig().getBoolean("staff_list", true); + + logPms = getConfig().getBoolean("privacy_settings.log_pms", true); + logStaffChat = getConfig().getBoolean("privacy_settings.log_staffchat", true); + logGroupChat = getConfig().getBoolean("privacy_settings.log_groupochat", true); + + pvPreventMessage = getConfig().getBoolean("premium_vanish.prevent_message", true); + pvPreventStaffList = getConfig().getBoolean("premium_vanish.prevent_staff_list", true); + pvSilenceJoin = getConfig().getBoolean("premium_vanish.silence_join", true); + + legacyServers.addAll(getConfig().getStringList("legacy_servers")); + } + + public String getVersion() { + return version; + } + + public boolean isFetchSpigotDisplayNames() { + return fetchSpigotDisplayNames; + } + + public boolean isSetDisplayName() { + return setDisplayName; + } + + public String getDisplayNameFormat() { + return displayNameFormat; + } + + public boolean isPm() { + return pm; + } + + public boolean isNoPmServer(String serverName) { + return noPmServers.contains(serverName); + } + + public boolean isTogglePm() { + return togglePm; + } + + public String getPmOutFormat() { + return pmOutFormat; + } + + public String getPmInFormat() { + return pmInFormat; + } + + public String getPmSpyFormat() { + return pmSpyFormat; + } + + public String getDefaultChannel() { + return defaultChannel; + } + + public boolean isForceChannelOnJoin() { + return forceChannelOnJoin; + } + + public boolean isGlobal() { + return global; + } + + public boolean isGlobalServer(String serverName) { + return !localServers.contains(serverName); + } + + public String getGlobalFormat() { + return globalFormat; + } + + public String getLocalSpyFormat() { + return localSpyFormat; + } + + public String getGroupChatFormat() { + return groupChatFormat; + } + + public char getGroupChatColor() { + return groupChatColor; + } + + public char getGroupNameColor() { + return groupNameColor; + } + + public String getModChatFormat() { + return modChatFormat; + } + + public char getModChatColor() { + return modChatColor; + } + + public char getModNameColor() { + return modNameColor; + } + + public String getAdminChatFormat() { + return adminChatFormat; + } + + public char getAdminChatColor() { + return adminChatColor; + } + + public char getAdminNameColor() { + return adminNameColor; + } + + public boolean isStaffList() { + return staffList; + } + + public boolean isLogPms() { + return logPms; + } + + public boolean isLogStaffChat() { + return logStaffChat; + } + + public boolean isLogGroupChat() { + return logGroupChat; + } + + public boolean isPvPreventMessage() { + return pvPreventMessage; + } + + public boolean isPvPreventStaffList() { + return pvPreventStaffList; + } + + public boolean isPvSilenceJoin() { + return pvSilenceJoin; + } + + public boolean isLegacyServer(String serverName) { + return legacyServers.contains(serverName); + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfigUpdater.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfigUpdater.java new file mode 100644 index 00000000..0bde8fad --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfigUpdater.java @@ -0,0 +1,341 @@ +package xyz.olivermartin.multichat.proxy.common.config; + +import net.md_5.bungee.api.plugin.Plugin; +import net.md_5.bungee.config.Configuration; +import net.md_5.bungee.config.ConfigurationProvider; +import net.md_5.bungee.config.YamlConfiguration; +import org.yaml.snakeyaml.Yaml; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +public class ProxyConfigUpdater { + + private final Plugin plugin; + private final AbstractProxyConfig config; + private final File backupDir; + private BufferedWriter writer; + private final Yaml yaml = new Yaml(); + + /** + * Create an updater for a proxy config. Will not do anything until you call {@link #update()} + * + * @param config the config that this updater will update + */ + public ProxyConfigUpdater(AbstractProxyConfig config) { + this.config = config; + this.plugin = config.getPlugin(); + this.backupDir = new File(config.getDataFolder(), "backups"); + } + + /** + * Update a yaml file from a resource inside your plugin jar, if the new version is higher than the old version. + *

+ * Creates the yaml file if it does not exist. + */ + public void update() { + if (!config.getConfigFile().exists()) { + plugin.getLogger().info("Creating " + config.getFileName() + " ..."); + try { + Files.copy(plugin.getResourceAsStream(config.getFileName()), config.getConfigFile().toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + return; + } + + Configuration oldConfig; + try { + oldConfig = ConfigurationProvider.getProvider(YamlConfiguration.class).load(config.getConfigFile()); + } catch (IOException e) { + e.printStackTrace(); + return; + } + Configuration newConfig = ConfigurationProvider.getProvider(YamlConfiguration.class).load( + new InputStreamReader(plugin.getResourceAsStream(config.getFileName())) + ); + + String oldVersionString = oldConfig.getString("version"); + String newVersionString = newConfig.getString("version"); + if (oldVersionString == null) { + plugin.getLogger().info("Your saved version of " + config.getFileName() + + " does not have a version. The auto updater will cancel."); + return; + } + if (newVersionString == null) { + plugin.getLogger().info("The plugin-stored version of " + config.getFileName() + + " does not have a version. Please contact the plugin developer: " + + plugin.getDescription().getAuthor()); + return; + } + + boolean shouldUpdate = false; + String[] oldVersionStringSplit = oldVersionString.split("\\."); + String[] newVersionStringSplit = newVersionString.split("\\."); + for (int i = 0; i < oldVersionStringSplit.length; i++) { + if (i > newVersionStringSplit.length - 1) break; + try { + int oldVersionInt = Integer.parseInt(oldVersionStringSplit[i]); + int newVersionInt = Integer.parseInt(newVersionStringSplit[i]); + + if (newVersionInt > oldVersionInt) { + shouldUpdate = true; + break; + } + } catch (NumberFormatException ignored) { + break; + } + } + + if (!shouldUpdate) return; + + plugin.getLogger().info("New config version found for " + config.getFileName() + "! Attempting auto update..."); + + if (!backupDir.exists() && !backupDir.mkdirs()) { + plugin.getLogger().severe("The backups directory could not be created."); + return; + } + + // Back old config up + try { + InputStream in = new BufferedInputStream(new FileInputStream(config.getConfigFile())); + OutputStream out = new BufferedOutputStream(new FileOutputStream( + new File(backupDir, config.getFileName().replace(".yml", oldVersionString + ".yml"))) + ); + + byte[] buffer = new byte[1024]; + int lengthRead; + while ((lengthRead = in.read(buffer)) > 0) { + out.write(buffer, 0, lengthRead); + out.flush(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + oldConfig.set("version", newVersionString); + + try { + write(oldConfig, newConfig); + plugin.getLogger().info("Auto update for " + config.getFileName() + " successful! Please check it yourself to verify."); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Get all keys and child keys of a configuration + *

+ * Thanks BungeeCord for not offering this. + * + * @param configuration the configuration to get the keys of + * @param previousKey the previous key (used for recursion, should be called with "") + * @return an insertion-ordered set of key names + */ + private Set getDeepKeys(Configuration configuration, String previousKey) { + Set output = new LinkedHashSet<>(); + configuration.getKeys().forEach(key -> { + Object deepKeyObject = configuration.get(key); + output.add(previousKey + key); + if (deepKeyObject instanceof Configuration) { + output.add(previousKey + key); + Configuration deepKey = (Configuration) deepKeyObject; + output.addAll(getDeepKeys(deepKey, key + ".")); + } + }); + return output; + } + + private void write(Configuration oldConfig, Configuration newConfig) throws IOException { + BufferedReader resourceBufferedReader = new BufferedReader( + new InputStreamReader(plugin.getResourceAsStream(config.getFileName()), StandardCharsets.UTF_8) + ); + Map comments = getComments(resourceBufferedReader.lines().collect(Collectors.toList())); + resourceBufferedReader.close(); + + writer = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(config.getConfigFile()), StandardCharsets.UTF_8) + ); + + for (String key : getDeepKeys(newConfig, "")) { + String[] currentKeys = key.split("\\."); + String actualKey = currentKeys[currentKeys.length - 1]; + String comment = comments.remove(key); + + StringBuilder indentBuilder = new StringBuilder(); + for (int i = 0; i < currentKeys.length - 1; i++) + indentBuilder.append(" "); + String indent = indentBuilder.toString(); + + if (comment != null) + writer.write(comment); + + Object newObject = newConfig.get(key); + Object oldObject = oldConfig.get(key); + + if (newObject instanceof Configuration && oldObject instanceof Configuration) { + // Write the old section + writeSection(indent, actualKey, (Configuration) oldObject); + } else if (newObject instanceof Configuration) { + // Write the new section + writeSection(indent, actualKey, (Configuration) newObject); + } else if (oldObject != null) { + // Write the old object + write(indent, actualKey, oldObject); + } else { + // Write the new object + write(indent, actualKey, newObject); + } + } + + // All keys written, write leftover comments + String danglingComments = comments.get(null); + + if (danglingComments != null) + writer.write(danglingComments); + + writer.close(); + } + + private void write(String indent, String key, Object toWrite) throws IOException { + if (toWrite instanceof String || toWrite instanceof Character) { + String string = String.valueOf(toWrite); + writer.write(indent + key + ": " + yaml.dump(string.replace("\n", "\\n"))); + } else if (toWrite instanceof List) { + writer.write(getListAsString(indent, key, (List) toWrite)); + } else { + writer.write(indent + key + ": " + yaml.dump(toWrite)); + } + } + + private void writeSection(String indent, String key, Configuration section) throws IOException { + if (section.getKeys().isEmpty()) { + writer.write(indent + key + ": {}"); + } else { + writer.write(indent + key + ":"); + } + + writer.write("\n"); + } + + private String getListAsString(String indent, String key, List list) { + StringBuilder builder = new StringBuilder(indent).append(key).append(":"); + + if (list.isEmpty()) { + builder.append(" []\n"); + return builder.toString(); + } + + builder.append("\n"); + + for (Object toWrite : list) { + builder.append(indent); + + if (toWrite instanceof String || toWrite instanceof Character) { + builder.append("- '").append(toWrite).append("'"); + } else if (toWrite instanceof List) { + builder.append("- ").append(yaml.dump(toWrite)); + } else if (toWrite instanceof Map) { + AtomicBoolean first = new AtomicBoolean(true); + ((Map) toWrite).forEach(((mapKey, mapValue) -> { + if (first.get()) { + builder.append("- "); + first.set(false); + } else + builder.append(" "); + builder.append(mapKey).append(": ").append(yaml.dump(mapValue)); + })); + } else { + builder.append("- ").append(toWrite); + } + } + + return builder.toString(); + } + + private Map getComments(List lines) { + Map comments = new HashMap<>(); + StringBuilder keysBuilder = new StringBuilder(); + StringBuilder commentBuilder = new StringBuilder(); + long indents = 0; + + for (String line : lines) { + String trimmedLine = line == null ? "" : line.trim(); + if (trimmedLine.startsWith("-")) continue; + + if (trimmedLine.isEmpty() || trimmedLine.startsWith("#")) { + commentBuilder.append(line).append("\n"); + } else { + indents = setFullKey(keysBuilder, line, indents); + + if (keysBuilder.length() > 0) { + comments.put(keysBuilder.toString(), commentBuilder.toString()); + commentBuilder.setLength(0); + } + } + } + + if (commentBuilder.length() > 0) { + comments.put(null, commentBuilder.toString()); + } + + return comments; + } + + private void removeLastKey(StringBuilder keyBuilder) { + String temp = keyBuilder.toString(); + String[] keys = temp.split("\\."); + + if (keys.length == 1) { + keyBuilder.setLength(0); + return; + } + + temp = temp.substring(0, temp.length() - keys[keys.length - 1].length() - 1); + keyBuilder.setLength(temp.length()); + } + + private long setFullKey(StringBuilder keysBuilder, String configLine, long indents) { + // One indent is 2 spaces + long currentIndents = 0; + for (char c : configLine.toCharArray()) { + if (c == ' ') currentIndents++; + // Ignore further spaces + else break; + } + currentIndents = currentIndents / 2; + + String key = configLine.trim().split(":")[0]; + + if (keysBuilder.length() == 0) { + keysBuilder.append(key); + } else if (currentIndents == indents) { + removeLastKey(keysBuilder); + + if (keysBuilder.length() > 0) { + keysBuilder.append("."); + } + + keysBuilder.append(key); + } else if (currentIndents > indents) { + keysBuilder.append(".").append(key); + } else { + long difference = indents - currentIndents; + + for (int i = 0; i < difference + 1; i++) { + removeLastKey(keysBuilder); + } + + if (keysBuilder.length() > 0) { + keysBuilder.append("."); + } + + keysBuilder.append(key); + } + + return currentIndents; + } +} \ No newline at end of file diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfigs.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfigs.java new file mode 100644 index 00000000..6ad48a96 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyConfigs.java @@ -0,0 +1,95 @@ +package xyz.olivermartin.multichat.proxy.common.config; + +import net.md_5.bungee.api.plugin.Plugin; + +import java.io.File; +import java.util.*; + +/** + * Utility class to access proxy configs. + */ +public class ProxyConfigs { + + private ProxyConfigs() { + } + + /** + * Used to access the proxy's config.yml. + */ + public static final ProxyConfig CONFIG = new ProxyConfig(); + + /** + * Used to access the proxy's aliases.yml. + */ + public static final ProxyAliases ALIASES = new ProxyAliases(); + + /** + * Used to access the proxy's chatcontrol.yml. + */ + public static final ProxyChatControl CHAT_CONTROL = new ProxyChatControl(); + + /** + * Used to access the proxy's messages.yml. + */ + public static final ProxyMessages MESSAGES = new ProxyMessages(); + + /** + * Used to access the proxy's joinmessages.yml. + */ + public static final ProxyJoinMessages JOIN_MESSAGES = new ProxyJoinMessages(); + + /** + * List of all configurations that are managed by the plugin and have pre-defined values. + */ + public static final List ALL = Arrays.asList(CONFIG, ALIASES, CHAT_CONTROL, MESSAGES, JOIN_MESSAGES); + + /** + * List of all configurations that are saved in the plugin jar and don't have pre-defined values. + */ + public static final Set RAW_CONFIGS = new HashSet<>(); + + /** + * Loads or reloads and gets the {@link AbstractProxyConfig} of a .yml file inside a plugin's resources. + * Calling reloadValues on the config will do nothing, you will have to make your own implementation. + *

+ * Currently only used by french translations in MultiChat. + * + * @param plugin the plugin of which the resources should be loaded + * @param fileName the name of the file that ends with .yml + * @return the {@link AbstractProxyConfig} of that file + */ + public static AbstractProxyConfig loadRawConfig(Plugin plugin, String fileName) { + return loadRawConfig(plugin, fileName, plugin.getDataFolder()); + } + + /** + * Loads or reloads and gets the {@link AbstractProxyConfig} of a .yml file inside a plugin's resources. + * Calling reloadValues on the config will do nothing, you will have to make your own implementation. + *

+ * Currently only used by french translations in MultiChat. + * + * @param plugin the plugin of which the resources should be loaded + * @param fileName the name of the file that ends with .yml + * @param dataFolder the path where the file should end up + * @return the {@link AbstractProxyConfig} of that file + */ + public static AbstractProxyConfig loadRawConfig(Plugin plugin, String fileName, File dataFolder) { + if (!fileName.endsWith(".yml")) + throw new IllegalArgumentException("File name did not end with .yml"); + + AbstractProxyConfig rawConfig = RAW_CONFIGS.stream() + .filter(abstractProxyConfig -> abstractProxyConfig.getFileName().equals(fileName)) + .findFirst() + .orElse(null); + if (rawConfig == null) { + rawConfig = new AbstractProxyConfig(fileName) {}; + rawConfig.setPlugin(plugin); + rawConfig.setDataFolder(dataFolder); + } else + RAW_CONFIGS.remove(rawConfig); + rawConfig.reloadConfig(); + RAW_CONFIGS.add(rawConfig); + + return rawConfig; + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyJoinMessages.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyJoinMessages.java new file mode 100644 index 00000000..54b1d3cb --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyJoinMessages.java @@ -0,0 +1,78 @@ +package xyz.olivermartin.multichat.proxy.common.config; + +/** + * Class to represent the proxy's joinmessages.yml. + *

+ * All methods should be relatively straight forward and represent their respective entries in the config. + */ +public class ProxyJoinMessages extends AbstractProxyConfig { + + private String version, serverJoin, silentJoin, networkQuit, silentQuit, welcomeMessage, privateWelcomeMessage; + private boolean showJoin, showQuit, welcome, privateWelcome; + + ProxyJoinMessages() { + super("joinmessages.yml"); + } + + @Override + void reloadValues() { + version = getConfig().getString("version", "1.10"); + + showJoin = getConfig().getBoolean("showjoin", true); + showQuit = getConfig().getBoolean("showquit", true); + + serverJoin = getConfig().getString("serverjoin", "&e%NAME% &ejoined the network"); + silentJoin = getConfig().getString("silentjoin", "&b&o%NAME% &b&ojoined the network silently"); + networkQuit = getConfig().getString("networkquit", "&e%NAME% left the network"); + silentQuit = getConfig().getString("silentquit", "&b&o%NAME% &b&oleft the network silently"); + + welcome = getConfig().getBoolean("welcome", true); + welcomeMessage = getConfig().getString("welcome_message", "&dWelcome %NAME% to the network for the first time!"); + privateWelcome = getConfig().getBoolean("private_welcome", false); + privateWelcomeMessage = getConfig().getString("private_welcome_message", "&5Hi there %NAME%, please make sure you read the /rules!"); + } + + public String getVersion() { + return version; + } + + public boolean isShowJoin() { + return showJoin; + } + + public boolean isShowQuit() { + return showQuit; + } + + public String getServerJoin() { + return serverJoin; + } + + public String getSilentJoin() { + return silentJoin; + } + + public String getNetworkQuit() { + return networkQuit; + } + + public String getSilentQuit() { + return silentQuit; + } + + public boolean isWelcome() { + return welcome; + } + + public String getWelcomeMessage() { + return welcomeMessage; + } + + public boolean isPrivateWelcome() { + return privateWelcome; + } + + public String getPrivateWelcomeMessage() { + return privateWelcomeMessage; + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyMessages.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyMessages.java new file mode 100644 index 00000000..efe755b7 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/config/ProxyMessages.java @@ -0,0 +1,96 @@ +package xyz.olivermartin.multichat.proxy.common.config; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; + +import java.util.HashMap; +import java.util.Map; + +/** + * Class to represent the proxy's messages.yml. + *

+ * All methods should be relatively straight forward and represent their respective entries in the config. + */ +public class ProxyMessages extends AbstractProxyConfig { + + private final Map messagesMap = new HashMap<>(); + + ProxyMessages() { + super("messages.yml"); + } + + @Override + void reloadValues() { + messagesMap.clear(); + + getConfig().getKeys().forEach(key -> messagesMap.put(key, getConfig().getString(key))); + } + + public String getPrefix() { + return messagesMap.getOrDefault("prefix", "&8&l[&2&lM&a&lC&8&l]&f "); + } + + public String getMessage(String key) { + return messagesMap.getOrDefault(key, "&cERROR - Please report to plugin dev - No message defined for: " + key); + } + + public void sendMessage(CommandSender sender, String id) { + sendMessage(sender, id, true); + } + + public void sendMessage(CommandSender sender, String id, boolean usePrefix) { + sendMessage(sender, id, usePrefix, null); + } + + public void sendMessage(CommandSender sender, String id, String special) { + sendMessage(sender, id, true, special, false); + } + + public void sendMessage(CommandSender sender, String id, boolean usePrefix, String special) { + sendMessage(sender, id, usePrefix, special, false); + } + + public void sendMessage(CommandSender sender, String id, String special, boolean specialJson) { + sendMessage(sender, id, true, special, specialJson); + } + + // TODO: [2.0] [ConfigRefactor] Should probably take another look at this method at some point + public void sendMessage(CommandSender sender, String id, boolean usePrefix, String special, boolean specialJson) { + + boolean isSpecial = special != null; + + // Translate format codes + String message = (usePrefix ? getPrefix() : "+++") + getMessage(id); + message = MultiChatUtil.translateColorCodes(message); + if (isSpecial) special = MultiChatUtil.translateColorCodes(special); + + // Handle legacy servers + if (sender instanceof ProxiedPlayer) { + ProxiedPlayer player = (ProxiedPlayer) sender; + if (ProxyConfigs.CONFIG.isLegacyServer(player.getServer().getInfo().getName())) { + message = MultiChatUtil.approximateRGBColorCodes(message); + if (isSpecial) special = MultiChatUtil.approximateRGBColorCodes(special); + } + } else { + // Handle console + message = MultiChatUtil.approximateRGBColorCodes(message); + if (isSpecial) special = MultiChatUtil.approximateRGBColorCodes(special); + } + + // If we want to treat the "Special" part as Json, then we will parse it here and treat it as a non special message + if (isSpecial && specialJson) { + message = message.replace("%SPECIAL%", special); + isSpecial = false; + } + + // Parse & send message + if (isSpecial) { + sender.sendMessage(ProxyJsonUtils.parseMessage(message, "%SPECIAL%", special)); + } else { + sender.sendMessage(ProxyJsonUtils.parseMessage(message)); + } + + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/Context.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/Context.java new file mode 100644 index 00000000..db42d472 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/Context.java @@ -0,0 +1,127 @@ +package xyz.olivermartin.multichat.proxy.common.contexts; + +import java.util.ArrayList; +import java.util.List; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +public class Context { + + private String id; + private int priority; + private String defaultChannel; + private boolean forceChannel; + private boolean blacklistServers; + private List servers; + + public Context(String id, int priority, String defaultChannel, boolean forceChannel, boolean blacklistServers, List servers) { + this.id = id; + this.priority = priority; + this.defaultChannel = defaultChannel; + this.forceChannel = forceChannel; + this.blacklistServers = blacklistServers; + this.servers = servers; + } + + public Context(String id, int priority, String defaultChannel, boolean forceChannel) { + this.id = id; + this.priority = priority; + this.defaultChannel = defaultChannel; + this.forceChannel = forceChannel; + this.blacklistServers = true; + this.servers = new ArrayList(); + } + + public Context(String id, int priority, String defaultChannel) { + this.id = id; + this.priority = priority; + this.defaultChannel = defaultChannel; + this.forceChannel = false; + this.blacklistServers = true; + this.servers = new ArrayList(); + } + + public Context(String id, int priority) { + this.id = id; + this.priority = priority; + this.defaultChannel = "global"; + this.forceChannel = false; + this.blacklistServers = true; + this.servers = new ArrayList(); + } + + /** + * Get the ID of this context + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * Get the priority of this context + * @return the priority + */ + public int getPriority() { + return this.priority; + } + + /** + * Get the default channel of this context + * @return the default channel + */ + public String getDefaultChannel() { + return this.defaultChannel; + } + + /** + * Are players forced into the default channel every time they enter the context? + * @return true if they are forced into the default channel + */ + public boolean isForceChannel() { + return this.forceChannel; + } + + /** + * Is the server list a blacklist (rather than a whitelist) + * @return true if the server list is a blacklist + */ + public boolean isBlacklistServers() { + return this.blacklistServers; + } + + /** + *

Gets the blacklist/whitelist of servers for this context.

+ *

List is a blacklist if isBlacklistServers() returns true, otherwise is a whitelist

+ * @return the blacklist/whitelist of servers + */ + public List getServerList() { + return this.servers; + } + + /** + *

Checks if a command sender is contained by this context (on one of the allowed servers)

+ *

Note: If the sender is not a player then it is assumed they are always in the context

+ * @param sender The sender to check + * @return true if the sender is within the context + */ + public boolean contains(CommandSender sender) { + + if (!(sender instanceof ProxiedPlayer)) return true; + + ProxiedPlayer player = (ProxiedPlayer) sender; + + if (player.getServer() == null) return false; + + String server = player.getServer().getInfo().getName(); + + if (blacklistServers) { + return !servers.contains(server); + } else { + return servers.contains(server); + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/ContextManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/ContextManager.java new file mode 100644 index 00000000..3bfcb850 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/ContextManager.java @@ -0,0 +1,52 @@ +package xyz.olivermartin.multichat.proxy.common.contexts; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import net.md_5.bungee.api.connection.ProxiedPlayer; + +public class ContextManager { + + private Map contexts; + private GlobalContext global; + + public ContextManager(GlobalContext global) { + contexts = new HashMap(); + this.global = global; + contexts.put("global", global); + } + + public Context getGlobalContext() { + return this.global; + } + + public void setGlobalContext(GlobalContext global) { + this.global = global; + contexts.remove("global"); + contexts.put("global", global); + } + + public Optional getContext(String id) { + return Optional.ofNullable(contexts.get(id)); + } + + public Context getContext(ProxiedPlayer player) { + + int lastPriority = -1; + Context lastContext = null; + + for (Context c : contexts.values()) { + if (c.contains(player)) { + if (c.getPriority() > lastPriority) { + lastContext = c; + lastPriority = c.getPriority(); + } + } + } + + return lastContext; + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/GlobalContext.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/GlobalContext.java new file mode 100644 index 00000000..c0699429 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/contexts/GlobalContext.java @@ -0,0 +1,34 @@ +package xyz.olivermartin.multichat.proxy.common.contexts; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +import java.util.ArrayList; + +public class GlobalContext extends Context { + + public GlobalContext(String defaultChannel, boolean forceChannel, boolean blacklistServers) { + super("global", 0, defaultChannel, forceChannel, blacklistServers, new ArrayList<>()); + } + + @Override + public boolean contains(CommandSender sender) { + if (!(sender instanceof ProxiedPlayer)) return true; + + ProxiedPlayer player = (ProxiedPlayer) sender; + if (player.getServer() == null) return false; + + /* + global blacklist needed + -------------------------------- + 0 0 0 + 0 1 1 + 1 0 1 + 1 1 0 + + This concludes that we can use XOR + */ + return ProxyConfigs.CONFIG.isGlobalServer(player.getServer().getInfo().getName()) ^ isBlacklistServers(); + } +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyLoginListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyLoginListener.java new file mode 100644 index 00000000..cd795541 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyLoginListener.java @@ -0,0 +1,67 @@ +package xyz.olivermartin.multichat.proxy.common.listeners; + +import java.util.UUID; + +import com.olivermartin410.plugins.TChatInfo; + +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.PostLoginEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import net.md_5.bungee.event.EventPriority; +import xyz.olivermartin.multichat.bungee.ConsoleManager; +import xyz.olivermartin.multichat.bungee.PlayerMetaManager; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +public class ProxyLoginListener implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onLogin(PostLoginEvent event) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + ProxiedPlayer player = event.getPlayer(); + UUID uuid = player.getUniqueId(); + + // Set up modchat info + if (player.hasPermission("multichat.staff.mod")) { + + if (!ds.getModChatPreferences().containsKey(uuid)) { + + TChatInfo chatinfo = new TChatInfo(); + chatinfo.setChatColor(ProxyConfigs.CONFIG.getModChatColor()); + chatinfo.setNameColor(ProxyConfigs.CONFIG.getModNameColor()); + ds.getModChatPreferences().put(uuid, chatinfo); + + } + } + + // Set up adminchat info + if (player.hasPermission("multichat.staff.admin")) { + + if (!ds.getAdminChatPreferences().containsKey(uuid)) { + + TChatInfo chatinfo = new TChatInfo(); + chatinfo.setChatColor(ProxyConfigs.CONFIG.getAdminChatColor()); + chatinfo.setNameColor(ProxyConfigs.CONFIG.getAdminNameColor()); + ds.getAdminChatPreferences().put(uuid, chatinfo); + + } + } + + // Register player in volatile meta manager + PlayerMetaManager.getInstance().registerPlayer(uuid, event.getPlayer().getName()); + + // Set up groupchat info + if (!ds.getViewedChats().containsKey(uuid)) { + + ds.getViewedChats().put(uuid, null); + ConsoleManager.log("Registered player " + player.getName()); + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyLogoutListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyLogoutListener.java new file mode 100644 index 00000000..368ecded --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyLogoutListener.java @@ -0,0 +1,106 @@ +package xyz.olivermartin.multichat.proxy.common.listeners; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.PlayerDisconnectEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import net.md_5.bungee.event.EventPriority; +import xyz.olivermartin.multichat.bungee.*; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.UUID; + +public class ProxyLogoutListener implements Listener { + + private void displayMessage(ProxiedPlayer player, String message) { + + if (player.getServer() == null) return; + + message = MultiChatUtil.translateColorCodes(message); + + if (ProxyConfigs.CONFIG.isLegacyServer(player.getServer().getInfo().getName())) message = MultiChatUtil.approximateRGBColorCodes(message); + + player.sendMessage(ProxyJsonUtils.parseMessage(message)); + + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onLogout(PlayerDisconnectEvent event) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + ProxiedPlayer player = event.getPlayer(); + UUID uuid = event.getPlayer().getUniqueId(); + + /* + * Remove volatile entries + */ + + if (ds.getHiddenStaff().contains(uuid)) { + ds.getHiddenStaff().remove(uuid); + } + + if (Events.mcbPlayers.contains(uuid)) { + Events.mcbPlayers.remove(uuid); + } + + if (Events.MCToggle.contains(uuid)) { + Events.MCToggle.remove(uuid); + } + if (Events.ACToggle.contains(uuid)) { + Events.ACToggle.remove(uuid); + } + if (Events.GCToggle.contains(uuid)) { + Events.GCToggle.remove(uuid); + } + + // If using sessional ignore, then wipe ignores stored + if (ProxyConfigs.CHAT_CONTROL.isSessionIgnore()) { + ChatControl.unignoreAll(uuid); + } + + // Reset their spam data on logout (nothing is stored persistently) + ChatControl.spamPardonPlayer(uuid); + + // Remove viewed group chat preferences + if (ds.getViewedChats().containsKey(uuid)) { + ds.getViewedChats().remove(uuid); + } + + // Unregister player from volatile meta store + PlayerMetaManager.getInstance().unregisterPlayer(uuid); + + ConsoleManager.log("Un-Registered player " + player.getName()); + + // Remove player from the "joined network" list + ds.getJoinedNetwork().remove(player.getUniqueId()); + + // If we are handling the quit messages, then handle them... + if (ProxyConfigs.JOIN_MESSAGES.isShowQuit()) { + // Get the formats + String quitFormat = ProxyConfigs.JOIN_MESSAGES.getNetworkQuit(); + boolean silenceQuit = player.hasPermission("multichat.staff.silentjoin"); + if (silenceQuit) + quitFormat = ProxyConfigs.JOIN_MESSAGES.getSilentQuit(); + + // Replace the placeholders + String serverName = player.getServer().getInfo().getName(); + quitFormat = new ChatManipulation().replaceJoinMsgVars(quitFormat, player.getName(), serverName); + + // Broadcast + for (ProxiedPlayer target : ProxyServer.getInstance().getPlayers()) { + if (silenceQuit && !target.hasPermission("multichat.staff.silentjoin")) + continue; + + displayMessage(target, quitFormat); + } + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyServerConnectedListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyServerConnectedListener.java new file mode 100644 index 00000000..c428e0b6 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyServerConnectedListener.java @@ -0,0 +1,164 @@ +package xyz.olivermartin.multichat.proxy.common.listeners; + +import de.myzelyam.api.vanish.BungeeVanishAPI; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.ServerConnectedEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import net.md_5.bungee.event.EventPriority; +import xyz.olivermartin.multichat.bungee.*; +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyJsonUtils; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; + +import java.util.UUID; + +public class ProxyServerConnectedListener implements Listener { + + private void displayMessage(ProxiedPlayer player, ProxiedPlayer sender, String senderServer, String message) { + + message = MultiChatUtil.translateColorCodes(message); + + if (player.getUniqueId().equals(sender.getUniqueId())) { + if (ProxyConfigs.CONFIG.isLegacyServer(senderServer)) message = MultiChatUtil.approximateRGBColorCodes(message); + } else { + if (player.getServer() == null) return; + if (ProxyConfigs.CONFIG.isLegacyServer(player.getServer().getInfo().getName())) message = MultiChatUtil.approximateRGBColorCodes(message); + } + + player.sendMessage(ProxyJsonUtils.parseMessage(message)); + + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onServerConnected(ServerConnectedEvent event) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + + ProxiedPlayer player = event.getPlayer(); + UUID uuid = player.getUniqueId(); + + String defaultChannel = MultiChatProxy.getInstance().getContextManager().getGlobalContext().getDefaultChannel(); + boolean forceChannel = MultiChatProxy.getInstance().getContextManager().getGlobalContext().isForceChannel(); + boolean firstJoin = false; + + // Set up chat info + if (!ChatModeManager.getInstance().existsPlayer(uuid)) { + + boolean globalMode; + + if (!defaultChannel.equalsIgnoreCase("local")) { + globalMode = true; + } else { + globalMode = false; + } + ChatModeManager.getInstance().registerPlayer(uuid, globalMode); + firstJoin = true; + + } + + // If we are forcing the channels, then force it + if (forceChannel) { + + boolean globalMode; + if (!defaultChannel.equalsIgnoreCase("local")) { + globalMode = true; + } else { + globalMode = false; + } + ChatModeManager.getInstance().registerPlayer(uuid, globalMode); + + } + + // Set player to appropriate channels in NEW CHANNELS system + if (ChatModeManager.getInstance().isGlobal(uuid)) { + channelManager.select(uuid, "global"); + } else { + channelManager.select(uuid, "local"); + } + + // Remove any old UUID - Name pairings + if (UUIDNameManager.existsUUID(uuid)) { + UUIDNameManager.removeUUID(uuid); + } + + // Register updated entry in UUID - Name map + UUIDNameManager.addNew(uuid, player.getName()); + ConsoleManager.log("Refreshed UUID-Name lookup: " + uuid.toString()); + + // If player is only switching server (not joining for first time) then leave now + if (ds.getJoinedNetwork().contains(player.getUniqueId())) return; + ds.getJoinedNetwork().add(player.getUniqueId()); + + // If MultiChat is handling join messages... + if (ProxyConfigs.JOIN_MESSAGES.isShowJoin() + || ProxyConfigs.JOIN_MESSAGES.isWelcome() + || ProxyConfigs.JOIN_MESSAGES.isPrivateWelcome()) { + + // PremiumVanish support, return as early as possible to avoid loading unnecessary resources + if (MultiChat.premiumVanish && ProxyConfigs.CONFIG.isPvSilenceJoin() && BungeeVanishAPI.isInvisible(player)) { + return; + } + + // Load join message formats from config + String joinformat = ProxyConfigs.JOIN_MESSAGES.getServerJoin(); + String silentformat = ProxyConfigs.JOIN_MESSAGES.getSilentJoin(); + String welcomeMessage = ProxyConfigs.JOIN_MESSAGES.getWelcomeMessage(); + String privateWelcomeMessage = ProxyConfigs.JOIN_MESSAGES.getPrivateWelcomeMessage(); + + // Replace the placeholders + ChatManipulation chatman = new ChatManipulation(); // TODO Legacy + joinformat = chatman.replaceJoinMsgVars(joinformat, player.getName(), event.getServer().getInfo().getName()); + silentformat = chatman.replaceJoinMsgVars(silentformat, player.getName(), event.getServer().getInfo().getName()); + welcomeMessage = chatman.replaceJoinMsgVars(welcomeMessage, player.getName(), event.getServer().getInfo().getName()); + privateWelcomeMessage = chatman.replaceJoinMsgVars(privateWelcomeMessage, player.getName(), event.getServer().getInfo().getName()); + + // Check which messages should be broadcast + boolean broadcastWelcome = ProxyConfigs.JOIN_MESSAGES.isWelcome(); + boolean privateWelcome = ProxyConfigs.JOIN_MESSAGES.isPrivateWelcome(); + boolean broadcastJoin = !player.hasPermission("multichat.staff.silentjoin"); + + // Broadcast + for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { + + if (broadcastJoin) { + + if (firstJoin && broadcastWelcome) { + displayMessage(onlineplayer, event.getPlayer(), event.getServer().getInfo().getName(), welcomeMessage); + } + + if (firstJoin && privateWelcome + && onlineplayer.getName().equals(player.getName())) { + + displayMessage(onlineplayer, event.getPlayer(), event.getServer().getInfo().getName(), privateWelcomeMessage); + + } + + if (ProxyConfigs.JOIN_MESSAGES.isShowJoin()) { + displayMessage(onlineplayer, event.getPlayer(), event.getServer().getInfo().getName(), joinformat); + } + + } else { + + ds.getHiddenStaff().add(player.getUniqueId()); + + if (ProxyConfigs.JOIN_MESSAGES.isShowJoin()) { + if (onlineplayer.hasPermission("multichat.staff.silentjoin") ) { + displayMessage(onlineplayer, event.getPlayer(), event.getServer().getInfo().getName(), silentformat); + } + } + + } + + } + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyServerSwitchListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyServerSwitchListener.java new file mode 100644 index 00000000..4bf8794a --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/ProxyServerSwitchListener.java @@ -0,0 +1,63 @@ +package xyz.olivermartin.multichat.proxy.common.listeners; + +import java.util.concurrent.TimeUnit; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.ServerSwitchEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import net.md_5.bungee.event.EventPriority; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.ProxyLocalCommunicationManager; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +public class ProxyServerSwitchListener implements Listener { + + @EventHandler(priority = EventPriority.LOWEST) + public void onServerSwitch(ServerSwitchEvent event) { + + // Tell the new server the player's channel preference & if it is a legacy server + ProxyServer.getInstance().getScheduler().schedule(MultiChatProxy.getInstance().getPlugin(), new Runnable() { + + public void run() { + + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + String channelFormat; + + switch (channelManager.getChannel(event.getPlayer())) { + + case "global": + channelFormat = channelManager.getGlobalChannel().getInfo().getFormat(); + break; + case "local": + channelFormat = channelManager.getLocalChannel().getFormat(); + break; + default: + if (channelManager.existsProxyChannel(channelManager.getChannel(event.getPlayer()))) { + channelFormat = channelManager.getProxyChannel(channelManager.getChannel(event.getPlayer())).get().getInfo().getFormat(); + } else { + channelFormat = channelManager.getGlobalChannel().getInfo().getFormat(); + } + break; + } + + ProxyLocalCommunicationManager.sendPlayerDataMessage(event.getPlayer().getName(), MultiChatProxy.getInstance().getChannelManager().getChannel(event.getPlayer()), channelFormat, event.getPlayer().getServer().getInfo(), (event.getPlayer().hasPermission("multichat.chat.colour")||event.getPlayer().hasPermission("multichat.chat.color")||event.getPlayer().hasPermission("multichat.chat.colour.simple")||event.getPlayer().hasPermission("multichat.chat.color.simple")), (event.getPlayer().hasPermission("multichat.chat.colour")||event.getPlayer().hasPermission("multichat.chat.color")||event.getPlayer().hasPermission("multichat.chat.colour.rgb")||event.getPlayer().hasPermission("multichat.chat.color.rgb"))); + ProxyLocalCommunicationManager.sendLegacyServerData(event.getPlayer().getServer().getInfo()); + + if (ProxyConfigs.CONFIG.isFetchSpigotDisplayNames()) { + + ProxiedPlayer player = event.getPlayer(); + if (player.getServer() != null) { + ProxyLocalCommunicationManager.sendUpdatePlayerMetaRequestMessage(player.getName(), player.getServer().getInfo()); + } + + } + } + + }, 500L, TimeUnit.MILLISECONDS); + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerActionListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerActionListener.java new file mode 100644 index 00000000..1d874526 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerActionListener.java @@ -0,0 +1,62 @@ +package xyz.olivermartin.multichat.proxy.common.listeners.communication; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.util.regex.PatternSyntaxException; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.PluginMessageEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import xyz.olivermartin.multichat.common.communication.CommChannels; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; + +/** + * Listener for communication over the Player Action communication channel + * + * @author Oliver Martin (Revilo410) + * + */ +public class ProxyPlayerActionListener implements Listener { + + @EventHandler + public void onPluginMessage(PluginMessageEvent event) { + + // Ignore if sent to a different channel + if (!event.getTag().equals(CommChannels.PLAYER_ACTION)) return; + + event.setCancelled(true); + + ByteArrayInputStream stream = new ByteArrayInputStream(event.getData()); + DataInputStream in = new DataInputStream(stream); + + String command; + String playerRegex; + + try { + command = in.readUTF(); + playerRegex = in.readUTF(); + } catch (IOException e) { + e.printStackTrace(); + return; + } + + try { + + for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { + + if (p.getName().matches(playerRegex)) { + ProxyServer.getInstance().getPluginManager().dispatchCommand(p, command); + } + + } + + } catch (PatternSyntaxException e) { + ProxyConfigs.MESSAGES.sendMessage(ProxyServer.getInstance().getConsole(), "command_execute_regex"); + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerChatListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerChatListener.java new file mode 100644 index 00000000..ca91d9ea --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerChatListener.java @@ -0,0 +1,122 @@ +package xyz.olivermartin.multichat.proxy.common.listeners.communication; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.PluginMessageEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import xyz.olivermartin.multichat.bungee.DebugManager; +import xyz.olivermartin.multichat.bungee.PlayerMeta; +import xyz.olivermartin.multichat.bungee.PlayerMetaManager; +import xyz.olivermartin.multichat.common.communication.CommChannels; +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.channels.ChannelManager; +import xyz.olivermartin.multichat.proxy.common.channels.proxy.ProxyChannel; + +/** + * Listener for communication over the Player Chat communication channel + * + * @author Oliver Martin (Revilo410) + * + */ +public class ProxyPlayerChatListener implements Listener { + + @SuppressWarnings("unchecked") + @EventHandler + public void onPluginMessage(PluginMessageEvent event) { + + // Ignore if sent to a different channel + if (!event.getTag().equals(CommChannels.PLAYER_CHAT)) return; + + event.setCancelled(true); + + /* + * Possible channels: + * - global + * - local (spy) + * + * This range will expand in the future + */ + + ByteArrayInputStream stream = new ByteArrayInputStream(event.getData()); + + + UUID uuid; + String channel; + String message; + String format; + Set otherRecipients; + + try { + + ObjectInputStream in = new ObjectInputStream(stream); + + uuid = UUID.fromString(in.readUTF()); + DebugManager.log("{multichat:pchat} UUID = '" + uuid + "'"); + channel = in.readUTF(); + DebugManager.log("{multichat:pchat} Channel = '" + channel + "'"); + message = in.readUTF(); + DebugManager.log("{multichat:pchat} Message = '" + message + "'"); + format = in.readUTF(); + DebugManager.log("{multichat:pchat} Format = '" + format + "'"); + otherRecipients = (Set) in.readObject(); + + } catch (IOException | ClassNotFoundException e) { + e.printStackTrace(); + return; + } + + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + + // If the player UUID doesn't exist, then ignore it + if (player == null) { + DebugManager.log("{multichat:pchat} Could not get player! Abandoning chat message... (Is IP-Forwarding on?)"); + return; + } + + DebugManager.log("{multichat:pchat} Got player successfully! Name = '" + player.getName() + "'"); + + Optional opm = PlayerMetaManager.getInstance().getPlayer(uuid); + ChannelManager channelManager = MultiChatProxy.getInstance().getChannelManager(); + + if (opm.isPresent()) { + + switch (channel) { + + case "global": + channelManager.getGlobalChannel().distributeMessage(player, message, format, otherRecipients); + break; + + case "local": + channelManager.getLocalChannel().distributeMessage(player, message, format, otherRecipients); + break; + + default: + + Optional opProxyChannel = channelManager.getProxyChannel(channel); + + if (opProxyChannel.isPresent()) { + + ProxyChannel proxyChannel = opProxyChannel.get(); + proxyChannel.distributeMessage(player, message, format, otherRecipients); + + } else { + DebugManager.log("{multichat:pchat} Channel: " + channel + ", is not recognised"); + } + + return; + + } + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerMetaListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerMetaListener.java new file mode 100644 index 00000000..21338f58 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyPlayerMetaListener.java @@ -0,0 +1,108 @@ +package xyz.olivermartin.multichat.proxy.common.listeners.communication; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.util.Optional; +import java.util.UUID; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.PluginMessageEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import xyz.olivermartin.multichat.bungee.PlayerMeta; +import xyz.olivermartin.multichat.bungee.PlayerMetaManager; +import xyz.olivermartin.multichat.common.communication.CommChannels; + +/** + * Listener for communication over the Player Meta communication channel + * + * @author Oliver Martin (Revilo410) + * + */ +public class ProxyPlayerMetaListener implements Listener { + + @EventHandler + public void onPluginMessage(PluginMessageEvent event) { + + // Ignore if sent to a different channel + if (!event.getTag().equals(CommChannels.PLAYER_META)) return; + + event.setCancelled(true); + + /* + * Possible meta IDs: + * - prefix + * - suffix + * - dn + * - world + * - nick + */ + + ByteArrayInputStream stream = new ByteArrayInputStream(event.getData()); + DataInputStream in = new DataInputStream(stream); + + UUID uuid; + String metaId; + String metaValue; + + try { + uuid = UUID.fromString(in.readUTF()); + metaId = in.readUTF(); + metaValue = in.readUTF(); + } catch (IOException e) { + e.printStackTrace(); + return; + } + + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + + // If the player UUID doesn't exist, then ignore it + if (player == null) return; + + synchronized (player) { + + Optional opm = PlayerMetaManager.getInstance().getPlayer(uuid); + + if (opm.isPresent()) { + + switch (metaId) { + + case "prefix": + opm.get().prefix = metaValue; + PlayerMetaManager.getInstance().updateDisplayName(uuid); // TODO Do we need this? + break; + + case "suffix": + opm.get().suffix = metaValue; + PlayerMetaManager.getInstance().updateDisplayName(uuid); // TODO Do we need this? + break; + + case "dn": + opm.get().localDisplayName = metaValue; + PlayerMetaManager.getInstance().updateDisplayName(uuid); // TODO Do we need this? + break; + + case "world": + opm.get().world = metaValue; + PlayerMetaManager.getInstance().updateDisplayName(uuid); // TODO Do we need this? + break; + + case "nick": + opm.get().nick = metaValue; + PlayerMetaManager.getInstance().updateDisplayName(uuid); // TODO Do we need this? + break; + + default: + return; + + } + + } + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyServerActionListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyServerActionListener.java new file mode 100644 index 00000000..59be0632 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/listeners/communication/ProxyServerActionListener.java @@ -0,0 +1,45 @@ +package xyz.olivermartin.multichat.proxy.common.listeners.communication; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.event.PluginMessageEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import xyz.olivermartin.multichat.common.communication.CommChannels; + +/** + * Listener for communication over the Server Action communication channel + * + * @author Oliver Martin (Revilo410) + * + */ +public class ProxyServerActionListener implements Listener { + + @EventHandler + public void onPluginMessage(PluginMessageEvent event) { + + // Ignore if sent to a different channel + if (!event.getTag().equals(CommChannels.SERVER_ACTION)) return; + + event.setCancelled(true); + + ByteArrayInputStream stream = new ByteArrayInputStream(event.getData()); + DataInputStream in = new DataInputStream(stream); + + String command; + + try { + command = in.readUTF(); + } catch (IOException e) { + e.printStackTrace(); + return; + } + + ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), command); + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyDataStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyDataStore.java new file mode 100644 index 00000000..e424100c --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyDataStore.java @@ -0,0 +1,205 @@ +package xyz.olivermartin.multichat.proxy.common.storage; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import com.olivermartin410.plugins.TChatInfo; +import com.olivermartin410.plugins.TGroupChatInfo; + +/** + * A proxy data store of settings and other things for MultiChatProxy + * + *

These may be updated due to messages received from the local servers

+ * + * @author Oliver Martin (Revilo410) + * + */ +public class ProxyDataStore { + + // Is global chat frozen? + private boolean chatFrozen = false; + + // Mod chat colours + private Map modChatPreferences = new HashMap(); + + // Admin chat colours + private Map adminChatPreferences = new HashMap(); + + // Group chats + private Map groupChats = new HashMap(); + + // Which players are viewing which group chats + private Map viewedChats = new HashMap(); + + // The last person a player has messaged + private Map lastMsg = new HashMap(); + + // Who is spying on all groups? + private List allSpy = new ArrayList(); + + // Who has social spy on? + private List socialSpy = new ArrayList(); + + // Who has local spy on? + private List localSpy = new ArrayList(); + + // Which staff are hidden? + private Set hiddenStaff = new HashSet(); + + // Which players have had their join message processed for the network + private Set joinedNetwork = new HashSet(); + + public synchronized boolean isChatFrozen() { + return this.chatFrozen; + } + + /** + * @return the modchatpreferences + */ + public Map getModChatPreferences() { + return modChatPreferences; + } + + /** + * @return the adminchatpreferences + */ + public Map getAdminChatPreferences() { + return adminChatPreferences; + } + + /** + * @return the groupchats + */ + public Map getGroupChats() { + return groupChats; + } + + /** + * @return the viewedchats + */ + public Map getViewedChats() { + return viewedChats; + } + + /** + * @return the lastmsg + */ + public Map getLastMsg() { + return lastMsg; + } + + /** + * @return the allspy + */ + public List getAllSpy() { + return allSpy; + } + + /** + * @return the socialspy + */ + public List getSocialSpy() { + return socialSpy; + } + + public synchronized void setChatFrozen(boolean frozen) { + this.chatFrozen = frozen; + } + + /** + * @param modChatPreferences the modchatpreferences to set + */ + public void setModChatPreferences(Map modChatPreferences) { + this.modChatPreferences = modChatPreferences; + } + + /** + * @param adminChatPreferences the adminchatpreferences to set + */ + public void setAdminChatPreferences(Map adminChatPreferences) { + this.adminChatPreferences = adminChatPreferences; + } + + /** + * @param groupChats the groupchats to set + */ + public void setGroupChats(Map groupChats) { + this.groupChats = groupChats; + } + + /** + * @param viewedChats the viewedchats to set + */ + public void setViewedChats(Map viewedChats) { + this.viewedChats = viewedChats; + } + + /** + * @param lastMsg the lastmsg to set + */ + public void setLastMsg(Map lastMsg) { + this.lastMsg = lastMsg; + } + + /** + * @param allSpy the allspy to set + */ + public void setAllSpy(List allSpy) { + this.allSpy = allSpy; + } + + /** + * @param socialSpy the socialspy to set + */ + public void setSocialSpy(List socialSpy) { + this.socialSpy = socialSpy; + } + + /** + * @return the hiddenStaff + */ + public Set getHiddenStaff() { + return hiddenStaff; + } + + /** + * @param hiddenStaff the hiddenStaff to set + */ + public void setHiddenStaff(Set hiddenStaff) { + this.hiddenStaff = hiddenStaff; + } + + /** + * @return the localSpy + */ + public List getLocalSpy() { + return localSpy; + } + + /** + * @param localSpy the localSpy to set + */ + public void setLocalSpy(List localSpy) { + this.localSpy = localSpy; + } + + /** + * @return the joinedNetwork + */ + public Set getJoinedNetwork() { + return joinedNetwork; + } + + /** + * @param joinedNetwork the joinedNetwork to set + */ + public void setJoinedNetwork(Set joinedNetwork) { + this.joinedNetwork = joinedNetwork; + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyFileStore.java new file mode 100644 index 00000000..eb58dc28 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyFileStore.java @@ -0,0 +1,9 @@ +package xyz.olivermartin.multichat.proxy.common.storage; + +public interface ProxyFileStore { + + public boolean reload(); + + public boolean save(); + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyFileStoreManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyFileStoreManager.java new file mode 100644 index 00000000..0288b2e3 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyFileStoreManager.java @@ -0,0 +1,40 @@ +package xyz.olivermartin.multichat.proxy.common.storage; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class ProxyFileStoreManager { + + Map fileStores; + + public ProxyFileStoreManager() { + this.fileStores = new HashMap(); + } + + public void registerFileStore(String id, ProxyFileStore fileStore) { + this.fileStores.put(id.toLowerCase(), fileStore); + } + + public void unregisterFileStore(String id) { + this.fileStores.remove(id.toLowerCase()); + } + + public Optional getFileStore(String id) { + if (!fileStores.containsKey(id.toLowerCase())) return Optional.empty(); + return Optional.of(fileStores.get(id.toLowerCase())); + } + + public void reload() { + for (ProxyFileStore fileStore : fileStores.values()) { + fileStore.reload(); + } + } + + public void save() { + for (ProxyFileStore fileStore : fileStores.values()) { + fileStore.save(); + } + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyGenericFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyGenericFileStore.java new file mode 100644 index 00000000..492fcd5f --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/ProxyGenericFileStore.java @@ -0,0 +1,78 @@ +package xyz.olivermartin.multichat.proxy.common.storage; + +import java.io.File; + +import xyz.olivermartin.multichat.bungee.DebugManager; + +public abstract class ProxyGenericFileStore implements ProxyFileStore { + + private String fileName; + private File fileDirectory; + + public ProxyGenericFileStore(String fileName, File fileDirectory) { + this.fileName = fileName; + this.fileDirectory = fileDirectory; + startupFile(); + } + + public String getFileName() { + return fileName; + } + + public File getFileDirectory() { + return this.fileDirectory; + } + + public File getFile() { + return new File(fileDirectory, fileName); + } + + protected boolean startupFile() { + + File file = getFile(); + + boolean status; + + if (!file.exists()) { + status = saveFile(file); + DebugManager.log("[ProxyFileStore] [" + getFileName() + "] Created new file (was successful = " + status + ")"); + } + + status = loadFile(file); + DebugManager.log("[ProxyFileStore] [" + getFileName() + "] Loaded file (was successful = " + status + ")"); + + return status; + + } + + /** + * Save the data to file + * @return true if successful + */ + public boolean save() { + return saveFile(getFile()); + } + + /** + * Load the data from the file into the system (overwrites anything currently loaded) + * @return true if successful + */ + public boolean reload() { + return startupFile(); + } + + /** + * Load the file contents into the correct place + * @param file + * @return true if successful + */ + protected abstract boolean loadFile(File file); + + /** + * Save the file contents from the correct place + * @param file + * @return true if successful + */ + protected abstract boolean saveFile(File file); + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyAdminChatFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyAdminChatFileStore.java new file mode 100644 index 00000000..6e2bc66f --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyAdminChatFileStore.java @@ -0,0 +1,71 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.UUID; + +import com.olivermartin410.plugins.TChatInfo; + +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyAdminChatFileStore extends ProxyGenericFileStore { + + public ProxyAdminChatFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + HashMap result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (HashMap)in.readObject(); + in.close(); + ds.setAdminChatPreferences(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + try { + + FileOutputStream stream = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(stream); + out.writeObject(ds.getAdminChatPreferences()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyAnnouncementsFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyAnnouncementsFileStore.java new file mode 100644 index 00000000..0009fdc9 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyAnnouncementsFileStore.java @@ -0,0 +1,64 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; + +import xyz.olivermartin.multichat.bungee.Announcements; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyAnnouncementsFileStore extends ProxyGenericFileStore { + + public ProxyAnnouncementsFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + HashMap result = null; + + try { + + FileInputStream stream = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(stream); + result = (HashMap)in.readObject(); + in.close(); + Announcements.loadAnnouncementList(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + try { + + FileOutputStream stream = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(stream); + out.writeObject(Announcements.getAnnouncementList()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyBulletinsFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyBulletinsFileStore.java new file mode 100644 index 00000000..22cdf627 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyBulletinsFileStore.java @@ -0,0 +1,71 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; + +import xyz.olivermartin.multichat.bungee.Bulletins; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyBulletinsFileStore extends ProxyGenericFileStore { + + public ProxyBulletinsFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + ArrayList result = null; + boolean enabled = false; + int timeBetween = 0; + + try { + + FileInputStream stream = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(stream); + enabled = in.readBoolean(); + timeBetween = in.readInt(); + result = (ArrayList)in.readObject(); + in.close(); + Bulletins.setArrayList(result); + if (enabled) Bulletins.startBulletins(timeBetween); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + try { + + FileOutputStream stream = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(stream); + out.writeBoolean(Bulletins.isEnabled()); + out.writeInt(Bulletins.getTimeBetween()); + out.writeObject(Bulletins.getArrayList()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyCastsFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyCastsFileStore.java new file mode 100644 index 00000000..7bd9049f --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyCastsFileStore.java @@ -0,0 +1,64 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; + +import xyz.olivermartin.multichat.bungee.CastControl; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyCastsFileStore extends ProxyGenericFileStore { + + public ProxyCastsFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + HashMap result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (HashMap)in.readObject(); + in.close(); + CastControl.castList = result; + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + try { + + FileOutputStream saveFile = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(saveFile); + out.writeObject(CastControl.castList); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGlobalChatFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGlobalChatFileStore.java new file mode 100644 index 00000000..ffd933ad --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGlobalChatFileStore.java @@ -0,0 +1,65 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Map; +import java.util.UUID; + +import xyz.olivermartin.multichat.bungee.ChatModeManager; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyGlobalChatFileStore extends ProxyGenericFileStore { + + public ProxyGlobalChatFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + Map result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (Map)in.readObject(); + in.close(); + ChatModeManager.getInstance().loadData(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + try { + + FileOutputStream saveFile = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(saveFile); + out.writeObject(ChatModeManager.getInstance().getData()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGroupChatFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGroupChatFileStore.java new file mode 100644 index 00000000..7bfa4493 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGroupChatFileStore.java @@ -0,0 +1,70 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; + +import com.olivermartin410.plugins.TGroupChatInfo; + +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyGroupChatFileStore extends ProxyGenericFileStore { + + public ProxyGroupChatFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + HashMap result = null; + + try { + + FileInputStream stream = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(stream); + result = (HashMap)in.readObject(); + in.close(); + ds.setGroupChats(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + try { + + FileOutputStream stream = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(stream); + out.writeObject(ds.getGroupChats()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGroupSpyFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGroupSpyFileStore.java new file mode 100644 index 00000000..e11d9350 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyGroupSpyFileStore.java @@ -0,0 +1,69 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; +import java.util.UUID; + +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyGroupSpyFileStore extends ProxyGenericFileStore { + + public ProxyGroupSpyFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + List result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (List)in.readObject(); + in.close(); + ds.setAllSpy(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + try { + + FileOutputStream stream = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(stream); + out.writeObject(ds.getAllSpy()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyIgnoreFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyIgnoreFileStore.java new file mode 100644 index 00000000..f49a7fed --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyIgnoreFileStore.java @@ -0,0 +1,73 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import xyz.olivermartin.multichat.bungee.ChatControl; +import xyz.olivermartin.multichat.proxy.common.config.ProxyConfigs; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyIgnoreFileStore extends ProxyGenericFileStore { + + public ProxyIgnoreFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + if (ProxyConfigs.CHAT_CONTROL.isSessionIgnore()) { + ChatControl.setIgnoreMap(new HashMap<>()); + return true; + } + + Map> result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (Map>)in.readObject(); + in.close(); + ChatControl.setIgnoreMap(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + if (ProxyConfigs.CHAT_CONTROL.isSessionIgnore()) return true; + + try { + + FileOutputStream saveFile = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(saveFile); + out.writeObject(ChatControl.getIgnoreMap()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyLocalSpyFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyLocalSpyFileStore.java new file mode 100644 index 00000000..c632b973 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyLocalSpyFileStore.java @@ -0,0 +1,69 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; +import java.util.UUID; + +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyLocalSpyFileStore extends ProxyGenericFileStore { + + public ProxyLocalSpyFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + List result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (List)in.readObject(); + in.close(); + ds.setLocalSpy(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + try { + + FileOutputStream saveFile = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(saveFile); + out.writeObject(ds.getLocalSpy()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyMuteFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyMuteFileStore.java new file mode 100644 index 00000000..6beedb06 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyMuteFileStore.java @@ -0,0 +1,65 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Set; +import java.util.UUID; + +import xyz.olivermartin.multichat.bungee.ChatControl; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyMuteFileStore extends ProxyGenericFileStore { + + public ProxyMuteFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + Set result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (Set)in.readObject(); + in.close(); + ChatControl.setMutedPlayers(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + try { + + FileOutputStream saveFile = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(saveFile); + out.writeObject(ChatControl.getMutedPlayers()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxySocialSpyFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxySocialSpyFileStore.java new file mode 100644 index 00000000..8e62b1f3 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxySocialSpyFileStore.java @@ -0,0 +1,69 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; +import java.util.UUID; + +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxySocialSpyFileStore extends ProxyGenericFileStore { + + public ProxySocialSpyFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + List result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (List)in.readObject(); + in.close(); + ds.setSocialSpy(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + try { + + FileOutputStream saveFile = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(saveFile); + out.writeObject(ds.getSocialSpy()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyStaffChatFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyStaffChatFileStore.java new file mode 100644 index 00000000..b892e910 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyStaffChatFileStore.java @@ -0,0 +1,71 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.UUID; + +import com.olivermartin410.plugins.TChatInfo; + +import xyz.olivermartin.multichat.proxy.common.MultiChatProxy; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyDataStore; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyStaffChatFileStore extends ProxyGenericFileStore { + + public ProxyStaffChatFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + HashMap result = null; + + try { + + FileInputStream stream = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(stream); + result = (HashMap)in.readObject(); + in.close(); + ds.setModChatPreferences(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + ProxyDataStore ds = MultiChatProxy.getInstance().getDataStore(); + + try { + + FileOutputStream stream = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(stream); + out.writeObject(ds.getModChatPreferences()); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyUUIDNameFileStore.java b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyUUIDNameFileStore.java new file mode 100644 index 00000000..760365ae --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/proxy/common/storage/files/ProxyUUIDNameFileStore.java @@ -0,0 +1,65 @@ +package xyz.olivermartin.multichat.proxy.common.storage.files; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.UUID; + +import xyz.olivermartin.multichat.bungee.UUIDNameManager; +import xyz.olivermartin.multichat.proxy.common.storage.ProxyGenericFileStore; + +public class ProxyUUIDNameFileStore extends ProxyGenericFileStore { + + public ProxyUUIDNameFileStore(String fileName, File fileDirectory) { + super(fileName, fileDirectory); + } + + @SuppressWarnings("unchecked") + @Override + protected boolean loadFile(File file) { + + HashMap result = null; + + try { + + FileInputStream saveFile = new FileInputStream(file); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (HashMap)in.readObject(); + in.close(); + UUIDNameManager.uuidname.putAll(result); + return true; + + } catch (IOException|ClassNotFoundException e) { + + e.printStackTrace(); + return false; + + } + + } + + @Override + protected boolean saveFile(File file) { + + try { + + FileOutputStream stream = new FileOutputStream(file); + ObjectOutputStream out = new ObjectOutputStream(stream); + out.writeObject(UUIDNameManager.uuidname); + out.close(); + return true; + + } catch (IOException e) { + + e.printStackTrace(); + return false; + + } + + } + +} diff --git a/multichat/src/main/resources/aliases.yml b/multichat/src/main/resources/aliases.yml new file mode 100644 index 00000000..9cf28195 --- /dev/null +++ b/multichat/src/main/resources/aliases.yml @@ -0,0 +1,173 @@ +############################################################ +# +------------------------------------------------------+ # +# | MultiChat Command Aliases | # +# +------------------------------------------------------+ # +############################################################ + +# By Revilo410 + +################## +# DON'T EDIT # +version: "1.10" # +################## + +# 1. Command Aliases + +############################################################ +# +------------------------------------------------------+ # +# | General | # +# +------------------------------------------------------+ # +############################################################ + +# The admin chat colour command has the following aliases (other than /mcacc) +mcacc: +- acc + +# The admin chat command has the following aliases (other than /mcac) +mcac: +- ac + +# The announcement command has the following aliases (other than /mcannouncement) +mcannouncement: +- announcement +- announce +- announcements + +# The bulletin command has the following aliases (other than /mcbulletin) +mcbulletin: +- bulletin +- bulletins + +# The cast command has the following aliases (other than /mccast) +mccast: +- cast + +# The channel command has the following aliases (other than /mcchannel) +mcchannel: +- channel +- ch + +# The clearchat command has the following aliases (other than /mcclearchat) +mcclearchat: +- clearchat +- chatclear +- wipechat +- killchat + +# The display command has the following aliases (other than /mcdisplay) +mcdisplay: +- display + +# The freezechat command has the following aliases (other than /mcfreezechat) +mcfreezechat: +- freezechat +- pausechat +- lockchat +- chatlock + +# The group chat command has the following aliases (other than /mcgc) +mcgc: +- gc + +# The global command has the following aliases (other than /mcglobal) +mcglobal: +- global +- g + +# The group command has the following aliases (other than /mcgroup) +mcgroup: +- group + +# The group list command has the following aliases (other than /mcgroups) +mcgroups: +- groups +- grouplist + +# The helpme command has the following aliases (other than /mchelpme) +mchelpme: +- helpme +- helpop + +# The ignore command has the following aliases (other than /mcignore) +mcignore: +- ignore +- blockplayer + +# The local command has the following aliases (other than /mclocal) +mclocal: +- local +- l + +# The localspy command has the following aliases (other than /mclocalspy) +mclocalspy: +- localspy +- localchatspy +- lspy + +# The mod chat colour command has the following aliases (other than /mcmcc) +mcmcc: +- mcc + +# The mod chat command has the following aliases (other than /mcmc) +mcmc: +- mc + +# The private message command has the following aliases (other than /mcmsg) +mcmsg: +- msg +- m +- message +- t +- tell +- w +- whisper +- chat +- pm + +# The multichat bypass command has the following aliases (other than /mcbypass) +mcbypass: +- bypass +- mcb +- multichatbypass + +# The multichat command has the following aliases (other than /multichat) +multichat: +- mcinfo +- mcversion + +# The multichat execute command has the following aliases (other than /mcexecute) +mcexecute: +- execute +- mce +- multichatexecute +- gexe +- gexecute + +# The mute command has the following aliases (other than /mcmute) +mcmute: +- mute +- silence +- multichatmute + +# The reply command has the following aliases (other than /mcr) +mcr: +- r +- reply +- respond + +# The socialspy command has the following aliases (other than /mcsocialspy) +mcsocialspy: +- socialspy +- spy +- sspy + +# The staff list command has the following aliases (other than /mcstaff) +mcstaff: +- staff +- stafflist +- liststaff + +# The usecast command has the following aliases (other than /mcusecast) +mcusecast: +- usecast +- ccast diff --git a/multichat/src/main/resources/aliases_fr.yml b/multichat/src/main/resources/aliases_fr.yml new file mode 100644 index 00000000..932d76c5 --- /dev/null +++ b/multichat/src/main/resources/aliases_fr.yml @@ -0,0 +1,175 @@ +############################################################ +# +------------------------------------------------------+ # +# | MultiChat Aliases | # +# +------------------------------------------------------+ # +############################################################ + +# By Revilo410 + +# Pour utiliser ce fichier, renommer en 'aliases.yml' + +################## +# DON'T EDIT # +version: "1.10" # +################## + +# 1. Command Aliases + +############################################################ +# +------------------------------------------------------+ # +# | General | # +# +------------------------------------------------------+ # +############################################################ + +# La commande 'acc' possède les alias suivants (autres que /mcacc) +mcacc: +- acc + +# La commande 'ac' possède les alias suivants (autres que /mcac) +mcac: +- ac + +# La commande 'announcement' possède les alias suivants (autres que /mcannouncement) +mcannouncement: +- announcement +- announce +- announcements + +# La commande 'bulletin' possède les alias suivants (autres que /mcbulletin) +mcbulletin: +- bulletin +- bulletins + +# La commande 'cast' possède les alias suivants (autres que /mccast) +mccast: +- cast + +# La commande 'channel' possède les alias suivants (autres que /mcchannel) +mcchannel: +- channel +- ch + +# La commande 'clearchat' possède les alias suivants (autres que /mcclearchat) +mcclearchat: +- clearchat +- chatclear +- wipechat +- killchat + +# La commande 'display' possède les alias suivants (autres que /mcdisplay) +mcdisplay: +- display + +# La commande 'freezechat' possède les alias suivants (autres que /mcfreezechat) +mcfreezechat: +- freezechat +- pausechat +- lockchat +- chatlock + +# La commande 'gc' possède les alias suivants (autres que /mcgc) +mcgc: +- gc + +# La commande 'global' possède les alias suivants (autres que /mcglobal) +mcglobal: +- global +- g + +# La commande 'group' possède les alias suivants (autres que /mcgroup) +mcgroup: +- group + +# La commande 'groups' possède les alias suivants (autres que /mcgroups) +mcgroups: +- groups +- grouplist + +# La commande 'helpme' possède les alias suivants (autres que /mchelpme) +mchelpme: +- helpme +- helpop + +# La commande 'ignore' possède les alias suivants (autres que /mcignore) +mcignore: +- ignore +- blockplayer + +# La commande 'local' possède les alias suivants (autres que /mclocal) +mclocal: +- local +- l + +# La commande 'localspy' possède les alias suivants (autres que /mclocalspy) +mclocalspy: +- localspy +- localchatspy +- lspy + +# La commande 'mcc' possède les alias suivants (autres que /mcmcc) +mcmcc: +- mcc + +# La commande 'mc' possède les alias suivants (autres que /mcmc) +mcmc: +- mc + +# La commande 'msg' possède les alias suivants (autres que /mcmsg) +mcmsg: +- msg +- m +- message +- t +- tell +- w +- whisper +- chat +- pm + +# La commande 'bypass' possède les alias suivants (autres que /mcbypass) +mcbypass: +- bypass +- mcb +- multichatbypass + +# La commande 'multichat' possède les alias suivants (autres que /multichat) +multichat: +- mcinfo +- mcversion + +# La commande 'execute' possède les alias suivants (autres que /mcexecute) +mcexecute: +- execute +- mce +- multichatexecute +- gexe +- gexecute + +# La commande 'mute' possède les alias suivants (autres que /mcmute) +mcmute: +- mute +- silence +- multichatmute + +# La commande 'r' possède les alias suivants (autres que /mcr) +mcr: +- r +- reply +- respond + +# La commande 'socialspy' possède les alias suivants (autres que /mcsocialspy) +mcsocialspy: +- socialspy +- spy +- sspy + +# La commande 'staff' possède les alias suivants (autres que /mcstaff) +mcstaff: +- staff +- stafflist +- liststaff + +# La commande 'usecast' possède les alias suivants (autres que /mcusecast) +mcusecast: +- usecast +- ccast diff --git a/multichat/src/main/resources/bungee.yml b/multichat/src/main/resources/bungee.yml index 8d77e173..0b2e6560 100644 --- a/multichat/src/main/resources/bungee.yml +++ b/multichat/src/main/resources/bungee.yml @@ -1,6 +1,6 @@ name: MultiChat main: xyz.olivermartin.multichat.bungee.MultiChat -version: 1.9.5 +version: "1.10" author: Revilo410 api-version: 1.16 softdepends: [PremiumVanish] diff --git a/multichat/src/main/resources/chatcontrol.yml b/multichat/src/main/resources/chatcontrol.yml index 05d56095..7dbd9273 100644 --- a/multichat/src/main/resources/chatcontrol.yml +++ b/multichat/src/main/resources/chatcontrol.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.9.5" # +version: "1.10" # ################## # 1. Chat Control Rules @@ -151,12 +151,6 @@ apply_mute_to: group_chats: false helpme: false -# Mute command aliases (in addition to /multichatmute) - -mutecommand: -- mute -- mcmute - ################## # Ignore Command # ################## @@ -179,11 +173,6 @@ apply_ignore_to: private_messages: true group_chats: false -# Ignore command aliases (in addition to /ignore) - -ignorecommand: -- blockchat - ############################################################ # +------------------------------------------------------+ # # | Link / URL Controls | # diff --git a/multichat/src/main/resources/chatcontrol_fr.yml b/multichat/src/main/resources/chatcontrol_fr.yml index ea1d8e44..bbf4635e 100644 --- a/multichat/src/main/resources/chatcontrol_fr.yml +++ b/multichat/src/main/resources/chatcontrol_fr.yml @@ -8,7 +8,7 @@ ################## # NE PAS EDITER # -version: "1.9.5" # +version: "1.10" # ################## # French Translation by Nogapra - Thank you ! @@ -161,11 +161,6 @@ apply_mute_to: group_chats: false helpme: false -# Alias de commande MUTE (en plus de /multichatmute). -mutecommand: -- mute -- mcmute - ################### # Commande Ignore # ################### @@ -188,11 +183,6 @@ apply_ignore_to: private_messages: true group_chats: false -# Alias de commande ignore (en plus de la commande /ignore) - -ignorecommand: -- blockchat - ############################################################ # +------------------------------------------------------+ # # | Contrôle de Liens / URL | # diff --git a/multichat/src/main/resources/config.yml b/multichat/src/main/resources/config.yml index 65a6e95f..90b6f7b6 100644 --- a/multichat/src/main/resources/config.yml +++ b/multichat/src/main/resources/config.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.9.5" # +version: "1.10" # ################## # 1. General @@ -97,31 +97,6 @@ pmin: "&6[&c%DISPLAYNAME% &6-> &cMe&6] &f%MESSAGE%" pmspy: "&8&l<< &f%NAME% &7-> &f%NAMET%&8: &7%MESSAGE% &8&l>>" -############## -# PM ALIASES # -############## - -# The /msg command has the following aliases (other than /msg) -msgcommand: -- m -- message -- t -- tell -- w -- whisper -- chat -- pm - -# The /r command has the following aliases (other than /r) -rcommand: -- reply -- respond - -# The /socialspy command has the following aliases (other than /socialspy) -socialspycommand: -- spy -- sspy - ############################################################ # +------------------------------------------------------+ # # | Chat Channels | # @@ -135,18 +110,6 @@ default_channel: "global" # Force players into default channel when they join the server? force_channel_on_join: false -# The /channel command has the following aliases (other than /channel) -channelcommand: -- ch - -# The /global command has the following aliases (other than /global) -globalcommand: -- g - -# The /local command has the following aliases (other than /local) -localcommand: -- l - ############################################################ # +------------------------------------------------------+ # # | Global Chat | # @@ -187,6 +150,27 @@ no_global: [] globalformat: "&2[&aG&2] &f%DISPLAYNAME%&f: " +###################### +# Local Chat Formats # +###################### + +# This is the format used for LOCAL SPY +# %FORMAT% = The original format of the message, usually contains prefixes, displayname etc. + +# Additionally, you can use the following placeholders: +# %NAME% = The name of the sender +# %DISPLAYNAME% = The display name of the sender +# %PREFIX% = The prefix of the sender +# %SUFFIX% = The suffix of the sender +# %NICK% = The nickname of the sender +# %SERVER% = The server of the sender +# %WORLD% = The world of the sender + +# Global Chat Format +# Will display as [FORMAT] [MESSAGE] + +localspyformat: "&8[&7SPY&8] %FORMAT%" + ############################################################ # +------------------------------------------------------+ # # | Group Chats | # @@ -247,19 +231,6 @@ adminchat: # Set to false to disable the '/staff' staff list command staff_list: true -# MultiChat bypass command aliases (other than /multichatbypass) -multichatbypasscommand: -- mcb -- bypass - -# MultiChat execute command aliases (other than /multichatexecute) -multichatexecutecommand: -- mcexecute -- mce -- gexecute -- gexe -- gcommand - # Control what aspects of chat are logged by MultiChat (useful for GDPR etc.) privacy_settings: log_pms: true @@ -273,6 +244,9 @@ premium_vanish: silence_join: true # Prevent vanished players sending a join message # Legacy (PRE-1.16) Servers +# +# Please note: If you use any Sponge servers then they will need to be listed here! +# # Listing servers here will mark them as 'LEGACY' servers # RGB colour codes will be approximated to their nearest value (i.e. &a, &b and so on) # This prevents them displaying in chat as &x... diff --git a/multichat/src/main/resources/config_fr.yml b/multichat/src/main/resources/config_fr.yml index c8c67d91..95f185e2 100644 --- a/multichat/src/main/resources/config_fr.yml +++ b/multichat/src/main/resources/config_fr.yml @@ -8,7 +8,7 @@ ################## # NE PAS EDITER # -version: "1.9.5" # +version: "1.10" # ################## # French Translation by Nogapra - Thank you ! @@ -103,31 +103,6 @@ pmin: "&6[&c%DISPLAYNAME% &6-> &cMe&6] &f%MESSAGE%" # Formatage des message en socialspy. pmspy: "&8&l<< &f%NAME% &7-> &f%NAMET%&8: &7%MESSAGE% &8&l>>" -################################### -# Alias pour les messages privées # -################################### - -# La commande /msg possède les alias suivants (autres que /msg). -msgcommand: -- m -- message -- t -- tell -- w -- whisper -- chat -- pm - -# La commande /r possède les alias suivants (autres que /r). -rcommand: -- reply -- respond - -# La commande /socialspy a les alias suivants (autres que /socialspy). -socialspycommand: -- spy -- sspy - ############################################################ # +------------------------------------------------------+ # # | Cannaux de chat | # @@ -142,18 +117,6 @@ default_channel: "global" # Paramétrage disponible : true ou false force_channel_on_join: false -# La commande /Channel possède les alias suivants (autres que /Channel) -channelcommand: -- ch - -# La commande /Global possède les alias suivants (autres que /Global) -globalcommand: -- g - -# La commande /Local possède les alias suivants (autres que /Local) -localcommand: -- l - ############################################################ # +------------------------------------------------------+ # # | Chat global | # @@ -193,6 +156,27 @@ no_global: [] # Will display as [FORMAT] [MESSAGE] globalformat: "&2[&aG&2] &f%DISPLAYNAME%&f: " +###################### +# Local Chat Formats # +###################### + +# This is the format used for LOCAL SPY +# %FORMAT% = The original format of the message, usually contains prefixes, displayname etc. + +# Additionally, you can use the following placeholders: +# %NAME% = Le nom de l’expéditeur +# %DISPLAYNAME% = Le nom d'affichage de l’expéditeur +# %PREFIX% = Le préfixe de l’expéditeur +# %SUFFIX% = Le suffixe de l’expéditeur +# %NICK% = Le surnom de l’expéditeur +# %SERVER% = Le serveur de l’expéditeur +# %WORLD% = Le monde de l’expéditeur + +# Global Chat Format +# Will display as [FORMAT] [MESSAGE] + +localspyformat: "&8[&7SPY&8] %FORMAT%" + ############################################################ # +------------------------------------------------------+ # # | Chats de groupe | # @@ -252,19 +236,6 @@ adminchat: # Paramétrage disponible : true ou false staff_list: true -# Alias de commande de contournement MultiChat (autre que /multichatbypass). -multichatbypasscommand: -- mcb -- bypass - -# Alias de commande MultiChat Execute (autre que /multichatexecute). -multichatexecutecommand: -- mcexecute -- mce -- gexecute -- gexe -- gcommand - # Contrôlez quels aspects du chat sont enregistrés dans les logs MultiChat (utile pour la RGDP etc.) privacy_settings: log_pms: true diff --git a/multichat/src/main/resources/joinmessages.yml b/multichat/src/main/resources/joinmessages.yml index b3f5df17..875599df 100644 --- a/multichat/src/main/resources/joinmessages.yml +++ b/multichat/src/main/resources/joinmessages.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.9.5" # +version: "1.10" # ################## ############################################################ @@ -29,6 +29,7 @@ showquit: true # USES STANDARD MINECRAFT '&X' COLOUR/FORMAT CODES # %NAME% = The name of the sender +# %SERVER% = The server of the sender # NETWORK join message @@ -55,6 +56,7 @@ welcome: true # Define the welcome message here # USES STANDARD MINECRAFT '&X' COLOUR/FORMAT CODES # %NAME% = The name of the sender +# %SERVER% = The server of the sender welcome_message: "&dWelcome %NAME% to the network for the first time!" @@ -65,4 +67,6 @@ private_welcome: false # Define the private welcome message here # USES STANDARD MINECRAFT '&X' COLOUR/FORMAT CODES # %NAME% = The name of the sender +# %SERVER% = The server of the sender + private_welcome_message: "&5Hi there %NAME%, please make sure you read the /rules!" diff --git a/multichat/src/main/resources/joinmessages_fr.yml b/multichat/src/main/resources/joinmessages_fr.yml index c793379d..dd4604fd 100644 --- a/multichat/src/main/resources/joinmessages_fr.yml +++ b/multichat/src/main/resources/joinmessages_fr.yml @@ -8,7 +8,7 @@ ################## # Ne pas éditer # -version: "1.9.5" # +version: "1.10" # ################## # French Translation by Nogapra - Thank you! @@ -34,6 +34,7 @@ showquit: true # Utilisez les code couleur de minecraft Standard '&X' COLOUR/FORMAT CODES # %NAME% = le nom du joueur +# %SERVER% = le serveur du joueur # Message de connexion sur le réseaux de serveur @@ -61,6 +62,7 @@ welcome: true # Définissez le message de bienvenue ci-dessous # Utilisez les code couleur de minecraft Standard '&X' COLOUR/FORMAT CODES # %NAME% = Le nom du joueur +# %SERVER% = le serveur du joueur welcome_message: "&dBienvenue %NAME% pour votre première connexion sur nos serveurs!" @@ -71,5 +73,6 @@ private_welcome: false # Définissez le message de bienvenue ci-dessous # Utilisez les code couleur de minecraft Standard '&X' COLOUR/FORMAT CODES # %NAME% = Le nom du joueur +# %SERVER% = le serveur du joueurs private_welcome_message: "&dSalut %NAME%! S'il vous plaît lire les règles!" diff --git a/multichat/src/main/resources/localconfig.yml b/multichat/src/main/resources/localconfig.yml index 883bfb4f..c8d2e9bc 100644 --- a/multichat/src/main/resources/localconfig.yml +++ b/multichat/src/main/resources/localconfig.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.9.5" # +version: "1.10" # ################## # 1. Global Chat Settings diff --git a/multichat/src/main/resources/localconfig_fr.yml b/multichat/src/main/resources/localconfig_fr.yml index a11251ec..63944894 100644 --- a/multichat/src/main/resources/localconfig_fr.yml +++ b/multichat/src/main/resources/localconfig_fr.yml @@ -8,7 +8,7 @@ ################## # NE PAS EDITER # -version: "1.9.5" # +version: "1.10" # ################## # French Translation by Nogapra - Thank you ! diff --git a/multichat/src/main/resources/messages.yml b/multichat/src/main/resources/messages.yml index f85951a1..dcf0040e 100644 --- a/multichat/src/main/resources/messages.yml +++ b/multichat/src/main/resources/messages.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.9.5" # +version: "1.10" # ################## ############################################################ @@ -22,7 +22,7 @@ console_main_prefix: "&8[&2M&aC&8]&f " console_chat_prefix: "&fCHAT &f> " console_modchat_prefix: "&3STAFFCHAT &f> &3" console_adminchat_prefix: "&5STAFFCHAT &f> &5" -console_groupchat_prefix": "&2GROUPCHAT &f> &2" +console_groupchat_prefix: "&2GROUPCHAT &f> &2" console_display_prefix: "&fDISPLAY &f> " console_socialspy_prefix: "&cSOCIALSPY &f> &c" console_helpme_prefix: "&4HELPME &f> &4" @@ -165,6 +165,12 @@ command_local_enabled_1: "&3LOCAL CHAT ENABLED" command_local_enabled_2: "&bYour messages will only go to this server!" command_local_only_players: "&cOnly players can change their chat state" +command_localspy_disabled: "&cLocal Spy Disabled" +command_localspy_enabled: "&bLocal Spy Enabled" +command_localspy_usage: "&bUsage: /localspy" +command_localspy_desc: "&bToggles if the user has local spy enabled or disabled" +command_localspy_only_players: "&cOnly players can toggle localspy" + command_mcc_usage: "&aUsage: /mcc " command_mcc_only_players: "&cOnly players can change chat colours!" command_mcc_updated: "&aMod-Chat colours updated!" diff --git a/multichat/src/main/resources/messages_fr.yml b/multichat/src/main/resources/messages_fr.yml index 57a737b6..c0309dce 100644 --- a/multichat/src/main/resources/messages_fr.yml +++ b/multichat/src/main/resources/messages_fr.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.9.5" # +version: "1.10" # ################## # French Translation by Nogapra - Thank you! diff --git a/multichat/src/main/resources/plugin.yml b/multichat/src/main/resources/plugin.yml index 0dc727d8..ac80bd9f 100644 --- a/multichat/src/main/resources/plugin.yml +++ b/multichat/src/main/resources/plugin.yml @@ -1,6 +1,7 @@ name: MultiChat -version: 1.9.5 +version: "1.10" author: Revilo410 +api-version: 1.13 main: xyz.olivermartin.multichat.local.spigot.MultiChatLocalSpigotPlugin softdepend: [Vault,PlaceholderAPI] commands: diff --git a/multichat/src/test/java/xyz/olivermartin/multichat/junit/MultiChatUtilTest.java b/multichat/src/test/java/xyz/olivermartin/multichat/junit/MultiChatUtilTest.java new file mode 100644 index 00000000..28adeb76 --- /dev/null +++ b/multichat/src/test/java/xyz/olivermartin/multichat/junit/MultiChatUtilTest.java @@ -0,0 +1,273 @@ +package xyz.olivermartin.multichat.junit; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +import xyz.olivermartin.multichat.common.MultiChatUtil; +import xyz.olivermartin.multichat.common.TranslateMode; + +public class MultiChatUtilTest { + + public static void main(String[] args) { + Result result = JUnitCore.runClasses(MultiChatUtilTest.class); + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); + } + } + + @Test + public void shouldTranslateColorCodesCorrectly() { + + String rawMessage = "&r&aHello &kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!"; + + // ALL + assertEquals("All codes should be translated appropriately", + "§r§aHello §kthere! §6§lthis §ois §ma §nmessage! §r§x§a§b§c§d§e§fRGB §r§x§a§b§c§d§e§ftoo§r§x§a§b§c§d§e§f!", + MultiChatUtil.translateColorCodes(rawMessage)); + + // ALL #2 + assertEquals("All codes should be translated appropriately", + "§r§aHello §kthere! §6§lthis §ois §ma §nmessage! §r§x§a§b§c§d§e§fRGB §r§x§a§b§c§d§e§ftoo§r§x§a§b§c§d§e§f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.ALL)); + + // SIMPLE + assertEquals("Simple codes should be translated appropriately", + "§r§aHello §kthere! §6§lthis §ois §ma §nmessage! &#ABCDEFRGB &xAbCdEftoo&x§a§b§c§d§e§f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.SIMPLE)); + + // SIMPLE COLOR + assertEquals("Simple color codes should be translated appropriately", + "&r§aHello &kthere! §6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x§a§b§c§d§e§f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.COLOR_SIMPLE)); + + // ALL COLOR + assertEquals("All color codes should be translated appropriately", + "§r§aHello &kthere! §6<his &ois &ma &nmessage! §r§x§a§b§c§d§e§fRGB §r§x§a§b§c§d§e§ftoo§r§x§a§b§c§d§e§f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.COLOR_ALL)); + + // FORMAT UNDERLINE + assertEquals("Underline codes should be translated appropriately", + "&r&aHello &kthere! &6<his &ois &ma §nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.FORMAT_UNDERLINE)); + + // FORMAT ITALIC + assertEquals("Italic codes should be translated appropriately", + "&r&aHello &kthere! &6<his §ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.FORMAT_ITALIC)); + + // FORMAT BOLD + assertEquals("Bold codes should be translated appropriately", + "&r&aHello &kthere! &6§lthis &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.FORMAT_BOLD)); + + // FORMAT STRIKE + assertEquals("Strike codes should be translated appropriately", + "&r&aHello &kthere! &6<his &ois §ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.FORMAT_STRIKE)); + + // FORMAT OBFUSCATED + assertEquals("Obfuscation codes should be translated appropriately", + "&r&aHello §kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.FORMAT_OBFUSCATED)); + + // FORMAT RESET + assertEquals("Reset codes should be translated appropriately", + "§r&aHello &kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.FORMAT_RESET)); + + // FORMAT ALL + assertEquals("All format codes should be translated appropriately", + "§r&aHello §kthere! &6§lthis §ois §ma §nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.FORMAT_ALL)); + + // X + assertEquals("All X codes should be translated appropriately", + "&r&aHello &kthere! &6<his &ois &ma &nmessage! &r§x&a&b&c&d&e&fRGB &r§x&a&b&c&d&e&ftoo&r§x&a&b&c&d&e&f!", + MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.X)); + + } + + @Test + public void shouldNotChangeWithMultipleTranslations() { + + String rawMessage = "&r&aHello &kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!"; + + String translated1 = MultiChatUtil.translateColorCodes(rawMessage); + + String translated2 = MultiChatUtil.translateColorCodes(translated1); + + assertEquals("Resulting translations should be the same after multiple parses", + translated1, + translated2); + + } + + @Test + public void shouldApproximateRGBColorCodesCorrectly() { + + String rawMessage = "&r&aHello &kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!"; + + String translated = MultiChatUtil.translateColorCodes(rawMessage); + + String approximated = MultiChatUtil.approximateRGBColorCodes(translated); + + assertEquals("Translated RGB color codes should be approximated to nearest minecraft equivalent", + "§r§aHello §kthere! §6§lthis §ois §ma §nmessage! §7RGB §7too§7!", + approximated); + + String simpleTranslated = MultiChatUtil.translateColorCodes(rawMessage, TranslateMode.SIMPLE); + + String simpleApproximated = MultiChatUtil.approximateRGBColorCodes(simpleTranslated); + + assertEquals("Non translated RGB color codes should NOT be approximated to nearest minecraft equivalent", + "§r§aHello §kthere! §6§lthis §ois §ma §nmessage! &#ABCDEFRGB &xAbCdEftoo&x§a§b§c§d§e§f!", + simpleApproximated); + + String jsonMessage = "{\"text\":\"hello world\", \"color\":\"#ABCDEF\"}"; + + assertEquals("JSON RGB color codes should be approximated to nearest simple equivalent", + "{\"text\":\"hello world\", \"color\":\"gray\"}", + MultiChatUtil.approximateRGBColorCodes(jsonMessage)); + + String jsonMessage2 = "{\"text\":\"hello world\", \"color\":\"#aBcDeF\"}"; + + assertEquals("JSON RGB color codes should be approximated to nearest simple equivalent (test 2)", + "{\"text\":\"hello world\", \"color\":\"gray\"}", + MultiChatUtil.approximateRGBColorCodes(jsonMessage2)); + + String jsonMessage3 = "{\"text\":\"hello world\", \"color\":\"#abcdef\"}"; + + assertEquals("JSON RGB color codes should be approximated to nearest simple equivalent (test 3)", + "{\"text\":\"hello world\", \"color\":\"gray\"}", + MultiChatUtil.approximateRGBColorCodes(jsonMessage3)); + + String jsonMessage4 = "{\"text\":\"hello world\", \"color\":\"gray\"}"; + + assertEquals("Non RGB JSON messages should not be appoximated by the method", + jsonMessage4, + MultiChatUtil.approximateRGBColorCodes(jsonMessage4)); + + } + + @Test + public void shouldNotChangeWithMultipleRGBApproximations() { + + String rawMessage = "&r&aHello &kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!"; + + String translated = MultiChatUtil.translateColorCodes(rawMessage); + + String approximated = MultiChatUtil.approximateRGBColorCodes(translated); + + String approximated2 = MultiChatUtil.approximateRGBColorCodes(approximated); + + assertEquals("Approximated RGB codes should remain the same after multiple parses of the approximator", + approximated, + approximated2); + + } + + @Test + public void shouldGetMessageFromArgsCorrectly() { + + String[] args = new String[] {"this", "is", "a", "message!"}; + + assertEquals("Message should be returned exactly from args", + "this is a message!", + MultiChatUtil.getMessageFromArgs(args)); + + assertEquals("Message should be returned exactly from args (with offset start)", + "is a message!", + MultiChatUtil.getMessageFromArgs(args, 1)); + + assertEquals("Message should be returned exactly from args (with offset start and end)", + "is a", + MultiChatUtil.getMessageFromArgs(args, 1, 2)); + + Collection collection = Arrays.asList(args); + + assertEquals("Message should be returned exactly from args (collection version)", + "this is a message!", + MultiChatUtil.getStringFromCollection(collection)); + + } + + @Test + public void shouldStripColorCodesCorrectly() { + + String rawMessage = "&r&aHello &kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!"; + + // ALL + assertEquals("All codes should be stripped appropriately", + "Hello there! this is a message! RGB too!", + MultiChatUtil.stripColorCodes(rawMessage, false)); + + // ALL #2 + assertEquals("All codes should be stripped appropriately", + "Hello there! this is a message! RGB too!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.ALL)); + + // SIMPLE + assertEquals("Simple codes should be stripped appropriately", + "Hello there! this is a message! &#ABCDEFRGB &xAbCdEftoo&x!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.SIMPLE)); + + // SIMPLE COLOR + assertEquals("Simple color codes should be stripped appropriately", + "&rHello &kthere! <his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.COLOR_SIMPLE)); + + // ALL COLOR + assertEquals("All color codes should be stripped appropriately", + "Hello &kthere! <his &ois &ma &nmessage! RGB too!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.COLOR_ALL)); + + // FORMAT UNDERLINE + assertEquals("Underline codes should be stripped appropriately", + "&r&aHello &kthere! &6<his &ois &ma message! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.FORMAT_UNDERLINE)); + + // FORMAT ITALIC + assertEquals("Italic codes should be stripped appropriately", + "&r&aHello &kthere! &6<his is &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.FORMAT_ITALIC)); + + // FORMAT BOLD + assertEquals("Bold codes should be stripped appropriately", + "&r&aHello &kthere! &6this &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.FORMAT_BOLD)); + + // FORMAT STRIKE + assertEquals("Strike codes should be stripped appropriately", + "&r&aHello &kthere! &6<his &ois a &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.FORMAT_STRIKE)); + + // FORMAT OBFUSCATED + assertEquals("Obfuscation codes should be stripped appropriately", + "&r&aHello there! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.FORMAT_OBFUSCATED)); + + // FORMAT RESET + assertEquals("Reset codes should be stripped appropriately", + "&aHello &kthere! &6<his &ois &ma &nmessage! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.FORMAT_RESET)); + + // FORMAT ALL + assertEquals("All format codes should be stripped appropriately", + "&aHello there! &6this is a message! &#ABCDEFRGB &xAbCdEftoo&x&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.FORMAT_ALL)); + + // X + assertEquals("All X codes should be stripped appropriately", + "&r&aHello &kthere! &6<his &ois &ma &nmessage! &r&a&b&c&d&e&fRGB &r&a&b&c&d&e&ftoo&r&a&b&c&d&e&f!", + MultiChatUtil.stripColorCodes(rawMessage, false, TranslateMode.X)); + + } + +}